2
votes

I am new to java security so it may sound stupid to you guys. I am using triple-des algorithm for encryption decryption in that i am using hash value as keys. I am using sha-512 for hashing i have heard that two same strings hash will be same but i am getting different output for same string. I am affixing the code of sha-512. Let me know what the problem is if possible.

public class SHA256Algo {

    public static String createHash(String text) throws UnsupportedEncodingException, NoSuchAlgorithmException 
    {
        String encryptedText = "" ;
        MessageDigest md = MessageDigest.getInstance("SHA-512");

        md.update(text.getBytes("UTF-16")); // Change this to "UTF-16" if needed
        byte[] digest = md.digest();
        String str = digest.toString() ;
        return str ;
    }

    public static void main(String[] args) {
        try {
            System.out.println(createHash("tarun")) ;
            System.out.println(createHash("tarun")) ;
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

output :
[B@32d2bb53
[B@29086036

1
toString() on array does not have the effect you expect.user3458
Can you use third-party libraries? This would be much simpler if you could use Guava's Hashing.sha512().hashString(text, Charsets.UTF_16).toString(), which would accomplish exactly what you want.Louis Wasserman

1 Answers

4
votes

Arrays are objects too in Java, but they don't override Object's toString() method. The output is not the hashed output, but the result of Object's toString() method.

[T]his method returns a string equal to the value of:

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

The getClass().getName() is responsible for [B, then there is the @ character, and the rest of the characters are the hexadecimal hash code, also from Object.

You need to convert the byte array to a String in another way besides calling toString(). This may involve conversion of the byte array to Base 64 or to hexadecimal characters.