AES和RSA都是公认为安全的加密算法,在秘钥没有泄露的情况下,几乎不可能被破译(密钥的管理至关重要)。
/**
* 对称加密
*
* @throws Exception
*/
public static void AES() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
// 可选128位、192位和256位,128位的密钥长度已经足够用于许多应用场景
keyGen.init(128);
SecretKey secretKey = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal("123456789".getBytes());
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedData = cipher.doFinal(encryptedData);
// Base64不会遗漏二进制数据,可以转为可视数据
System.out.println("加密:" + Base64.getEncoder().encodeToString(encryptedData));
System.out.println("解密: " + new String(decryptedData));
}
/**
* 非对称加密
*
* @throws Exception
*/
public static void RSA() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
// 最小512(不安全),推荐2048位及以上
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] data = "123456789".getBytes();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal(data);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedData = cipher.doFinal(encryptedData);
System.out.println("加密:" + Base64.getEncoder().encodeToString(encryptedData));
System.out.println("解密: " + new String(decryptedData));
}
标签:记录,秘钥,init,Cipher,encryptedData,byte,keyGen,cipher,加密算法
From: https://www.cnblogs.com/lemonpuer/p/17926546.html