Шифрование файлов


[adsense1]
Простая программка на C# предназначенная для шифрования (дешифровки) файлов. Выполняет шифрование данных с помощью алгоритма RSA.

encrypt

RSACryptoServiceProvider.Encrypt - метод выполняет шифрование данных с помощью алгоритма RSA.

 

using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Security.Cryptography;
using System.IO;
namespace WpfApplication2
{

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

const string EncrFolder = @"c:\Encrypt\";
const string DecrFolder = @"c:\Decrypt\";
const string SrcFolder = @"c:\docs\";
const string PubKeyFile = @"c:\encrypt\rsaPublicKey.txt";

// Key container name for private/public key value /пара ключей
const string keyName = "Key01";
CspParameters cspp = new CspParameters();
//cspp.KeyContainerName = keyName;
RSACryptoServiceProvider rsa;
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
Microsoft.Win32.OpenFileDialog openFileDialog2 = new Microsoft.Win32.OpenFileDialog();

private void Button_Click(object sender, RoutedEventArgs e)
{
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
// Display OpenFileDialog by calling ShowDialog method
Nullable result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = dlg.FileName;
textBox2.Text = filename;/////////////////////////////////////
}
}

private void EncryptFile(string inFile)
{

// Create instance of Rijndael for
// symetric encryption of the data.
RijndaelManaged rjndl = new RijndaelManaged();
rjndl.KeySize = 256;
rjndl.BlockSize = 256;
rjndl.Mode = CipherMode.CBC;
ICryptoTransform transform = rjndl.CreateEncryptor();

// Use RSACryptoServiceProvider to
// enrypt the Rijndael key.
// rsa is previously instantiated:
// rsa = new RSACryptoServiceProvider(cspp);
byte[] keyEncrypted = rsa.Encrypt(rjndl.Key, false);

// Create byte arrays to contain
// the length values of the key and IV.
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];

int lKey = keyEncrypted.Length;
LenK = BitConverter.GetBytes(lKey);
int lIV = rjndl.IV.Length;
LenIV = BitConverter.GetBytes(lIV);

// Write the following to the FileStream
// for the encrypted file (outFs):
// - length of the key
// - length of the IV
// - ecrypted key
// - the IV
// - the encrypted cipher content

int startFileName = inFile.LastIndexOf("\\") + 1;
// Change the file's extension to ".enc"
string outFile = EncrFolder + inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".enc";

using (FileStream outFs = new FileStream(outFile, FileMode.Create))
{

outFs.Write(LenK, 0, 4);
outFs.Write(LenIV, 0, 4);
outFs.Write(keyEncrypted, 0, lKey);
outFs.Write(rjndl.IV, 0, lIV);

// Now write the cipher text using
// a CryptoStream for encrypting.
using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
{

// By encrypting a chunk at
// a time, you can save memory
// and accommodate large files.
int count = 0;
int offset = 0;

// blockSizeBytes can be any arbitrary size.
int blockSizeBytes = rjndl.BlockSize / 8;
byte[] data = new byte[blockSizeBytes];
int bytesRead = 0;

using (FileStream inFs = new FileStream(inFile, FileMode.Open))
{
do
{
count = inFs.Read(data, 0, blockSizeBytes);
offset += count;
outStreamEncrypted.Write(data, 0, count);
bytesRead += blockSizeBytes;
}
while (count > 0);
inFs.Close();
}
outStreamEncrypted.FlushFinalBlock();
outStreamEncrypted.Close();
}
outFs.Close();
}

}

private void DecryptFile(string inFile)
{

// Создать экземпляр Rijndael для асимметричн расшифровки данных.
RijndaelManaged rjndl = new RijndaelManaged();
rjndl.KeySize = 256;
rjndl.BlockSize = 256;
rjndl.Mode = CipherMode.CBC;

// Create byte arrays to get the length of the encrypted key and IV.
// These values were stored as 4 bytes each
// at the beginning of the encrypted package.
byte[] LenK = new byte[4];
byte[] LenIV = new byte[4];

// Consruct the file name for the decrypted file.
string outFile = DecrFolder + inFile.Substring(0, inFile.LastIndexOf(".")) + ".txt";

// Use FileStream objects to read the encrypted
// file (inFs) and save the decrypted file (outFs).
using (FileStream inFs = new FileStream(EncrFolder + inFile, FileMode.Open))
{

inFs.Seek(0, SeekOrigin.Begin);
inFs.Seek(0, SeekOrigin.Begin);
inFs.Read(LenK, 0, 3);
inFs.Seek(4, SeekOrigin.Begin);
inFs.Read(LenIV, 0, 3);

// Convert the lengths to integer values.
int lenK = BitConverter.ToInt32(LenK, 0);
int lenIV = BitConverter.ToInt32(LenIV, 0);

// Определить начальную postition в ciphter текста (startC) и его длины (lenC).
int startC = lenK + lenIV + 8;
int lenC = (int)inFs.Length - startC;

// Create the byte arrays for
// the encrypted Rijndael key,
// the IV, and the cipher text.
byte[] KeyEncrypted = new byte[lenK];
byte[] IV = new byte[lenIV];

// Извлечь ключ и IV, начиная с индекса 8 после значений длины.
inFs.Seek(8, SeekOrigin.Begin);
inFs.Read(KeyEncrypted, 0, lenK);
inFs.Seek(8 + lenK, SeekOrigin.Begin);
inFs.Read(IV, 0, lenIV);
Directory.CreateDirectory(DecrFolder);
// Use RSACryptoServiceProvider
// to decrypt the Rijndael key.
byte[] KeyDecrypted = rsa.Decrypt(KeyEncrypted, false);

// Decrypt the key.
ICryptoTransform transform = rjndl.CreateDecryptor(KeyDecrypted, IV);

// Decrypt the cipher text from
// from the FileSteam of the encrypted
// file (inFs) into the FileStream
// for the decrypted file (outFs).
using (FileStream outFs = new FileStream(outFile, FileMode.Create))
{

int count = 0;
int offset = 0;

// blockSizeBytes can be any arbitrary size.
int blockSizeBytes = rjndl.BlockSize / 8;
byte[] data = new byte[blockSizeBytes];

// By decrypting a chunk a time,
// you can save memory and
// accommodate large files.

// Start at the beginning
// of the cipher text.
inFs.Seek(startC, SeekOrigin.Begin);
using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
{
do
{
count = inFs.Read(data, 0, blockSizeBytes);
offset += count;
outStreamDecrypted.Write(data, 0, count);

}
while (count > 0);

outStreamDecrypted.FlushFinalBlock();
outStreamDecrypted.Close();
}
outFs.Close();
}
inFs.Close();
}
}

public static void GenKey_SaveInContainer(string keyName)
{
// Создание объекта в CspParameters и установка ключевого контейнера
// Имя используется для хранения пары ключей RSA.
CspParameters cp = new CspParameters();
cp.KeyContainerName = keyName;

// Создание нового экземпляра RSACryptoServiceProvider, который обращается
//к ключевому контейнеру MyKeyContainerName.
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);

// Метод ToXMLString возвращает информацию о ключе в формате XML.
MessageBox.Show("Информация об открытом ключе в формате XML: \n " + rsa.ToXmlString(true));
}

private void button1_Click(object sender, RoutedEventArgs e)//Create asim key
{
{
cspp.KeyContainerName = keyName;
rsa = new RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;
if (rsa.PublicOnly == true)
this.textBox1.Text = "Key: " + cspp.KeyContainerName + " - Только Public key";
else
this.textBox1.Text = "Key: " + cspp.KeyContainerName + " - Полная пара ключей создана. \nДля сохранения откр. ключа нажмите -ExportPublicKey-";

}
}

private void button2_Click(object sender, RoutedEventArgs e)
{
// Сохранить public key в файл.
Directory.CreateDirectory(EncrFolder);
StreamWriter sw = new StreamWriter(PubKeyFile, false);
sw.Write(rsa.ToXmlString(false));
sw.Close();
this.textBox1.Text = "Public key сохранен в c:\\Encrypt\\.\n Нажмите -Encrypt- для выбора файла подлежащего шифрованию";
}

private void button3_Click(object sender, RoutedEventArgs e)
{
StreamReader sr = new StreamReader(PubKeyFile);
cspp.KeyContainerName = keyName;
rsa = new RSACryptoServiceProvider(cspp);
string keytxt = sr.ReadToEnd();
rsa.FromXmlString(keytxt);
rsa.PersistKeyInCsp = true;
if (rsa.PublicOnly == true)
textBox1.Text = "Key: " + cspp.KeyContainerName + " - Public Only";
else
textBox1.Text = "Key: " + cspp.KeyContainerName + " - Полная пара ключей";
sr.Close();
GenKey_SaveInContainer(keyName);
}

private void button4_Click(object sender, RoutedEventArgs e)//Encrypt
{
Directory.CreateDirectory(DecrFolder);
if (rsa == null)
MessageBox.Show("Key not set.");
else
{
// Показ диалог выбора файла для шифровки.
dlg.InitialDirectory = SrcFolder;
if (dlg.ShowDialog() == true)
{
string fName = dlg.FileName;
if (fName != null)
{
FileInfo fInfo = new FileInfo(fName);
// Pass the file name without the path.
string name = fInfo.FullName;
EncryptFile(name);
this.textBox2.Text = "Файл зашифрован и сохранен в c:\\Encrypt\\. \nСоздан каталог -Decrypt-. \nНажмите -Decrypt- для выбора файла(*.enc) подлежащего Расшифровке";
}
}
}
}

private void button5_Click(object sender, RoutedEventArgs e)
{
try
{
if (rsa == null)
MessageBox.Show("Key not set. Жми -Create asim key-");
else
{
// Показ диалог выбора файла для расшифровки.
openFileDialog2.InitialDirectory = EncrFolder;
if (openFileDialog2.ShowDialog() == true)
{
string fName = openFileDialog2.FileName;
if (fName != null)
{
FileInfo fi = new FileInfo(fName);
string name = fi.Name;
DecryptFile(name);
string filename = dlg.FileName;
this.textBox2.Text = "Расшифрованныый файл -" + filename + "- сохранен в c:\\Decrypt\\";

}
}
}
}
catch { MessageBox.Show("Key not set. Жми -Create asim key-"); }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.textBox1.Text = "Создайте ключевую пару. Нажмите -Create asim key-";
}

}
}


 
[adsense1]
Файл проекта можно скачать wpfapplication2rca

 

Оставьте комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *