//1初始化秘钥
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
System.out.println("PublicKey:"+Base64.encodeBase64(rsaPublicKey.getEncoded()));
System.out.println("PrivateKey:"+Base64.encodeBase64(rsaPrivateKey.getEncoded()));
//2私钥加密,公钥解密——加密
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[] result = cipher.doFinal(s.getBytes());//待加密的字符串
System.out.println("加密密文:"+Base64.encodeBase64(result));
//2私钥加密,公钥解密——解密
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded());
KeyFactory keyFactory1 = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory1.generatePublic(x509EncodedKeySpec);
Cipher cipher1 = Cipher.getInstance("RSA");
cipher1.init(Cipher.DECRYPT_MODE, publicKey);
result = cipher.doFinal(result);
System.out.println("解密密文:"+new String(result));