/// <summary>
/// Encrypts a file.
/// </summary>
/// <param name="algorithm">The algorithm.</param>
private static void EncryptFile(SupportedStreamAlgorithms algorithm)
{
// 1. Create random file
FileInfo rndFile = RandomFile.CreateRandomBinary();
Console.WriteLine("File created.");
string encryptedFile = rndFile.FullName + ".enc";
string decryptedFile = encryptedFile + ".dec";
// 2. Set algorithm
IStreamAlgorithm cryptoAlgo = StreamAlgorithmFactory.Create(algorithm);
// 3. Encrypt
StreamCrypter crypter = new StreamCrypter(cryptoAlgo);
crypter.GenerateKeys("littlelitesoftware");
crypter.EncryptDecrypt(rndFile.FullName, encryptedFile, true, null);
Console.WriteLine("File encrypted into " + encryptedFile);
// 4. Decrypt
StreamCrypter decrypter = new StreamCrypter(cryptoAlgo);
crypter.GenerateKeys("littlelitesoftware");
crypter.EncryptDecrypt(encryptedFile, decryptedFile, false, null);
Console.WriteLine("File decrypted into " + decryptedFile);
// 5. Confront them
FileManager fm = FileManager.Reference;
byte[] originalFileContents = fm.ReadBinaryFile(rndFile.FullName);
byte[] decryptedFileContents = fm.ReadBinaryFile(decryptedFile);
string fmFeedback = fm.ErrorMessage;
if (fmFeedback.Length == 0)
{
if (originalFileContents.Length == decryptedFileContents.Length)
{
bool areEqual = true;
int count = 0;
foreach (byte b in originalFileContents)
{
if (b != decryptedFileContents[count++])
{
areEqual = false;
Console.WriteLine("Found difference at byte " + count);
break;
}
}
if (areEqual)
{
Console.WriteLine("File decryption OK");
}
else
{
Console.WriteLine(">>> File decryption KO: different bytes");
}
}
else
{
Console.WriteLine(">>> File decryption KO: different lengths");
}
}
else
{
Console.WriteLine("IOError: "+fmFeedback);
}
}