我正在尝试实现 RSA 加密,它能够执行以下操作:
- 接受字符串值作为使用公钥加密的输入
- 以字符串形式返回加密的密码
- 接受加密密码作为使用私钥解密的输入
- 返回解密后的原始值
如果我直接解密,我就能使加密/解密工作byte
加密返回的数组,但如果我解析它似乎无法使其工作byte
数组到一个String
然后回到byte
s again.
下面的代码does work:
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));
下面的代码does NOT work:
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));
谁能建议我需要做什么才能使第二个版本成功运行?
我认为你的问题是因为将字节数组转换为字符串时默认的java编码/解码字符集,反之亦然。
我已经调试了您的代码,并且 reCipherBytes 的长度与 cipherBytes 不同,这就是第二个代码块引发异常的原因。
我建议您使用 base64 编码将密码字节转换为字符串。
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));
这段代码片段应该可以工作
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)