c#中怎么實(shí)現(xiàn)sm4加密

c#
小億
89
2024-03-26 18:49:16

在C#中實(shí)現(xiàn)SM4加密可以通過使用第三方庫(kù)來(lái)實(shí)現(xiàn)。一個(gè)常用的庫(kù)是Bouncy Castle,可以通過NuGet安裝。

首先,安裝Bouncy Castle庫(kù):

Install-Package BouncyCastle

然后,使用以下代碼示例實(shí)現(xiàn)SM4加密:

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Engines;

public class SM4Encryption
{
    public static string Encrypt(string plaintext, string key)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);

        SM4Engine sm4 = new SM4Engine();
        KeyParameter keyParam = new KeyParameter(keyBytes);
        sm4.Init(true, keyParam);

        byte[] ciphertextBytes = new byte[plaintextBytes.Length];
        for (int i = 0; i < plaintextBytes.Length; i++)
        {
            sm4.ProcessBlock(plaintextBytes, i, ciphertextBytes, i);
        }

        return Convert.ToBase64String(ciphertextBytes);
    }

    public static string Decrypt(string ciphertext, string key)
    {
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] ciphertextBytes = Convert.FromBase64String(ciphertext);

        SM4Engine sm4 = new SM4Engine();
        KeyParameter keyParam = new KeyParameter(keyBytes);
        sm4.Init(false, keyParam);

        byte[] plaintextBytes = new byte[ciphertextBytes.Length];
        for (int i = 0; i < ciphertextBytes.Length; i++)
        {
            sm4.ProcessBlock(ciphertextBytes, i, plaintextBytes, i);
        }

        return Encoding.UTF8.GetString(plaintextBytes);
    }
}

使用示例:

string plaintext = "Hello, SM4!";
string key = "0123456789abcdeffedcba9876543210";
string ciphertext = SM4Encryption.Encrypt(plaintext, key);
Console.WriteLine("Ciphertext: " + ciphertext);

string decryptedText = SM4Encryption.Decrypt(ciphertext, key);
Console.WriteLine("Decrypted Text: " + decryptedText);

請(qǐng)注意,以上代碼示例僅供參考,并不保證在所有情況下都能正確工作。在實(shí)際應(yīng)用中,建議根據(jù)具體需求進(jìn)行適當(dāng)調(diào)整和優(yōu)化。

0