RSA 加密 - 在字节数组和字符串之间转换

Nia*_*all 2 java encryption cryptography encryption-asymmetric

我正在尝试实现能够执行以下操作的 RSA 加密:

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

如果我直接解密byte由加密返回的数组,我能够使加密/解密工作,但如果我将byte数组解析为 aString然后byte再次返回s ,似乎无法使其工作。

以下代码确实有效:

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));
Run Code Online (Sandbox Code Playgroud)

以下代码不起作用

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

String cipherText = new String(cipherBytes);
byte[] reCipherBytes = cipherText.getBytes();

cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plainText = cipher.doFinal(reCipherBytes);
System.out.println("plain : " + new String(plainText));
Run Code Online (Sandbox Code Playgroud)

谁能建议我需要做什么才能使第二个版本成功运行?

小智 5

我认为您的问题是因为在将字节数组转换为字符串时使用默认的 java 编码/解码字符集,反之亦然。

我已经调试了您的代码,并且 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));
Run Code Online (Sandbox Code Playgroud)

此代码片段应该可以工作