Java 计算字符串的 SHA-1 摘要的十六进制表示 [英] Java calculate hex representation of a SHA-1 digest of a String

查看:22
本文介绍了Java 计算字符串的 SHA-1 摘要的十六进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将用户密码作为 sha1 哈希存储在数据库中.

I'm storing the user password on the db as a sha1 hash.

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

Unfortunately I'm getting strange answers.

我将字符串存储如下:

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"

而不是

aff --> V@D~fx : 8

aff --> �V@D~fx����:�8

推荐答案

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

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.

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

Easy solution: Use Apache's commons-codec library:

String password = new String(Hex.encodeHex(cript.digest()),
                             CharSet.forName("UTF-8"));

这篇关于Java 计算字符串的 SHA-1 摘要的十六进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆