md5摘要的生成方式

本文介绍了在Java程序、Linux使用md5sum命令及Windows系统中如何生成MD5摘要。通过对比,揭示了Java程序与md5sum在处理字符串时的差异,主要在于Linux的echo命令默认添加换行符导致的MD5值不同,以及如何通过echo -n或echo -e来避免这种情况。同时提到了Windows系统中使用certutil命令进行MD5计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、java程序生成MD5摘要

在java程序中实现MD5摘要方法,生成16进制的字符串

	/**
     * 将字符串的MD5值转为16进制字符串
     * @param inStr
     * @return
     */
    public static String string2MD5(String inStr){
        String result = null;
        MessageDigest messageDigest;

        try {
            messageDigest = MessageDigest.getInstance(ENCRYPT_ALGORITHM);
            byte[] outByteArray = messageDigest.digest(inStr.getBytes());
            result = HexUtils.toHexString(outByteArray);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return result;
    }
	
	/**
     * 计算文件的md5值
     * @param filePath
     * @return
     */
	public static String file2MD5(String filePath){
        String result = null;
        MessageDigest messageDigest;
        File file = new File(filePath);
        try {
            FileInputStream in = new FileInputStream(file);
            FileChannel ch = in.getChannel();
            MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY,0,file.length());

            messageDigest = MessageDigest.getInstance(ENCRYPT_ALGORITHM);
            messageDigest.update(byteBuffer);

            byte[] outByteArray = messageDigest.digest();
            result = HexUtils.toHexString(outByteArray);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
    
    public static void main(String[] args) {
        // 1aabac6d068eef6a7bad3fdf50a05cc8
        String xxx = "dd";
        String s = string2MD5(xxx);
        System.out.printf(s);
    }

2、linux使用md5sum生成摘要

使用md5sum生成字符串的摘要值

// 使用echo默认情况,在字符串末尾自动添加换行符
[root@localhost ~]# echo 'dd' | md5sum
b064a020db8018f18ff5ae367d01b212  -
// echo -n,表示不在字符串末尾自动添加换行符
[root@localhost ~]# echo -n 'dd' | md5sum
1aabac6d068eef6a7bad3fdf50a05cc8  -
// echo -n -e,表示不在字符串末尾自动添加换行符,-e表示支持以'\'作为转义字符进行转义;手动添加换行符后md5值与echo不加参数的情况一致
[root@localhost ~]# echo -n -e 'dd\n' | md5sum
b064a020db8018f18ff5ae367d01b212  -
  • 从上面两种生成方式不同可以获取结论,java程序和md5sum的算法是一致,导致md5不一致的原因是echo输出字符串时会在字符串末尾添加’\n’换行符。
  • echo -n ‘字符串’,将字符串转为输出流,在字符串末尾不添加‘\n’
  • echo -e ‘字符串’,在字符串中可以使用反斜杠作为转移字符

3、windows操作系统中计算MD5的方法

Windows 系统自带工具 certutil,具体命令 certutil -hashfile 文件地址 MD5

D:\logs>certutil -hashfile aa.txt MD5
MD5 的 aa.txt 哈希:
b064a020db8018f18ff5ae367d01b212
CertUtil: -hashfile 命令成功完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值