RSA优缺点: RSA的安全性依赖于大数分解,小于1024位的N已经被证明是不安全的,而且由于RSA算法进行的都是大数计算,使得RSA最快的情况也比DES慢上倍,这是RSA最大的缺陷,因此通常只能用于加密少量数据或者加密密钥,但RSA仍然不失为一种高强度的算法。
加密方法:
/**
* @description:RSA公钥/私钥/签名工具包
*/
public class RSAUtils {
/**
* 加密算法RSA
* /RSA/ECB/PKCS1Padding RSA
*/
public static final String KEY_ALGORITHM = "RSA/ECB/PKCS1Padding";
/**
* 签名算法
*/
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
* 获取公钥的key
*/
// public static final String PUBLIC_KEY ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClOB/q2myynP4c6cJq8tmWOcOw7N4fDhL9QeqWWYOERlnyl4ZAeuUIJpuP0FUHNESvlFIrxiYaYjVVKjMEcwbRUJP8EMWtO4dNRrbxJFKPXpCk2fF82WBxt81dLhgvYPX77EEcqzGNMrTRX6/EuOEVawKgBOUywtCNe2ZijSGccwIDAQAB";
// public static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7VEIlt7cbOC61b0tLHS1OTx5RixSNewAhUFH10h63H2Xp27SKy039YeTb337TxPuErP0+DBGmXRLyyp64AqUH5aaVHn8geOsoUEjKBv78ics1IU1c5mZxzsgpnCVmkq7uEFauDsjKs5Bbf+RviX4te4WPRoGHX4txdEK+7QMeUQIDAQAB";
public static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7VEIlt7cbOC61b0tLHS1OTx5RixSNewAhUFH10h63H2Xp27SKy039YeTb337TxPuErP0+DBGmXRLyyp64AqUH5aaVHn8geOsoUEjKBv78ics1IU1c5mZxzsgpnCVmkq7uEFauDsjKs5Bbf+RviX4te4WPRoGHX4txdEK+7QMeUQIDAQAB";
/**
* 获取私钥的key
*/
// public static final String PRIVATE_KEY = "MIICdQIBADANBgkqhkiG9w0BAQ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2JGCIf9t7BitQQJAPk0/lP8cNksQdTja6jIFreq11b/1k2YwbwkhZ+fdNyEndFZyjLcD57K/nHtLIOFgVV9kkaF2HBvs7xb3xL8/KQJBALNCcIwLEWdYdMu+HaGDWZ4W5Yz9lZI5NHVFA8WD2UNfmmZasNzsl1FuBrjq7ohoZqlOtGdOARdBIakmL/ZY//w=";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* 私钥
*/
public static RSAPrivateKey PRIVATE_KEY_RSA;
/**
* 公钥
*/
public static RSAPublicKey PUBLIC_KEY_RSA;
/**
* 生成密钥对(公钥和私钥)
*/
public static Map<String, Object> genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
* 用私钥对信息生成数字签名
*/
public static String sign(String dataStr) throws Exception {
byte[] data = new BASE64Decoder().decodeBuffer(dataStr);
RSAUtils.loadPrivateKey(PRIVATE_KEY);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(PRIVATE_KEY_RSA);
signature.update(data);
return new BASE64Encoder().encodeBuffer(signature.sign());
}
/**
* 校验数字签名
*
* @param sign 数字签名
*/
public static boolean verify(String dataStr, String sign) throws Exception {
byte[] data = new BASE64Decoder().decodeBuffer(dataStr);
RSAUtils.loadPublicKey(PUBLIC_KEY);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(PUBLIC_KEY_RSA);
signature.update(data);
return signature.verify(new BASE64Decoder().decodeBuffer(sign));
}
/**
* 私钥解密
*
* @param encryptedData 已加密数据
*/
public static byte[] decryptByPrivateKey(byte[] encryptedData) throws Exception {
if (PRIVATE_KEY_RSA == null) {
throw new Exception("解密私钥为空,请设置");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, PRIVATE_KEY_RSA);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此解密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("解密私钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("密文长度非法");
} catch (BadPaddingException e) {
throw new Exception("密文数据已损坏==");
}
}
/**
* 公钥解密
*/
public static byte[] decryptByPublicKey(byte[] encryptedData) throws Exception {
if (PUBLIC_KEY_RSA == null) {
throw new Exception("解密公钥为空,请设置");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, PUBLIC_KEY_RSA);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此解密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("解密公钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("密文长度非法");
} catch (BadPaddingException e) {
throw new Exception("密文数据已损坏");
}
}
/**
* 公钥加密
*
* @param data 源数据
*/
public static byte[] encryptByPublicKey(byte[] data) throws Exception {
if (PUBLIC_KEY_RSA == null) {
throw new Exception("加密公钥为空,请设置");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, PUBLIC_KEY_RSA);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此加密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("加密公钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文长度非法");
} catch (BadPaddingException e) {
throw new Exception("明文数据已损坏");
}
}
/**
* 私钥加密
*
* @param data 源数据
*/
public static byte[] encryptByPrivateKey(byte[] data) throws Exception {
if (PRIVATE_KEY_RSA == null) {
throw new Exception("加密私钥为空,请设置");
}
Cipher cipher = null;
try {
cipher = Cipher.getInstance(KEY_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, PRIVATE_KEY_RSA);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此加密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (InvalidKeyException e) {
throw new Exception("加密私钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文长度非法");
} catch (BadPaddingException e) {
throw new Exception("明文数据已损坏");
}
}
/**
* 获取私钥
*
* @param keyMap 密钥对
*/
public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return new BASE64Encoder().encodeBuffer(key.getEncoded());
}
/**
* 获取公钥
*
* @param keyMap 密钥对
*/
public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return new BASE64Encoder().encodeBuffer(key.getEncoded());
}
/**
* 从字符串中加载公钥
*
* @param publicKeyStr 公钥数据字符串
* @throws Exception 加载公钥时产生的异常
*/
public static void loadPublicKey(String publicKeyStr) throws Exception {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
RSAUtils.PUBLIC_KEY_RSA = (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
} catch (Exception e) {
throw new Exception("所有---" + e.getLocalizedMessage());
}
}
/**
* 从字符串中加载私钥
*
* @throws Exception 加载私钥时产生的异常
*/
public static void loadPrivateKey(String privateKeyStr) throws Exception {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAUtils.PRIVATE_KEY_RSA = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
} catch (InvalidKeySpecException e) {
e.printStackTrace();
throw new Exception("私钥非法");
} catch (NullPointerException e) {
throw new Exception("私钥数据为空");
} catch (Exception e) {
throw new Exception("所有-----" + e.getLocalizedMessage());
}
}
/**
* 私钥解密后的字符串
*/
public static String decryptPrivateWithBase64(String base64String) throws Exception {
RSAUtils.loadPrivateKey(PRIVATE_KEY);
byte[] binaryData = decryptByPrivateKey(new BASE64Decoder().decodeBuffer(base64String));
String string = new String(binaryData);
return string;
}
/**
* 公钥加密后的字符串
*/
public static String encryptPublicWithBase64(String string) throws Exception {
//获取公钥
RSAUtils.loadPublicKey(PUBLIC_KEY);
//字符串进行加密
byte[] binaryData = encryptByPublicKey(string.getBytes());
// LogUtil.e("RSA:" + new String(binaryData));
//结果进行base64转换
String base64String = new BASE64Encoder().encodeBuffer(binaryData);
return base64String;
}
/**
* 公钥解密后的字符串
*/
public static String decryptPublicWithBase64(String base64String) throws Exception {
RSAUtils.loadPublicKey(PUBLIC_KEY);
byte[] binaryData = decryptByPublicKey(new BASE64Decoder().decodeBuffer(base64String));
String string = new String(binaryData);
return string;
}
/**
* 私钥加密后的字符串
*/
public static String encryptPrivateWithBase64(String string) throws Exception {
RSAUtils.loadPrivateKey(PRIVATE_KEY);
byte[] binaryData = encryptByPrivateKey(string.getBytes());
String base64String = new BASE64Encoder().encodeBuffer(binaryData);
return base64String;
}
public static void main(String args[]) throws Exception {
String v = "{\"id\":\"0dd2242adf9d47eeb8194a887812c48e\"}";
// mbBlfQRjg03Hv0OW5RmD4kyLjHfzNjbuxW1NYlwSR/vA8d7tYl6cLP88Jfaj595OXJuToqBNrJ9uO8Ey54kfZEDPMcjt++3NVHGSix8aJoPGqDgKwuGqmhmnYUx5o0RTRUq6nGQT2QlxMN/BSgm86yDMZ5C2aqMAETox/lJqe1E=
String str1 = RSAUtils.encryptPublicWithBase64(v);
// String str1 = "oaI7FMlh1ExJSC0WQmOTcArbA2Vk4sRxH7TmXWY/lbI9LCAXdFWY91f9tuJq0BwDlGm1dZZDrZOacZVfhqPGwnRumlzrW8H8i2EGXPiyyn8lpWhdZzmDMrWcCkqEdoyvRCHz8jk2wWTV58SvoQjFIvH2XpdvCmCcT8ZcwBiEGfY=";
String str2 = RSAUtils.decryptPrivateWithBase64(str1);
}
}