MD2 消息摘要

MD 是 Message Digest Algorithm 的简称,中文名消息摘要算法,目前最新为第五版即 MD5,历史版本有 MD4、MD2 等,由于存在缺陷都已不再使用。消息摘要算法各个版本间的生成的消息摘要结果是不一样的。

Rivest 在 1989 年开发出 MD2 算法。在这个算法中,首先对信息进行数据补位,使信息的字节长度是 16 的倍数。然后,以一个 16 位的检验和追加到信息末尾,并且根据这个新产生的信息计算出散列值。后来,Rogier 和 Chauvaud 发现如果忽略了检验将和 MD2 产生冲突。MD2 算法加密后结果是唯一的(即不同信息加密后的结果不同)。

JDK

JDK 自带的 MessageDigest 类为应用程序提供信息摘要算法的功能,如 MD5 或 SHA 算法。信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。实例:

import org.apache.commons.codec.binary.Hex;
import java.security.MessageDigest;

public class CryptMd2Demo1 {

    public static void main(String[] args) throws Exception {
        String src = "hello world";
        // 获得消息摘要MD2对象
        MessageDigest digest = MessageDigest.getInstance("MD2");
        byte[] md2Byte = digest.digest(src.getBytes());
        System.out.println("md2Byte :"+ Hex.encodeHexString(md2Byte));
    }

}

输出结果:

md2Byte :d9cce882ee690a5c1ce70beff3a78c77

Commons Codec

Apache Commons Codec 提供的 DigestUtils 类用于简化常见 MessageDigest(消息摘要)任务的操作。此类是不可变的并且是线程安全的。

MessageDigestAlgorithms 类为标准消息摘要算法提供常量,提供了 DigestUtils 支持的消息摘要算法名称常亮。它可与 getDigest(String) 方法和其他需要摘要算法名称的方法一起使用。

实例1:使用 digest() 方法进行 MD2 消息摘要算法计算。

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;

public class CryptMd2Demo2 {

    public static void main(String[] args) {
        String src = "hello world";
        DigestUtils digest = new DigestUtils(MessageDigestAlgorithms.MD2);
        byte[] md2Byte = digest.digest(src.getBytes());
        System.out.println("md2Byte :"+ Hex.encodeHexString(md2Byte));
    }

}

输出结果:

md2Byte :d9cce882ee690a5c1ce70beff3a78c77

实例2:使用 digestAsHex() 方法,生成消息摘要字符串,避免自己将字节数组转化成字符串。

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;

public class CryptMd2Demo3 {

    public static void main(String[] args) {
        String src = "hello world";
        DigestUtils digest = new DigestUtils(MessageDigestAlgorithms.MD2);
        System.out.println("md2Byte :"+ digest.digestAsHex(src.getBytes()));
    }

}

输出结果:

md2Byte :d9cce882ee690a5c1ce70beff3a78c77

实例3:使用静态方法 md2Hex() 计算 MD2 消息摘要。

import org.apache.commons.codec.digest.DigestUtils;

public class CryptMd2Demo4 {

    public static void main(String[] args) {
        String src = "hello world";
        System.out.println("md2Byte :"+ DigestUtils.md2Hex(src.getBytes()));
    }

}

输出结果:

md2Byte :d9cce882ee690a5c1ce70beff3a78c77

注意:更多关于 DigestUtils 的用法,请参考官网API:

http://commons.apache.org/proper/commons-codec/apidocs/index.html

说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号