在C#中,可以使用一些加密算法來實現字符串加密和解密。常用的加密算法包括對稱加密算法(如AES、DES、RC4等)和非對稱加密算法(如RSA)。
下面是一個簡單示例,演示如何使用AES算法進行字符串加密和解密:
using System;
using System.Security.Cryptography;
using System.Text;
public class AesEncryption
{
private static readonly byte[] key = Encoding.UTF8.GetBytes("encryptionkey123"); // 16 bytes key for AES
private static readonly byte[] iv = Encoding.UTF8.GetBytes("encryptioniv456"); // 16 bytes IV for AES
public static string EncryptString(string plainText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
byte[] encrypted;
using (var msEncrypt = new System.IO.MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new System.IO.StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
return Convert.ToBase64String(encrypted);
}
}
public static string DecryptString(string cipherText)
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = key;
aesAlg.IV = iv;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
string plaintext = null;
using (var msDecrypt = new System.IO.MemoryStream(cipherBytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new System.IO.StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
return plaintext;
}
}
public static void Main()
{
string original = "Hello, world!";
string encrypted = EncryptString(original);
string decrypted = DecryptString(encrypted);
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Encrypted: {0}", encrypted);
Console.WriteLine("Decrypted: {0}", decrypted);
}
}
在上面的示例中,我們使用了AES算法來加密和解密字符串。首先,我們需要定義一個16字節的密鑰和初始向量IV,然后使用這些參數創建一個Aes實例。接著,我們使用CreateEncryptor方法創建一個加密器,并使用CreateDecryptor方法創建一個解密器。最后,我們可以分別使用加密器和解密器來加密和解密字符串。