public CreateEncryptor ( ) : ICryptoTransform | ||
return | ICryptoTransform |
// Define AES key and initialization vector byte[] key = new byte[16] { 0x46, 0x3C, 0x7C, 0xDA, 0x6F, 0x4B, 0x58, 0x89, 0xC9, 0x20, 0xFC, 0x2E, 0x5D, 0x0A, 0x26, 0x3B }; byte[] iv = new byte[16] { 0x8F, 0xBD, 0xF3, 0xD8, 0x0E, 0xB4, 0xFC, 0x7C, 0x8D, 0xEA, 0x71, 0x85, 0xEF, 0xCF, 0x2B, 0x0E }; // Create RijndaelManaged object with key and IV RijndaelManaged rijndael = new RijndaelManaged(); rijndael.Key = key; rijndael.IV = iv; // Convert plaintext string to byte array string plaintext = "Hello, world!"; byte[] input = System.Text.Encoding.UTF8.GetBytes(plaintext); // Create encryptor and transform data ICryptoTransform encryptor = rijndael.CreateEncryptor(); byte[] output = encryptor.TransformFinalBlock(input, 0, input.Length); // Convert ciphertext byte array to base64-encoded string string ciphertext = Convert.ToBase64String(output); Console.WriteLine("Ciphertext: {0}", ciphertext);
// Define AES key and initialization vector byte[] key = new byte[16] { 0x46, 0x3C, 0x7C, 0xDA, 0x6F, 0x4B, 0x58, 0x89, 0xC9, 0x20, 0xFC, 0x2E, 0x5D, 0x0A, 0x26, 0x3B }; byte[] iv = new byte[16] { 0x8F, 0xBD, 0xF3, 0xD8, 0x0E, 0xB4, 0xFC, 0x7C, 0x8D, 0xEA, 0x71, 0x85, 0xEF, 0xCF, 0x2B, 0x0E }; // Create RijndaelManaged object with key and IV RijndaelManaged rijndael = new RijndaelManaged(); rijndael.Key = key; rijndael.IV = iv; // Open input and output streams FileStream input = new FileStream("input.txt", FileMode.Open, FileAccess.Read); FileStream output = new FileStream("output.enc", FileMode.Create, FileAccess.Write); // Create encryptor and transform data ICryptoTransform encryptor = rijndael.CreateEncryptor(); CryptoStream cryptoStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write); // Encrypt data from input to output byte[] buffer = new byte[4096]; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { cryptoStream.Write(buffer, 0, read); } // Close streams cryptoStream.FlushFinalBlock(); cryptoStream.Close(); input.Close(); output.Close();This example shows how to create a symmetric encryption object using RijndaelManaged and use it to encrypt the contents of a file using a key and initialization vector. The encrypted data is written to a new file with the ".enc" extension. Package library: System.Security.Cryptography.RijndaelManaged is included in the System.Security.Cryptography namespace of the .NET Framework Class Library.