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



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: Encrypt and Decrypt a file using .NET 2.0?
    ... public static string GenerateKey() ... DES des = DES.Create; ... // 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: FlushFinalBlock method was called twice on a CryptoStream ERROR MESSAGE
    ... and only requires the one CryptoStream object (one for encrypt and one for ... What I meant before is each 32 bytes string ... > TransformBlock to encrypt but haven't had much success unencrypting on the ... >> of the streamReader/writer to save another stream indirection. ...
    (microsoft.public.dotnet.languages.csharp)
  • 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: 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)