zoukankan      html  css  js  c++  java
  • C# 加密大全

    自己整理的常用加密方式。

      1 using System;
      2 using System.Collections.Generic;
      3 using System.IO;
      4 using System.Linq;
      5 using System.Security.Cryptography;
      6 using System.Text;
      7 using System.Web;
      8 
      9 namespace WebDemo.Until
     10 {
     11 
     12     public class EncryptHelper
     13     {
     14         #region DES对称加密解密
     15 
     16         /// <summary> 加密字符串
     17         /// </summary> 
     18         /// <param name="strText">需被加密的字符串</param> 
     19         /// <param name="strEncrKey">密钥</param> 
     20         /// <returns></returns> 
     21         public static string DesEncrypt(string strText, string strEncrKey)
     22         {
     23             try
     24             {
     25                 byte[] byKey = null;
     26                 byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
     27 
     28                 byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
     29                 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     30                 byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
     31                 MemoryStream ms = new MemoryStream();
     32                 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
     33                 cs.Write(inputByteArray, 0, inputByteArray.Length);
     34                 cs.FlushFinalBlock();
     35                 return Convert.ToBase64String(ms.ToArray());
     36             }
     37             catch
     38             {
     39                 return "";
     40             }
     41         }
     42 
     43         /// <summary> 解密字符串
     44         /// </summary> 
     45         /// <param name="strText">需被解密的字符串</param> 
     46         /// <param name="sDecrKey">密钥</param> 
     47         /// <returns></returns> 
     48         public static string DesDecrypt(string strText, string sDecrKey)
     49         {
     50             try
     51             {
     52                 byte[] byKey = null;
     53                 byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
     54                 byte[] inputByteArray = new Byte[strText.Length];
     55 
     56                 byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
     57                 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     58                 inputByteArray = Convert.FromBase64String(strText);
     59                 MemoryStream ms = new MemoryStream();
     60                 CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
     61                 cs.Write(inputByteArray, 0, inputByteArray.Length);
     62                 cs.FlushFinalBlock();
     63                 Encoding encoding = new UTF8Encoding();
     64                 return encoding.GetString(ms.ToArray());
     65             }
     66             catch
     67             {
     68                 return null;
     69             }
     70         }
     71 
     72         /// <summary> 加密文件
     73         ///
     74         /// </summary> 
     75         /// <param name="m_InFilePath">原路径</param> 
     76         /// <param name="m_OutFilePath">加密后的文件路径</param> 
     77         /// <param name="strEncrKey">密钥</param> 
     78         public static void DesEncryptFile(string m_InFilePath, string m_OutFilePath, string strEncrKey)
     79         {
     80             try
     81             {
     82                 byte[] byKey = null;
     83                 byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
     84 
     85                 byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
     86                 FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
     87                 FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
     88                 fout.SetLength(0);
     89                 //Create variables to help with read and write. 
     90                 byte[] bin = new byte[100]; //This is intermediate storage for the encryption. 
     91                 long rdlen = 0; //This is the total number of bytes written. 
     92                 long totlen = fin.Length; //This is the total length of the input file. 
     93                 int len; //This is the number of bytes to be written at a time.
     94 
     95                 DES des = new DESCryptoServiceProvider();
     96                 CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
     97 
     98                 //Read from the input file, then encrypt and write to the output file. 
     99                 while (rdlen < totlen)
    100                 {
    101                     len = fin.Read(bin, 0, 100);
    102                     encStream.Write(bin, 0, len);
    103                     rdlen = rdlen + len;
    104                 }
    105                 encStream.Close();
    106                 fout.Close();
    107                 fin.Close();
    108             }
    109             catch
    110             {
    111             }
    112 
    113         }
    114 
    115         /// <summary> 解密文件
    116         /// 
    117         /// </summary> 
    118         /// <param name="m_InFilePath">被解密路径</param> 
    119         /// <param name="m_OutFilePath">解密后的路径</param> 
    120         /// <param name="sDecrKey">密钥</param> 
    121         public static void DesDecryptFile(string m_InFilePath, string m_OutFilePath, string sDecrKey)
    122         {
    123             try
    124             {
    125                 byte[] byKey = null;
    126                 byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
    127 
    128                 byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
    129                 FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
    130                 FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
    131                 fout.SetLength(0);
    132                 //Create variables to help with read and write. 
    133                 byte[] bin = new byte[100]; //This is intermediate storage for the encryption. 
    134                 long rdlen = 0; //This is the total number of bytes written. 
    135                 long totlen = fin.Length; //This is the total length of the input file. 
    136                 int len; //This is the number of bytes to be written at a time.
    137 
    138                 DES des = new DESCryptoServiceProvider();
    139                 CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
    140 
    141                 //Read from the input file, then encrypt and write to the output file. 
    142                 while (rdlen < totlen)
    143                 {
    144                     len = fin.Read(bin, 0, 100);
    145                     encStream.Write(bin, 0, len);
    146                     rdlen = rdlen + len;
    147                 }
    148                 encStream.Close();
    149                 fout.Close();
    150                 fin.Close();
    151             }
    152             catch
    153             {
    154             }
    155         }
    156         #endregion
    157 
    158         #region 3DES对称加密解密
    159         /// <summary>
    160         ///3DES加密
    161         /// </summary>
    162         /// <param name="originalValue">加密数据</param>
    163         /// <param name="key">24位字符的密钥字符串</param>
    164         /// <param name="IV">8位字符的初始化向量字符串</param>
    165         /// <returns></returns>
    166         public static string DESEncrypt(string originalValue, string key, string IV)
    167         {
    168             SymmetricAlgorithm sa = new TripleDESCryptoServiceProvider();
    169             sa.Mode = CipherMode.CBC;
    170             sa.Padding = PaddingMode.PKCS7;
    171             sa.Key = Encoding.UTF8.GetBytes(key);
    172             sa.IV = Encoding.UTF8.GetBytes(IV);
    173             ICryptoTransform ct = sa.CreateEncryptor();
    174             byte[] byt = Encoding.UTF8.GetBytes(originalValue);
    175             MemoryStream ms = new MemoryStream();
    176             CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
    177             cs.Write(byt, 0, byt.Length);
    178             cs.FlushFinalBlock();
    179             cs.Close();
    180             return Convert.ToBase64String(ms.ToArray());
    181         }
    182         /// <summary>
    183         /// 3DES解密
    184         /// </summary>
    185         /// <param name="data">解密数据</param>
    186         /// <param name="key">24位字符的密钥字符串(需要和加密时相同)</param>
    187         /// <param name="iv">8位字符的初始化向量字符串(需要和加密时相同)</param>
    188         /// <returns></returns>
    189         public static string DESDecrypst(string data, string key, string IV)
    190         {
    191             SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
    192             mCSP.Mode = CipherMode.CBC;
    193             mCSP.Padding = PaddingMode.PKCS7;
    194             mCSP.Key = Encoding.UTF8.GetBytes(key);
    195             mCSP.IV = Encoding.UTF8.GetBytes(IV);
    196             ICryptoTransform ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
    197             byte[] byt = Convert.FromBase64String(data);
    198             MemoryStream ms = new MemoryStream();
    199             CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
    200             cs.Write(byt, 0, byt.Length);
    201             cs.FlushFinalBlock();
    202             cs.Close();
    203             return Encoding.UTF8.GetString(ms.ToArray());
    204         }
    205         #endregion
    206 
    207         #region AES RijndaelManaged加密解密
    208 
    209         private static readonly string Default_AES_Key = "@#kim123";
    210         private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79,
    211                                              0x53,0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };
    212         public static string AES_Encrypt(string encryptString)
    213         {
    214             return AES_Encrypt(encryptString, Default_AES_Key);
    215         }
    216 
    217         public static string AES_Decrypt(string decryptString)
    218         {
    219             return AES_Decrypt(decryptString, Default_AES_Key);
    220         }
    221 
    222         #region AES(CBC)有向量(IV)
    223         /// <summary>对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法)
    224         /// 
    225         /// </summary>
    226         /// <param name="encryptString">待加密字符串</param>
    227         /// <param name="encryptKey">加密密钥,须半角字符</param>
    228         /// <returns>加密结果字符串</returns>
    229         public static string AES_Encrypt(string encryptString, string encryptKey)
    230         {
    231             encryptKey = GetSubString(encryptKey, 32, "");
    232             encryptKey = encryptKey.PadRight(32, ' ');
    233 
    234             RijndaelManaged rijndaelProvider = new RijndaelManaged();
    235             rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
    236             rijndaelProvider.IV = Keys;
    237             ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
    238 
    239             byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
    240             byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
    241 
    242             return Convert.ToBase64String(encryptedData);
    243         }
    244 
    245         /// <summary> 对称加密算法AES RijndaelManaged解密字符串
    246         ///
    247         /// </summary>
    248         /// <param name="decryptString">待解密的字符串</param>
    249         /// <param name="decryptKey">解密密钥,和加密密钥相同</param>
    250         /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
    251         public static string AES_Decrypt(string decryptString, string decryptKey)
    252         {
    253             try
    254             {
    255                 decryptKey = GetSubString(decryptKey, 32, "");
    256                 decryptKey = decryptKey.PadRight(32, ' ');
    257 
    258                 RijndaelManaged rijndaelProvider = new RijndaelManaged();
    259                 rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
    260                 rijndaelProvider.IV = Keys;
    261                 ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
    262 
    263                 byte[] inputData = Convert.FromBase64String(decryptString);
    264                 byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
    265 
    266                 return Encoding.UTF8.GetString(decryptedData);
    267             }
    268             catch
    269             {
    270                 return string.Empty;
    271             }
    272         }
    273         #endregion
    274 
    275         #region AES(ECB)无向量(IV)
    276         /// <summary>  
    277         /// AES加密(无向量)  
    278         /// </summary>  
    279         /// <param name="plainBytes">被加密的明文</param>  
    280         /// <param name="key">密钥 32 </param>  
    281         /// <returns>密文</returns>  
    282         public static string AESEncryptECB(string encryptString, string encryptKey)
    283         {
    284             try
    285             {
    286                 encryptKey = GetSubString(encryptKey, 32, "");
    287                 encryptKey = encryptKey.PadRight(32, ' ');
    288 
    289                 RijndaelManaged rijndaelProvider = new RijndaelManaged();
    290                 rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
    291                 rijndaelProvider.Mode = CipherMode.ECB;
    292                 rijndaelProvider.Padding = PaddingMode.PKCS7;
    293                 ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
    294                 byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
    295                 byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
    296                 return Convert.ToBase64String(encryptedData);
    297             }
    298             catch (Exception ex)
    299             {
    300                 return ex.Message;
    301             }
    302         }
    303 
    304 
    305         /// <summary>  
    306         /// AES解密(无向量)  
    307         /// </summary>  
    308         /// <param name="decryptString">被加密的明文</param>  
    309         /// <param name="decryptKey">密钥</param>  
    310         /// <returns>明文</returns>  
    311         public static string AESDecryptECB(string decryptString, string decryptKey)
    312         {
    313             try
    314             {
    315                 decryptKey = GetSubString(decryptKey, 32, "");
    316                 decryptKey = decryptKey.PadRight(32, ' ');
    317 
    318                 RijndaelManaged rijndaelProvider = new RijndaelManaged();
    319                 rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 32));
    320                 rijndaelProvider.Mode = CipherMode.ECB;
    321                 rijndaelProvider.Padding = PaddingMode.PKCS7;
    322                 ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
    323                 byte[] inputData = Convert.FromBase64String(decryptString);
    324                 byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
    325                 return Encoding.UTF8.GetString(decryptedData);
    326             }
    327             catch (Exception ex)
    328             {
    329                 return ex.Message;
    330             }
    331         }
    332         #endregion
    333 
    334 
    335         /// <summary>
    336         /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
    337         /// </summary>
    338         /// <param name="sourceString">源字符串</param>
    339         /// <param name="length">所取字符串字节长度</param>
    340         /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
    341         /// <returns>某字符串的一部分</returns>
    342         private static string GetSubString(string sourceString, int length, string tailString)
    343         {
    344             return GetSubString(sourceString, 0, length, tailString);
    345         }
    346 
    347         /// <summary>
    348         /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
    349         /// </summary>
    350         /// <param name="sourceString">源字符串</param>
    351         /// <param name="startIndex">索引位置,以0开始</param>
    352         /// <param name="length">所取字符串字节长度</param>
    353         /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
    354         /// <returns>某字符串的一部分</returns>
    355         private static string GetSubString(string sourceString, int startIndex, int length, string tailString)
    356         {
    357             string myResult = sourceString;
    358 
    359             //当是日文或韩文时(注:中文的范围:u4e00 - u9fa5, 日文在u0800 - u4e00, 韩文为xAC00-xD7A3)
    360             if (System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[u0800-u4e00]+") ||
    361                 System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[xAC00-xD7A3]+"))
    362             {
    363                 //当截取的起始位置超出字段串长度时
    364                 if (startIndex >= sourceString.Length)
    365                 {
    366                     return string.Empty;
    367                 }
    368                 else
    369                 {
    370                     return sourceString.Substring(startIndex,
    371                                                    ((length + startIndex) > sourceString.Length) ? (sourceString.Length - startIndex) : length);
    372                 }
    373             }
    374 
    375             //中文字符,如"中国人民abcd123"
    376             if (length <= 0)
    377             {
    378                 return string.Empty;
    379             }
    380             byte[] bytesSource = Encoding.Default.GetBytes(sourceString);
    381 
    382             //当字符串长度大于起始位置
    383             if (bytesSource.Length > startIndex)
    384             {
    385                 int endIndex = bytesSource.Length;
    386 
    387                 //当要截取的长度在字符串的有效长度范围内
    388                 if (bytesSource.Length > (startIndex + length))
    389                 {
    390                     endIndex = length + startIndex;
    391                 }
    392                 else
    393                 {   //当不在有效范围内时,只取到字符串的结尾
    394                     length = bytesSource.Length - startIndex;
    395                     tailString = "";
    396                 }
    397 
    398                 int[] anResultFlag = new int[length];
    399                 int nFlag = 0;
    400                 //字节大于127为双字节字符
    401                 for (int i = startIndex; i < endIndex; i++)
    402                 {
    403                     if (bytesSource[i] > 127)
    404                     {
    405                         nFlag++;
    406                         if (nFlag == 3)
    407                         {
    408                             nFlag = 1;
    409                         }
    410                     }
    411                     else
    412                     {
    413                         nFlag = 0;
    414                     }
    415                     anResultFlag[i] = nFlag;
    416                 }
    417                 //最后一个字节为双字节字符的一半
    418                 if ((bytesSource[endIndex - 1] > 127) && (anResultFlag[length - 1] == 1))
    419                 {
    420                     length = length + 1;
    421                 }
    422 
    423                 byte[] bsResult = new byte[length];
    424                 Array.Copy(bytesSource, startIndex, bsResult, 0, length);
    425                 myResult = Encoding.Default.GetString(bsResult);
    426                 myResult = myResult + tailString;
    427 
    428                 return myResult;
    429             }
    430 
    431             return string.Empty;
    432 
    433         }
    434 
    435         /// <summary>
    436         /// 加密文件流
    437         /// </summary>
    438         /// <param name="fs"></param>
    439         /// <returns></returns>
    440         public static CryptoStream AES_EncryptStrream(FileStream fs, string decryptKey)
    441         {
    442             decryptKey = GetSubString(decryptKey, 32, "");
    443             decryptKey = decryptKey.PadRight(32, ' ');
    444 
    445             RijndaelManaged rijndaelProvider = new RijndaelManaged();
    446             rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
    447             rijndaelProvider.IV = Keys;
    448 
    449             ICryptoTransform encrypto = rijndaelProvider.CreateEncryptor();
    450             CryptoStream cytptostreamEncr = new CryptoStream(fs, encrypto, CryptoStreamMode.Write);
    451             return cytptostreamEncr;
    452         }
    453 
    454         /// <summary>
    455         /// 解密文件流
    456         /// </summary>
    457         /// <param name="fs"></param>
    458         /// <returns></returns>
    459         public static CryptoStream AES_DecryptStream(FileStream fs, string decryptKey)
    460         {
    461             decryptKey = GetSubString(decryptKey, 32, "");
    462             decryptKey = decryptKey.PadRight(32, ' ');
    463 
    464             RijndaelManaged rijndaelProvider = new RijndaelManaged();
    465             rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
    466             rijndaelProvider.IV = Keys;
    467             ICryptoTransform Decrypto = rijndaelProvider.CreateDecryptor();
    468             CryptoStream cytptostreamDecr = new CryptoStream(fs, Decrypto, CryptoStreamMode.Read);
    469             return cytptostreamDecr;
    470         }
    471 
    472         /// <summary>
    473         /// 对指定文件加密
    474         /// </summary>
    475         /// <param name="InputFile"></param>
    476         /// <param name="OutputFile"></param>
    477         /// <returns></returns>
    478         public static bool AES_EncryptFile(string InputFile, string OutputFile)
    479         {
    480             try
    481             {
    482                 string decryptKey = "www.iqidi.com";
    483 
    484                 FileStream fr = new FileStream(InputFile, FileMode.Open);
    485                 FileStream fren = new FileStream(OutputFile, FileMode.Create);
    486                 CryptoStream Enfr = AES_EncryptStrream(fren, decryptKey);
    487                 byte[] bytearrayinput = new byte[fr.Length];
    488                 fr.Read(bytearrayinput, 0, bytearrayinput.Length);
    489                 Enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
    490                 Enfr.Close();
    491                 fr.Close();
    492                 fren.Close();
    493             }
    494             catch
    495             {
    496                 //文件异常
    497                 return false;
    498             }
    499             return true;
    500         }
    501 
    502         /// <summary>
    503         /// 对指定的文件解压缩
    504         /// </summary>
    505         /// <param name="InputFile"></param>
    506         /// <param name="OutputFile"></param>
    507         /// <returns></returns>
    508         public static bool AES_DecryptFile(string InputFile, string OutputFile)
    509         {
    510             try
    511             {
    512                 string decryptKey = "www.iqidi.com";
    513                 FileStream fr = new FileStream(InputFile, FileMode.Open);
    514                 FileStream frde = new FileStream(OutputFile, FileMode.Create);
    515                 CryptoStream Defr = AES_DecryptStream(fr, decryptKey);
    516                 byte[] bytearrayoutput = new byte[1024];
    517                 int m_count = 0;
    518 
    519                 do
    520                 {
    521                     m_count = Defr.Read(bytearrayoutput, 0, bytearrayoutput.Length);
    522                     frde.Write(bytearrayoutput, 0, m_count);
    523                     if (m_count < bytearrayoutput.Length)
    524                         break;
    525                 } while (true);
    526 
    527                 Defr.Close();
    528                 fr.Close();
    529                 frde.Close();
    530             }
    531             catch
    532             {
    533                 //文件异常
    534                 return false;
    535             }
    536             return true;
    537         }
    538 
    539         #endregion
    540 
    541         #region RSA加密 解密
    542 
    543         /// <summary>RSA加密
    544         /// 
    545         /// </summary>
    546         /// <param name="plaintext">明文</param>
    547         /// <param name="publicKey">公钥</param>
    548         /// <returns>密文字符串</returns>
    549         public static string EncryptByRSA(string plaintext, string publicKey)
    550         {
    551             try
    552             {
    553                 UnicodeEncoding ByteConverter = new UnicodeEncoding();
    554                 byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
    555                 using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
    556                 {
    557                     RSA.FromXmlString(publicKey);
    558                     byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false);
    559                     return Convert.ToBase64String(encryptedData);
    560                 }
    561             }
    562             catch (Exception)
    563             {
    564                 return null;
    565             }
    566 
    567         }
    568 
    569 
    570         /// <summary> RSA解密
    571         ///
    572         /// </summary>
    573         /// <param name="ciphertext">密文</param>
    574         /// <param name="privateKey">私钥</param>
    575         /// <returns>明文字符串</returns>
    576         public static string DecryptByRSA(string ciphertext, string privateKey)
    577         {
    578             try
    579             {
    580                 UnicodeEncoding byteConverter = new UnicodeEncoding();
    581                 using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
    582                 {
    583                     RSA.FromXmlString(privateKey);
    584                     byte[] encryptedData = Convert.FromBase64String(ciphertext);
    585                     byte[] decryptedData = RSA.Decrypt(encryptedData, false);
    586                     return byteConverter.GetString(decryptedData);
    587                 }
    588             }
    589             catch (Exception)
    590             {
    591                 return null;
    592             }
    593 
    594         }
    595 
    596 
    597         /// <summary>生成RSA加密 解密的 密钥
    598         /// 生成的key就是 方法EncryptByRSA与DecryptByRSA用的key了
    599         /// </summary>
    600         /// <param name="path">要生成的密钥文件的路径(文件夹)</param>
    601         public static void getRSAKey(string path)
    602         {
    603             RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    604             string datetimestr = System.DateTime.Now.ToString("yyyyMMddHHmmss");
    605             using (StreamWriter writer = new StreamWriter("RSA解密_PrivateKey_" + datetimestr + ".xml"))  //这个文件要保密...
    606             {
    607                 writer.WriteLine(rsa.ToXmlString(true));
    608             }
    609             using (StreamWriter writer = new StreamWriter("RSA加密_PublicKey_" + datetimestr + ".xml"))
    610             {
    611                 writer.WriteLine(rsa.ToXmlString(false));
    612             }
    613         }
    614         #endregion
    615 
    616         #region Base64加密解密
    617 
    618         /// <summary>
    619         /// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。
    620         /// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 ,
    621         /// 這樣共有62個字元,用來作為開始的64個數字,最後兩個用來作為數字的符號在不同的
    622         /// 系統中而不同。
    623         /// Base64加密
    624         /// </summary>
    625         /// <param name="str"></param>
    626         /// <returns></returns>
    627         public static string Base64Encrypt(string str)
    628         {
    629             byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
    630             return Convert.ToBase64String(encbuff);
    631         }
    632 
    633         /// <summary>
    634         /// Base64解密
    635         /// </summary>
    636         /// <param name="str"></param>
    637         /// <returns></returns>
    638         public static string Base64Decrypt(string str)
    639         {
    640             byte[] decbuff = Convert.FromBase64String(str);
    641             return System.Text.Encoding.UTF8.GetString(decbuff);
    642         }
    643         #endregion
    644 
    645         #region MD5
    646         /// <summary>
    647 
    648         /// 获得32位的MD5加密
    649         /// </summary>
    650         /// <param name="input"></param>
    651         /// <returns></returns>
    652         public static string GetMD5_32(string input)
    653         {
    654             MD5 md5 = MD5.Create();
    655             byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(input));
    656             StringBuilder sb = new StringBuilder();
    657             for (int i = 0; i < data.Length; i++)
    658             {
    659                 sb.AppendFormat("{0:X2}", data[i]);
    660             }
    661             return sb.ToString();
    662         }
    663 
    664         /// <summary>
    665         /// 获得16位的MD5加密
    666         /// </summary>
    667         /// <param name="input"></param>
    668         /// <returns></returns>
    669         public static string GetMD5_16(string input)
    670         {
    671             return GetMD5_32(input).Substring(8, 16);
    672         }
    673         /// <summary>
    674         /// 获得8位的MD5加密
    675         /// </summary>
    676         /// <param name="input"></param>
    677         /// <returns></returns>
    678         public static string GetMD5_8(string input)
    679         {
    680             return GetMD5_32(input).Substring(8, 8);
    681         }
    682         /// <summary>
    683         /// 获得4位的MD5加密
    684         /// </summary>
    685         /// <param name="input"></param>
    686         /// <returns></returns>
    687         public static string GetMD5_4(string input)
    688         {
    689             return GetMD5_32(input).Substring(8, 4);
    690         }
    691 
    692         public static string MD5EncryptHash(String input)
    693         {
    694             MD5 md5 = new MD5CryptoServiceProvider();
    695             //the GetBytes method returns byte array equavalent of a string
    696             byte[] res = md5.ComputeHash(Encoding.Default.GetBytes(input), 0, input.Length);
    697             char[] temp = new char[res.Length];
    698             //copy to a char array which can be passed to a String constructor
    699             Array.Copy(res, temp, res.Length);
    700             //return the result as a string
    701             return new String(temp);
    702         }
    703         #endregion
    704 
    705         #region MD5签名验证
    706 
    707         /// <summary>
    708         /// 对给定文件路径的文件加上标签
    709         /// </summary>
    710         /// <param name="path">要加密的文件的路径</param>
    711         /// <returns>标签的值</returns>
    712         public static bool AddMD5(string path)
    713         {
    714             bool IsNeed = true;
    715 
    716             if (CheckMD5(path))                                  //已进行MD5处理
    717                 IsNeed = false;
    718 
    719             try
    720             {
    721                 FileStream fsread = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
    722                 byte[] md5File = new byte[fsread.Length];
    723                 fsread.Read(md5File, 0, (int)fsread.Length);                               // 将文件流读取到Buffer中
    724                 fsread.Close();
    725 
    726                 if (IsNeed)
    727                 {
    728                     string result = MD5Buffer(md5File, 0, md5File.Length);             // 对Buffer中的字节内容算MD5
    729                     byte[] md5 = System.Text.Encoding.ASCII.GetBytes(result);       // 将字符串转换成字节数组以便写人到文件中
    730                     FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
    731                     fsWrite.Write(md5File, 0, md5File.Length);                               // 将文件,MD5值 重新写入到文件中。
    732                     fsWrite.Write(md5, 0, md5.Length);
    733                     fsWrite.Close();
    734                 }
    735                 else
    736                 {
    737                     FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
    738                     fsWrite.Write(md5File, 0, md5File.Length);
    739                     fsWrite.Close();
    740                 }
    741             }
    742             catch
    743             {
    744                 return false;
    745             }
    746 
    747             return true;
    748         }
    749 
    750         /// <summary>
    751         /// 对给定路径的文件进行验证
    752         /// </summary>
    753         /// <param name="path"></param>
    754         /// <returns>是否加了标签或是否标签值与内容值一致</returns>
    755         public static bool CheckMD5(string path)
    756         {
    757             try
    758             {
    759                 FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
    760                 byte[] md5File = new byte[get_file.Length];                                      // 读入文件
    761                 get_file.Read(md5File, 0, (int)get_file.Length);
    762                 get_file.Close();
    763 
    764                 string result = MD5Buffer(md5File, 0, md5File.Length - 32);             // 对文件除最后32位以外的字节计算MD5,这个32是因为标签位为32位。
    765                 string md5 = System.Text.Encoding.ASCII.GetString(md5File, md5File.Length - 32, 32);   //读取文件最后32位,其中保存的就是MD5值
    766                 return result == md5;
    767             }
    768             catch
    769             {
    770                 return false;
    771             }
    772         }
    773 
    774         /// <summary>
    775         /// 计算文件的MD5值
    776         /// </summary>
    777         /// <param name="MD5File">MD5签名文件字符数组</param>
    778         /// <param name="index">计算起始位置</param>
    779         /// <param name="count">计算终止位置</param>
    780         /// <returns>计算结果</returns>
    781         private static string MD5Buffer(byte[] MD5File, int index, int count)
    782         {
    783             System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
    784             byte[] hash_byte = get_md5.ComputeHash(MD5File, index, count);
    785             string result = System.BitConverter.ToString(hash_byte);
    786 
    787             result = result.Replace("-", "");
    788             return result;
    789         }
    790         #endregion
    791 
    792         #region  SHA256加密算法
    793 
    794 
    795         /// <summary>
    796         /// SHA256函数
    797         /// </summary>
    798         /// <param name="str">原始字符串</param>
    799         /// <returns>SHA256结果(返回长度为44字节的字符串)</returns>
    800         public static string SHA256(string str)
    801         {
    802             byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
    803             SHA256Managed Sha256 = new SHA256Managed();
    804             byte[] Result = Sha256.ComputeHash(SHA256Data);
    805             return Convert.ToBase64String(Result);  //返回长度为44字节的字符串
    806         }
    807         #endregion
    808 
    809         #region RC4加密 解密
    810 
    811         /// <summary>RC4加密算法
    812         /// 返回进过rc4加密过的字符
    813         /// </summary>
    814         /// <param name="str">被加密的字符</param>
    815         /// <param name="ckey">密钥</param>
    816         public static string EncryptRC4wq(string str, string ckey)
    817         {
    818             int[] s = new int[256];
    819             for (int i = 0; i < 256; i++)
    820             {
    821                 s[i] = i;
    822             }
    823             //密钥转数组
    824             char[] keys = ckey.ToCharArray();//密钥转字符数组
    825             int[] key = new int[keys.Length];
    826             for (int i = 0; i < keys.Length; i++)
    827             {
    828                 key[i] = keys[i];
    829             }
    830             //明文转数组
    831             char[] datas = str.ToCharArray();
    832             int[] mingwen = new int[datas.Length];
    833             for (int i = 0; i < datas.Length; i++)
    834             {
    835                 mingwen[i] = datas[i];
    836             }
    837 
    838             //通过循环得到256位的数组(密钥)
    839             int j = 0;
    840             int k = 0;
    841             int length = key.Length;
    842             int a;
    843             for (int i = 0; i < 256; i++)
    844             {
    845                 a = s[i];
    846                 j = (j + a + key[k]);
    847                 if (j >= 256)
    848                 {
    849                     j = j % 256;
    850                 }
    851                 s[i] = s[j];
    852                 s[j] = a;
    853                 if (++k >= length)
    854                 {
    855                     k = 0;
    856                 }
    857             }
    858             //根据上面的256的密钥数组 和 明文得到密文数组
    859             int x = 0, y = 0, a2, b, c;
    860             int length2 = mingwen.Length;
    861             int[] miwen = new int[length2];
    862             for (int i = 0; i < length2; i++)
    863             {
    864                 x = x + 1;
    865                 x = x % 256;
    866                 a2 = s[x];
    867                 y = y + a2;
    868                 y = y % 256;
    869                 s[x] = b = s[y];
    870                 s[y] = a2;
    871                 c = a2 + b;
    872                 c = c % 256;
    873                 miwen[i] = mingwen[i] ^ s[c];
    874             }
    875             //密文数组转密文字符
    876             char[] mi = new char[miwen.Length];
    877             for (int i = 0; i < miwen.Length; i++)
    878             {
    879                 mi[i] = (char)miwen[i];
    880             }
    881             string miwenstr = new string(mi);
    882             return miwenstr;
    883         }
    884 
    885         /// <summary>RC4解密算法
    886         /// 返回进过rc4解密过的字符
    887         /// </summary>
    888         /// <param name="str">被解密的字符</param>
    889         /// <param name="ckey">密钥</param>
    890         public static string DecryptRC4wq(string str, string ckey)
    891         {
    892             int[] s = new int[256];
    893             for (int i = 0; i < 256; i++)
    894             {
    895                 s[i] = i;
    896             }
    897             //密钥转数组
    898             char[] keys = ckey.ToCharArray();//密钥转字符数组
    899             int[] key = new int[keys.Length];
    900             for (int i = 0; i < keys.Length; i++)
    901             {
    902                 key[i] = keys[i];
    903             }
    904             //密文转数组
    905             char[] datas = str.ToCharArray();
    906             int[] miwen = new int[datas.Length];
    907             for (int i = 0; i < datas.Length; i++)
    908             {
    909                 miwen[i] = datas[i];
    910             }
    911 
    912             //通过循环得到256位的数组(密钥)
    913             int j = 0;
    914             int k = 0;
    915             int length = key.Length;
    916             int a;
    917             for (int i = 0; i < 256; i++)
    918             {
    919                 a = s[i];
    920                 j = (j + a + key[k]);
    921                 if (j >= 256)
    922                 {
    923                     j = j % 256;
    924                 }
    925                 s[i] = s[j];
    926                 s[j] = a;
    927                 if (++k >= length)
    928                 {
    929                     k = 0;
    930                 }
    931             }
    932             //根据上面的256的密钥数组 和 密文得到明文数组
    933             int x = 0, y = 0, a2, b, c;
    934             int length2 = miwen.Length;
    935             int[] mingwen = new int[length2];
    936             for (int i = 0; i < length2; i++)
    937             {
    938                 x = x + 1;
    939                 x = x % 256;
    940                 a2 = s[x];
    941                 y = y + a2;
    942                 y = y % 256;
    943                 s[x] = b = s[y];
    944                 s[y] = a2;
    945                 c = a2 + b;
    946                 c = c % 256;
    947                 mingwen[i] = miwen[i] ^ s[c];
    948             }
    949             //明文数组转明文字符
    950             char[] ming = new char[mingwen.Length];
    951             for (int i = 0; i < mingwen.Length; i++)
    952             {
    953                 ming[i] = (char)mingwen[i];
    954             }
    955             string mingwenstr = new string(ming);
    956             return mingwenstr;
    957         }
    958         #endregion
    959     }
    960 }
    View Code
  • 相关阅读:
    ActiveMQ 即时通讯服务 浅析
    Asp.net Mvc (Filter及其执行顺序)
    ActiveMQ基本介绍
    ActiveMQ持久化消息的三种方式
    Windows Azure Virtual Machine (27) 使用psping工具,测试Azure VM网络连通性
    Azure China (10) 使用Azure China SAS Token
    Windows Azure Affinity Groups (3) 修改虚拟网络地缘组(Affinity Group)的配置
    Windows Azure Storage (22) Azure Storage如何支持多级目录
    Windows Azure Virtual Machine (26) 使用高级存储(SSD)和DS系列VM
    Azure Redis Cache (2) 创建和使用Azure Redis Cache
  • 原文地址:https://www.cnblogs.com/gygang/p/8873702.html
Copyright © 2011-2022 走看看