c# 基于BouncyCastle.Crypto的国密sm2,sm4封装,与java版本兼容

与java版本兼容

using System;
using System.Text;
using System.Text.RegularExpressions;
using Org.BouncyCastle.Asn1.GM;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;

namespace Commons.Secret
{
   
    public sealed class SMCrypto
    {
   
        /// <summary>
        /// 生成SM2公钥私钥
        /// </summary>
        /// <param name="publicKey">SM2公钥 16进制</param>
        /// <param name="privateKey">SM2私钥 16进制</param>
        public static void GenerateSm2KeyHex(out string publicKey, out string privateKey)
        {
   
            GenerateSm2Key(out var a, out var b);
            publicKey = Hex.ToHexString(a);
            privateKey = Hex.ToHexString(b);
        }

        /// <summary>
        /// 生成SM2公钥私钥
        /// </summary>
        /// <param name="publicKey">SM2公钥</param>
        /// <param name="privateKey">SM2私钥</param>
        public static void GenerateSm2Key(out byte[] publicKey, out byte[] privateKey)
        {
   
            var g = new ECKeyPairGenerator();
            g.Init(new ECKeyGenerationParameters(new ECDomainParameters(GMNamedCurves.GetByName("SM2P256V1")), new SecureRandom()));
            var k = g.GenerateKeyPair();
            publicKey = ((ECPublicKeyParameters)k.Public).Q.GetEncoded(false);
            privateKey = ((ECPrivateKeyParameters)k.Private).D.ToByteArray();
        }

        /// <summary>
        /// SM2加密
        /// </summary>
        /// <param name="sourceData">数据源 16进制字符串</param>
        /// <param name="publicKey">公钥 16进制字符串</param>
        /// <returns></returns>
        public static byte[] Sm2Encrypt(string sourceData, string publicKey)
        {
   
            return Sm2Encrypt(Decode(sourceData), Decode(publicKey));
        }

        /// <summary>
        /// SM2加密
        /// </summary>
        /// <param name="sourceData">数据源</param></
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java 中实现国密算法 SM2、SM3、SM4 可以使用 Bouncy Castle 密码库。Bouncy Castle 是一个流行的密码库,支持多种密码算法,包括国密算法。 以下是一个简单的示例,说明如何在 Java 中使用 Bouncy Castle 实现 SM2、SM3、SM4: 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)); } } ``` 以上是实现 SM2、SM3、SM4 的简单示例,具体实现可以根据具体需求进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值