1、首先上公钥加密代码
public String encryptByPublicKey(String publicKeyString, String text) throws Exception
{
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes());
return Base64.encodeBase64String(result);
}
2、运行过程中可能会出现错误,错误如下
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException :
3、原因
因为公钥给的上PKCS1格式(适用于非java),转换为PKCS8格式(适用于java)后,就没问题了
4、PKCS1格式转换为PKCS8格式在线工具
SSL在线工具-在线RSA公私钥格式转换|公钥PKCS1与PKCS8转换|私钥PKCS1与PKCS8转换-SSLeye官网