C# 各种加密/解密方式和Base64编码/解码

C# 各种加密/解密方式和Base64编码/解码

  • MD5加密

  • DES加密/解密

  • SHA1加密

  • RSA加密/解密

  • AES加密/解密

  • Base64编码/解码

  • RSA-SHA1 数字签名

  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using System.Data;
  5 using System.Linq;
  6 using System.Reflection;
  7 using System.Text;
  8 using System.Security.Cryptography;
  9 using System.IO;
 10 
 11 namespace Common
 12 {
 13     /// <summary>
 14     /// 加密
 15     /// </summary>
 16     public class EncryptHelper
 17     {
 18         #region MD5加密
 19         /// <summary>
 20         /// GetMD5
 21         /// </summary>
 22         /// <param name="str"></param>
 23         /// <returns></returns>
 24         public static string EncryptMD5(string source)
 25         {
 26             byte[] b = System.Text.Encoding.Default.GetBytes(source);
 27             b = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(b);
 28             string ret = "";
 29             for (int i = 0; i < b.Length; i++)
 30             {
 31                 ret += b[i].ToString("x").PadLeft(2, '0');
 32             }
 33             return ret;
 34         }
 35 
 36         /// <summary>
 37         /// 用MD5加密,全大写
 38         /// </summary>
 39         /// <param name="source">待加密字符串</param>
 40         /// <returns>加密后字符串</returns>
 41         public static string EncryptMD5ToUpper(string source)
 42         {
 43             return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, "md5").ToUpper();
 44         }
 45         #endregion
 46 
 47         #region DES加密
 48 
 49         //默认密钥向量
 50         private static byte[] Keys = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };
 51         /// <summary>
 52         /// DES加密字符串
 53         /// </summary>
 54         /// <param name="encryptString">待加密的字符串</param>
 55         /// <param name="encryptKey">加密密钥,要求为8位</param>
 56         /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
 57         public static string EncryptDES(string encryptString, string encryptKey)
 58         {
 59             try
 60             {
 61                 byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
 62                 byte[] rgbIV = Keys;
 63                 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
 64                 DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
 65                 MemoryStream mStream = new MemoryStream();
 66                 CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
 67                 cStream.Write(inputByteArray, 0, inputByteArray.Length);
 68                 cStream.FlushFinalBlock();
 69                 return Convert.ToBase64String(mStream.ToArray());
 70             }
 71             catch
 72             {
 73                 return encryptString;
 74             }
 75         }
 76 
 77         /// <summary>
 78         /// DES解密字符串
 79         /// </summary>
 80         /// <param name="decryptString">待解密的字符串</param>
 81         /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
 82         /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
 83         public static string DecryptDES(string decryptString, string decryptKey)
 84         {
 85             try
 86             {
 87                 byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
 88                 byte[] rgbIV = Keys;
 89                 byte[] inputByteArray = Convert.FromBase64String(decryptString);
 90                 DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
 91                 MemoryStream mStream = new MemoryStream();
 92                 CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
 93                 cStream.Write(inputByteArray, 0, inputByteArray.Length);
 94                 cStream.FlushFinalBlock();
 95                 return Encoding.UTF8.GetString(mStream.ToArray());
 96             }
 97             catch
 98             {
 99                 return decryptString;
100             }
101         }
102         #endregion
103 
104         #region SHA1加密
105         /// <summary>
106         /// use sha1 to encrypt string
107         /// </summary>
108         public static string EncryptSHA1(string source)
109         {
110             byte[] StrRes = Encoding.Default.GetBytes(source);
111             HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
112             StrRes = iSHA.ComputeHash(StrRes);
113             StringBuilder EnText = new StringBuilder();
114             foreach (byte iByte in StrRes)
115             {
116                 EnText.AppendFormat("{0:x2}", iByte);
117             }
118             return EnText.ToString();
119         }
120         #endregion
121 
122         #region RSA加密
123         /// <summary>
124         /// RSA加密
125         /// </summary>
126         /// <param name="publickey"></param>
127         /// <param name="content"></param>
128         /// <returns></returns>
129         public static string EncryptRSA(string publickey, string content)
130         {
131             RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
132             byte[] cipherbytes;
133             rsa.FromXmlString(publickey);
134             cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false);
135 
136             return Convert.ToBase64String(cipherbytes);
137         }
138 
139         /// <summary>
140         /// RSA解密
141         /// </summary>
142         /// <param name="privatekey"></param>
143         /// <param name="content"></param>
144         /// <returns></returns>
145         public static string DecryptRSA(string privatekey, string content)
146         {
147             RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
148             byte[] cipherbytes;
149             rsa.FromXmlString(privatekey);
150             cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
151 
152             return Encoding.UTF8.GetString(cipherbytes);
153         }
154         #endregion
155 
156         #region AES加密
157         /*
158          * 跨程序使用AES加密,需要注意运算模式和填充模式;
159          * 比如java
160          * 需要设置
161          * Mode = CipherMode.ECB; //C#默认运算模式为CBC,java默认为ECB,因此要将C#的加密方式改为ECB
162          * Padding = PaddingMode.PKCS7; //设置为PKCS7,否则解密后字符串结尾会出现多余字符
163          * 测试地址:http://www.seacha.com/tools/aes.html 
164          */
165 
166         //默认密钥向量 
167         private static byte[] _Aeskey = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
168 
169         /// <summary>
170         /// AES加密,返回Base64编码后的字符
171         /// </summary>
172         /// <param name="plainText">明文字符串</param>
173         /// <param name="strKey">密钥</param>
174         /// <returns>返回加密后的Base64编码字符串</returns>
175         public static string EncryptAES(string plainText, string strKey)
176         {
177             byte[] byteArray = Encoding.UTF8.GetBytes(plainText);
178 
179             RijndaelManaged rDel = new RijndaelManaged();
180             rDel.Key = Encoding.UTF8.GetBytes(strKey);
181             rDel.IV = _Aeskey;
182             rDel.BlockSize = 128;
183             rDel.Mode = CipherMode.ECB;//设置为ECB
184             rDel.Padding = PaddingMode.PKCS7;//设置为PKCS7,否则解密后字符串结尾会出现多余字符
185 
186             ICryptoTransform cTransform = rDel.CreateEncryptor();
187             var s = cTransform.TransformFinalBlock(byteArray, 0, byteArray.Length);
188             var encrypt = Convert.ToBase64String(s);
189             rDel.Clear();
190             return encrypt;
191         }
192         /// <summary>
193         /// AES解密,返回解密后的字符串
194         /// </summary>
195         /// <param name="cipherText">Base64编码的密文</param>
196         /// <param name="strKey">密钥</param>
197         /// <returns>返回解密后的字符串</returns>
198         public static string DecryptAES(string cipherText, string strKey)
199         {
200             byte[] byteArray = Convert.FromBase64String(cipherText);
201 
202             RijndaelManaged rDel = new RijndaelManaged();
203             rDel.Key = Encoding.UTF8.GetBytes(strKey);
204             rDel.IV = _Aeskey;
205             rDel.BlockSize = 128;
206             rDel.Mode = CipherMode.ECB;//必须设置为ECB
207             rDel.Padding = PaddingMode.PKCS7;//必须设置为PKCS7
208 
209             ICryptoTransform cTransform = rDel.CreateDecryptor();
210 
211             var s = cTransform.TransformFinalBlock(byteArray, 0, byteArray.Length);
212 
213             var decrypt = Encoding.UTF8.GetString(s);
214             rDel.Clear();
215             return decrypt;
216 
217 
218 
219         }
220         #endregion
221 
222         #region Base64编码
223         public static string EncryptBase64(string source)
224         {
225             byte[] bytes = Encoding.Default.GetBytes(source);
226             return Convert.ToBase64String(bytes);
227         }
228         public static string EncryptBase64(byte[] bytes)
229         {
230             return Convert.ToBase64String(bytes);
231         }
232         public static string DecryptBase64(string source)
233         {
234             byte[] outputb = Convert.FromBase64String(source);
235             return Encoding.Default.GetString(outputb);
236         }
237         #endregion
238 
239         #region RSA-SHA1 数字签名
240         /// <summary>
241         /// 数字签名 
242         /// </summary>
243         /// <param name="plaintext">原文</param>
244         /// <param name="privateKey">私钥</param>
245         /// <returns>Base64 签名</returns>
246         public static string HashAndSignString(string plaintext, string privateKey)
247         {
248             UTF8Encoding ByteConverter = new UTF8Encoding();
249             byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
250 
251             using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider())
252             {
253                 RSAalg.FromXmlString(privateKey);
254                 //使用SHA1进行摘要算法,生成签名
255                 byte[] encryptedData = RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider());
256                 return Convert.ToBase64String(encryptedData);
257             }
258         }
259         /// <summary>
260         /// 验证签名
261         /// </summary>
262         /// <param name="plaintext">原文</param>
263         /// <param name="SignedData">Base64 签名</param>
264         /// <param name="publicKey">公钥</param>
265         /// <returns></returns>
266         public static bool VerifySigned(string plaintext, string SignedData, string publicKey)
267         {
268             try
269             {
270                 using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider())
271                 {
272                     RSAalg.FromXmlString(publicKey);
273                     UTF8Encoding ByteConverter = new UTF8Encoding();
274                     byte[] dataToVerifyBytes = ByteConverter.GetBytes(plaintext);
275                     byte[] signedDataBytes = Convert.FromBase64String(SignedData);
276                     return RSAalg.VerifyData(dataToVerifyBytes, new SHA1CryptoServiceProvider(), signedDataBytes);
277                 }
278             }
279             catch (Exception)
280             {
281                 return false;
282             }
283         }
284         #endregion
285     } 
286 }
View Code

 

posted @ 2017-01-13 09:53  Adam-L  阅读(1202)  评论(0)    收藏  举报