package org.shoper.rsa.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.Provider;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidParameterException;
import java.security.interfaces.RSAPublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
import javax.crypto.Cipher;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
/**
* RSA算法加密/解密工具类。
*
* @author fuchun
* @version 1.0.0, 2010-05-05
*/
public abstract class RSAUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtils.class);
/** 算法名称 */
private static final String ALGORITHOM = "RSA";
/**保存生成的密钥对的文件名称。 */
private static final String RSA_PAIR_FILENAME = "/__RSA_PAIR.txt";
/** 密钥大小 */
private static final int KEY_SIZE = 1024;
/** 默认的安全服务提供者 */
private static final Provider DEFAULT_PROVIDER = new BouncyCastleProvider();
private static KeyPairGenerator keyPairGen = null;
private static KeyFactory keyFactory = null;
/** 缓存的密钥对。 */
private static KeyPair oneKeyPair = null;
private static File rsaPairFile = null;
static {
try {
keyPairGen = KeyPairGenerator.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
keyFactory = KeyFactory.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
} catch (NoSuchAlgorithmException ex) {
LOGGER.error(ex.getMessage());
}
rsaPairFile = new File(getRSAPairFilePath());
}
private RSAUtils() {
}
/**
* 生成并返回RSA密钥对。
*/
private static synchronized KeyPair generateKeyPair() {
try {
keyPairGen.initialize(KEY_SIZE, new SecureRandom(DateFormatUtils.format(new Date(),"yyyyMMdd").getBytes()));
oneKeyPair = keyPairGen.generateKeyPair();
saveKeyPair(oneKeyPair);
return oneKeyPair;
} catch (InvalidParameterException ex) {
LOGGER.error("KeyPairGenerator does not support a key length of " + KEY_SIZE + ".", ex);
} catch (NullPointerException ex) {
LOGGER.error("RSAUtils#KEY_PAIR_GEN is null, can not generate KeyPairGenerator instance.",
ex);
}
return null;
}
/**
* 返回生成/读取的密钥对文件的路径。
*/
private static String getRSAPairFilePath() {
String urlPath = RSAUtils.class.getResource("/").getPath();
return (new File(urlPath).getParent() + RSA_PAIR_FILENAME);
}
/**
* 若需要创建新的密钥对文件,则返回 {@code true},否则 {@code false}。
*/
private static boolean isCreateKeyPairFile() {
// 是否创建新的密钥对文件
boolean createNewKeyPair = false;
if (!rsaPairFile.exists() || rsaPairFile.isDirectory()) {
createNewKeyPair = true;
}
return createNewKeyPair;
}
/**
* 将指定的RSA密钥对以文件形式保存。
*
* @param keyPair 要保存的密钥对。
*/
private static void saveKeyPair(KeyPair keyPair) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = FileUtils.openOutputStream(rsaPairFile);
oos = new ObjectOutputStream(fos);
oos.writeObject(keyPair);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
IOUtils.closeQuietly(oos);
IOUtils.closeQuietly(fos);
}
}
/**
* 返回RSA密钥对。
*/
public static KeyPair getKeyPair() {
// 首先判断是否需要重新生成新的密钥对文件
if (isCreateKeyPairFile()) {
// 直接强制生成密钥对文件,并存入缓存。
return generateKeyPair();
}
if (oneKeyPair != null) {
return oneKeyPair;
}
return readKeyPair();
}
// 同步读出保存的密钥对
private static KeyPair readKeyPair() {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = FileUtils.openInputStream(rsaPairFile);
ois = new ObjectInputStream(fis);
oneKeyPair = (KeyPair) ois.readObject();
return oneKeyPair;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
IOUtils.closeQuietly(ois);
IOUtils.closeQuietly(fis);
}
return null;
}
/**
* 根据给定的系数和专用指数构造一个RSA专用的公钥对象。
*
* @param modulus 系数。
* @param publicExponent 专用指数。
* @return RSA专用公钥对象。
*/
public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) {
RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(new BigInteger(modulus),
new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
} catch (InvalidKeySpecException ex) {
LOGGER.error("RSAPublicKeySpec is unavailable.", ex);
} catch (NullPointerException ex) {
LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
}
return null;
}
/**
* 根据给定的系数和专用指数构造一个RSA专用的私钥对象。
*
* @param modulus 系数。
* @param privateExponent 专用指数。
* @return RSA专用私钥对象。
*/
public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) {
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus),
new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFactory.generatePrivate(privateKeySpec);
} catch (InvalidKeySpecException ex) {
LOGGER.error("RSAPrivateKeySpec is unavailable.", ex);
} catch (NullPointerException ex) {
LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
}
return null;
}
/**
* 根据给定的16进制系数和专用指数字符串构造一个RSA专用的私钥对象。
*
* @param modulus 系数。
* @param privateExponent 专用指数。
* @return RSA专用私钥对象。
*/
public static RSAPrivateKey getRSAPrivateKey(String hexModulus, String hexPrivateExponent) {
if(StringUtils.isBlank(hexModulus) || StringUtils.isBlank(hexPrivateExponent)) {
if(LOGGER.isDebugEnabled()) {
LOGGER.debug("hexModulus and hexPrivateExponent cannot be empty. RSAPrivateKey value is null to return.");
}
return null;
}
byte[] modulus
表单RSA加密实例+Struts2
5星 · 超过95%的资源 需积分: 15 161 浏览量
2013-03-28
00:35:23
上传
评论
收藏 6.23MB 7Z 举报
Shoper
- 粉丝: 12
- 资源: 4
最新资源
- 全卷积网络基于voc2012数据集简单pytorch实现
- pycharm的一些介绍-用于更好的学习python
- 基于C++的程序设计大赛天梯赛L2答案(天梯赛)
- 基于python实现的三次样条插值和均值插值法实现
- Python语言教程2-python批量图片大小处理-多文件夹
- Python语言教程1-python批量图片重命名,将后缀某几个不想要的字去除
- Space Combat Kit 太空战斗套件Unity游戏开发插件资源unitypackage C#
- Universal Device Preview 通用设备预览Unity游戏开发插件资源unitypackage
- Paladin Anim Set 圣骑士动画集Unity游戏动作动画插件资源unitypackage
- 计算机财务管理期末考报表部分题目及答案.doc
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈