首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

C# SM2 SM3 SM4 使用

  • 25-02-19 03:41
  • 2621
  • 10041
blog.csdn.net

目录

效果

SM2

SM3

SM4

项目

代码

SM2Utils.cs

Sm3Utils.cs

Sm4Utils.cs

下载


效果

SM2

  1. 公钥:04ca3e272e11b5633681cb0fbbfd8c162be08918ce5b644cd33d49c17be8674caf6c20a11de8b65333924dfe7d42246abb4a4c36b663bef1aafc624a35acf4d2b1
  2. 私钥:27e9d8598679a6066f4dfebb2b5d5fe830ce6c6b8b9cf4a4e515e55678ba44a9
  3. 原文:测试信息lxw123456!@#$%^&*()abcDEFG
  4. 结果: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 };
        }

        ///


        /// 加密函数
        ///

        ///
        ///
        ///
        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));

        }


        ///


        /// 解密函数
        ///

        ///
        ///
        ///
        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);
        }
    }
}
 

  1. using Org.BouncyCastle.Crypto;
  2. using Org.BouncyCastle.Crypto.Engines;
  3. using Org.BouncyCastle.Crypto.Generators;
  4. using Org.BouncyCastle.Crypto.Parameters;
  5. using Org.BouncyCastle.Math;
  6. using Org.BouncyCastle.Math.EC;
  7. using Org.BouncyCastle.Security;
  8. using Org.BouncyCastle.Utilities.Encoders;
  9. using System;
  10. using System.Text;
  11. namespace SMDemo
  12. {
  13. public class SM2KeyPair
  14. {
  15. public string PrivateKey { get; set; } //私钥
  16. public string PublicKey { get; set; } //公钥
  17. }
  18. public class SM2Utils
  19. {
  20. //国密标准256位曲线参数
  21. BigInteger SM2_ECC_P = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16);
  22. BigInteger SM2_ECC_A = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16);
  23. BigInteger SM2_ECC_B = new BigInteger("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16);
  24. BigInteger SM2_ECC_N = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16);
  25. BigInteger SM2_ECC_H = BigInteger.One;
  26. BigInteger SM2_ECC_GX = new BigInteger("32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7", 16);
  27. BigInteger SM2_ECC_GY = new BigInteger("BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0", 16);
  28. public SM2KeyPair GenerateKey()
  29. {
  30. ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H);
  31. ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY);
  32. ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N);
  33. ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
  34. ECKeyGenerationParameters aKeyGenParams = new ECKeyGenerationParameters(domainParams, new SecureRandom());
  35. keyPairGenerator.Init(aKeyGenParams);
  36. AsymmetricCipherKeyPair aKp = keyPairGenerator.GenerateKeyPair();
  37. ECPublicKeyParameters aPub = (ECPublicKeyParameters)aKp.Public;
  38. ECPrivateKeyParameters aPriv = (ECPrivateKeyParameters)aKp.Private;
  39. BigInteger privateKey = aPriv.D;
  40. ECPoint publicKey = aPub.Q;
  41. byte[] pubkey = Hex.Encode(publicKey.GetEncoded());
  42. string temp_pubkey = Encoding.UTF8.GetString(pubkey);
  43. string temp_prikey = Encoding.UTF8.GetString(Hex.Encode(privateKey.ToByteArray()));
  44. return new SM2KeyPair() { PrivateKey = temp_prikey, PublicKey = temp_pubkey };
  45. }
  46. /// <summary>
  47. /// 加密函数
  48. /// </summary>
  49. /// <param name="publicKeyStr"></param>
  50. /// <param name="plainText"></param>
  51. /// <returns></returns>
  52. public string Encrypt(string publicKeyStr, string plainText)
  53. {
  54. byte[] publicKey = Hex.Decode(publicKeyStr);
  55. byte[] data = Encoding.UTF8.GetBytes(plainText);
  56. if (null == publicKey || publicKey.Length == 0)
  57. {
  58. return null;
  59. }
  60. if (data == null || data.Length == 0)
  61. {
  62. return null;
  63. }
  64. byte[] source = new byte[data.Length];
  65. Array.Copy(data, 0, source, 0, data.Length);
  66. ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H);
  67. ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY);
  68. ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N);
  69. ECPoint userkey = curve.DecodePoint(publicKey);
  70. ECPublicKeyParameters aPub = new ECPublicKeyParameters(userkey, domainParams);
  71. SM2Engine sm2Engine = new SM2Engine();
  72. sm2Engine.Init(true, new ParametersWithRandom(aPub));
  73. byte[] enc = sm2Engine.ProcessBlock(source, 0, source.Length);
  74. return Encoding.UTF8.GetString(Hex.Encode(enc));
  75. }
  76. /// <summary>
  77. /// 解密函数
  78. /// </summary>
  79. /// <param name="privateKey"></param>
  80. /// <param name="encryptedData"></param>
  81. /// <returns></returns>
  82. public string Decrypt(string privateKeyStr, string chiperText)
  83. {
  84. byte[] privateKey = Hex.Decode(privateKeyStr);
  85. byte[] encryptedData = Hex.Decode(chiperText);
  86. if (null == privateKey || privateKey.Length == 0)
  87. {
  88. return null;
  89. }
  90. if (encryptedData == null || encryptedData.Length == 0)
  91. {
  92. return null;
  93. }
  94. byte[] enc = new byte[encryptedData.Length];
  95. Array.Copy(encryptedData, 0, enc, 0, encryptedData.Length);
  96. BigInteger userD = new BigInteger(1, privateKey);
  97. ECCurve curve = new FpCurve(SM2_ECC_P, SM2_ECC_A, SM2_ECC_B, SM2_ECC_N, SM2_ECC_H);
  98. ECPoint g = curve.CreatePoint(SM2_ECC_GX, SM2_ECC_GY);
  99. ECDomainParameters domainParams = new ECDomainParameters(curve, g, SM2_ECC_N);
  100. ECPrivateKeyParameters aPriv = new ECPrivateKeyParameters(userD, domainParams);
  101. SM2Engine sm2Engine = new SM2Engine();
  102. sm2Engine.Init(false, aPriv);
  103. byte[] dec = sm2Engine.ProcessBlock(enc, 0, enc.Length);
  104. return Encoding.UTF8.GetString(dec);
  105. }
  106. }
  107. }

Sm3Utils.cs

  1. using Org.BouncyCastle.Crypto.Digests;
  2. using Org.BouncyCastle.Utilities.Encoders;
  3. using System;
  4. using System.Text;
  5. namespace SMDemo
  6. {
  7. public class Sm3Utils
  8. {
  9. public static string GetHash(string plainText)
  10. {
  11. String resultHexString = "";
  12. // 将字符串转换成byte数组
  13. byte[] srcData = Encoding.UTF8.GetBytes(plainText);
  14. SM3Digest digest = new SM3Digest();
  15. digest.BlockUpdate(srcData, 0, srcData.Length);
  16. byte[] hash = new byte[digest.GetDigestSize()];
  17. digest.DoFinal(hash, 0);
  18. // 将返回的hash值转换成16进制字符串
  19. resultHexString = new UTF8Encoding().GetString(Hex.Encode(hash));
  20. return resultHexString;
  21. }
  22. }
  23. }

Sm4Utils.cs

  1. using Org.BouncyCastle.Crypto;
  2. using Org.BouncyCastle.Crypto.Parameters;
  3. using Org.BouncyCastle.Security;
  4. using Org.BouncyCastle.Utilities.Encoders;
  5. using System.Text;
  6. namespace SMDemo
  7. {
  8. public class Sm4Utils
  9. {
  10. public static string EncryptEBC(string plaintext, string key)
  11. {
  12. var dataBytes = Encoding.UTF8.GetBytes(plaintext);
  13. var keyBytes = Encoding.UTF8.GetBytes(key);
  14. KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  15. IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/ECB/PKCS7Padding");
  16. inCipher.Init(true, keyParam);
  17. byte[] cipher = inCipher.DoFinal(dataBytes);
  18. return Hex.ToHexString(cipher, 0, cipher.Length);
  19. }
  20. public static string DecryptEBC(string chipherText, string key)
  21. {
  22. var dataBytes = Hex.Decode(chipherText);
  23. var keyBytes = Encoding.UTF8.GetBytes(key);
  24. KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  25. IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/ECB/PKCS7Padding");
  26. inCipher.Init(false, keyParam);
  27. byte[] plain = inCipher.DoFinal(dataBytes);
  28. return Encoding.UTF8.GetString(plain);
  29. }
  30. /// <summary>
  31. /// CBC模式加密
  32. /// </summary>
  33. /// <param name="data"></param>
  34. /// <param name="key"></param>
  35. /// <returns></returns>
  36. public static string EncryptCBC(string plaintext, string key)
  37. {
  38. var dataBytes = Encoding.UTF8.GetBytes(plaintext);
  39. var keyBytes = Encoding.UTF8.GetBytes(key);
  40. KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  41. ParametersWithIV keyParamWithIv = new ParametersWithIV(keyParam, keyBytes);
  42. IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7Padding");
  43. inCipher.Init(true, keyParamWithIv);
  44. byte[] cipher = inCipher.DoFinal(dataBytes);
  45. return Hex.ToHexString(cipher, 0, cipher.Length);
  46. }
  47. /// <summary>
  48. /// CBC模式解密
  49. /// </summary>
  50. /// <param name="data"></param>
  51. /// <param name="key"></param>
  52. /// <returns></returns>
  53. public static string DecryptCBC(string chipherText, string key)
  54. {
  55. var dataBytes = Hex.Decode(chipherText);
  56. var keyBytes = Encoding.UTF8.GetBytes(key);
  57. KeyParameter keyParam = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  58. ParametersWithIV keyParamWithIv = new ParametersWithIV(keyParam, keyBytes);
  59. IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7Padding");
  60. inCipher.Init(false, keyParamWithIv);
  61. byte[] plain = inCipher.DoFinal(dataBytes);
  62. return Encoding.UTF8.GetString(plain);
  63. }
  64. }
  65. }

下载

下载地址

天天代码码天天
微信公众号
.NET 人工智能实践
注:本文转载自blog.csdn.net的天天代码码天天的文章"https://lw112190.blog.csdn.net/article/details/141855870"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top