Convert String encoded to byte

0

I am the AES-GCM encryption user on my server, and decrypt it on my android client. However I'm having a conversion problem.

We assume that:

1- Encrypted text generates value in bytes: [B@541fe858

2- This value is embedded in JSONObject and sent to the client.

3- The client receives this value with:

  String cryptoJSON =  JSONencryptedresponseWS.getString("crypto");

That results in the correct value of [B@541fe858 .

4- However then this String must be converted to bytes, to pass this value to the decrypt function. The problem is that by doing the methods cryptoJSON.getBytes or using base64.decode , it results in a different value than expected (ie [B@f2f55b3 ).

Does anyone know how to extract the concrete value that is in String to byte format, do a direct conversion?

    
asked by anonymous 19.12.2017 / 18:55

1 answer

2
  

1- Encrypted text generates value in bytes: [B@541fe858

Wrong. This is not the encrypted value. It is just the result of calling the toString() method in an array.

For example:

byte[] bytes = {(byte) 'a', (byte) 'b', (byte) 'c'};
System.out.println(bytes);
System.out.println(bytes.toString());
byte[] bytes2 = {(byte) 'a', (byte) 'b', (byte) 'c'};
System.out.println(bytes2);

Produce output:

[B@1540e19d
[B@1540e19d
[B@677327b6

See here at ideone.

What you should do is use constructor of String that receives byte[] as parameter:

byte[] bytes = {(byte) 'a', (byte) 'b', (byte) 'c'};
String s = new String(bytes);
System.out.println(s);

Here's the output:

abc

The rest of your question is wrong because it is based on the fact that the format starting with [B@ is correct, but it is not. This is because arrays do not override the toString() method of the Object class, which by default produces the binary name of the class, followed by a '@' and followed by the result of hashCode() in hexadecimal. The binary name of byte[] is [B . The hashCode() of an array is also inherited from Object and derived from the object's memory address.

This default behavior of toString() inherited from Object is most often a useless behavior that produces a result without any use. Even objects with identical content but different memory locations will generate different and equally useless results in toString() (see in the first code of this answer that the two arrays of identical contents generate different results in toString() ). This is what is happening to you. You should use suitable builder for String to have the correct byte[] encoding.

    
19.12.2017 / 19:12