SM2 SM3 SM4 国密版本,基于bouncycastle 实现

本来想用 hutool 的国密算法工具 SmUtil,报这个错 java.lang.NoSuchMethodError: org.bouncycastle.crypto.engines.SM2Engine <init>(Lorg/bouncycaSTLe/asn1/DEREncodableVector;)V

项目里不能修改 bouncycastle 的版本,既然 hutool 底层也是用的 bouncycastle 实现,就干脆直接用 bouncycastle 做一套国密算法吧。。

<dependency>
  <groupId>org.bouncycastle</groupId>
  <artifactId>bcprov-jdk15to18</artifactId>
  <version>1.69</version>
</dependency>

SM2实现

package com.ty.bbc.utils.gm;

import org.bouncycastle.asn1.gm.GMNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
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.math.ec.ECPoint;
import org.bouncycastle.util.encoders.Hex;

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

public class SM2Util {

    /**
     * 生成 SM2 公私钥对
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidAlgorithmParameterException
     */
    public KeyPair geneSM2KeyPair() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
        final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
        // 获取一个椭圆曲线类型的密钥对生成器
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
        // 使用SM2参数初始化生成器
        kpg.initialize(sm2Spec);
        // 获取密钥对
        KeyPair keyPair = kpg.generateKeyPair();
        return keyPair;
    }

    /**
     * 获取私钥(16进制字符串,头部不带00长度共64)
     * @param privateKey 私钥
     * @return
     */
    public String getPriKeyHexString(PrivateKey privateKey){
        BCECPrivateKey s=(BCECPrivateKey)privateKey;
        String priKeyHexString = Hex.toHexString(s.getD().toByteArray());
        if(null!= priKeyHexString && priKeyHexString.length()==66 && "00".equals(priKeyHexString.substring(0,2))){
            return priKeyHexString.substring(2);
        }
        return priKeyHexString;
    }

    /**
     * 获取公钥(16进制字符串,头部带04长度共130)
     * @param publicKey
     * @return
     */
    public String getPubKeyHexString(PublicKey publicKey){
        BCECPublicKey p=(BCECPublicKey)publicKey;
        return Hex.toHexString(p.getQ().getEncoded(false));
    }

    /**
     * SM2加密算法
     * @param publicKey 公钥
     * @param data      明文数据
     * @return
     */
    public String encrypt(PublicKey publicKey, String data){
        BCECPublicKey p=(BCECPublicKey)publicKey;
        return encrypt(Hex.toHexString(p.getQ().getEncoded(false)), data);
    }

    /**
     * SM2解密算法
     * @param privateKey  私钥(16进制字符串)
     * @param cipherData  密文数据
     * @return
     */
    public String decrypt(PrivateKey privateKey, String cipherData) {
        BCECPrivateKey s=(BCECPrivateKey)privateKey;
        return decrypt(Hex.toHexString(s.getD().toByteArray()), cipherData);
    }

    /**
     * SM2加密算法
     * @param pubKeyHexString  公钥(16进制字符串)
     * @param data             明文数据
     * @return
     */
    public String encrypt(String pubKeyHexString, 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(pubKeyHexString));
        // 公钥前面的02或者03表示是压缩公钥,04表示未压缩公钥, 04的时候,可以去掉前面的04
        ECPublicKeyParameters publicKeyParameters = new ECPublicKeyParameters(pukPoint, domainParameters);

        SM2Engine sm2Engine = new SM2Engine();
        // 设置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 priKeyHexString  私钥(16进制字符串)
     * @param cipherData       密文数据
     * @return
     */
    public String decrypt(String priKeyHexString, String cipherData) {

        // 使用BC库加解密时密文以04开头,传入的密文前面没有04则补上
        if (!cipherData.startsWith("04")){
            cipherData = "04" + 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(priKeyHexString, 16);
        ECPrivateKeyParameters privateKeyParameters = new ECPrivateKeyParameters(privateKeyD, domainParameters);

        SM2Engine sm2Engine = new SM2Engine();
        // 设置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;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {

        String M="encryption standard";
        System.out.println("\n明文:"+ M);

        SM2Util sm2 = new SM2Util();
        KeyPair keyPair = sm2.geneSM2KeyPair();

        PublicKey publicKey = keyPair.getPublic();
        String pubKeyHexString = sm2.getPubKeyHexString(publicKey);
        System.out.println("公钥:"+ pubKeyHexString);

        PrivateKey privateKey = keyPair.getPrivate();
        String priKeyHexString = sm2.getPriKeyHexString(privateKey);
        System.out.println("私钥:"+ priKeyHexString);

        String cipherData = sm2.encrypt(pubKeyHexString, M);
        System.out.println("密文:" + cipherData);

        String text=sm2.decrypt(priKeyHexString, cipherData);
        System.out.println("解密:"+text);
    }
}



SM3实现

package com.ty.bbc.utils.gm;

import org.bouncycastle.crypto.digests.SM3Digest;
import org.bouncycastle.util.encoders.Hex;

/**
 * @author jiangzhe
 * @create 2022/8/23 14:13
 */
public class SM3Util {

    public String hash1(String data){
        return Hex.toHexString(hash2(data));
    }

    public byte[] hash2(String data){
        SM3Digest sm3Digest=new SM3Digest();
        byte[] srcData = data.getBytes();
        sm3Digest.update(srcData,0,srcData.length);
        byte[] hash = new byte[sm3Digest.getDigestSize()];
        sm3Digest.doFinal(hash, 0);
        return hash;
    }

    public static void main(String[] args) {
        SM3Util sm3 = new SM3Util();
        String data = "abcd";
        System.out.println("摘要:" + sm3.hash1(data));
        //输出 82ec580fe6d36ae4f81cae3c73f4a5b3b5a09c943172dc9053c69fd8e18dca1e 就说明符合SM3算法要求
    }
}

SM4实现

package com.ty.bbc.utils.gm;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.bouncycastle.util.encoders.Hex;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;

public class SM4Util {

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

    private static final String ENCODING = "UTF-8";
    public static final String ALGORITHM_NAME = "SM4";
    // 加密算法/分组加密模式/分组填充方式
    // PKCS5Padding-以8个字节为一组进行分组加密
    // 定义分组加密模式使用:PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    // 128-32位16进制;256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;

    /**
     * 自动生成密钥(16进制字符串,长度32)
     *
     * @return
     * @explain
     */
    public static String generateKey() throws Exception {
        return Hex.toHexString(generateKey(DEFAULT_KEY_SIZE));
    }

    /**
     * @param keySize
     * @return
     * @throws Exception
     * @explain
     */
    public static byte[] generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return kg.generateKey().getEncoded();
    }

    /**
     * 生成ECB暗号
     *
     * @param algorithmName 算法名称
     * @param mode          模式
     * @param key
     * @return
     * @throws Exception
     * @explain ECB模式(电子密码本模式:Electronic codebook)
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    /**
     * sm4加密
     *
     * @param hexKey   16进制密钥(忽略大小写)
     * @param paramStr 待加密字符串
     * @return 返回16进制的加密字符串
     * @explain 加密模式:ECB
     * 密文长度不固定,会随着被加密字符串长度的变化而变化
     */
    public static String encryptEcb(String hexKey, String paramStr) {
        try {
            String cipherText = "";
            // 16进制字符串-->byte[]
            byte[] keyData = ByteUtils.fromHexString(hexKey);
            // String-->byte[]
            byte[] srcData = paramStr.getBytes(ENCODING);
            // 加密后的数组
            byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
            // byte[]-->hexString
            cipherText = ByteUtils.toHexString(cipherArray);
            return cipherText;
        } catch (Exception e) {
            return paramStr;
        }
    }

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

    /**
     * sm4解密
     *
     * @param hexKey     16进制密钥
     * @param cipherText 16进制的加密字符串(忽略大小写)
     * @return 解密后的字符串
     * @throws Exception
     * @explain 解密模式:采用ECB
     */
    public static String decryptEcb(String hexKey, String cipherText) {
        // 用于接收解密后的字符串
        String decryptStr = "";
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // hexString-->byte[]
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        // 解密
        byte[] srcData = new byte[0];
        try {
            srcData = decrypt_Ecb_Padding(keyData, cipherData);
            // byte[]-->String
            decryptStr = new String(srcData, ENCODING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptStr;
    }

    /**
     * 解密
     *
     * @param key
     * @param cipherText
     * @return
     * @throws Exception
     * @explain
     */
    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);
    }

    /**
     * 校验加密前后的字符串是否为同一数据
     *
     * @param hexKey     16进制密钥(忽略大小写)
     * @param cipherText 16进制加密后的字符串
     * @param paramStr   加密前的字符串
     * @return 是否为同一数据
     * @throws Exception
     * @explain
     */
    public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception {
        // 用于接收校验结果
        boolean flag = false;
        // hexString-->byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        // 将16进制字符串转换成数组
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        // 解密
        byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
        // 将原字符串转换成byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        // 判断2个数组是否一致
        flag = Arrays.equals(decryptData, srcData);
        return flag;
    }

    public static void main(String[] args) {
        try {
            String json = "{\"name\":\"jz\"}";
            System.out.println("明文:" + json);

            // 生成32位16进制密钥
            String key = SM4Util.generateKey();
            System.out.println("密钥:" + key);

            String cipher = SM4Util.encryptEcb(key, json);
            System.out.println("密文:" + cipher);

            System.out.println("数据是否有效:" + SM4Util.verifyEcb(key, cipher, json));

            String res = SM4Util.decryptEcb(key, cipher);
            System.out.println("解密后数据:" + res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java实现国密算法 SM2SM3SM4 可以使用 Bouncy Castle 密码库。Bouncy Castle 是一个流行的密码库,支持多种密码算法,包括国密算法。 以下是一个简单的示例,说明如何在 Java 中使用 Bouncy Castle 实现 SM2SM3SM4: 1. 添加 Bouncy Castle 依赖 在 Maven 项目中,可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15to18</artifactId> <version>1.68</version> </dependency> ``` 2. SM2 加密和解密示例 ```java import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.params.*; import org.bouncycastle.crypto.signers.SM2Signer; import org.bouncycastle.crypto.util.PrivateKeyFactory; import org.bouncycastle.crypto.util.PublicKeyFactory; import java.security.SecureRandom; public class SM2Example { public static void main(String[] args) throws Exception { // 生成密钥对 ECKeyPairGenerator ecKeyPairGenerator = new ECKeyPairGenerator(); SecureRandom secureRandom = new SecureRandom(); X9ECParameters ecParams = SECNamedCurves.getByName("sm2p256v1"); ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParams.getCurve(), ecParams.getG(), ecParams.getN(), ecParams.getH(), ecParams.getSeed()); ECKeyGenerationParameters keyParams = new ECKeyGenerationParameters(ecDomainParameters, secureRandom); ecKeyPairGenerator.init(keyParams); AsymmetricCipherKeyPair keyPair = ecKeyPairGenerator.generateKeyPair(); // 加密 SM2Engine sm2Engine = new SM2Engine(); CipherParameters publicKeyParameters = PublicKeyFactory.createKey(keyPair.getPublic().getEncoded()); CipherParameters privateKeyParameters = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); sm2Engine.init(true, new ParametersWithRandom(publicKeyParameters, secureRandom)); byte[] plainText = "hello world".getBytes(); byte[] cipherText = sm2Engine.processBlock(plainText, 0, plainText.length); // 解密 sm2Engine.init(false, privateKeyParameters); byte[] decryptedText = sm2Engine.processBlock(cipherText, 0, cipherText.length); System.out.println(new String(decryptedText)); } } ``` 3. SM3 摘要示例 ```java import org.bouncycastle.crypto.digests.SM3Digest; public class SM3Example { public static void main(String[] args) { // 计算摘要 byte[] input = "hello world".getBytes(); SM3Digest digest = new SM3Digest(); digest.update(input, 0, input.length); byte[] result = new byte[digest.getDigestSize()]; digest.doFinal(result, 0); // 输出摘要 System.out.println(bytesToHex(result)); } private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray(); public static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { int v = bytes[i] & 0xFF; hexChars[i * 2] = HEX_ARRAY[v >>> 4]; hexChars[i * 2 + 1] = HEX_ARRAY[v & 0x0F]; } return new String(hexChars); } } ``` 4. SM4 加密和解密示例 ```java import org.bouncycastle.crypto.engines.SM4Engine; import org.bouncycastle.crypto.params.KeyParameter; import java.security.SecureRandom; public class SM4Example { public static void main(String[] args) { // 生成密钥 SecureRandom secureRandom = new SecureRandom(); byte[] key = new byte[16]; secureRandom.nextBytes(key); KeyParameter keyParameter = new KeyParameter(key); // 加密 SM4Engine sm4Engine = new SM4Engine(); sm4Engine.init(true, keyParameter); byte[] plainText = "hello world".getBytes(); byte[] cipherText = new byte[sm4Engine.getOutputSize(plainText.length)]; int length = sm4Engine.processBytes(plainText, 0, plainText.length, cipherText, 0); sm4Engine.doFinal(cipherText, length); // 解密 sm4Engine.init(false, keyParameter); byte[] decryptedText = new byte[sm4Engine.getOutputSize(cipherText.length)]; length = sm4Engine.processBytes(cipherText, 0, cipherText.length, decryptedText, 0); sm4Engine.doFinal(decryptedText, length); System.out.println(new String(decryptedText)); } } ``` 以上是实现 SM2SM3SM4 的简单示例,具体实现可以根据具体需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七里香的秋刀鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值