2025.4.17

Hutool 是一个 Java 工具类库,确实支持国密 SM4 算法。以下是关于 Hutool 中 SM4 算法的使用方法:

1. 引入依赖

在项目中引入 Hutool 的依赖,推荐使用 hutool-all,它包含了 Hutool 的所有功能模块:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.36</version> <!-- 请根据实际情况选择合适的版本 -->
</dependency>

2. 使用 SM4 算法

Hutool 提供了 SmUtil 工具类来简化国密算法的使用。以下是 SM4 算法的使用示例:

生成 SM4 密钥

import cn.hutool.crypto.SmUtil;

public class SM4Example {
    public static void main(String[] args) {
        // 获取 SM4 密钥
        byte[] key = SmUtil.sm4().getSecretKey().getEncoded();
        System.out.println("SM4 密钥: " + cn.hutool.core.util.HexUtil.encodeHexStr(key));
    }
}

加密和解密

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;

public class SM4Example {
    public static void main(String[] args) {
        String content = "Hello, SM4!";
        byte[] key = SmUtil.sm4().getSecretKey().getEncoded(); // 使用随机密钥

        // 加密
        SM4 sm4 = new SM4(key);
        String encrypted = sm4.encryptHex(content);
        System.out.println("加密结果: " + encrypted);

        // 解密
        String decrypted = sm4.decryptStr(encrypted);
        System.out.println("解密结果: " + decrypted);
    }
}

3. 支持的加密模式

Hutool 的 SM4 实现支持多种加密模式,例如 CBC、ECB 等。可以通过构造函数指定加密模式和填充方式,例如:

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;

public class SM4Example {
    public static void main(String[] args) {
        String content = "Hello, SM4!";
        byte[] key = SmUtil.sm4().getSecretKey().getEncoded(); // 使用随机密钥

        // 使用 CBC 模式和 PKCS5Padding
        SM4 sm4 = new SM4(Mode.CBC, Padding.PKCS5Padding, key);

        String encrypted = sm4.encryptHex(content);
        System.out.println("加密结果: " + encrypted);

        String decrypted = sm4.decryptStr(encrypted);
        System.out.println("解密结果: " + decrypted);
    }
}

4. 其他说明

  • Hutool 的 SmUtil 是对 Bouncy Castle 的封装,因此使用起来更加简单。
  • 如果需要更复杂的加密需求(例如指定初始向量 IV),可以通过构造函数传入相关参数。

通过以上方法,你可以在项目中方便地使用 Hutool 实现 SM4 加密和解密功能。

posted @ 2025-04-17 23:00  258333  阅读(105)  评论(0)    收藏  举报