[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

JCE, string -> byte[] -> string



I'm currently working with the JCE to implement TripleDES encryption in one 
of our products.  My stumbling block is this:  When encrypting and 
decrypting strings, its necessary to convert to string to a byte array, 
encrypt the byte array to a new byte array and convert that back to a 
string.  The encrypted string then goes through the reverse process to get 
from ciphertext to plaintext.

If I take the output of the encryption cipher, a byte array, and input that 
into the decryption cipher, all is well and good, I get back the original 
string.  However, if I attempt to convert the encrypted byte array to a 
string, either by:

  String encryptedString = new String(encryptedBytes);

or by Base64 encoding of the bytes and then reverse the process to decrypt 
the string, I can semi-regularly, depending on the input, generate output 
from the decryption process which is almost identical to the original, but 
not quite.  Looking at individual bytes, if the original and decrypted byte 
arrays are compared byte-for-byte, there will be multiples of 16 bytes (2 
blocks for DESede/CFB/PKCS5Padding) which are decrypted wrong.  This makes 
sense since the CFB mode will make the value of two adjacent blocks 
dependent on each other.

So, I have narrowed down the problem to the String -> byte[] -> String 
conversion process.  That leaves me hopelessly stuck, however.  Has anyone 
seen this problem before?  Can anyone offer advice regarding this 
conversion and ensuring that it is always repeatable?  I have a feeling it 
has to do with character encoding, but I can't be sure...

-dhs