1

I am trying to convert a String to a SHA1 hash!

This is my code

public static void SHA1(String x) throws NoSuchAlgorithmException
{

    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    SHA1 = sha1.digest((x).getBytes()); 

}

I have a private static byte[] SHA1;

Sadly the output comes out like this

[B@1a758cb

I am trying to make the code as small as possible! Thanks

7
  • 2
    Your example wouldn't even compile - how are you outputting SHA1? What are you expecting? Commented Oct 23, 2011 at 3:32
  • I just gave the code for the method... with some little work you can fill the rest in! Commented Oct 23, 2011 at 6:27
  • @Hego555: Don't call getBytes on a String without giving a specific encoding. This will use the platform default encoding and will thus not lead to the same output on all the platforms. Commented Oct 23, 2011 at 8:50
  • @JB Nizet isn't SHA1 the same on all platforms? this is not my code I got it off the internet, just modified for my needs :) Commented Oct 24, 2011 at 21:30
  • I didn't say SHA1 was not the same on all the platforms. SHA1 takes bytes as input. So before using the SHA1 algorithm, the code transforms the string (unicode characters) into bytes. This transformation doesn't give the same result if the encoding is ASCII, UTF-8, UTF-16, or ISO-8859-1. If you use this algorithm, with a given string as input, on two machines with a different platform encoding, it willlead to two different results. Not because of SHA1, but because you don't transform chars into bytes the same way. Commented Oct 24, 2011 at 21:35

1 Answer 1

4

You have to print the bytes in your array, and you'd likely want to display the hash as hex.

for(byte b : SHA1 ) {
  System.out.printf("%02x",b);
}
System.out.println();
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! it worked, for future reference can you explain how it worked!
System.out.println( Arrays.toString(SHA1) ); is much more readable code IMHO, but may not do what you want.
@jackrabbit does that convert Arrays to string... i am guessing it does just cant test it :) Thanks for the code!
Yes exactly. That's java.lang.Arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.