Created
October 19, 2018 15:26
-
-
Save funzeye/aa1611928bce94956e1f81608f8da3cf to your computer and use it in GitHub Desktop.
Encryption and decryption in a .NET application using AES Rijndael with autogen IV. Symmetric Cipher Key accessed from config file. Recommend you encrypt key in config also.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class EncryptionService : IEncryptionService | |
{ | |
private const int Keysize = 256; | |
public string Encrypt(string plainText) | |
{ | |
var toEncryptBytes = Encoding.UTF8.GetBytes(plainText); | |
using (var provider = CreateCipher()) | |
{ | |
using (var encryptor = provider.CreateEncryptor(provider.Key, provider.IV)) | |
{ | |
using (var ms = new MemoryStream()) | |
{ | |
ms.Write(provider.IV, 0, 16); | |
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) | |
{ | |
cs.Write(toEncryptBytes, 0, toEncryptBytes.Length); | |
cs.FlushFinalBlock(); | |
} | |
return Convert.ToBase64String(ms.ToArray()); | |
} | |
} | |
} | |
} | |
private RijndaelManaged CreateCipher() | |
{ | |
var cipher = new RijndaelManaged(); | |
string encryptionKey = ConfigurationManager.AppSettings["IbanCryptoKey"].ToString(); | |
cipher.KeySize = Keysize; | |
cipher.Key = Convert.FromBase64String(encryptionKey); | |
cipher.Mode = CipherMode.CBC; | |
cipher.Padding = PaddingMode.PKCS7; | |
return cipher; | |
} | |
public string Decrypt(string cipherText) | |
{ | |
using (var provider = CreateCipher()) | |
{ | |
using (var ms = new MemoryStream(Convert.FromBase64String(cipherText))) | |
{ | |
byte[] buffer = new byte[16]; | |
ms.Read(buffer, 0, 16); | |
provider.IV = buffer; | |
using (var decryptor = provider.CreateDecryptor()) | |
{ | |
using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) | |
{ | |
using (var sr = new StreamReader(cs)) | |
{ | |
return sr.ReadToEnd(); | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment