Skip to content

Esempio di codice per il trasferimento di file criptati in c#

Non dimenticare che in informatica un problema ha quasi sempre più di una soluzione, quindi ti mostreremo la più ottimale e la migliore.

Esempio: come criptare un file c#

//  Call this function to remove the key from memory after use for security[DllImport("KERNEL32.DLL", EntryPoint ="RtlZeroMemory")]publicstaticexternboolZeroMemory(IntPtr Destination,int Length);/// <summary>/// Creates a random salt that will be used to encrypt your file. This method is required on FileEncrypt./// summary>/// <returns>returns>publicstaticbyte[]GenerateRandomSalt(){byte[] data =newbyte[32];using(RNGCryptoServiceProvider rng =newRNGCryptoServiceProvider()){for(int i =0; i <10; i++){// Fille the buffer with the generated data
            rng.GetBytes(data);}}return data;}/// <summary>/// Encrypts a file from its path and a plain password./// summary>/// <paramname="inputFile">param>/// <paramname="password">param>privatevoidFileEncrypt(string inputFile,string password){//http://stackoverflow.com/questions/27645527/aes-encryption-on-large-files//generate random saltbyte[] salt =GenerateRandomSalt();//create output file nameFileStream fsCrypt =newFileStream(inputFile +".aes", FileMode.Create);//convert password string to byte arrraybyte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);//Set Rijndael symmetric encryption algorithmRijndaelManaged AES =newRijndaelManaged();
    AES.KeySize =256;
    AES.BlockSize =128;
    AES.Padding = PaddingMode.PKCS7;//http://stackoverflow.com/questions/2659214/why-do-i-need-to-use-the-rfc2898derivebytes-class-in-net-instead-of-directly//"What it does is repeatedly hash the user password along with the salt." High iteration counts.var key =newRfc2898DeriveBytes(passwordBytes, salt,50000);
    AES.Key = key.GetBytes(AES.KeySize /8);
    AES.IV = key.GetBytes(AES.BlockSize /8);//Cipher modes: http://security.stackexchange.com/questions/52665/which-is-the-best-cipher-mode-and-padding-mode-for-aes-encryption
    AES.Mode = CipherMode.CFB;// write salt to the begining of the output file, so in this case can be random every time
    fsCrypt.Write(salt,0, salt.Length);CryptoStream cs =newCryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write);FileStream fsIn =newFileStream(inputFile, FileMode.Open);//create a buffer (1mb) so only this amount will allocate in the memory and not the whole filebyte[] buffer =newbyte[1048576];int read;try{while((read = fsIn.Read(buffer,0, buffer.Length))>0){
            Application.DoEvents();// -> for responsive GUI, using Task will be better!
            cs.Write(buffer,0, read);}// Close up
        fsIn.Close();}catch(Exception ex){
        Console.WriteLine("Error: "+ ex.Message);}finally{
        cs.Close();
        fsCrypt.Close();}}/// <summary>/// Decrypts an encrypted file with the FileEncrypt method through its path and the plain password./// summary>/// <paramname="inputFile">param>/// <paramname="outputFile">param>/// <paramname="password">param>privatevoidFileDecrypt(string inputFile,string outputFile,string password){byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);byte[] salt =newbyte[32];FileStream fsCrypt =newFileStream(inputFile, FileMode.Open);
    fsCrypt.Read(salt,0, salt.Length);RijndaelManaged AES =newRijndaelManaged();
    AES.KeySize =256;
    AES.BlockSize =128;var key =newRfc2898DeriveBytes(passwordBytes, salt,50000);
    AES.Key = key.GetBytes(AES.KeySize /8);
    AES.IV = key.GetBytes(AES.BlockSize /8);
    AES.Padding = PaddingMode.PKCS7;
    AES.Mode = CipherMode.CFB;CryptoStream cs =newCryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);FileStream fsOut =newFileStream(outputFile, FileMode.Create);int read;byte[] buffer =newbyte[1048576];try{while((read = cs.Read(buffer,0, buffer.Length))>0){
            Application.DoEvents();
            fsOut.Write(buffer,0, read);}}catch(CryptographicException ex_CryptographicException){
        Console.WriteLine("CryptographicException error: "+ ex_CryptographicException.Message);}catch(Exception ex){
        Console.WriteLine("Error: "+ ex.Message);}try{
        cs.Close();}catch(Exception ex){
        Console.WriteLine("Error by closing CryptoStream: "+ ex.Message);}finally{
        fsOut.Close();
        fsCrypt.Close();}}

Ti mostriamo commenti e valutazioni

Apprezziamo il fatto che desideri aggiungere valore alle nostre informazioni aiutandoti con la tua esperienza di revisione.



Utilizzate il nostro motore di ricerca

Ricerca
Generic filters

Lascia un commento

Il tuo indirizzo email non sarà pubblicato.