C# DES加密

需要引用名称空间

1 using System;
2 using System.Text;
3 using System.Security.Cryptography;
4 using System.IO;

具体代码:

 1 public class CryptoHelper
 2     {
 3         /// <summary>
 4         /// 使用DES加密
 5         /// </summary>
 6         /// <param name="plain">明文</param>
 7         /// <param name="key">加密钥匙</param>
 8         /// <param name="iv">向量</param>
 9         /// <returns>返回密文</returns>
10         public static string DesEncode(string plain, string key, string iv)
11         {
12             //把密钥转换成字节数组
13             byte[] keyBytes = Encoding.ASCII.GetBytes(key);
14 
15             //把向量转换成字节数组
16             byte[] ivBytes = Encoding.ASCII.GetBytes(iv);
17 
18             //声明1个新的DES对象 
19             DESCryptoServiceProvider des = new DESCryptoServiceProvider();
20 
21             //开辟一块内存流
22             MemoryStream msEncrypt = new MemoryStream();
23 
24             //把内存流对象包装成加密流对象 
25             CryptoStream csEncrypt = new CryptoStream(msEncrypt, des.CreateEncryptor(keyBytes, ivBytes), CryptoStreamMode.Write);
26 
27             //把加密流对象包装成写入流对象
28             StreamWriter swEncrypt = new StreamWriter(csEncrypt);
29 
30             //写入流对象写入明文  
31             swEncrypt.WriteLine(plain);
32 
33             //写入流关闭  
34             swEncrypt.Close();
35 
36             //加密流关闭  
37             csEncrypt.Close();
38 
39             //把内存流转换成字节数组,内存流现在已经是密文了  
40             byte[] bytesCipher=msEncrypt.ToArray();
41 
42             //内存流关闭 
43             msEncrypt.Close();
44             //将字节数组转化成Base64字符串
45             return Convert.ToBase64String(bytesCipher);
46         }
47 
48         public static string DesDeCode(string cipher, string key, string iv)
49         {
50             //将密文通过Base64位还原成字节数组
51             byte[] cipherByte = Convert.FromBase64String(cipher);
52 
53             //把密钥转换成字节数组
54             byte[] keyBytes = Encoding.ASCII.GetBytes(key);
55 
56             //把向量转换成字节数组
57             byte[] ivBytes = Encoding.ASCII.GetBytes(iv);
58 
59             //声明1个新的DES对象 
60             DESCryptoServiceProvider des = new DESCryptoServiceProvider();
61 
62             //开辟一块内存流,并存放密文字节数组
63             MemoryStream msDecrypt = new MemoryStream(cipherByte);
64 
65             //把内存流对象包装成解密流对象 
66             CryptoStream csDecrypt = new CryptoStream(msDecrypt, des.CreateDecryptor(keyBytes, ivBytes), CryptoStreamMode.Read);
67 
68             //把解密流对象包装成写入流对象
69             StreamReader srDecrypt = new StreamReader(csDecrypt);
70 
71             //明文=读出流的读出内容   
72             string strPlainText=srDecrypt.ReadLine();
73 
74             //读出流关闭  
75             srDecrypt.Close();
76 
77             //解密流关闭  
78             csDecrypt.Close();
79 
80             //内存流关闭  
81             msDecrypt.Close();
82 
83             //返回明文  
84             return strPlainText;
85         }
86     }
原文地址:https://www.cnblogs.com/Jeremy2001/p/6691628.html