Зашифровать часть файла быстро - C#

Узнай цену своей работы

Формулировка задачи:

Помогите пожалуйста, как зашифровать большой файл (больше гигабайта) с перезаписью его с помощью AES, возможно ли считать лиш чась файла и ее записать обратно по быстрому? или хотябы перезаписать файл помогите что надо в код добавить чтобы перезаписывал допустим первые 128 килобайт файла и была возможность расшифровать потом вот пример кода что туда добавить?
Листинг программы
  1. private void AES_Encrypt2(string inputFile, string password)
  2. {
  3. //http://stackoverflow.com/questions/27645527/aes-encryption-on-large-files
  4. //generate random salt
  5. byte[] salt = GenerateRandomSalt();
  6. //create output file name
  7. FileStream fsCrypt = new FileStream(inputFile + ".aes", FileMode.Create);
  8. //convert password string to byte arrray
  9. byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
  10. //Set Rijndael symmetric encryption algorithm
  11. RijndaelManaged AES = new RijndaelManaged();
  12. AES.KeySize = 256;
  13. AES.BlockSize = 128;
  14. AES.Padding = PaddingMode.PKCS7;
  15. //http://stackoverflow.com/questions/2659214/why-do-i-need-to-use-the-rfc2898derivebytes-class-in-net-instead-of-directly
  16. //"What it does is repeatedly hash the user password along with the salt." High iteration counts.
  17. var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
  18. AES.Key = key.GetBytes(AES.KeySize / 8);
  19. AES.IV = key.GetBytes(AES.BlockSize / 8);
  20. //Cipher modes: [url]http://security.stackexchange.com/questions/52665/which-is-the-best-cipher-mode-and-padding-mode-for-aes-encryption[/url]
  21. AES.Mode = CipherMode.CBC; //cbf
  22. //write salt to the begining of the output file, so in this case can be random every time
  23. fsCrypt.Write(salt, 0, salt.Length);
  24. CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write);
  25. FileStream fsIn = new FileStream(inputFile, FileMode.Open);
  26. //create a buffer (1mb) so only this amount will allocate in the memory and not the whole file
  27. byte[] buffer = new byte[1048576];
  28. int read;
  29. try
  30. {
  31. while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
  32. {
  33. Application.DoEvents(); // -> for responsive GUI, using Task will be better!
  34. cs.Write(buffer, 0, read);
  35. }
  36. //close up
  37. fsIn.Close();
  38. }
  39. catch (Exception ex)
  40. {
  41. Debug.WriteLine("Error: " + ex.Message);
  42. }
  43. finally
  44. {
  45. cs.Close();
  46. fsCrypt.Close();
  47. }
  48. }
  49. private void AES_Decrypt2(string inputFile, string password)
  50. {
  51. //todo:
  52. // - create error message on wrong password
  53. // - on cancel: close and delete file
  54. // - on wrong password: close and delete file!
  55. // - create a better filen name
  56. // - could be check md5 hash on the files but it make this slow
  57. byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
  58. byte[] salt = new byte[32];
  59. FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
  60. fsCrypt.Read(salt, 0, salt.Length);
  61. RijndaelManaged AES = new RijndaelManaged();
  62. AES.KeySize = 256;
  63. AES.BlockSize = 128;
  64. var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
  65. AES.Key = key.GetBytes(AES.KeySize / 8);
  66. AES.IV = key.GetBytes(AES.BlockSize / 8);
  67. AES.Padding = PaddingMode.PKCS7;
  68. AES.Mode = CipherMode.CBC; //CFB
  69.  
  70. CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);
  71. FileStream fsOut = new FileStream(inputFile + ".decrypted", FileMode.Create);
  72. int read;
  73. byte[] buffer = new byte[1048576];
  74. try
  75. {
  76. while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
  77. {
  78. Application.DoEvents();
  79. fsOut.Write(buffer, 0, read);
  80. }
  81. }
  82. catch (System.Security.Cryptography.CryptographicException ex_CryptographicException)
  83. {
  84. Debug.WriteLine("CryptographicException error: " + ex_CryptographicException.Message);
  85. }
  86. catch (Exception ex)
  87. {
  88. Debug.WriteLine("Error: " + ex.Message);
  89. }
  90. try
  91. {
  92. cs.Close();
  93. }
  94. catch (Exception ex)
  95. {
  96. Debug.WriteLine("Error by closing CryptoStream: " + ex.Message);
  97. }
  98. finally
  99. {
  100. fsOut.Close();
  101. fsCrypt.Close();
  102. }
  103. }
  104. public static byte[] GenerateRandomSalt()
  105. {
  106. //Source: [url]http://www.dotnetperls.com/rngcryptoserviceprovider[/url]
  107. byte[] data = new byte[32];
  108. using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
  109. {
  110. // Ten iterations.
  111. for (int i = 0; i < 10; i++)
  112. {
  113. // Fill buffer.
  114. rng.GetBytes(data);
  115. }
  116. }
  117. return data;
  118. }

Решение задачи: «Зашифровать часть файла быстро»

textual
Листинг программы
  1.  byte[] buffer = new byte[1048576];

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

6   голосов , оценка 4.167 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы