开发者

Problem with javax.crypto.Cipher. Some characters are broken in dercypted string

When I am using (encrypt/decrypt) javax.crypto.Cipher class for long string, some characters in output string are invalid.

//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, ou开发者_JAVA技巧tputBytes, 0);
 return new String(outputBytes, 0, cypheredBytes);


axtavt is correct. The problem is that you cannot turn an arbitrary byte array (cypheredBytes) into a String. If you really need it as a String (say, to send across the wire) then you'll need to turn it into something like hex or Base 64. You'll find codecs for each of these in Commons Codecs.


I guess it's a problem with character encodings.

The following transformation may be not reversible:

String str = String(outputBytes, 0, cypheredBytes); 
byte[] inputBytes = str.getBytes(); 

Keep the encrypted message as a byte[] instead of String.

Also, the following lines depend on system default encoding:

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

Consider explicit encoding specification:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜