Usage of TripleDESCryptoServiceProvider.

 
1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.IO;
 6 using System.Security.Cryptography;
 7 namespace StringTest
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             System.Security.Cryptography.TripleDESCryptoServiceProvider tDeSalg = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
14             byte[] keyArray = tDeSalg.Key;
15             byte[] IVArrary = tDeSalg.IV;
16             string plainTextString = "Here is some data to encrypt. 这里是一些要加密的数据。";
17             // 使用utf-8编码(也可以使用其它的编码)
18             Encoding sEncoding = Encoding.GetEncoding("utf-8");
19             // 把字符串明文转换成utf-8编码的字节流
20             byte[] plainTextArray = sEncoding.GetBytes(plainTextString);
21 
22             byte[] encrptedArr = EncryptString(plainTextArray, keyArray, IVArrary);
23 
24             string Output = UTF8Encoding.UTF8.GetString(DecrptString(encrptedArr, keyArray, IVArrary));
25             Console.Write(Output);
26         }
27 
28         public static byte[] EncryptString(byte[] plainTextArray, byte[] Key, byte[] IV)
29         {
30             MemoryStream mStream = new MemoryStream();
31             System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream(
32                 mStream, new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV), CryptoStreamMode.Write);
33             cStream.Write(plainTextArray, 0, plainTextArray.Length);
34 
35             cStream.FlushFinalBlock();
36 
37             byte[] ret = mStream.ToArray();
38             cStream.Close();
39             mStream.Close();
40             return ret;
41         }
42 
43 
44         public static byte[] DecrptString(byte[] encryptedDataArray, byte[] key, byte[] IV)
45         {
46             MemoryStream ms = new MemoryStream(encryptedDataArray);
47             System.Security.Cryptography.CryptoStream cStream = new CryptoStream(ms, new System.Security.Cryptography.TripleDESCryptoServiceProvider().CreateDecryptor(key, IV), CryptoStreamMode.Read);
48             byte[] outPutArrary = new byte[encryptedDataArray.Length];
49             cStream.Read(outPutArrary, 0, outPutArrary.Length);
50             return outPutArrary;
51         }
52     }
53 }

posted on 2011-07-12 17:03  Paul_  阅读(966)  评论(0编辑  收藏  举报

导航