摘要加密实现

142 阅读1分钟

前言

不可逆加密算法加密出来的数据不能被还原,此类算法一般用来生成摘要

MD5

public class Main {
    public static void main(String[] args) throws InterruptedException {
        String md5Hex = DigestUtil.md5Hex("hello word");
        System.out.println(md5Hex);
    }
}

SM3

SM3算法是根据哈希函数生成摘要,不需要公私钥,验证摘要只需要比较 原数据生成的摘要和 提供的摘要是否一样就可以

public class Test {
    public static void main(String[] args) {
        String digestHex = SmUtil.sm3("hello world");
        System.out.println(digestHex);
    }
}

SHA256

import java.security.MessageDigest;

public class SHA256 {
    private static final String SHA_256_ALGORITHM = "SHA-256";

    public static String encrypt(String data) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance(SHA_256_ALGORITHM);
        byte[] digest = messageDigest.digest(data.getBytes());
        StringBuilder stringBuilder = new StringBuilder();

        for (byte b : digest) {
            stringBuilder.append(Integer.toHexString((b & 0xFF) | 0x100), 1, 3); //将byte数组转换为16进制字符串
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) throws Exception {
        String data = "Hello World";
        String encryptedData = encrypt(data);
        System.out.println("加密后的数据:" + encryptedData);
        System.out.println(encryptedData.length());
    }
}