通过java实现国密SM4加密解密(笔记)

需要注意的是:密文长度(字节)需要固定在16的整数倍上,秘钥亦是。

参考原博文:https://blog.csdn.net/liberty888/article/details/131835870

1. 引入

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;

2. 常量定义

	static {
        Security.addProvider(new BouncyCastleProvider());
    }
    private static final String ENCODING = "UTF-8";
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 不填充时将PKCS5Padding改为NoPadding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    // 128-32位16进制;256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;

3. 生成秘钥

	public static String generateKey() throws Exception {
        return new String(Hex.encodeHex(generateKey(DEFAULT_KEY_SIZE),false));
    }

4. 生成ECB暗号

	/**
     * 生成ECB暗号
     * @explain ECB模式(电子密码本模式:Electronic codebook)
     * @param algorithmName 算法名称
     * @param mode 模式
     * @param key 秘钥
     * @return
     * @throws Exception
     */
    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;
    }

5. 加密

1)方法

	/**
     * @explain 加密模式:ECB
     *          密文长度不固定,需要手动将其固定在16的整数倍上(字节)
     * @param hexKey 16进制密钥(忽略大小写)
     * @param paramStr 待加密字符串(16进制)
     * @return 返回16进制的加密字符串
     * @throws Exception
     */
    public static String encryptEcb(String hexKey, String paramStr) throws Exception {
    	String cipherText = "";
    	// 将秘钥和待加密字符串转为byte[]
        byte[] keyData = ByteUtil.hexStrToBytes(hexKey); 
        byte[] srcData = SM4Crypt.pad(paramStr); // 将待加密字符串补充到16的整数倍,再转为byte[],具体方法见下文
        // 加密后得到的数组
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, keyData)
        byte[] cipherArray = cipher.doFinal(srcData);
        cipherText = ByteUtil.bytesToHexString(cipherArray,0,cipherArray.length);
        System.out.println("--加密--");
        System.out.println("原数据:"+paramStr);
        System.out.println("补充后的原数据:"+ByteUtil.bytesToHexString(srcData,0,srcData.length));
        System.out.println("秘钥:"+hexKey);
        System.out.println("加密后字符串:"+cipherText);
        return cipherText;
    }

2)结果

SM4加密结果输出

6. 解密

1)方法

	/**
     * sm4解密
     * @explain 解密模式:采用ECB
     * @param hexKey 16进制密钥
     * @param cipherText 16进制的加密字符串(忽略大小写)
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String decryptEcb(String hexKey, String cipherText) throws Exception {
        // 用于接收解密后的字符串
        String decryptStr = "";
        // 将秘钥和待加密字符串转为byte[]
        byte[] keyData = ByteUtil.hexStrToBytes(hexKey);
        byte[] cipherData = SM4Crypt.pad(cipherText);
        // 解密
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, keyData)
        byte[] srcData = cipher.doFinal(cipherData);
        decryptStr = ByteUtil.bytesToHexString(srcData,0,srcData.length);
        System.out.println("--解密--");
        System.out.println("原数据:"+cipherText);
        System.out.println("补充后的原数据:"+ByteUtil.bytesToHexString(cipherData,0,cipherData.length));
        System.out.println("秘钥:"+hexKey);
        System.out.println("解密后字符串:"+decryptStr);
        return decryptStr;
    }

2)结果

SM4解密结果

一些用到的工具类

ByteUtil.hexStrToBytes()
ByteUtil工具类自己创建,其hexStrToBytes方法如下:

	// 将16进制字符串转为byte[]
	public static byte[] hexStrToBytes(String hexStr) {
        String t = hexStr;
        if (t.length() % 2 == 1) {
            t = "0" + hexStr;
        }
        byte[] bytes = new byte[t.length() / 2];
        for (int i = 0; i < t.length(); i += 2) {
            bytes[i / 2] = (byte) Integer.parseInt(t.substring(i, i + 2), 16);
        }
        return bytes;
    }

ByteUtil.bytesToHexString()
将byte[]转为16进制字符串,bytesToHexString()方法如下:
(start:byte[]中开始字节,end:byte[]中结束字节,所包含区间为左闭右开)

	public static String bytesToHexString(byte[] src, int start, int end) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = start; i < end; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString().toUpperCase();
    }

pad()
我这里的处理是:不满16字节,后补0x00

	public static byte[] pad(String arg_text) {
        byte[] encrypt = ByteUtil.hexStrToBytes(arg_text);
        int len = encrypt.length % 16;
        if (len != 0) {
            len = 16 - (encrypt.length % 16);
            for (int i = 0;i<len;i++){
                arg_text = arg_text+"00";
            }
        }
        return ByteUtil.hexStrToBytes(arg_text);
    }
阅读全文
AI总结
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐