AesSimple. Simples Aes Clase to encrypt / decrypt configuration strings

using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace RopControls { public class AesSimple { public static string Encrypt(string plainText, string passPhrase, string saltValue) { var saltValueBytes = Encoding.ASCII.GetBytes(saltValue); var plainTextBytes = Encoding.UTF8.GetBytes(plainText); var cifrador = new AesManaged(); var password = new Rfc2898DeriveBytes(passPhrase, saltValueBytes); var key = password.GetBytes(cifrador.KeySize / 8); var iv = password.GetBytes(cifrador.BlockSize / 8); cifrador.Key = key; cifrador.IV = iv; var encryptor = cifrador.CreateEncryptor(); var memoryStream = new MemoryStream(); var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); cryptoStream.FlushFinalBlock(); var cipherTextBytes = memoryStream.ToArray(); memoryStream.Close(); cryptoStream.Close(); var cipherText = Convert.ToBase64String(cipherTextBytes); return cipherText; } public static string Decrypt(string cipherText, string passPhrase, string saltValue) { var saltValueBytes = Encoding.ASCII.GetBytes(saltValue); var cipherTextBytes = Convert.FromBase64String(cipherText); var cifrador = new AesManaged(); var password = new Rfc2898DeriveBytes(passPhrase, saltValueBytes); var key = password.GetBytes(cifrador.KeySize / 8); var iv = password.GetBytes(cifrador.BlockSize / 8); cifrador.Key = key; cifrador.IV = iv; var memoryStream = new MemoryStream(cipherTextBytes); var cryptoStream = new CryptoStream(memoryStream, cifrador.CreateDecryptor(), CryptoStreamMode.Read); var plainTextBytes = new byte[cipherTextBytes.Length]; var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); memoryStream.Close(); cryptoStream.Close(); var plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); return plainText; } public static string Decrypt(string[] array) { return Decrypt(array[0], array[1], array[2]); } public static string GetMD5(string str) { MD5 md5 = MD5CryptoServiceProvider.Create(); ASCIIEncoding encoding = new ASCIIEncoding(); byte[] stream = null; StringBuilder sb = new StringBuilder(); stream = md5.ComputeHash(encoding.GetBytes(str)); for (int i = 0; i < stream.Length; i++) sb.AppendFormat("{0:x2}", stream[i]); return sb.ToString(); } } }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.