由于RSA加密得字符串长度和密钥长度有关,所以一般结合aes加密使用
加密方式如图
解密方式如图
?具体java实现如下
RSAUtils.java
package com.utils.sign;
import com.constant.Constants;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;
import javax.crypto.Cipher;
/**
* RSA加密类
* 不同长度的密钥对应可以加密不同最大长度的原文,2048就对应245
*/
public class RSAUtils {
/**
* 密钥长度 于原文长度对应 长度越长速度越慢
*/
private final static int KEY_SIZE = 2048;
/**
* 随机生成密钥对
*/
public static List<String> genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器
keyPairGen.initialize(KEY_SIZE, 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());
// 将公钥和私钥保存到
List<String> keyList = new ArrayList<>(2);
//0表示公钥
keyList.add(publicKeyString);
//1表示私钥
keyList.add(privateKeyString);
return keyList;
}
/**
* RSA公钥加密
*
* @param str 加密字符串
* @param publicKey 公钥
* @return 密文
* @throws Exception 加密过程中的异常信息
*/
public static String encrypt(String str, String publicKey) throws Exception {
//base64编码的公钥
byte[] decoded = Base64.decode(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return Base64.encode(cipher.doFinal(str.getBytes("UTF-8")));
}
/**
* RSA私钥解密
*
* @param str 加密字符串
* @param privateKey 私钥
* @return 明文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception {
//64位解码加密后的字符串
byte[] inputByte = Base64.decode(str);
//base64编码的私钥
byte[] decoded = Base64.decode(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
return new String(cipher.doFinal(inputByte));
}
public static void main(String[] args) throws Exception {
long temp;
//生成公钥和私钥
// List<String> keys = genKeyPair();
// //加密字符串
// System.out.println("公钥:" + keys.get(0));
// System.out.println("私钥:" + keys.get(1));
//System.out.println("生成密钥消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
//客户id + 授权时间 + 所用模块
String message = "admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123admin123";
System.out.println("原文:" + message);
temp = System.currentTimeMillis();
//通过原文,和公钥加密。
String messageEn = encrypt(message, Constants.PUBLIC_KEY);
System.out.println("密文:" + messageEn);
System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
temp = System.currentTimeMillis();
//通过密文,和私钥解密。
String messageDe = decrypt(messageEn, Constants.PRIVATE_KEY);
System.out.println("解密:" + messageDe);
System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
}
}
AesUtils.java
package com.utils.sign;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
/**
* AES工具类
*/
public class AesUtils {
private static final String CHARSET = "utf-8";
/**
* 生成随机密钥
* @param keySize 密钥大小推荐128 256
* @return
* @throws NoSuchAlgorithmException
*/
public static String generateSecret(int keySize) throws NoSuchAlgorithmException {
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(keySize, new SecureRandom());
SecretKey key = generator.generateKey();
return byteToHexString(key.getEncoded());
}
public static String encrypt(String strToEncrypt, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
SecretKeySpec secretKey = getKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
}
public static String decrypt(String strToDecrypt, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
SecretKeySpec secretKey = getKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
private static SecretKeySpec getKey(String myKey) throws UnsupportedEncodingException, NoSuchAlgorithmException {
byte[] key = myKey.getBytes(CHARSET);
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
return new SecretKeySpec(key, "AES");
}
/**
* byte数组转化为16进制字符串
* @param bytes
* @return
*/
private static String byteToHexString(byte[] bytes){
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String strHex=Integer.toHexString(bytes[i]);
if(strHex.length() > 3){
sb.append(strHex.substring(6));
} else {
if(strHex.length() < 2){
sb.append("0" + strHex);
} else {
sb.append(strHex);
}
}
}
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, UnsupportedEncodingException {
String key = generateSecret(256);
String enData = encrypt("你好测试hello", key);
System.out.println(enData);
String deData = decrypt(enData, key);
System.out.println(deData);
enData = encrypt("你好测试", key);
System.out.println(enData);
deData = decrypt(enData, key);
System.out.println(deData);
}
}
CryptUtil.java
package com.utils.sign;
import com.constant.Constants;
/**
* 使用rsa和aes加密算法对数据进行加解密
* 加密得数据逗号分割,
* 前部分为用rsa加密得aes密钥,后部分为aes用前面密钥加密得字符串
*/
public class CryptUtil {
private static String split = ",";
private static Integer aesKeySize = 128;
public static String encryptData(String data) throws Exception{
return encryptData(data,Constants.PUBLIC_KEY);
}
public static String decryptData(String data) throws Exception{
return decryptData(data,Constants.PRIVATE_KEY);
}
/**
* 公钥加密
* @param data
* @param publicInfoStr
* @return 使用RSA加密AES的key,使用AES加密数据
*/
private static String encryptData(String data, String publicInfoStr) throws Exception{
// 随机生成AES key
String aesKey = AesUtils.generateSecret(aesKeySize);
// 使用AES加密数据
String enData = AesUtils.encrypt(data, aesKey);
// 使用RSA加密AES key
String enAesKey = RSAUtils.encrypt(aesKey, publicInfoStr);
return enAesKey + split + enData;
}
/**
* 私钥解密
* @param data 逗号分割:'使用RSA加密AES的key,使用AES加密数据'
* @param privateInfoStr
* @return 解密后的数据
*/
private static String decryptData(String data, String privateInfoStr) throws Exception{
// 拆解数据
String[] dataArr = data.split(split);
if(dataArr.length != 2){
throw new IllegalArgumentException("data必须逗号分割:'使用RSA加密AES的key,使用AES加密数据'");
}
// 使用RSA解密AES key
String aesKey = RSAUtils.decrypt(dataArr[0], privateInfoStr);
// 使用AES解密数据
return AesUtils.decrypt(dataArr[1], aesKey);
}
public static void main(String[] args) throws Exception{
// 生成公钥和私钥
// List<String> keys = RSAUtils.genKeyPair();
// //加密字符串
// System.out.println("公钥:" + keys.get(0));
// System.out.println("私钥:" + keys.get(1));
long temp;
temp = System.currentTimeMillis();
String enStr = encryptData("你好测试测试测试测试你好测试你好测试测试");
System.out.println(enStr);
System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
temp = System.currentTimeMillis();
String deStr = decryptData(enStr);
System.out.println(deStr);
System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
}
}
最终调用CryptUtil.encryptData(str)加密字符串,CryptUtil.decryptData(str)解密字符串
rsa得公钥私钥需要使用RSAUtils.genKeyPair()生成,并保存在代码中
|