如何使用 Visual C# 加密和解密文件 转载
如何使用 Visual C# 加密和解密文件<div style="FONT-SIZE: 10pt"> <tr> <td style="FONT-SIZE: 10pt">文章编号</td> <td style="FONT-SIZE: 10pt">:</td> <td style="FONT-SIZE: 10pt">307010</td> </tr> <tr> <td style="FONT-SIZE: 10pt">最后修改</td> <td style="FONT-SIZE: 10pt">:</td> <td style="FONT-SIZE: 10pt">2007年1月23日</td> </tr> <tr> <td style="FONT-SIZE: 10pt">修订</td> <td style="FONT-SIZE: 10pt">:</td> <td style="FONT-SIZE: 10pt">7.3</td> </tr> |
<div style="FONT-SIZE: 10pt">本文介绍如何使用 Microsoft .NET Framework 提供的加密类对文本文件进行加密以使其处于不可读状态,然后再对该信息进行解密,以恢复到原来的格式。
<p style="FONT-SIZE: 10pt"><a href="http://support.microsoft.com/kb/307010/zh-cn#top">
<img alt="" src="http://support.microsoft.com/library/images/support/en-us/uparrow.gif">回到顶端
<h3 id="tocHeadRef">要求
下面列出了推荐使用的硬件、软件、网络架构以及所需的 Service Pack:
<table>
<tr>
<td style="FONT-SIZE: 10pt">?</td>
<td style="FONT-SIZE: 10pt">Microsoft Windows 2000 Professional、Windows 2000 Server、Windows 2000 Advanced Server、Windows NT 4.0 Server 或 Microsoft Windows XP Professional</td>
</tr>
<tr>
<td style="FONT-SIZE: 10pt">?</td>
<td style="FONT-SIZE: 10pt">Microsoft Visual Studio 2005 或 Microsoft Visual Studio .NET</td>
</tr>
Microsoft .NET Framework 中的 System.Security.Cryptographic 命名空间提供了多种帮助您加密和解密的工具。CryptoStream 类就是所提供的诸多类中的一个。CryptoStream 类设计用于在内容以流的形式输出到文件时加密和解密内容。
<p style="FONT-SIZE: 10pt"><a href="http://support.microsoft.com/kb/307010/zh-cn#top">
<img alt="" src="http://support.microsoft.com/library/images/support/en-us/uparrow.gif">回到顶端
<h3 id="tocHeadRef">加密文件
要加密文件,请按照下列步骤操作:
<table>
<tr>
<td style="FONT-SIZE: 10pt">1.</td>
<td style="FONT-SIZE: 10pt">启动 Visual Studio 2005 或 Visual Studio .NET。</td>
</tr>
<tr>
<td style="FONT-SIZE: 10pt">2.</td>
<td style="FONT-SIZE: 10pt">单击“项目”下的“Visual C#”,然后单击“模板”下的“控制台应用程序”。Visual C# .NET 为您创建一个静态类,以及一个空的 Main() 过程。</td>
</tr>
<tr>
<td style="FONT-SIZE: 10pt">3.</td>
<td style="FONT-SIZE: 10pt">对以下命名空间使用 using 语句(如以下示例代码中所示):
<table>
<tr>
<td style="FONT-SIZE: 10pt">?</td>
<td style="FONT-SIZE: 10pt">System</td>
</tr>
<tr>
<td style="FONT-SIZE: 10pt">?</td>
<td style="FONT-SIZE: 10pt">System.Security</td>
</tr>
<tr>
<td style="FONT-SIZE: 10pt">?</td>
<td style="FONT-SIZE: 10pt">System.Security.Cryptography</td>
</tr>
<tr>
<td style="FONT-SIZE: 10pt">?</td>
<td style="FONT-SIZE: 10pt">System.Text</td>
</tr>
<tr>
<td style="FONT-SIZE: 10pt">?</td>
<td style="FONT-SIZE: 10pt">System.IO</td>
</tr> using System; using System.IO; using System.Security; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Text;
要解密文件,请按照下列步骤操作:
<table>
<tr>
<td style="FONT-SIZE: 10pt">1.</td>
<td style="FONT-SIZE: 10pt">创建一个方法,然后将它命名为 DecryptFile。解密过程与加密过程相似,但 DecryptFile 过程与 EncryptFile 过程有两个关键区别。
<table>
<tr>
<td style="FONT-SIZE: 10pt">?</td>
<td style="FONT-SIZE: 10pt">CryptoStream 对象是使用 CreateDecryptor 而非 CreateEncryptor 创建的,这将指定对象的使用方式。</td>
</tr>
<tr>
<td style="FONT-SIZE: 10pt">?</td>
<td style="FONT-SIZE: 10pt">在将解密的文本写入到目标文件时,CryptoStream 对象现在是源,而不是目标流。</td>
</tr> static void DecryptFile(string sInputFilename,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,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(); }
用一个文本文件 (.txt) 测试此代码,确认它可对此文件进行正确的加密和解密。确保将文件解密到一个新文件(如本文中的 Main() 过程中所示),而不是解密到原来的文件中。检查解密后的文件,然后与原文件进行比较。
<p style="FONT-SIZE: 10pt"><a href="http://support.microsoft.com/kb/307010/zh-cn#top">
<img alt="" src="http://support.microsoft.com/library/images/support/en-us/uparrow.gif">回到顶端
<h3 id="tocHeadRef">完整代码列表
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 sKey) { FileStream fsInput = new FileStream(sInputFilename,FileAccess.Read); FileStream fsEncrypted = new FileStream(sOutputFilename,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,CryptoStreamMode.Write); byte[] bytearrayinput = new byte[fsInput.Length]; fsInput.Read(bytearrayinput,bytearrayinput.Length); cryptostream.Write(bytearrayinput,bytearrayinput.Length); cryptostream.Close(); fsInput.Close(); fsEncrypted.Close(); } static void DecryptFile(string sInputFilename,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,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,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",sSecretKey); // Decrypt the file. DecryptFile(@"C:Encrypted.txt",sSecretKey); // Remove the Key from memory. ZeroMemory(gch.AddrOfPinnedObject(),sSecretKey.Length * 2); gch.Free(); } } }
<div style="FONT-SIZE: 10pt">有关加密以及使用 .NET 的加密功能的更多信息,请访问下面的 MSDN 网站:
<div style="FONT-SIZE: 10pt">System.Security.Cryptography 命名空间<a href="http://msdn2.microsoft.com/zh-cn/library/system.security.cryptography(VS.80).aspx">http://msdn2.microsoft.com/zh-cn/library/system.security.cryptography(VS.80).aspx (http://msdn2.microsoft.com/zh-cn/library/system.security.cryptography(VS.80).aspx)
<div style="FONT-SIZE: 10pt">Microsoft .NET Framework 开发中心<a href="http://msdn2.microsoft.com/zh-cn/netframework/default.aspx">http://msdn2.microsoft.com/zh-cn/netframework/default.aspx (http://msdn2.microsoft.com/zh-cn/netframework/default.aspx)
有关 Visual C# .NET 的更多一般信息,请访问以下 Usenet 新闻组:
<div style="FONT-SIZE: 10pt">
<a href="http://go.microsoft.com/fwlink/?linkid=5217">microsoft.public.dotnet.languages.csharp (http://go.microsoft.com/fwlink/?linkid=5217)
<p style="FONT-SIZE: 10pt"><a href="http://support.microsoft.com/kb/307010/zh-cn#top">
<img alt="" src="http://support.microsoft.com/library/images/support/en-us/uparrow.gif">回到顶端
这篇文章中的信息适用于:
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!