适用于前后端公用的SM2国密加密传输, JAVA + VUE_java sm2

引包, 测试好几遍, 这个包适合jdk1.8使用

1、后端代码示例

引包,

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk18on</artifactId>
            <version>1.72</version>
        </dependency>

没有意外就应该直接能用下面代码了

import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.engines.SM2Engine;
import org.bouncycastle.crypto.params.*;
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.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;

import java.math.BigInteger;
import java.security.*;
import java.security.spec.ECGenParameterSpec;


/**
 * 简单的sm2
 */
public class SimpSM2Util {

    /**
     * SM2加密算法
     * @param publicKey     公钥
     * @param data          明文数据
     * @return
     */
    public static String encrypt(String publicKey, String data) {
        // 获取一条SM2曲线参数
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        // 构造ECC算法参数,曲线方程、椭圆曲线G点、大整数N
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
        //提取公钥点
        ECPoint pukPoint = sm2ECParameters.getCurve().decodePoint(Hex.decode(publicKey));
        // 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04
        ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);

        SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
        // 设置sm2为加密模式
        sm2Engine.init(true, new ParametersWithRandom(publicKeyParameters, new SecureRandom()));

        byte[] arrayOfBytes = null;
        try {
            byte[] in = data.getBytes();
            arrayOfBytes = sm2Engine.processBlock(in, 0, in.length);
        } catch (Exception e) {
            System.out.println("SM2加密时出现异常:"+e.getMessage());
        }
        return Hex.toHexString(arrayOfBytes);

    }

    /**
     * SM2解密算法
     * @param privateKey        私钥
     * @param cipherData        密文数据
     * @return
     */
    public static String decrypt(String privateKey, String cipherData) {
        // 使用BC库加解密时密文以04开头,传入的密文前面没有04则补上
        if (!cipherData.startsWith("04")){
            cipherData = "04" + cipherData;
        }
        byte[] cipherDataByte = Hex.decode(cipherData);
        BigInteger privateKeyD = new BigInteger(privateKey, 16);
        //获取一条SM2曲线参数
        X9ECParameters sm2ECParameters = GMNamedCurves.getByName("sm2p256v1");
        //构造domain参数
        ECDomainParameters domainParameters = new ECDomainParameters(sm2ECParameters.getCurve(), sm2ECParameters.getG(), sm2ECParameters.getN());
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);

        SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
        // 设置sm2为解密模式
        sm2Engine.init(false, privateKeyParameters);

        String result = "";
        try {
            byte[] arrayOfBytes = sm2Engine.processBlock(cipherDataByte, 0, cipherDataByte.length);
            return new String(arrayOfBytes);
        } catch (Exception e) {
            System.out.println("SM2解密时出现异常:"+e.getMessage());
        }
        return result;
    }

    /*@Test  
    // 生成密钥
    public void createKey() throws Exception{
        //String M="encryption standard111111111111111111111111111111";
        SimpSM2Util sm2 = new SimpSM2Util();
        ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
        // 获取一个椭圆曲线类型的密钥对生成器
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
        // 使用SM2参数初始化生成器
        kpg.initialize(sm2Spec);
        // 获取密钥对
        KeyPair keyPair = kpg.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        BCECPublicKey p=(BCECPublicKey)publicKey;
        System.out.println("publicKey:"+Hex.toHexString(p.getQ().getEncoded(false)));

        PrivateKey privateKey = keyPair.getPrivate();
        BCECPrivateKey s=(BCECPrivateKey)privateKey;
        System.out.println("privateKey:"+Hex.toHexString(s.getD().toByteArray()));

    }*/
}


publicKey:04aa909915f87880507e3de515220cc8f82b1c5693f56a0475b3b48ff7448c229734cd724e603000dd78569faa9fbc1eeb93a6d836190a0ee734e2d9e74d804f28
    privateKey:00a684d832831d5371d2ff9de6a021a33fb396451e74e0ffe0d415c298b36876fe

加密:  SimpSM2Util.encrypt(“共有密钥”, “明文”);

解密:  SimpSM2Util.decrypt(“私有密钥”, “密文”);

后端代码使用一个工具类, 可参考


import org.bouncycastle.crypto.engines.SM2Engine;

/**
 * 简单单例SM2加解密, 配合前端
 */
public class LoSM2 {

    private static String ECNameModel = "sm2p256v1";
    private static SM2Engine.Mode CipherMode = SM2Engine.Mode.C1C3C2;
    private final String privateKey;
    private final String publicKey;

    private LoSM2(String privateKey, String publicKey){
        this.privateKey = privateKey;
        this.publicKey = publicKey;
    }

    private volatile static LoSM2 instance = null;

    public static LoSM2 getInstance(){
        if(instance == null){
            throw new RuntimeException("请InitKey初始化密钥!!!");
        }
        return instance;
    }

    /**
     * SM2初始密钥(私钥,公钥)
     * @param privateKey
     * @param publicKey
     * @return
     */
    public static LoSM2 InitKey(String privateKey, String publicKey) {
        if(instance == null){
            synchronized(LoSM2.class){
                if(instance == null){
                    instance = new LoSM2(privateKey, publicKey);
                }
            }
        }
        return instance;
    }

    private static class SM2SimpSelfLoader {
        private static final LoSM2 instance = InitKey("", "");
    }
好的,关于Java基于SM2国密算法传输数据,需要先引入Bouncy Castle库,它是一个提供了许多加密算法支持的开源库。接下来,我们需要使用SM2算法进行加密和解密。 下面是使用SM2算法进行加密和解密的基本步骤: 1. 生成SM2密钥对,包括公钥和私钥。 2. 使用公钥进行加密,将明文数据进行加密,得到密文。 3. 使用私钥进行解密,将密文进行解密,得到明文数据。 下面是一个简单的Java代码示例,演示了如何使用SM2算法进行加密和解密: ``` import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.params.ECPrivateKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Hex; import java.security.Security; public class SM2EncryptionDemo { public static void main(String[] args) throws Exception { Security.addProvider(new BouncyCastleProvider()); // 生成SM2密钥对 ECKeyPairGenerator generator = new ECKeyPairGenerator(); generator.init(new ParametersWithRandom(SM2Util.getSM2ParameterSpec(), new SecureRandom())); AsymmetricCipherKeyPair keyPair = generator.generateKeyPair(); ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.getPrivate(); ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.getPublic(); // 明文数据 String plainText = "Hello, world!"; // 使用公钥进行加密 byte[] cipherText = SM2Util.encrypt(publicKey, plainText.getBytes()); // 使用私钥进行解密 byte[] decryptedData = SM2Util.decrypt(privateKey, cipherText); String decryptedText = new String(decryptedData); System.out.println("明文数据: " + plainText); System.out.println("加密后的数据:" + Hex.toHexString(cipherText)); System.out.println("解密后的数据:" + decryptedText); } } ``` 需要注意的是,SM2算法需要使用国密规范的参数,可以使用Bouncy Castle库中提供的SM2Util类来获取SM2相关参数。具体实现细节可以参考相关文档和API。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值