我试图通过引用此链接中的示例来生成字符串的 sha1 - http://www.sha1-online.com/sha1-java/
public class HashTextTest {
/**
* @param args
* @throws NoSuchAlgorithmException
*/
public static void main(String[] args) throws NoSuchAlgorithmException {
System.out.println(sha1("test string to sha1"));
}
static String sha1(String input) throws NoSuchAlgorithmException {
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
我不想从字符串缓冲区中得到这一行凌乱的代码 - sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
.
有没有其他方法可以做到这一点?
最佳答案
这里您需要的是将一个字节格式化为两个十六进制数字。
sb.append(String.format("%02x", result[i]));
就可以了。
如果您需要大写的十六进制数字,请使用
sb.append(String.format("%02X", result[i]));
此外,如果您不介意编码字节之间的空格,则可以使用
new sun.misc.HexDumpEncoder().encode(result).substring(6);
一次编码整个字节[]。
关于java - 如何将 SHA1 输出转换为十六进制字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20897550/