java encrypt加密_RSA使用JSEncrypt加密并使用BouncyCastle(Java)解密

这可能是 this answered question的重复,但我似乎无法得到相同的结果.希望在这里有一些指导.

JSEncrypt(客户端)

let encrypt = new Encrypt.JSEncrypt();

encrypt.setPublicKey(this.publicKey); // retrieved from server

encrypt.encrypt(password);

BouncyCastle(服务器) – RSA密钥生成

KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

generator.initialize(1024);

KeyPair pair = generator.generateKeyPair();

PublicKey pubKey = pair.getPublic();

PrivateKey privKey = pair.getPrivate();

// returned to client

String publicKeyStr = new String(Base64.encodeBase64(pubKey.getEncoded()));

String privateKeyStr = new String(Base64.encodeBase64(privKey.getEncoded()));

BouncyCastle(服务器) – 解密

Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding");

cipher.init(Cipher.DECRYPT_MODE, privateKey);

// org.apache.commons.codec.binary.Hex

byte[] cipherText = cipher.doFinal(Hex.decodeHex(encrypted.toCharArray()));

decrypted = new String(cipherText, BaseConstant.ENC_UTF8);

错误

org.apache.commons.codec.DecoderException: Illegal hexadecimal character I at index 0

at org.apache.commons.codec.binary.Hex.toDigit(Hex.java:178)

at org.apache.commons.codec.binary.Hex.decodeHex(Hex.java:89)

我注意到的一件事是JSEncrypt的加密文本长度为172,而服务器端的加密产生256.

回答的问题提到使用RSA / None / PKCS1Padding,我已经设置了.我还能错过什么?

最佳答案 Hex.decodeHex()方法中发生错误,这意味着您的数据不是十六进制编码的字符串.

JSEncrypt.encrypt()方法返回Base64中的加密数据(而不是Hex字符串).要解密它,您必须从base64格式解码它.

所以代替:

byte[] cipherText = cipher.doFinal(Hex.decodeHex(encrypted.toCharArray()));

做这个:

byte[] cipherText = cipher.doFinal(Base64.decodeBase64(encrypted.toCharArray()));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值