RSA 加密工具类,生成密钥对,加解密功能。喜欢的拿去使用。
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.concurrent.ConcurrentMap;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import com.google.common.collect.Maps;
import com.opentrans.otms.api.web.enums.ResponseEnum;
import com.opentrans.otms.exception.RFIException;
import com.opentrans.otms.logger.Logger;
import com.opentrans.otms.logger.LoggerFactory;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
public class RSAEncryptUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(RSAEncryptUtil.class);
private static final ConcurrentMap KEY_CACHE_MAP = Maps.newConcurrentMap();
public static final String PRIVATE_KEY = "RSAPrivateKey";
public static final String INVITATION_PUBLIC_KEY = "InvitationRSAPublicKey";
public static final String INVITATION_PRIVATE_KEY = "InvitaionRSAPrivateKey";
private RSAEncryptUtil() {
}
public static void main(String[] args) {
genKeyPair(512);
}
public static void genKeyPair(int keysize) {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为96-1024位
keyPairGen.initialize(keysize, new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// 得到私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 得到公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 得到公钥字符串
String publicKeyString = Base64.encode(publicKey.getEncoded());
// 得到私钥字符串
String privateKeyString = Base64.encode(privateKey.getEncoded());
LOGGER.info("public key is :" + publicKeyString);
LOGGER.info("private key is :" + privateKeyString);
} catch (Exception e) {
LOGGER.info("get key pair error :{}", e);
}
}
public static RSAPrivateKey getPrivateKeyByStr(String privateKeyStr, String key) {
try {
RSAPrivateKey privateKey = (RSAPrivateKey) KEY_CACHE_MAP.get(key);
if (privateKey == null) {
byte[] buffer = Base64.decode(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
KEY_CACHE_MAP.put(key, privateKey);
}
return privateKey;
} catch (NoSuchAlgorithmException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "私钥非法");
} catch (NullPointerException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "私钥数据为空");
}
}
public static RSAPublicKey getPublicKeyByStr(String publicKeyStr) {
try {
byte[] buffer = Base64.decode(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "公钥非法");
} catch (NullPointerException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "公钥数据为空");
}
}
/**
* 公钥加密过程
*
* @param publicKey
* 公钥
* @param plainTextData
* 明文数据
* @return
* @throws Exception
* 加密过程中的异常信息
*/
public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) {
if (publicKey == null) {
throw new Exception(ResponseEnum.ERROR.getCode(), "加密公钥为空, 请设置");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plainTextData);
} catch (NoSuchAlgorithmException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "无此加密算法");
} catch (NoSuchPaddingException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "");
} catch (InvalidKeyException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "加密公钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "明文长度非法");
} catch (BadPaddingException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "明文数据已损坏");
}
}
/**
* 私钥加密过程
*
* @param privateKey
* 私钥
* @param plainTextData
* 明文数据
* @return
* @throws Exception
* 加密过程中的异常信息
*/
public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) {
if (privateKey == null) {
throw new RFIException(ResponseEnum.ERROR.getCode(), "加密私钥为空, 请设置");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(plainTextData);
} catch (NoSuchAlgorithmException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "无此加密算法");
} catch (NoSuchPaddingException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "");
} catch (InvalidKeyException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "加密私钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "明文长度非法");
} catch (BadPaddingException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "明文数据已损坏");
}
}
/**
* 私钥解密过程
*
* @param privateKey
* 私钥
* @param cipherData
* 密文数据
* @return 明文
* @throws Exception
* 解密过程中的异常信息
*/
public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) {
if (privateKey == null) {
throw new RFIException(ResponseEnum.ERROR.getCode(), "解密私钥为空, 请设置");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(cipherData);
} catch (NoSuchAlgorithmException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "无此解密算法");
} catch (NoSuchPaddingException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "解密私钥为空, 请设置");
} catch (InvalidKeyException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "解密私钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "密文长度非法");
} catch (BadPaddingException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "密文数据已损坏");
}
}
/**
* 公钥解密过程
*
* @param publicKey
* 公钥
* @param cipherData
* 密文数据
* @return 明文
* @throws Exception
* 解密过程中的异常信息
*/
public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) {
if (publicKey == null) {
throw new Exception(ResponseEnum.ERROR.getCode(), "无此解密算法");
}
Cipher cipher = null;
try {
// 使用默认RSA
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(cipherData);
} catch (NoSuchAlgorithmException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "无此解密算法");
} catch (NoSuchPaddingException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "");
} catch (InvalidKeyException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "解密公钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "密文长度非法");
} catch (BadPaddingException e) {
throw new Exception(ResponseEnum.ERROR.getCode(), "密文数据已损坏");
}
}
}