- 生成私钥
openssl genrsa -out private.pem 1024
- 生成公钥
openssl rsa -in private.pem -pubout -out public.pem
- 转换成 pkcs8 格式
openssl pkcs8 -topk8 -inform PEM -in private.pem -outform PEM -nocrypt > private_pkcs8.pem
RSA 加密解密
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException, IOException, BadPaddingException, IllegalBlockSizeException {
String msg = "msg";
byte[] publicKey = Base64Utils.decode(getPublicKey().getBytes(StandardCharsets.UTF_8));
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKey));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] bytes = cipher.doFinal(msg.getBytes(StandardCharsets.UTF_8));
System.out.println("加密:" + Base64Utils.encodeToString(bytes));
byte[] privateKey = Base64Utils.decode( getPrivateKey().getBytes(StandardCharsets.UTF_8));
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKey));
//RSA解密
Cipher dcipher = Cipher.getInstance("RSA");
dcipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(dcipher.doFinal(bytes));
System.out.println("解密:" + outStr);
}
异常
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Data must not be longer than 117 bytes
PS:RSA加密对明文的长度有所限制,规定需加密的明文最大长度=密钥长度-11(单位是字节,即byte),所以在加密和解密的过程中需要分块进行。而密钥默认是1024位,即1024位/8位-11=128-11=117字节。所以默认加密前的明文最大长度117字节,解密密文最大长度为128字。那么为啥两者相差11字节呢?是因为RSA加密使用到了填充模式(padding),即内容不足117字节时会自动填满,用到填充模式自然会占用一定的字节,而且这部分字节也是参与加密的