Red de conocimiento informático - Conocimiento del nombre de dominio - Cómo cifrar y descifrar archivos usando C#

Cómo cifrar y descifrar archivos usando C#

Consulte

Usar System;

Usar System.IO;

Usar System.Security;

Usar System.Runtime.InteropServices <; /p>

Utilice System.Runtime.InteropServices y System.Runtime.InteropServices. Por razones de seguridad, llame a esta función para eliminar la clave de la memoria después de usarla

[System.Runtime.InteropServices.DllImport("KERNEL32. EntryPoint="RtlZeroMemory")]

public static extern bool ZeroMemory(IntPtr Destination, int Longitud);

// Función para generar clave de 64 bits

static string GenerateKey()

{

// Crear una instancia de algoritmo Symetric

// Crear una instancia de algoritmo Symetric

DESCryptoServiceProvider desCrypto =(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

p>

// Cifrar utilizando una clave generada automáticamente.

return ASCIIEncoding.ASCII.GetString(desCrypto.Key);

}

static void EncryptFile(string sInputFilename,

string sOutputFilename ,

cadena sKey)

{

FileStream fsInput = new FileStream(sInputFilename,

FileMode.Open,

FileMode.Open,

FileMode.Open,

FileMode.Open,

FileMode.Open,

FileMode.OpenOpen,

FileAccess.Read);

FileStream fsEncrypted = new FileStream(sOutputFilename,

FileMode.Create,

FileAccess.Write);

DESCryptoServiceProvider DES = nuevo DESCryptoServiceProvider();

DES.Key = ASCIIEncoding.ASCII.GetBytes( Clave = ASCIIEncoding.ASCII.GetBytes(sKey);

DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

DES.V = ASCIIEncoding.ASCII.GetBytes(sKey);

DES.IV = ASCIIEncoding.ASCII.GetBytes( sKey)ASCIIEncoding.ASCII.GetBytes(sKey);

ICryptoTransform desencrypt = DES.CreateEncryptor();

CryptoStream cryptostream = new CryptoStream(fsEncrypted,

desencrypt ,

CryptoStreamMode.

cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);

cryptostream.Close();

fsInput.Close();

fsEncrypted.Close();

cryptostream.Close();

fsInput.Close()Close();

p>

}

static void DecryptFile(cadena sInputFilename,

cadena sOutputFilename,

cadena sKey)

{

p>

DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

//Este proveedor requiere una clave de 64 bits y IV.

//Establece la clave secreta para el algoritmo DES.

DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);

//Establece el vector de inicialización.

FileStream fsread = new FileStream(sInputFilename,

FileMode.Open,

FileAccess.Read);

//Crear un DES decryptor de la instancia DES.

ICryptoTransform desdecrypt = DES.CreateDecryptor();

// Crea un flujo criptográfico configurado para leer desde la instancia DES.

CryptoStream cryptostreamDecr = new CryptoStream(fsread,

desdecrypt,

CryptoStreamMode.Read);

//Imprime el contenido del archivo descifrado.

StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);

fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());<

fsDecrypted.Flush( );

fsDecrypted.Close();

}

static void Main()

{

// Debe ser de 64 bits, 8 bytes.

// Distribuir esta clave a los usuarios.

Distribuya esta clave a los usuarios que descifrarán este archivo.

string sSecretKey;

// Obtenga la clave para cifrar el archivo.

sSecretKey = GenerateKey();

// Para mayor seguridad, fije la clave.

GCHandle gch = GCHandle.Alloc( sSecretKey,GCHandleType.Pinned );

// Cifre el archivo.

// Obtenga la clave del archivo para cifrar el archivo.

EncryptFile(@"C:\MyData.txt",

@"C:\Encrypted.txt",

sSecretKey);

// Descifrar el archivo.

GCHandle gch = GCHandle.DecryptFile(@"C:\Encrypted.txt",

@"C :\Decrypted.txt",

sSecretKey);

// Elimina la clave de la memoria.

ZeroMemory( gch.AddrOfPinnedObject(), sSecretKey.Length * 2);

gch.Free();

}

}

}

}