在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方法创建一个解密器。最后,我们可以分别使用加密器和解密器来加密和解密字符串。