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")));
|
// }
|
|
}
|