百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

对称加密算法之Java SM4算法应用 附可用工具类

toyiye 2024-08-10 21:26 7 浏览 0 评论

??SM4算法简介


??与DES和AES密码算法实现类似,SM4是一种分组密码算法。SM4分组密码算法用于无线局域网和可信计算系统的专用分组密码算法,该算法的分组长度为128比特,密码长度为128比特。SM4算法是我国制定WAPI标准的组成部分,同时也可以用于其它环境下的数据加密保护。

??加密算法与密钥扩展算法均采用32轮非线性迭代结构,以字(32位)为单位进行加密运算,每一次迭代运算均为一轮变换函数F。SM4算法加/解密算法的结构相同,只是使用轮密钥相反,其中解密轮密钥是加密轮密钥的逆序。

??概念性的内容只介绍到这里,本文着重讲解SM4如何应用。

??Maven依赖

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.59</version>
</dependency>

??工具类实现

??SM4Util提供了针对文本内容、字节数组内容的加解密实现,SM4Util工具类可以直接复制使用,代码如下:

package com.arhorchin.securitit.enordecryption.sm;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
 * @author Securitit.
 * @note 基于国标SM4算法封装的工具类.
 */
public class SM4Util {
    /**
     * logger.
     */
    private static Logger logger = Logger.getLogger(SM4Util.class);
    // 初始化算法提供者信息.
    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    /**
     * 数据编码.
     */
    private static final String CHARSET_UTF8 = "UTF-8";
    /**
     * 秘钥空间大小.
     */
    public static final int SM4_KEY_SIZE = 128;
    /**
     * 默认秘钥空间为128,Key的长度是16.
     */
    public static final int SM4_KEY_LENGTH = 16;
    /**
     * 算法编号.
     */
    public static final String SM4_NAME = "SM4";
    /**
     * CBC模式串.
     */
    public static final String SM4_NAME_ECB = "SM4/CBC/PKCS5Padding";
    /**
     * 首次加密初始向量.
     */
    public static final byte[] SM4_KEY_IV = { 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 };
    /**
     * 生成SM4算法的KEY.
     * @return 生成的SM4秘钥.
     * @throws Exception .
     */
    protected static String generateSm4Key() throws Exception {
        return Base64.encodeBase64String(generateSm4Key(SM4_KEY_SIZE));
    }
    /**
     * 生成SM4算法的KEY.
     * @param sm4Key 指定秘钥空间大小.
     * @return 生成的SM4秘钥.
     * @throws Exception .
     */
    private static byte[] generateSm4Key(int sm4Key) throws Exception {
        KeyGenerator keyGenerator = null;
        keyGenerator = KeyGenerator.getInstance(SM4_NAME, BouncyCastleProvider.PROVIDER_NAME);
        keyGenerator.init(sm4Key, new SecureRandom());
        return keyGenerator.generateKey().getEncoded();
    }
    /**
     * 对文本内容进行加密.
     * @param plainText 待加密明文内容.
     * @param sm4Key SM4秘钥.
     * @return 加密的密文.
     */
    public static String encodeText(String plainText, String sm4Key) throws Exception {
        return encodeByCbc(plainText, sm4Key);
    }
    /**
     * 对文本密文进行解密.
     * @param cipherText 待解密密文.
     * @param sm4Key SM4秘钥.
     * @return 解密的明文.
     * @throws Exception .
     */
    public static String decodeText(String cipherText, String sm4Key) throws Exception {
        return decodeByCbc(cipherText, sm4Key);
    }
    /**
     * 对字节数组内容进行加密.
     * @param plainText 待加密明文内容.
     * @param sm4Key SM4秘钥.
     * @return 加密的密文.
     */
    public static byte[] encodeBytes(byte[] plainBytes, String sm4Key) throws Exception {
        byte[] sm4KeyBytes = null;
        byte[] cipherBytes = null;
        try {
            // 秘钥位数处理转换.
            sm4Key = sm4KeyPadding(sm4Key);
            // base64格式秘钥转换:sm4Key to byte[].
            sm4KeyBytes = Base64.decodeBase64(sm4Key);
            // 使用转换后的原文和秘钥进行加密操作.
            cipherBytes = encodeCbcPadding(plainBytes, sm4KeyBytes);
            // 对加密结果使用base64进行编码:cipherBytes to Base64格式.
        } catch (Exception ex) {
            logger.error("SM4Util.encodeByCbc.", ex);
            cipherBytes = new byte[] { 1 };
        }
        return cipherBytes;
    }
    /**
     * 对字节数组密文进行解密.
     * @param cipherText 待解密密文.
     * @param sm4Key SM4秘钥.
     * @return 解密的明文.
     */
    public static byte[] decodeBytes(byte[] cipherBytes, String sm4Key) throws Exception {
        byte[] keyBts = null;
        byte[] plainBytes = new byte[0];
        try {
            // 秘钥位数处理转换.
            sm4Key = sm4KeyPadding(sm4Key);
            // base64格式秘钥转换:sm4Key to byte[].
            keyBts = Base64.decodeBase64(sm4Key);
            // 使用转换后的密文和秘钥进行解密操作
            plainBytes = decryptCbcPadding(cipherBytes, keyBts);
        } catch (Exception ex) {
            logger.error("SM4Util.decodeByCbc.", ex);
            plainBytes = new byte[] { 0 };
        }
        return plainBytes;
    }
    /**
     * 基于CBC模式进行SM4加密.
     * @param plainText 待加密明文.
     * @param sm4Key Base64格式秘钥.
     * @return 加密后Base64格式密文.
     * @throws Exception 可能异常.
     */
    private static String encodeByCbc(String plainText, String sm4Key) throws Exception {
        String cipherText = "";
        byte[] sm4KeyBytes = null;
        byte[] plainBytes = null;
        byte[] cipherBytes = null;
        try {
            // 秘钥位数处理转换.
            sm4Key = sm4KeyPadding(sm4Key);
            // base64格式秘钥转换:sm4Key to byte[].
            sm4KeyBytes = Base64.decodeBase64(sm4Key);
            // String格式原文转换:plainText to byte[].
            plainBytes = plainText.getBytes(CHARSET_UTF8);
            // 使用转换后的原文和秘钥进行加密操作.
            cipherBytes = encodeCbcPadding(plainBytes, sm4KeyBytes);
            // 对加密结果使用base64进行编码:cipherBytes to Base64格式.
            cipherText = Base64.encodeBase64String(cipherBytes);
        } catch (Exception ex) {
            logger.error("SM4Util.encodeByCbc.", ex);
            cipherText = "";
        }
        return cipherText;
    }
    /**
     * SM4算法的CBC模式加密.
     * @param plainBytes 待加密明文.
     * @param sm4Key Base64格式秘钥.
     * @return 加密后byte[]格式密文.
     * @throws Exception 可能异常.
     */
    private static byte[] encodeCbcPadding(byte[] plainBytes, byte[] sm4Key) throws Exception {
        Cipher cipher = null;
        cipher = generateSm4EcbCipher(SM4_NAME_ECB, Cipher.ENCRYPT_MODE, sm4Key);
        return cipher.doFinal(plainBytes);
    }
    /**
     * 基于CBC模式进行SM4解密.
     * @param cipherText 待解密密文.
     * @param sm4Key Base64格式秘钥.
     * @return 解密后原文.
     * @throws Exception 可能异常.
     */
    private static String decodeByCbc(String cipherText, String sm4Key) throws Exception {
        String plainText = "";
        byte[] keyBts = null;
        byte[] cipherBts = null;
        byte[] plainBytes = new byte[0];
        try {
            // 秘钥位数处理转换.
            sm4Key = sm4KeyPadding(sm4Key);
            // base64格式秘钥转换:sm4Key to byte[].
            keyBts = Base64.decodeBase64(sm4Key);
            // base64格式密文转换:cipherText to byte[].
            cipherBts = Base64.decodeBase64(cipherText);
            // 使用转换后的密文和秘钥进行解密操作
            plainBytes = decryptCbcPadding(cipherBts, keyBts);
            // 将解密结果转换为字符串:srcData to String.
            plainText = new String(plainBytes, CHARSET_UTF8);
        } catch (Exception ex) {
            logger.error("SM4Util.decodeByCbc.", ex);
            plainText = "";
        }
        return plainText;
    }
    /**
     * SM4算法的CBC模式解密.
     * @param plainBytes 待加密密文.
     * @param sm4Key Base64格式秘钥.
     * @return 解密后byte[]格式密文.
     * @throws Exception 可能异常.
     */
    private static byte[] decryptCbcPadding(byte[] cipherBytes, byte[] sm4Key) throws Exception {
        Cipher cipher = null;
        cipher = generateSm4EcbCipher(SM4_NAME_ECB, Cipher.DECRYPT_MODE, sm4Key);
        return cipher.doFinal(cipherBytes);
    }
    /**
     * 针对错误的秘钥进行补齐或除余操作.
     * @param sm4Key Base64格式秘钥.
     * @return 补齐或除余后的结果.
     */
    private static String sm4KeyPadding(String sm4Key) {
        String targetSm4Key = null;
        byte[] sm4KeyBytes = null;
        byte[] targetSm4KeyBts = null;
        try {
            if (null == sm4Key) {
                targetSm4Key = "";
                return targetSm4Key;
            }
            sm4KeyBytes = Base64.decodeBase64(sm4Key);
            // 若Key超长,则除去多余的内容.
            if (sm4KeyBytes.length > SM4_KEY_LENGTH) {
                targetSm4KeyBts = new byte[SM4_KEY_LENGTH];
                System.arraycopy(sm4KeyBytes, 0, targetSm4KeyBts, 0, SM4_KEY_LENGTH);
            }
            // 若Key较短,则补齐多余的内容.
            else if (sm4KeyBytes.length < SM4_KEY_LENGTH) {
                targetSm4KeyBts = new byte[SM4_KEY_LENGTH];
                System.arraycopy(sm4KeyBytes, 0, targetSm4KeyBts, 0, sm4KeyBytes.length);
                Arrays.fill(targetSm4KeyBts, sm4KeyBytes.length, SM4_KEY_LENGTH, (byte) 1);
            } else {
                targetSm4KeyBts = sm4KeyBytes;
            }
        } catch (Exception ex) {
            logger.error("SM4Util.sm4KeyPadding.", ex);
            targetSm4KeyBts = new byte[0];
        }
        // 以Base64格式返回Key.
        return Base64.encodeBase64String(targetSm4KeyBts);
    }
    /**
     * 生成SM4算法实例.
     * @param sm4Name 算法名称.
     * @param sm4Mode 加密模式.
     * @param sm4Key 秘钥内容.
     * @return SM4算法实例.
     * @throws Exception 可能异常.
     */
    private static Cipher generateSm4EcbCipher(String sm4Name, int sm4Mode, byte[] sm4Key) throws Exception {
        Cipher cipher = null;
        Key secretKey = null;
        IvParameterSpec ivParameterSpec = null;
        cipher = Cipher.getInstance(sm4Name, BouncyCastleProvider.PROVIDER_NAME);
        secretKey = new SecretKeySpec(sm4Key, SM4_NAME);
        ivParameterSpec = new IvParameterSpec(SM4_KEY_IV);
        cipher.init(sm4Mode, secretKey, ivParameterSpec);
        return cipher;
    }
}

??工具类测试

??在Maven依赖引入正确的情况下,复制上面的代码到项目中,修改package,可以直接使用,下面我们对工具类进行简单测试。测试类代码如下:

package com.arhorchin.securitit.enordecryption.sm;
import java.util.Arrays;
/**
 * @author Securitit.
 * @note SM4Util测试类.
 */
public class SM4UtilTester {
    public static void main(String[] args) throws Exception {
        String sm4Key = null;
        String plainText = "This is 一段明文内容!";
        String cipherText = null;
        System.out.println("----------------------- 获取SM4秘钥 -------------------------");
        sm4Key = SM4Util.generateSm4Key();
        System.out.println("秘钥:" + sm4Key);
        System.out.println();
        System.out.println("----------------------- 文本加解密测试 -------------------------");
        // 文本加解密测试.
        System.out.println("明文:" + plainText);
        cipherText = SM4Util.encodeText(plainText, sm4Key);
        System.out.println("密文:" + cipherText);
        plainText = SM4Util.decodeText(cipherText, sm4Key);
        System.out.println("解密明文:" + plainText);
        System.out.println();
        System.out.println("----------------------- 字节数组加解密测试 -------------------------");
        // 字节数组加解密测试.
        byte[] plainBytes = plainText.getBytes("UTF-8");
        byte[] cipherBytes = null;
        System.out.println("明文:" + Arrays.toString(plainBytes));
        cipherBytes = SM4Util.encodeBytes(plainBytes, sm4Key);
        System.out.println("密文:" + Arrays.toString(cipherBytes));
        plainBytes = SM4Util.decodeBytes(cipherBytes, sm4Key);
        System.out.println("解密明文:" + Arrays.toString(plainBytes));
        System.out.println();
    }
}

??控制台输出

??查看Console中的控制台内容,明文和解密后明文对比,可以确认SM4Util可以正常工作,控制台如下图:

----------------------- 获取SM4秘钥 -------------------------
秘钥:wgH7Ao/ksrtUevtvX/JqZA==
----------------------- 文本加解密测试 -------------------------
明文:This is 一段明文内容!
密文:rPF+fQ8hhF0aCqExD7we/gQPEhTnGwqpaYBl9yS0D7k=
解密明文:This is 一段明文内容!
----------------------- 字节数组加解密测试 -------------------------
明文:[84, 104, 105, 115, 32, 105, 115, 32, -28, -72, -128, -26, -82, -75, -26, -104, -114, -26, -106, -121, -27, -122, -123, -27, -82, -71, -17, -68, -127]
密文:[-84, -15, 126, 125, 15, 33, -124, 93, 26, 10, -95, 49, 15, -68, 30, -2, 4, 15, 18, 20, -25, 27, 10, -87, 105, -128, 101, -9, 36, -76, 15, -71]
解密明文:[84, 104, 105, 115, 32, 105, 115, 32, -28, -72, -128, -26, -82, -75, -26, -104, -114, -26, -106, -121, -27, -122, -123, -27, -82, -71, -17, -68, -127]

??总结

??SM4是国家标准算法,一般在应用时可能常用DES、3DES、AES等加密算法,但在某些特定场景下,如要求使用国标密码算法,则可以考虑使用SM4或其他国标密码算法。

??若文中存在错误和不足,欢迎指正!

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码