SM国密算法

package com.abc.apollo.common.util;

import javax.crypto.IllegalBlockSizeException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SmUtil {
    private static PublicKey publicKey = null;
    private static PrivateKey privateKey = null;
    private static byte[] key = null;
    private static byte[] iv = null;

    static {
        try {
            setup();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 生成公私钥对
     * @throws Exception
     */
    public static void setup() throws Exception {
        String[] keys = KeyUtils.generateSmKey();
        publicKey = KeyUtils.createPublicKey(keys[0]);
        privateKey = KeyUtils.createPrivateKey(keys[1]);

        key = Sm4.generateKey();
        iv = AbstractSymmetric.initIv(16);
    }


    public static void main(String[] args) throws Exception {
//        System.out.println(encryptSm4String("apollo"));
//        System.out.println(encryptSm4String("Apollo_123"));

//        System.out.println(decryptSm4String("P82APgvQtFuBVT2Sg4ycdA=="));
//        System.out.println(decryptSm4String("2NT7rME/kkcTMRV8xNjsig=="));

        System.out.println(sm3Hex("158"));
        System.out.println(sm3bcHex("158"));
        System.out.println(hmacSm3Hex("".getBytes(), "abc"));
    }

    public static void main2(String[] args) throws InterruptedException {
        List<String> algorithm = new ArrayList<>();
        algorithm.add(("SM4/ECB/NOPADDING"));
        algorithm.add(("SM4/ECB/PKCS5PADDING"));
        algorithm.add(("SM4/ECB/ISO10126PADDING"));
        algorithm.add(("SM4/CBC/NOPADDING"));
        algorithm.add(("SM4/CBC/PKCS5PADDING"));
        algorithm.add(("SM4/CBC/ISO10126PADDING"));
        algorithm.add(("SM4/PCBC/NOPADDING"));
        algorithm.add(("SM4/PCBC/PKCS5PADDING"));
        algorithm.add(("SM4/PCBC/ISO10126PADDING"));
        algorithm.add(("SM4/CTR/NOPADDING"));
        algorithm.add(("SM4/CTR/PKCS5PADDING"));
        algorithm.add(("SM4/CTR/ISO10126PADDING"));
        algorithm.add(("SM4/CTS/NOPADDING"));
        algorithm.add(("SM4/CTS/PKCS5PADDING"));
        algorithm.add(("SM4/CTS/ISO10126PADDING"));
        if (iv == null)
            iv = AbstractSymmetric.initIv(16);

        String text = "apollo";
        for (String s : algorithm) {
            //SM4加密
            try {
                System.out.println("SM4加密算法: " + s);
                System.out.println("SM4加密原始数据: " + text);
                System.out.println("SM4加密key: " + Base64.getEncoder().encodeToString(key));
                System.out.println("SM4加密iv: " + Base64.getEncoder().encodeToString(iv));

                byte[] encrypt = Sm4.encrypt(s, key, iv, text.getBytes());
                System.out.println("SM4加密数据密文: " + Base64.getEncoder().encodeToString(encrypt));

                //SM4解密
                byte[] decrypt = Sm4.decrypt(s, key, iv, encrypt);
                System.out.println("SM4解密数据: " + new String(decrypt));
            } catch (Exception e) {
                if (e instanceof IllegalBlockSizeException) {
                    System.err.println("SM4解密数据:算法 " + s + "数据需自己手工对齐");
                } else {
                    System.err.println("SM4解密数据:算法 " + s +"::"+ e.getMessage());
                }
            } finally {
                System.err.println("---------------------------------------");
                TimeUnit.SECONDS.sleep(1);
            }
        }
    }

    public static byte[] decryptSm2(byte[] encryptByte) {
        return Sm2.decrypt(encryptByte, privateKey);
    }

    public static byte[] encryptSm2(String text) {
       return Sm2.encrypt(text.getBytes(), publicKey);
    }

    public static String sm3Hex(String text){
        return Sm3.sm3Hex(text.getBytes());
    }

    public static String sm3bcHex(String text) throws Exception {
        return Sm3.sm3bcHex(text.getBytes());
    }

    public static String hmacSm3Hex(byte[] key, String text) {
        return Sm3.hmacSm3Hex(key ,text.getBytes());
    }

    public static byte[] decryptSm4(byte[] encryptByte) throws Exception {
        return Sm4.decrypt("SM4/CBC/PKCS5PADDING", key, iv, encryptByte);
    }

    public static byte[] encryptSm4(String text) throws Exception {
        byte[] encrypt = Sm4.encrypt("SM4/CBC/PKCS5PADDING", key, iv, text.getBytes());
        return encrypt;
    }

    public static String encryptSm4String(String text) throws Exception {
        return encodeToString(encryptSm4(text));
    }

    public static String decryptSm4String(String text) throws Exception {
        return new String(decryptSm4(Base64.getDecoder().decode(text)));
    }

    public static byte[] signByPrivateKey(byte[] data, PrivateKey pk) throws Exception {
        return Sm2.signByPrivateKey(data, pk);
    }

    public static boolean verifyByPublicKey(byte[] data, PublicKey publicKey, byte[] signature) throws Exception {
        return Sm2.verifyByPublicKey(data, publicKey, signature);
    }

    public static String encryptSm2String(String text) {
        return encodeToString(encryptSm2(text));
    }

    public static String decryptSm2String(String text) {
        return new String(decryptSm2(Base64.getDecoder().decode(text)));
    }

    public static String encodeToString(byte[] input){
        return Base64.getEncoder().encodeToString(input);
    }

    public static byte[] decodeToByte(String src){
        return Base64.getDecoder().decode(src);
    }
}

 

package com.abc.apollo.common.util;

import org.bouncycastle.asn1.gm.GMObjectIdentifiers;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey;
import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;

import java.security.*;

public class Sm2 {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 根据publicKey对原始数据data,使用SM2加密
     */
    public static byte[] encrypt(byte[] data, PublicKey publicKey) {
        ECPublicKeyParameters localECPublicKeyParameters = null;

        if (publicKey instanceof BCECPublicKey) {
            BCECPublicKey localECPublicKey = (BCECPublicKey) publicKey;
            ECParameterSpec localECParameterSpec = localECPublicKey.getParameters();
            ECDomainParameters localECDomainParameters = new ECDomainParameters(localECParameterSpec.getCurve(),
                localECParameterSpec.getG(), localECParameterSpec.getN());
            localECPublicKeyParameters = new ECPublicKeyParameters(localECPublicKey.getQ(), localECDomainParameters);
        }
        SM2Engine localSM2Engine = new SM2Engine();
        localSM2Engine.init(true, new ParametersWithRandom(localECPublicKeyParameters, new SecureRandom()));
        byte[] arrayOfByte2;
        try {
            arrayOfByte2 = localSM2Engine.processBlock(data, 0, data.length);
            return arrayOfByte2;
        } catch (InvalidCipherTextException e) {

            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据privateKey对加密数据encodedata,使用SM2解密
     */
    public static byte[] decrypt(byte[] encodedata, PrivateKey privateKey) {
        SM2Engine localSM2Engine = new SM2Engine();
        BCECPrivateKey sm2PriK = (BCECPrivateKey) privateKey;
        ECParameterSpec localECParameterSpec = sm2PriK.getParameters();
        ECDomainParameters localECDomainParameters = new ECDomainParameters(localECParameterSpec.getCurve(),
            localECParameterSpec.getG(), localECParameterSpec.getN());
        ECPrivateKeyParameters localECPrivateKeyParameters = new ECPrivateKeyParameters(sm2PriK.getD(),
            localECDomainParameters);
        localSM2Engine.init(false, localECPrivateKeyParameters);
        try {
            byte[] arrayOfByte3 = localSM2Engine.processBlock(encodedata, 0, encodedata.length);
            return arrayOfByte3;
        } catch (InvalidCipherTextException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 私钥签名
     */
    public static byte[] signByPrivateKey(byte[] data, PrivateKey privateKey) throws Exception {
        Signature sig = Signature.getInstance(GMObjectIdentifiers.sm2sign_with_sm3.toString(), BouncyCastleProvider.PROVIDER_NAME);
        sig.initSign(privateKey);
        sig.update(data);
        byte[] ret = sig.sign();
        return ret;
    }

    /**
     * 公钥验签
     */
    public static boolean verifyByPublicKey(byte[] data, PublicKey publicKey, byte[] signature) throws Exception {
        Signature sig = Signature.getInstance(GMObjectIdentifiers.sm2sign_with_sm3.toString(), BouncyCastleProvider.PROVIDER_NAME);
        sig.initVerify(publicKey);
        sig.update(data);
        boolean ret = sig.verify(signature);
        return ret;
    }
}

 

package com.abc.apollo.common.util;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.MessageDigest;
import java.security.Security;

public class Sm3 {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static byte[] sm3(byte[] srcData) {
        SM3Digest sm3Digest = new SM3Digest();
        sm3Digest.update(srcData, 0, srcData.length);
        byte[] hash = new byte[sm3Digest.getDigestSize()];
        sm3Digest.doFinal(hash, 0);
        return hash;
    }

    public static String sm3Hex(byte[] srcData) {
        byte[] hash = sm3(srcData);
        String hexString = org.apache.commons.codec.binary.Hex.encodeHexString(hash);
        return hexString;
    }

    public static byte[] hmacSm3(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[] hash = new byte[mac.getMacSize()];
        mac.doFinal(hash, 0);
        return hash;
    }

    public static String hmacSm3Hex(byte[] key, byte[] srcData) {
        byte[] hash = hmacSm3(key, srcData);
        String hexString = org.apache.commons.codec.binary.Hex.encodeHexString(hash);
        return hexString;
    }

    public static byte[] sm3bc(byte[] srcData) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance("SM3", "BC");
        byte[] digest = messageDigest.digest(srcData);
        return digest;
    }

    public static String sm3bcHex(byte[] srcData) throws Exception {
        byte[] hash = sm3bc(srcData);
        String hexString = org.apache.commons.codec.binary.Hex.encodeHexString(hash);
        return hexString;
    }
}

 

package com.aaaa.apollo.common.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

public class Sm4 {
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static final String ALGORITHM_NAME = "SM4";
    public static final String DEFAULT_KEY = "random_seed";
    // 128-32位16进制;256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;


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

    public static byte[] generateKey() throws NoSuchAlgorithmException, NoSuchProviderException {
        return generateKey(DEFAULT_KEY, DEFAULT_KEY_SIZE);
    }

    public static byte[] generateKey(String seed) throws NoSuchAlgorithmException, NoSuchProviderException {
        return generateKey(seed, DEFAULT_KEY_SIZE);
    }

    public static byte[] generateKey(String seed, int keySize) throws NoSuchAlgorithmException, NoSuchProviderException {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        if (null != seed && !"".equals(seed)) {
            random.setSeed(seed.getBytes());
        }
        kg.init(keySize, random);
        return kg.generateKey().getEncoded();
    }

    /**
     * @description 加密
     */
    public static byte[] encrypt(String algorithmName, byte[] key, byte[] iv, byte[] data) throws Exception {
        return sm4core(algorithmName, Cipher.ENCRYPT_MODE, key, iv, data);
    }

    /**
     * @description 解密
     */
    public static byte[] decrypt(String algorithmName, byte[] key, byte[] iv, byte[] data) throws Exception {
        return sm4core(algorithmName, Cipher.DECRYPT_MODE, key, iv, data);
    }

    private static byte[] sm4core(String algorithmName, int type, byte[] key, byte[] iv, byte[] data) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        if (algorithmName.contains("/ECB/")) {
            cipher.init(type, sm4Key);
        } else {
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
            cipher.init(type, sm4Key, ivParameterSpec);
        }

        return cipher.doFinal(data);
    }
}

 

posted @ 2023-03-15 11:48  牧之丨  阅读(230)  评论(0编辑  收藏  举报