RSA和AES简介
RSA
加密机制:属于非对称加密,公钥用于对数据进行加密,私钥对数据进行解密,两者不可逆。公钥和私钥是同时生成的,且一一对应。比如:A拥有公钥,B拥有公钥和私钥。A将数据通过公钥进行加密后,发送密文给B,B可以通过私钥进行解密。
AES
加密机制:属于对称加密,就是说,A用密钥对数据进行AES加密后,B用同样的密钥对密文进行AES解密。
加密思路:
- 调用方先将请求参数用AES加密,再利用RSA公钥对AES的密钥值加密;
- 调用方将加密后的数据发送给服务端;
- 服务端接收到头信息里的加密串,先用RSA私钥解密出AES密钥值,再用解密出的AES密钥值解密请求参数;
- 处理完毕后,服务端再用AES密钥对响应参数加密;
- 将加密后的结果返回给调用方。
混合加密原因
- 单纯的使用 RSA(非对称加密)方式,效率会很低,因为非对称加密解密方式虽然很保险,但是过程复杂,耗费时间长,性能不高;
- RSA优势在于数据传输安全,且对于几个字节的数据,加密和解密时间基本可以忽略,所以用它非常适合加密 AES 秘钥(一般16个字节);
- 单纯的使用AES(对称加密)方式的话,非常不安全。这种方式使用的密钥是一个固定的密钥,客户端和服务端是一样的,一旦密钥被人获取,那么,我们所发的每一条数据都会被都对方破解;
- AES有个很大的优点,那就是加密解密效率很高,而我们传输正文数据时,正好需要这种加解密效率高的,所以这种方式适合用于传输量大的数据内容。
AES加密工具:
public class AESUtil {
/**
* 密钥算法
*/
private static final String KEY_ALGORITHM = "AES";
private static String bit = "321";
/**
* 加密/解密算法 / 工作模式 / 填充方式
* Java 6支持PKCS5Padding填充方式
* Bouncy Castle支持PKCS7Padding填充方式
*/
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS7Padding";
static {
//如果是PKCS7Padding填充方式,则必须加上下面这行
Security.addProvider(new BouncyCastleProvider());
}
/**
* 生成密钥
* @return 密钥
* @throws Exception
*/
public static String generateKey() throws Exception {
//实例化密钥生成器
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
kg.init(128, new SecureRandom(bit.getBytes()));
//生成密钥
SecretKey secretKey = kg.generateKey();
//获得密钥的字符串形式
return Base64.encodeBase64String(secretKey.getEncoded());
}
public static Key getKey(String strKey) {
try {
if (strKey == null) {
strKey = "";
}
KeyGenerator _generator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(strKey.getBytes());
_generator.init(128, secureRandom);
return _generator.generateKey();
} catch (Exception e) {
throw new RuntimeException(" 初始化密钥出现异常 ");
}
}
public static String aesEncrypt(String sourceStr, String encryptKey) throws Exception {
return encrypt(sourceStr, Base64.encodeBase64String(encryptKey.getBytes()));
}
/**
* AES加密
* @param source 源字符串
* @param key 密钥
* @return 加密后的密文
* @throws Exception
*/
public static String encrypt(String source, String key) throws Exception {
byte[] sourceBytes = source.getBytes(StandardCharsets.UTF_8);
byte[] keyBytes = Base64.decodeBase64(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
System.out.println("secretKey length:" + secretKey.getEncoded().length);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] decrypted = cipher.doFinal(sourceBytes);
return Base64.encodeBase64String(decrypted);
}
public static String aesDecrypt(String encryptedStr, String decryptKey) throws Exception {
return decrypt(encryptedStr, Base64.encodeBase64String(decryptKey.getBytes()));
}
/**
* AES解密
* @param encryptStr 加密后的密文
* @param key 密钥
* @return 源字符串
* @throws Exception
*/
public static String decrypt(String encryptStr, String key) throws Exception {
byte[] sourceBytes = Base64.decodeBase64(encryptStr);
byte[] keyBytes = Base64.decodeBase64(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, KEY_ALGORITHM));
byte[] decoded = cipher.doFinal(sourceBytes);
return new String(decoded, StandardCharsets.UTF_8);
}
}
RSA加密工具:
public class RsaUtil {
/**
* 安全加固 PHP填充方式
*/
private static final String CIPHER_ALGORITHM = "RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";
/**
* 用于封装随机产生的公钥与私钥
*/
private static Map<Integer, String> keyMap = new HashMap<Integer, String>();
/**
* 0表示公钥
*/
private final static Integer publicKeyFlag = 0;
/**
* 1表示私钥
*/
private final static Integer privateKeyFlag = 1;
/**
* 算法
*/
private final static String algorithm = "RSA";
/**
* 密钥大小为96-1024位
*/
private final static Integer keySize = 1024;
/**
* 随机生成密钥对
* @throws NoSuchAlgorithmException
*/
public static Map<Integer, String> genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(algorithm);
// 初始化密钥对生成器
keyPairGen.initialize(keySize,new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// 得到私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 得到公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 得到私钥字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// 将公钥和私钥保存到Map
keyMap.put(publicKeyFlag,publicKeyString);
keyMap.put(privateKeyFlag,privateKeyString);
return keyMap;
}
/**
* RSA公钥加密
* @param str 加密字符串
* @param publicKey 公钥
* @param urlSafe url安全
* @return 密文
* @throws Exception 加密过程中的异常信息
*/
public static String encrypt( String str, String publicKey, boolean urlSafe ) throws Exception{
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] bdata=cipher.doFinal(str.getBytes("UTF-8"));
if(urlSafe) {
return Base64.encodeBase64URLSafeString(bdata);
}
return Base64.encodeBase64String(bdata);
}
/**
* RSA私钥解密
* @param str 加密字符串
* @param privateKey 私钥
* @return 铭文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(algorithm).generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, priKey);
return new String(cipher.doFinal(inputByte));
}
/**
* RSA公钥加密(RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING)
*
* @param str
* 加密字符串
* @param publicKey
* 公钥
* @return 密文
* @throws Exception
* 加密过程中的异常信息
*/
public static String encryptNew( String str, String publicKey) throws Exception{
//base64编码的公钥
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] byteData=cipher.doFinal(str.getBytes("UTF-8"));
return Base64.encodeBase64String(byteData);
}
/**
* RSA私钥解密(RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING)
*
* @param str
* 加密字符串
* @param privateKey
* 私钥
* @return 铭文
* @throws Exception
* 解密过程中的异常信息
*/
public static String decryptNew(String str, String privateKey) throws Exception{
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(algorithm).generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, priKey);
return new String(cipher.doFinal(inputByte));
}
}