Java字符串到SHA1 [英] Java String to SHA1
问题描述
我正在尝试用Java创建一个简单的String to SHA1转换器,这就是我所拥有的......
I'm trying to make a simple String to SHA1 converter in Java and this is what I've got...
public static String toSHA1(byte[] convertme) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
}
catch(NoSuchAlgorithmException e) {
e.printStackTrace();
}
return new String(md.digest(convertme));
}
当我传递 toSHA1(密码。 getBytes())
,我得到 [ a ɹ?? %l 3~ 。
我知道这可能是一个简单的编码修复像UTF-8,但有人可以告诉我应该做什么来得到我想要的 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
?或者我完全错了吗?
When I pass it toSHA1("password".getBytes())
, I get [�a�ɹ??�%l�3~��.
I know it's probably a simple encoding fix like UTF-8, but could someone tell me what I should do to get what I want which is 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
? Or am I doing this completely wrong?
推荐答案
更新
你可以使用 Apache Commons Codec (1.7+版本)为您完成这项工作。
UPDATE
You can use Apache Commons Codec (version 1.7+) to do this job for you.
DigestUtils.sha1Hex(stringToConvertToSHexRepresentation)
感谢@ Jon Onstott 了解此建议。
旧答案
将字节数组转换为十六进制字符串。 Real's How To告诉你如何。
return byteArrayToHexString(md.digest(convertme))
和(从Real的方法复制)
and (copied from Real's How To)
public static String byteArrayToHexString(byte[] b) {
String result = "";
for (int i=0; i < b.length; i++) {
result +=
Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
BTW,你可能会得到使用Base64进行更紧凑的表示。 Apache Commons Codec API 1.4 ,有这个很好的实用程序来消除所有的痛苦。 在此处引用
BTW, you may get more compact representation using Base64. Apache Commons Codec API 1.4, has this nice utility to take away all the pain. refer here
这篇关于Java字符串到SHA1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!