C#加密算法汇总

简介:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
方法一:
     //须添加对System.Web的引用
     using  System.Web.Security;
     
     ...
     
     /// <summary>
     /// SHA1加密字符串
     /// </summary>
     /// <param name="source">源字符串</param>
     /// <returns>加密后的字符串</returns>
     public  string  SHA1( string  source)
     {
         return  FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1" );
     }
 
 
     /// <summary>
     /// MD5加密字符串
     /// </summary>
     /// <param name="source">源字符串</param>
     /// <returns>加密后的字符串</returns>
     public  string  MD5( string  source)
     {
         return  FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5" );;
     }

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
方法二(可逆加密解密):
     using  System.Security.Cryptography;
     
     ...
     
     public  string  Encode( string  data)
     {
         byte [] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
         byte [] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
     
         DESCryptoServiceProvider cryptoProvider = new  DESCryptoServiceProvider();
         int  i = cryptoProvider.KeySize;
         MemoryStream ms = new  MemoryStream();
         CryptoStream cst = new  CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
     
         StreamWriter sw = new  StreamWriter(cst);
         sw.Write(data);
         sw.Flush();
         cst.FlushFinalBlock();
         sw.Flush();
         return  Convert.ToBase64String(ms.GetBuffer(), 0, ( int )ms.Length);
     
     }
     
     public  string  Decode( string  data)
     {
         byte [] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
         byte [] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
     
         byte [] byEnc;
         try
         {
             byEnc = Convert.FromBase64String(data);
         }
         catch
         {
             return  null ;
         }
     
         DESCryptoServiceProvider cryptoProvider = new  DESCryptoServiceProvider();
         MemoryStream ms = new  MemoryStream(byEnc);
         CryptoStream cst = new  CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
         StreamReader sr = new  StreamReader(cst);
         return  sr.ReadToEnd();
     }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
方法三(MD5不可逆):
     using  System.Security.Cryptography;
     
     ...
     
     //MD5不可逆加密
     
     //32位加密
     
     public  string  GetMD5_32( string  s, string  _input_charset)
     {
         MD5 md5 = new  MD5CryptoServiceProvider();
         byte [] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
         StringBuilder sb = new  StringBuilder(32);
         for  ( int  i = 0; i < t.Length; i++)
         {
             sb.Append(t[i].ToString( "x" ).PadLeft(2, '0' ));
         }
         return  sb.ToString();
     }
     
     //16位加密
     public  static  string  GetMd5_16( string  ConvertString)
     {
         MD5CryptoServiceProvider md5 = new  MD5CryptoServiceProvider();
         string  t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
         t2 = t2.Replace( "-" , "" );
         return  t2;
     }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
方法四(对称加密):
     using  System.IO;
     using  System.Security.Cryptography;
     
     ...
     
     private  SymmetricAlgorithm mobjCryptoService;
     private  string  Key;
     /// <summary>   
     /// 对称加密类的构造函数   
     /// </summary>   
     public  SymmetricMethod()
     {
         mobjCryptoService = new  RijndaelManaged();
         Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7" ;
     }
     /// <summary>   
     /// 获得密钥   
     /// </summary>   
     /// <returns>密钥</returns>   
     private  byte [] GetLegalKey()
     {
         string  sTemp = Key;
         mobjCryptoService.GenerateKey();
         byte [] bytTemp = mobjCryptoService.Key;
         int  KeyLength = bytTemp.Length;
         if  (sTemp.Length > KeyLength)
             sTemp = sTemp.Substring(0, KeyLength);
         else  if  (sTemp.Length < KeyLength)
             sTemp = sTemp.PadRight(KeyLength, ' ' );
         return  ASCIIEncoding.ASCII.GetBytes(sTemp);
     }
     /// <summary>   
     /// 获得初始向量IV   
     /// </summary>   
     /// <returns>初试向量IV</returns>   
     private  byte [] GetLegalIV()
     {
         string  sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk" ;
         mobjCryptoService.GenerateIV();
         byte [] bytTemp = mobjCryptoService.IV;
         int  IVLength = bytTemp.Length;
         if  (sTemp.Length > IVLength)
             sTemp = sTemp.Substring(0, IVLength);
         else  if  (sTemp.Length < IVLength)
             sTemp = sTemp.PadRight(IVLength, ' ' );
         return  ASCIIEncoding.ASCII.GetBytes(sTemp);
     }
     /// <summary>   
     /// 加密方法   
     /// </summary>   
     /// <param name="Source">待加密的串</param>   
     /// <returns>经过加密的串</returns>   
     public  string  Encrypto( string  Source)
     {
         byte [] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
         MemoryStream ms = new  MemoryStream();
         mobjCryptoService.Key = GetLegalKey();
         mobjCryptoService.IV = GetLegalIV();
         ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
         CryptoStream cs = new  CryptoStream(ms, encrypto, CryptoStreamMode.Write);
         cs.Write(bytIn, 0, bytIn.Length);
         cs.FlushFinalBlock();
         ms.Close();
         byte [] bytOut = ms.ToArray();
         return  Convert.ToBase64String(bytOut);
     }
     /// <summary>   
     /// 解密方法   
     /// </summary>   
     /// <param name="Source">待解密的串</param>   
     /// <returns>经过解密的串</returns>   
     public  string  Decrypto( string  Source)
     {
         byte [] bytIn = Convert.FromBase64String(Source);
         MemoryStream ms = new  MemoryStream(bytIn, 0, bytIn.Length);
         mobjCryptoService.Key = GetLegalKey();
         mobjCryptoService.IV = GetLegalIV();
         ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
         CryptoStream cs = new  CryptoStream(ms, encrypto, CryptoStreamMode.Read);
         StreamReader sr = new  StreamReader(cs);
         return  sr.ReadToEnd();
     }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
方法五:
     using  System.IO;
     using  System.Security.Cryptography;
     using  System.Text;
     
     ...
     
     //默认密钥向量
     private  static  byte [] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
     /// <summary>
     /// DES加密字符串
     /// </summary>
     /// <param name="encryptString">待加密的字符串</param>
     /// <param name="encryptKey">加密密钥,要求为8位</param>
     /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
     public  static  string  EncryptDES( string  encryptString, string  encryptKey)
     {
         try
         {
             byte [] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
             byte [] rgbIV = Keys;
             byte [] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
             DESCryptoServiceProvider dCSP = new  DESCryptoServiceProvider();
             MemoryStream mStream = new  MemoryStream();
             CryptoStream cStream = new  CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
             cStream.Write(inputByteArray, 0, inputByteArray.Length);
             cStream.FlushFinalBlock();
             return  Convert.ToBase64String(mStream.ToArray());
         }
         catch
         {
             return  encryptString;
         }
     }
     
     /// <summary>
     /// DES解密字符串
     /// </summary>
     /// <param name="decryptString">待解密的字符串</param>
     /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
     /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
     public  static  string  DecryptDES( string  decryptString, string  decryptKey)
     {
         try
         {
             byte [] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
             byte [] rgbIV = Keys;
             byte [] inputByteArray = Convert.FromBase64String(decryptString);
             DESCryptoServiceProvider DCSP = new  DESCryptoServiceProvider();
             MemoryStream mStream = new  MemoryStream();
             CryptoStream cStream = new  CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
             cStream.Write(inputByteArray, 0, inputByteArray.Length);
             cStream.FlushFinalBlock();
             return  Encoding.UTF8.GetString(mStream.ToArray());
         }
         catch
         {
             return  decryptString;
         }
     }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
方法六(文件加密):
     using  System.IO;
     using  System.Security.Cryptography;
     using  System.Text;
     
     ...
     
     //加密文件
     private  static  void  EncryptData(String inName, String outName, byte [] desKey, byte [] desIV)
     {
         //Create the file streams to handle the input and output files.
         FileStream fin = new  FileStream(inName, FileMode.Open, FileAccess.Read);
         FileStream fout = new  FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
         fout.SetLength(0);
     
         //Create variables to help with read and write.
         byte [] bin = new  byte [100]; //This is intermediate storage for the encryption.
         long  rdlen = 0;              //This is the total number of bytes written.
         long  totlen = fin.Length;    //This is the total length of the input file.
         int  len;                     //This is the number of bytes to be written at a time.
     
         DES des = new  DESCryptoServiceProvider();
         CryptoStream encStream = new  CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
     
         //Read from the input file, then encrypt and write to the output file.
         while  (rdlen < totlen)
         {
             len = fin.Read(bin, 0, 100);
             encStream.Write(bin, 0, len);
             rdlen = rdlen + len;
         }
     
         encStream.Close();
         fout.Close();
         fin.Close();
     }
     
     //解密文件
     private  static  void  DecryptData(String inName, String outName, byte [] desKey, byte [] desIV)
     {
         //Create the file streams to handle the input and output files.
         FileStream fin = new  FileStream(inName, FileMode.Open, FileAccess.Read);
         FileStream fout = new  FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
         fout.SetLength(0);
     
         //Create variables to help with read and write.
         byte [] bin = new  byte [100]; //This is intermediate storage for the encryption.
         long  rdlen = 0;              //This is the total number of bytes written.
         long  totlen = fin.Length;    //This is the total length of the input file.
         int  len;                     //This is the number of bytes to be written at a time.
     
         DES des = new  DESCryptoServiceProvider();
         CryptoStream encStream = new  CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
     
         //Read from the input file, then encrypt and write to the output file.
         while  (rdlen < totlen)
         {
             len = fin.Read(bin, 0, 100);
             encStream.Write(bin, 0, len);
             rdlen = rdlen + len;
         }
     
         encStream.Close();
         fout.Close();
         fin.Close();
 
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using  System;
using  System.Security.Cryptography; //这个是处理文字编码的前提
using  System.Text;
using  System.IO;
/// <summary>
/// DES加密方法
/// </summary>
/// <param name="strPlain">明文</param>
/// <param name="strDESKey">密钥</param>
/// <param name="strDESIV">向量</param>
/// <returns>密文</returns>
public  string  DESEncrypt( string  strPlain, string  strDESKey, string  strDESIV)
{
  //把密钥转换成字节数组
  byte [] bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey);
  //把向量转换成字节数组
  byte [] bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV);
  //声明1个新的DES对象
  DESCryptoServiceProvider desEncrypt= new  DESCryptoServiceProvider();
  //开辟一块内存流
  MemoryStream msEncrypt= new  MemoryStream();
  //把内存流对象包装成加密流对象
  CryptoStream csEncrypt= new  CryptoStream(msEncrypt,desEncrypt.CreateEncryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Write);
  //把加密流对象包装成写入流对象
  StreamWriter swEncrypt= new  StreamWriter(csEncrypt);
  //写入流对象写入明文
  swEncrypt.WriteLine(strPlain);
  //写入流关闭
  swEncrypt.Close();
  //加密流关闭
  csEncrypt.Close();
  //把内存流转换成字节数组,内存流现在已经是密文了
  byte [] bytesCipher=msEncrypt.ToArray();
  //内存流关闭
  msEncrypt.Close();
  //把密文字节数组转换为字符串,并返回
  return  UnicodeEncoding.Unicode.GetString(bytesCipher);
}
 
 
 
 
/// <summary>
/// DES解密方法
/// </summary>
/// <param name="strCipher">密文</param>
/// <param name="strDESKey">密钥</param>
/// <param name="strDESIV">向量</param>
/// <returns>明文</returns>
public  string  DESDecrypt( string  strCipher, string  strDESKey, string  strDESIV)
{
  //把密钥转换成字节数组
  byte [] bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey);
  //把向量转换成字节数组
  byte [] bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV);
  //把密文转换成字节数组
  byte [] bytesCipher=UnicodeEncoding.Unicode.GetBytes(strCipher);
  //声明1个新的DES对象
  DESCryptoServiceProvider desDecrypt= new  DESCryptoServiceProvider();
  //开辟一块内存流,并存放密文字节数组
  MemoryStream msDecrypt= new  MemoryStream(bytesCipher);
  //把内存流对象包装成解密流对象
  CryptoStream csDecrypt= new  CryptoStream(msDecrypt,desDecrypt.CreateDecryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Read);
  //把解密流对象包装成读出流对象
  StreamReader srDecrypt= new  StreamReader(csDecrypt);
  //明文=读出流的读出内容
  string  strPlainText=srDecrypt.ReadLine();
  //读出流关闭
  srDecrypt.Close();
  //解密流关闭
  csDecrypt.Close();
  //内存流关闭
  msDecrypt.Close();
  //返回明文
  return  strPlainText;
}



    本文转自曾祥展博客园博客,原文链接:http://www.cnblogs.com/zengxiangzhan/archive/2010/01/30/1659687.html ,如需转载请自行联系原作者
相关文章
|
4月前
|
存储 运维 监控
基于 C# 语言的 Dijkstra 算法在局域网内监控软件件中的优化与实现研究
本文针对局域网监控系统中传统Dijkstra算法的性能瓶颈,提出了一种基于优先队列和邻接表优化的改进方案。通过重构数据结构与计算流程,将时间复杂度从O(V²)降至O((V+E)logV),显著提升大规模网络环境下的计算效率与资源利用率。实验表明,优化后算法在包含1000节点、5000链路的网络中,计算时间缩短37.2%,内存占用减少21.5%。该算法适用于网络拓扑发现、异常流量检测、故障定位及负载均衡优化等场景,为智能化局域网监控提供了有效支持。
106 5
|
16天前
|
存储 机器学习/深度学习 监控
网络管理监控软件的 C# 区间树性能阈值查询算法
针对网络管理监控软件的高效区间查询需求,本文提出基于区间树的优化方案。传统线性遍历效率低,10万条数据查询超800ms,难以满足实时性要求。区间树以平衡二叉搜索树结构,结合节点最大值剪枝策略,将查询复杂度从O(N)降至O(logN+K),显著提升性能。通过C#实现,支持按指标类型分组建树、增量插入与多维度联合查询,在10万记录下查询耗时仅约2.8ms,内存占用降低35%。测试表明,该方案有效解决高负载场景下的响应延迟问题,助力管理员快速定位异常设备,提升运维效率与系统稳定性。
55 4
|
5月前
|
存储 算法 安全
如何控制上网行为——基于 C# 实现布隆过滤器算法的上网行为管控策略研究与实践解析
在数字化办公生态系统中,企业对员工网络行为的精细化管理已成为保障网络安全、提升组织效能的核心命题。如何在有效防范恶意网站访问、数据泄露风险的同时,避免过度管控对正常业务运作的负面影响,构成了企业网络安全领域的重要研究方向。在此背景下,数据结构与算法作为底层技术支撑,其重要性愈发凸显。本文将以布隆过滤器算法为研究对象,基于 C# 编程语言开展理论分析与工程实践,系统探讨该算法在企业上网行为管理中的应用范式。
159 8
|
5月前
|
存储 监控 算法
解析公司屏幕监控软件中 C# 字典算法的数据管理效能与优化策略
数字化办公的时代背景下,企业为维护信息安全并提升管理效能,公司屏幕监控软件的应用日益普及。此软件犹如企业网络的 “数字卫士”,持续记录员工电脑屏幕的操作动态。然而,伴随数据量的持续增长,如何高效管理这些监控数据成为关键议题。C# 中的字典(Dictionary)数据结构,以其独特的键值对存储模式和高效的操作性能,为公司屏幕监控软件的数据管理提供了有力支持。下文将深入探究其原理与应用。
111 4
|
6月前
|
机器学习/深度学习 监控 算法
员工上网行为监控软件中基于滑动窗口的C#流量统计算法解析​
在数字化办公环境中,员工上网行为监控软件需要高效处理海量网络请求数据,同时实时识别异常行为(如高频访问非工作网站)。传统的时间序列统计方法因计算复杂度过高,难以满足低延迟需求。本文将介绍一种基于滑动窗口的C#统计算法,通过动态时间窗口管理,实现高效的行为模式分析与流量计数。
173 2
|
6月前
|
人工智能 运维 算法
基于 C# 深度优先搜索算法的局域网集中管理软件技术剖析
现代化办公环境中,局域网集中管理软件是保障企业网络高效运行、实现资源合理分配以及强化信息安全管控的核心工具。此类软件需应对复杂的网络拓扑结构、海量的设备信息及多样化的用户操作,而数据结构与算法正是支撑其强大功能的基石。本文将深入剖析深度优先搜索(Depth-First Search,DFS)算法,并结合 C# 语言特性,详细阐述其在局域网集中管理软件中的应用与实现。
146 3
|
3月前
|
监控 算法 安全
基于 C# 基数树算法的网络屏幕监控敏感词检测技术研究
随着数字化办公和网络交互迅猛发展,网络屏幕监控成为信息安全的关键。基数树(Trie Tree)凭借高效的字符串处理能力,在敏感词检测中表现出色。结合C#语言,可构建高时效、高准确率的敏感词识别模块,提升网络安全防护能力。
98 2
|
4月前
|
监控 算法 数据处理
内网实时监控中的 C# 算法探索:环形缓冲区在实时数据处理中的关键作用
本文探讨了环形缓冲区在内网实时监控中的应用,结合C#实现方案,分析其原理与优势。作为固定长度的循环队列,环形缓冲区通过FIFO机制高效处理高速数据流,具备O(1)时间复杂度的读写操作,降低延迟与内存开销。文章从设计逻辑、代码示例到实际适配效果展开讨论,并展望其与AI结合的潜力,为开发者提供参考。
206 2
|
4月前
|
监控 算法 安全
公司电脑监控软件关键技术探析:C# 环形缓冲区算法的理论与实践
环形缓冲区(Ring Buffer)是企业信息安全管理中电脑监控系统设计的核心数据结构,适用于高并发、高速率与短时有效的多源异构数据处理场景。其通过固定大小的连续内存空间实现闭环存储,具备内存优化、操作高效、数据时效管理和并发支持等优势。文章以C#语言为例,展示了线程安全的环形缓冲区实现,并结合URL访问记录监控应用场景,分析了其在流量削峰、关键数据保护和高性能处理中的适配性。该结构在日志捕获和事件缓冲中表现出色,对提升监控系统效能具有重要价值。
118 1
|
5月前
|
存储 监控 算法
基于 C# 的局域网计算机监控系统文件变更实时监测算法设计与实现研究
本文介绍了一种基于C#语言的局域网文件变更监控算法,通过事件驱动与批处理机制结合,实现高效、低负载的文件系统实时监控。核心内容涵盖监控机制选择(如事件触发机制)、数据结构设计(如监控文件列表、事件队列)及批处理优化策略。文章详细解析了C#实现的核心代码,并提出性能优化与可靠性保障措施,包括批量处理、事件过滤和异步处理等技术。最后,探讨了该算法在企业数据安全监控、文件同步备份等场景的应用潜力,以及未来向智能化扩展的方向,如文件内容分析、智能告警机制和分布式监控架构。
155 3

热门文章

最新文章