openssl生成RSA公钥私钥

  1. 生成私钥
 openssl genrsa -out private.pem 1024
  1. 生成公钥
openssl rsa -in private.pem -pubout -out public.pem
  1. 转换成 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字节时会自动填满,用到填充模式自然会占用一定的字节,而且这部分字节也是参与加密的

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值