Java 實現 國密SM4/ECB/PKCS7Padding對稱加密解密

Java 實現 國密SM4/ECB/PKCS7Padding對稱加密解密,爲了演示方便本問使用的是IntelliJ IDEA 2022.1 (Community Edition)來構建代碼的

1、pom.xml文件添加需要的jar

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SM345</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <!--sm3,sm4加密算法-->
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.66</version>
        </dependency>
    </dependencies>
</project>

 

2、java代碼

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.apache.commons.codec.binary.Base64;

/**
 * sm4加密算法工具類
 *
 * @author Marydon
 * @version 1.0
 * @explain sm4加密、解密與加密結果驗證
 * 可逆算法
 * @creationTime 2018年7月6日上午11:46:59
 * @email [email protected]
 * @since
 */
public class Sm4Util {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final String ENCODING = "UTF-8";
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分組加密模式/分組填充方式
    // PKCS5Padding-以8個字節爲一組進行分組加密
    // 定義分組加密模式使用:PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING7 = "SM4/ECB/PKCS5Padding";
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS7Padding";
    // 64-16位16進制;128-32位16進制;256-64位16進制
    public static final int DEFAULT_KEY_SIZE = 128;

    /**
     * 生成ECB暗號
     *
     * @param algorithmName 算法名稱
     * @param mode          模式
     * @param key
     * @return
     * @throws Exception
     * @explain ECB模式(電子密碼本模式:Electronic codebook)
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    // 產生密鑰

    /**
     * 自動生成密鑰
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @explain
     */
    public static byte[] generateKey() throws Exception {
        return generateKey(DEFAULT_KEY_SIZE);
    }

    /**
     * @param keySize
     * @return
     * @throws Exception
     * @explain
     */
    public static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }

    /**
     * sm4加密
     *
     * @param hexKey   16進制密鑰(忽略大小寫)
     * @param paramStr 待加密字符串
     * @return 返回16進制的加密字符串
     * @throws Exception
     * @explain 加密模式:ECB
     * 密文長度不固定,會隨着被加密字符串長度的變化而變化
     */
    public static String encryptEcb(String hexKey, String paramStr) throws Exception {
        String cipherText = "";
        // 16進制字符串-->byte[]
        //byte[] keyData = ByteUtils.fromHexString(hexKey);
        byte[] keyData = hexKey.getBytes(ENCODING);
        // String-->byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 加密後的數組
        byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
        // byte[]-->hexString
        //cipherText = ByteUtils.toHexString(cipherArray);
        cipherText = Base64.encodeBase64String(cipherArray);
        return cipherText;
    }

    /**
     * 加密模式之Ecb
     *
     * @param key
     * @param data
     * @return
     * @throws Exception
     * @explain
     */
    public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * sm4解密
     *
     * @param hexKey     16進制密鑰
     * @param cipherText 16進制的加密字符串(忽略大小寫)
     * @return 解密後的字符串
     * @throws Exception
     * @explain 解密模式:採用ECB
     */
    public static String decryptEcb(String hexKey, String cipherText) throws Exception {
        // 用於接收解密後的字符串
        String decryptStr = "";
        // hexString-->byte[]
        //byte[] keyData = ByteUtils.fromHexString(hexKey);
        byte[]  keyData = hexKey.getBytes(ENCODING);
        // hexString-->byte[]
        //byte[] cipherData = ByteUtils.fromHexString(cipherText);
        byte[] cipherData =Base64.decodeBase64(cipherText);
        // 解密
        byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
        // byte[]-->String
        decryptStr = new String(srcData, ENCODING);
        return decryptStr;
    }

    /**
     * 解密
     *
     * @param key
     * @param cipherText
     * @return
     * @throws Exception
     * @explain
     */
    public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText) throws Exception {
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }

    /**
     * 校驗加密前後的字符串是否爲同一數據
     *
     * @param hexKey     16進制密鑰(忽略大小寫)
     * @param cipherText 16進制加密後的字符串
     * @param paramStr   加密前的字符串
     * @return 是否爲同一數據
     * @throws Exception
     * @explain
     */
    public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception {
        // 用於接收校驗結果
        boolean flag = false;
        // hexString-->byte[]
        //byte[] keyData = ByteUtils.fromHexString(hexKey);
        byte[] keyData = hexKey.getBytes(ENCODING);
        // 將16進制字符串轉換成數組
        //byte[] cipherData = ByteUtils.fromHexString(cipherText);
        byte[] cipherData = Base64.decodeBase64(cipherText);
        // 解密
        byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
        // 將原字符串轉換成byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 判斷2個數組是否一致
        flag = Arrays.equals(decryptData, srcData);
        return flag;
    }
}

3、本文用到了一個Base64的jar加包commons-codec-1.16.0.jar,import org.apache.commons.codec.binary.Base64;需要下載添加引用即可

選擇 文件  項目結構 項目設置  庫  點擊最右邊的+ 選擇 下載的commons-codec-1.16.0.jar加包即可。

 

4、使用代碼

import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
//import org.apache.commons.codec.binary.Hex;
//import org.apache.commons.codec.binary.Base64;

public class Longteng {

    public static void main(String[] args) {
        try {

            String json = "{\"name\":\"Marydon\",\"website\":\"http://www.cnblogs.com/Marydon20170307\"}";
            json = "1234567890abcdefghijklmnopqrstuvwxyz";
            System.out.println("國密SM4加密解密:");
            // 自定義的32位16進制密鑰
            // String key = "86C63180C2806ED1F47B859DE501215B";
            String key = "1234567890123456";
            String cipher = Sm4Util.encryptEcb(key, json);
            System.out.println("國密SM4加密解密:\r\n密鑰:" + key + " \n加密內容:" + json + " \n加密後v" + cipher);

            //System.out.println(cipher);//比對加密解密信息
            System.out.println(Sm4Util.verifyEcb(key, cipher, json));// true
            json = Sm4Util.decryptEcb(key, cipher);
            System.out.println("國密SM4加密解密:\n密鑰:" + key + " \n加密內容:" + cipher + " \n解密後:" + json);

            //System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章