我将用户密码存储在db上作为sha1哈希。
不幸的是,我得到了奇怪的答案。
我将字符串存储为:
MessageDigest cript = MessageDigest.getInstance("SHA-1");
cript.reset();
cript.update(userPass.getBytes("utf8"));
this.password = new String(cript.digest());
我想要这样的东西 - >
aff - >“0c05aa56405c447e6678b7f3127febde5c3a9238”
而不是
aff - >�V@ \D~fx����:�8
发生这种情况是因为cript.digest()返回一个字节数组,您尝试将其打印为字符串。您想将其转换为可打印的十六进制字符串。
简单的解决方案:使用Apache的commons-codec library:
String password = new String(Hex.encodeHex(cript.digest()),
CharSet.forName("UTF-8"));
要使用UTF-8,请执行以下操作:
http://en.wikipedia.org/wiki/Password-authenticated_key_agreement
要从摘要中获取Base64字符串,您可以执行以下操作:
userPass.getBytes("UTF-8");
由于this.password = new BASE64Encoder().encode(cript.digest());
返回一个字节数组,您可以使用Apache的MessageDigest.digest()
(更简单)将其转换为String。
EG
Hex Encoding
如何将byte []转换为base64字符串?
this.password = Hex.encodeHexString(cript.digest());
你也可以使用这个代码(来自crackstation.net):
byte[] chkSumBytArr = digest.digest();
BASE64Encoder encoder = new BASE64Encoder();
String base64CheckSum = encoder.encode(chkSumBytArr);
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;
}
echo -n“aff”| sha1sum生成正确的输出(echo默认插入换行符)
您需要首先对结果进行十六进制编码。 MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
messageDigest.reset();
messageDigest.update(password.getBytes("UTF-8"));
String sha1String = new BigInteger(1, messageDigest.digest()).toString(16);
返回一个“原始”哈希,而不是人类可读的哈希。
编辑:
@thejh提供了一个应该有效的代码链接。就个人而言,我建议使用MessageDigest
或Bouncycastle来完成这项工作。如果你想做任何其他与加密有关的操作,Bouncycastle会很好。
使用apache通用编解码器库:
DigestUtils.sha1Hex("aff")
结果是0c05aa56405c447e6678b7f3127febde5c3a9238
而已 :)
哈希算法的一次迭代不安全。它太快了。您需要多次迭代哈希来执行密钥加强。
此外,您没有使用密码。这会对预先计算的词典(如“彩虹表”)造成漏洞。
您可以使用内置于Java运行时的代码,而不是尝试使用自己的代码(或使用一些粗略的第三方膨胀软件)来正确执行此操作。有关详细信息,请参阅this answer。
一旦你正确地散列了密码,你就会有一个byte[]
。将此转换为十六进制String
的简单方法是使用BigInteger
类:
String passwordHash = new BigInteger(1, cript.digest()).toString(16);
如果你想确保你的字符串总是有40个字符,你可能需要在左边用零填充(你可以用qazxsw poi来做)。
如果您不想为项目添加任何额外的依赖项,您也可以使用
String.format()
crypt.digest()方法返回一个byte []。此字节数组是正确的SHA-1总和,但加密哈希值通常以十六进制形式显示给人。散列中的每个字节将产生两个十六进制数字。
要将字节安全地转换为十六进制,请使用:
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.update(message.getBytes("utf8"));
byte[] digestBytes = digest.digest();
String digestStr = javax.xml.bind.DatatypeConverter.printHexBinary(digestBytes);
// %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
请注意,在Java中使用字节非常容易出错。我会仔细检查一切并测试一些奇怪的情况。
你也应该考虑使用比SHA-1更强的东西。 /*
* 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);
}
}
使用http://csrc.nist.gov/groups/ST/hash/statement.html:
Maven的:
Google Guava
样品:
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>14.0.1</version>
</dependency>
如果你使用Spring很简单:
HashCode hashCode = Hashing.sha1().newHasher()
.putString(password, Charsets.UTF_8)
.hash();
String hash = BaseEncoding.base16().lowerCase().encode(hashCode.asBytes());
存储密码不可逆的简单标准哈希算法不仅仅是简单的标准哈希算法。
有关详细信息,请参阅例如
MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("SHA-1");
String hash = encoder.encodePassword(password, "salt goes here");
您也可以使用http://en.wikipedia.org/wiki/Scrypt方法来避免以明文形式将密码传递给服务器。
digest()返回一个字节数组,您将使用默认编码将其转换为字符串。你想要做的是base64编码。