首页 > 编程语言 >C# SM2 SM3 SM4 使用

C# SM2 SM3 SM4 使用

时间:2024-09-08 09:53:30浏览次数:9  
标签:ECC string C# SM4 SM3 SM2 using new byte

目录

效果

SM2

SM3

SM4

项目

代码

SM2Utils.cs

Sm3Utils.cs

Sm4Utils.cs

下载


效果

SM2

公钥:04ca3e272e11b5633681cb0fbbfd8c162be08918ce5b644cd33d49c17be8674caf6c20a11de8b65333924dfe7d42246abb4a4c36b663bef1aafc624a35acf4d2b1
私钥:27e9d8598679a6066f4dfebb2b5d5fe830ce6c6b8b9cf4a4e515e55678ba44a9
原文:测试信息lxw123456!@#$%^&*()abcDEFG
结果:043267543680002a384bdcc8e2db3648f1d5d1a5956ca4798bdfe3ca4a667a620d4df25683e260147ab846a049505ae88ff572f983078f3b1c7d4692c384e6c045292023ff0d69ae3c4f4139b19843a3a5ffa130a1e6758659f4d11a51d32d17a617dda0612319a091a4dcac7e6a67d55f4145c882ca9bbb687641182468a2962d5a0c6bf25ddc

在线校验
地址:https://the-x.cn/cryptography/Sm2.aspx

SM3

SM4

项目

代码

SM2Utils.cs

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Text;

namespace SMDemo
{
    public class SM2KeyPair
    {
        public string PrivateKey { get; set; } //私钥
        public string PublicKey { get; set; } //公钥

    }
    public class SM2Utils
    {
        //国密标准256位曲线参数
        BigInteger SM2_ECC_P = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16);
        BigInteger SM2_ECC_A = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16);
        BigInteger SM2_ECC_B = new BigInteger("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16);
        BigInteger SM2_ECC_N = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16);
        BigInteger SM2_ECC_H = BigInteger.One;
        BigInteger SM2_ECC_GX = new BigInteger("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16);
        BigInteger SM2_ECC_GY = new BigInteger("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16);

        public SM2KeyPair GenerateKey()
        {
            ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H);
            ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY);
            ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N);
            ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
            ECKeyGenerationParameters aKeyGenParams = new ECKeyGenerationParameters(domainParams, new SecureRandom());
            keyPairGenerator.Init(aKeyGenParams);
            AsymmetricCipherKeyPair aKp = keyPairGenerator.GenerateKeyPair();
            ECPublicKeyParameters aPub = (ECPublicKeyParameters)aKp.Public;
            ECPrivateKeyParameters aPriv = (ECPrivateKeyParameters)aKp.Private;

            BigInteger privateKey = aPriv.D;
            ECPoint publicKey = aPub.Q;

            byte[] pubkey = Hex.Encode(publicKey.GetEncoded());
            string temp_pubkey = Encoding.UTF8.GetString(pubkey);

            string temp_prikey = Encoding.UTF8.GetString(Hex.Encode(privateKey.ToByteArray()));

            return new SM2KeyPair() { PrivateKey = temp_prikey, PublicKey = temp_pubkey };
        }

        /// <summary>
        /// 加密函数
        /// </summary>
        /// <param name="publicKeyStr"></param>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public string Encrypt(string publicKeyStr, string plainText)
        {
            byte[] publicKey = Hex.Decode(publicKeyStr);
            byte[] data = Encoding.UTF8.GetBytes(plainText);

            if (null == publicKey || publicKey.Length == 0)
            {
                return null;
            }
            if (data == null || data.Length == 0)
            {
                return null;
            }
            byte[] source = new byte[data.Length];
            Array.Copy(data, 0, source, 0, data.Length);
            ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H);
            ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY);
            ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N);
            ECPoint userkey = curve.DecodePoint(publicKey);
            ECPublicKeyParameters aPub = new ECPublicKeyParameters(userkey, domainParams);

            SM2Engine sm2Engine = new SM2Engine();
            sm2Engine.Init(true, new ParametersWithRandom(aPub));
            byte[] enc = sm2Engine.ProcessBlock(source, 0, source.Length);
            return Encoding.UTF8.GetString(Hex.Encode(enc));

        }


        /// <summary>
        /// 解密函数
        /// </summary>
        /// <param name="privateKey"></param>
        /// <param name="encryptedData"></param>
        /// <returns></returns>
        public string Decrypt(string privateKeyStr, string chiperText)
        {
            byte[] privateKey = Hex.Decode(privateKeyStr);
            byte[] encryptedData = Hex.Decode(chiperText);

            if (null == privateKey || privateKey.Length == 0)
            {
                return null;
            }
            if (encryptedData == null || encryptedData.Length == 0)
            {
                return null;
            }

            byte[] enc = new byte[encryptedData.Length];
            Array.Copy(encryptedData, 0, enc, 0, encryptedData.Length);
            BigInteger userD = new BigInteger(1, privateKey);
            ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H);
            ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY);
            ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N);
            ECPrivateKeyParameters aPriv = new ECPrivateKeyParameters(userD, domainParams);

            SM2Engine sm2Engine = new SM2Engine();
            sm2Engine.Init(false, aPriv);
            byte[] dec = sm2Engine.ProcessBlock(enc, 0, enc.Length);
            return Encoding.UTF8.GetString(dec);
        }
    }
}

Sm3Utils.cs

using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Utilities.Encoders;
using System;
using System.Text;

namespace SMDemo
{
    public class Sm3Utils
    {
        public static string GetHash(string plainText)
        {
            String resultHexString = "";
            // 将字符串转换成byte数组
            byte[] srcData = Encoding.UTF8.GetBytes(plainText);
            SM3Digest digest = new SM3Digest();
            digest.BlockUpdate(srcData, 0, srcData.Length);
            byte[] hash = new byte[digest.GetDigestSize()];
            digest.DoFinal(hash, 0);
            // 将返回的hash值转换成16进制字符串
            resultHexString = new UTF8Encoding().GetString(Hex.Encode(hash));
            return resultHexString;
        }
    }
}

Sm4Utils.cs

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using System.Text;

namespace SMDemo
{
    public class Sm4Utils
    {
        public static string EncryptEBC(string plaintext, string key)
        {
            var dataBytes = Encoding.UTF8.GetBytes(plaintext);
            var keyBytes = Encoding.UTF8.GetBytes(key);
            KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
            IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/ECB/PKCS7Padding");
            inCipher.Init(true, keyParam);
            byte[] cipher = inCipher.DoFinal(dataBytes);
            return Hex.ToHexString(cipher, 0, cipher.Length);
        }

        public static string DecryptEBC(string chipherText, string key)
        {
            var dataBytes = Hex.Decode(chipherText);
            var keyBytes = Encoding.UTF8.GetBytes(key);
            KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
            IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/ECB/PKCS7Padding");
            inCipher.Init(false, keyParam);
            byte[] plain = inCipher.DoFinal(dataBytes);
            return Encoding.UTF8.GetString(plain);
        }


        /// <summary>
        /// CBC模式加密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string EncryptCBC(string plaintext, string key)
        {
            var dataBytes = Encoding.UTF8.GetBytes(plaintext);
            var keyBytes = Encoding.UTF8.GetBytes(key);
            KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
            ParametersWithIV keyParamWithIv = new ParametersWithIV(keyParam, keyBytes);
            IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7Padding");
            inCipher.Init(true, keyParamWithIv);
            byte[] cipher = inCipher.DoFinal(dataBytes);
            return Hex.ToHexString(cipher, 0, cipher.Length);
        }

        /// <summary>
        /// CBC模式解密
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string DecryptCBC(string chipherText, string key)
        {
            var dataBytes = Hex.Decode(chipherText);
            var keyBytes = Encoding.UTF8.GetBytes(key);
            KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
            ParametersWithIV keyParamWithIv = new ParametersWithIV(keyParam, keyBytes);
            IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7Padding");
            inCipher.Init(false, keyParamWithIv);
            byte[] plain = inCipher.DoFinal(dataBytes);
            return Encoding.UTF8.GetString(plain);
        }

    }
}

下载

下载地址

标签:ECC,string,C#,SM4,SM3,SM2,using,new,byte
From: https://blog.csdn.net/weixin_46771779/article/details/142021880

相关文章

  • C++ STL-deque容器入门详解
    1.1deque容器基本概念功能:双端数组,可以对头端进行插入删除操作deque与vector区别:vector对于头部的插入删除效率低,数据量越大,效率越低deque相对而言,对头部的插入删除速度回比vector快vector访问元素时的速度会比deque快,这和两者内部实现有关deque内部工作原理:deque内部......
  • C++ STL-Map容器从入门到精通详解
    1.简介Map也是一种关联容器,它是键—值对的集合,即它的存储都是以一对键和值进行存储的,Map通常也可以理解为关联数组(associativearray),就是每一个值都有一个键与之一一对应,因此,map也是不允许重复元素出现的。同时map也具备set的相关功能,其底层也会将元素进行自动排序。功能......
  • 多线程篇(阻塞队列- BlockingQueue)(持续更新迭代)
    目录一、了解什么是阻塞队列之前,需要先知道队列1.Queue(接口)二、阻塞队列1.前言2.什么是阻塞队列3.Java里面常见的阻塞队列三、BlockingQueue(接口)1.前言2.简介3.特性3.1.队列类型3.2.队列数据结构2.简介4.核心功能入队(放入数据)出队(取出数据)总结四......
  • 【题解】CF1955E
    CF1955E翻译思路代码翻译原题链接CF1955E思路  由于每次操作区间长度是定值,所以我们可以说,如果最前面的数已经是1了,那它再也不会被进入操作。因为如果把它变回0,那想再变成1只能以它为起点再操作一次,前后两次操作抵消。  所以思路很简单,直接......
  • 如何来避免FOUC
    FOUC(FlashofUnstyledContent)是指在网页加载过程中,由于CSS样式加载延迟或加载顺序不当,导致页面出现短暂的无样式内容闪烁现象。为了避免FOUC,可以采取以下几种方法:1.优化CSS加载内联CSS:将关键的CSS样式直接嵌入到HTML文档的<head>部分,这样可以确保在页面渲染之前样式就已经......
  • ES6中try-catch
    在ES6(ECMAScript2015)中,try-catch 语句的语法和使用方式与在之前的ECMAScript版本中是一样的。try-catch 语句用于处理代码中可能发生的错误,确保程序的健壮性和用户体验。基本语法try{//尝试执行的代码块//如果发生错误,则执行catch块中的代码}catch(er......
  • C# kvaser can 通讯
    1、查看官方文档  https://kvaser.com/canlib-webhelp/section_install_windows.html   2、安装canwindows驱动https://www.kvaser.com/downloads-kvaser/?utm_source=software&utm_ean=7330130980013&utm_status=latest 3、安装canlibhttps://www.kvaser.co......
  • 自动化运维工具之WGCLOUD使用操作指南,为服务器安全保驾护航
    WGCLOUD官网下载安装包:www.wgstart.com 1、部署WGCLOUD运行的前置条件说明WGCLOUD包括:server为服务端(或主控端),agent为客户端(探针端、被控端)WGCLOUD的server和agent,可以部署在已有业务运行的主机,不要求主机是纯净的操作系统。当然了,纯净的系统也可以部署WGCLOUDWGCLOUD是绿色......
  • SAP S/4HANA Cloud:云端企业资源规划的未来
     在数字化转型的浪潮中,SAPS/4HANACloud作为SAP公司推出的一款云端ERP解决方案,正成为企业资源规划的新宠。它不仅提供了传统ERP系统的所有功能,还通过云端技术为企业带来了更高的灵活性和可扩展性。   SAPS/4HANACloud的核心优势SAPS/4HANACloud的优势在于其强大的......
  • docker php和nginx的通信
    1安装网络dockernetworkcreatephpClassExamples_network2安装nginx2.1生成临时容器dockerrun-it--nametest_nginx-dnginx查看临时容器内部,找到关键目录1、工作目录:lsusr/share/nginx/html 2、配置目录lsetc/nginx/conf.d3、日志目录lsvar......