当我将该字符串转换回byte []时,两者都不相同。谁能帮我?

问题描述 投票:0回答:1

我使用secureRandom类来获取byte [],我使用string.getBytes()将byte []转换为字符串。当我将该字符串转换回byte []时,两者都不相同。谁能帮我?

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;
    }
}

当前输出:

[B@2133c8f8

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

[B@7a79be86

预期产量:

[B@2133c8f8

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

[B@2133c8f8
java
1个回答
1
投票

你应该用

String str = new String(salt);

代替

String str = Arrays.toString(salt);

另请注意,您正在打印实例哈希代码,这不是您想要的,这将起作用:

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));
© www.soinside.com 2019 - 2024. All rights reserved.