要在Java中计算加密哈希值,将使用MessageDigest Class(位于包java.security下)。
MessageDigest类提供以下加密哈希函数来查找文本的哈希值,它们是:
1. MD5
2. SHA-1
3. SHA-256
4. SHA-512
该算法在名为getInstance()的静态方法中初始化。选择算法后,它将计算摘要值并以字节数组形式返回结果。
使用BigInteger类,该类将结果字节数组转换为其符号幅度表示。
该表示形式转换为十六进制格式以获取MessageDigest
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
// Java program to calculate MD5 hash value
public class MD5 {
public static String getMd5(String input) {
try {
// Static getInstance method is called with hashing MD5
MessageDigest md = MessageDigest.getInstance("MD5");
// digest() method is called to calculate message digest
// of an input digest() return array of byte
byte[] messageDigest = md.digest(input.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
// Driver code
public static void main(String args[]) throws NoSuchAlgorithmException {
String s = "MD5";
System.out.println("Your String is: " + s);
System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));
}
}
输出:
Your String is: MD5
Your HashCode Generated by MD5 is: 7f138a09169b250e9dcb378140907378
将getInstance("MD5")更改为getInstance("SHA-1")、getInstance("SHA-256")、getInstance("SHA-512")可计算相应的哈希值。