博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用C#加密及解密字符串
阅读量:5299 次
发布时间:2019-06-14

本文共 6822 字,大约阅读时间需要 22 分钟。

1 using System;  2 using System.IO;  3 using System.Security.Cryptography;  4 using System.Text;  5   6 namespace Utility  7 {  8     ///   9     /// http://stackoverflow.com/questions/202011/encrypt-and-decrypt-a-string 10     ///  11     public class Encryptor 12     { 13         private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5"); // update by yourself 14  15         public static string Encrypt(string text) 16         { 17             var s = DateTime.Now.Year.ToString().Substring(0, 2); 18             return EncryptStringAES(text, s); 19         } 20  21         public static string Decrypt(string text) 22         { 23             var s = DateTime.Now.Year.ToString().Substring(0, 2); 24             return DecryptStringAES(text, s); 25         } 26  27         ///  28         /// Encrypt the given string using AES.  The string can be decrypted using 29         /// DecryptStringAES().  The sharedSecret parameters must match. 30         ///  31         /// The text to encrypt. 32         /// A password used to generate a key for encryption. 33         public static string EncryptStringAES(string plainText, string sharedSecret) 34         { 35             if (string.IsNullOrEmpty(plainText)) 36                 throw new ArgumentNullException("plainText"); 37             if (string.IsNullOrEmpty(sharedSecret)) 38                 throw new ArgumentNullException("sharedSecret"); 39  40             string outStr = null;                       // Encrypted string to return 41             RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data. 42  43             try 44             { 45                 // generate the key from the shared secret and the salt 46                 Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt); 47  48                 // Create a RijndaelManaged object 49                 aesAlg = new RijndaelManaged(); 50                 aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); 51  52                 // Create a decryptor to perform the stream transform. 53                 ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); 54  55                 // Create the streams used for encryption. 56                 using (MemoryStream msEncrypt = new MemoryStream()) 57                 { 58                     // prepend the IV 59                     msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); 60                     msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length); 61                     using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) 62                     { 63                         using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) 64                         { 65                             //Write all data to the stream. 66                             swEncrypt.Write(plainText); 67                         } 68                     } 69                     outStr = Convert.ToBase64String(msEncrypt.ToArray()); 70                 } 71             } 72             finally 73             { 74                 // Clear the RijndaelManaged object. 75                 if (aesAlg != null) 76                     aesAlg.Clear(); 77             } 78  79             // Return the encrypted bytes from the memory stream. 80             return outStr; 81         } 82  83         ///  84         /// Decrypt the given string.  Assumes the string was encrypted using 85         /// EncryptStringAES(), using an identical sharedSecret. 86         ///  87         /// The text to decrypt. 88         /// A password used to generate a key for decryption. 89         public static string DecryptStringAES(string cipherText, string sharedSecret) 90         { 91             if (string.IsNullOrEmpty(cipherText)) 92                 throw new ArgumentNullException("cipherText"); 93             if (string.IsNullOrEmpty(sharedSecret)) 94                 throw new ArgumentNullException("sharedSecret"); 95  96             // Declare the RijndaelManaged object 97             // used to decrypt the data. 98             RijndaelManaged aesAlg = null; 99 100             // Declare the string used to hold101             // the decrypted text.102             string plaintext = null;103 104             try105             {106                 // generate the key from the shared secret and the salt107                 Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);108 109                 // Create the streams used for decryption.110                 byte[] bytes = Convert.FromBase64String(cipherText);111                 using (MemoryStream msDecrypt = new MemoryStream(bytes))112                 {113                     // Create a RijndaelManaged object114                     // with the specified key and IV.115                     aesAlg = new RijndaelManaged();116                     aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);117                     // Get the initialization vector from the encrypted stream118                     aesAlg.IV = ReadByteArray(msDecrypt);119                     // Create a decrytor to perform the stream transform.120                     ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);121                     using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))122                     {123                         using (StreamReader srDecrypt = new StreamReader(csDecrypt))124 125                             // Read the decrypted bytes from the decrypting stream126                             // and place them in a string.127                             plaintext = srDecrypt.ReadToEnd();128                     }129                 }130             }131             finally132             {133                 // Clear the RijndaelManaged object.134                 if (aesAlg != null)135                     aesAlg.Clear();136             }137 138             return plaintext;139         }140 141         private static byte[] ReadByteArray(Stream s)142         {143             byte[] rawLength = new byte[sizeof(int)];144             if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)145             {146                 throw new SystemException("Stream did not contain properly formatted byte array");147             }148 149             byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];150             if (s.Read(buffer, 0, buffer.Length) != buffer.Length)151             {152                 throw new SystemException("Did not read byte array properly");153             }154 155             return buffer;156         }157     }158 }

 Encryp and decrypt a string via C#

转载于:https://www.cnblogs.com/cicaday/p/4008254.html

你可能感兴趣的文章
仿微博添加和删除的动画
查看>>
C#图像处理(5):无损保存图片
查看>>
Python中函数参数类型和参数绑定
查看>>
ubuntu更换开机动画
查看>>
TCP/IP网络编程之套接字类型与协议设置
查看>>
IOS 时间 日期 用法大全
查看>>
Linux -定时任务调度
查看>>
自加自减运算符的错误使用和理解【个人学习笔记,如有错误欢迎指正】
查看>>
APNS推送通知的流程
查看>>
Web程序中打开QQ、邮箱、阿里旺旺等
查看>>
前端切页面 架构配置 node npm grunt grunt合并HTML必看
查看>>
malloc与new,C++中的指针与引用,C++struct与class的区别
查看>>
移动端开发小结 移动端开发小结
查看>>
js跨域请求获得数据
查看>>
6月14日云栖精选夜读:阿里云将新增印度和印尼数据中心 加速全球化布局
查看>>
angular中的代码执行顺序和$scope.$digest();
查看>>
获取Android设备的方向
查看>>
HDU 4568 Hunter 最短路+TSP
查看>>
CentOS 7.2 部署邮件服务器(Postfix)
查看>>
Layui框架+PHP打造个人简易版网盘系统
查看>>