The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AesCounterStream.cs 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. using System;
  2. using System.IO;
  3. namespace Teknik.Utilities.Cryptography
  4. {
  5. public class AesCounterStream : Stream
  6. {
  7. private Stream _Inner;
  8. private CounterModeCryptoTransform _Cipher;
  9. /// <summary>
  10. /// Performs Encryption or Decryption on a stream with the given Key and IV
  11. ///
  12. /// Cipher is AES-256 in CTR mode with no padding
  13. /// </summary>
  14. /// <param name="stream"></param>
  15. /// <param name="encrypt"></param>
  16. /// <param name="key"></param>
  17. /// <param name="iv"></param>
  18. public AesCounterStream(Stream stream, bool encrypt, byte[] key, byte[] iv)
  19. {
  20. _Inner = stream;
  21. // Create the Aes Cipher
  22. AesCounterMode aes = new AesCounterMode(iv);
  23. if (encrypt)
  24. {
  25. _Cipher = (CounterModeCryptoTransform)aes.CreateEncryptor(key, iv); // Encrypt
  26. }
  27. else
  28. {
  29. _Cipher = (CounterModeCryptoTransform)aes.CreateDecryptor(key, iv); // Decrypt
  30. }
  31. // Sync the counter
  32. SyncCounter();
  33. }
  34. public override int Read(byte[] buffer, int offset, int count)
  35. {
  36. if (_Inner != null && CanRead)
  37. {
  38. byte[] readBuf = new byte[count];
  39. int processed = 0;
  40. // Read the data from the stream
  41. int bytesRead = _Inner.Read(readBuf, 0, count);
  42. if (bytesRead > 0)
  43. {
  44. // Process the read buffer
  45. processed = _Cipher.TransformBlock(readBuf, 0, bytesRead, buffer, offset);
  46. }
  47. // Do we have more?
  48. if (processed < bytesRead)
  49. {
  50. // Finalize the cipher
  51. byte[] finalBuf = _Cipher.TransformFinalBlock(readBuf, processed + offset, bytesRead);
  52. finalBuf.CopyTo(buffer, processed);
  53. processed += finalBuf.Length;
  54. }
  55. return processed;
  56. }
  57. return -1;
  58. }
  59. public override void Write(byte[] buffer, int offset, int count)
  60. {
  61. if (_Inner != null && CanWrite)
  62. {
  63. // Process the cipher
  64. byte[] output = new byte[count];
  65. // Process the buffer
  66. int processed = _Cipher.TransformBlock(buffer, offset, count, output, 0);
  67. // Do we have more?
  68. if (processed < count)
  69. {
  70. // Finalize the cipher
  71. byte[] finalBuf = _Cipher.TransformFinalBlock(buffer, processed + offset, count);
  72. finalBuf.CopyTo(output, processed);
  73. }
  74. _Inner.Write(output, 0, count);
  75. }
  76. }
  77. public override bool CanRead
  78. {
  79. get
  80. {
  81. if (_Inner != null)
  82. {
  83. return _Inner.CanRead;
  84. }
  85. return false;
  86. }
  87. }
  88. public override bool CanSeek
  89. {
  90. get
  91. {
  92. if (_Inner != null)
  93. {
  94. return _Inner.CanSeek;
  95. }
  96. return false;
  97. }
  98. }
  99. public override bool CanWrite
  100. {
  101. get
  102. {
  103. if (_Inner != null)
  104. {
  105. return _Inner.CanWrite;
  106. }
  107. return false;
  108. }
  109. }
  110. public override long Length
  111. {
  112. get
  113. {
  114. if (_Inner != null)
  115. {
  116. return _Inner.Length;
  117. }
  118. return -1;
  119. }
  120. }
  121. public override long Position
  122. {
  123. get
  124. {
  125. if (_Inner != null)
  126. {
  127. return _Inner.Position;
  128. }
  129. return -1;
  130. }
  131. set
  132. {
  133. if (_Inner != null)
  134. {
  135. _Inner.Position = value;
  136. // Sync the counter
  137. SyncCounter();
  138. }
  139. }
  140. }
  141. public override void Flush()
  142. {
  143. if (_Inner != null)
  144. {
  145. _Inner.Flush();
  146. }
  147. }
  148. public override long Seek(long offset, SeekOrigin origin)
  149. {
  150. if (_Inner != null)
  151. {
  152. long newPos = _Inner.Seek(offset, origin);
  153. // Sync the counter
  154. SyncCounter();
  155. return newPos;
  156. }
  157. return -1;
  158. }
  159. public override void SetLength(long value)
  160. {
  161. if (_Inner != null)
  162. {
  163. _Inner.SetLength(value);
  164. }
  165. }
  166. private void SyncCounter()
  167. {
  168. if (_Cipher != null)
  169. {
  170. // Calculate the counter iterations and position needed
  171. int iterations = (int)Math.Floor(_Inner.Position / (decimal)_Cipher.InputBlockSize);
  172. int counterPos = (int)(_Inner.Position % _Cipher.InputBlockSize);
  173. // Are we out of sync with the cipher?
  174. if (_Cipher.Iterations != iterations + 1 || _Cipher.CounterPosition != counterPos)
  175. {
  176. // Reset the current counter
  177. _Cipher.ResetCounter();
  178. // Iterate the counter to the current position
  179. for (int i = 0; i < iterations; i++)
  180. {
  181. _Cipher.IncrementCounter();
  182. }
  183. // Encrypt the counter
  184. _Cipher.EncryptCounter();
  185. // Set the current position of the counter
  186. _Cipher.CounterPosition = counterPos;
  187. // Increment the counter for the next time
  188. _Cipher.IncrementCounter();
  189. }
  190. }
  191. }
  192. }
  193. }