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

欢迎大家关注本博,同时欢迎大家评论交流,可以给个赞哦!!!

  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>

  工具类实现

  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或其他国标密码算法。

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

本博微信公众号“超哥说码”,欢迎大家订阅,公众号正在完善中,会及时将更优质的博文推送于您!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/securitit/article/details/108207357
今日推荐