Come crittografare un file in C #

April 3

Come crittografare un file in C #


Sapendo come crittografare file possono aiutare a proteggere le informazioni sul file sensibili nel computer. I file sono in genere crittografati quando sono inviati su Internet per la protezione. Microsoft Visual C # è un linguaggio di programmazione orientato agli oggetti utilizzati per creare le applicazioni del computer. C # è spesso la prima scelta per i programmatori per la sua flessibilità e facilità d'uso. In pochi passi si può crittografare un file di testo utilizzando C #.

istruzione

1 Aprire Microsoft Visual C # Express e fare clic su "Nuovo progetto ..." nel riquadro a sinistra dello schermo. Fare doppio clic su "Applicazione Console" nel riquadro centrale della finestra "Nuovo progetto".

2 Premere il tasto "Ctrl" + "A" e premere il tasto "Elimina" per eliminare il codice esistente.

3 Copia e incolla il seguente codice al modulo "Program.cs":

using System;

using System.IO;

utilizzando System.Security;

utilizzando System.Security.Cryptography;

using System.Runtime.InteropServices;

utilizzando System.Text;

namespace CSEncryptDecrypt

{

class Class1

{

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

ZeroMemory public static extern bool (IntPtr Destinazione, int lunghezza);

stringa statica GenerateKey ()

{

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

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

}

static void sInputFilename EncryptFile (string,

stringa di sOutputFilename,

stringa 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 Main ()

{

stringa sSecretKey;

sSecretKey = GenerateKey ();

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

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

@ "C: \ MyEncryptedFile.txt",

sSecretKey);

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

gch.Free ();

}

}

}

4 Modificare la seguente riga di codice e digitare il nome del file che si desidera crittografare:

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

@"C:\MyEncryptedFile.txt",

sSecretKey);

Premere il tasto "F5" per eseguire il programma.