SM2国密算法使用Hutool工具类实现加解密

2020-11-23  本文已影响0人  李小二的倔强

天为罗盖地为毯,日月星辰伴我眠;何人撒下名利网,富贵贫困不一般;
也有骑马与坐轿,也有推车把担担;骑马坐轿修来的福,推车担担命该然;
骏马驮着痴呆汉,美妇常伴拙夫眠;八十老翁门站,三岁顽童染黄泉;
不是老天不睁眼,善恶到头报应循环。

导入hutool工具类jar包,因为使用很模块所以导入hutool-all包

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.2</version>
        </dependency>

hutool 官方案例 1、使用随机生成的密钥对加密或解密 2、使用自定义密钥对加密或解密

    @Test
    void testContextLoads() {
        //使用随机生成的密钥对加密或解密
//        SM2 sm2 = SmUtil.sm2();
//        // 公钥加密,私钥解密
//        String encryptStr = sm2.encryptBcd(text, KeyType.PublicKey);
//        System.out.println(encryptStr);
//        String decryptStr = StrUtil.utf8Str(sm2.decryptFromBcd(encryptStr, KeyType.PrivateKey));
//
//        System.out.println(decryptStr);



        String data = "certification is Certification(id=5fb5e11958371b3e7362d7fc, portEntry=470605, entryDate=2020-10-10, orderNo=22011191052041380(9622), province=广东省, weight=80.0, consignee=深圳市龙华区永嘉鑫冻品批发行, consigner=深圳市龙岗区新锦华冻品批发行, batchInfoList=[BatchInfo(id=null, batchNo=20200817, countryOfOrigin=303, productName=无, customName=猪小排, specification=10公斤/件, productType=LIS, weight=40.0)], updateTime=Thu Nov 19 11:06:01 CST 2020)";

        //使用自定义密钥对加密或解密
        KeyPair pair = SecureUtil.generateKeyPair("SM2");
        byte[] privateKey = pair.getPrivate().getEncoded();
        byte[] publicKey = pair.getPublic().getEncoded();

        SM2 sm2 = SmUtil.sm2(privateKey, publicKey);
        // 公钥加密,私钥解密
        String encryptStr = sm2.encryptBcd(data, KeyType.PublicKey);
        System.out.println(encryptStr);
        String decryptStr = StrUtil.utf8Str(sm2.decryptFromBcd(encryptStr, KeyType.PrivateKey));
        System.out.println(decryptStr);

    }

生产公私钥文件并进行测试

    @Test
    void newTests() {

        String data = "certification is Certification(id=5fb5e11958371b3e7362d7fc, portEntry=470605, entryDate=2020-10-10, orderNo=22011191052041380(9622), province=广东省, weight=80.0, consignee=深圳市龙华区永嘉鑫冻品批发行, consigner=深圳市龙岗区新锦华冻品批发行, batchInfoList=[BatchInfo(id=null, batchNo=20200817, countryOfOrigin=303, productName=无, customName=猪小排, specification=10公斤/件, productType=LIS, weight=40.0)], updateTime=Thu Nov 19 11:06:01 CST 2020)";

        //获取公私钥对
        KeyPair pair = SecureUtil.generateKeyPair("SM2");

        //获取单个公私钥
        PublicKey aPublic = pair.getPublic();
        PrivateKey aPrivate = pair.getPrivate();
//        String publicKeyStr = Base64.encode(aPublic.getEncoded());
//        String privateKeyStr = Base64.encode(aPrivate.getEncoded());
//        System.out.println(publicKeyStr);
//        System.out.println(privateKeyStr);

//         String publicKeyStr  = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE05TmmaKh0mIJfjtaQRRD6q0R7TbXF01bfSpIzT1zMnCn7gQhZ4lI8Z+70u17aSdNbGlra0dYede0shcwVn3eug==";
//         String privateKeyStr = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgG++LDvBFXRJGX/bAePG53fnkewcD6Cb9lyaYT+TC+yugCgYIKoEcz1UBgi2hRANCAATTlOaZoqHSYgl+O1pBFEPqrRHtNtcXTVt9KkjNPXMycKfuBCFniUjxn7vS7XtpJ01saWtrR1h517SyFzBWfd66";



//        /**
//         * 储存的私钥格式
//         * EC Private Key [a0:25:f2:09:ca:de:00:9e:26:48:bc:b4:0f:96:0f:d4:c1:19:ea:c7]
//         *             X: d394e699a2a1d262097e3b5a411443eaad11ed36d7174d5b7d2a48cd3d733270
//         *             Y: a7ee0421678948f19fbbd2ed7b69274d6c696b6b475879d7b4b21730567ddeba
//         */
//        PrivateKey aPrivate = SM2Utils.strToPrivateKey(privateKeyStr);
//
//        /**
//         * 储存的公钥格式
//         * EC Public Key [a0:25:f2:09:ca:de:00:9e:26:48:bc:b4:0f:96:0f:d4:c1:19:ea:c7]
//         *             X: d394e699a2a1d262097e3b5a411443eaad11ed36d7174d5b7d2a48cd3d733270
//         *             Y: a7ee0421678948f19fbbd2ed7b69274d6c696b6b475879d7b4b21730567ddeba
//         */
//        PublicKey aPublic = SM2Utils.strToPublicKey(publicKeyStr);
//
//
//        //将  PublicKey、PrivateKey 转成 privatekey.pem 格式
        SM2Utils.exportPublicKey(aPublic,"I:/publickey.pem");
        SM2Utils.exportPrivateKey(aPrivate,"I:/privatekey.pem");

        PublicKey aaPublic = SM2Utils.importPublicKey("I:/publickey.pem");
        PrivateKey aaPrivate = SM2Utils.importPrivateKey("I:/privatekey.pem");

        //利用公钥加密
        SM2 sm2 = SmUtil.sm2();
        sm2.setPublicKey(aaPublic);
        String encryptStr = sm2.encryptBcd(data, KeyType.PublicKey);
        System.out.println(encryptStr);

        //利用私钥解密
        SM2 sm21 = SmUtil.sm2();
        sm21.setPrivateKey(aaPrivate);
        String decryptStr = StrUtil.utf8Str(sm21.decryptFromBcd(encryptStr, KeyType.PrivateKey));
        System.out.println(decryptStr);

    }

公钥进行加密

    @Test
    void publicKeyEncrypt() {
        String data = "certification is Certification(id=5fb5e11958371b3e7362d7fc, portEntry=470605, entryDate=2020-10-10, orderNo=22011191052041380(9622), province=广东省, weight=80.0, consignee=深圳市龙华区永嘉鑫冻品批发行, consigner=深圳市龙岗区新锦华冻品批发行, batchInfoList=[BatchInfo(id=null, batchNo=20200817, countryOfOrigin=303, productName=无, customName=猪小排, specification=10公斤/件, productType=LIS, weight=40.0)], updateTime=Thu Nov 19 11:06:01 CST 2020)";

        PublicKey publicKey = SM2Utils.importPublicKey("I:/publickey.pem");
        //利用公钥加密
        SM2 sm2 = SmUtil.sm2();
        sm2.setPublicKey(publicKey);
        String encryptStr = sm2.encryptBcd(data, KeyType.PublicKey);
        System.out.println(encryptStr);

    }

私钥进行解密

    @Test
    void privateKeyEncrypt() {
        String data = "0488B44AC1DF78371203C5E9F35CD307B34194C80E18422B417E49F9A716703995578CFE9952B7808AE1629EE1B6DDD05492387E9FFF9628DDC9EB3EE3FCD18B17B9E7EFBD6C9F28921EB86488540305726F5428191338FF11E9011179B9F3B67E273BEFE760FDA4F2AD05F518413ED32C2FA9DFE2E16AE284AE34FEFD53B1401B405192A8A00C865CBFD4E000DA0423A287679372592B58688975922D7DA03F6897838E3A1D46057F538411E0CA1A6789ABA191CD6799368F59610CF81C62F6499CE01F572F1D2F6878F4B2047B98141B56BCA81EF68A3D8BBA1228BEC034F6256002CC52DFF4B01DA800CFE95EF276019BE23A0CE4536F7963A9A2467D858E37467CF3B91E432B5EF77ADCF5AAB4660B80F7E2268F002A68A60CEEAA2B16311E0DF2656A4107ECC29310CA47AD2D63D9C5569D7C3D147336741F70ADBCD046F4C02D1501EB6288A262154BF1B73C333E8563F2FA9BFCECC226464541FE59E9EDFCFF21DA2A6CD0DEDE761C5AD9F82A25092F4BB8B16AD0EB03FF1D89900B4E0BBFB414E8556794A76E078B83FE55D7D4135D04F86C14F720D0BA3AF04C97368F4332703D1E350A405171B2B9A95345E968526AB66148F0A595DD5557A8C4F1EB2789685B326FAECAD821E1822652D1DAEDB9610F0D23F900C7A21A1BFC63E675E8955A3B6C014653E409A8220FF6AD65FFEBB61949916028CBB62EFB8170E6E82D9F57E44AEBFD3268D5FCD6FC6CECEF39878B5BAD369DC7D51880BFEDF203A11AF236D0CB119DD193B5EA3F4C357DEBA54B15706363B8CE6FB60B4B198C1F2A14E7DCF0D6B1";

        PrivateKey privateKey = SM2Utils.importPrivateKey("I:/privatekey.pem");
        //利用私钥解密
        SM2 sm21 = SmUtil.sm2();
        sm21.setPrivateKey(privateKey);
        String decryptStr = StrUtil.utf8Str(sm21.decryptFromBcd(data, KeyType.PrivateKey));
        System.out.println(decryptStr);
    }

SM2Utils 工具类

package cn.pid21.tracing.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.pid21.common.Constants;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.*;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;

/**
 * SM2Utils 工具类
 *
 * 未来要将String类型转成 PrivateKey、PublicKey
 *
 * @author lishijian
 * @version tracing 1.0.0.RELEASE
 * <b>Creation Time:</b> 2020/11/19 10:30
 */
@Slf4j
public class SM2Utils {

    static final BouncyCastleProvider bc = new BouncyCastleProvider();


    /**
     * 生成 SM2 公私钥
     *
     * @return Map<String,String>
     */
    public static Map<String,Object> generateKey(){
        KeyPair pair = SecureUtil.generateKeyPair(Constants.Auth.SM2_ALGORITHM);
        Map<String,Object> map = Maps.newHashMap();
        map.put("publicKey", pair.getPublic());
        map.put("privateKey", pair.getPrivate());

        return map;
    }

    /**
     * 通过公钥解密
     * @param body
     * @param aPublic
     * @return
     */
    public static String encrypt(String body,PublicKey aPublic){

        //利用公钥加密
        SM2 sm2 = SmUtil.sm2();
        sm2.setPublicKey(aPublic);
        String encryptStr = sm2.encryptBcd(body, KeyType.PublicKey);


        return encryptStr;
    }

    /**
     * 通过私钥解密
     * @param data
     * @param aPrivate
     * @return
     */
    public static String decrypt(String data,PrivateKey aPrivate){

        SM2 sm21 = SmUtil.sm2();
        sm21.setPrivateKey(aPrivate);
        String decryptStr = StrUtil.utf8Str(sm21.decryptFromBcd(data, KeyType.PrivateKey));

        return decryptStr;
    }

    /**
     * 将数据库中读取的str私钥转为 PrivateKey
     * @param privateKeyStr
     * @return
     */
    public static PrivateKey strToPrivateKey(String privateKeyStr) {

        PrivateKey privateKey = null;
        try {
            byte[] encPriv = Base64.decode(privateKeyStr);

            KeyFactory keyFact = KeyFactory.getInstance("EC", bc);
            // 根据采用的编码结构反序列化公私钥
            privateKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(encPriv));

        } catch (Exception e) {
            e.printStackTrace();
        }

        return privateKey;
    }

    /**
     * 将数据库中读取的str公钥转为 PublicKey
     * @param publicKeyStr
     * @return
     */
    public static PublicKey strToPublicKey(String publicKeyStr) {
        PublicKey publicKey = null;
        try {
            byte[] encPub = Base64.decode(publicKeyStr);
            KeyFactory keyFact = KeyFactory.getInstance("EC", bc);
            // 根据采用的编码结构反序列化公私钥
            publicKey = keyFact.generatePublic(new X509EncodedKeySpec(encPub));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return publicKey;
    }


    /**
     * 导出.pem公钥到本地
     *
     * @param publicKey
     * @param path
     */
    public static void exportPublicKey(PublicKey publicKey, String path) {
        File file = new File(path);
        try {
            if (!file.exists())
                file.createNewFile();
            byte[] encPub = publicKey.getEncoded();
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(encPub);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出.pem私钥到本地
     *
     * @param privateKey
     * @param keyPath
     */
    public static void exportPrivateKey(PrivateKey privateKey, String keyPath) {
        File file = new File(keyPath);
        try {
            if (!file.exists())
                file.createNewFile();
            byte[] encPriv = privateKey.getEncoded();
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(encPriv);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 从本地导入.pem公钥
     *
     * @param path
     * @return
     */
    public static PublicKey importPublicKey(String path) {
        File file = new File(path);
        try {
            if (!file.exists())
                return null;
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte buffer[] = new byte[16];
            int size;
            while ((size = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, size);
            }
            fis.close();
            byte[] bytes = baos.toByteArray();
            String publicKeyStr = Base64.encode(bytes);

            return strToPublicKey(publicKeyStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从本地导入.pem私钥
     *
     * @param keyPath
     * @return
     */
    public static PrivateKey importPrivateKey(String keyPath) {
        File file = new File(keyPath);
        try {
            if (!file.exists())
                return null;
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte buffer[] = new byte[16];
            int size;
            while ((size = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, size);
            }
            fis.close();

            byte[] bytes = baos.toByteArray();
            String privateKeyStr = Base64.encode(bytes);

            return strToPrivateKey(privateKeyStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
}

上一篇下一篇

猜你喜欢

热点阅读