All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.founder.mip.utils.SM4CodeAndDecodeDemo Maven / Gradle / Ivy

There is a newer version: 3.6.1.9
Show newest version
package com.founder.mip.utils;

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.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class SM4CodeAndDecodeDemo {

    private static final String ENCODING = "UTF-8";
    public static final String ALGORIGTHM_NAME = "SM4";
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS7Padding";
    public static final int DEFAULT_KEY_SIZE = 128;

    public SM4CodeAndDecodeDemo() {
    }

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

    /**
     * @Description:生成ecb暗号
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, "BC");
        Key sm4Key = new SecretKeySpec(key, ALGORIGTHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

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

    public static byte[] generateKey(int keySize) throws Exception {

        KeyGenerator kg = KeyGenerator.getInstance("SM4", "BC");
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }


    /**
     * @Description:加密
     */
    public static String encryptEcb(String hexKey, String paramStr, String charset) throws Exception {
        String cipherText = "";
        if (null != paramStr && !"".equals(paramStr)) {
            byte[] keyData = Hex.decode(hexKey);
            charset = charset.trim();
            if (charset.length() <= 0) {
                charset = ENCODING;
            }
            byte[] srcData = paramStr.getBytes(charset);
            byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
            cipherText = Hex.toHexString(cipherArray);
        }
        return cipherText;
    }

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

    /**
     * @Description:sm4解密
     */
    public static String decryptEcb(String hexKey, String cipherText, String charset) throws Exception {
        String decryptStr = "";
        byte[] keyData = Hex.decode(hexKey);
        byte[] cipherData = Hex.decode(cipherText);
        byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
        charset = charset.trim();
        if (charset.length() <= 0) {
            charset = ENCODING;
        }
        decryptStr = new String(srcData, charset);
        return decryptStr;
    }

    /**
     * @Description:解密
     */
    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);
    }

    /**
     * @Description:密码校验
     */
    public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception {
        boolean flag = false;
        byte[] keyData = Hex.decode(hexKey);
        byte[] cipherData = Hex.decode(cipherText);
        byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
        byte[] srcData = paramStr.getBytes(ENCODING);
        flag = Arrays.equals(decryptData, srcData);
        return flag;
    }

    /**
     * @Description:测试类
     */
    public static void main(String[] args) {


        try {
            //key
            String key = "cc9368581322479ebf3e79348a2757d8";
            System.out.println(key.length());

            //appid
            String appid = "cc9368581322479ebf3e79348a2757d9";
            System.out.println(appid.length());

            //用appid加密key
            String cipher1 = SM4CodeAndDecodeDemo.encryptEcb(appid, key, ENCODING);


            //加密后的秘文截取前32位作为key加密json数据
            System.out.println(cipher1.substring(0, 32) + "        " + cipher1.substring(0, 32).length());

            String json = "{\"appId\":\"cc9368581322479ebf3e79348a2757d9\",\"appUserId\":\"o8z4C5avQXqC0aWFPf1Mzu6D7WCQ_bd\",\"idNo\":\"350181199011193519\",\"idType\":\"01\",\"phoneNumber\":\"13763873033\",\"userName\":\"测试\"}";

            //加密后的秘文截取前32位作为key加密json数据
            String cipher = SM4CodeAndDecodeDemo.encryptEcb(cipher1.substring(0, 32), json, ENCODING);
            System.out.println(cipher);

            //验证是否加密正确
            System.out.println(SM4CodeAndDecodeDemo.verifyEcb(cipher1.substring(0, 32), cipher, json));

            //解密密文
            json = SM4CodeAndDecodeDemo.decryptEcb(cipher1.substring(0, 32), cipher, ENCODING);

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

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy