views:

115

answers:

2

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, outputBytes, 0);
 return new String(outputBytes, 0, cypheredBytes);
A: 

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");
axtavt
Thanx, but it doesn`t help
While the idea here is correct, the last part is ultimately incorrect. You cannot make an arbitrary byte array into a String *even if* you specify UTF-8 encoding and *even if* it appears to work.
GregS
@GregS: It's not an arbitrary array, it's a result of `str.getBytes("UTF-8")`
axtavt
@axtavt: No, it is the result of cypheredBytes = cipher.doFinal(inputString, 0, inputBytes, outputBytes, 0);
GregS
+1  A: 

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.

Tourmalet
+1 correct, and pointing the OP to the codecs library is good too. Don't roll your own, use Apache Common Codecs.
GregS
Or just cart the crypto data around as a byte[] array ...
EJP