public static string Decrypt(byte[] cypherText, string cnxString) { using (AesManaged aes = new AesManaged()) { AESUtilityInfo p = ReadParams(cnxString: cnxString); ICryptoTransform decryptor = aes.CreateDecryptor(p.Key, p.IV); using (MemoryStream msDecrypt = new MemoryStream(cypherText)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader swDecrypt = new StreamReader(csDecrypt)) // utf-8 { return(swDecrypt.ReadToEnd()); } } } } }
public static byte[] Encrypt(string clearText, string cnxString) { using (AesManaged aes = new AesManaged()) { byte[] tmpKey; byte[] tmpIV; AESUtilityInfo p = ReadParams(cnxString: cnxString); if (p == null) { tmpKey = aes.Key; tmpIV = aes.IV; PersistParams(aes.Key, aes.IV, cnxString: cnxString); } else { tmpKey = p.Key; tmpIV = p.IV; } ICryptoTransform encryptor = aes.CreateEncryptor(tmpKey, tmpIV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) // utf-8 { swEncrypt.Write(clearText); } return(msEncrypt.ToArray()); } } } }