Java 计算字符串的 SHA-1 摘要的十六进制表示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4400774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java calculate hex representation of a SHA-1 digest of a String
提问by Marcos Roriz Junior
I'm storing the user password on the db as a sha1 hash.
我将用户密码作为 sha1 哈希存储在数据库上。
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"
aff --> "0c05aa56405c447e6678b7f3127febde5c3a9238"
rather than
而不是
aff --> ?V@\D~fx????:?8
aff --> ?V@\D~fx????:?8
采纳答案by Jason Nichols
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.
发生这种情况是因为 cript.digest() 返回一个字节数组,您试图将其打印为字符串。您想将其转换为可打印的十六进制字符串。
Easy solution: Use Apache's commons-codec library:
简单的解决方案:使用 Apache 的commons-codec 库:
String password = new String(Hex.encodeHex(cript.digest()),
CharSet.forName("UTF-8"));
回答by Buhake Sindi
To use UTF-8, do this:
要使用 UTF-8,请执行以下操作:
userPass.getBytes("UTF-8");
And to get a Base64 String from the digest, you can do something like this:
要从摘要中获取 Base64 字符串,您可以执行以下操作:
this.password = new BASE64Encoder().encode(cript.digest());
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).
由于MessageDigest.digest()
返回一个字节数组,您可以使用 Apache 的十六进制编码(更简单)将其转换为字符串。
E.g.
例如
this.password = Hex.encodeHexString(cript.digest());
回答by developmentalinsanity
You need to hex encode the result first. MessageDigest
returns a "raw" hash, rather than a human readable one.
您需要先对结果进行十六进制编码。MessageDigest
返回一个“原始”散列,而不是人类可读的散列。
Edit:
编辑:
@thejh provided a link to code which should work. Personally, I'd suggest using either Bouncycastleor Apache Commons Codecto do the job. Bouncycastle would be good if you want to do any other crypto-related operations.
@thejh 提供了一个应该可以工作的代码链接。就个人而言,我建议使用Bouncycastle或Apache Commons Codec来完成这项工作。如果你想做任何其他与加密相关的操作,Bouncycastle 会很好。
回答by PaulJWilliams
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.
digest() 返回一个字节数组,您将使用默认编码将其转换为字符串。您要做的是对它进行 base64 编码。
回答by erickson
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 answerfor details.
您可以使用 Java 运行时内置的代码,而不是尝试使用自己的代码(或使用一些粗略的第三方膨胀软件)来正确执行此操作。有关详细信息,请参阅此答案。
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:
正确地对密码进行哈希处理后,您将获得一个byte[]
. 将其转换为十六进制的一种简单方法String
是使用BigInteger
类:
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()
.)
如果你想确保你的字符串总是有 40 个字符,你可能需要在左边做一些零填充(你可以用String.format()
.)
回答by cyber-monk
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.
crypt.digest() 方法返回一个字节[]。这个字节数组是正确的 SHA-1 和,但加密哈希通常以十六进制形式显示给人类。散列中的每个字节将产生两个十六进制数字。
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("%1x", 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.
请注意,在 Java 中使用字节非常容易出错。我会仔细检查所有内容并测试一些奇怪的情况。
Also you should consider using something stronger than SHA-1. http://csrc.nist.gov/groups/ST/hash/statement.html
此外,您应该考虑使用比 SHA-1 更强的东西。 http://csrc.nist.gov/groups/ST/hash/statement.html
回答by altumano
Using apache common codec library:
使用 apache 通用编解码器库:
DigestUtils.sha1Hex("aff")
The result is 0c05aa56405c447e6678b7f3127febde5c3a9238
结果是 0c05aa56405c447e6678b7f3127febde5c3a9238
That's it :)
就是这样 :)
回答by Vedran
If you use Spring its quite simple:
如果您使用 Spring,它非常简单:
MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("SHA-1");
String hash = encoder.encodePassword(password, "salt goes here");
回答by Mahes
How about converting byte[] to base64 string?
如何将 byte[] 转换为 base64 字符串?
byte[] chkSumBytArr = digest.digest();
BASE64Encoder encoder = new BASE64Encoder();
String base64CheckSum = encoder.encode(chkSumBytArr);
回答by Stefan L
There's more than just simple standard hash algorithms involved in storing passwords nonreversible.
不可逆地存储密码不仅仅是简单的标准哈希算法。
- Do multiple rounds to make brute-force attacks slower
- Use a per-record "salt" as input to the hash algorithm besides the password to make dictionary attacks less feasible and avoid output collisions.
- Use "pepper", an application-configuration-setting as input to the hash algorithm to make a stolen database-dump with an unknown "pepper" useless.
- 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.
- 多轮使蛮力攻击变慢
- 除了密码之外,还使用每条记录的“盐”作为哈希算法的输入,以降低字典攻击的可行性并避免输出冲突。
- 使用“pepper”(一种应用程序配置设置)作为散列算法的输入,以使带有未知“pepper”的被盗数据库转储变得无用。
- 填充输入以避免某些散列算法中的弱点,例如,通过修改散列,您可以在不知道密码的情况下将字符附加到密码中。
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
- 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_agreementmethod to avoid passing the password in cleartext to the server at all.
您还可以使用http://en.wikipedia.org/wiki/Password-authenticated_key_agreement方法来完全避免将密码以明文形式传递给服务器。