Implementing MD5 encryption algorithm in Java

In Java, you can implement the MD5 encryption algorithm by using the MessageDigest class provided by Java. Here is a simple example code:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        String password = "password123";

        // 获取MD5加密对象
        MessageDigest md = MessageDigest.getInstance("MD5");

        // 将密码转换为字节数组
        byte[] passwordBytes = password.getBytes();

        // 对字节数组进行MD5加密
        byte[] md5Bytes = md.digest(passwordBytes);

        // 将加密结果转换为十六进制字符串
        StringBuilder sb = new StringBuilder();
        for (byte b : md5Bytes) {
            sb.append(Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3));
        }

        // 打印加密后的字符串
        System.out.println("加密后的字符串:" + sb.toString());
    }
}

In the example code above, firstly the MD5 encryption object is obtained through the MessageDigest.getInstance(“MD5”) method. Then the string to be encrypted is converted to a byte array, and the md.digest method is used to encrypt the byte array with MD5, resulting in the encrypted result md5Bytes. Finally, the encrypted result is converted to a hexadecimal string and printed out.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds