DM5_Java_32位大写加密/小写加密

2022-11-30 16:05:16 浏览数 (1)

为了方便大家使用,我准备了一个不需要单独引包的MD5大写的32位加密代码,希望能为大家带来一定的价值:

代码语言:javascript复制
package test;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class common {
    public static void main(String[] args) {
    	//输出结果:96E79218965EB72C92A549DD5A330112
        System.out.println(encrypt("111111"));
    }
    /**
     * 32位大写加密
     * @param password
     * @return
     */
    private static String encrypt(String password) {
        String passwordMd5 = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(password.getBytes("utf-8"));
            passwordMd5 = toHex(bytes);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return passwordMd5;
    }

    private static String toHex(byte[] bytes) {
        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i  ) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }
}

小写的,自己看改哪里,自己改就行:

代码语言:javascript复制
package test;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class common {
    public static void main(String[] args) {
    	//输出结果:96e79218965eb72c92a549dd5a330112
        System.out.println(encrypt("111111"));
    }
    /**
     * 32位大写加密
     * @param password
     * @return
     */
    private static String encrypt(String password) {
        String passwordMd5 = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(password.getBytes("utf-8"));
            passwordMd5 = toHex(bytes);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return passwordMd5;
    }

    private static String toHex(byte[] bytes) {
    	//大小写,自己改这里就行了。
        final char[] HEX_DIGITS = "0123456789abcde".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i  ) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }
}

有用就点赞、评论、收藏加关注啊。

0 人点赞