string plaintext = "The quick brown fox jumps over the lazy dog"; string key = "mysecretkey"; byte[] encryptedData; using (RijndaelManaged rijAlg = new RijndaelManaged()) { rijAlg.Key = Encoding.UTF8.GetBytes(key); rijAlg.Mode = CipherMode.ECB; // Electronic Code Book mode rijAlg.Padding = PaddingMode.PKCS7; ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV); byte[] plainData = Encoding.UTF8.GetBytes(plaintext); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { csEncrypt.Write(plainData, 0, plainData.Length); csEncrypt.FlushFinalBlock(); encryptedData = msEncrypt.ToArray(); } } } Console.WriteLine(Convert.ToBase64String(encryptedData));
string encryptedText = "0mLc3f8u3256Uli56ia06w=="; string key = "mysecretkey"; byte[] decryptedData; using (RijndaelManaged rijAlg = new RijndaelManaged()) { rijAlg.Key = Encoding.UTF8.GetBytes(key); rijAlg.Mode = CipherMode.ECB; // Electronic Code Book mode rijAlg.Padding = PaddingMode.PKCS7; ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); byte[] encryptedData = Convert.FromBase64String(encryptedText); using (MemoryStream msDecrypt = new MemoryStream(encryptedData)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (MemoryStream msPlain = new MemoryStream()) { csDecrypt.CopyTo(msPlain); decryptedData = msPlain.ToArray(); } } } } Console.WriteLine(Encoding.UTF8.GetString(decryptedData));In this example, we create a RijndaelManaged object with the same secret key, mode, and padding mode as the encryption example. We then create a decryptor object and use it to decrypt the input data. Finally, we output the decrypted data as a string. The package library used in these examples is the built-in System.Security.Cryptography namespace in .NET.