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

…衆ロ難τιáo~ 提交于 2019-11-26 09:37:04

问题


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


回答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"));



回答2:


Using apache common codec library:

DigestUtils.sha1Hex("aff")

The result is 0c05aa56405c447e6678b7f3127febde5c3a9238

That's it :)




回答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().)




回答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);



回答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




回答6:


With Google Guava:

Maven:

<dependency>
   <artifactId>guava</artifactId>
   <groupId>com.google.guava</groupId>
   <version>14.0.1</version>
</dependency>

Sample:

HashCode hashCode = Hashing.sha1().newHasher()
   .putString(password, Charsets.UTF_8)
   .hash();            

String hash = BaseEncoding.base16().lowerCase().encode(hashCode.asBytes());



回答7:


If you use Spring its quite simple:

MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("SHA-1");
String hash = encoder.encodePassword(password, "salt goes here");



回答8:


There's more than just simple standard hash algorithms involved in storing passwords nonreversible.

  1. Do multiple rounds to make brute-force attacks slower
  2. Use a per-record "salt" as input to the hash algorithm besides the password to make dictionary attacks less feasible and avoid output collisions.
  3. Use "pepper", an application-configuration-setting as input to the hash algorithm to make a stolen database-dump with an unknown "pepper" useless.
  4. Pad the input to avoid weaknesses in some hash algorithms e.g. where you could append a character to the password without knowing the password, by modifying the hash.

For more info, see e.g.

  • https://password-hashing.net/
  • http://en.wikipedia.org/wiki/Category:Key_derivation_functions
  • http://en.wikipedia.org/wiki/PBKDF2
  • http://en.wikipedia.org/wiki/Scrypt

You could also use a http://en.wikipedia.org/wiki/Password-authenticated_key_agreement method to avoid passing the password in cleartext to the server at all.




回答9:


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.




回答10:


To use UTF-8, do this:

userPass.getBytes("UTF-8");

And to get a Base64 String from the digest, you can do something like this:

this.password = new BASE64Encoder().encode(cript.digest());

Since MessageDigest.digest() returns a byte array, you can convert it to String using Apache's Hex Encoding (simpler).

E.g.

this.password = Hex.encodeHexString(cript.digest());



回答11:


How about converting byte[] to base64 string?

    byte[] chkSumBytArr = digest.digest();
    BASE64Encoder encoder = new BASE64Encoder();
    String base64CheckSum = encoder.encode(chkSumBytArr);



回答12:


you can use this code too(from crackstation.net):

private static String toHex(byte[] array) { BigInteger bi = new BigInteger(1, array); String hex = bi.toString(16); int paddingLength = (array.length * 2) - hex.length(); if(paddingLength > 0) return String.format("%0" + paddingLength + "d", 0) + hex; else return hex; }




回答13:


        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        messageDigest.reset();
        messageDigest.update(password.getBytes("UTF-8"));
        String sha1String = new BigInteger(1, messageDigest.digest()).toString(16);



回答14:


echo -n "aff" | sha1sum produce the correct output (echo inserts a newline by default)




回答15:


You need to hex encode the result first. MessageDigest returns a "raw" hash, rather than a human readable one.

Edit:

@thejh provided a link to code which should work. Personally, I'd suggest using either Bouncycastle or Apache Commons Codec to do the job. Bouncycastle would be good if you want to do any other crypto-related operations.



来源:https://stackoverflow.com/questions/4400774/java-calculate-hex-representation-of-a-sha-1-digest-of-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!