溫馨提示×

c# string如何實(shí)現(xiàn)加密解密

c#
小樊
82
2024-10-18 18:25:35
欄目: 編程語言

在C#中,可以使用System.Security.Cryptography命名空間下的類來實(shí)現(xiàn)字符串的加密和解密。以下是一個(gè)使用AES加密和解密的示例:

首先,確保已經(jīng)安裝了System.Security.Cryptography.Aes NuGet包。如果沒有安裝,可以通過以下命令安裝:

dotnet add package System.Security.Cryptography.Aes

然后,可以使用以下代碼實(shí)現(xiàn)加密和解密:

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

class AesEncryptionExample
{
    static void Main()
    {
        string key = "your-secret-key"; // 密鑰應(yīng)該是16、24或32個(gè)字符長度的字符串
        string plaintext = "Hello, World!"; // 要加密的字符串

        string encrypted = Encrypt(plaintext, key);
        Console.WriteLine("Encrypted text: " + encrypted);

        string decrypted = Decrypt(encrypted, key);
        Console.WriteLine("Decrypted text: " + decrypted);
    }

    static string Encrypt(string plaintext, string key)
    {
        byte[] iv = new byte[16]; // 初始化向量(IV)長度為16字節(jié)(AES-128)
        byte[] array;

        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = iv;

            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
                    {
                        streamWriter.Write(plaintext);
                    }
                    array = memoryStream.ToArray();
                }
            }
        }

        return Convert.ToBase64String(array);
    }

    static string Decrypt(string ciphertext, string key)
    {
        byte[] iv = new byte[16]; // 初始化向量(IV)長度為16字節(jié)(AES-128)
        byte[] array;

        using (Aes aes = Aes.Create())
        {
            aes.Key = Encoding.UTF8.GetBytes(key);
            aes.IV = iv;

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

            using (MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(ciphertext)))
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader streamReader = new StreamReader(cryptoStream))
                    {
                        array = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());
                    }
                }
            }
        }

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

請注意,這個(gè)示例使用了AES-128加密算法。你可以根據(jù)需要選擇其他加密算法,例如AES-192或AES-256。但是,密鑰和IV的長度將相應(yīng)地變化。例如,對于AES-256,密鑰應(yīng)該是32個(gè)字符長度的字符串,IV應(yīng)該是16字節(jié)(AES-128)或24字節(jié)(AES-192或AES-256)長度的字符串。

0