【国密SM4】基于Hutool的SM4秘钥生成、加密解密(20行代码搞定)

前言

在项目开发中,经常需要使用加密技术,比较常用的就有国密SM4算法。SM4是中国国家密码管理局发布的对称加密算法,目前在各个领域都得到了广泛应用。

本文将详细介绍如何使用Hutool框架实现SM4秘钥生成、加解密。

一、简介

对称加密算法:加密和解密使用相同的密钥。

分组长度与密钥长度:均为128位(16字节)。

加密模式:支持多种模式,如ECB(电子密码本)、CBC(加密分组链接)、CTR(计数器模式)、CFB(密码反馈模式)、OFB(输出反馈模式)等,以适应不同的应用场景。

轮函数结构:SM4算法采用了与AES类似的轮函数结构,但具体的S盒和线性变换与AES不同,因此具有独特的加密性能。

安全性:在同等密钥长度下,SM4的安全性与AES相当,能够满足各种安全应用场景的需求。

二、实现

2.1 引入依赖

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.18</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.70</version>
</dependency>

2.2 实现工具类

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;

import javax.crypto.SecretKey;

/**
 * SM4加解密工具类
 *
 * @author 只有影子
 * @date 2024/7/30
 */
public class Sm4Util {

    /**
     * 获取sm4秘钥
     *
     * @return sm4秘钥
     */
    public static String getSm4Key() {
        SM4 sm4 = SmUtil.sm4();
        SecretKey secretKey = sm4.getSecretKey();
        byte[] encoded = secretKey.getEncoded();
        return HexUtil.encodeHexStr(encoded);
    }

    /**
     * sm4加密
     *
     * @param content 文本
     * @param sm4Key  sm4秘钥
     * @return 加密后的结果
     */
    public static String encrypt(String content, String sm4Key) {
        SM4 sm4 = new SM4(HexUtil.decodeHex(sm4Key));
        return sm4.encryptHex(content);
    }

    /**
     * @param content
     * @param sm4Key
     * @return 解密后的结果
     */
    public static String decrypt(String content, String sm4Key) {
        SM4 sm4 = new SM4(HexUtil.decodeHex(sm4Key));
        return sm4.decryptStr(content);
    }
}

2.3 使用

// 原文本
public static void main(String[] args) {
    // 原文本
    String content = "你好 sm4";

    // 获取秘钥
    String sm4Key = Sm4Util.getSm4Key();
    System.out.println("sm4秘钥:" + sm4Key);

    // 加密
    String encrypt = Sm4Util.encrypt(content, sm4Key);
    System.out.println("加密后:" + encrypt);

    // 解密
    String decrypt = Sm4Util.decrypt(encrypt, sm4Key);
    System.out.println("解密后:" + decrypt);
}

输出结果示例:

sm4秘钥:6dbfc14984eb7dbe6d4e275429c70a73
加密后:5684c1c131d8dd3f99a3906ba4c9c94f
解密后:你好 sm4

至此一个简单的SM4秘钥生成、加解密就完成了。

参考文章

百度百科

hutool文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丶只有影子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值