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

100,274

Solution 1

This is happening because cript.digest() returns a byte array, which you're trying to print out as a character String. You want to convert it to a printable Hex String.

Easy solution: Use Apache's commons-codec library:

String password = new String(Hex.encodeHex(cript.digest()),
                             CharSet.forName("UTF-8"));

Solution 2

Using apache common codec library:

DigestUtils.sha1Hex("aff")

The result is 0c05aa56405c447e6678b7f3127febde5c3a9238

That's it :)

Solution 3

One iteration of a hash algorithm is not secure. It's too fast. You need to perform key strengthening by iterating the hash many times.

Furthermore, you are not salting the password. This creates a vulnerability to pre-computed dictionaries, like "rainbow tables."

Instead of trying to roll your own code (or using some sketchy third-party bloatware) to do this correctly, you can use code built-in to the Java runtime. See this answer for details.

Once you have hashed the password correctly, you'll have a byte[]. An easy way to convert this to a hexadecimal String is with the BigInteger class:

String passwordHash = new BigInteger(1, cript.digest()).toString(16);

If you want to make sure that your string always has 40 characters, you may need to do some padding with zeroes on the left (you could do this with String.format().)

Solution 4

If you don't want to add any extra dependencies to your project, you could also use

MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(message.getBytes("utf8"));
byte[] digestBytes = digest.digest();
String digestStr = javax.xml.bind.DatatypeConverter.printHexBinary(digestBytes);

Solution 5

The crypt.digest() method returns a byte[]. This byte array is the correct SHA-1 sum, but crypto hashes are typically displayed to humans in hex form. Each byte in your hash will result in two hex digits.

To safely convert a byte to hex use this:

// %1$ == arg 1
// 02  == pad with 0's
// x   == convert to hex
String hex = String.format("%1$02x", byteValue);

This code snippet can be used for converting a char to hex:

/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 
import java.io.*;

public class UnicodeFormatter  {

   static public String byteToHex(byte b) {
      // Returns hex String representation of byte b
      char hexDigit[] = {
         '0', '1', '2', '3', '4', '5', '6', '7',
         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
      };
      char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
      return new String(array);
   }

   static public String charToHex(char c) {
      // Returns hex String representation of char c
      byte hi = (byte) (c >>> 8);
      byte lo = (byte) (c & 0xff);
      return byteToHex(hi) + byteToHex(lo);
   }
}

Note that working with bytes in Java is very error prone. I would double check everything and test some strange cases as well.

Also you should consider using something stronger than SHA-1. http://csrc.nist.gov/groups/ST/hash/statement.html

Share:
100,274
Marcos Roriz Junior
Author by

Marcos Roriz Junior

I’m an adjunct professor of Transportation Engineering at Faculty of Science and Technology (FCT) in Federal University of Goiás (UFG). I’m interested in exploring Computer Science within Transportation Engineering through Computational Intelligence (e.g., Machine Learning, Evolutionary Computing, and Fuzzy Logic) and Distributed Systems (e.g., Internet of Things and Data Stream Processing) to enable Intelligent Transportation Systems and Smart Cities. Further, I’m also interested on investigating the direct and collateral effects of such systems in our society.

Updated on July 08, 2022

Comments

  • Marcos Roriz Junior
    Marcos Roriz Junior almost 2 years

    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