我将用户密码作为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()返回一个字节数组,您正尝试将其打印为字符串String。您想将其转换为可打印的十六进制字符串。

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

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

10-04 18:03