Java加密算法的方法
import java.security.*;
public class MessageCheck {
public static void main(String[] args) {
String info1 = "admin";
//String info1 = "Hello World!";
String info2 = "Hello World!";
try{
// 生成 MessageDigest 实例,确定计算方法
//MessageDigest md1 = MessageDigest.getInstance("SHA-1");
MessageDigest md1 = MessageDigest.getInstance("MD5");
// 添加要计算的摘要信息
md1.update(info1.getBytes()); // transform parameter to byte[]
// 完成哈希计算,返回计算得到的摘要(对于MD5是16位,SHA是20位)
byte[] digA = md1.digest();
// 生成 MessageDigest 实例,确定计算方法
//MessageDigest md2 = MessageDigest.getInstance("SHA-1");
MessageDigest md2 = MessageDigest.getInstance("MD5");
md2.update(info2.getBytes());
byte[] digB = md2.digest();
// 比较两信息是否相等
if (md2.isEqual(digA, digB)) {
System.out.println("两信息相等,检查正常!");
System.out.println(hasString(digA) + "/n" + hasString(digB));
}
else {
System.out.println("两信息不相等,摘要不相同!");
System.out.println(hasString(digA) + "/n" + hasString(digB));
}
} catch (NoSuchAlgorithmException e) {
System.out.println("非法摘要算法!");
e.printStackTrace();
}
}
public static String hasString(byte[] b) {
String has = "", tmp = "";
for (int i = 0; i < b.length; i++){
// 以十六进制的无符号整数形式返回一个整数参数的字符串表示形式
tmp=(java.lang.Integer.toHexString(b[i] & 0XFF));
if (tmp.length() == 1)
has = has + "0" + tmp;
else
has = has + tmp;
if (i < b.length - 1) has = has + ":";
}
return has.toUpperCase();
}
}///~:
本文地址:http://www.45fan.com/a/question/72089.html