rain
2024-05-30 c00662a72ca1582c064a2bd76aa92fd22fbfedc6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.dji.sample.territory.utils;
 
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;
 
import java.nio.charset.StandardCharsets;
 
/**
 * @PROJECT_NAME: drone
 * @DESCRIPTION: sm3加密算法工具类
 * @USER: aix
 * @DATE: 2024/5/9 9:28
 */
public class Sm3Util {
 
    /**
     * 计算SM3哈希值
     *
     * @param input 输入的字符串
     * @return SM3哈希值的十六进制字符串表示
     */
    public static String calculateSM3Hash(String input) {
        // 转换为字节数组
        byte[] inputBytes = input.getBytes(StandardCharsets.UTF_8);
 
        // 初始化SM3摘要
        SM3Digest digest = new SM3Digest();
 
        // 更新摘要
        digest.update(inputBytes, 0, inputBytes.length);
 
        // 完成摘要计算并获取结果
        byte[] hash = new byte[digest.getDigestSize()];
        digest.doFinal(hash, 0);
 
        // 将字节数组转换为十六进制大写字符串
        return Hex.toHexString(hash).toUpperCase();
    }
 
    /**
     * 验证给定的哈希值是否与原始数据的SM3哈希值匹配
     *
     * @param str 原始数据
     * @param sm3HexString 预期的哈希值(十六进制字符串)
     * @return 如果匹配则返回true,否则返回false
     */
    public static boolean verify(String str, String sm3HexString) {
 
        String calculatedHash = calculateSM3Hash(str);
        return sm3HexString.equalsIgnoreCase(calculatedHash);
    }
 
//    public static void main(String[] args) {
//        System.out.println(calculateSM3Hash("123"));
//        System.out.println(verify("1234", calculateSM3Hash("123")));
//    }
 
}