Java 中的 MD2 哈希

原文:https://www.geeksforgeeks.org/md2-hash-in-java/

MD2 是一个消息摘要算法。这是一个由罗纳德·瑞文斯特于 1989 年开发的加密散列函数。它针对 8 位计算机进行了优化。MD2 算法在公钥基础设施中用作用 MD2 和 RSA 生成的证书的一部分。从 2014 年开始,这个算法现在不被认为是安全算法。

为了计算 Java 中的加密散列值,使用了包 java.security 下的消息摘要类

MessagDigest 类提供以下加密哈希函数来查找文本的哈希值,如下所示:

  • MD2
  • 讯息摘要 5
  • SHA-1
  • SHA-224
  • SHA-256
  • SHA-384
  • SHA-512

这些算法在名为 getInstance() 的静态方法中初始化。选择算法后,计算消息摘要值,并将结果作为字节数组返回。使用 BigInteger 类,将结果字节数组转换为它的符号表示。然后,该表示被转换为十六进制格式,以获得预期的消息摘要。

示例:

输入:hello world T3】输出:d9cc 882 ee 690 a5 C1 ce 70 bef3a 78 c77

输入 : GeeksForGeeks 输出:787 df 774 a 3d 25 DCA 997 B1 c8 bfee 4af

下面的程序展示了 MD2 哈希在 Java 中的实现。

// Java program to calculate MD2 hash value

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class GFG {
    public static String encryptThisString(String input)
    {
        try {
            // getInstance() method is called with algorithm MD2
            MessageDigest md = MessageDigest.getInstance("MD2");

            // digest() method is called
            // to calculate message digest of the input string
            // returned as 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);

            // Add preceding 0s to make it 32 bit
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }

            // return the 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
    {
        System.out.println("HashCode Generated by MD2 for: ");

        String s1 = "GeeksForGeeks";
        System.out.println("\n" + s1 + " : " + encryptThisString(s1));

        String s2 = "hello world";
        System.out.println("\n" + s2 + " : " + encryptThisString(s2));
    }
}

输出:

HashCode Generated by MD2 for: 

GeeksForGeeks : 787df774a3d25dca997b1f1c8bfee4af

hello world : d9cce882ee690a5c1ce70beff3a78c77

应用:

  • 密码系统
  • 数据完整性