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

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

问题描述



不幸的是,我收到了奇怪的答案。



我将字符串存储为:

  MessageDigest cript = MessageDigest.getInstance(SHA-1 ); 
cript.reset();
cript.update(userPass.getBytes(utf8));
this.password = new String(cript.digest());

我想要这样 - >



< - >0c05aa56405c447e6678b7f3127febde5c3a9238



而不是

aff - > V@ \这是因为cript.digest()返回一个字节数组,这是因为cript.digest()返回一个字节数组,你正试图打印出一个字符字符串。你想将它转换为可打印的Hex字符串。

=noreferrer> commons-codec库:

 字符串密码=新字符串(Hex.encodeHex(cript。 digest()),
CharSet.forName(UTF-8));


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

解决方案

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.

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

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

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

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