วิธีการเข้ารหัส และถอดรหัสลับแฟ้ม โดยใช้ Visual C#

หมายเลขบทความ (Article ID): 307010 - ผลิตภัณฑ์ที่เกี่ยวข้องในบทความนี้
สำหรับ Microsoft Visual Basicสุทธิรุ่นของบทความนี้ ดู 301070.
บทความนี้อ้างถึงเว็บไซต์ Microsoft ต่อไปนี้สุทธิ จำนวนมากไลบรารีคลาสกรอบ:
  • System.IO
  • System.Security
  • System.Security.Cryptography
หมายเหตุ บทความนี้ไม่ใช้กับ MicrosoftNET Framework 2.0
ขยายทั้งหมด | ยุบทั้งหมด

เนื้อหาบนหน้านี้

สรุป

บทความนี้อธิบายวิธีการใช้การเข้ารหัสคลา ที่จัดหาให้ โดย Microsoftโปรดเรียกการเข้ารหัสแฟ้มข้อความไปยัง สถานะที่ไม่สามารถอ่าน แล้วถอดรหัสแฟ้มข้อความนั้นกลับไปต้นฉบับ รูปแบบ

ความต้องการ

รายการต่อไปนี้จะให้คำอธิบายเกี่ยวกับฮาร์ดแวร์แนะนำ ซอฟต์แวร์ โครงสร้างพื้นฐานเครือข่าย และ service pack ที่คุณต้องมี:
  • Microsoft Windows 2000 Professional, Windows 2000 Server Windows 2000 Server เซิร์ฟเวอร์ Windows NT 4.0 หรือ Microsoft Windows XP การขั้นสูง Professional
  • Microsoft Visual Studio 2005 หรือ Microsoft Visual Studio .สุทธิ

การเข้ารหัสลับและการถอดรหัสลับ

Namespace ของSystem.Security.Cryptographicใน Microsoftการจัดการและส่งให้มากมาย เครื่องมือเพื่อช่วยคุณในการเข้ารหัส และถอดรหัสลับ คลาCryptoStreamเป็นหนึ่งในประเภทสินค้าจำนวนมากที่ได้รับ คลาCryptoStreamถูกออกแบบมา เพื่อเข้ารหัสลับ หรือถอดรหัสลับเนื้อหาซึ่งเป็น ส่งเป็นกระแสข้อมูลออกไปยังแฟ้ม

การเข้ารหัสลับแฟ้ม

การเข้ารหัสลับแฟ้ม ให้ทำตามขั้นตอนเหล่านี้:
  1. เริ่ม Visual Studio 2005 หรือ Visual Studioการเปลี่ยนแปลง
  2. คลิก Visual C# ภายใต้โครงการแล้ว คลิก แอพลิเคชันของคอนโซลภายใต้ แม่แบบ. Visual C#สุทธิสร้างคลาStaticคุณร่วมกับกระบวนงานMain()ว่างเปล่า
  3. ใช้ (ตามที่ระบุไว้ในตัวอย่างรหัสต่อไปนี้) คำสั่งที่ใช้ในการ จำนวนมากดังต่อไปนี้:
    • ระบบ
    • System.Security
    • System.Security.Cryptography
    • System.Text
    • System.IO
    เพื่อให้คุณไม่ได้รับการประกาศจากเหล่านี้ จำนวนมากในภายหลังในรหัสของคุณ คุณต้องใช้คำสั่งเหล่านี้ก่อนอื่น ประกาศ
    using System;
    using System.IO;
    using System.Security;
    using System.Security.Cryptography;
    using System.Runtime.InteropServices;
    using System.Text;
    					
  4. สร้างคีย์ลับใน การเข้ารหัส และถอดรหัสข้อมูลนั้น DESCryptoServiceProviderจะขึ้นอยู่กับอัลกอริทึมการเข้ารหัสลับแบบ ในแบบ ต้องมีการเข้ารหัสลับคีย์และ initialization vector (IV) เพื่อเข้ารหัสลับ ข้อมูล เมื่อต้องการถอดรหัสลับข้อมูล คุณต้องมีคีย์เดียวกันและ IV เดียวกัน คุณต้องการ นอกจากนี้ ใช้อัลกอริทึมการเข้ารหัสลับเดียวกัน คุณสามารถสร้างคีย์ โดยใช้ อย่างใดอย่างหนึ่งในวิธีต่อไปนี้:
    • วิธีที่ 1 คุณสามารถแสดงพร้อมท์ให้ผู้ใช้ใส่รหัสผ่าน ใช้รหัสผ่านเป็นแล้ว คีย์นี้และ IV
    • วิธีที่ 2 เมื่อคุณสร้างอินสแตนซ์ใหม่ของแบบที่เข้ารหัสลับ คลาสที่ คีย์ใหม่ และ IV โดยการสำหรับเซสชัน ใช้ คีย์และ IV ที่สร้างขึ้น โดยมีการจัดการแบบเข้ารหัสประเภทสินค้าเพื่อ เข้ารหัส และถอดรหัสลับแฟ้ม

      สำหรับข้อมูลเพิ่มเติมเกี่ยวกับวิธีการ สร้างกระจายคีย์ ดู MicrosoftNET Framework SDK เอกสารประกอบ หรือดูที่เว็บเครือข่ายนักพัฒนา Microsoft (MSDN) ต่อไปนี้ ไซต์:
  5. เพิ่มฟังก์ชันต่อไปนี้เพื่อสร้างคีย์ใหม่สำหรับการ เซสชัน (ตามที่ระบุไว้ในวิธีที่ 2 ขั้นตอนที่ 4):
    //  Call this function to remove the key from memory after use for security.
    [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")]
    public static extern bool ZeroMemory(ref string Destination, int Length);
    		
    // Function to Generate a 64 bits Key.
    static string GenerateKey() 
    {
    	// Create an instance of Symetric Algorithm. Key and IV is generated automatically.
    	DESCryptoServiceProvider desCrypto =(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
    
    	// Use the Automatically generated key for Encryption. 
    	return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
    }
  6. สร้างวิธีการในระดับชั้นของคุณที่ชื่อEncryptFile คลาEncryptFileต้องมีสามพารามิเตอร์ต่อไปนี้:
    • sInputFilename
    • sOutputFilename
    • sKey (คีย์ลับที่ใช้ในการเข้ารหัส และถอดรหัสลับ แฟ้ม)
    static void EncryptFile(string sInputFilename,
    		string sOutputFilename,
    		string sKey)
    					
  7. ในขั้นตอนEncryptFileสร้างวัตถุFileStreamค่านำเข้าและขาออกวัตถุFileStream วัตถุเหล่านี้สามารถอ่าน และเขียนไปยังเป้าหมาย แฟ้ม
    FileStream fsInput = new FileStream(sInputFilename, 
    				FileMode.Open, 
    				FileAccess.Read);
    
    FileStream fsEncrypted = new FileStream(sOutputFilename, 
    				FileMode.Create, 
    				FileAccess.Write);
    					
  8. ประกาศอินสแตนซ์ของคลาสDESCryptoServiceProvider แสดงถึงการเข้ารหัสลับที่แท้จริงและที่เกิดขึ้นจริง เทคโนโลยีการถอดรหัสลับที่ใช้ในแฟ้ม ณจุดนี้ คุณสามารถสร้าง ผู้ให้บริการที่แตกต่างกันถ้าคุณต้องการใช้ RSAsecutiry หรือเงื่อนไขอื่นที่เข้ารหัสลับ เทคนิค
    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
    					
  9. ผู้ให้บริการการเข้ารหัสลับจะต้องให้มาพร้อมกับของคุณ มีคีย์ลับที่เป็นอาร์เรย์ของไบต์ System.Text namespace มีฟังก์ชันที่ชื่อGetBytes() เป็นส่วนหนึ่งของคุณลักษณะการเข้ารหัสGetBytes()ฟังก์ชันสายอักขระที่ใช้ แล้ว ส่งกลับค่าอาร์เรย์ของไบต์ ที่ ขนาดของคีย์แตกต่างกันสำหรับแต่ละเทคนิคการเข้ารหัสลับได้ ตัวอย่าง ข้อมูลการเข้ารหัสลับมาตรฐาน (DES) ใช้คีย์แบบ 64 บิตที่มีค่าเท่ากับ 8 ไบต์ หรือ เมื่อต้องการอักขระ 8 ตัว

    ถ้าคุณไม่ได้ใส่คีย์ ผู้ให้บริการแบบสุ่ม สร้างหนึ่ง ซึ่งเข้ารหัสลับแฟ้มเรียบร้อยแล้ว แต่ไม่มีวิธีการ ถอดรหัสลับแฟ้ม หมายเหตุว่า คุณต้องให้เวกเตอร์การเตรียมใช้งาน (IV) มีใช้ค่านี้เป็นส่วนหนึ่งของการเข้ารหัสลับ เช่นเดียวกับคีย์ IV มี สร้างขึ้นถ้าคุณไม่ใส่ค่าแบบสุ่ม เนื่องจากค่าต้อง อนุญาตเหมือนกันสำหรับการเข้ารหัสลับและการถอดรหัสลับ คุณต้องไม่ให้มีการสุ่ม การสร้างค่าเหล่านี้
    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
    					
  10. สร้างอินสแตนซ์ของคลาสCryptoStreamโดยใช้ตัวให้บริการการเข้ารหัสลับเพื่อขอรับการเข้ารหัสลับ วัตถุ (CreateEncryptor) และที่มีอยู่แสดงวัตถุFileStreamเป็นส่วนหนึ่งของตัวสร้าง
    ICryptoTransform desencrypt = DES.CreateEncryptor();
    CryptoStream cryptostream = new CryptoStream(fsEncrypted, 
    					desencrypt, 
    					CryptoStreamMode.Write);
    					
  11. อ่านในแฟ้มที่นำเข้า และเขียนออกมาเพื่อแสดงผล แฟ้ม ผ่านวัตถุCryptoStreamที่แฟ้มถูกเข้ารหัสลับ โดยใช้คีย์ที่คุณ จัดไว้ให้
    byte[] bytearrayinput = new byte[fsInput.Length - 1];
    fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
    cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
    					

ถอดรหัสไฟล์ได้

เมื่อต้องการถอดรหัสไฟล์ได้ ให้ทำตามขั้นตอนเหล่านี้:
  1. สร้างวิธีการ และตั้งชื่อเป็นDecryptFile. กระบวนการถอดรหัสลับที่คล้ายกันกับ กระบวนการเข้ารหัส อย่างไรก็ตามDecryptFileขั้นตอนมีความแตกต่างที่สำคัญสองจากกระบวนการEncryptFile
    • ใช้CreateDecryptorแทนของCreateEncryptorในการสร้างวัตถุCryptoStreamที่ระบุวิธีใช้วัตถุ
    • เมื่อเขียนข้อความแบบถอดรหัสลับไปยังปลายทาง ขณะนี้แฟ้มCryptoStreamวัตถุต้นทางของปลายทาง กระแสข้อมูล
    static void DecryptFile(string sInputFilename, 
    	                string sOutputFilename,
    	                string sKey)
    {
    	DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
    	//A 64 bit key and IV is required for this provider.
    	//Set secret key For DES algorithm.
    	DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    	//Set initialization vector.
    	DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
    
    	//Create a file stream to read the encrypted file back.
    	FileStream fsread = new FileStream(sInputFilename, 
    		                           FileMode.Open, 
    		                           FileAccess.Read);
    	//Create a DES decryptor from the DES instance.
    	ICryptoTransform desdecrypt = DES.CreateDecryptor();
    	//Create crypto stream set to read and do a 
    	//DES decryption transform on incoming bytes.
    	CryptoStream cryptostreamDecr = new CryptoStream(fsread, 
    		                                         desdecrypt,
    		                                         CryptoStreamMode.Read);
    	//Print the contents of the decrypted file.
    	StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
    	fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
    	fsDecrypted.Flush();
    	fsDecrypted.Close();
    }
    					
  2. เพิ่มบรรทัดต่อไปนี้: Main()ขั้นตอนการเรียกทั้งEncryptFileและDecryptFile
    static void Main()
    {
          // Must be 64 bits, 8 bytes.
          // Distribute this key to the user who will decrypt this file.
          string sSecretKey;
             
          // Get the key for the file to encrypt.
          sSecretKey = GenerateKey();
    
          // For additional security pin the key.
          GCHandle gch = GCHandle.Alloc( sSecretKey,GCHandleType.Pinned );
             
          // Encrypt the file.        
          EncryptFile(@"C:\MyData.txt", 
             @"C:\Encrypted.txt", 
             sSecretKey);
    
          // Decrypt the file.
          DecryptFile(@"C:\Encrypted.txt", 
             @"C:\Decrypted.txt", 
             sSecretKey);
    
          // Remove the key from memory. 
          ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
          gch.Free();
    }
  3. บันทึกแฟ้ม เรียกใช้โปรแกรมประยุกต์ของคุณ ตรวจสอบให้แน่ใจว่าการ เส้นทางที่ใช้สำหรับจุดชื่อแฟ้มการป้อนข้อมูลที่มีอยู่แล้ว แฟ้ม

ขั้นตอนทดสอบ

ทดสอบรหัสนี้กับแฟ้มข้อความ (.txt) เพื่อยืนยันว่า รหัส การเข้ารหัสลับ และการถอดรหัสลับแฟ้มได้อย่างถูกต้อง ตรวจสอบให้แน่ใจว่า คุณถอดรหัสลับแฟ้ม ไปยังแฟ้มใหม่ (เช่นในกระบวนงานMain()ในบทความนี้) แทนที่จะไปยังแฟ้มต้นฉบับ ตรวจสอบแฟ้มการถอดรหัสลับ และเปรียบเทียบกับแฟ้มต้นฉบับ

รายการรหัสเสร็จสมบูรณ์

using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;

namespace CSEncryptDecrypt
{
   class Class1
   {
      //  Call this function to remove the key from memory after use for security
      [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")]
      public static extern bool ZeroMemory(IntPtr Destination, int Length);
		
      // Function to Generate a 64 bits Key.
      static string GenerateKey() 
      {
         // Create an instance of Symetric Algorithm. Key and IV is generated automatically.
         DESCryptoServiceProvider desCrypto =(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

         // Use the Automatically generated key for Encryption. 
         return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
      }

      static void EncryptFile(string sInputFilename,
         string sOutputFilename, 
         string sKey) 
      {
         FileStream fsInput = new FileStream(sInputFilename, 
            FileMode.Open, 
            FileAccess.Read);

         FileStream fsEncrypted = new FileStream(sOutputFilename, 
            FileMode.Create, 
            FileAccess.Write);
         DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
         DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
         DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
         ICryptoTransform desencrypt = DES.CreateEncryptor();
         CryptoStream cryptostream = new CryptoStream(fsEncrypted, 
            desencrypt, 
            CryptoStreamMode.Write); 

         byte[] bytearrayinput = new byte[fsInput.Length];
         fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
         cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
         cryptostream.Close();
         fsInput.Close();
         fsEncrypted.Close();
      }

      static void DecryptFile(string sInputFilename, 
         string sOutputFilename,
         string sKey)
      {
         DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
         //A 64 bit key and IV is required for this provider.
         //Set secret key For DES algorithm.
         DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
         //Set initialization vector.
         DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

         //Create a file stream to read the encrypted file back.
         FileStream fsread = new FileStream(sInputFilename, 
            FileMode.Open, 
            FileAccess.Read);
         //Create a DES decryptor from the DES instance.
         ICryptoTransform desdecrypt = DES.CreateDecryptor();
         //Create crypto stream set to read and do a 
         //DES decryption transform on incoming bytes.
         CryptoStream cryptostreamDecr = new CryptoStream(fsread, 
            desdecrypt,
            CryptoStreamMode.Read);
         //Print the contents of the decrypted file.
         StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
         fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
         fsDecrypted.Flush();
         fsDecrypted.Close();
      } 

      static void Main()
      {
         // Must be 64 bits, 8 bytes.
         // Distribute this key to the user who will decrypt this file.
         string sSecretKey;
         
         // Get the Key for the file to Encrypt.
         sSecretKey = GenerateKey();

         // For additional security Pin the key.
         GCHandle gch = GCHandle.Alloc( sSecretKey,GCHandleType.Pinned );
         
         // Encrypt the file.        
         EncryptFile(@"C:\MyData.txt", 
            @"C:\Encrypted.txt", 
            sSecretKey);

         // Decrypt the file.
         DecryptFile(@"C:\Encrypted.txt", 
            @"C:\Decrypted.txt", 
            sSecretKey);

         // Remove the Key from memory. 
         ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
         gch.Free();
      }
   }
}

ข้อมูลอ้างอิง

สำหรับข้อมูลเพิ่มเติม เกี่ยวกับการเข้ารหัส และใช้ใน คุณลักษณะการเข้ารหัสลับของสุทธิ ดูเว็บไซต์ต่อไปนี้:
System.Security.Cryptography namespace
Microsoftศูนย์นักพัฒนาของกรอบสุทธิ
สำหรับข้อมูลเพิ่มเติมเกี่ยวกับ Visual C#สุทธิ ดู กลุ่มข่าวสาร usenet บนต่อไปนี้:
microsoft.public.dotnet.languages.csharp

คุณสมบัติ

หมายเลขบทความ (Article ID): 307010 - รีวิวครั้งสุดท้าย: 11 มิถุนายน 2555 - Revision: 5.0
ใช้กับ
  • Microsoft Visual C# 2005
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords: 
kbsecurity kbio kbcrypt kbhowtomaster kbmt KB307010 KbMtth
แปลโดยคอมพิวเตอร์
ข้อมูลสำคัญ: บทความนี้แปลโดยซอฟต์แวร์การแปลด้วยคอมพิวเตอร์ของ Microsoft แทนที่จะเป็นนักแปลที่เป็นบุคคล Microsoft มีบทความที่แปลโดยนักแปลและบทความที่แปลด้วยคอมพิวเตอร์ เพื่อให้คุณสามารถเข้าถึงบทความทั้งหมดในฐานความรู้ของเรา ในภาษาของคุณเอง อย่างไรก็ตาม บทความที่แปลด้วยคอมพิวเตอร์นั้นอาจมีข้อบกพร่อง โดยอาจมีข้อผิดพลาดในคำศัพท์ รูปแบบการใช้ภาษาและไวยากรณ์ เช่นเดียวกับกรณีที่ชาวต่างชาติพูดผิดเมื่อพูดภาษาของคุณ Microsoft ไม่มีส่วนรับผิดชอบต่อความคลาดเคลื่อน ความผิดพลาดหรือความเสียหายที่เกิดจากการแปลเนื้อหาผิดพลาด หรือการใช้บทแปลของลูกค้า และ Microsoft มีการปรับปรุงซอฟต์แวร์การแปลด้วยคอมพิวเตอร์อยู่เป็นประจำ
ต่อไปนี้เป็นฉบับภาษาอังกฤษของบทความนี้:307010

ให้ข้อเสนอแนะ