Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# sm2加密

作者:龙之灬殇   发布日期:2025-12-23   浏览:28

using System;
using System.Security.Cryptography;
using System.Text;

public class SM2Encryption
{
    public static void Main(string[] args)
    {
        // 生成密钥对
        using (ECDiffieHellmanCng alice = new ECDiffieHellmanCng())
        using (ECDiffieHellmanCng bob = new ECDiffieHellmanCng())
        {
            alice.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            alice.HashAlgorithm = CngAlgorithm.Sha256;

            bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
            bob.HashAlgorithm = CngAlgorithm.Sha256;

            // Alice 和 Bob 交换公钥并生成共享密钥
            byte[] aliceSharedKey = alice.DeriveKeyMaterial(bob.PublicKey);
            byte[] bobSharedKey = bob.DeriveKeyMaterial(alice.PublicKey);

            Console.WriteLine("Alice's shared key: " + Convert.ToBase64String(aliceSharedKey));
            Console.WriteLine("Bob's shared key: " + Convert.ToBase64String(bobSharedKey));

            // 加密和解密示例
            string originalMessage = "Hello, SM2!";
            byte[] encryptedMessage = Encrypt(originalMessage, aliceSharedKey);
            string decryptedMessage = Decrypt(encryptedMessage, bobSharedKey);

            Console.WriteLine("Original message: " + originalMessage);
            Console.WriteLine("Encrypted message: " + Convert.ToBase64String(encryptedMessage));
            Console.WriteLine("Decrypted message: " + decryptedMessage);
        }
    }

    private static byte[] Encrypt(string plainText, byte[] sharedKey)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = sharedKey;
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (System.IO.MemoryStream msEncrypt = new System.IO.MemoryStream())
            {
                msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
                msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);
                using (System.IO.CryptoStream csEncrypt = new System.IO.CryptoStream(msEncrypt, encryptor, System.IO.CryptoStreamMode.Write))
                using (System.IO.StreamWriter swEncrypt = new System.IO.StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(plainText);
                }
                return msEncrypt.ToArray();
            }
        }
    }

    private static string Decrypt(byte[] cipherText, byte[] sharedKey)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = sharedKey;
            int ivSize = BitConverter.ToInt32(cipherText, 0);
            aesAlg.IV = cipherText[sizeof(int)..(ivSize + sizeof(int))];

            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (System.IO.MemoryStream msDecrypt = new System.IO.MemoryStream(cipherText, ivSize + sizeof(int), cipherText.Length - ivSize - sizeof(int)))
            using (System.IO.CryptoStream csDecrypt = new System.IO.CryptoStream(msDecrypt, decryptor, System.IO.CryptoStreamMode.Read))
            using (System.IO.StreamReader srDecrypt = new System.IO.StreamReader(csDecrypt))
            {
                return srDecrypt.ReadToEnd();
            }
        }
    }
}

解释说明

  1. 密钥生成:

    • 使用 ECDiffieHellmanCng 类生成椭圆曲线 Diffie-Hellman 密钥对。
    • Alice 和 Bob 各自生成一对密钥,并通过公钥交换生成共享密钥。
  2. 加密和解密:

    • 使用 AES 对称加密算法进行实际的加密和解密操作。
    • 共享密钥用于 AES 的密钥,IV(初始化向量)在加密时随机生成并在密文前附加,解密时读取并使用。
  3. 输出:

    • 打印出原始消息、加密后的消息以及解密后的消息,以验证加密和解密过程是否正确。

请注意,这段代码是基于 .NET Framework 或 .NET Core 中的 ECDiffieHellmanCng 类实现的。如果你需要更具体的 SM2 实现,可能需要使用第三方库或自定义实现。

上一篇:c# 数组初始化

下一篇:c# 读取文件

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站