在C# WinForms應用程序中,有多種方法可以對數據進行加密。以下是一些建議的方法:
使用對稱加密算法(如AES):
首先,需要安裝System.Security.Cryptography命名空間。在項目中添加以下引用:
using System.Security.Cryptography;
using System.Text;
然后,可以使用AES加密和解密數據。以下是一個簡單的示例:
public static string Encrypt(string plainText, string key)
{
byte[] iv = new byte[16];
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);
}
public static string Decrypt(string cipherText, string key)
{
byte[] iv = new byte[16];
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))
{
return streamReader.ReadToEnd();
}
}
}
}
}
使用這些方法,可以對字符串進行加密和解密:
string key = "your_encryption_key";
string plainText = "Hello, World!";
string encryptedText = Encrypt(plainText, key);
string decryptedText = Decrypt(encryptedText, key);
使用非對稱加密算法(如RSA):
首先,需要安裝System.Security.Cryptography.Algorithms命名空間。在項目中添加以下引用:
using System.Security.Cryptography.Algorithms;
using System.Security.Cryptography.Encoding;
using System.Security.Cryptography.私鑰;
然后,可以使用RSA加密和解密數據。以下是一個簡單的示例:
public static string Encrypt(string plainText, RSA rsa)
{
byte[] data = Encoding.UTF8.GetBytes(plainText);
byte[] encryptedData = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
return Convert.ToBase64String(encryptedData);
}
public static string Decrypt(string cipherText, RSA rsa)
{
byte[] encryptedData = Convert.FromBase64String(cipherText);
byte[] decryptedData = rsa.Decrypt(encryptedData, RSAEncryptionPadding.Pkcs1);
return Encoding.UTF8.GetString(decryptedData);
}
使用這些方法,可以對字符串進行加密和解密:
RSA rsa = RSA.Create();
rsa.ImportSubjectPublicKeyInfo(publicKey, out _);
string key = "your_encryption_key";
string plainText = "Hello, World!";
string encryptedText = Encrypt(plainText, rsa);
string decryptedText = Decrypt(encryptedText, rsa);
請注意,為了確保數據安全,密鑰(key)應該妥善保管,不要泄露給他人。在實際應用中,可能需要考慮更安全的密鑰管理和存儲方法。