js 和 java 实现 SM4 ECB 模式十六进制加密和解密

说明

  1. 加密后的内容是16进制。试着找过Base64的,但是前端加密后发现密文和正确的密文对不上,也许是不会用,能力有限,不研究了,直接用16进制的。
  2. 后端下载完jar包后,还需要做一些环境配置,否则运行时报错。

后端

依赖

		<!-- 国密 -->
		<dependency>
		    <groupId>org.bouncycastle</groupId>
		    <artifactId>bcprov-jdk15on</artifactId>
		    <version>1.70</version>
		</dependency>

环境配置

  1. 下载后的jar包放在 jre\lib\ext
    在这里插入图片描述
  2. 修改 jre\lib\security\java.security,最后一行增加 security.provider.11=org.bouncycastle.jce.provider.BouncyCastleProvider在这里插入图片描述

代码

package com.xxx.utils.sm4;

import java.math.BigInteger;  

public class ConvertUtil   
{  
    /** 
     * 整形转换成网络传输的字节流(字节数组)型数据 
     *  
     * @param num 一个整型数据 
     * @return 4个字节的自己数组 
     */  
    public static byte[] intToBytes(int num)  
    {  
        byte[] bytes = new byte[4];  
        bytes[0] = (byte) (0xff & (num >> 0));  
        bytes[1] = (byte) (0xff & (num >> 8));  
        bytes[2] = (byte) (0xff & (num >> 16));  
        bytes[3] = (byte) (0xff & (num >> 24));  
        return bytes;  
    }  
  
    /** 
     * 四个字节的字节数据转换成一个整形数据 
     *  
     * @param bytes 4个字节的字节数组 
     * @return 一个整型数据 
     */  
    public static int byteToInt(byte[] bytes)   
    {  
        int num = 0;  
        int temp;  
        temp = (0x000000ff & (bytes[0])) << 0;  
        num = num | temp;  
        temp = (0x000000ff & (bytes[1])) << 8;  
        num = num | temp;  
        temp = (0x000000ff & (bytes[2])) << 16;  
        num = num | temp;  
        temp = (0x000000ff & (bytes[3])) << 24;  
        num = num | temp;  
        return num;  
    }  
  
    /** 
     * 长整形转换成网络传输的字节流(字节数组)型数据 
     *  
     * @param num 一个长整型数据 
     * @return 4个字节的自己数组 
     */  
    public static byte[] longToBytes(long num)   
    {  
        byte[] bytes = new byte[8];  
        for (int i = 0; i < 8; i++)   
        {  
            bytes[i] = (byte) (0xff & (num >> (i * 8)));  
        }  
  
        return bytes;  
    }  
  
    /** 
     * 大数字转换字节流(字节数组)型数据 
     *  
     * @param n 
     * @return 
     */  
    public static byte[] byteConvert32Bytes(BigInteger n)   
    {  
        byte tmpd[] = (byte[])null;  
        if(n == null)  
        {  
            return null;  
        }  
          
        if(n.toByteArray().length == 33)  
        {  
            tmpd = new byte[32];  
            System.arraycopy(n.toByteArray(), 1, tmpd, 0, 32);  
        }   
        else if(n.toByteArray().length == 32)  
        {  
            tmpd = n.toByteArray();  
        }   
        else  
        {  
            tmpd = new byte[32];  
            for(int i = 0; i < 32 - n.toByteArray().length; i++)  
            {  
                tmpd[i] = 0;  
            }  
            System.arraycopy(n.toByteArray(), 0, tmpd, 32 - n.toByteArray().length, n.toByteArray().length);  
        }  
        return tmpd;  
    }  
      
    /** 
     * 换字节流(字节数组)型数据转大数字 
     *  
     * @param b 
     * @return 
     */  
    public static BigInteger byteConvertInteger(byte[] b)  
    {  
        if (b[0] < 0)  
        {  
            byte[] temp = new byte[b.length + 1];  
            temp[0] = 0;  
            System.arraycopy(b, 0, temp, 1, b.length);  
            return new BigInteger(temp);  
        }  
        return new BigInteger(b);  
    }  
      
    /** 
     * 根据字节数组获得值(十六进制数字) 
     *  
     * @param bytes 
     * @return 
     */  
    public static String getHexString(byte[] bytes)   
    {  
        return getHexString(bytes, true);  
    }  
      
    /** 
     * 根据字节数组获得值(十六进制数字) 
     *  
     * @param bytes 
     * @param upperCase 
     * @return 
     */  
    public static String getHexString(byte[] bytes, boolean upperCase)   
    {  
        String ret = "";  
        for (int i = 0; i < bytes.length; i++)   
        {  
            ret += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1);  
        }  
        return upperCase ? ret.toUpperCase() : ret;  
    }  
      
    /** 
     * 打印十六进制字符串 
     *  
     * @param bytes 
     */  
    public static void printHexString(byte[] bytes)   
    {  
        for (int i = 0; i < bytes.length; i++)   
        {  
            String hex = Integer.toHexString(bytes[i] & 0xFF);  
            if (hex.length() == 1)   
            {  
                hex = '0' + hex;  
            }  
            System.out.print("0x" + hex.toUpperCase() + ",");  
        }  
        System.out.println("");  
    }  
      
    /** 
     * Convert hex string to byte[] 
     *  
     * @param hexString 
     *            the hex string 
     * @return byte[] 
     */  
    public static byte[] hexStringToBytes(String hexString)   
    {  
        if (hexString == null || hexString.equals(""))   
        {  
            return null;  
        }  
          
        hexString = hexString.toUpperCase();  
        int length = hexString.length() / 2;  
        char[] hexChars = hexString.toCharArray();  
        byte[] d = new byte[length];  
        for (int i = 0; i < length; i++)   
        {  
            int pos = i * 2;  
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
        }  
        return d;  
    }  
      
    /** 
     * Convert char to byte 
     *  
     * @param c 
     *            char 
     * @return byte 
     */  
    public static byte charToByte(char c)   
    {  
        return (byte) "0123456789ABCDEF".indexOf(c);  
    }  
      
    /** 
     * 用于建立十六进制字符的输出的小写字符数组 
     */  
    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',  
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};  
   
    /** 
     * 用于建立十六进制字符的输出的大写字符数组 
     */  
    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',  
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};  
   
    /** 
     * 将字节数组转换为十六进制字符数组 
     * 
     * @param data byte[] 
     * @return 十六进制char[] 
     */  
    public static char[] encodeHex(byte[] data) {  
        return encodeHex(data, true);  
    }  
   
    /** 
     * 将字节数组转换为十六进制字符数组 
     * 
     * @param data        byte[] 
     * @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式 
     * @return 十六进制char[] 
     */  
    public static char[] encodeHex(byte[] data, boolean toLowerCase) {  
        return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);  
    }  
   
    /** 
     * 将字节数组转换为十六进制字符数组 
     * 
     * @param data     byte[] 
     * @param toDigits 用于控制输出的char[] 
     * @return 十六进制char[] 
     */  
    protected static char[] encodeHex(byte[] data, char[] toDigits) {  
        int l = data.length;  
        char[] out = new char[l << 1];  
        // two characters form the hex value.  
        for (int i = 0, j = 0; i < l; i++) {  
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];  
            out[j++] = toDigits[0x0F & data[i]];  
        }  
        return out;  
    }  
   
    /** 
     * 将字节数组转换为十六进制字符串 
     * 
     * @param data byte[] 
     * @return 十六进制String 
     */  
    public static String encodeHexString(byte[] data) {  
        return encodeHexString(data, true);  
    }  
   
    /** 
     * 将字节数组转换为十六进制字符串 
     * 
     * @param data        byte[] 
     * @param toLowerCase <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式 
     * @return 十六进制String 
     */  
    public static String encodeHexString(byte[] data, boolean toLowerCase) {  
        return encodeHexString(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);  
    }  
   
    /** 
     * 将字节数组转换为十六进制字符串 
     * 
     * @param data     byte[] 
     * @param toDigits 用于控制输出的char[] 
     * @return 十六进制String 
     */  
    protected static String encodeHexString(byte[] data, char[] toDigits) {  
        return new String(encodeHex(data, toDigits));  
    }  
   
    /** 
     * 将十六进制字符数组转换为字节数组 
     * 
     * @param data 十六进制char[] 
     * @return byte[] 
     * @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常 
     */  
    public static byte[] decodeHex(char[] data) {  
        int len = data.length;  
   
        if ((len & 0x01) != 0) {  
            throw new RuntimeException("Odd number of characters.");  
        }  
   
        byte[] out = new byte[len >> 1];  
   
        // two characters form the hex value.  
        for (int i = 0, j = 0; j < len; i++) {  
            int f = toDigit(data[j], j) << 4;  
            j++;  
            f = f | toDigit(data[j], j);  
            j++;  
            out[i] = (byte) (f & 0xFF);  
        }  
   
        return out;  
    }  
   
    /** 
     * 将十六进制字符转换成一个整数 
     * 
     * @param ch    十六进制char 
     * @param index 十六进制字符在字符数组中的位置 
     * @return 一个整数 
     * @throws RuntimeException 当ch不是一个合法的十六进制字符时,抛出运行时异常 
     */  
    protected static int toDigit(char ch, int index) {  
        int digit = Character.digit(ch, 16);  
        if (digit == -1) {  
            throw new RuntimeException("Illegal hexadecimal character " + ch  
                    + " at index " + index);  
        }  
        return digit;  
    }  
   
    /** 
     * 数字字符串转ASCII码字符串 
     *  
     * @param String 
     *            字符串 
     * @return ASCII字符串 
     */  
    public static String StringToAsciiString(String content) {  
        String result = "";  
        int max = content.length();  
        for (int i = 0; i < max; i++) {  
            char c = content.charAt(i);  
            String b = Integer.toHexString(c);  
            result = result + b;  
        }  
        return result;  
    }  
      
    /** 
     * 十六进制转字符串 
     *  
     * @param hexString 
     *            十六进制字符串 
     * @param encodeType 
     *            编码类型4:Unicode,2:普通编码 
     * @return 字符串 
     */  
    public static String hexStringToString(String hexString, int encodeType) {  
        String result = "";  
        int max = hexString.length() / encodeType;  
        for (int i = 0; i < max; i++) {  
            char c = (char) hexStringToAlgorism(hexString  
                    .substring(i * encodeType, (i + 1) * encodeType));  
            result += c;  
        }  
        return result;  
    }  
      
    /** 
     * 十六进制字符串装十进制 
     *  
     * @param hex 
     *            十六进制字符串 
     * @return 十进制数值 
     */  
    public static int hexStringToAlgorism(String hex) {  
        hex = hex.toUpperCase();  
        int max = hex.length();  
        int result = 0;  
        for (int i = max; i > 0; i--) {  
            char c = hex.charAt(i - 1);  
            int algorism = 0;  
            if (c >= '0' && c <= '9') {  
                algorism = c - '0';  
            } else {  
                algorism = c - 55;  
            }  
            result += Math.pow(16, max - i) * algorism;  
        }  
        return result;  
    }  
      
    /** 
     * 十六转二进制 
     *  
     * @param hex 
     *            十六进制字符串 
     * @return 二进制字符串 
     */  
    public static String hexStringToBinary(String hex) {  
        hex = hex.toUpperCase();  
        String result = "";  
        int max = hex.length();  
        for (int i = 0; i < max; i++) {  
            char c = hex.charAt(i);  
            switch (c) {  
            case '0':  
                result += "0000";  
                break;  
            case '1':  
                result += "0001";  
                break;  
            case '2':  
                result += "0010";  
                break;  
            case '3':  
                result += "0011";  
                break;  
            case '4':  
                result += "0100";  
                break;  
            case '5':  
                result += "0101";  
                break;  
            case '6':  
                result += "0110";  
                break;  
            case '7':  
                result += "0111";  
                break;  
            case '8':  
                result += "1000";  
                break;  
            case '9':  
                result += "1001";  
                break;  
            case 'A':  
                result += "1010";  
                break;  
            case 'B':  
                result += "1011";  
                break;  
            case 'C':  
                result += "1100";  
                break;  
            case 'D':  
                result += "1101";  
                break;  
            case 'E':  
                result += "1110";  
                break;  
            case 'F':  
                result += "1111";  
                break;  
            }  
        }  
        return result;  
    }  
      
    /** 
     * ASCII码字符串转数字字符串 
     *  
     * @param String 
     *            ASCII字符串 
     * @return 字符串 
     */  
    public static String AsciiStringToString(String content) {  
        String result = "";  
        int length = content.length() / 2;  
        for (int i = 0; i < length; i++) {  
            String c = content.substring(i * 2, i * 2 + 2);  
            int a = hexStringToAlgorism(c);  
            char b = (char) a;  
            String d = String.valueOf(b);  
            result += d;  
        }  
        return result;  
    }  
      
    /** 
     * 将十进制转换为指定长度的十六进制字符串 
     *  
     * @param algorism 
     *            int 十进制数字 
     * @param maxLength 
     *            int 转换后的十六进制字符串长度 
     * @return String 转换后的十六进制字符串 
     */  
    public static String algorismToHexString(int algorism, int maxLength) {  
        String result = "";  
        result = Integer.toHexString(algorism);  
  
        if (result.length() % 2 == 1) {  
            result = "0" + result;  
        }  
        return patchHexString(result.toUpperCase(), maxLength);  
    }  
      
    /** 
     * 字节数组转为普通字符串(ASCII对应的字符) 
     *  
     * @param bytearray 
     *            byte[] 
     * @return String 
     */  
    public static String byteToString(byte[] bytearray) {  
        String result = "";  
        char temp;  
  
        int length = bytearray.length;  
        for (int i = 0; i < length; i++) {  
            temp = (char) bytearray[i];  
            result += temp;  
        }  
        return result;  
    }  
      
    /** 
     * 二进制字符串转十进制 
     *  
     * @param binary 
     *            二进制字符串 
     * @return 十进制数值 
     */  
    public static int binaryToAlgorism(String binary) {  
        int max = binary.length();  
        int result = 0;  
        for (int i = max; i > 0; i--) {  
            char c = binary.charAt(i - 1);  
            int algorism = c - '0';  
            result += Math.pow(2, max - i) * algorism;  
        }  
        return result;  
    }  
  
    /** 
     * 十进制转换为十六进制字符串 
     *  
     * @param algorism 
     *            int 十进制的数字 
     * @return String 对应的十六进制字符串 
     */  
    public static String algorismToHEXString(int algorism) {  
        String result = "";  
        result = Integer.toHexString(algorism);  
  
        if (result.length() % 2 == 1) {  
            result = "0" + result;  
  
        }  
        result = result.toUpperCase();  
  
        return result;  
    }  
      
    /** 
     * HEX字符串前补0,主要用于长度位数不足。 
     *  
     * @param str 
     *            String 需要补充长度的十六进制字符串 
     * @param maxLength 
     *            int 补充后十六进制字符串的长度 
     * @return 补充结果 
     */  
    static public String patchHexString(String str, int maxLength) {  
        String temp = "";  
        for (int i = 0; i < maxLength - str.length(); i++) {  
            temp = "0" + temp;  
        }  
        str = (temp + str).substring(0, maxLength);  
        return str;  
    }  
      
    /** 
     * 将一个字符串转换为int 
     *  
     * @param s 
     *            String 要转换的字符串 
     * @param defaultInt 
     *            int 如果出现异常,默认返回的数字 
     * @param radix 
     *            int 要转换的字符串是什么进制的,如16 8 10. 
     * @return int 转换后的数字 
     */  
    public static int parseToInt(String s, int defaultInt, int radix) {  
        int i = 0;  
        try {  
            i = Integer.parseInt(s, radix);  
        } catch (NumberFormatException ex) {  
            i = defaultInt;  
        }  
        return i;  
    }  
      
    /** 
     * 将一个十进制形式的数字字符串转换为int 
     *  
     * @param s 
     *            String 要转换的字符串 
     * @param defaultInt 
     *            int 如果出现异常,默认返回的数字 
     * @return int 转换后的数字 
     */  
    public static int parseToInt(String s, int defaultInt) {  
        int i = 0;  
        try {  
            i = Integer.parseInt(s);  
        } catch (NumberFormatException ex) {  
            i = defaultInt;  
        }  
        return i;  
    }  
      
    /** 
     * 十六进制串转化为byte数组 
     *  
     * @return the array of byte 
     */  
    public static byte[] hexToByte(String hex)  
            throws IllegalArgumentException {  
        if (hex.length() % 2 != 0) {  
            throw new IllegalArgumentException();  
        }  
        char[] arr = hex.toCharArray();  
        byte[] b = new byte[hex.length() / 2];  
        for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {  
            String swap = "" + arr[i++] + arr[i];  
            int byteint = Integer.parseInt(swap, 16) & 0xFF;  
            b[j] = new Integer(byteint).byteValue();  
        }  
        return b;  
    }  
      
    /** 
     * 字节数组转换为十六进制字符串 
     *  
     * @param b 
     *            byte[] 需要转换的字节数组 
     * @return String 十六进制字符串 
     */  
    public static String byteToHex(byte b[]) {  
        if (b == null) {  
            throw new IllegalArgumentException(  
                    "Argument b ( byte array ) is null! ");  
        }  
        String hs = "";  
        String stmp = "";  
        for (int n = 0; n < b.length; n++) {  
            stmp = Integer.toHexString(b[n] & 0xff);  
            if (stmp.length() == 1) {  
                hs = hs + "0" + stmp;  
            } else {  
                hs = hs + stmp;  
            }  
        }  
        return hs.toUpperCase();  
    }
    
    /** 
     * 字节数组转换为十六进制字符串,转换为小写
     *  
     * @param b 
     *            byte[] 需要转换的字节数组 
     * @return String 十六进制字符串 
     */  
    public static String byteToHexLowerCase(byte b[]) {  
        if (b == null) {  
            throw new IllegalArgumentException(  
                    "Argument b ( byte array ) is null! ");  
        }  
        String hs = "";  
        String stmp = "";  
        for (int n = 0; n < b.length; n++) {  
            stmp = Integer.toHexString(b[n] & 0xff);  
            if (stmp.length() == 1) {  
                hs = hs + "0" + stmp;  
            } else {  
                hs = hs + stmp;  
            }  
        }  
        return hs.toLowerCase();  
    }  
      
    public static byte[] subByte(byte[] input, int startIndex, int length) {  
        byte[] bt = new byte[length];  
        for (int i = 0; i < length; i++) {  
            bt[i] = input[i + startIndex];  
        }  
        return bt;  
    }  
}


package com.xxx.utils.sm4;

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;

/**
 * 使用的时候看下pom依赖版本是多少的,之后去C:\Program Files\Java\jre1.8.0_221\lib\ext 吧那个jar包下载下来
 * 
 * 
 * 
 * sm4加密算法工具类  (新)
 * @explain sm4加密、解密与加密结果验证
 *          可逆算法
 * @author Marydon
 * @creationTime 2018年7月6日上午11:46:59
 * @version 1.0
 * @since
 * @email marydon20170307@163.com
 */
public class SM4Utils {

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

	public static final String ALGORITHM_NAME = "SM4";
	// 加密算法/分组加密模式/分组填充方式
	// PKCS5Padding-以8个字节为一组进行分组加密
	// 定义分组加密模式使用:PKCS5Padding
	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;
	// 密钥
	public static final String SECRET_KEY = "xxxxxxxxxx";

	static {
		        Security.addProvider(new BouncyCastleProvider());
		  }
	/**
	 * 生成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;
	}

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

	/**
	 * @explain
	 * @param keySize
	 * @return
	 * @throws Exception
	 */
	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加密
	 * @explain 加密模式:ECB
	 *          密文长度不固定,会随着被加密字符串长度的变化而变化
	 * @param hexKey
	 *            16进制密钥(忽略大小写)
	 * @param paramStr 待加密byte数组
	 * @return 返回加密后的byte数组
	 * @throws Exception
	 */
	public static byte[] encryptEcb(String hexKey, byte[] paramStr) throws Exception {
		// 16进制字符串--&gt;byte[]
		byte[] keyData = ByteUtils.fromHexString(hexKey);
		// String--&gt;byte[]
		byte[] srcData = paramStr;
		// 加密后的数组
		byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
		return cipherArray;
	}
	
	/**
	 * sm4加密
	 * @explain 加密模式:ECB
	 *          密文长度不固定,会随着被加密字符串长度的变化而变化
	 * @param hexKey
	 *            16进制密钥(忽略大小写)
	 * @param paramStr 待加密byte数组
	 * @return 返回加密后的16进制
	 * @throws Exception
	 */
	public static String encryptEcbToHexString(String hexKey, byte[] paramStr) throws Exception {
		return ConvertUtil.byteToHexLowerCase(encryptEcb(hexKey, paramStr));
	}
	
	/**
	 * sm4加密
	 * @explain 加密模式:ECB
	 *          密文长度不固定,会随着被加密字符串长度的变化而变化
	 * @param hexKey
	 *            16进制密钥(忽略大小写)
	 * @param paramStr 待加密byte数组
	 * @return 返回加密后的16进制
	 * @throws Exception
	 */
	public static String encryptEcbToHexString(String hexKey, String paramStr) throws Exception {
		return ConvertUtil.byteToHexLowerCase(encryptEcb(hexKey, paramStr.getBytes()));
	}
	
	/**
	 * sm4加密
	 * @explain 加密模式:ECB
	 *          密文长度不固定,会随着被加密字符串长度的变化而变化
	 * @param hexKey
	 *            16进制密钥(忽略大小写)
	 * @param paramStr 待加密byte数组
	 * @return 返回加密后的byte数组
	 * @throws Exception
	 */
	public static byte[] encryptEcb(byte[] paramStr) throws Exception {
		// 16进制字符串--&gt;byte[]
		byte[] keyData = ByteUtils.fromHexString(SECRET_KEY);
		// String--&gt;byte[]
		byte[] srcData = paramStr;
		// 加密后的数组
		byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
		return cipherArray;
	}
	
	/**
	 * sm4加密
	 * @explain 加密模式:ECB
	 *          密文长度不固定,会随着被加密字符串长度的变化而变化
	 * @param hexKey
	 *            16进制密钥(忽略大小写)
	 * @param paramStr 待加密byte数组
	 * @return 返回加密后的16进制
	 * @throws Exception
	 */
	public static String encryptEcbToHexString(byte[] paramStr) throws Exception {
		return ConvertUtil.byteToHexLowerCase(encryptEcb(paramStr));
	}
	
	/**
	 * sm4加密
	 * @explain 加密模式:ECB
	 *          密文长度不固定,会随着被加密字符串长度的变化而变化
	 * @param hexKey
	 *            16进制密钥(忽略大小写)
	 * @param paramStr 待加密byte数组
	 * @return 返回加密后的16进制
	 * @throws Exception
	 */
	public static String encryptEcbToHexString(String paramStr) throws Exception {
		return ConvertUtil.byteToHexLowerCase(encryptEcb(paramStr.getBytes()));
	}

	/**
	 * 加密模式之Ecb
	 * @explain
	 * @param key
	 * @param data
	 * @return
	 * @throws Exception
	 */
	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解密
	 * @explain 解密模式:采用ECB
	 * @param hexKey
	 *            16进制密钥
	 * @param cipherText
	 *            	byte加密数组
	 * @return 解密后的byte数组
	 * @throws Exception
	 */
	public static byte[] decryptEcb(String hexKey, byte[] cipherText) throws Exception {
		// hexString--&gt;byte[]
		byte[] keyData = ByteUtils.fromHexString(hexKey);
		// hexString--&gt;byte[]
		byte[] cipherData = cipherText;
		// 解密
		byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
		// byte[]--&gt;String
		return srcData;
	}
	
	/**
	 * sm4解密
	 * @explain 解密模式:采用ECB
	 * @param hexKey
	 *            16进制密钥
	 * @param cipherText
	 *            	byte加密数组
	 * @return 解密后的字符串
	 * @throws Exception
	 */
	public static String decryptEcbToString(String hexKey, byte[] cipherText) throws Exception {
		return new String(decryptEcb(hexKey, cipherText));
	}
	
	/**
	 * sm4解密
	 * @explain 解密模式:采用ECB
	 * @param hexKey
	 *            16进制密钥
	 * @param cipherText
	 *            	byte加密数组
	 * @return 解密后的字符串
	 * @throws Exception
	 */
	public static String decryptEcbToString(String hexKey, String cipherText) throws Exception {
		return new String(decryptEcb(hexKey, ConvertUtil.hexStringToBytes(cipherText)));
	}
	
	/**
	 * sm4解密
	 * @explain 解密模式:采用ECB
	 * @param hexKey
	 *            16进制密钥
	 * @param cipherText
	 *            	byte加密数组
	 * @return 解密后的字符串
	 * @throws Exception
	 */
	public static String decryptEcbToString(byte[] cipherText) throws Exception {
		return new String(decryptEcb(SECRET_KEY, cipherText));
	}
	
	/**
	 * sm4解密
	 * @explain 解密模式:采用ECB
	 * @param hexKey
	 *            16进制密钥
	 * @param cipherText
	 *            	byte加密数组
	 * @return 解密后的字符串
	 * @throws Exception
	 */
	public static String decryptEcbToString(String cipherText) throws Exception {
		return new String(decryptEcb(SECRET_KEY, ConvertUtil.hexStringToBytes(cipherText)));
	}
	
	/**
	 * sm4解密
	 * @explain 解密模式:采用ECB
	 * @param hexKey
	 *            16进制密钥
	 * @param cipherText
	 *            	byte加密数组
	 * @return 解密后的byte数组
	 * @throws Exception
	 */
	public static byte[] decryptEcb(byte[] cipherText) throws Exception {
		// hexString--&gt;byte[]
		byte[] keyData = ByteUtils.fromHexString(SECRET_KEY);
		// hexString--&gt;byte[]
		byte[] cipherData = cipherText;
		// 解密
		byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
		// byte[]--&gt;String
		return srcData;
	}

	/**
	 * 解密
	 * @explain
	 * @param key
	 * @param cipherText
	 * @return
	 * @throws Exception
	 */
	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);
	}

	/**
	 * 校验加密前后的字符串是否为同一数据
	 * @explain
	 * @param hexKey
	 *            16进制密钥(忽略大小写)
	 * @param cipherText
	 *            	加密后byte数组
	 * @param paramStr
	 *           	 加密前的byte数组
	 * @return 是否为同一数据
	 * @throws Exception
	 */
	public static boolean verifyEcb(String hexKey, byte[] cipherText, byte[] paramStr) throws Exception {
		// 用于接收校验结果
		boolean flag = false;
		// hexString--&gt;byte[]
		byte[] keyData = ByteUtils.fromHexString(hexKey);
		// 将16进制字符串转换成数组
		byte[] cipherData = cipherText;
		// 解密
		byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
		// 将原字符串转换成byte[]
		byte[] srcData = paramStr;
		// 判断2个数组是否一致
		flag = Arrays.equals(decryptData, srcData);
		return flag;
	}

}


测试

	@Test
	public void testSM4() throws Exception {
		try {
			String data = "心有猛虎,细嗅蔷薇!";
			byte[] keyByte = SM4Utils.generateKey();
			String key = ConvertUtil.byteToHexLowerCase(keyByte);
			System.out.println("key = " + key);
			// 加密
			String e = SM4Utils.encryptEcbToHexString(key, data);
			System.out.println("加密后:" + e);
			// 解密
			String d = SM4Utils.decryptEcbToString(key, e);
            System.out.println("解密后:" + d);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
key = 85e615189a7ed0781bd0cf390cfd0348
加密后:c7a8ee117d3eb8078e899a777e90786e7a1cdda1848c55de7bdbc3e7973d8640
解密后:心有猛虎,细嗅蔷薇!

前端

代码

/* eslint-disable no-bitwise, no-mixed-operators, complexity */
const DECRYPT = 0
const CBC = 0
const ROUND = 32
const BLOCK = 16

const Sbox = [
  0xd6, 0x90, 0xe9, 0xfe, 0xcc, 0xe1, 0x3d, 0xb7, 0x16, 0xb6, 0x14, 0xc2, 0x28, 0xfb, 0x2c, 0x05,
  0x2b, 0x67, 0x9a, 0x76, 0x2a, 0xbe, 0x04, 0xc3, 0xaa, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99,
  0x9c, 0x42, 0x50, 0xf4, 0x91, 0xef, 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43, 0xed, 0xcf, 0xac, 0x62,
  0xe4, 0xb3, 0x1c, 0xa9, 0xc9, 0x08, 0xe8, 0x95, 0x80, 0xdf, 0x94, 0xfa, 0x75, 0x8f, 0x3f, 0xa6,
  0x47, 0x07, 0xa7, 0xfc, 0xf3, 0x73, 0x17, 0xba, 0x83, 0x59, 0x3c, 0x19, 0xe6, 0x85, 0x4f, 0xa8,
  0x68, 0x6b, 0x81, 0xb2, 0x71, 0x64, 0xda, 0x8b, 0xf8, 0xeb, 0x0f, 0x4b, 0x70, 0x56, 0x9d, 0x35,
  0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, 0xd1, 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, 0x87,
  0xd4, 0x00, 0x46, 0x57, 0x9f, 0xd3, 0x27, 0x52, 0x4c, 0x36, 0x02, 0xe7, 0xa0, 0xc4, 0xc8, 0x9e,
  0xea, 0xbf, 0x8a, 0xd2, 0x40, 0xc7, 0x38, 0xb5, 0xa3, 0xf7, 0xf2, 0xce, 0xf9, 0x61, 0x15, 0xa1,
  0xe0, 0xae, 0x5d, 0xa4, 0x9b, 0x34, 0x1a, 0x55, 0xad, 0x93, 0x32, 0x30, 0xf5, 0x8c, 0xb1, 0xe3,
  0x1d, 0xf6, 0xe2, 0x2e, 0x82, 0x66, 0xca, 0x60, 0xc0, 0x29, 0x23, 0xab, 0x0d, 0x53, 0x4e, 0x6f,
  0xd5, 0xdb, 0x37, 0x45, 0xde, 0xfd, 0x8e, 0x2f, 0x03, 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b, 0x51,
  0x8d, 0x1b, 0xaf, 0x92, 0xbb, 0xdd, 0xbc, 0x7f, 0x11, 0xd9, 0x5c, 0x41, 0x1f, 0x10, 0x5a, 0xd8,
  0x0a, 0xc1, 0x31, 0x88, 0xa5, 0xcd, 0x7b, 0xbd, 0x2d, 0x74, 0xd0, 0x12, 0xb8, 0xe5, 0xb4, 0xb0,
  0x89, 0x69, 0x97, 0x4a, 0x0c, 0x96, 0x77, 0x7e, 0x65, 0xb9, 0xf1, 0x09, 0xc5, 0x6e, 0xc6, 0x84,
  0x18, 0xf0, 0x7d, 0xec, 0x3a, 0xdc, 0x4d, 0x20, 0x79, 0xee, 0x5f, 0x3e, 0xd7, 0xcb, 0x39, 0x48
]

const CK = [
  0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,
  0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
  0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,
  0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
  0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229,
  0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
  0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209,
  0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279
]

/**
 * 16 进制串转字节数组
 */
function hexToArray(str) {
  const arr = []
  for (let i = 0, len = str.length; i < len; i += 2) {
    arr.push(parseInt(str.substr(i, 2), 16))
  }
  return arr
}

/**
 * 字节数组转 16 进制串
 */
function ArrayToHex(arr) {
  return arr.map(item => {
    item = item.toString(16)
    return item.length === 1 ? '0' + item : item
  }).join('')
}

/**
 * utf8 串转字节数组
 */
function utf8ToArray(str) {
  const arr = []

  for (let i = 0, len = str.length; i < len; i++) {
    const point = str.codePointAt(i)

    if (point <= 0x007f) {
      // 单字节,标量值:00000000 00000000 0zzzzzzz
      arr.push(point)
    } else if (point <= 0x07ff) {
      // 双字节,标量值:00000000 00000yyy yyzzzzzz
      arr.push(0xc0 | (point >>> 6)) // 110yyyyy(0xc0-0xdf)
      arr.push(0x80 | (point & 0x3f)) // 10zzzzzz(0x80-0xbf)
    } else if (point <= 0xD7FF || (point >= 0xE000 && point <= 0xFFFF)) {
      // 三字节:标量值:00000000 xxxxyyyy yyzzzzzz
      arr.push(0xe0 | (point >>> 12)) // 1110xxxx(0xe0-0xef)
      arr.push(0x80 | ((point >>> 6) & 0x3f)) // 10yyyyyy(0x80-0xbf)
      arr.push(0x80 | (point & 0x3f)) // 10zzzzzz(0x80-0xbf)
    } else if (point >= 0x010000 && point <= 0x10FFFF) {
      // 四字节:标量值:000wwwxx xxxxyyyy yyzzzzzz
      i++
      arr.push((0xf0 | (point >>> 18) & 0x1c)) // 11110www(0xf0-0xf7)
      arr.push((0x80 | ((point >>> 12) & 0x3f))) // 10xxxxxx(0x80-0xbf)
      arr.push((0x80 | ((point >>> 6) & 0x3f))) // 10yyyyyy(0x80-0xbf)
      arr.push((0x80 | (point & 0x3f))) // 10zzzzzz(0x80-0xbf)
    } else {
      // 五、六字节,暂时不支持
      arr.push(point)
      throw new Error('input is not supported')
    }
  }

  return arr
}

/**
 * 字节数组转 utf8 串
 */
function arrayToUtf8(arr) {
  const str = []
  for (let i = 0, len = arr.length; i < len; i++) {
    if (arr[i] >= 0xf0 && arr[i] <= 0xf7) {
      // 四字节
      str.push(String.fromCodePoint(((arr[i] & 0x07) << 18) + ((arr[i + 1] & 0x3f) << 12) + ((arr[i + 2] & 0x3f) << 6) + (arr[i + 3] & 0x3f)))
      i += 3
    } else if (arr[i] >= 0xe0 && arr[i] <= 0xef) {
      // 三字节
      str.push(String.fromCodePoint(((arr[i] & 0x0f) << 12) + ((arr[i + 1] & 0x3f) << 6) + (arr[i + 2] & 0x3f)))
      i += 2
    } else if (arr[i] >= 0xc0 && arr[i] <= 0xdf) {
      // 双字节
      str.push(String.fromCodePoint(((arr[i] & 0x1f) << 6) + (arr[i + 1] & 0x3f)))
      i++
    } else {
      // 单字节
      str.push(String.fromCodePoint(arr[i]))
    }
  }

  return str.join('')
}

/**
 * 32 比特循环左移
 */
function rotl(x, y) {
  return x << y | x >>> (32 - y)
}

/**
 * 非线性变换
 */
function byteSub(a) {
  return (Sbox[a >>> 24 & 0xFF] & 0xFF) << 24 |
    (Sbox[a >>> 16 & 0xFF] & 0xFF) << 16 |
    (Sbox[a >>> 8 & 0xFF] & 0xFF) << 8 |
    (Sbox[a & 0xFF] & 0xFF)
}

/**
 * 线性变换,加密/解密用
 */
function l1(b) {
  return b ^ rotl(b, 2) ^ rotl(b, 10) ^ rotl(b, 18) ^ rotl(b, 24)
}

/**
 * 线性变换,生成轮密钥用
 */
function l2(b) {
  return b ^ rotl(b, 13) ^ rotl(b, 23)
}

/**
 * 以一组 128 比特进行加密/解密操作
 */
function sms4Crypt(input, output, roundKey) {
  const x = new Array(4)

  // 字节数组转成字数组(此处 1 字 = 32 比特)
  const tmp = new Array(4)
  for (let i = 0; i < 4; i++) {
    tmp[0] = input[0 + 4 * i] & 0xff
    tmp[1] = input[1 + 4 * i] & 0xff
    tmp[2] = input[2 + 4 * i] & 0xff
    tmp[3] = input[3 + 4 * i] & 0xff
    x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3]
  }

  // x[i + 4] = x[i] ^ l1(byteSub(x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ roundKey[i]))
  for (let r = 0, mid; r < 32; r += 4) {
    mid = x[1] ^ x[2] ^ x[3] ^ roundKey[r + 0]
    x[0] ^= l1(byteSub(mid)) // x[4]

    mid = x[2] ^ x[3] ^ x[0] ^ roundKey[r + 1]
    x[1] ^= l1(byteSub(mid)) // x[5]

    mid = x[3] ^ x[0] ^ x[1] ^ roundKey[r + 2]
    x[2] ^= l1(byteSub(mid)) // x[6]

    mid = x[0] ^ x[1] ^ x[2] ^ roundKey[r + 3]
    x[3] ^= l1(byteSub(mid)) // x[7]
  }

  // 反序变换
  for (let j = 0; j < 16; j += 4) {
    output[j] = x[3 - j / 4] >>> 24 & 0xff
    output[j + 1] = x[3 - j / 4] >>> 16 & 0xff
    output[j + 2] = x[3 - j / 4] >>> 8 & 0xff
    output[j + 3] = x[3 - j / 4] & 0xff
  }
}

/**
 * 密钥扩展算法
 */
function sms4KeyExt(key, roundKey, cryptFlag) {
  const x = new Array(4)

  // 字节数组转成字数组(此处 1 字 = 32 比特)
  const tmp = new Array(4)
  for (let i = 0; i < 4; i++) {
    tmp[0] = key[0 + 4 * i] & 0xff
    tmp[1] = key[1 + 4 * i] & 0xff
    tmp[2] = key[2 + 4 * i] & 0xff
    tmp[3] = key[3 + 4 * i] & 0xff
    x[i] = tmp[0] << 24 | tmp[1] << 16 | tmp[2] << 8 | tmp[3]
  }

  // 与系统参数做异或
  x[0] ^= 0xa3b1bac6
  x[1] ^= 0x56aa3350
  x[2] ^= 0x677d9197
  x[3] ^= 0xb27022dc

  // roundKey[i] = x[i + 4] = x[i] ^ l2(byteSub(x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ CK[i]))
  for (let r = 0, mid; r < 32; r += 4) {
    mid = x[1] ^ x[2] ^ x[3] ^ CK[r + 0]
    roundKey[r + 0] = x[0] ^= l2(byteSub(mid)) // x[4]

    mid = x[2] ^ x[3] ^ x[0] ^ CK[r + 1]
    roundKey[r + 1] = x[1] ^= l2(byteSub(mid)) // x[5]

    mid = x[3] ^ x[0] ^ x[1] ^ CK[r + 2]
    roundKey[r + 2] = x[2] ^= l2(byteSub(mid)) // x[6]

    mid = x[0] ^ x[1] ^ x[2] ^ CK[r + 3]
    roundKey[r + 3] = x[3] ^= l2(byteSub(mid)) // x[7]
  }

  // 解密时使用反序的轮密钥
  if (cryptFlag === DECRYPT) {
    for (let r = 0, mid; r < 16; r++) {
      mid = roundKey[r]
      roundKey[r] = roundKey[31 - r]
      roundKey[31 - r] = mid
    }
  }
}

function sm4(inArray, key, cryptFlag, {
  padding = 'pkcs#5',
  mode,
  output = 'string'
} = {}) {
  if (mode === CBC) {
    // @TODO,CBC 模式,默认走 ECB 模式
  }

  // 检查 key
  if (typeof key === 'string') key = hexToArray(key)
  if (key.length !== (128 / 8)) {
    // key 不是 128 比特
    throw new Error('key is invalid')
  }

  // 检查输入
  if (typeof inArray === 'string') {
    if (cryptFlag !== DECRYPT) {
      // 加密,输入为 utf8 串
      inArray = utf8ToArray(inArray)
    } else {
      // 解密,输入为 16 进制串
      inArray = hexToArray(inArray)
    }
  } else {
    inArray = [...inArray]
  }

  // 新增填充
  if (padding === 'pkcs#5' && cryptFlag !== DECRYPT) {
    const paddingCount = BLOCK - inArray.length % BLOCK
    for (let i = 0; i < paddingCount; i++) inArray.push(paddingCount)
  }

  // 生成轮密钥
  const roundKey = new Array(ROUND)
  sms4KeyExt(key, roundKey, cryptFlag)

  const outArray = []
  let restLen = inArray.length
  let point = 0
  while (restLen >= BLOCK) {
    const input = inArray.slice(point, point + 16)
    const output = new Array(16)
    sms4Crypt(input, output, roundKey)

    for (let i = 0; i < BLOCK; i++) {
      outArray[point + i] = output[i]
    }

    restLen -= BLOCK
    point += BLOCK
  }

  // 去除填充
  if (padding === 'pkcs#5' && cryptFlag === DECRYPT) {
    const paddingCount = outArray[outArray.length - 1]
    outArray.splice(outArray.length - paddingCount, paddingCount)
  }

  // 调整输出
  if (output !== 'array') {
    if (cryptFlag !== DECRYPT) {
      // 加密,输出转 16 进制串
      return ArrayToHex(outArray)
    } else {
      // 解密,输出转 utf8 串
      return arrayToUtf8(outArray)
    }
  } else {
    return outArray
  }
}

调用

// 第三个参数:1 表示加密 2 表示解密
sm4('内容', '与后端一致的key', 1)

在线工具测试

在线SM4加密/解密
在这里插入图片描述

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是Java使用SM4算法ECB模式加密的示例代码: ```java import org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.security.Security; import java.util.Base64; public class SM4Util { private static final String ALGORITHM_NAME = "SM4"; private static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS7Padding"; /** * SM4加密 * * @param key 16位秘钥 * @param data 待加密数据 * @return 加密结果 * @throws Exception */ public static String encryptData_ECB(String key, String data) throws Exception { Security.addProvider(new BouncyCastleProvider()); Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, "BC"); SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM_NAME); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8")); return Base64.getEncoder().encodeToString(encrypted); } /** * SM4解密 * * @param key 16位秘钥 * @param cipherText 待解密数据 * @return 解密结果 * @throws Exception */ public static String decryptData_ECB(String key, String cipherText) throws Exception { Security.addProvider(new BouncyCastleProvider()); Cipher cipher = Cipher.getInstance(ALGORITHM_NAME_ECB_PADDING, "BC"); SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM_NAME); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText)); return new String(decrypted, "UTF-8"); } } ``` 使用示例: ```java public class Test { public static void main(String[] args) throws Exception { String key = "1234567890abcdef"; String data = "hello world"; String encryptedData = SM4Util.encryptData_ECB(key, data); System.out.println("加密后的数据:" + encryptedData); String decryptedData = SM4Util.decryptData_ECB(key, encryptedData); System.out.println("解密后的数据:" + decryptedData); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值