/// <summary> /// Decrypts a string /// </summary> /// <param name="text">Input string</param> /// <param name="cryptor">Cryptor</param> public static string Decrypt(string text, Cryptor cryptor) { if(string.IsNullOrEmpty(text)) throw new ArgumentException("The parameter is null or empty.", "text"); else if(cryptor == null) throw new Exception("Crypor is not defined"); var plainText = ""; var baseText = Convert.FromBase64String(text); using(var ms = new MemoryStream(baseText)) { var crypt = new RijndaelManaged(); crypt.KeySize = cryptor.KeySize; crypt.BlockSize = cryptor.BlockSize; crypt.Key = cryptor.Key; crypt.IV = cryptor.IV; crypt.Mode = cryptor.Mode; using(var cs = new CryptoStream(ms, crypt.CreateDecryptor(), CryptoStreamMode.Read)) { using(StreamReader sr = new StreamReader(cs)) plainText = sr.ReadToEnd(); } } return plainText; }
/// <summary> /// Encrypts a string /// </summary> /// <param name="text">Input string</param> /// <param name="cryptor">Cryptor</param> public static string Encrypt(string text, Cryptor cryptor) { if(string.IsNullOrEmpty(text)) throw new ArgumentException("The parameter is null or empty.","text"); else if(cryptor == null) throw new Exception("Crypor is not defined"); // Setup encryptor and encrypt the message using(var ms = new MemoryStream()) { var crypt = new RijndaelManaged() { KeySize = cryptor.KeySize, BlockSize = cryptor.BlockSize, Key = cryptor.Key, IV = cryptor.IV, Mode = cryptor.Mode }; using(var cs = new CryptoStream(ms, crypt.CreateEncryptor(), CryptoStreamMode.Write)) { using(var sw = new StreamWriter(cs)) sw.Write(text); } return Convert.ToBase64String(ms.ToArray()); } }
/// <summary> /// Encrypts the contents of a file /// </summary> /// <param name="path">Path to file</param> /// <param name="cryptor">Cryptor information</param> public static void EncryptFile(string path, string contents, Cryptor cryptor) { File.WriteAllText(path, Encrypt(contents, cryptor)); }
/// <summary> /// Decrypts the contents of a file /// </summary> /// <param name="path">Path to file</param> /// <param name="cryptor">Cryptor information</param> public static string DecryptFile(string path, Cryptor cryptor) { return Decrypt(File.ReadAllText(path), cryptor); }