📜  Java的MD5 哈希

📅  最后修改于: 2021-10-27 09:20:36             🧑  作者: Mango

为了计算Java的加密散列值,在包Java.security 下使用MessageDigest类。

MessageDigest 类提供以下加密哈希函数来查找文本的哈希值,它们是:
1. MD5
2. SHA-1
3. SHA-256

该算法在名为getInstance() 的静态方法中初始化。选择算法后,它计算摘要值并将结果以字节数组形式返回。

使用 BigInteger 类,它将结果字节数组转换为其符号大小表示

此表示转换为十六进制格式以获取 MessageDigest

例子:

Input : hello world
Output : 5eb63bbbe01eeed093cb22bb8f5acdc3

Input : GeeksForGeeks
Output : e39b9c178b2c9be4e99b141d956c6ff6
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 = "GeeksForGeeks";
        System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));
    }
}

输出:

Your HashCode Generated by MD5 is: e39b9c178b2c9be4e99b141d956c6ff6

参考: MessageDigest 的Java文档

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程