一、pom文件引用
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.58</version>
</dependency>
二、SM3 实现工具类
package com.prison.common.util;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import java.security.MessageDigest;
import java.security.Security;
/**
* @author WangJing
* @Description SM3实现工具类
* @date 2021/11/24 16:10
*/
public class Sm3Util {
static {
Security.addProvider(new BouncyCastleProvider());
}
public static byte[] sm3(byte[] srcData) {
SM3Digest sm3Digest = new SM3Digest();
sm3Digest.update(srcData, 0, srcData.length);
byte[] hash = new byte[sm3Digest.getDigestSize()];
sm3Digest.doFinal(hash, 0);
return hash;
}
public static String sm3Hex(byte[] srcData) {
byte[] hash = sm3(srcData);
String hexString = Hex.toHexString(hash);
return hexString;
}
public static byte[] hmacSm3(byte[] key, byte[] srcData) {
KeyParameter keyParameter = new KeyParameter(key);
SM3Digest digest = new SM3Digest();
HMac mac = new HMac(digest);
mac.init(keyParameter);
mac.update(srcData, 0, srcData.length);
byte[] hash = new byte[mac.getMacSize()];
mac.doFinal(hash, 0);
return hash;
}
public static String hmacSm3Hex(byte[] key, byte[] srcData) {
byte[] hash = hmacSm3(key, srcData);
String hexString = Hex.toHexString(hash);
return hexString;
}
public static byte[] sm3bc(byte[] srcData) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance("SM3", "BC");
byte[] digest = messageDigest.digest(srcData);
return digest;
}
public static String sm3bcHex(byte[] srcData) throws Exception {
byte[] hash = sm3bc(srcData);
String hexString = Hex.toHexString(hash);
return hexString;
}
}
三、Sm3Util 的测试类
package com.prison.common.util;
import org.junit.Assert;
import org.junit.Test;
/**
* @author WangJing
* @Description Sm3Util 的测试类
* @date 2021/11/24 16:10
*/
public class Sm3UtilTest {
final String testStr = "wangjing";
final String key = "ABCD";
@Test
public void sm3() throws Exception {
String sm3HexValue = Sm3Util.sm3Hex(testStr.getBytes());
System.out.println(sm3HexValue);
String sm3bcHexValue = Sm3Util.sm3bcHex(testStr.getBytes());
System.out.println(sm3bcHexValue);
Assert.assertEquals(sm3HexValue, sm3bcHexValue);
System.out.println();
String hmacSm3HexValue = Sm3Util.hmacSm3Hex(key.getBytes(), testStr.getBytes());
System.out.println(hmacSm3HexValue);
}
}
四、执行效果
0a2de7dc3cddac1adad62d4907bc2dcfea737c51885a8d9664aeaaefdc35fbd5
0a2de7dc3cddac1adad62d4907bc2dcfea737c51885a8d9664aeaaefdc35fbd5
102a2688951939d098bae310d75b909f27bc517abd152d118fb40a4a3a355688
注:以上内容仅提供参考和交流,请勿用于商业用途,如有侵权联系本人删除!