Blake2bDigest.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  6. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests
  7. {
  8. /* The BLAKE2 cryptographic hash function was designed by Jean-
  9. Philippe Aumasson, Samuel Neves, Zooko Wilcox-O'Hearn, and Christian
  10. Winnerlein.
  11. Reference Implementation and Description can be found at: https://blake2.net/
  12. Internet Draft: https://tools.ietf.org/html/draft-saarinen-blake2-02
  13. This implementation does not support the Tree Hashing Mode.
  14. For unkeyed hashing, developers adapting BLAKE2 to ASN.1 - based
  15. message formats SHOULD use the OID tree at x = 1.3.6.1.4.1.1722.12.2.
  16. Algorithm | Target | Collision | Hash | Hash ASN.1 |
  17. Identifier | Arch | Security | nn | OID Suffix |
  18. ---------------+--------+-----------+------+------------+
  19. id-blake2b160 | 64-bit | 2**80 | 20 | x.1.20 |
  20. id-blake2b256 | 64-bit | 2**128 | 32 | x.1.32 |
  21. id-blake2b384 | 64-bit | 2**192 | 48 | x.1.48 |
  22. id-blake2b512 | 64-bit | 2**256 | 64 | x.1.64 |
  23. ---------------+--------+-----------+------+------------+
  24. */
  25. /**
  26. * Implementation of the cryptographic hash function Blakbe2b.
  27. * <p>
  28. * Blake2b offers a built-in keying mechanism to be used directly
  29. * for authentication ("Prefix-MAC") rather than a HMAC construction.
  30. * <p>
  31. * Blake2b offers a built-in support for a salt for randomized hashing
  32. * and a personal string for defining a unique hash function for each application.
  33. * <p>
  34. * BLAKE2b is optimized for 64-bit platforms and produces digests of any size
  35. * between 1 and 64 bytes.
  36. */
  37. public class Blake2bDigest
  38. : IDigest
  39. {
  40. // Blake2b Initialization Vector:
  41. private static readonly ulong[] blake2b_IV =
  42. // Produced from the square root of primes 2, 3, 5, 7, 11, 13, 17, 19.
  43. // The same as SHA-512 IV.
  44. {
  45. 0x6a09e667f3bcc908UL, 0xbb67ae8584caa73bUL, 0x3c6ef372fe94f82bUL,
  46. 0xa54ff53a5f1d36f1UL, 0x510e527fade682d1UL, 0x9b05688c2b3e6c1fUL,
  47. 0x1f83d9abfb41bd6bUL, 0x5be0cd19137e2179UL
  48. };
  49. // Message word permutations:
  50. private static readonly byte[,] blake2b_sigma =
  51. {
  52. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
  53. { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 },
  54. { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 },
  55. { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 },
  56. { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 },
  57. { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 },
  58. { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 },
  59. { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 },
  60. { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 },
  61. { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 },
  62. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 },
  63. { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }
  64. };
  65. private const int ROUNDS = 12; // to use for Catenas H'
  66. private const int BLOCK_LENGTH_BYTES = 128;// bytes
  67. // General parameters:
  68. private int digestLength = 64; // 1- 64 bytes
  69. private int keyLength = 0; // 0 - 64 bytes for keyed hashing for MAC
  70. private byte[] salt = null;// new byte[16];
  71. private byte[] personalization = null;// new byte[16];
  72. // the key
  73. private byte[] key = null;
  74. // Tree hashing parameters:
  75. // Because this class does not implement the Tree Hashing Mode,
  76. // these parameters can be treated as constants (see init() function)
  77. /*
  78. * private int fanout = 1; // 0-255 private int depth = 1; // 1 - 255
  79. * private int leafLength= 0; private long nodeOffset = 0L; private int
  80. * nodeDepth = 0; private int innerHashLength = 0;
  81. */
  82. // whenever this buffer overflows, it will be processed
  83. // in the Compress() function.
  84. // For performance issues, long messages will not use this buffer.
  85. private byte[] buffer = null;// new byte[BLOCK_LENGTH_BYTES];
  86. // Position of last inserted byte:
  87. private int bufferPos = 0;// a value from 0 up to 128
  88. private ulong[] internalState = new ulong[16]; // In the Blake2b paper it is
  89. // called: v
  90. private ulong[] chainValue = null; // state vector, in the Blake2b paper it
  91. // is called: h
  92. private ulong t0 = 0UL; // holds last significant bits, counter (counts bytes)
  93. private ulong t1 = 0UL; // counter: Length up to 2^128 are supported
  94. private ulong f0 = 0UL; // finalization flag, for last block: ~0L
  95. // For Tree Hashing Mode, not used here:
  96. // private long f1 = 0L; // finalization flag, for last node: ~0L
  97. public Blake2bDigest()
  98. : this(512)
  99. {
  100. }
  101. public Blake2bDigest(Blake2bDigest digest)
  102. {
  103. this.bufferPos = digest.bufferPos;
  104. this.buffer = Arrays.Clone(digest.buffer);
  105. this.keyLength = digest.keyLength;
  106. this.key = Arrays.Clone(digest.key);
  107. this.digestLength = digest.digestLength;
  108. this.chainValue = Arrays.Clone(digest.chainValue);
  109. this.personalization = Arrays.Clone(digest.personalization);
  110. this.salt = Arrays.Clone(digest.salt);
  111. this.t0 = digest.t0;
  112. this.t1 = digest.t1;
  113. this.f0 = digest.f0;
  114. }
  115. /**
  116. * Basic sized constructor - size in bits.
  117. *
  118. * @param digestSize size of the digest in bits
  119. */
  120. public Blake2bDigest(int digestSize)
  121. {
  122. if (digestSize < 8 || digestSize > 512 || digestSize % 8 != 0)
  123. throw new ArgumentException("BLAKE2b digest bit length must be a multiple of 8 and not greater than 512");
  124. buffer = new byte[BLOCK_LENGTH_BYTES];
  125. keyLength = 0;
  126. this.digestLength = digestSize / 8;
  127. Init();
  128. }
  129. /**
  130. * Blake2b for authentication ("Prefix-MAC mode").
  131. * After calling the doFinal() method, the key will
  132. * remain to be used for further computations of
  133. * this instance.
  134. * The key can be overwritten using the clearKey() method.
  135. *
  136. * @param key A key up to 64 bytes or null
  137. */
  138. public Blake2bDigest(byte[] key)
  139. {
  140. buffer = new byte[BLOCK_LENGTH_BYTES];
  141. if (key != null)
  142. {
  143. this.key = new byte[key.Length];
  144. Array.Copy(key, 0, this.key, 0, key.Length);
  145. if (key.Length > 64)
  146. throw new ArgumentException("Keys > 64 are not supported");
  147. keyLength = key.Length;
  148. Array.Copy(key, 0, buffer, 0, key.Length);
  149. bufferPos = BLOCK_LENGTH_BYTES; // zero padding
  150. }
  151. digestLength = 64;
  152. Init();
  153. }
  154. /**
  155. * Blake2b with key, required digest length (in bytes), salt and personalization.
  156. * After calling the doFinal() method, the key, the salt and the personal string
  157. * will remain and might be used for further computations with this instance.
  158. * The key can be overwritten using the clearKey() method, the salt (pepper)
  159. * can be overwritten using the clearSalt() method.
  160. *
  161. * @param key A key up to 64 bytes or null
  162. * @param digestLength from 1 up to 64 bytes
  163. * @param salt 16 bytes or null
  164. * @param personalization 16 bytes or null
  165. */
  166. public Blake2bDigest(byte[] key, int digestLength, byte[] salt, byte[] personalization)
  167. {
  168. if (digestLength < 1 || digestLength > 64)
  169. throw new ArgumentException("Invalid digest length (required: 1 - 64)");
  170. this.digestLength = digestLength;
  171. this.buffer = new byte[BLOCK_LENGTH_BYTES];
  172. if (salt != null)
  173. {
  174. if (salt.Length != 16)
  175. throw new ArgumentException("salt length must be exactly 16 bytes");
  176. this.salt = new byte[16];
  177. Array.Copy(salt, 0, this.salt, 0, salt.Length);
  178. }
  179. if (personalization != null)
  180. {
  181. if (personalization.Length != 16)
  182. throw new ArgumentException("personalization length must be exactly 16 bytes");
  183. this.personalization = new byte[16];
  184. Array.Copy(personalization, 0, this.personalization, 0, personalization.Length);
  185. }
  186. if (key != null)
  187. {
  188. if (key.Length > 64)
  189. throw new ArgumentException("Keys > 64 are not supported");
  190. this.key = new byte[key.Length];
  191. Array.Copy(key, 0, this.key, 0, key.Length);
  192. keyLength = key.Length;
  193. Array.Copy(key, 0, buffer, 0, key.Length);
  194. bufferPos = BLOCK_LENGTH_BYTES; // zero padding
  195. }
  196. Init();
  197. }
  198. // initialize chainValue
  199. private void Init()
  200. {
  201. if (chainValue == null)
  202. {
  203. chainValue = new ulong[8];
  204. chainValue[0] = blake2b_IV[0] ^ (ulong)(digestLength | (keyLength << 8) | 0x1010000);
  205. // 0x1010000 = ((fanout << 16) | (depth << 24) | (leafLength <<
  206. // 32));
  207. // with fanout = 1; depth = 0; leafLength = 0;
  208. chainValue[1] = blake2b_IV[1];// ^ nodeOffset; with nodeOffset = 0;
  209. chainValue[2] = blake2b_IV[2];// ^ ( nodeDepth | (innerHashLength << 8) );
  210. // with nodeDepth = 0; innerHashLength = 0;
  211. chainValue[3] = blake2b_IV[3];
  212. chainValue[4] = blake2b_IV[4];
  213. chainValue[5] = blake2b_IV[5];
  214. if (salt != null)
  215. {
  216. chainValue[4] ^= Pack.LE_To_UInt64(salt, 0);
  217. chainValue[5] ^= Pack.LE_To_UInt64(salt, 8);
  218. }
  219. chainValue[6] = blake2b_IV[6];
  220. chainValue[7] = blake2b_IV[7];
  221. if (personalization != null)
  222. {
  223. chainValue[6] ^= Pack.LE_To_UInt64(personalization, 0);
  224. chainValue[7] ^= Pack.LE_To_UInt64(personalization, 8);
  225. }
  226. }
  227. }
  228. private void InitializeInternalState()
  229. {
  230. // initialize v:
  231. Array.Copy(chainValue, 0, internalState, 0, chainValue.Length);
  232. Array.Copy(blake2b_IV, 0, internalState, chainValue.Length, 4);
  233. internalState[12] = t0 ^ blake2b_IV[4];
  234. internalState[13] = t1 ^ blake2b_IV[5];
  235. internalState[14] = f0 ^ blake2b_IV[6];
  236. internalState[15] = blake2b_IV[7];// ^ f1 with f1 = 0
  237. }
  238. /**
  239. * update the message digest with a single byte.
  240. *
  241. * @param b the input byte to be entered.
  242. */
  243. public virtual void Update(byte b)
  244. {
  245. int remainingLength = 0; // left bytes of buffer
  246. // process the buffer if full else add to buffer:
  247. remainingLength = BLOCK_LENGTH_BYTES - bufferPos;
  248. if (remainingLength == 0)
  249. { // full buffer
  250. t0 += BLOCK_LENGTH_BYTES;
  251. if (t0 == 0)
  252. { // if message > 2^64
  253. t1++;
  254. }
  255. Compress(buffer, 0);
  256. Array.Clear(buffer, 0, buffer.Length);// clear buffer
  257. buffer[0] = b;
  258. bufferPos = 1;
  259. }
  260. else
  261. {
  262. buffer[bufferPos] = b;
  263. bufferPos++;
  264. return;
  265. }
  266. }
  267. /**
  268. * update the message digest with a block of bytes.
  269. *
  270. * @param message the byte array containing the data.
  271. * @param offset the offset into the byte array where the data starts.
  272. * @param len the length of the data.
  273. */
  274. public virtual void BlockUpdate(byte[] message, int offset, int len)
  275. {
  276. if (message == null || len == 0)
  277. return;
  278. int remainingLength = 0; // left bytes of buffer
  279. if (bufferPos != 0)
  280. { // commenced, incomplete buffer
  281. // complete the buffer:
  282. remainingLength = BLOCK_LENGTH_BYTES - bufferPos;
  283. if (remainingLength < len)
  284. { // full buffer + at least 1 byte
  285. Array.Copy(message, offset, buffer, bufferPos,
  286. remainingLength);
  287. t0 += BLOCK_LENGTH_BYTES;
  288. if (t0 == 0)
  289. { // if message > 2^64
  290. t1++;
  291. }
  292. Compress(buffer, 0);
  293. bufferPos = 0;
  294. Array.Clear(buffer, 0, buffer.Length);// clear buffer
  295. }
  296. else
  297. {
  298. Array.Copy(message, offset, buffer, bufferPos, len);
  299. bufferPos += len;
  300. return;
  301. }
  302. }
  303. // process blocks except last block (also if last block is full)
  304. int messagePos;
  305. int blockWiseLastPos = offset + len - BLOCK_LENGTH_BYTES;
  306. for (messagePos = offset + remainingLength; messagePos < blockWiseLastPos; messagePos += BLOCK_LENGTH_BYTES)
  307. { // block wise 128 bytes
  308. // without buffer:
  309. t0 += BLOCK_LENGTH_BYTES;
  310. if (t0 == 0)
  311. {
  312. t1++;
  313. }
  314. Compress(message, messagePos);
  315. }
  316. // fill the buffer with left bytes, this might be a full block
  317. Array.Copy(message, messagePos, buffer, 0, offset + len
  318. - messagePos);
  319. bufferPos += offset + len - messagePos;
  320. }
  321. /**
  322. * close the digest, producing the final digest value. The doFinal
  323. * call leaves the digest reset.
  324. * Key, salt and personal string remain.
  325. *
  326. * @param out the array the digest is to be copied into.
  327. * @param outOffset the offset into the out array the digest is to start at.
  328. */
  329. public virtual int DoFinal(byte[] output, int outOffset)
  330. {
  331. f0 = 0xFFFFFFFFFFFFFFFFUL;
  332. t0 += (ulong)bufferPos;
  333. if (bufferPos > 0 && t0 == 0)
  334. {
  335. t1++;
  336. }
  337. Compress(buffer, 0);
  338. Array.Clear(buffer, 0, buffer.Length);// Holds eventually the key if input is null
  339. Array.Clear(internalState, 0, internalState.Length);
  340. for (int i = 0; i < chainValue.Length && (i * 8 < digestLength); i++)
  341. {
  342. byte[] bytes = Pack.UInt64_To_LE(chainValue[i]);
  343. if (i * 8 < digestLength - 8)
  344. {
  345. Array.Copy(bytes, 0, output, outOffset + i * 8, 8);
  346. }
  347. else
  348. {
  349. Array.Copy(bytes, 0, output, outOffset + i * 8, digestLength - (i * 8));
  350. }
  351. }
  352. Array.Clear(chainValue, 0, chainValue.Length);
  353. Reset();
  354. return digestLength;
  355. }
  356. /**
  357. * Reset the digest back to it's initial state.
  358. * The key, the salt and the personal string will
  359. * remain for further computations.
  360. */
  361. public virtual void Reset()
  362. {
  363. bufferPos = 0;
  364. f0 = 0L;
  365. t0 = 0L;
  366. t1 = 0L;
  367. chainValue = null;
  368. Array.Clear(buffer, 0, buffer.Length);
  369. if (key != null)
  370. {
  371. Array.Copy(key, 0, buffer, 0, key.Length);
  372. bufferPos = BLOCK_LENGTH_BYTES; // zero padding
  373. }
  374. Init();
  375. }
  376. private void Compress(byte[] message, int messagePos)
  377. {
  378. InitializeInternalState();
  379. ulong[] m = new ulong[16];
  380. for (int j = 0; j < 16; j++)
  381. {
  382. m[j] = Pack.LE_To_UInt64(message, messagePos + j * 8);
  383. }
  384. for (int round = 0; round < ROUNDS; round++)
  385. {
  386. // G apply to columns of internalState:m[blake2b_sigma[round][2 * blockPos]] /+1
  387. G(m[blake2b_sigma[round,0]], m[blake2b_sigma[round,1]], 0, 4, 8, 12);
  388. G(m[blake2b_sigma[round,2]], m[blake2b_sigma[round,3]], 1, 5, 9, 13);
  389. G(m[blake2b_sigma[round,4]], m[blake2b_sigma[round,5]], 2, 6, 10, 14);
  390. G(m[blake2b_sigma[round,6]], m[blake2b_sigma[round,7]], 3, 7, 11, 15);
  391. // G apply to diagonals of internalState:
  392. G(m[blake2b_sigma[round,8]], m[blake2b_sigma[round,9]], 0, 5, 10, 15);
  393. G(m[blake2b_sigma[round,10]], m[blake2b_sigma[round,11]], 1, 6, 11, 12);
  394. G(m[blake2b_sigma[round,12]], m[blake2b_sigma[round,13]], 2, 7, 8, 13);
  395. G(m[blake2b_sigma[round,14]], m[blake2b_sigma[round,15]], 3, 4, 9, 14);
  396. }
  397. // update chain values:
  398. for (int offset = 0; offset < chainValue.Length; offset++)
  399. {
  400. chainValue[offset] = chainValue[offset] ^ internalState[offset] ^ internalState[offset + 8];
  401. }
  402. }
  403. private void G(ulong m1, ulong m2, int posA, int posB, int posC, int posD)
  404. {
  405. internalState[posA] = internalState[posA] + internalState[posB] + m1;
  406. internalState[posD] = Rotr64(internalState[posD] ^ internalState[posA], 32);
  407. internalState[posC] = internalState[posC] + internalState[posD];
  408. internalState[posB] = Rotr64(internalState[posB] ^ internalState[posC], 24); // replaces 25 of BLAKE
  409. internalState[posA] = internalState[posA] + internalState[posB] + m2;
  410. internalState[posD] = Rotr64(internalState[posD] ^ internalState[posA], 16);
  411. internalState[posC] = internalState[posC] + internalState[posD];
  412. internalState[posB] = Rotr64(internalState[posB] ^ internalState[posC], 63); // replaces 11 of BLAKE
  413. }
  414. private static ulong Rotr64(ulong x, int rot)
  415. {
  416. return x >> rot | x << -rot;
  417. }
  418. /**
  419. * return the algorithm name
  420. *
  421. * @return the algorithm name
  422. */
  423. public virtual string AlgorithmName
  424. {
  425. get { return "BLAKE2b"; }
  426. }
  427. /**
  428. * return the size, in bytes, of the digest produced by this message digest.
  429. *
  430. * @return the size, in bytes, of the digest produced by this message digest.
  431. */
  432. public virtual int GetDigestSize()
  433. {
  434. return digestLength;
  435. }
  436. /**
  437. * Return the size in bytes of the internal buffer the digest applies it's compression
  438. * function to.
  439. *
  440. * @return byte length of the digests internal buffer.
  441. */
  442. public virtual int GetByteLength()
  443. {
  444. return BLOCK_LENGTH_BYTES;
  445. }
  446. /**
  447. * Overwrite the key
  448. * if it is no longer used (zeroization)
  449. */
  450. public virtual void ClearKey()
  451. {
  452. if (key != null)
  453. {
  454. Array.Clear(key, 0, key.Length);
  455. Array.Clear(buffer, 0, buffer.Length);
  456. }
  457. }
  458. /**
  459. * Overwrite the salt (pepper) if it
  460. * is secret and no longer used (zeroization)
  461. */
  462. public virtual void ClearSalt()
  463. {
  464. if (salt != null)
  465. {
  466. Array.Clear(salt, 0, salt.Length);
  467. }
  468. }
  469. }
  470. }
  471. #pragma warning restore
  472. #endif