一:百科

HMAC运算利用hash算法,以一个消息M和一个密钥K作为输入,生成一个定长的消息摘要作为输出。支持的算法包括:MD5,sha1、sha256、SM3等。是以HMAC-MD5,HMAC-SM3的HMAC-X命名。

二:目的

由于要求,需要使用HMAC-SM3来验证消息的完整性和真实性,确保数据在传输和存储过程中不被篡改。

三:测试

SM3不在Java标准库中,需要添加jar包

四:代码

public static String hmacSm3(String data,String key){
        Digest digest=new SM3Digest();
        HMac hmac=new HMac(digest);
        hmac.init(new KeyParameter(key.getBytes()));
        hmac.update(data.getBytes(StandardCharsets.UTF_8),0,data.getBytes().length);
        byte[] hmac_sm3=new byte[hmac.getMacSize()];
        hmac.doFinal(hmac_sm3, 0);
        return Hex.toHexString(hmac_sm3);
    }

五:其他子类

Digest digest1=new MD5Digest();
Digest digest2=new SHA1Digest();

更多推荐