LOGO OA教程 ERP教程 模切知識(shí)交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

C# 實(shí)現(xiàn)SM2加密解密

admin
2024年7月20日 9:41 本文熱度 1842

SM2是由中國(guó)國(guó)家密碼管理局制定的公鑰密碼算法,屬于國(guó)家密碼標(biāo)準(zhǔn)之一。SM2算法基于橢圓曲線密碼學(xué),兼具安全性和高效性,被廣泛應(yīng)用在金融、電子政務(wù)和電子商務(wù)等領(lǐng)域。

特點(diǎn)

  1. 安全性:SM2基于橢圓曲線密碼學(xué),提供高強(qiáng)度的安全保障。

  2. 高效性:在相同的安全強(qiáng)度下,SM2比RSA和DSA更加高效,計(jì)算復(fù)雜度較低。

  3. 國(guó)家標(biāo)準(zhǔn):SM2是中國(guó)國(guó)家密碼標(biāo)準(zhǔn)GB/T 32918,具有國(guó)家認(rèn)可的權(quán)威性。


應(yīng)用場(chǎng)景

  1. 數(shù)字簽名:用于身份驗(yàn)證和不可否認(rèn)性。

  2. 數(shù)據(jù)加密:用于保護(hù)敏感信息的傳輸與存儲(chǔ)。

  3. 密鑰交換:用于安全的密鑰分發(fā)和交換過程。


代碼示例

第三方庫BouncyCastle

using Org.BouncyCastle.Asn1.X9;using Org.BouncyCastle.Crypto.Generators;using Org.BouncyCastle.Crypto;using Org.BouncyCastle.Crypto.Parameters;using Org.BouncyCastle.Security;using Org.BouncyCastle.Asn1.Sec;using Org.BouncyCastle.Asn1.GM;using System.Security.Cryptography.X509Certificates;using Org.BouncyCastle.Crypto.Engines;using Org.BouncyCastle.Math;
namespace AppSm2{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }
       private void btnCreateKey_Click(object sender, EventArgs e)        {            // 1. 生成SM2密鑰對(duì)            var keyPair = GenerateSM2KeyPair();            var publicKey = (ECPublicKeyParameters)keyPair.Public;            var privateKey = (ECPrivateKeyParameters)keyPair.Private;            File.WriteAllText("./public.dat", Convert.ToBase64String(publicKey.Q.GetEncoded()));            File.WriteAllText("./private.dat", Convert.ToBase64String(privateKey.D.ToByteArrayUnsigned()));        }
       /// <summary>        /// 生成公私鑰        /// </summary>        /// <returns></returns>        private AsymmetricCipherKeyPair GenerateSM2KeyPair()        {            // 使用國(guó)標(biāo)曲線參數(shù) "Wapi" 被GMNamedCurves定義 (SM2標(biāo)準(zhǔn)曲線)            X9ECParameters sm2Params = GMNamedCurves.GetByName("sm2p256v1");            var ecParams = new ECDomainParameters(sm2Params.Curve, sm2Params.G, sm2Params.N, sm2Params.H);
           var keyGenerationParameters = new ECKeyGenerationParameters(ecParams, new SecureRandom());            var keyPairGenerator = new ECKeyPairGenerator();            keyPairGenerator.Init(keyGenerationParameters);
           return keyPairGenerator.GenerateKeyPair();        }
       private void btnEncrypt_Click(object sender, EventArgs e)        {            // 將Base64格式公鑰轉(zhuǎn)換回ECPublicKeyParameters            var restoredPublicKey = RestorePublicKeyFromBase64(File.ReadAllText("./public.dat"));            byte[] cipherText = Encrypt(txt1.Text, restoredPublicKey);            txt2.Text = Convert.ToBase64String(cipherText);        }
       /// <summary>        /// 還原公鑰        /// </summary>        /// <param name="base64PublicKey"></param>        /// <returns></returns>        private ECPublicKeyParameters RestorePublicKeyFromBase64(string base64PublicKey)        {            // 將Base64格式的公鑰字符串轉(zhuǎn)換為字節(jié)數(shù)組            byte[] publicKeyBytes = Convert.FromBase64String(base64PublicKey);
           // 獲取SM2曲線參數(shù),這里使用sm2p256v1曲線            X9ECParameters sm2Params = GMNamedCurves.GetByName("sm2p256v1");
           // 創(chuàng)建ECDomainParameters對(duì)象,包含曲線的一些基本參數(shù),如曲線、生成元G、階N和系數(shù)H            var ecParams = new ECDomainParameters(sm2Params.Curve, sm2Params.G, sm2Params.N, sm2Params.H);
           // 使用曲線參數(shù)解碼公鑰字節(jié)數(shù)組,將其轉(zhuǎn)換為ECPoint            var q = sm2Params.Curve.DecodePoint(publicKeyBytes);
           // 根據(jù)解碼后的ECPoint和ECDomainParameters創(chuàng)建ECPublicKeyParameters對(duì)象            return new ECPublicKeyParameters(q, ecParams);        }
       /// <summary>        /// 加密        /// </summary>        /// <param name="plainText"></param>        /// <param name="publicKey"></param>        /// <returns></returns>        private byte[] Encrypt(string plainText, ECPublicKeyParameters publicKey)        {            var sm2Engine = new SM2Engine();            sm2Engine.Init(true, new ParametersWithRandom(publicKey, new SecureRandom()));
           byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(plainText);            return sm2Engine.ProcessBlock(plainBytes, 0, plainBytes.Length);        }
       private void btnDecrypt_Click(object sender, EventArgs e)        {            var restoredPrivateKey = RestorePrivateKeyFromBase64(File.ReadAllText("./private.dat"));            string decryptedText = Decrypt(txt2.Text, restoredPrivateKey);            txt3.Text = decryptedText;        }
       /// <summary>        /// 解密        /// </summary>        /// <param name="base64CipherText"></param>        /// <param name="privateKey"></param>        /// <returns></returns>        private static string Decrypt(string base64CipherText, ECPrivateKeyParameters privateKey)        {            var sm2Engine = new SM2Engine();            sm2Engine.Init(false, privateKey);
           byte[] cipherBytes = Convert.FromBase64String(base64CipherText);            byte[] decryptedBytes = sm2Engine.ProcessBlock(cipherBytes, 0, cipherBytes.Length);            return System.Text.Encoding.UTF8.GetString(decryptedBytes);        }
       /// <summary>        /// 還私公鑰        /// </summary>        /// <param name="base64PrivateKey"></param>        /// <returns></returns>        private ECPrivateKeyParameters RestorePrivateKeyFromBase64(string base64PrivateKey)        {            // 將Base64格式的私鑰字符串轉(zhuǎn)換為字節(jié)數(shù)組            byte[] privateKeyBytes = Convert.FromBase64String(base64PrivateKey);
           // 使用BigInteger構(gòu)造函數(shù)將字節(jié)數(shù)組轉(zhuǎn)換為無符號(hào)大整數(shù),這將表示我們的私鑰            BigInteger d = new BigInteger(1, privateKeyBytes);
           // 獲取SM2曲線參數(shù),這里使用sm2p256v1曲線            X9ECParameters sm2Params = GMNamedCurves.GetByName("sm2p256v1");
           // 創(chuàng)建ECDomainParameters對(duì)象,包含曲線的一些基本參數(shù),如曲線、生成元G、階N和系數(shù)H            var ecParams = new ECDomainParameters(sm2Params.Curve, sm2Params.G, sm2Params.N, sm2Params.H);
           // 根據(jù)無符號(hào)大整數(shù)和ECDomainParameters創(chuàng)建ECPrivateKeyParameters對(duì)象,表示私鑰            return new ECPrivateKeyParameters(d, ecParams);        }    }}

代碼說明

  1. 生成密鑰對(duì):使用GenerateSM2KeyPair方法生成SM2密鑰對(duì)。

  2. 加密:用公鑰加密明文,返回密文。

  3. 解密:用私鑰解密密文,返回明文。


小結(jié)

本文介紹了SM2算法的基本特點(diǎn)、應(yīng)用場(chǎng)景,并提供了一個(gè)完整的C#示例代碼。通過BouncyCastle庫,開發(fā)者可以方便地在C#應(yīng)用程序中實(shí)現(xiàn)SM2加密和解密操作。

SM2作為中國(guó)國(guó)家密碼標(biāo)準(zhǔn),在確保信息安全傳輸方面起到了至關(guān)重要的作用。在未來的應(yīng)用中,SM2有望在更多領(lǐng)域中發(fā)揮更大的作用。


該文章在 2024/7/22 12:18:38 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點(diǎn)晴ERP是一款針對(duì)中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國(guó)內(nèi)大量中小企業(yè)的青睞。
點(diǎn)晴PMS碼頭管理系統(tǒng)主要針對(duì)港口碼頭集裝箱與散貨日常運(yùn)作、調(diào)度、堆場(chǎng)、車隊(duì)、財(cái)務(wù)費(fèi)用、相關(guān)報(bào)表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點(diǎn),圍繞調(diào)度、堆場(chǎng)作業(yè)而開發(fā)的。集技術(shù)的先進(jìn)性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點(diǎn)晴WMS倉儲(chǔ)管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲(chǔ)管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號(hào)管理軟件。
點(diǎn)晴免費(fèi)OA是一款軟件和通用服務(wù)都免費(fèi),不限功能、不限時(shí)間、不限用戶的免費(fèi)OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved

黄频国产免费高清视频,久久不卡精品中文字幕一区,激情五月天AV电影在线观看,欧美国产韩国日本一区二区
中文乱码在线波多野结衣 | 日本十八禁黄无遮禁在线视频 | 亚洲欧美日韩Aⅴ在线观看 日韩欧美一本书道一区二区 | 日韩精品一区二区亚洲AV观看 | 久久久精品国产免费 | 日本在线不卡中文字幕资源 |