Encryp and decrypt a string

  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(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         /// <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 / 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         /// <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 / 8);
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, 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 }
时间: 2024-08-02 04:49:19

Encryp and decrypt a string的相关文章

A very simple C++ module to encrypt/decrypt strings based on B64 and Vigenere ciper.

https://github.com/philipperemy/easy-encryption Easy Encryption A very simple yet powerful standalone C++ module (API) to encrypt/decrypt strings based on B64 and Vigenere ciper (symmetric cipher). It works as follows: Alice encodes in base64 the mes

hdu 4787 GRE Words Revenge 在线AC自动机

hdu 4787 GRE Words Revenge Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 327680/327680 K (Java/Others)Total Submission(s): 2505    Accepted Submission(s): 614 Problem Description Now Coach Pang is preparing for the Graduate Record Examina

HDU4787 GRE Words Revenge(AC自动机 分块 合并)

题目 Source http://acm.hdu.edu.cn/showproblem.php?pid=4787 Description Now Coach Pang is preparing for the Graduate Record Examinations as George did in 2011. At each day, Coach Pang can: "+w": learn a word w "?p": read a paragraph p, an

设计模式实战应用之五:工厂方法模式

工厂方法模式的定义        工厂方法模式的应用相当广泛. 工厂方法模式在 Java API 中的应用比比皆是:java.util.Collection 接口的 iterator 方法就是一个非常著名的工厂方法模式的演示样例:java.net.URLStreamHandlerFactory 的 createURLStreamHandler(String protocol)  也是工厂方法模式的一个非常经典的应用,URLStreamHandlerFactory 定义了一个用来创建 URLStr

加密解密大汇总

在项目开发中,出于系统安全考虑,我们总会想到使用加密解密进行处理.首先保证的一点就是数据被窃取后,不能使其正常阅读.其次,就是防止接口随意调用. (PS:鄙人目前就想到了这两点好处,如果还有什么优点,欢迎给位补充o(^▽^)o) 接下来就说几个常用的加密算法:DES加密算法,AES加密算法,RSA加密算法,Base64加密算法,MD5加密算法,SHA1加密算法 1.DES加密算法 加密方式---- 使用异或,置换,代换,移位四种基本运算进行16轮循环加密而成. 共分为一般加密和三重加密>> D

de4dot FAQ

How to deobfuscate but make sure metadata tokens stay the same? --preserve-tokens will preserve all important metadata tokens, the #US and #Blob heaps, and keep junk data in signatures. --keep-types should normally also be used. If used, no obfuscato

C# 加密–RSA前端与后台的加密&amp;解密

1. 前言 本问是根据网上很多文章的总结得到的. 2. 介绍 RSA加密算法是一种非对称加密算法. 对极大整数做因数分解的难度决定了RSA算法的可靠性.换言之,对一极大整数做因数分解愈困难,RSA算法愈可靠.假如有人找到一种快速因数分解的算法的话,那么用RSA加密的信息的可靠性就肯定会极度下降.但找到这样的算法的可能性是非常小的.今天只有短的RSA钥匙才可能被强力方式解破.到2016年为止,世界上还没有任何可靠的攻击RSA算法的方式.只要其钥匙的长度足够长,用RSA加密的信息实际上是不能被解破的

创建加密应用程序

此演练提供用于对内容进行加密和解密的代码示例.这些代码示例是专为 Windows 窗体应用程序设计的.此应用程序并不演示实际方案(如使用智能卡),而是演示加密和解密的基础. 此演练使用下列加密准则: 使用 RijndaelManaged 类(一种对称算法)并利用它自动生成的 Key 和 IV 对数据进行加密和解密. 使用 RSACryptoServiceProvider(一种不对称算法)对 RijndaelManaged 加密的数据的密钥进行加密和解密.不对称算法最适用于少量数据,如密钥. 注意

Python网页小爬虫

最近右胳膊受伤,打了石膏在家休息.为了实现之前的想法,就用左手打字.写代码,查资料完成了这个资源小爬虫.网页爬虫, 最主要的是协议分析(必须要弄清楚自己的目的),另外就是要考虑对爬取的数据归类,存储.这是一个在线歌曲网站的爬虫,网站名 字就不说了,此贴目的是技术交流,请不用做其他用途! 相关技术点:http协议.js.AES.文件.文件夹操作.正则表达式.数据库技术.SQL -------------------------------------------分割线 以下 为设计思路------