SM4加解密算法工具类JAVA实现(基于hutool-all以及bcprov-jdk15to18实现) 支持MODE以及自定义Key以及iv的设定

Maven追加相应依赖

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.8</version>
        </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15to18</artifactId>
            <version>1.66</version>
        </dependency>

直接上代码实现

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.symmetric.SM4;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

import static cn.hutool.crypto.Mode.CBC;
import static cn.hutool.crypto.Padding.ZeroPadding;

public class Sm4EncryptUtil {

    public static String encrypt(String plainTxt){
        String cipherTxt = "";
        SymmetricCrypto sm4 = new SM4(CBC, ZeroPadding, "abc1111111111333".getBytes(CharsetUtil.CHARSET_UTF_8), "iviviviviviviviv".getBytes(CharsetUtil.CHARSET_UTF_8));
        byte[] encrypHex = sm4.encrypt(plainTxt);
        cipherTxt = Base64.encode(encrypHex);
        return "{SM4}" + cipherTxt;
    }

    public static String decrypt(String cipherTxt){
        if(!cipherTxt.startsWith("{SM4}")){
            return cipherTxt;
        }
        cipherTxt = cipherTxt.substring(5);
        String plainTxt = "";
        SymmetricCrypto sm4 = new SM4(CBC, ZeroPadding, "abc1111111111333".getBytes(CharsetUtil.CHARSET_UTF_8), "iviviviviviviviv".getBytes(CharsetUtil.CHARSET_UTF_8));
        byte[] cipherHex = Base64.decode(cipherTxt);
        plainTxt = sm4.decryptStr(cipherHex, CharsetUtil.CHARSET_UTF_8);
        return plainTxt;
    }

    public static void main(String[] argc){
        String originTxt = "测试";
        System.out.println("原文: " + originTxt);
        String cipherTxt = encrypt(originTxt);
        System.out.println("密文: " + cipherTxt);
        String plainTxt = decrypt(cipherTxt);
        System.out.println("解密结果: " + plainTxt);
    }
}


版权声明:本文为ljzgood原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。