当前位置: 首页 > news >正文

C#加密汇总

方法一:

 
  1. //须添加对System.Web的引用
  2. using System.Web.Security;
  3. ...
  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. }
 

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

 
  1. using System.Security.Cryptography;
  2. ...
  3. public string Encode(string data)
  4. {
  5.     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
  6.     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
  7.     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
  8.     int i = cryptoProvider.KeySize;
  9.     MemoryStream ms = new MemoryStream();
  10.     CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
  11.     StreamWriter sw = new StreamWriter(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(string data)
  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 = new DESCryptoServiceProvider();
  32.     MemoryStream ms = new MemoryStream(byEnc);
  33.     CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
  34.     StreamReader sr = new StreamReader(cst);
  35.     return sr.ReadToEnd();
  36. }
 

方法三(MD5不可逆):

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

方法四(对称加密):

 
  1. using System.IO;
  2. using System.Security.Cryptography;
  3. ...
  4. private SymmetricAlgorithm mobjCryptoService;
  5. private string Key;
  6. /// <summary>   
  7. /// 对称加密类的构造函数   
  8. /// </summary>   
  9. public SymmetricMethod()
  10. {
  11.     mobjCryptoService = new RijndaelManaged();
  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.     string sTemp = Key;
  21.     mobjCryptoService.GenerateKey();
  22.     byte[] bytTemp = mobjCryptoService.Key;
  23.     int KeyLength = 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.     return ASCIIEncoding.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.     int IVLength = 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.     return ASCIIEncoding.ASCII.GetBytes(sTemp);
  45. }
  46. /// <summary>   
  47. /// 加密方法   
  48. /// </summary>   
  49. /// <param name="Source">待加密的串</param>   
  50. /// <returns>经过加密的串</returns>   
  51. public string Encrypto(string Source)
  52. {
  53.     byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
  54.     MemoryStream ms = new MemoryStream();
  55.     mobjCryptoService.Key = GetLegalKey();
  56.     mobjCryptoService.IV = GetLegalIV();
  57.     ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
  58.     CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
  59.     cs.Write(bytIn, 0, bytIn.Length);
  60.     cs.FlushFinalBlock();
  61.     ms.Close();
  62.     byte[] bytOut = ms.ToArray();
  63.     return Convert.ToBase64String(bytOut);
  64. }
  65. /// <summary>   
  66. /// 解密方法   
  67. /// </summary>   
  68. /// <param name="Source">待解密的串</param>   
  69. /// <returns>经过解密的串</returns>   
  70. public string Decrypto(string Source)
  71. {
  72.     byte[] bytIn = Convert.FromBase64String(Source);
  73.     MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
  74.     mobjCryptoService.Key = GetLegalKey();
  75.     mobjCryptoService.IV = GetLegalIV();
  76.     ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
  77.     CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
  78.     StreamReader sr = new StreamReader(cs);
  79.     return sr.ReadToEnd();
  80. }
 

方法五:

 
  1. using System.IO;
  2. using System.Security.Cryptography;
  3. using System.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, string encryptKey)
  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 = new DESCryptoServiceProvider();
  21.         MemoryStream mStream = new MemoryStream();
  22.         CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
  23.         cStream.Write(inputByteArray, 0, inputByteArray.Length);
  24.         cStream.FlushFinalBlock();
  25.         return Convert.ToBase64String(mStream.ToArray());
  26.     }
  27.     catch
  28.     {
  29.         return encryptString;
  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, string decryptKey)
  39. {
  40.     try
  41.     {
  42.         byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
  43.         byte[] rgbIV = Keys;
  44.         byte[] inputByteArray = Convert.FromBase64String(decryptString);
  45.         DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
  46.         MemoryStream mStream = new MemoryStream();
  47.         CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
  48.         cStream.Write(inputByteArray, 0, inputByteArray.Length);
  49.         cStream.FlushFinalBlock();
  50.         return Encoding.UTF8.GetString(mStream.ToArray());
  51.     }
  52.     catch
  53.     {
  54.         return decryptString;
  55.     }
 

方法六(文件加密):

 
  1. using System.IO;
  2. using System.Security.Cryptography;
  3. using System.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 = new FileStream(inName, FileMode.Open, FileAccess.Read);
  10.     FileStream fout = new FileStream(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 = new DESCryptoServiceProvider();
  18.     CryptoStream encStream = new CryptoStream(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 = new FileStream(inName, FileMode.Open, FileAccess.Read);
  35.     FileStream fout = new FileStream(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 = new DESCryptoServiceProvider();
  43.     CryptoStream encStream = new CryptoStream(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();

转载于:https://www.cnblogs.com/agile2011/archive/2011/07/17/2108777.html

相关文章:

  • 压缩打包介绍,gzip、bzip2、xz压缩工具
  • eclipse不能自动编译工程的解决方法
  • 普天发布新一代配线架,终结争论?
  • Server2008 安装 Zune
  • Asp.Net 开放式并发处理(和保守性并发)介绍
  • 如何在Windows XP上安装Windows Phone Developer Tools
  • 使用PowerShell配置IP地址
  • 基于jquery的常见函数封装
  • 理想
  • 物联网技术对智能远程医疗的影响
  • 帮助我了解Android2.2联系人结构(二)
  • 拦截器实现文件过滤
  • IE6下的PNG图片半透明问题解决(a:hover)
  • Ubuntu 14.04安装LAMP(Linux,Apache,MySQL,PHP)
  • 好用的Java数学表达式计算工具——Exp4j
  • 2018天猫双11|这就是阿里云!不止有新技术,更有温暖的社会力量
  • android百种动画侧滑库、步骤视图、TextView效果、社交、搜房、K线图等源码
  • css选择器
  • ECMAScript入门(七)--Module语法
  • Javascript 原型链
  • JavaScript服务器推送技术之 WebSocket
  • JS题目及答案整理
  • Laravel Telescope:优雅的应用调试工具
  • node入门
  • Puppeteer:浏览器控制器
  • Python socket服务器端、客户端传送信息
  • python学习笔记-类对象的信息
  • Sass Day-01
  • 从0到1:PostCSS 插件开发最佳实践
  • 从伪并行的 Python 多线程说起
  • 仿天猫超市收藏抛物线动画工具库
  • 技术发展面试
  • 开发基于以太坊智能合约的DApp
  • 使用Maven插件构建SpringBoot项目,生成Docker镜像push到DockerHub上
  • 推荐一款sublime text 3 支持JSX和es201x 代码格式化的插件
  • 项目实战-Api的解决方案
  • 学习ES6 变量的解构赋值
  • 扩展资源服务器解决oauth2 性能瓶颈
  • #NOIP 2014#Day.2 T3 解方程
  • #基础#使用Jupyter进行Notebook的转换 .ipynb文件导出为.md文件
  • (10)ATF MMU转换表
  • (14)目标检测_SSD训练代码基于pytorch搭建代码
  • (2)关于RabbitMq 的 Topic Exchange 主题交换机
  • (二)pulsar安装在独立的docker中,python测试
  • (附源码)spring boot球鞋文化交流论坛 毕业设计 141436
  • (附源码)springboot宠物管理系统 毕业设计 121654
  • (转)IOS中获取各种文件的目录路径的方法
  • (转)Oracle 9i 数据库设计指引全集(1)
  • .net core 6 集成 elasticsearch 并 使用分词器
  • .Net Redis的秒杀Dome和异步执行
  • .NET 指南:抽象化实现的基类
  • .NET中两种OCR方式对比
  • @transactional 方法执行完再commit_当@Transactional遇到@CacheEvict,你的代码是不是有bug!...
  • [1525]字符统计2 (哈希)SDUT
  • [Android]创建TabBar