For a given byte[], always the same, I'd like to get the corresponding String. the byte[] result
has always the same value.
However the String returned is never the same, each time I launch my app the result changes.
byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
String result = Base64.encodeBase64String(results);
I tried several other ways to get my String like String result = new String(results, "UTF-8");
, with Array
,... but it remains different everytime.
This is happening after a cipher encryption. Here is the full code:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5padding");
byte[] keyBuf= new byte[16];
byte[] b= key.getBytes("UTF-8");
int len= b.length;
if (len > keyBuf.length) len = keyBuf.length;
System.arraycopy(b, 0, keyBuf, 0, len);
SecretKeySpec keySpec = new SecretKeySpec(keyBuf, "AES256");
byte[] ivBuf= new byte[16];
//IvParameterSpec ivSpec = new IvParameterSpec(ivBuf);
IvParameterSpec ivSpec=null;
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] results = cipher.doFinal(text.getBytes("UTF-8"));
String result = Base64.encodeBase64String(results);
return result;
How can I ensure that the String "result" will remains the same?
You're using a different IV every time you encrypt - therefore you'll get different ciphertext each time you encrypt, too. Your results
byte array is different each time, therefore the base64 representation is different.
If you really want to get the same result each time you encrypt the same input, you'll need to use the same IV each time... but be aware that that will reduce the security significantly. (Note that currently you're not even doing anything with ivSpec
. You would probably want to pass it as a third argument to Cipher.init
... but you'd want to do it having initialized it with an IV, not just using null
.)
See more on this question at Stackoverflow