I want to store a byte array wrapped in a String object. Here’s the scenario
- The user enters a password.
- The bytes of that password are obtained using the getBytes() String method.
- They bytes are encrypted using java’s crypo package.
- Those bytes are then converted into a String using the constructor new String(bytes[])
- That String is stored, or otherwise passed around (NOT changed)
- The bytes of that String are obtained and they are different then the encoded bytes.
Here’s a snippet of code that describes what I’m talking about.
String s = "test123";
byte[] a = s.getBytes();
byte[] b = env.encrypt(a);
String t = new String(b);
byte[] c = t.getBytes();
byte[] d = env.decrypt(c);
Where env.encrypt() and env.decrypt() do the encryption and decryption. The problem I’m having is that the b array is of length 8 and the c array is of length 16. I would think that they would be equal. What’s going on here? I tried to modify the code as below
String s = "test123";
Charset charset = Charset.getDefaultCharset();
byte[] a = s.getBytes(charset);
byte[] b = env.encrypt(a);
String t = new String(b, charset);
byte[] c = t.getBytes(charset);
byte[] d = env.decrypt(c);
but that didn’t help.
Any ideas?
It’s not a good idea to store binary data in a String object. You’d be better off using something like Base64 encoding, which is intended to make binary data into a printable string, and is completely reversible.
In fact, I just found a public domain base64 encoder for Java: http://iharder.sourceforge.net/current/java/base64/