在ASP.NET中,使用System.IO.Stream
类进行加密和解密操作时,通常需要结合使用System.Security.Cryptography
命名空间中的加密算法。以下是一个简单的示例,展示了如何使用AES加密和解密数据。
首先,确保已经安装了System.Security.Cryptography
NuGet包。
using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace ASPNetStreamEncryption { public class StreamEncryptionHelper { private static readonly byte[] Key = Encoding.UTF8.GetBytes("your-secret-key"); // 16 bytes for AES-128, 24 bytes for AES-192, 32 bytes for AES-256 private static readonly byte[] IV = Encoding.UTF8.GetBytes("your-initial-vector"); // 16 bytes for AES public static Stream EncryptStream(Stream inputStream, Stream outputStream) { using (Aes aes = Aes.Create()) { aes.Key = Key; aes.IV = IV; using (ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV)) { return new CryptoStream(inputStream, encryptor, CryptoStreamMode.Write); } } } public static Stream DecryptStream(Stream inputStream, Stream outputStream) { using (Aes aes = Aes.Create()) { aes.Key = Key; aes.IV = IV; using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV)) { return new CryptoStream(inputStream, decryptor, CryptoStreamMode.Write); } } } } }
接下来,你可以在ASP.NET应用程序中使用这个StreamEncryptionHelper
类来加密和解密数据。例如:
public class EncryptionController : Controller { public IActionResult EncryptFile() { using (var inputStream = new FileStream("input.txt", FileMode.Open)) using (var outputStream = new FileStream("output.enc", FileMode.Create)) { Stream encryptedStream = StreamEncryptionHelper.EncryptStream(inputStream, outputStream); encryptedStream.Close(); } return Ok("File encrypted successfully."); } public IActionResult DecryptFile() { using (var inputStream = new FileStream("output.enc", FileMode.Open)) using (var outputStream = new FileStream("output.txt", FileMode.Create)) { Stream decryptedStream = StreamEncryptionHelper.DecryptStream(inputStream, outputStream); decryptedStream.Close(); } return Ok("File decrypted successfully."); } }
请注意,这个示例仅用于演示目的。在实际应用中,你需要考虑更多的安全因素,例如密钥和初始向量的存储、错误处理和异常管理等。