一、对称加密算法AES
/**
* AES加密算法
*
* @Author ykq
*/
public class Aes256 {
private static String src = "i am ykq";
public static void main(String[] args) {
try {
// AES生成Key
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
// 初始化长度
keyGenerator.init(256);
// 生成key
SecretKey secretKey = keyGenerator.generateKey();
// 获取key的byte数组
byte[] keyByte = secretKey.getEncoded();
// 对key进行转换
Key key = new SecretKeySpec(keyByte, "AES");
// 加密的方式,工作模式,填充方式
/**
* 模式说明:
* 算法/模式/填充 16字节加密后数据长度 不满16字节加密后长度
* AES/CBC/NoPadding 16 不支持
* AES/CBC/PKCS5Padding 32 16
* AES/CBC/ISO10126Padding 32 16
* AES/CFB/NoPadding 16 原始数据长度
* AES/CFB/PKCS5Padding 32 16
* AES/CFB/ISO10126Padding 32 16
* AES/ECB/NoPadding 16 不支持
* AES/ECB/PKCS5Padding 32 16
* AES/ECB/ISO10126Padding 32 16
* AES/OFB/NoPadding 16 原始数据长度
* AES/OFB/PKCS5Padding 32 16
* AES/OFB/ISO10126Padding 32 16
* AES/PCBC/NoPadding 16 不支持
* AES/PCBC/PKCS5Padding 32 16
* AES/PCBC/ISO10126Padding 32 16
*/
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// 加密方式,以key初始化
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptSrc = cipher.doFinal(src.getBytes());
String encryptStr = Base64.getEncoder().encodeToString(encryptSrc);
System.out.println("加密结果:" + encryptStr);
// 对加密的字符串进行解密
// 以解密方式,对key初始化
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptByte = cipher.doFinal(Base64.getDecoder().decode(encryptStr));
String decryptStr = new String(decryptByte);
System.out.println("解密结果:" + decryptStr);
} catch (Exception e) {
System.out.println("异常:" + e);
}
}
}
实现效果:
二、非对称加密算法RSA
public class RSA {
private static String src = "i am ykq";
public static void main(String[] args) {
try {
// 生产key
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 生成私钥
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
// 生成公钥
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
// 私钥加密
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] encryptByte = cipher.doFinal(src.getBytes());
String encryptStr = Base64.getEncoder().encodeToString(encryptByte);
System.out.println("加密后的字符串:" + encryptStr);
// 公钥解密
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] decryptByte = cipher.doFinal(Base64.getDecoder().decode(encryptStr));
System.out.println("解密后的字符串:" + new String(decryptByte));
} catch (Exception e) {
e.printStackTrace();
}
}
}
实现效果: