zoukankan      html  css  js  c++  java
  • 基于.net的加密汇总(1)

    引用C#加密汇总

    方法一:

     
    1. //须添加对System.Web的引用
    2. usingSystem.Web.Security;
    3. ...
    4. /// <summary>
    5. /// SHA1加密字符串
    6. /// </summary>
    7. /// <param name="source">源字符串</param>
    8. /// <returns>加密后的字符串</returns>
    9. public string SHA1(stringsource)
    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(stringsource)
    19. {
    20.     return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");;
    21. }
     

    方法二(可逆加密解密):

     
    1. usingSystem.Security.Cryptography;
    2. ...
    3. public string Encode(stringdata)
    4. {
    5.     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
    6.     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
    7.     DESCryptoServiceProvider cryptoProvider = newDESCryptoServiceProvider();
    8.     inti = cryptoProvider.KeySize;
    9.     MemoryStream ms = newMemoryStream();
    10.     CryptoStream cst = newCryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
    11.     StreamWriter sw = newStreamWriter(cst);
    12.     sw.Write(data);
    13.     sw.Flush();
    14.     cst.FlushFinalBlock();
    15.     sw.Flush();
    16.     return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
    17. }
    18. public string Decode(stringdata)
    19. {
    20.     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
    21.     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
    22.     byte[] byEnc;
    23.     try
    24.     {
    25.         byEnc = Convert.FromBase64String(data);
    26.     }
    27.     catch
    28.     {
    29.         return null;
    30.     }
    31.     DESCryptoServiceProvider cryptoProvider = newDESCryptoServiceProvider();
    32.     MemoryStream ms = newMemoryStream(byEnc);
    33.     CryptoStream cst = newCryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
    34.     StreamReader sr = newStreamReader(cst);
    35.     returnsr.ReadToEnd();
    36. }
     

    方法三(MD5不可逆):

     
    1. usingSystem.Security.Cryptography;
    2. ...
    3. //MD5不可逆加密
    4. //32位加密
    5. public string GetMD5_32(string s, string_input_charset)
    6. {
    7.     MD5 md5 = newMD5CryptoServiceProvider();
    8.     byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
    9.     StringBuilder sb = newStringBuilder(32);
    10.     for (inti = 0; i < t.Length; i++)
    11.     {
    12.         sb.Append(t[i].ToString("x").PadLeft(2, '0'));
    13.     }
    14.     returnsb.ToString();
    15. }
    16. //16位加密
    17. public static string GetMd5_16(stringConvertString)
    18. {
    19.     MD5CryptoServiceProvider md5 = newMD5CryptoServiceProvider();
    20.     stringt2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
    21.     t2 = t2.Replace("-", "");
    22.     returnt2;
    23. }
     

    方法四(对称加密):

     
    1. usingSystem.IO;
    2. usingSystem.Security.Cryptography;
    3. ...
    4. privateSymmetricAlgorithm mobjCryptoService;
    5. private stringKey;
    6. /// <summary>  
    7. /// 对称加密类的构造函数  
    8. /// </summary>  
    9. publicSymmetricMethod()
    10. {
    11.     mobjCryptoService = newRijndaelManaged();
    12.     Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
    13. }
    14. /// <summary>  
    15. /// 获得密钥  
    16. /// </summary>  
    17. /// <returns>密钥</returns>  
    18. private byte[] GetLegalKey()
    19. {
    20.     stringsTemp = Key;
    21.     mobjCryptoService.GenerateKey();
    22.     byte[] bytTemp = mobjCryptoService.Key;
    23.     intKeyLength = bytTemp.Length;
    24.     if(sTemp.Length > KeyLength)
    25.         sTemp = sTemp.Substring(0, KeyLength);
    26.     else if(sTemp.Length < KeyLength)
    27.         sTemp = sTemp.PadRight(KeyLength, ' ');
    28.     returnASCIIEncoding.ASCII.GetBytes(sTemp);
    29. }
    30. /// <summary>  
    31. /// 获得初始向量IV  
    32. /// </summary>  
    33. /// <returns>初试向量IV</returns>  
    34. private byte[] GetLegalIV()
    35. {
    36.     string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
    37.     mobjCryptoService.GenerateIV();
    38.     byte[] bytTemp = mobjCryptoService.IV;
    39.     intIVLength = bytTemp.Length;
    40.     if(sTemp.Length > IVLength)
    41.         sTemp = sTemp.Substring(0, IVLength);
    42.     else if(sTemp.Length < IVLength)
    43.         sTemp = sTemp.PadRight(IVLength, ' ');
    44.     returnASCIIEncoding.ASCII.GetBytes(sTemp);
    45. }
    46. /// <summary>  
    47. /// 加密方法  
    48. /// </summary>  
    49. /// <param name="Source">待加密的串</param>  
    50. /// <returns>经过加密的串</returns>  
    51. public string Encrypto(stringSource)
    52. {
    53.     byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
    54.     MemoryStream ms = newMemoryStream();
    55.     mobjCryptoService.Key = GetLegalKey();
    56.     mobjCryptoService.IV = GetLegalIV();
    57.     ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
    58.     CryptoStream cs = newCryptoStream(ms, encrypto, CryptoStreamMode.Write);
    59.     cs.Write(bytIn, 0, bytIn.Length);
    60.     cs.FlushFinalBlock();
    61.     ms.Close();
    62.     byte[] bytOut = ms.ToArray();
    63.     returnConvert.ToBase64String(bytOut);
    64. }
    65. /// <summary>  
    66. /// 解密方法  
    67. /// </summary>  
    68. /// <param name="Source">待解密的串</param>  
    69. /// <returns>经过解密的串</returns>  
    70. public string Decrypto(stringSource)
    71. {
    72.     byte[] bytIn = Convert.FromBase64String(Source);
    73.     MemoryStream ms = newMemoryStream(bytIn, 0, bytIn.Length);
    74.     mobjCryptoService.Key = GetLegalKey();
    75.     mobjCryptoService.IV = GetLegalIV();
    76.     ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
    77.     CryptoStream cs = newCryptoStream(ms, encrypto, CryptoStreamMode.Read);
    78.     StreamReader sr = newStreamReader(cs);
    79.     returnsr.ReadToEnd();
    80. }
     

    方法五:

     
    1. usingSystem.IO;
    2. usingSystem.Security.Cryptography;
    3. usingSystem.Text;
    4. ...
    5. //默认密钥向量
    6. private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
    7. /**//**//**//// <summary>
    8. /// DES加密字符串
    9. /// </summary>
    10. /// <param name="encryptString">待加密的字符串</param>
    11. /// <param name="encryptKey">加密密钥,要求为8位</param>
    12. /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
    13. public static string EncryptDES(string encryptString, stringencryptKey)
    14. {
    15.     try
    16.     {
    17.         byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
    18.         byte[] rgbIV = Keys;
    19.         byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
    20.         DESCryptoServiceProvider dCSP = newDESCryptoServiceProvider();
    21.         MemoryStream mStream = newMemoryStream();
    22.         CryptoStream cStream = newCryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
    23.         cStream.Write(inputByteArray, 0, inputByteArray.Length);
    24.         cStream.FlushFinalBlock();
    25.         returnConvert.ToBase64String(mStream.ToArray());
    26.     }
    27.     catch
    28.     {
    29.         returnencryptString;
    30.     }
    31. }
    32. /**//**//**//// <summary>
    33. /// DES解密字符串
    34. /// </summary>
    35. /// <param name="decryptString">待解密的字符串</param>
    36. /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
    37. /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
    38. public static string DecryptDES(string decryptString, stringdecryptKey)
    39. {
    40.     try
    41.     {
    42.         byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
    43.         byte[] rgbIV = Keys;
    44.         byte[] inputByteArray = Convert.FromBase64String(decryptString);
    45.         DESCryptoServiceProvider DCSP = newDESCryptoServiceProvider();
    46.         MemoryStream mStream = newMemoryStream();
    47.         CryptoStream cStream = newCryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
    48.         cStream.Write(inputByteArray, 0, inputByteArray.Length);
    49.         cStream.FlushFinalBlock();
    50.         returnEncoding.UTF8.GetString(mStream.ToArray());
    51.     }
    52.     catch
    53.     {
    54.         returndecryptString;
    55.     }
     

    方法六(文件加密):

     
    1. using System.IO;
    2. usingSystem.Security.Cryptography;
    3. usingSystem.Text;
    4. ...
    5. //加密文件
    6. private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
    7. {
    8.     //Create the file streams to handle the input and output files.
    9.     FileStream fin = newFileStream(inName, FileMode.Open, FileAccess.Read);
    10.     FileStream fout = newFileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
    11.     fout.SetLength(0);
    12.     //Create variables to help with read and write.
    13.     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
    14.     long rdlen = 0;              //This is the total number of bytes written.
    15.     long totlen = fin.Length;    //This is the total length of the input file.
    16.     int len;                     //This is the number of bytes to be written at a time.
    17.     DES des = newDESCryptoServiceProvider();
    18.     CryptoStream encStream = newCryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
    19.     //Read from the input file, then encrypt and write to the output file.
    20.     while(rdlen < totlen)
    21.     {
    22.         len = fin.Read(bin, 0, 100);
    23.         encStream.Write(bin, 0, len);
    24.         rdlen = rdlen + len;
    25.     }
    26.     encStream.Close();
    27.     fout.Close();
    28.     fin.Close();
    29. }
    30. //解密文件
    31. private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV)
    32. {
    33.     //Create the file streams to handle the input and output files.
    34.     FileStream fin = newFileStream(inName, FileMode.Open, FileAccess.Read);
    35.     FileStream fout = newFileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
    36.     fout.SetLength(0);
    37.     //Create variables to help with read and write.
    38.     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
    39.     long rdlen = 0;              //This is the total number of bytes written.
    40.     long totlen = fin.Length;    //This is the total length of the input file.
    41.     int len;                     //This is the number of bytes to be written at a time.
    42.     DES des = newDESCryptoServiceProvider();
    43.     CryptoStream encStream = newCryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
    44.     //Read from the input file, then encrypt and write to the output file.
    45.     while(rdlen < totlen)
    46.     {
    47.         len = fin.Read(bin, 0, 100);
    48.         encStream.Write(bin, 0, len);
    49.         rdlen = rdlen + len;
    50.     }
    51.     encStream.Close();
    52.     fout.Close();
    53.     fin.Close();
  • 相关阅读:
    P1744 采购特价商品
    P1359 租用游艇
    P3092 [USACO13NOV]没有找零No Change
    P1272 重建道路
    P2014 选课
    P1026 统计单词个数
    P1776 宝物筛选_NOI导刊2010提高(02)
    自定义异步非阻塞tornado框架
    tornado进阶篇
    tornado基础篇
  • 原文地址:https://www.cnblogs.com/alvinyue/p/2727925.html
Copyright © 2011-2022 走看看