PkzipClassic.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. using System.Net.ApiService.Compression.Checksum;
  2. using System;
  3. using System.Security.Cryptography;
  4. namespace System.Net.ApiService.Compression.Encryption {
  5. /// <summary>
  6. /// PkzipClassic embodies the classic or original encryption facilities used in Pkzip archives.
  7. /// While it has been superceded by more recent and more powerful algorithms, its still in use and
  8. /// is viable for preventing casual snooping
  9. /// </summary>
  10. public abstract class PkzipClassic : SymmetricAlgorithm
  11. {
  12. /// <summary>
  13. /// Generates new encryption keys based on given seed
  14. /// </summary>
  15. /// <param name="seed">The seed value to initialise keys with.</param>
  16. /// <returns>A new key value.</returns>
  17. static public byte[] GenerateKeys(byte[] seed)
  18. {
  19. if (seed == null)
  20. {
  21. throw new ArgumentNullException(nameof(seed));
  22. }
  23. if (seed.Length == 0)
  24. {
  25. throw new ArgumentException("Length is zero", nameof(seed));
  26. }
  27. uint[] newKeys = {
  28. 0x12345678,
  29. 0x23456789,
  30. 0x34567890
  31. };
  32. for (int i = 0; i < seed.Length; ++i)
  33. {
  34. newKeys[0] = Crc32.ComputeCrc32(newKeys[0], seed[i]);
  35. newKeys[1] = newKeys[1] + (byte)newKeys[0];
  36. newKeys[1] = newKeys[1] * 134775813 + 1;
  37. newKeys[2] = Crc32.ComputeCrc32(newKeys[2], (byte)(newKeys[1] >> 24));
  38. }
  39. byte[] result = new byte[12];
  40. result[0] = (byte)(newKeys[0] & 0xff);
  41. result[1] = (byte)((newKeys[0] >> 8) & 0xff);
  42. result[2] = (byte)((newKeys[0] >> 16) & 0xff);
  43. result[3] = (byte)((newKeys[0] >> 24) & 0xff);
  44. result[4] = (byte)(newKeys[1] & 0xff);
  45. result[5] = (byte)((newKeys[1] >> 8) & 0xff);
  46. result[6] = (byte)((newKeys[1] >> 16) & 0xff);
  47. result[7] = (byte)((newKeys[1] >> 24) & 0xff);
  48. result[8] = (byte)(newKeys[2] & 0xff);
  49. result[9] = (byte)((newKeys[2] >> 8) & 0xff);
  50. result[10] = (byte)((newKeys[2] >> 16) & 0xff);
  51. result[11] = (byte)((newKeys[2] >> 24) & 0xff);
  52. return result;
  53. }
  54. }
  55. /// <summary>
  56. /// PkzipClassicCryptoBase provides the low level facilities for encryption
  57. /// and decryption using the PkzipClassic algorithm.
  58. /// </summary>
  59. internal class PkzipClassicCryptoBase
  60. {
  61. /// <summary>
  62. /// Transform a single byte
  63. /// </summary>
  64. /// <returns>
  65. /// The transformed value
  66. /// </returns>
  67. protected byte TransformByte()
  68. {
  69. uint temp = ((keys[2] & 0xFFFF) | 2);
  70. return (byte)((temp * (temp ^ 1)) >> 8);
  71. }
  72. /// <summary>
  73. /// Set the key schedule for encryption/decryption.
  74. /// </summary>
  75. /// <param name="keyData">The data use to set the keys from.</param>
  76. protected void SetKeys(byte[] keyData)
  77. {
  78. if (keyData == null)
  79. {
  80. throw new ArgumentNullException(nameof(keyData));
  81. }
  82. if (keyData.Length != 12)
  83. {
  84. throw new InvalidOperationException("Key length is not valid");
  85. }
  86. keys = new uint[3];
  87. keys[0] = (uint)((keyData[3] << 24) | (keyData[2] << 16) | (keyData[1] << 8) | keyData[0]);
  88. keys[1] = (uint)((keyData[7] << 24) | (keyData[6] << 16) | (keyData[5] << 8) | keyData[4]);
  89. keys[2] = (uint)((keyData[11] << 24) | (keyData[10] << 16) | (keyData[9] << 8) | keyData[8]);
  90. }
  91. /// <summary>
  92. /// Update encryption keys
  93. /// </summary>
  94. protected void UpdateKeys(byte ch)
  95. {
  96. keys[0] = Crc32.ComputeCrc32(keys[0], ch);
  97. keys[1] = keys[1] + (byte)keys[0];
  98. keys[1] = keys[1] * 134775813 + 1;
  99. keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24));
  100. }
  101. /// <summary>
  102. /// Reset the internal state.
  103. /// </summary>
  104. protected void Reset()
  105. {
  106. keys[0] = 0;
  107. keys[1] = 0;
  108. keys[2] = 0;
  109. }
  110. #region Instance Fields
  111. private uint[] keys;
  112. #endregion Instance Fields
  113. }
  114. /// <summary>
  115. /// PkzipClassic CryptoTransform for encryption.
  116. /// </summary>
  117. internal class PkzipClassicEncryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform
  118. {
  119. /// <summary>
  120. /// Initialise a new instance of <see cref="PkzipClassicEncryptCryptoTransform"></see>
  121. /// </summary>
  122. /// <param name="keyBlock">The key block to use.</param>
  123. internal PkzipClassicEncryptCryptoTransform(byte[] keyBlock)
  124. {
  125. SetKeys(keyBlock);
  126. }
  127. #region ICryptoTransform Members
  128. /// <summary>
  129. /// Transforms the specified region of the specified byte array.
  130. /// </summary>
  131. /// <param name="inputBuffer">The input for which to compute the transform.</param>
  132. /// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
  133. /// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
  134. /// <returns>The computed transform.</returns>
  135. public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
  136. {
  137. byte[] result = new byte[inputCount];
  138. TransformBlock(inputBuffer, inputOffset, inputCount, result, 0);
  139. return result;
  140. }
  141. /// <summary>
  142. /// Transforms the specified region of the input byte array and copies
  143. /// the resulting transform to the specified region of the output byte array.
  144. /// </summary>
  145. /// <param name="inputBuffer">The input for which to compute the transform.</param>
  146. /// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
  147. /// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
  148. /// <param name="outputBuffer">The output to which to write the transform.</param>
  149. /// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
  150. /// <returns>The number of bytes written.</returns>
  151. public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
  152. {
  153. for (int i = inputOffset; i < inputOffset + inputCount; ++i)
  154. {
  155. byte oldbyte = inputBuffer[i];
  156. outputBuffer[outputOffset++] = (byte)(inputBuffer[i] ^ TransformByte());
  157. UpdateKeys(oldbyte);
  158. }
  159. return inputCount;
  160. }
  161. /// <summary>
  162. /// Gets a value indicating whether the current transform can be reused.
  163. /// </summary>
  164. public bool CanReuseTransform
  165. {
  166. get
  167. {
  168. return true;
  169. }
  170. }
  171. /// <summary>
  172. /// Gets the size of the input data blocks in bytes.
  173. /// </summary>
  174. public int InputBlockSize
  175. {
  176. get
  177. {
  178. return 1;
  179. }
  180. }
  181. /// <summary>
  182. /// Gets the size of the output data blocks in bytes.
  183. /// </summary>
  184. public int OutputBlockSize
  185. {
  186. get
  187. {
  188. return 1;
  189. }
  190. }
  191. /// <summary>
  192. /// Gets a value indicating whether multiple blocks can be transformed.
  193. /// </summary>
  194. public bool CanTransformMultipleBlocks
  195. {
  196. get
  197. {
  198. return true;
  199. }
  200. }
  201. #endregion ICryptoTransform Members
  202. #region IDisposable Members
  203. /// <summary>
  204. /// Cleanup internal state.
  205. /// </summary>
  206. public void Dispose()
  207. {
  208. Reset();
  209. }
  210. #endregion IDisposable Members
  211. }
  212. /// <summary>
  213. /// PkzipClassic CryptoTransform for decryption.
  214. /// </summary>
  215. internal class PkzipClassicDecryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform
  216. {
  217. /// <summary>
  218. /// Initialise a new instance of <see cref="PkzipClassicDecryptCryptoTransform"></see>.
  219. /// </summary>
  220. /// <param name="keyBlock">The key block to decrypt with.</param>
  221. internal PkzipClassicDecryptCryptoTransform(byte[] keyBlock)
  222. {
  223. SetKeys(keyBlock);
  224. }
  225. #region ICryptoTransform Members
  226. /// <summary>
  227. /// Transforms the specified region of the specified byte array.
  228. /// </summary>
  229. /// <param name="inputBuffer">The input for which to compute the transform.</param>
  230. /// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
  231. /// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
  232. /// <returns>The computed transform.</returns>
  233. public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
  234. {
  235. byte[] result = new byte[inputCount];
  236. TransformBlock(inputBuffer, inputOffset, inputCount, result, 0);
  237. return result;
  238. }
  239. /// <summary>
  240. /// Transforms the specified region of the input byte array and copies
  241. /// the resulting transform to the specified region of the output byte array.
  242. /// </summary>
  243. /// <param name="inputBuffer">The input for which to compute the transform.</param>
  244. /// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
  245. /// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
  246. /// <param name="outputBuffer">The output to which to write the transform.</param>
  247. /// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
  248. /// <returns>The number of bytes written.</returns>
  249. public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
  250. {
  251. for (int i = inputOffset; i < inputOffset + inputCount; ++i)
  252. {
  253. var newByte = (byte)(inputBuffer[i] ^ TransformByte());
  254. outputBuffer[outputOffset++] = newByte;
  255. UpdateKeys(newByte);
  256. }
  257. return inputCount;
  258. }
  259. /// <summary>
  260. /// Gets a value indicating whether the current transform can be reused.
  261. /// </summary>
  262. public bool CanReuseTransform
  263. {
  264. get
  265. {
  266. return true;
  267. }
  268. }
  269. /// <summary>
  270. /// Gets the size of the input data blocks in bytes.
  271. /// </summary>
  272. public int InputBlockSize
  273. {
  274. get
  275. {
  276. return 1;
  277. }
  278. }
  279. /// <summary>
  280. /// Gets the size of the output data blocks in bytes.
  281. /// </summary>
  282. public int OutputBlockSize
  283. {
  284. get
  285. {
  286. return 1;
  287. }
  288. }
  289. /// <summary>
  290. /// Gets a value indicating whether multiple blocks can be transformed.
  291. /// </summary>
  292. public bool CanTransformMultipleBlocks
  293. {
  294. get
  295. {
  296. return true;
  297. }
  298. }
  299. #endregion ICryptoTransform Members
  300. #region IDisposable Members
  301. /// <summary>
  302. /// Cleanup internal state.
  303. /// </summary>
  304. public void Dispose()
  305. {
  306. Reset();
  307. }
  308. #endregion IDisposable Members
  309. }
  310. /// <summary>
  311. /// Defines a wrapper object to access the Pkzip algorithm.
  312. /// This class cannot be inherited.
  313. /// </summary>
  314. public sealed class PkzipClassicManaged : PkzipClassic
  315. {
  316. /// <summary>
  317. /// Get / set the applicable block size in bits.
  318. /// </summary>
  319. /// <remarks>The only valid block size is 8.</remarks>
  320. public override int BlockSize
  321. {
  322. get
  323. {
  324. return 8;
  325. }
  326. set
  327. {
  328. if (value != 8)
  329. {
  330. throw new CryptographicException("Block size is invalid");
  331. }
  332. }
  333. }
  334. /// <summary>
  335. /// Get an array of legal <see cref="KeySizes">key sizes.</see>
  336. /// </summary>
  337. public override KeySizes[] LegalKeySizes
  338. {
  339. get
  340. {
  341. KeySizes[] keySizes = new KeySizes[1];
  342. keySizes[0] = new KeySizes(12 * 8, 12 * 8, 0);
  343. return keySizes;
  344. }
  345. }
  346. /// <summary>
  347. /// Generate an initial vector.
  348. /// </summary>
  349. public override void GenerateIV()
  350. {
  351. // Do nothing.
  352. }
  353. /// <summary>
  354. /// Get an array of legal <see cref="KeySizes">block sizes</see>.
  355. /// </summary>
  356. public override KeySizes[] LegalBlockSizes
  357. {
  358. get
  359. {
  360. KeySizes[] keySizes = new KeySizes[1];
  361. keySizes[0] = new KeySizes(1 * 8, 1 * 8, 0);
  362. return keySizes;
  363. }
  364. }
  365. /// <summary>
  366. /// Get / set the key value applicable.
  367. /// </summary>
  368. public override byte[] Key
  369. {
  370. get
  371. {
  372. if (key_ == null)
  373. {
  374. GenerateKey();
  375. }
  376. return (byte[])key_.Clone();
  377. }
  378. set
  379. {
  380. if (value == null)
  381. {
  382. throw new ArgumentNullException(nameof(value));
  383. }
  384. if (value.Length != 12)
  385. {
  386. throw new CryptographicException("Key size is illegal");
  387. }
  388. key_ = (byte[])value.Clone();
  389. }
  390. }
  391. /// <summary>
  392. /// Generate a new random key.
  393. /// </summary>
  394. public override void GenerateKey()
  395. {
  396. key_ = new byte[12];
  397. var rnd = new Random();
  398. rnd.NextBytes(key_);
  399. }
  400. /// <summary>
  401. /// Create an encryptor.
  402. /// </summary>
  403. /// <param name="rgbKey">The key to use for this encryptor.</param>
  404. /// <param name="rgbIV">Initialisation vector for the new encryptor.</param>
  405. /// <returns>Returns a new PkzipClassic encryptor</returns>
  406. public override ICryptoTransform CreateEncryptor(
  407. byte[] rgbKey,
  408. byte[] rgbIV)
  409. {
  410. key_ = rgbKey;
  411. return new PkzipClassicEncryptCryptoTransform(Key);
  412. }
  413. /// <summary>
  414. /// Create a decryptor.
  415. /// </summary>
  416. /// <param name="rgbKey">Keys to use for this new decryptor.</param>
  417. /// <param name="rgbIV">Initialisation vector for the new decryptor.</param>
  418. /// <returns>Returns a new decryptor.</returns>
  419. public override ICryptoTransform CreateDecryptor(
  420. byte[] rgbKey,
  421. byte[] rgbIV)
  422. {
  423. key_ = rgbKey;
  424. return new PkzipClassicDecryptCryptoTransform(Key);
  425. }
  426. #region Instance Fields
  427. private byte[] key_;
  428. #endregion Instance Fields
  429. }
  430. }