使用Bouncy Castle(pom版本:bcprov-jdk15on 1.59)中SM3摘要算法
程序员文章站
2022-03-03 08:03:35
SM3 摘要算法SM3摘要算法,可以进行密钥,也可不使用密钥本次进行 常规不需要密钥的杂凑算法public class SM3Util { /** * 编码方式 UTF-8 * 加载项 */ private static final String ENCODING = "UTF-8"; static { Security.addProvider(new BouncyCastleProvider()); } pub...
SM3 摘要算法
SM3摘要算法,可以进行密钥,也可不使用密钥
本次进行 常规不需要密钥的杂凑算法
public class SM3Util {
/**
* 编码方式 UTF-8
* 加载项
*/
private static final String ENCODING = "UTF-8";
static {
Security.addProvider(new BouncyCastleProvider());
}
public static String encrypt(String paramStr){
String resultHexString = "";
try {
byte[] srcData = paramStr.getBytes(ENCODING);
byte[] resultHash = hash(srcData);
resultHexString = Base64.getEncoder().encodeToString(resultHash);
//ByteUtils.toHexString(resultHash);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return resultHexString;
}
public static byte[] hash(byte[] srcData) {
SM3Digest digest = new SM3Digest();
digest.update(srcData, 0, srcData.length);
byte[] hash = new byte[digest.getDigestSize()];
digest.doFinal(hash, 0);
return hash;
}
public static boolean verify(String srcStr, String sm3HexString) {
boolean flag = false;
try {
byte[] srcData = srcStr.getBytes(ENCODING);
byte[] sm3Hash = Base64.getDecoder().decode(sm3HexString);
//ByteUtils.fromHexString(sm3HexString);
byte[] newHash = hash(srcData);
if (Arrays.equals(newHash, sm3Hash))
flag = true;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return flag;
}
}
本文地址:https://blog.csdn.net/ProgrammerGHP/article/details/107686629
下一篇: 面试题:小球落下求路径长度