RSA encyrption - 在bytes数组和String之间进行转换

时间:2017-04-10 14:01:52

标签: java encryption cryptography encryption-asymmetric

我正在尝试实施RSA加密,它能够执行以下操作:

  • 接受字符串值作为使用公钥加密的输入
  • 将加密的密码作为字符串
  • 返回
  • 接受加密的密码作为使用私钥解密的输入
  • 返回原始值,解密

如果我直接解密加密返回的byte数组,我能够使加密/解密工作,但如果我将byte数组解析为{,那么似乎无法使其工作{1}}然后再次返回String

以下代码可以工作:

byte

以下代码有效:

cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherBytes = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherBytes));
returnValue += new String(cipherBytes);

cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plainText = cipher.doFinal(cipherBytes);
System.out.println("plain : " + new String(plainText));

有人可以建议我需要做些什么来让第二个版本成功运作吗?

1 个答案:

答案 0 :(得分:4)

我认为你的问题是因为在将字节数组转换为字符串时默认的java ecoding / deconding字符集,反之亦然。

我调试了你的代码并且reCipherBytes与cipherBytes的长度不同,这就是第二个代码块抛出异常的原因。

我建议您使用base64编码将cipherBytes转换为字符串。

    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] cipherBytes = cipher.doFinal(input);
    System.out.println("cipher: " + new String(cipherBytes));
    String returnValue = new String(cipherBytes);

    String cipherText = Base64.getEncoder().encodeToString(cipherBytes);
    byte[] reCipherBytes = Base64.getDecoder().decode(cipherText);

    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] plainText = cipher.doFinal(reCipherBytes);
    System.out.println("plain : " + new String(plainText));

此代码片段应该可以使用