javax.crypto.Cipher有问题。某些字符在加密字符串中被打断

javax.crypto.Cipher有问题。某些字符在加密字符串中被打断,java,cryptography,Java,Cryptography,当我对长字符串使用(encrypt/decrypt)javax.crypto.Cipher类时,输出字符串中的某些字符无效 //ecnryption byte[] inputBytes = str.getBytes(); cypheredBytes = cipher.doFinal(inputString, 0, inputBytes, outputBytes, 0); return new String(outputBytes, 0, cypheredBytes); //decrypt

当我对长字符串使用(encrypt/decrypt)javax.crypto.Cipher类时,输出字符串中的某些字符无效

//ecnryption
 byte[] inputBytes = str.getBytes();
 cypheredBytes = cipher.doFinal(inputString, 0, inputBytes, outputBytes, 0);
 return new String(outputBytes, 0, cypheredBytes);

//decryption
 byte[] inputBytes = str.getBytes();
 cypheredBytes = cipher.doFinal (inputBytes, 0, inputBytes.length, outputBytes, 0);
 return new String(outputBytes, 0, cypheredBytes);

我想这是字符编码的问题

以下转换可能是不可逆的:

String str = String(outputBytes, 0, cypheredBytes); 
byte[] inputBytes = str.getBytes(); 
将加密邮件保留为
字节[]
而不是
字符串

此外,以下行取决于系统默认编码:

byte[] inputBytes = str.getBytes();         
...
return new String(outputBytes, 0, cypheredBytes);
考虑显式编码规范:

byte[] inputBytes = str.getBytes("UTF-8");         
...
return new String(outputBytes, 0, cypheredBytes, "UTF-8");

axtavt是正确的。问题是不能将任意字节数组(cypheredBytes)转换为字符串。如果你真的需要它作为一个字符串(比如说,通过电线发送),那么你需要把它转换成像十六进制或Base 64这样的东西。您可以在Commons codecs中找到每种格式的编解码器。

input string=“>SVCard 2008.12.09 07:28:25……虽然这里的想法是正确的,但最后一部分最终是错误的。即使您指定UTF-8编码,即使它看起来有效,您也不能将任意字节数组生成字符串。@GregS:这不是任意数组,它是由
str.getBytes(“UTF-8”)
No,它是由cypheredBytes=cipher.doFinal(inputString,0,inputBytes,outputBytes,0)生成的+1正确,将OP指向编解码器库也很好。不要使用自己的,使用Apache通用编解码器。