using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace ZJ_BYD.Untils { public static class DesHelper { //例 // string resule = EncryptDES( "这是一个测试字符串!!", "temp" ); //Console.WriteLine( resule ); //输出 UQYZz2CHw06AYY4YoySTiefE1KY3JE0XBOpe65PeUF8= //Console.WriteLine( DecryptDES( resule, "temp" ) ); //输出 这是一个测试字符串!! /// /// 加密 /// /// /// /// public static string EncryptStringToBytes_Aes(string plainText, string Key) { //取 32 位 key Key = Key.PadLeft(32, '0').Substring(0, 32); //设置加密的 key,其值来自参数 byte[] key = Encoding.UTF8.GetBytes(Key); var IV = Key.PadLeft(16, '0').Substring(0, 16); //设置加密的 iv 向量,这里使用硬编码演示 byte[] iv = Encoding.UTF8.GetBytes(IV);//"temp" byte[] encrypted; // Create an Aes object // with the specified key and IV. using (Aes aesAlg = Aes.Create()) { aesAlg.Key = key; aesAlg.IV = iv; // Create an encryptor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } // Return the encrypted bytes from the memory stream. return Convert.ToBase64String(encrypted); } /// /// 解密 /// /// /// /// public static string DecryptStringFromBytes_Aes(string cipherText, string Key) { try { //取 32 位 key Key = Key.PadLeft(32, '0').Substring(0, 32); //设置加密的 key,其值来自参数 byte[] key = Encoding.UTF8.GetBytes(Key); var IV = Key.PadLeft(16, '0').Substring(0, 16); //设置加密的 iv 向量,这里使用硬编码演示 byte[] iv = Encoding.UTF8.GetBytes(IV);//"temp" byte[] context = Convert.FromBase64String(cipherText); // Declare the string used to hold // the decrypted text. string plaintext = null; // Create an Aes object // with the specified key and IV. using (Aes aesAlg = Aes.Create()) { aesAlg.Key = key; aesAlg.IV = iv; // Create a decryptor to perform the stream transform. ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for decryption. using (MemoryStream msDecrypt = new MemoryStream(context)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { // Read the decrypted bytes from the decrypting stream // and place them in a string. plaintext = srDecrypt.ReadToEnd(); } } } } return plaintext; } catch (Exception) { return ""; } } } }