MD5加密



1.首先封装MD5工具类如下;
/**
 * MD5英文全称“Message-Digest Algorithm 5”,翻译过来是“消息摘要算法5”,由MD2、MD3、MD4演变过来的,是一种单向加密算法,是不可逆的一种的加密方式。
 * <p>
 * MD5应用场景:
 * 1.一致性验证
 * 2.数字签名
 * 3.安全访问认证
 */
public class Md5Util {


    /**
     * 计算字符串MD5值
     */
    public static String encrypt(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            //获得MD5摘要算法的 MessageDigest 对象
            md5 = MessageDigest.getInstance("MD5");
            //获得密文
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            //把密文转换成十六进制的字符串形式
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 计算文件的MD5值(nio方法)
     */
    public static String encrypt(File file) {
        String result = "";
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            byte[] bytes = md5.digest();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    /**
     * 对字符串多次MD5加密
     *
     * @param times 加密次数
     */
    public static String encrypt(String string, int times) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        String md5 = encrypt(string);
        for (int i = 0; i < times - 1; i++) {
            md5 = encrypt(md5);
        }
        return encrypt(md5);
    }


    /**
     * MD5加盐
     * 加盐的方式:
     * 1.string+key(盐值key)然后进行MD5加密
     * 2.用string明文的hashcode作为盐,然后进行MD5加密
     * 3.随机生成一串字符串作为盐,然后进行MD5加密
     */
    public static String encrypt(String string, String slat) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest((string + slat).getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


}
2.调用的参数形式为String
    //假设参数为 "name","黄家驹";"age","18";"sex","男"
        String encrypt = Md5Util.encrypt("name" + "黄家驹" + "&age" + "18" + "&sex" + "男");
        Log.e("MD5",encrypt);
输出;1f04400727db71ae4041796fa3fb4dda
    //想多次循环假如循环五次
        String encrypt1 = Md5Util.encrypt(encrypt, 5);
        Log.e("5次加密",encrypt1);
输出; bc6efcea3c522b596ecadfc301e3d367
### 使用Python中的`hashlib`模块实现MD5加密 在Python中,可以利用内置的`hashlib`库轻松完成MD5加密操作。以下是具体的方法: #### 导入必要的模块 为了使用MD5加密功能,首先需要导入`hashlib`模块[^1]。 ```python import hashlib ``` #### 创建MD5对象并更新数据 通过调用`hashlib.md5()`创建一个MD5哈希对象,并使用`.update(data)`方法传入待加密的数据。注意,`data`必须是字节类型(bytes),因此如果输入的是字符串,则需先将其编码为字节串。 ```python data = "example_password".encode('utf-8') # 将字符串转换为字节类型 md5_hash = hashlib.md5() md5_hash.update(data) ``` #### 获取加密结果 可以通过`.hexdigest()`方法获取最终的十六进制表示形式的MD5值。 ```python encrypted_result = md5_hash.hexdigest() print(encrypted_result) # 输出:2346bc9edbf3f7dbe0dc9d3f8c0ddc7a ``` 完整的代码如下所示: ```python import hashlib def encrypt_md5(input_string): data = input_string.encode('utf-8') md5_hash = hashlib.md5() md5_hash.update(data) encrypted_result = md5_hash.hexdigest() return encrypted_result # 测试函数 password = "example_password" result = encrypt_md5(password) print(f"The MD5 hash of '{password}' is {result}") ``` 上述代码定义了一个名为`encrypt_md5`的函数,用于接收任意字符串作为参数,并返回该字符串对应的MD5散列值。 --- 关于加盐处理,可以在原始密码基础上附加一段随机字符后再进行MD5加密,从而增加安全性[^2]^。例如: ```python import hashlib import os def salt_encrypt_md5(input_string, salt=os.urandom(16).hex()): combined_data = (input_string + salt).encode('utf-8') md5_hash = hashlib.md5() md5_hash.update(combined_data) encrypted_result = md5_hash.hexdigest() return encrypted_result, salt # 测试带盐加密 password = "example_password" hashed_value, used_salt = salt_encrypt_md5(password) print(f"Salted Hash: {hashed_value}, Salt Used: {used_salt}") ``` 此脚本不仅完成了基本的MD5加密,还引入了动态生成的盐值以增强保护力度。 --- ### 注意事项 尽管MD5是一种广泛应用的摘要算法,但由于其存在碰撞风险,现已不推荐单独依赖它来进行敏感信息安全保障工作[^4]。对于现代应用而言,建议采用更安全的替代方案如SHA-256或其他强健型哈希技术。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值