0

I have used secureRandom class to get byte[], I converted byte[] to string using string.getBytes(). When I converted back that string to byte[] the both are not same. can anyone help me?

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;

public class sha256Salt {

public static void main(String[] args) {

    try {
        String password = "uday123";
        byte[] salt = createSalt();
        System.out.println(salt);

        String str = Arrays.toString(salt);
        System.out.println(str);

        byte[] bytes1 =str.getBytes();
        System.out.println(bytes1);


        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.reset();
        md.update(salt);
        byte[] bytes= md.digest(password.getBytes());
//      String check
//      byte[] b = 

        StringBuilder buildThis = new StringBuilder();

        for(int i=0; i<bytes.length; i++)
        {
            buildThis.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
        }

        String hashValue = buildThis.toString();

//        System.out.println("salt : " + Arrays.toString(salt));
//       
//          System.out.println(bytes);
        System.out.println("hash value is : " + hashValue);

    } catch (NoSuchAlgorithmException e) {
        System.out.println("There is no such algorithm exception ");
        e.printStackTrace();
    }   

}


    private static final byte[] createSalt() {
        byte[] bytes1 = new byte[5];
        SecureRandom random = new SecureRandom();
        random.nextBytes(bytes1);
        return bytes1;
    }
}

Current output:

[B@2133c8f8

[-101, 80, -62, 44, -60]

[B@7a79be86

Expected output:

[B@2133c8f8

[-101, 80, -62, 44, -60]

[B@2133c8f8
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • Well, no. You copy it, therefore it isn't the same. – Zoe Feb 17 '19 at 14:16
  • 1
    Possible duplicate of [Java arrays printing out weird numbers and text](https://stackoverflow.com/questions/4479683/java-arrays-printing-out-weird-numbers-and-text) – Progman Feb 17 '19 at 19:02

1 Answers1

1

You should use

String str = new String(salt);

instead of

String str = Arrays.toString(salt);

Also note that you're printing the instance hash code, which isn't what you want, this will work:

String password = "uday123";
byte[] salt = createSalt();
System.out.println(Arrays.toString(salt));

String str = new String(salt);
System.out.println(str);

byte[] bytes1 = str.getBytes();
System.out.println(Arrays.toString(bytes1));
devgianlu
  • 1,547
  • 13
  • 25