废话不多说,直接上代码
public class RSAService {
private static final String RSA = "RSA";
private static final String PUBLIC_KEY = "xxx";
private static final String PRIVATE_KEY = "xxx";
public static void main(String[] args) throws Exception {
// 生成密钥对
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// 公钥和私钥的Base64编码表示
String publicKeyBase64 = Base64.getUrlEncoder().encodeToString(publicKey.getEncoded());
String privateKeyBase64 = Base64.getUrlEncoder().encodeToString(privateKey.getEncoded());
System.out.println("公钥: " + publicKeyBase64);
System.out.println("私钥: " + privateKeyBase64);
RSAService rsaService = new RSAService();
// 原文
HashMap<String, Object> map = new HashMap<>();
map.put("data", "Hello, RSA!");
// 公钥加密
String encryptedText = rsaService.encrypt(JSON.toJSONString(map));
System.out.println("加密后: " + encryptedText);
// 私钥解密
String decryptedText = rsaService.decrypt(encryptedText);
}
// 生成密钥对
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(RSA);
keyGen.initialize(2048);
return keyGen.generateKeyPair();
}
// 使用公钥加密
public String encrypt(String data) throws Exception {
byte[] keyBytes = Base64.getUrlDecoder().decode(PUBLIC_KEY);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey publicKey = keyFactory.generatePublic(spec);
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] bytes = cipher.doFinal(data.getBytes());
//二进制码转字符串
String base64Encoded = Base64.getUrlEncoder().encodeToString(bytes);
return base64Encoded;
}
// 使用私钥解密
public String decrypt(String data) throws Exception {
byte[] keyBytes = Base64.getUrlDecoder().decode(PRIVATE_KEY);
byte[] dataBytes = Base64.getUrlDecoder().decode(data);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey privateKey = keyFactory.generatePrivate(spec);
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bytes = cipher.doFinal(dataBytes);
return new String(bytes);
}
}