如何做可回復的加密 |
尚未結案
|
will
中階會員 ![]() ![]() ![]() 發表:176 回覆:135 積分:62 註冊:2002-04-14 發送簡訊給我 |
|
shieh2700
高階會員 ![]() ![]() ![]() ![]() 發表:0 回覆:127 積分:100 註冊:2002-06-13 發送簡訊給我 |
下述範例節錄自:
http://msdn.microsoft.com/library/cht/default.asp?url=/library/CHT/cpref/html/frlrfsystemsecuritycryptographydesclasstopic.php 範例
[Visual Basic, C#, C++] 以下範例方法使用 DESCryptoServiceProvider (DES 的實作) 配合指定的 Key 和初始化向量 (IV),加密由 inName 指定的檔案,並且將加密的結果輸出至 outName 所指定的檔案。
[Visual Basic] Private Shared Sub EncryptData(inName As String, outName As String, _ desKey() As Byte, desIV() As Byte) 'Create the file streams to handle the input and output files. Dim fin As New FileStream(inName, FileMode.Open, FileAccess.Read) Dim fout As New FileStream(outName, FileMode.OpenOrCreate, _ FileAccess.Write) fout.SetLength(0) 'Create variables to help with read and write. Dim bin(4096) As Byte 'This is intermediate storage for the encryption. Dim rdlen As Long = 0 'This is the total number of bytes written. Dim totlen As Long = fin.Length 'Total length of the input file. Dim len As Integer 'This is the number of bytes to be written at a time. Dim des As New DESCryptoServiceProvider() Dim encStream As New CryptoStream(fout, _ des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write) Console.WriteLine("Encrypting...") 'Read from the input file, then encrypt and write to the output file. While rdlen < totlen len = fin.Read(bin, 0, 4096) encStream.Write(bin, 0, len) rdlen = Convert.ToInt32(rdlen len / des.BlockSize * des.BlockSize) Console.WriteLine("Processed {0} bytes, {1} bytes total", len, _ rdlen) End While encStream.Close() End Sub [C#] 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); Console.WriteLine("Encrypting..."); //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; Console.WriteLine("{0} bytes processed", rdlen); } encStream.Close(); fout.Close(); fin.Close(); }[Visual Basic, C#] 解密可用相同的方式處理,即使用 CreateDecryptor ,而非 CreateEncryptor 。用來加密檔案的 Key 和 IV 必須與解密檔案的相同。 |
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |