473,725 Members | 2,295 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Encrypt and Decrypt a file using .NET 2.0?

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.

Apr 24 '07 #1
3 8294
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("KER NEL32.DLL", EntryPoint
= "RtlZeroMemory" )]
public static extern bool ZeroMemory(IntP tr 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.
DESCryptoServic eProvider desCrypto =
(DESCryptoServi ceProvider)DESC ryptoServicePro vider.Create();

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

public static void EncryptFile(str ing sInputFilename, string
sOutputFilename , string sKey)
{
DESCryptoServic eProvider DES = new DESCryptoServic eProvider();

using (FileStream inFile = new FileStream(sInp utFilename,
FileMode.Open, FileAccess.Read ) )
using (FileStream outFile = new FileStream(sOut putFilename,
FileMode.Create , FileAccess.Writ e))
using (ICryptoTransfo rm desencrypt =
DES.CreateEncry ptor(Encoding.A SCII.GetBytes(s Key),
Encoding.ASCII. GetBytes(sKey)) )
using (CryptoStream cryptoStream = new CryptoStream(ou tFile,
desencrypt, CryptoStreamMod e.Write))
{
byte[] bytearrayinput = new byte[inFile.Length];
inFile.Read(byt earrayinput, 0, bytearrayinput. Length);
cryptoStream.Wr ite(bytearrayin put, 0,
bytearrayinput. Length);
cryptoStream.Fl ush();
outFile.Flush() ;
}
}

public static void DecryptFile(str ing sInputFilename, string
sOutputFilename , string sKey)
{
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
DESCryptoServic eProvider DES = new DESCryptoServic eProvider();

using (FileStream inFile = new FileStream(sInp utFilename,
FileMode.Open, FileAccess.Read ))
using (FileStream outFile = File.OpenWrite( sOutputFilename ))
using (ICryptoTransfo rm desdecrypt =
DES.CreateDecry ptor(Encoding.A SCII.GetBytes(s Key),
Encoding.ASCII. GetBytes(sKey)) )
using (CryptoStream cryptoStream = new CryptoStream(in File,
desdecrypt, CryptoStreamMod e.Read))
{
// Read from the cryptoStream until EOF and write decrypted
bytes to outFile.
byte[] ba = new byte[1024];
int count = 0;
while ((count = cryptoStream.Re ad(ba, 0, ba.Length)) 0)
{
outFile.Write(b a, 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.Pi nned);

// Encrypt the file.
EncryptFile(@"C :\MyData.txt", @"C:\Encrypted. txt", sSecretKey);
Console.WriteLi ne("Encrypted") ;

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

// Remove the Key from memory.
ZeroMemory(gch. AddrOfPinnedObj ect(), sSecretKey.Leng th * 2);
gch.Free();

Console.WriteLi ne("Done.");
Console.WriteLi ne("Cat Decrypted.txt:" );
Cat(@"c:\decryp ted.txt");
}

public static void Cat(string path)
{
Console.WriteLi ne(File.ReadAll Text(path));
}
}
}
--
William Stacey [C# MVP]
PCR concurrency library: www.codeplex.com/pcr
PSH Scripts Project www.codeplex.com/psobject
"JDeats" <Je**********@g mail.comwrote in message
news:11******** **************@ n76g2000hsh.goo glegroups.com.. .
|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.
|
Apr 24 '07 #2
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("KER NEL32.DLL", EntryPoint
= "RtlZeroMemory" )]
public static extern bool ZeroMemory(IntP tr 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.K ey);
}

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

using (FileStream inFile = File.OpenRead(i nPath))
using (FileStream outFile = new FileStream(outP ath,
FileMode.Create , FileAccess.Writ e))
using (ICryptoTransfo rm desencrypt =
des.CreateEncry ptor(Encoding.A SCII.GetBytes(s Key),
Encoding.ASCII. GetBytes(sKey)) )
using (CryptoStream cryptoStream = new CryptoStream(ou tFile,
desencrypt, CryptoStreamMod e.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.Wr ite(buf, 0, read);
}
cryptoStream.Fl ush();
outFile.Flush() ;
}
}

public static void DecryptFile(str ing 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(inPa th, FileMode.Open,
FileAccess.Read ))
using (FileStream outFile = File.OpenWrite( outPath))
using (ICryptoTransfo rm desdecrypt =
des.CreateDecry ptor(Encoding.A SCII.GetBytes(s Key),
Encoding.ASCII. GetBytes(sKey)) )
using (CryptoStream cryptoStream = new CryptoStream(in File,
desdecrypt, CryptoStreamMod e.Read))
{
// Read from the cryptoStream until EOF and write decrypted
bytes to outFile.
byte[] ba = new byte[BufSize];
int read = 0;
while ((read = cryptoStream.Re ad(ba, 0, ba.Length)) 0)
{
outFile.Write(b a, 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.Pi nned);

// Encrypt the file.
EncryptFile(@"C :\MyData.txt", @"C:\Encrypted. txt", sSecretKey);
Console.WriteLi ne("Encrypted") ;

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

// Remove the Key from memory.
ZeroMemory(gch. AddrOfPinnedObj ect(), sSecretKey.Leng th * 2);
gch.Free();

Console.WriteLi ne("Done.");
Console.WriteLi ne("Cat Decrypted.txt:" );
Cat(@"c:\decryp ted.txt");
}

public static void Cat(string path)
{
Console.WriteLi ne(File.ReadAll Text(path));
}
}
}

--
William Stacey [C# MVP]
PCR concurrency library: www.codeplex.com/pcr
PSH Scripts Project www.codeplex.com/psobject
"William Stacey [C# MVP]" <wi************ @gmail.comwrote in message
news:O3******** ******@TK2MSFTN GP06.phx.gbl...
| 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("KER NEL32.DLL",
EntryPoint
| = "RtlZeroMemory" )]
| public static extern bool ZeroMemory(IntP tr 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.
| DESCryptoServic eProvider desCrypto =
| (DESCryptoServi ceProvider)DESC ryptoServicePro vider.Create();
|
| // Use the Automatically generated key for Encryption.
| return ASCIIEncoding.A SCII.GetString( desCrypto.Key);
| }
|
| public static void EncryptFile(str ing sInputFilename, string
| sOutputFilename , string sKey)
| {
| DESCryptoServic eProvider DES = new DESCryptoServic eProvider();
|
| using (FileStream inFile = new FileStream(sInp utFilename,
| FileMode.Open, FileAccess.Read ) )
| using (FileStream outFile = new FileStream(sOut putFilename,
| FileMode.Create , FileAccess.Writ e))
| using (ICryptoTransfo rm desencrypt =
| DES.CreateEncry ptor(Encoding.A SCII.GetBytes(s Key),
| Encoding.ASCII. GetBytes(sKey)) )
| using (CryptoStream cryptoStream = new CryptoStream(ou tFile,
| desencrypt, CryptoStreamMod e.Write))
| {
| byte[] bytearrayinput = new byte[inFile.Length];
| inFile.Read(byt earrayinput, 0, bytearrayinput. Length);
| cryptoStream.Wr ite(bytearrayin put, 0,
| bytearrayinput. Length);
| cryptoStream.Fl ush();
| outFile.Flush() ;
| }
| }
|
| public static void DecryptFile(str ing sInputFilename, string
| sOutputFilename , string sKey)
| {
| //A 64 bit key and IV is required for this provider.
| //Set secret key For DES algorithm.
| DESCryptoServic eProvider DES = new DESCryptoServic eProvider();
|
| using (FileStream inFile = new FileStream(sInp utFilename,
| FileMode.Open, FileAccess.Read ))
| using (FileStream outFile = File.OpenWrite( sOutputFilename ))
| using (ICryptoTransfo rm desdecrypt =
| DES.CreateDecry ptor(Encoding.A SCII.GetBytes(s Key),
| Encoding.ASCII. GetBytes(sKey)) )
| using (CryptoStream cryptoStream = new CryptoStream(in File,
| desdecrypt, CryptoStreamMod e.Read))
| {
| // Read from the cryptoStream until EOF and write decrypted
| bytes to outFile.
| byte[] ba = new byte[1024];
| int count = 0;
| while ((count = cryptoStream.Re ad(ba, 0, ba.Length)) 0)
| {
| outFile.Write(b a, 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.Pi nned);
|
| // Encrypt the file.
| EncryptFile(@"C :\MyData.txt", @"C:\Encrypted. txt", sSecretKey);
| Console.WriteLi ne("Encrypted") ;
|
| // Decrypt the file.
| DecryptFile(@"C :\Encrypted.txt ",
| @"C:\Decrypted. txt",sSecretKey );
| Console.WriteLi ne("Decrypted." );
|
| // Remove the Key from memory.
| ZeroMemory(gch. AddrOfPinnedObj ect(), sSecretKey.Leng th * 2);
| gch.Free();
|
| Console.WriteLi ne("Done.");
| Console.WriteLi ne("Cat Decrypted.txt:" );
| Cat(@"c:\decryp ted.txt");
| }
|
| public static void Cat(string path)
| {
| Console.WriteLi ne(File.ReadAll Text(path));
| }
| }
| }
|
|
| --
| William Stacey [C# MVP]
| PCR concurrency library: www.codeplex.com/pcr
| PSH Scripts Project www.codeplex.com/psobject
|
|
| "JDeats" <Je**********@g mail.comwrote in message
| news:11******** **************@ n76g2000hsh.goo glegroups.com.. .
||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.
||
|
|
Apr 24 '07 #3
Ok, last one. Made more general to handle all currently supported symmetric
algos. Also changed to use Streams instead of just files, so can do with
any stream and added helpers over the stream overloads to work with files
and buffers. Also makes IV required.

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

namespace Demo
{
public enum CryptoAlgo
{
DES,
RC2,
Rijndael,
TripleDES
}

public class Crypto : IDisposable
{
// Call this function to remove the key from memory after use for
security
[System.Runtime. InteropServices .DllImport("KER NEL32.DLL", EntryPoint
= "RtlZeroMemory" )]
private static extern bool ZeroMemory(IntP tr Destination, int
Length);
private SymmetricAlgori thm cAlgo;
private readonly int BufSize = 1024;

public Crypto(CryptoAl go algo) : this(algo, null, null)
{
}
public Crypto(CryptoAl go algo, string key, string iv)
{
switch (algo)
{
case CryptoAlgo.DES:
cAlgo = DES.Create();
break;
case CryptoAlgo.RC2:
cAlgo = RC2.Create();
break;
case CryptoAlgo.Rijn dael:
cAlgo = Rijndael.Create ();
break;
case CryptoAlgo.Trip leDES:
cAlgo = TripleDES.Creat e();
break;
default:
throw new ArgumentOutOfRa ngeException("a lgo");
}

if (key != null)
{
cAlgo.Key = Convert.FromBas e64String(key);
cAlgo.IV = Convert.FromBas e64String(iv);
}
}

/// <summary>
/// Gets the key for the algorithm as a Base64 string.
/// </summary>
public string Key
{
get
{
return Convert.ToBase6 4String(cAlgo.K ey);
}
}

/// <summary>
/// Gets the IV for the algorithm as a Base64 string.
/// </summary>
public string IV
{
get { return Convert.ToBase6 4String(cAlgo.I V); }
}

public void EncryptFile(str ing inPath, string outPath)
{
using (FileStream inStream = File.OpenRead(i nPath))
using (FileStream outStream = new FileStream(outP ath,
FileMode.Create , FileAccess.Writ e))
{
EncryptStream(i nStream, outStream);
}
}

public void DecryptFile(str ing inPath, string outPath)
{
using (FileStream inStream = File.OpenRead(i nPath))
using (FileStream outStream = new FileStream(outP ath,
FileMode.Create , FileAccess.Writ e))
{
DecryptStream(i nStream, outStream);
}
}

public byte[] EncryptBytes(by te[] buffer)
{
using (MemoryStream inStream = new MemoryStream(bu ffer))
using (MemoryStream outStream = new MemoryStream())
{
EncryptStream(i nStream, outStream);
return outStream.ToArr ay();
}
}

public byte[] DecryptBytes(by te[] buffer)
{
using (MemoryStream inStream = new MemoryStream(bu ffer))
using (MemoryStream outStream = new MemoryStream())
{
DecryptStream(i nStream, outStream);
return outStream.ToArr ay();
}
}

public void EncryptStream(S tream inStream, Stream outStream)
{
using (ICryptoTransfo rm encryptor = cAlgo.CreateEnc ryptor())
using (CryptoStream cryptoStream = new CryptoStream(ou tStream,
encryptor, CryptoStreamMod e.Write))
{
// Read from in file until EOF and write to crypto stream.
byte[] buf = new byte[BufSize];
int read = 0;
while ((read = inStream.Read(b uf, 0, buf.Length)) 0)
{
cryptoStream.Wr ite(buf, 0, read);
}
cryptoStream.Fl ush();
outStream.Flush ();
}
}

public void DecryptStream(S tream inStream, Stream outStream)
{
using (ICryptoTransfo rm decryptor = cAlgo.CreateDec ryptor())
using (CryptoStream cryptoStream = new CryptoStream(in Stream,
decryptor, CryptoStreamMod e.Read))
{
// Read from the cryptoStream until EOF and write decrypted
bytes to outFile.
byte[] ba = new byte[BufSize];
int read = 0;
while ((read = cryptoStream.Re ad(ba, 0, ba.Length)) 0)
{
outStream.Write (ba, 0, read);
}
outStream.Flush ();
}
}

public static void Test()
{
Crypto crypto = new Crypto(CryptoAl go.DES);
string key = crypto.Key;
string iv = crypto.IV;
crypto.EncryptF ile("c:\\mydata .txt", "c:\\encrypted. txt");
crypto.DecryptF ile("c:\\encryp ted.txt", "c:\\decrypted. txt");
Console.WriteLi ne("Decrypted.t xt:");
Console.WriteLi ne(File.ReadAll Text("c:\\decry pted.txt")); //
Will work for text files.

// Test decrypting with stored key.
crypto = new Crypto(CryptoAl go.DES, key, iv);
crypto.DecryptF ile("c:\\encryp ted.txt", "c:\\decrypted. txt");
Console.WriteLi ne("Decrypted.t xt:");
Console.WriteLi ne(File.ReadAll Text("c:\\decry pted.txt")); //
Will work for text files.

}

public void Dispose()
{
this.cAlgo.Clea r();
}
}
}

--
William Stacey [C# MVP]
PCR concurrency library: www.codeplex.com/pcr
PSH Scripts Project www.codeplex.com/psobject
"William Stacey [C# MVP]" <wi************ @gmail.comwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
| 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("KER NEL32.DLL",
EntryPoint
| = "RtlZeroMemory" )]
| public static extern bool ZeroMemory(IntP tr 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.K ey);
| }
|
| public static void EncryptFile(str ing inPath, string outPath,
string
| sKey)
| {
| DES des = DES.Create();
|
| using (FileStream inFile = File.OpenRead(i nPath))
| using (FileStream outFile = new FileStream(outP ath,
| FileMode.Create , FileAccess.Writ e))
| using (ICryptoTransfo rm desencrypt =
| des.CreateEncry ptor(Encoding.A SCII.GetBytes(s Key),
| Encoding.ASCII. GetBytes(sKey)) )
| using (CryptoStream cryptoStream = new CryptoStream(ou tFile,
| desencrypt, CryptoStreamMod e.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.Wr ite(buf, 0, read);
| }
| cryptoStream.Fl ush();
| outFile.Flush() ;
| }
| }
|
| public static void DecryptFile(str ing 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(inPa th,
FileMode.Open,
| FileAccess.Read ))
| using (FileStream outFile = File.OpenWrite( outPath))
| using (ICryptoTransfo rm desdecrypt =
| des.CreateDecry ptor(Encoding.A SCII.GetBytes(s Key),
| Encoding.ASCII. GetBytes(sKey)) )
| using (CryptoStream cryptoStream = new CryptoStream(in File,
| desdecrypt, CryptoStreamMod e.Read))
| {
| // Read from the cryptoStream until EOF and write decrypted
| bytes to outFile.
| byte[] ba = new byte[BufSize];
| int read = 0;
| while ((read = cryptoStream.Re ad(ba, 0, ba.Length)) 0)
| {
| outFile.Write(b a, 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.Pi nned);
|
| // Encrypt the file.
| EncryptFile(@"C :\MyData.txt", @"C:\Encrypted. txt", sSecretKey);
| Console.WriteLi ne("Encrypted") ;
|
| // Decrypt the file.
| DecryptFile(@"C :\Encrypted.txt ",
| @"C:\Decrypted. txt",sSecretKey );
| Console.WriteLi ne("Decrypted." );
|
| // Remove the Key from memory.
| ZeroMemory(gch. AddrOfPinnedObj ect(), sSecretKey.Leng th * 2);
| gch.Free();
|
| Console.WriteLi ne("Done.");
| Console.WriteLi ne("Cat Decrypted.txt:" );
| Cat(@"c:\decryp ted.txt");
| }
|
| public static void Cat(string path)
| {
| Console.WriteLi ne(File.ReadAll Text(path));
| }
| }
| }
|
| --
| William Stacey [C# MVP]
| PCR concurrency library: www.codeplex.com/pcr
| PSH Scripts Project www.codeplex.com/psobject
|
|
| "William Stacey [C# MVP]" <wi************ @gmail.comwrote in message
| news:O3******** ******@TK2MSFTN GP06.phx.gbl...
|| 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("KER NEL32.DLL",
| EntryPoint
|| = "RtlZeroMemory" )]
|| public static extern bool ZeroMemory(IntP tr 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.
|| DESCryptoServic eProvider desCrypto =
|| (DESCryptoServi ceProvider)DESC ryptoServicePro vider.Create();
||
|| // Use the Automatically generated key for Encryption.
|| return ASCIIEncoding.A SCII.GetString( desCrypto.Key);
|| }
||
|| public static void EncryptFile(str ing sInputFilename, string
|| sOutputFilename , string sKey)
|| {
|| DESCryptoServic eProvider DES = new DESCryptoServic eProvider();
||
|| using (FileStream inFile = new FileStream(sInp utFilename,
|| FileMode.Open, FileAccess.Read ) )
|| using (FileStream outFile = new FileStream(sOut putFilename,
|| FileMode.Create , FileAccess.Writ e))
|| using (ICryptoTransfo rm desencrypt =
|| DES.CreateEncry ptor(Encoding.A SCII.GetBytes(s Key),
|| Encoding.ASCII. GetBytes(sKey)) )
|| using (CryptoStream cryptoStream = new CryptoStream(ou tFile,
|| desencrypt, CryptoStreamMod e.Write))
|| {
|| byte[] bytearrayinput = new byte[inFile.Length];
|| inFile.Read(byt earrayinput, 0, bytearrayinput. Length);
|| cryptoStream.Wr ite(bytearrayin put, 0,
|| bytearrayinput. Length);
|| cryptoStream.Fl ush();
|| outFile.Flush() ;
|| }
|| }
||
|| public static void DecryptFile(str ing sInputFilename, string
|| sOutputFilename , string sKey)
|| {
|| //A 64 bit key and IV is required for this provider.
|| //Set secret key For DES algorithm.
|| DESCryptoServic eProvider DES = new DESCryptoServic eProvider();
||
|| using (FileStream inFile = new FileStream(sInp utFilename,
|| FileMode.Open, FileAccess.Read ))
|| using (FileStream outFile = File.OpenWrite( sOutputFilename ))
|| using (ICryptoTransfo rm desdecrypt =
|| DES.CreateDecry ptor(Encoding.A SCII.GetBytes(s Key),
|| Encoding.ASCII. GetBytes(sKey)) )
|| using (CryptoStream cryptoStream = new CryptoStream(in File,
|| desdecrypt, CryptoStreamMod e.Read))
|| {
|| // Read from the cryptoStream until EOF and write
decrypted
|| bytes to outFile.
|| byte[] ba = new byte[1024];
|| int count = 0;
|| while ((count = cryptoStream.Re ad(ba, 0, ba.Length)) 0)
|| {
|| outFile.Write(b a, 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.Pi nned);
||
|| // Encrypt the file.
|| EncryptFile(@"C :\MyData.txt", @"C:\Encrypted. txt",
sSecretKey);
|| Console.WriteLi ne("Encrypted") ;
||
|| // Decrypt the file.
|| DecryptFile(@"C :\Encrypted.txt ",
|| @"C:\Decrypted. txt",sSecretKey );
|| Console.WriteLi ne("Decrypted." );
||
|| // Remove the Key from memory.
|| ZeroMemory(gch. AddrOfPinnedObj ect(), sSecretKey.Leng th * 2);
|| gch.Free();
||
|| Console.WriteLi ne("Done.");
|| Console.WriteLi ne("Cat Decrypted.txt:" );
|| Cat(@"c:\decryp ted.txt");
|| }
||
|| public static void Cat(string path)
|| {
|| Console.WriteLi ne(File.ReadAll Text(path));
|| }
|| }
|| }
||
||
|| --
|| William Stacey [C# MVP]
|| PCR concurrency library: www.codeplex.com/pcr
|| PSH Scripts Project www.codeplex.com/psobject
||
||
|| "JDeats" <Je**********@g mail.comwrote in message
|| news:11******** **************@ n76g2000hsh.goo glegroups.com.. .
|||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.
|||
||
||
|
|
Apr 24 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
7956
by: wqhdebian | last post by:
As far as I know,when encrypt or decrypt ,a key must first be got,and the key is first generate by a tool or from SecurityRandom,that means I can not generate the same key with the same input.Does there is a method which can generate a same with the same input string? There is a need to transfer file between to site,and the customer wish to encrypt these files during transfering,and they want to store a string into each database at...
2
10387
by: Anilza Popat | last post by:
I would like to know how to encrypt and decrypt files using c#. I want a program that asks for password before encrypt or decrypt the file. best regards
8
8175
by: Gidi | last post by:
Hi, Is there Buid-In fuction in C# that Encrypt and Decrypt strings? i have a textbox which i'm writing into file, and i want to encrypt it before writing, i'm not looking for something fancy, just for a simple Encryption and Decryption function. thanks, Gidi.
1
3222
by: DazedAndConfused | last post by:
Can you encrpt a serialized object? Or am I trying to do something that just doesn't work that way? I am trying to encrypt a serialized object. I can read and write the object to a file without a problem(IF I don't encrypt it). The encryption routine I am using works great when I am just reading in text and writing out encrypted data/Reading in encrpted data and writing out decrypted text.
8
4277
by: toupeira23 | last post by:
Hello, I'm trying to encrypt passwords in my app. After discovering that there's no simple function to do this, I wrote a wrapper class which decodes a string using UTF8, encrypts it with TripleDES and returns a Base64-encoded string. The decryption function does the reverse, i.e. Base64-decodes the string, decrypts it with the same Key and IV, and encodes it again with UTF8. The problem is that after decrypting, the 8th character is...
2
3045
by: rino100 | last post by:
can anyone tell me why this c++ code works encrypting simple filenames but instead if you try to encrypt a filename like "video - 833 12_ ..avi" it doesn't rename the file?????? #include <fstream> #include <iostream> //cryptopp libraries #include <cryptopp/osrng.h> //needed for AutoSeededRandomPool #include <cryptopp/modes.h> #include <cryptopp/blowfish.h>
4
4707
by: google | last post by:
OK, I know how to encrypt and decrypt data, but here's the deal: I have a large Winforms .NET 2.0 application which is currently storing the connection string in the app.config file unencrypted (currently using Windows integrated security, so there's no password). There are only 3 users using the app right now, but that will change soon and we're not going to have our DBAs add every user to the database... Our data entry personnel have...
4
4208
by: Islamegy® | last post by:
I give up.. I tried everything to encrypt querystring and decrypt it back but this never success.. i use RSA encryption. I always get excption when Convert fromBase64String so i tried HttpUtitlity.UrlEncode() but i got bad data Exception.. Is there anyway to work around this??
4
6440
by: Max Vit | last post by:
Here is my problem: I have an application built in Access that outputs sensitive data to a text file. I would like to encrypt this data *whilst* the file is being outputted. The encryption I was using before (very weak) was to encrypt the file *after* the output had been completed but if for some reason the output did halt before being completed; then the text file was able to be read. ....and the encryption needs to be able to be...
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.