Java calculate hex representation of a SHA-1 diges

2020-01-26 07:02发布

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

标签: java hash sha1
15条回答
欢心
2楼-- · 2020-01-26 07:16

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);
查看更多
女痞
3楼-- · 2020-01-26 07:18

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; }

查看更多
Viruses.
4楼-- · 2020-01-26 07:18

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.

查看更多
一纸荒年 Trace。
5楼-- · 2020-01-26 07:22

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

查看更多
做自己的国王
6楼-- · 2020-01-26 07:24

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());
查看更多
爷的心禁止访问
7楼-- · 2020-01-26 07:25
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        messageDigest.reset();
        messageDigest.update(password.getBytes("UTF-8"));
        String sha1String = new BigInteger(1, messageDigest.digest()).toString(16);
查看更多
登录 后发表回答