Простая программка на C# предназначенная для шифрования (дешифровки) файлов. Выполняет шифрование данных с помощью алгоритма RSA.
RSACryptoServiceProvider.Encrypt - метод выполняет шифрование данных с помощью алгоритма RSA.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
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-"; } } } |
Файл проекта можно скачать wpfapplication2rca
1 - 1Поделиться