MD5编码相关的类

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5编码相关的类
 * 
 * @author wangjingtao
 * 
 */
public class MD5 {
    // 首先初始化一个字符数组,用来存放每个16进制字符
    private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**
     * 获得一个字符串的MD5值
     * 
     * @param input 输入的字符串
     * @return 输入字符串的MD5值
     * 
     */
    public static String md5(String input) {
        if (input == null)
            return null;

        try {
            // 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 输入的字符串转换成字节数组
            byte[] inputByteArray = input.getBytes("utf-8");
            // inputByteArray是输入字符串转换得到的字节数组
            messageDigest.update(inputByteArray);
            // 转换并返回结果,也是字节数组,包含16个元素
            byte[] resultByteArray = messageDigest.digest();
            // 字符数组转换成字符串返回
            return byteArrayToHex(resultByteArray);
        } catch (NoSuchAlgorithmException e) {
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;

        }
    }

    /**
     * 获取文件的MD5值
     * 
     * @param file
     * @return
     */
    public static String md5(File file) {
        try {
            if (!file.isFile()) {
                System.err.println("文件" + file.getAbsolutePath() + "不存在或者不是文件");
                return null;
            }

            FileInputStream in = new FileInputStream(file);

            String result = md5(in);

            in.close();

            return result;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String md5(InputStream in) {

        try {
            MessageDigest messagedigest = MessageDigest.getInstance("MD5");

            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = in.read(buffer)) != -1) {
                messagedigest.update(buffer, 0, read);
            }

            in.close();

            String result = byteArrayToHex(messagedigest.digest());

            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String byteArrayToHex(byte[] byteArray) {
        // new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
        char[] resultCharArray = new char[byteArray.length * 2];
        // 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
        int index = 0;
        for (byte b : byteArray) {
            resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
            resultCharArray[index++] = hexDigits[b & 0xf];
        }

        // 字符数组组合成字符串返回
        return new String(resultCharArray);

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Python语言实现的MD5算法代码: ```python import math import struct # 定义MD5算法所需的常数 T = [int(abs(math.sin(i + 1)) * 2**32) for i in range(64)] # 定义左移函数 def left_rotate(x, n): return ((x << n) & 0xffffffff) | (x >> (32 - n)) # 定义MD5算法的核心函数 def md5(message): # 定义四个缓冲区 a0 = 0x67452301 b0 = 0xefcdab89 c0 = 0x98badcfe d0 = 0x10325476 # 对消息进行预处理 length = len(message) message += b'\x80' while (len(message) * 8) % 512 != 448: message += b'\x00' message += struct.pack('<Q', length * 8) # 进行分块处理 chunks = [message[i:i+64] for i in range(0, len(message), 64)] for chunk in chunks: # 初始化缓冲区 a, b, c, d = a0, b0, c0, d0 # 进行64轮迭代 for i in range(64): if i < 16: f = (b & c) | ((~b) & d) g = i elif i < 32: f = (d & b) | ((~d) & c) g = (5 * i + 1) % 16 elif i < 48: f = b ^ c ^ d g = (3 * i + 5) % 16 else: f = c ^ (b | (~d)) g = (7 * i) % 16 # 计算新的a, b, c, d temp = d d = c c = b b = b + left_rotate((a + f + T[i] + struct.unpack('<I', chunk[4*g:4*g+4])[0]), 7) a = temp # 更新缓冲区 a0 = (a0 + a) & 0xffffffff b0 = (b0 + b) & 0xffffffff c0 = (c0 + c) & 0xffffffff d0 = (d0 + d) & 0xffffffff # 将结果转换为十六进制字符串 return '{:08x}{:08x}{:08x}{:08x}'.format(a0, b0, c0, d0) ``` 使用方法: ```python message = b'The quick brown fox jumps over the lazy dog' print(md5(message)) # 输出结果:9e107d9d372bb6826bd81d3542a419d6 ``` 这里的`message`是待加密的消息,以字节串的形式表示。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值