Un esempio su come cryptare e decryptare con una password, tramite l'algoritmo DES, un file di testo.
- Il parametro sInputFilename specifica il file da cryptare.
- Il parametro sOutputFilename specifica il file da decryptare.
- Il parametro sKey specifica la password da utilizzare.
Utilizzare i seguenti Namespace:
using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Text;
I metodi mostrati di seguito utilizzano il componente CryptoStream.
public static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
FileStream fsEncrypted = new FileStream(sInputFilename, FileMode.Create, FileAccess.ReadWrite);
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[fsEncrypted.Length];
fsEncrypted.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsEncrypted.Close();
}
public static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
ICryptoTransform desdecrypt = DES.CreateDecryptor();
CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}
Continua a leggere!