chatrapati shiva chatrapati shiva - 2 months ago 18
Android Question

String.valueOf() giving random values

I am trying to create a string from a byte array but it gives me some random value. The byte array is encrypted, so I'm not sure I'm decrypting correctly. The random values look like -[B@1uy3798. Each time it gives different random value. How can I solve this?

public class MainActivity {
public static void main(String[] args) {

Key publicKey = null;
Key privateKey = null;
byte[] encoded;
byte[] text = new byte[0];

try {
text = "This is my secret message".getBytes();

Cipher c = Cipher.getInstance("RSA");
c.init(Cipher.ENCRYPT_MODE, publicKey);
encoded = c.doFinal(text);

c = Cipher.getInstance("RSA");
c.init(Cipher.DECRYPT_MODE, privateKey);
text = c.doFinal(encoded);

} catch (Exception e) {
System.out.println("Exception encountered. Exception is " + e.getMessage());
}
System.out.println(String.valueOf(text)); //get random values here
}
}

Answer

String.valueOf(text) doesn't do what you think it does. What you want is new String(text).

String.valueOf(text) returns a string representation of the pointer to the array (its hashcode). You want to turn the array into a String, so use the appropriate constructor.

To explain why you're getting this value returned, you should look at the contract of toString() in java.lang.Object:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method. The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

To put it all together, you get -[B@1uy3798 because The [B is the name of the class byte[] (you'll see this in bytecode if you disassemble the class file), followed by '@', followed by 1uy3798. If you were to run the class again and call hashCode() on the byte[] text, you'd see that the hashcode matches the value you're seeing in the Toast.