在ASP.NET MVC环境中使用加密与解密
时间: 2024-03-16 18:46:36 浏览: 13
在ASP.NET MVC环境中,可以使用System.Security.Cryptography命名空间中的类来实现加密和解密。
例如,可以使用SymmetricAlgorithm类来加密和解密数据。以下是一个示例代码:
```
public static string Encrypt(string plainText, string key)
{
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
SymmetricAlgorithm algorithm = Aes.Create();
algorithm.Key = keyBytes;
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
algorithm.CreateEncryptor(),
CryptoStreamMode.Write);
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] encryptedBytes = memoryStream.ToArray();
return Convert.ToBase64String(encryptedBytes);
}
public static string Decrypt(string encryptedText, string key)
{
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
SymmetricAlgorithm algorithm = Aes.Create();
algorithm.Key = keyBytes;
MemoryStream memoryStream = new MemoryStream(encryptedBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
algorithm.CreateDecryptor(),
CryptoStreamMode.Read);
byte[] plainBytes = new byte[encryptedBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);
return Encoding.UTF8.GetString(plainBytes, 0, decryptedByteCount);
}
```
在此示例中,Encrypt方法接受明文和密钥作为输入,并返回加密后的文本。Decrypt方法接受加密后的文本和密钥作为输入,并返回解密后的明文。
请注意,在实际使用中,需要注意密钥的安全性和存储方式。密钥的安全性对加密的强度有很大的影响。