This question already has answers here: IllegalBlockSizeException when trying to encrypt and decrypt a string with AES                                                                    (4个答案)                                                                                        2年前关闭。                                我正在尝试实现能够执行以下操作的RSA加密:接受字符串值作为输入以使用公钥进行加密以字符串形式返回加密的密码接受加密密码作为输入以使用私钥解密返回原始值,解密如果我直接解密由加密返回的byte数组,则能够使加密/解密工作,但是如果我将byte数组解析为String然后又返回到 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));以下代码不起作用: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));谁能建议我需要做些什么才能使第二个版本成功工作? (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 我认为您的问题是由于将字节数组转换为字符串时会默认使用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));该代码片段应该工作 (adsbygoogle = window.adsbygoogle || []).push({});
10-04 21:13