Re: Encrypt and Decrypt a file using .NET 2.0?



Actually, here is a better one that handles any size file in buffer size
chunks.

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

namespace Demo
{
public 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);

const int BufSize = 1024;

// Function to Generate a 64 bits Key.
public static string GenerateKey()
{
// Create an instance of Symetric Algorithm. Key and IV is
generated automatically.
DES des = DES.Create();
return Encoding.ASCII.GetString(des.Key);
}

public static void EncryptFile(string inPath, string outPath, string
sKey)
{
DES des = DES.Create();

using (FileStream inFile = File.OpenRead(inPath))
using (FileStream outFile = new FileStream(outPath,
FileMode.Create, FileAccess.Write))
using (ICryptoTransform desencrypt =
des.CreateEncryptor(Encoding.ASCII.GetBytes(sKey),
Encoding.ASCII.GetBytes(sKey)))
using (CryptoStream cryptoStream = new CryptoStream(outFile,
desencrypt, CryptoStreamMode.Write))
{
// Read from in file until EOF and write to crypto stream.
byte[] buf = new byte[BufSize];
int read = 0;
while ((read = inFile.Read(buf, 0, buf.Length)) > 0)
{
cryptoStream.Write(buf, 0, read);
}
cryptoStream.Flush();
outFile.Flush();
}
}

public static void DecryptFile(string inPath, string outPath, string
sKey)
{
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
DES des = DES.Create();

using (FileStream inFile = new FileStream(inPath, FileMode.Open,
FileAccess.Read))
using (FileStream outFile = File.OpenWrite(outPath))
using (ICryptoTransform desdecrypt =
des.CreateDecryptor(Encoding.ASCII.GetBytes(sKey),
Encoding.ASCII.GetBytes(sKey)))
using (CryptoStream cryptoStream = new CryptoStream(inFile,
desdecrypt, CryptoStreamMode.Read))
{
// Read from the cryptoStream until EOF and write decrypted
bytes to outFile.
byte[] ba = new byte[BufSize];
int read = 0;
while ((read = cryptoStream.Read(ba, 0, ba.Length)) > 0)
{
outFile.Write(ba, 0, read);
}
outFile.Flush();
}
}

public static void DoCrypto()
{
// 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);
Console.WriteLine("Encrypted");

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

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

Console.WriteLine("Done.");
Console.WriteLine("Cat Decrypted.txt:");
Cat(@"c:\decrypted.txt");
}

public static void Cat(string path)
{
Console.WriteLine(File.ReadAllText(path));
}
}
}

--
William Stacey [C# MVP]
PCR concurrency library: www.codeplex.com/pcr
PSH Scripts Project www.codeplex.com/psobject


"William Stacey [C# MVP]" <william.stacey@xxxxxxxxx> wrote in message
news:O3JgxahhHHA.4680@xxxxxxxxxxxxxxxxxxxxxxx
| Works over here. Well with text files. It is not a good sample. Try
| something more like:
|
| using System;
| using System.IO;
| using System.Security;
| using System.Security.Cryptography;
| using System.Runtime.InteropServices;
| using System.Text;
|
| namespace Demo
| {
| public 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.
| public 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);
| }
|
| public static void EncryptFile(string sInputFilename, string
| sOutputFilename, string sKey)
| {
| DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
|
| using (FileStream inFile = new FileStream(sInputFilename,
| FileMode.Open, FileAccess.Read) )
| using (FileStream outFile = new FileStream(sOutputFilename,
| FileMode.Create, FileAccess.Write))
| using (ICryptoTransform desencrypt =
| DES.CreateEncryptor(Encoding.ASCII.GetBytes(sKey),
| Encoding.ASCII.GetBytes(sKey)))
| using (CryptoStream cryptoStream = new CryptoStream(outFile,
| desencrypt, CryptoStreamMode.Write))
| {
| byte[] bytearrayinput = new byte[inFile.Length];
| inFile.Read(bytearrayinput, 0, bytearrayinput.Length);
| cryptoStream.Write(bytearrayinput, 0,
| bytearrayinput.Length);
| cryptoStream.Flush();
| outFile.Flush();
| }
| }
|
| public static void DecryptFile(string sInputFilename, string
| sOutputFilename, string sKey)
| {
| //A 64 bit key and IV is required for this provider.
| //Set secret key For DES algorithm.
| DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
|
| using (FileStream inFile = new FileStream(sInputFilename,
| FileMode.Open, FileAccess.Read))
| using (FileStream outFile = File.OpenWrite(sOutputFilename))
| using (ICryptoTransform desdecrypt =
| DES.CreateDecryptor(Encoding.ASCII.GetBytes(sKey),
| Encoding.ASCII.GetBytes(sKey)))
| using (CryptoStream cryptoStream = new CryptoStream(inFile,
| desdecrypt, CryptoStreamMode.Read))
| {
| // Read from the cryptoStream until EOF and write decrypted
| bytes to outFile.
| byte[] ba = new byte[1024];
| int count = 0;
| while ((count = cryptoStream.Read(ba, 0, ba.Length)) > 0)
| {
| outFile.Write(ba, 0, count);
| }
| outFile.Flush();
| }
| }
|
| public static void DoCrypto()
| {
| // 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);
| Console.WriteLine("Encrypted");
|
| // Decrypt the file.
| DecryptFile(@"C:\Encrypted.txt",
| @"C:\Decrypted.txt",sSecretKey);
| Console.WriteLine("Decrypted.");
|
| // Remove the Key from memory.
| ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
| gch.Free();
|
| Console.WriteLine("Done.");
| Console.WriteLine("Cat Decrypted.txt:");
| Cat(@"c:\decrypted.txt");
| }
|
| public static void Cat(string path)
| {
| Console.WriteLine(File.ReadAllText(path));
| }
| }
| }
|
|
| --
| William Stacey [C# MVP]
| PCR concurrency library: www.codeplex.com/pcr
| PSH Scripts Project www.codeplex.com/psobject
|
|
| "JDeats" <Jeremy.Deats@xxxxxxxxx> wrote in message
| news:1177376866.469669.265330@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
||I have some .NET 1.1 code that utilizes this technique for encrypting
|| and decrypting a file.
|| http://support.microsoft.com/kb/307010
||
|| In .NET 2.0 this approach is not fully supported (a .NET 2.0 build
|| with these methods, will appear to encrypt and decrypt, but the
|| resulting decrypted file will be corrupted. I tried encrypting a .bmp
|| file and then decrypting, the resulting decrypted file under .NET 2.0
|| is garbage, the .NET 1.1 build works as expected).
||
|| I would like to know why this approach is no longer supported, aside
|| from building a .NET 1.1 class library and referencing it in my .NET
|| 2.0 project, what is the proper way to encrypt and decrypt a file
|| using ,NET 2.0 and the DES encryption algorithm.
||
|
|


.



Relevant Pages

  • RE: Using Win32 CryptDecrypt to Decrypt RijndaelManaged
    ... I figured out how to use RijndaelManaged with AES in the C++ app. ... C++ crypto WILL successfully decrypt the .NET generated ... I am trying to write a Win32 app that can decrypt that string using the ... I can get both to encrypt and decrypt successfully in their own projects, ...
    (microsoft.public.platformsdk.security)
  • Re: .NET Crypto Classes Interoperability with Win32 Crypto APIs
    ... >the hash of the string you are feeding in. ... when i encrypt a string using .NET classes and try ... >> decrypt it using Win32 APIs, ...
    (microsoft.public.dotnet.security)
  • Re: Encrypt and Decrypt a file using .NET 2.0?
    ... public static string GenerateKey() ... using (CryptoStream cryptoStream = new CryptoStream(outFile, ... // Distribute this key to the user who will decrypt this file. ... // Get the Key for the file to Encrypt. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Decryptionfailed to bring original text back....
    ... cryptography, but now using them on web.config, any idea, I like to ... There isn't really much reason to encrypt a .NET string with ... what happen when you decrypt the encrypted ...
    (microsoft.public.dotnet.security)
  • Re: Is this Possible?
    ... Encrypt it using DES. ... To decrypt, you will have to count the number of IP:PORT data values ... first 6 bytes from the DES result and XOR it with the encrypted data item. ...
    (sci.crypt)