1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5.  
  6. namespace Utility
  7. {
  8. /// <summary>
  9. /// http://stackoverflow.com/questions/202011/encrypt-and-decrypt-a-string
  10. /// </summary>
  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(, );
  18. return EncryptStringAES(text, s);
  19. }
  20.  
  21. public static string Decrypt(string text)
  22. {
  23. var s = DateTime.Now.Year.ToString().Substring(, );
  24. return DecryptStringAES(text, s);
  25. }
  26.  
  27. /// <summary>
  28. /// Encrypt the given string using AES. The string can be decrypted using
  29. /// DecryptStringAES(). The sharedSecret parameters must match.
  30. /// </summary>
  31. /// <param name="plainText">The text to encrypt.</param>
  32. /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
  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 / );
  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), , sizeof(int));
  60. msEncrypt.Write(aesAlg.IV, , 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. /// <summary>
  84. /// Decrypt the given string. Assumes the string was encrypted using
  85. /// EncryptStringAES(), using an identical sharedSecret.
  86. /// </summary>
  87. /// <param name="cipherText">The text to decrypt.</param>
  88. /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
  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 hold
  101. // the decrypted text.
  102. string plaintext = null;
  103.  
  104. try
  105. {
  106. // generate the key from the shared secret and the salt
  107. 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 object
  114. // with the specified key and IV.
  115. aesAlg = new RijndaelManaged();
  116. aesAlg.Key = key.GetBytes(aesAlg.KeySize / );
  117. // Get the initialization vector from the encrypted stream
  118. 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 stream
  126. // and place them in a string.
  127. plaintext = srDecrypt.ReadToEnd();
  128. }
  129. }
  130. }
  131. finally
  132. {
  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, , 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, )];
  150. if (s.Read(buffer, , 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#

使用C#加密及解密字符串的更多相关文章

  1. Linux下实现 OpenSSL 简单加密与解密字符串

    场景 shell脚本中存在明文密码 客户要求禁止使用明文密码,密码做加密处理. 方案 在网上了解到了Linux OpenSSL加密解密工具 可以指定各种加密算法为字符,文件做加密处理. 加密的案例比较 ...

  2. 使用Base64进行string的加密和解密 公钥加密—私钥签名

    使用Base64进行string的加密和解密   //字符串转bytesvar ebytes = System.Text.Encoding.Default.GetBytes(keyWord);//by ...

  3. 读取本地json文件,转出为指定格式json 使用Base64进行string的加密和解密

    读取本地json文件,转出为指定格式json   引用添加Json.Net 引用命名空间 using Newtonsoft.Json //读取自定目录下的json文件StreamReader sr = ...

  4. ASP.NET加密和解密数据库连接字符串

    大家知道,在应用程序中进行数据库操作需要连接字符串,而如果没有连接字符串,我们就无法在应用程序中完成检索数据,创建数据等一系列的数据库操作.当有人想要获取你程序中的数据库信息,他首先看到的可能会是We ...

  5. (译)利用ASP.NET加密和解密Web.config中连接字符串

    介绍 这篇文章我将介绍如何利用ASP.NET来加密和解密Web.config中连接字符串 背景描述 在以前的博客中,我写了许多关于介绍 Asp.net, Gridview, SQL Server, A ...

  6. 利用ASP.NET加密和解密Web.config中连接字符串

    摘自:博客园 介绍 这篇文章我将介绍如何利用ASP.NET来加密和解密Web.config中连接字符串 背景描述 在以前的博客中,我写了许多关于介绍 Asp.net, Gridview, SQL Se ...

  7. PHP的加密解密字符串函数

    程序中经常使用的PHP加密解密字符串函数 代码如下: /********************************************************************* 函数 ...

  8. PHP加密解密字符串

    项目中有时我们需要使用PHP将特定的信息进行加密,也就是通过加密算法生成一个加密字符串,这个加密后的字符串可以通过解密算法进行解密,便于程序对解密后的信息进行处理. 最常见的应用在用户登录以及一些AP ...

  9. MVC项目实践,在三层架构下实现SportsStore-10,连接字符串的加密和解密

    SportsStore是<精通ASP.NET MVC3框架(第三版)>中演示的MVC项目,在该项目中涵盖了MVC的众多方面,包括:使用DI容器.URL优化.导航.分页.购物车.订单.产品管 ...

随机推荐

  1. vue里computed的get和set

    computed里的对象有get和set方法. get是当该对象所依赖的变量发生变化是执行,重新returncomputed结果. set是该对象的值变化时会执行,并且将变化的结果作为参数传进set里 ...

  2. python全栈开发* 02 知识点汇总 * 180531

    运算符和编码 一  格式化输出 1  .输入  name ,age , job , hobby. 输出  :   ---------------  info of Mary  ------------ ...

  3. android json解析及简单例子+Android与服务器端数据交互+Android精彩案例【申明:来源于网络】

    android json解析及简单例子+Android与服务器端数据交互+Android精彩案例[申明:来源于网络] android json解析及简单例子:http://www.open-open. ...

  4. HDU 1241 - Oil Deposits - [BFS]

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1241 题意: 求某块平面上,连通块的数量.一个油田格子若周围八个方向也有一个油田格子,则认为两者相连通 ...

  5. 点击图片img提交form表单

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/stri ...

  6. 浅谈Java中的关键字

    谈到final关键字,想必很多人都不陌生,在使用匿名内部类的时候可能会经常用到final关键字.另外,Java中的String类就是一个final类,那么今天我们就来了解final这个关键字的用法. ...

  7. jenkins使用笔记

    jenkins动态在构建的时候给脚本传递参数 1.任务  >General > 参数化构建过程 >选项参数 2.把变量传递给shell脚本 3.构建的时候给参数赋值 4.shell脚 ...

  8. 去掉Tomcat的管理页面

    一.去掉Tomcat的管理页面 一.方法一:如果要去掉默认该界面,可以重命名tomcat目录下的ROOT,并新建空文件夹命名为ROOT 1.刚打开tomcat,默认访问的是tomcat管理页面,比如X ...

  9. DAX/PowerBI系列 - 累计总计(Cumulative Total)

    DAX/PowerBI系列 - 累计总计(Cumulative Total) 2017/07/23 更新:B列公式(见最后) 难度: ★★☆☆☆(2星) 适用: ★★☆☆☆(2星) 概况: 这个模式普 ...

  10. 取数游戏II

    传送门 #include <bits/stdc++.h> using namespace std; #define ll long long #define re register #de ...