Alex Rivera | Logout

Java calculate hex representation of a SHA-1 digest of a String

Asked 2010-12-09T16:44:07.587
67

I'm storing the user password on the db as a sha1 hash.

Unfortunately I'm getting strange answers.

I'm storing the string as this:

MessageDigest cript = MessageDigest.getInstance("SHA-1");
              cript.reset();
              cript.update(userPass.getBytes("utf8"));
              this.password = new String(cript.digest());

I wanted something like this -->

aff --> "0c05aa56405c447e6678b7f3127febde5c3a9238"

rather than

aff --> �V@\D~fx����:�8

Edit
Report

2 Answers

1

digest() returns a byte array, which you're converting to a string using the default encoding. What you want to do is base64 encode it.

answered 2010-12-09T16:47:44.353
1

How about converting byte[] to base64 string?

    byte[] chkSumBytArr = digest.digest();
    BASE64Encoder encoder = new BASE64Encoder();
    String base64CheckSum = encoder.encode(chkSumBytArr);
answered 2013-03-29T18:42:26.800

Your Answer