package com.conan.javase.encrypt;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by Conan on 2016/11/24.
*/
public class MessageDigestTest {
private static final String SHA = "SHA-1";
private static final String[] HEX_DIGEST = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
public static void main(String[] args) {
new MessageDigestTest().testDigest();
}
public void testDigest() {
try {
String info = "测试信息";
MessageDigest digest = MessageDigest.getInstance("MD5");
// MessageDigest digest = MessageDigest.getInstance("SHA-1");
// 使用要加密的信息来更新digest
digest.update(info.getBytes());
// 填充摘要信息,使其达到固定长度
byte[] digest_b = digest.digest();
System.out.println("本摘要信息 : " + byteArrayToHexString(digest_b));
} catch (NoSuchAlgorithmException e) {
System.out.println("非法摘要算法");
}
}
public String byteArrayToHexString(byte[] b) {
StringBuilder sb = new StringBuilder();
for (int n = 0; n < b.length; n++) {
sb.append(byteToHexString(b[n]));
}
return sb.toString();
}
private String byteToHexString(byte b) {
int ret = b;
if (ret < 0)
ret += 256;
int m = ret / 16;
int n = ret % 16;
return HEX_DIGEST[m] + HEX_DIGEST[n];
}
}