Java计算String的SHA-1摘要的十六进制表示

Mar*_*ior 58 java hash sha1

我将用户密码存储在db上作为sha1哈希.

不幸的是,我得到了奇怪的答案.

我将字符串存储为:

MessageDigest cript = MessageDigest.getInstance("SHA-1");
              cript.reset();
              cript.update(userPass.getBytes("utf8"));
              this.password = new String(cript.digest());
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西 - >

aff - >"0c05aa56405c447e6678b7f3127febde5c3a9238"

而不是

aff - > V@ \D~fx : 8

alt*_*ano 103

使用apache通用编解码器库:

DigestUtils.sha1Hex("aff")
Run Code Online (Sandbox Code Playgroud)

结果是0c05aa56405c447e6678b7f3127febde5c3a9238

而已 :)

  • 这在commons-codec-1.7中已弃用.你现在可以使用`String sha1password = DigestUtils.sha1Hex(password);` (21认同)
  • `echo -n"aff"| sha1sum`生成正确的输出(echo默认插入换行符) (4认同)

Jas*_*ols 40

发生这种情况是因为cript.digest()返回一个字节数组,您尝试将其打印为字符串.您想将其转换为可打印的十六进制字符串.

简单的解决方案:使用Apache的commons-codec库:

String password = new String(Hex.encodeHex(cript.digest()),
                             CharSet.forName("UTF-8"));
Run Code Online (Sandbox Code Playgroud)

  • 获取错误说构造函数String(char [],Charset)未定义.使用this.password = Hex.encodeHexString(cript.digest()); (2认同)

eri*_*son 25

哈希算法的一次迭代不安全.它太快了.您需要多次迭代哈希来执行密钥加强.

此外,您没有使用密码.这会对预先计算的词典(如"彩虹表")造成漏洞.

您可以使用内置于Java运行时的代码,而不是尝试使用自己的代码(或使用一些粗略的第三方膨胀软件)来正确执行此操作.有关详情,请参阅此答案.

一旦你正确地散列了密码,你就会得到一个byte[].将此转换为十六进制的简单方法String是使用以下BigInteger类:

String passwordHash = new BigInteger(1, cript.digest()).toString(16);
Run Code Online (Sandbox Code Playgroud)

如果你想确保你的字符串总是有40个字符,你可能需要在左边用零做一些填充(你可以用String.format().)

  • +1提及填充,因为许多人忘了. (4认同)

Man*_*hni 10

如果您不想为项目添加任何额外的依赖项,您也可以使用

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


cyb*_*onk 5

crypt.digest()方法返回一个byte [].此字节数组是正确的SHA-1总和,但加密哈希值通常以十六进制形式显示给人.散列中的每个字节将产生两个十六进制数字.

要将字节安全地转换为十六进制,请使用:

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

此代码段可用于将char转换为十六进制:

/*
 * 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);
   }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在Java中使用字节非常容易出错.我会仔细检查一切并测试一些奇怪的情况.

你也应该考虑使用比SHA-1更强的东西. http://csrc.nist.gov/groups/ST/hash/statement.html