?????? ??????This article applies to a different operating system than the one you are using. Article content that may not be relevant to you is disabled.
This article describes how to use the cryptography classes
that are provided by the Microsoft .NET Framework to encrypt a text file to an
unreadable state, and then to decrypt that text file back to its original
format.
TheSystem.Security.Cryptographicnamespace in the Microsoft .NET Framework provides a variety of
tools to help you with encryption and with decryption. TheCryptoStreamclass is one of the many classes that is provided. TheCryptoStreamclass is designed to encrypt or to decrypt content as it is
streamed out to a file.
????? ????,Visual C#?? ???????Projects?? ????-????? ????, ?? ???? ???????? ??????????? ???????????????. Visual C# .NET creates aStaticclass for you, together with an emptyMain()procedure.
?????usingstatement (as indicated in the sample code that follows) on the
following namespaces:
??????
System.Security
System.Security.Cryptography
System.Text
System.IO
so that you do not have to qualify declarations from these
namespaces later in your code. You must use these statements before any other
declarations.
using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
Generate a secret key to encrypt and to decrypt the data.
TheDESCryptoServiceProvideris based on a symmetric encryption algorithm. The symmetric
encryption requires a key and an initialization vector (IV) to encrypt the
data. To decrypt the data, you must have the same key and the same IV. ?? ?? ?? ??????????? ?????????? ?? ?? ????? ???? ?????? ?? ?? ?? ????? ??????? ?? ????? ?? ????? ????? ?? ???? ???:
For more information about how to
generate and distribute keys, see the Microsoft .NET Framework SDK
Documentation, or see the following Microsoft Developer Network (MSDN) Web
site:
Add the following function to generate a new key for a
session (as noted in Method 2 of step 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);
}
Create a method in your class that is namedEncryptFile. TheEncryptFileclass must have the following three parameters:
sInputFilename
sOutputFilename
sKey(The secret key that is used to encrypt and decrypt the
file.)
?????EncryptFileprocedure, create an inputFileStreamobject and an outputFileStream???????? ??? These objects can be read from and written to the target
files.
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.Read);
FileStream fsEncrypted = new FileStream(sOutputFilename,
FileMode.Create,
FileAccess.Write);
Declare an instance of theDESCryptoServiceProviderclass. This represents the actual encryption and the actual
decryption technology that is used on the files. At this point, you can create
a different provider if you prefer to use RSAsecutiry or another cryptographic
technique.
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
The cryptographic provider must be provided with your
secret key as an array of bytes. TheSystem.Textnamespace provides a function that is namedGetBytes(). ???? ????????? ???????? ?? ?? ??? ?? ??? ???GetBytes()?????? ??? ???????? ???? ??, ?? ???? ??? ?????? ?? ??? ???? ???? ??? ????? ?? ???? ??????????????? ??????? ???????? ?? ??? ????? ??? ?????? ?? ???, ???? ??????????? ???? (DES) ???? 64-??? ????? 8 ?????? ?? 8 ?????? ?? ??? ???? ???
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();
}
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();
}
}
}