• C#常用字符串加解密方法封装


    C#中常用的字符串加密、解密方法封装,包含只加密但不解密的方法。收藏起来备用。

      1 //方法一
      2 //须添加对System.Web的引用
      3 //using System.Web.Security;
      4 /// <summary>
      5 /// SHA1加密字符串
      6 /// </summary>
      7 /// <param name="source">源字符串</param>
      8 /// <returns>加密后的字符串</returns>
      9 public string SHA1(string source)
     10 {
     11     return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1");
     12 }
     13 /// <summary>
     14 /// MD5加密字符串
     15 /// </summary>
     16 /// <param name="source">源字符串</param>
     17 /// <returns>加密后的字符串</returns>
     18 public string MD5(string source)
     19 {
     20     return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");;
     21 }
     22 
     23 
     24 //方法二(可逆加密解密):
     25 //using System.Security.Cryptography;
     26 public string Encode(string data)
     27 {
     28     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
     29     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
     30     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
     31     int i = cryptoProvider.KeySize;
     32     MemoryStream ms = new MemoryStream();
     33     CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
     34     StreamWriter sw = new StreamWriter(cst);
     35     sw.Write(data);
     36     sw.Flush();
     37     cst.FlushFinalBlock();
     38     sw.Flush();
     39     return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
     40 }
     41 public string Decode(string data)
     42 {
     43     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
     44     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
     45     byte[] byEnc;
     46     try
     47     {
     48         byEnc = Convert.FromBase64String(data);
     49     }
     50     catch
     51     {
     52         return null;
     53     }
     54     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
     55     MemoryStream ms = new MemoryStream(byEnc);
     56     CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
     57     StreamReader sr = new StreamReader(cst);
     58 
     59 
     60 //方法三(MD5不可逆):
     61 //using System.Security.Cryptography;
     62 //MD5不可逆加密
     63 //32位加密
     64 public string GetMD5_32(string s, string _input_charset)
     65 {
     66     MD5 md5 = new MD5CryptoServiceProvider();
     67     byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
     68     StringBuilder sb = new StringBuilder(32);
     69     for (int i = 0; i < t.Length; i++)
     70     {
     71         sb.Append(t[i].ToString("x").PadLeft(2, '0'));
     72     }
     73     return sb.ToString();
     74 }
     75 //16位加密
     76 public static string GetMd5_16(string ConvertString)
     77 {
     78     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
     79     string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
     80     t2 = t2.Replace("-", "");
     81     return t2;
     82 }
     83 
     84 
     85 //方法四(对称加密):
     86 //using System.IO;
     87 //using System.Security.Cryptography;
     88 private SymmetricAlgorithm mobjCryptoService;
     89 private string Key;
     90 /// <summary>   
     91 /// 对称加密类的构造函数   
     92 /// </summary>   
     93 public SymmetricMethod()
     94 {
     95     mobjCryptoService = new RijndaelManaged();
     96     Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
     97 }
     98 /// <summary>   
     99 /// 获得密钥   
    100 /// </summary>   
    101 /// <returns>密钥</returns>   
    102 private byte[] GetLegalKey()
    103 {
    104     string sTemp = Key;
    105     mobjCryptoService.GenerateKey();
    106     byte[] bytTemp = mobjCryptoService.Key;
    107     int KeyLength = bytTemp.Length;
    108     if (sTemp.Length > KeyLength)
    109         sTemp = sTemp.Substring(0, KeyLength);
    110     else if (sTemp.Length < KeyLength)
    111         sTemp = sTemp.PadRight(KeyLength, ' ');
    112     return ASCIIEncoding.ASCII.GetBytes(sTemp);
    113 }
    114 /// <summary>   
    115 /// 获得初始向量IV   
    116 /// </summary>   
    117 /// <returns>初试向量IV</returns>   
    118 private byte[] GetLegalIV()
    119 {
    120     string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
    121     mobjCryptoService.GenerateIV();
    122     byte[] bytTemp = mobjCryptoService.IV;
    123     int IVLength = bytTemp.Length;
    124     if (sTemp.Length > IVLength)
    125         sTemp = sTemp.Substring(0, IVLength);
    126     else if (sTemp.Length < IVLength)
    127         sTemp = sTemp.PadRight(IVLength, ' ');
    128     return ASCIIEncoding.ASCII.GetBytes(sTemp);
    129 }
    130 /// <summary>   
    131 /// 加密方法   
    132 /// </summary>   
    133 /// <param name="Source">待加密的串</param>   
    134 /// <returns>经过加密的串</returns>   
    135 public string Encrypto(string Source)
    136 {
    137     byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
    138     MemoryStream ms = new MemoryStream();
    139     mobjCryptoService.Key = GetLegalKey();
    140     mobjCryptoService.IV = GetLegalIV();
    141     ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
    142     CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
    143     cs.Write(bytIn, 0, bytIn.Length);
    144     cs.FlushFinalBlock();
    145     ms.Close();
    146     byte[] bytOut = ms.ToArray();
    147     return Convert.ToBase64String(bytOut);
    148 }
    149 /// <summary>   
    150 /// 解密方法   
    151 /// </summary>   
    152 /// <param name="Source">待解密的串</param>   
    153 /// <returns>经过解密的串</returns>   
    154 public string Decrypto(string Source)
    155 {
    156     byte[] bytIn = Convert.FromBase64String(Source);
    157     MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
    158     mobjCryptoService.Key = GetLegalKey();
    159     mobjCryptoService.IV = GetLegalIV();
    160     ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
    161     CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
    162     StreamReader sr = new StreamReader(cs);
    163     return sr.ReadToEnd();
    164 }
    165 
    166 //方法五:
    167 //using System.IO;
    168 //using System.Security.Cryptography;
    169 //using System.Text;
    170 //默认密钥向量
    171 private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
    172 /**//**//**//// <summary>
    173 /// DES加密字符串 keleyi.com
    174 /// </summary>
    175 /// <param name="encryptString">待加密的字符串</param>
    176 /// <param name="encryptKey">加密密钥,要求为8位</param>
    177 /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
    178 public static string EncryptDES(string encryptString, string encryptKey)
    179 {
    180     try
    181     {
    182         byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
    183         byte[] rgbIV = Keys;
    184         byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
    185         DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
    186         MemoryStream mStream = new MemoryStream();
    187         CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
    188         cStream.Write(inputByteArray, 0, inputByteArray.Length);
    189         cStream.FlushFinalBlock();
    190         return Convert.ToBase64String(mStream.ToArray());
    191     }
    192     catch
    193     {
    194         return encryptString;
    195     }
    196 }
    197 /**//**//**//// <summary>
    198 /// DES解密字符串 keleyi.com
    199 /// </summary>
    200 /// <param name="decryptString">待解密的字符串</param>
    201 /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
    202 /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
    203 public static string DecryptDES(string decryptString, string decryptKey)
    204 {
    205     try
    206     {
    207         byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
    208         byte[] rgbIV = Keys;
    209         byte[] inputByteArray = Convert.FromBase64String(decryptString);
    210         DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
    211         MemoryStream mStream = new MemoryStream();
    212         CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
    213         cStream.Write(inputByteArray, 0, inputByteArray.Length);
    214         cStream.FlushFinalBlock();
    215         return Encoding.UTF8.GetString(mStream.ToArray());
    216     }
    217     catch
    218     {
    219         return decryptString;
    220     }
    221 } 
    222 
    223 
    224 //方法六(文件加密):
    225 //using System.IO;
    226 //using System.Security.Cryptography;
    227 //using System.Text;
    228 //加密文件
    229 private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
    230 {
    231     //Create the file streams to handle the input and output files.
    232     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
    233     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
    234     fout.SetLength(0);
    235     //Create variables to help with read and write.
    236     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
    237     long rdlen = 0;              //This is the total number of bytes written.
    238     long totlen = fin.Length;    //This is the total length of the input file.
    239     int len;                     //This is the number of bytes to be written at a time.
    240     DES des = new DESCryptoServiceProvider();
    241     CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
    242     //Read from the input file, then encrypt and write to the output file.
    243     while (rdlen < totlen)
    244     {
    245         len = fin.Read(bin, 0, 100);
    246         encStream.Write(bin, 0, len);
    247         rdlen = rdlen + len;
    248     }
    249     encStream.Close();
    250     fout.Close();
    251     fin.Close();
    252 }
    253 //解密文件
    254 private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV)
    255 {
    256     //Create the file streams to handle the input and output files.
    257     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
    258     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
    259     fout.SetLength(0);
    260     //Create variables to help with read and write.
    261     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
    262     long rdlen = 0;              //This is the total number of bytes written.
    263     long totlen = fin.Length;    //This is the total length of the input file.
    264     int len;                     //This is the number of bytes to be written at a time.
    265     DES des = new DESCryptoServiceProvider();
    266     CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
    267     //Read from the input file, then encrypt and write to the output file.
    268     while (rdlen < totlen)
    269     {
    270         len = fin.Read(bin, 0, 100);
    271         encStream.Write(bin, 0, len);
    272         rdlen = rdlen + len;
    273     }
    274     encStream.Close();
    275     fout.Close();
    276     fin.Close();
    277     return sr.ReadToEnd();
    278 }

    http://www.cnblogs.com/sosoft/

  • 相关阅读:
    windows2008英文版设置文件夹选项
    vmware的使用技巧:将鼠标光标移回所在系统
    java最简代码规范总结
    oracle sql developer工具的使用
    java生成自定义证书图片4
    java生成自定义证书图片3
    java使用resource时,使用try-with-resources代替try-catch-finally
    java中利用BigDecimal进行精确计算
    mybatis分页插件pagehleper的基本使用
    mybatis中mapper映射文件中>=和<=等特殊符号的写法
  • 原文地址:https://www.cnblogs.com/sosoft/p/3456610.html
Copyright © 2020-2023  润新知