Этот класс упрощает быстрое шифрование данных паролем с помощью встроенных функций .NET Framework.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
using System.Text; using System.Security.Cryptography; using System.IO; class Encryptor { public static byte[] Encrypt(byte[] input, string password) { try { TripleDESCryptoServiceProvider service = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] key = md5.ComputeHash(Encoding.ASCII.GetBytes(password)); byte[] iv = md5.ComputeHash(Encoding.ASCII.GetBytes(password)); return Transform(input, service.CreateEncryptor(key, iv)); } catch (Exception) { return new byte[0]; } } public static byte[] Decrypt(byte[] input, string password) { try { TripleDESCryptoServiceProvider service = new TripleDESCryptoServiceProvider(); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] key = md5.ComputeHash(Encoding.ASCII.GetBytes(password)); byte[] iv = md5.ComputeHash(Encoding.ASCII.GetBytes(password)); return Transform(input, service.CreateDecryptor(key, iv)); } catch (Exception) { return new byte[0]; } } public static string Encrypt(string text, string password) { byte[] input = Encoding.UTF8.GetBytes(text); byte[] output = Encrypt(input, password); return Convert.ToBase64String(output); } public static string Decrypt(string text, string password) { byte[] input = Convert.FromBase64String(text); byte[] output = Decrypt(input, password); return Encoding.UTF8.GetString(output); } private static byte[] Transform(byte[] input, ICryptoTransform CryptoTransform) { MemoryStream memStream = new MemoryStream(); CryptoStream cryptStream = new CryptoStream(memStream, CryptoTransform, CryptoStreamMode.Write); cryptStream.Write(input, 0, input.Length); cryptStream.FlushFinalBlock(); memStream.Position = 0; byte[] result = new byte[Convert.ToInt32(memStream.Length)]; memStream.Read(result, 0, Convert.ToInt32(result.Length)); memStream.Close(); cryptStream.Close(); return result; } } |