Java國密相關算法(bouncycastle)


公用類算法:

PCIKeyPair.java

/**
 * @Author: dzy
 * @Date: 2018/9/27 14:18
 * @Describe: 公私鑰對
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PCIKeyPair {

    private String priKey;      //私鑰
    private String pubKey;      //公鑰

}

CommonUtils.java

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @ClassName: CommonUtils
 * @Description: 通用工具類
 * @since: 0.0.1
 * @author: dzy
 * @date: 2017年2月22日 上午11:46:44
 */
public class CommonUtils {


    /**
     * @param date    日期
     * @param pattern 模式 如:yyyyMMdd等
     * @return
     * @Title: formatDate
     * @Description: 格式化日期
     * @since: 0.0.1
     */
    public static String formatDate(Date date, String pattern) {
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(date);
    }

    /**
     * @param strDate String類型日期
     * @param pattern 日期顯示模式
     * @return
     * @Title: parseDate
     * @Description: 將String日期轉換為Date類型日期
     * @since: 0.0.1
     */
    public static Date parseDate(String strDate, String pattern) {
        SimpleDateFormat formatter = null;
        if (StringUtils.isBlank(strDate)) {
            return null;
        }
        formatter = new SimpleDateFormat(pattern);
        try {
            return formatter.parse(strDate);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param date   操作前的日期
     * @param field  日期的部分如:年,月,日
     * @param amount 增加或減少的值(負數表示減少)
     * @return
     * @Title: dateAdd
     * @Description: 日期的加減操作
     * @since: 0.0.1
     */
    public static Date dateAdd(Date date, int field, int amount) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(field, amount);
        return calendar.getTime();
    }

    /**
     * @param source 源字符串
     * @param offset 填充開始的位置, 0-在左邊, source.getBytes().length 在右邊, 如果有中文時需小心位置
     * @param c      用於填充的字符
     * @param length 最后字符串的字節長度
     * @return
     * @Title: fill
     * @Description: 填充字符串, 長度是按字節計算, 不是字符
     * @since: 0.0.1
     */
    public static String fill(String source, int offset, char c, int length) throws UnsupportedEncodingException {
        if (null == source) {
            source = "";
        }
        if (source.getBytes(CustomConstants.CHARSET_UTF8).length == length) {
            return source;
        }
        byte[] buf = new byte[length];
        byte[] src = source.getBytes(CustomConstants.CHARSET_UTF8);
        if (src.length > length) {
            System.arraycopy(src, src.length - length, buf, 0, length);
            return new String(buf, CustomConstants.CHARSET_UTF8);
        }
        if (offset > src.length) {
            offset = src.length;
        } else if (offset < 0) {
            offset = 0;
        }
        int n = length - src.length;

        System.arraycopy(src, 0, buf, 0, offset);
        for (int i = 0; i < n; i++) {
            buf[i + offset] = (byte) c;
        }
        System.arraycopy(src, offset, buf, offset + n, src.length - offset);
        return new String(buf, CustomConstants.CHARSET_UTF8);
    }

    /**
     * @param original 原字符串
     * @param offset   填充開始的位置, 0-在左邊, original.getBytes().length 在右邊, 如果有中文時需小心位置
     * @param length   替換的字節數
     * @param c        用於替換的字符
     * @return
     * @Title: replace
     * @Description: 替換字符串, 長度是按字節計算, 不是字符
     * @since: 0.0.1
     */
    public static String replace(String original, int offset, int length, char c) throws UnsupportedEncodingException {
        if (original == null) {
            original = "";
        }
        if (original.getBytes(CustomConstants.CHARSET_UTF8).length <= offset) {
            return original;
        }
        if (original.getBytes(CustomConstants.CHARSET_UTF8).length < offset + length) {
            length = original.getBytes(CustomConstants.CHARSET_UTF8).length - offset;
        }
        byte[] buf = new byte[original.length()];
        byte[] src = original.getBytes(CustomConstants.CHARSET_UTF8);
        System.arraycopy(src, 0, buf, 0, offset);

        for (int i = offset; i < offset + length; i++) {
            buf[i] = (byte) c;
        }
        System.arraycopy(src, offset + length, buf, offset + length, src.length - offset - length);
        return new String(buf, CustomConstants.CHARSET_UTF8);
    }

    /**
     * @param s 16進制字符串
     * @return
     * @Title: hexToByte
     * @Description: 16進制字符串轉字節數組
     * @since: 0.0.1
     */
    public static byte[] hexToByte(String s) {
        byte[] result = null;
        try {
            int i = s.length();
//            if (i % 2 == 1) {
//                throw new Exception("字符串長度不是偶數.");
//            }
            if (i % 2 != 0) {
                throw new Exception("字符串長度不是偶數.");
            }
            result = new byte[i / 2];
            for (int j = 0; j < result.length; j++) {
                result[j] = (byte) Integer.parseInt(s.substring(j * 2, j * 2 + 2), 16);
            }
        } catch (Exception e) {
            result = null;
            e.printStackTrace();
//            log.error("16進制字符串轉字節數組時出現異常:", e);
        }
        return result;
    }

    /**
     * @param bytes 字節數組
     * @return
     * @Title: byte2hexString
     * @Description: 字節數組轉換為16進制字符串    //0x33 0xD2 0x00 0x46 轉換為 "33d20046" 轉換和打印報文用
     * @since: 0.0.1
     */
    public static String byte2hexString(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buf.toString().toUpperCase();
    }

    /**
     * @param hexString 16進制字符串    如:"33d20046" 轉換為 0x33 0xD2 0x00 0x46
     * @return
     * @Title: hexString2byte
     * @Description: 16進制字符串轉字節數組
     * @since: 0.0.1
     */
    public static byte[] hexString2byte(String hexString) {
        if (null == hexString || hexString.length() % 2 != 0 || hexString.contains("null")) {
            return null;
        }
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            bytes[i / 2] = (byte) (Integer.parseInt(hexString.substring(i, i + 2), 16) & 0xff);
        }
        return bytes;
    }

    /**
     * @param i 需要轉的int類型數字
     * @return
     * @Title: byte1ToBcd2
     * @Description: int類型轉BCD碼
     * @since: 0.0.1
     */
    public static String byte1ToBcd2(int i) {
//        return (new Integer(i / 16).toString() + (new Integer(i % 16)).toString());
        return Integer.toString(i / 16) + Integer.toString(i % 16);
    }

    /**
     * @param b 字節數組
     * @return
     * @Title: byteToHex2
     * @Description: 字節數組轉換為16進制字符串        For example, byte[] {0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF} will be changed to String "0123456789ABCDEF"
     * @since: 0.0.1
     */
    public static String byteToHex2(byte[] b) {
        StringBuffer result = new StringBuffer();
        String tmp = "";

        for (int i = 0; i < b.length; i++) {
            tmp = Integer.toHexString(b[i] & 0xff);
            if (tmp.length() == 1) {
                result.append("0" + tmp);
            } else {
                result.append(tmp);
            }
        }
        return result.toString().toUpperCase();
    }

    /**
     * @param num 數字
     * @param len 字節數組長度
     * @return
     * @Title: intToHexBytes
     * @Description: int類型轉16進制字節數組
     */
    public static byte[] intToHexBytes(int num, int len) {
        byte[] bytes = null;
        String hexString = Integer.toHexString(num);
        if (len > 0) {
            int length = len * 2;
            hexString = CustomStringUtils.leftFill(hexString, '0', length);
            bytes = CommonUtils.hexString2byte(hexString);
        }
        return bytes;
    }

    /*public static String byteToHex3(byte[] b) {
        String result = "";
        String tmp = "";

        for (int n = 0; n < b.length; n++) {
            tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                result = result + "0" + tmp;
            } else {
                result = result + tmp;
            }
            if (n < b.length - 1) {
                result = result + "";
            }
        }
        return result.toUpperCase();
    }*/

    /**
     * @param str 需要轉換編碼的字符串
     * @return
     * @Title: iso2Gbk
     * @Description: 將ISO-8859-1編碼的字符串轉成GBK編碼的字符串
     * @since: 0.0.1
     */
    public static String iso2Gbk(String str) {
        if (null == str) {
            return str;
        }
        try {
            return new String(str.getBytes("ISO-8859-1"), "GBK");
        } catch (UnsupportedEncodingException e) {
//            log.error("不支持的編碼異常:", e);
            e.printStackTrace();
            return str;
        }
    }

//    /**
//     * @param message
//     * @return
//     * @Title: getSubElement
//     * @Description: 分解各子域到HashMap
//     * @since: 0.0.1
//     */
//    public static Map<String, String> getSubElement(byte[] message) {
//        Map<String, String> map = new HashMap<String, String>();
//        String key = null;
//        String value = null;
//        int len = 0;
//        int idx = 0;
//        while (idx < message.length) {
//            key = new String(message, idx, 2);
//            idx += 2;    //取了SE id 移2位
//            len = Integer.parseInt(new String(message, idx, 2));
//            idx += 2;    //取了SE id的內容長度  移2位
//            value = new String(message, idx, len);
//            map.put(key, value);
//            idx += len;
//        }
//        return map;
//    }

    //byte數組轉成long

    /**
     * @param b 將字節數組轉long類型 位置為小端
     * @return
     */
    public static long byteToLong(byte[] b) {
        long s = 0;
        long s0 = b[0] & 0xff;// 最低位
        long s1 = b[1] & 0xff;
        long s2 = b[2] & 0xff;
        long s3 = b[3] & 0xff;
        long s4 = b[4] & 0xff;// 最低位
        long s5 = b[5] & 0xff;
        long s6 = b[6] & 0xff;
        long s7 = b[7] & 0xff;

        // s0不變
        s1 <<= 8;
        s2 <<= 16;
        s3 <<= 24;
        s4 <<= 8 * 4;
        s5 <<= 8 * 5;
        s6 <<= 8 * 6;
        s7 <<= 8 * 7;
        s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;
        return s;
    }

    /**
     * @param b 將字節數組轉int類型     位置為小端
     * @return
     */
    public static int byteToInt(byte[] b) {
        int s = 0;
        int s0 = b[0] & 0xff;// 最低位
        int s1 = b[1] & 0xff;
        int s2 = b[2] & 0xff;
        int s3 = b[3] & 0xff;

        // s0不變
        s1 <<= 8;
        s2 <<= 16;
        s3 <<= 24;

        s = s0 | s1 | s2 | s3;
        return s;
    }

    /**
     * int類型轉換小端的byte數組
     * @param i
     * @return
     */
    public static byte[] intToLittleBytes(int i) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(4);
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
        byteBuffer.asIntBuffer().put(i);
        byte[] littleBytes = byteBuffer.array();
        return littleBytes;
    }

    /**
     * 將一個字節轉成10進制
     * @param b
     * @return
     */
    public static int byteToInt(byte b) {
        int value = b & 0xff;
        return value;
    }

    /**
     *  字節數組合並
     * @param bt1   字節數組bt1
     * @param bt2   字節數組bt2
     * @return
     */
    public static byte[] byteMerger(byte[] bt1, byte[] bt2){
        byte[] bt3 = new byte[bt1.length+bt2.length];
        System.arraycopy(bt1, 0, bt3, 0, bt1.length);
        System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
        return bt3;
    }

}

SM2算法:

 

package com.pcidata.common.tools.encrypt;

import com.pcidata.common.tools.CommonUtils;
import com.pcidata.common.tools.CustomStringUtils;
import com.pcidata.modules.key.modelvo.response.PCIKeyPair;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.generators.ECKeyPairGenerator;
import org.bouncycastle.crypto.params.*;
import org.bouncycastle.crypto.signers.SM2Signer;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.math.ec.ECPoint;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.Strings;
import org.bouncycastle.util.encoders.Hex;

import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

/**
 * @Author: dzy
 * @Date: 2018/9/28 15:53
 * @Describe: SM2工具類
 */
@Slf4j
public class SM2Util {

    /**
     * 生成SM2公私鑰對
     * @return
     */
    private static AsymmetricCipherKeyPair genKeyPair0() {
        //獲取一條SM2曲線參數
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");

        //構造domain參數
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
                sm2ECParameters.getG(), sm2ECParameters.getN());

        //1.創建密鑰生成器
        ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();

        //2.初始化生成器,帶上隨機數
        try {
            keyPairGenerator.init(new ECKeyGenerationParameters(domainParameters, SecureRandom.getInstance("SHA1PRNG")));
        } catch (NoSuchAlgorithmException e) {
            log.error("生成公私鑰對時出現異常:", e);
//            e.printStackTrace();
        }

        //3.生成密鑰對
        AsymmetricCipherKeyPair asymmetricCipherKeyPair = keyPairGenerator.generateKeyPair();
        return asymmetricCipherKeyPair;
    }

    /**
     * 生成公私鑰對(默認壓縮公鑰)
     * @return
     */
    public static PCIKeyPair genKeyPair() {
        return genKeyPair(true);
    }

    /**
     * 生成公私鑰對
     * @param compressedPubKey  是否壓縮公鑰
     * @return
     */
    public static PCIKeyPair genKeyPair(boolean compressedPubKey) {
        AsymmetricCipherKeyPair asymmetricCipherKeyPair = genKeyPair0();

        //提取公鑰點
        ECPoint ecPoint = ((ECPublicKeyParameters) asymmetricCipherKeyPair.getPublic()).getQ();
        //公鑰前面的02或者03表示是壓縮公鑰,04表示未壓縮公鑰,04的時候,可以去掉前面的04
        String pubKey = Hex.toHexString(ecPoint.getEncoded(compressedPubKey));

        BigInteger privatekey = ((ECPrivateKeyParameters) asymmetricCipherKeyPair.getPrivate()).getD();
        String priKey = privatekey.toString(16);

        PCIKeyPair keyPair = new PCIKeyPair(priKey, pubKey);
        return keyPair;
    }

    /**
     * 私鑰簽名
     * @param privateKey    私鑰
     * @param content       待簽名內容
     * @return
     */
    public static String sign(String privateKey, String content) {
        //待簽名內容轉為字節數組
        byte[] message = Hex.decode(content);

        //獲取一條SM2曲線參數
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        //構造domain參數
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
                sm2ECParameters.getG(), sm2ECParameters.getN());

        BigInteger privateKeyD = new BigInteger(privateKey, 16);
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);

        //創建簽名實例
        SM2Signer sm2Signer = new SM2Signer();

        //初始化簽名實例,帶上ID,國密的要求,ID默認值:1234567812345678
        try {
            sm2Signer.init(true, new ParametersWithID(new ParametersWithRandom(privateKeyParameters, SecureRandom.getInstance("SHA1PRNG")), Strings.toByteArray("1234567812345678")));
        } catch (NoSuchAlgorithmException e) {
            log.error("簽名時出現異常:", e);
        }

        //生成簽名,簽名分為兩部分r和s,分別對應索引0和1的數組
        BigInteger[] bigIntegers = sm2Signer.generateSignature(message);

        byte[] rBytes = modifyRSFixedBytes(bigIntegers[0].toByteArray());
        byte[] sBytes = modifyRSFixedBytes(bigIntegers[1].toByteArray());

        byte[] signBytes = ByteUtils.concatenate(rBytes, sBytes);
        String sign = Hex.toHexString(signBytes);

        return sign;
    }

    /**
     * 將R或者S修正為固定字節數
     * @param rs
     * @return
     */
    private static byte[] modifyRSFixedBytes(byte[] rs) {
        int length = rs.length;
        int fixedLength = 32;
        byte[] result = new byte[fixedLength];
        if (length < 32) {
            System.arraycopy(rs, 0, result, fixedLength - length, length);
        } else {
            System.arraycopy(rs, length - fixedLength, result, 0, fixedLength);
        }
        return result;
    }

    /**
     * 驗證簽名
     * @param publicKey     公鑰
     * @param content       待簽名內容
     * @param sign          簽名值
     * @return
     */
    public static boolean verify(String publicKey, String content, String sign) {
        //待簽名內容
        byte[] message = Hex.decode(content);
        byte[] signData = Hex.decode(sign);

        // 獲取一條SM2曲線參數
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        // 構造domain參數
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
                sm2ECParameters.getG(),
                sm2ECParameters.getN());
        //提取公鑰點
        ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(CommonUtils.hexString2byte(publicKey));
        // 公鑰前面的02或者03表示是壓縮公鑰,04表示未壓縮公鑰, 04的時候,可以去掉前面的04
        ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);

        //獲取簽名
        BigInteger R = null;
        BigInteger S = null;
        byte[] rBy = new byte[33];
        System.arraycopy(signData, 0, rBy, 1, 32);
        rBy[0] = 0x00;
        byte[] sBy = new byte[33];
        System.arraycopy(signData, 32, sBy, 1, 32);
        sBy[0] = 0x00;
        R = new BigInteger(rBy);
        S = new BigInteger(sBy);

        //創建簽名實例
        SM2Signer sm2Signer = new SM2Signer();
        ParametersWithID parametersWithID = new ParametersWithID(publicKeyParameters, Strings.toByteArray("1234567812345678"));
        sm2Signer.init(false, parametersWithID);

        //驗證簽名結果
        boolean verify = sm2Signer.verifySignature(message, R, S);
        return verify;
    }

    /**
     * SM2加密算法
     * @param publicKey     公鑰
     * @param data          數據
     * @return
     */
    public static String encrypt(String publicKey, String data){
        // 獲取一條SM2曲線參數
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        // 構造domain參數
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
                sm2ECParameters.getG(),
                sm2ECParameters.getN());
        //提取公鑰點
        ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(CommonUtils.hexString2byte(publicKey));
        // 公鑰前面的02或者03表示是壓縮公鑰,04表示未壓縮公鑰, 04的時候,可以去掉前面的04
        ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);

        SM2Engine sm2Engine = new SM2Engine();
        sm2Engine.init(true, new ParametersWithRandom(publicKeyParameters, new SecureRandom()));

        byte[] arrayOfBytes = null;
        try {
            byte[] in = data.getBytes("utf-8");
            arrayOfBytes = sm2Engine.processBlock(in, 0, in.length);
        } catch (Exception e) {
            log.error("SM2加密時出現異常:", e);
        }
        return Hex.toHexString(arrayOfBytes);
    }

    /**
     * SM2加密算法
     * @param publicKey     公鑰
     * @param data          明文數據
     * @return
     */
    public static String encrypt(PublicKey publicKey, String data) {

        ECPublicKeyParameters ecPublicKeyParameters = null;
        if (publicKey instanceof BCECPublicKey) {
            BCECPublicKey bcecPublicKey = (BCECPublicKey) publicKey;
            ECParameterSpec ecParameterSpec = bcecPublicKey.getParameters();
            ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParameterSpec.getCurve(),
                    ecParameterSpec.getG(), ecParameterSpec.getN());
            ecPublicKeyParameters = new ECPublicKeyParameters(bcecPublicKey.getQ(), ecDomainParameters);
        }

        SM2Engine sm2Engine = new SM2Engine();
        sm2Engine.init(true, new ParametersWithRandom(ecPublicKeyParameters, new SecureRandom()));

        byte[] arrayOfBytes = null;
        try {
            byte[] in = data.getBytes("utf-8");
            arrayOfBytes = sm2Engine.processBlock(in,0, in.length);
        } catch (Exception e) {
            log.error("SM2加密時出現異常:", e);
        }
        return Hex.toHexString(arrayOfBytes);
    }

    /**
     * SM2解密算法
     * @param privateKey    私鑰
     * @param cipherData    密文數據
     * @return
     */
    public static String decrypt(String privateKey, String cipherData) {
        byte[] cipherDataByte = Hex.decode(cipherData);

        //獲取一條SM2曲線參數
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        //構造domain參數
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
                sm2ECParameters.getG(), sm2ECParameters.getN());

        BigInteger privateKeyD = new BigInteger(privateKey, 16);
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);

        SM2Engine sm2Engine = new SM2Engine();
        sm2Engine.init(false, privateKeyParameters);

        String result = null;
        try {
            byte[] arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
            return new String(arrayOfBytes, "utf-8");
        } catch (Exception e) {
            log.error("SM2解密時出現異常:", e);
        }
        return result;

    }

    /**
     * SM2解密算法
     * @param privateKey        私鑰
     * @param cipherData        密文數據
     * @return
     */
    public static String decrypt(PrivateKey privateKey, String cipherData) {
        byte[] cipherDataByte = Hex.decode(cipherData);

        BCECPrivateKey bcecPrivateKey = (BCECPrivateKey) privateKey;
        ECParameterSpec ecParameterSpec = bcecPrivateKey.getParameters();

        ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParameterSpec.getCurve(),
                ecParameterSpec.getG(), ecParameterSpec.getN());

        ECPrivateKeyParameters ecPrivateKeyParameters = new ECPrivateKeyParameters(bcecPrivateKey.getD(),
                ecDomainParameters);

        SM2Engine sm2Engine = new SM2Engine();
        sm2Engine.init(false, ecPrivateKeyParameters);

        String result = null;
        try {
            byte[] arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
            return new String(arrayOfBytes, "utf-8");
        } catch (Exception e) {
            log.error("SM2解密時出現異常:", e);
        }
        return result;
    }

    /**
     * 將未壓縮公鑰壓縮成壓縮公鑰
     * @param pubKey    未壓縮公鑰(16進制,不要帶頭部04)
     * @return
     */
    public static String compressPubKey(String pubKey) {
        pubKey = CustomStringUtils.append("04", pubKey);    //將未壓縮公鑰加上未壓縮標識.
        // 獲取一條SM2曲線參數
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        // 構造domain參數
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
                sm2ECParameters.getG(),
                sm2ECParameters.getN());
        //提取公鑰點
        ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(CommonUtils.hexString2byte(pubKey));
        // 公鑰前面的02或者03表示是壓縮公鑰,04表示未壓縮公鑰, 04的時候,可以去掉前面的04
//        ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);

        String compressPubKey = Hex.toHexString(pukPoint.getEncoded(Boolean.TRUE));

        return compressPubKey;
    }

    /**
     * 將壓縮的公鑰解壓為非壓縮公鑰
     * @param compressKey   壓縮公鑰
     * @return
     */
    public static String unCompressPubKey(String compressKey) {
        // 獲取一條SM2曲線參數
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        // 構造domain參數
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(),
                sm2ECParameters.getG(),
                sm2ECParameters.getN());
        //提取公鑰點
        ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(CommonUtils.hexString2byte(compressKey));
        // 公鑰前面的02或者03表示是壓縮公鑰,04表示未壓縮公鑰, 04的時候,可以去掉前面的04
//        ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);

        String pubKey = Hex.toHexString(pukPoint.getEncoded(Boolean.FALSE));
        pubKey = pubKey.substring(2);       //去掉前面的04   (04的時候,可以去掉前面的04)

        return pubKey;
    }

}

 

 

SM3算法:

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;

import java.security.MessageDigest;

/**
 * @Author: dzy
 * @Date: 2018/10/19 16:36
 * @Describe: SM3工具類(雜湊算法-hash算法)
 */
@Slf4j
public class SM3Util {

    /**
     * 16進制字符串SM3生成HASH簽名值算法
     * @param hexString     16進制字符串
     * @return
     */
    public static String hexEncrypt(String hexString) {
        byte[] srcData = Hex.decode(hexString);
        byte[] encrypt = encrypt(srcData);
        String cipherStr  = Hex.toHexString(encrypt);
        return cipherStr;
    }

    /**
     * 16進制字符串SM3生成HASH簽名值算法
     * @param hexKey        16進制密鑰
     * @param hexString     16進制字符串
     * @return
     */
    public static String hexEncrypt(String hexKey, String hexString) {
        byte[] key = Hex.decode(hexKey);
        byte[] srcData = Hex.decode(hexString);
        byte[] encrypt = encrypt(key, srcData);
        String cipherStr  = Hex.toHexString(encrypt);
        return cipherStr;
    }

    /**
     * 普通文本SM3生成HASH簽名算法
     * @param plain     待簽名數據
     * @return
     */
    public static String plainEncrypt(String plain) {
        // 將返回的hash值轉換成16進制字符串
        String cipherStr = null;
        try {
            //將字符串轉換成byte數組
            byte[] srcData = plain.getBytes(CustomConstants.CHARSET_UTF8);
            //調用encrypt計算hash
            byte[] encrypt = encrypt(srcData);
            //將返回的hash值轉換成16進制字符串
            cipherStr = Hex.toHexString(encrypt);
        } catch (Exception e) {
            log.error("將字符串轉換為字節時出現異常:", e);
        }
        return cipherStr;
    }

    /**
     * 普通文本SM3生成HASH簽名算法
     * @param hexKey        密鑰
     * @param plain         待簽名數據
     * @return
     */
    public static String plainEncrypt(String hexKey, String plain) {
        // 將返回的hash值轉換成16進制字符串
        String cipherStr = null;
        try {
            //將字符串轉換成byte數組
            byte[] srcData = plain.getBytes(CustomConstants.CHARSET_UTF8);
            //密鑰
            byte[] key = Hex.decode(hexKey);
            //調用encrypt計算hash
            byte[] encrypt = encrypt(key, srcData);
            //將返回的hash值轉換成16進制字符串
            cipherStr = Hex.toHexString(encrypt);
        } catch (Exception e) {
            log.error("將字符串轉換為字節時出現異常:", e);
        }
        return cipherStr;
    }

    /**
     * SM3計算hashCode
     * @param srcData   待計算數據
     * @return
     */
    public static byte[] encrypt(byte[] srcData) {
        SM3Digest sm3Digest = new SM3Digest();
        sm3Digest.update(srcData, 0, srcData.length);
        byte[] encrypt = new byte[sm3Digest.getDigestSize()];
        sm3Digest.doFinal(encrypt, 0);
        return encrypt;
    }

    /**
     * 通過密鑰進行加密
     * @param key       密鑰byte數組
     * @param srcData   被加密的byte數組
     * @return
     */
    public static byte[] encrypt(byte[] key, byte[] srcData) {
        KeyParameter keyParameter = new KeyParameter(key);
        SM3Digest digest = new SM3Digest();
        HMac mac = new HMac(digest);
        mac.init(keyParameter);
        mac.update(srcData, 0, srcData.length);
        byte[] result = new byte[mac.getMacSize()];
        mac.doFinal(result, 0);
        return result;
    }

    /**
     * SM3計算hashCode
     * @param srcData   待計算數據
     * @return
     * @throws Exception
     */
    public static byte[] encrypt_0(byte[] srcData) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance("SM3", "BC");
        byte[] digest = messageDigest.digest(srcData);
        return digest;
    }

}

SM4算法:

import org.bouncycastle.crypto.engines.SM4Engine;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;

/**
 * @Author: dzy
 * @Date: 2018/10/9 16:41
 * @Describe: SM4算法
 */
public class SM4Util {

    //加解密的字節快大小
    public static final int BLOCK_SIZE = 16;

    /**
     * SM4ECB加密算法
     * @param in            待加密內容
     * @param keyBytes      密鑰
     * @return
     */
    public static byte[] encryptByEcb0(byte[] in, byte[] keyBytes) {
        SM4Engine sm4Engine = new SM4Engine();
        sm4Engine.init(true, new KeyParameter(keyBytes));
        int inLen = in.length;
        byte[] out = new byte[inLen];

        int times = inLen / BLOCK_SIZE;

        for (int i = 0; i < times; i++) {
            sm4Engine.processBlock(in, i * BLOCK_SIZE, out, i * BLOCK_SIZE);
        }

        return out;
    }

    /**
     * SM4ECB加密算法
     * @param in            待加密內容
     * @param keyBytes      密鑰
     * @return
     */
    public static String encryptByEcb(byte[] in, byte[] keyBytes) {
        byte[] out = encryptByEcb0(in, keyBytes);
        String cipher = Hex.toHexString(out);
        return cipher;
    }

    /**
     * SM4的ECB加密算法
     * @param content   待加密內容
     * @param key       密鑰
     * @return
     */
    public static String encryptByEcb(String content, String key) {
        byte[] in = Hex.decode(content);
        byte[] keyBytes = Hex.decode(key);

        String cipher = encryptByEcb(in, keyBytes);
        return cipher;
    }

    /**
     * SM4的ECB解密算法
     * @param in        密文內容
     * @param keyBytes  密鑰
     * @return
     */
    public static byte[] decryptByEcb0(byte[] in, byte[] keyBytes) {
        SM4Engine sm4Engine = new SM4Engine();
        sm4Engine.init(false, new KeyParameter(keyBytes));
        int inLen = in.length;
        byte[] out = new byte[inLen];

        int times = inLen / BLOCK_SIZE;

        for (int i = 0; i < times; i++) {
            sm4Engine.processBlock(in, i * BLOCK_SIZE, out, i * BLOCK_SIZE);
        }

        return out;
    }

    /**
     * SM4的ECB解密算法
     * @param in        密文內容
     * @param keyBytes  密鑰
     * @return
     */
    public static String decryptByEcb(byte[] in, byte[] keyBytes) {
        byte[] out = decryptByEcb0(in, keyBytes);
        String plain = Hex.toHexString(out);
        return plain;
    }

    /**
     * SM4的ECB解密算法
     * @param cipher    密文內容
     * @param key       密鑰
     * @return
     */
    public static String decryptByEcb(String cipher, String key) {
        byte[] in = Hex.decode(cipher);
        byte[] keyBytes = Hex.decode(key);

        String plain = decryptByEcb(in, keyBytes);
        return plain;
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM