生成密钥
// 创建一个RSA密钥对生成器
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
// 设置密钥长度,通常为2048位
keyPairGenerator.initialize(2048);
// 生成RSA密钥对
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
System.out.println("公钥: " + Base64.getEncoder().encodeToString(publicKey.getEncoded()));
System.out.println("私钥: " + Base64.getEncoder().encodeToString(privateKey.getEncoded()));
加密
String publicKeyBase64 = "test123";
PublicKey publicKey = KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyBase64)));
// 使用公钥加密数据
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = encryptCipher.doFinal(originalText.getBytes()
System.out.println("加密后的数据: " + Base64.getEncoder().encodeToString(encryptedBytes));
解密
// 使用私钥解密数据
String privateKeyBase64 = "test122";
PrivateKey privateKey = KeyFactory.getInstance("RSA")
.generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyBase64)));
// 使用公钥加密数据
Cipher decryptCipher = Cipher.getInstance("RSA");
decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = decryptCipher.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes);