1 //========================================================================
2 //
3 // Decrypt.cc
4 //
5 // Copyright 1996-2003 Glyph & Cog, LLC
6 //
7 //========================================================================
8 
9 //========================================================================
10 //
11 // Modified under the Poppler project - http://poppler.freedesktop.org
12 //
13 // All changes made under the Poppler project to this file are licensed
14 // under GPL version 2 or later
15 //
16 // Copyright (C) 2008 Julien Rebetez <julien@fhtagn.net>
17 // Copyright (C) 2008, 2010, 2016-2021 Albert Astals Cid <aacid@kde.org>
18 // Copyright (C) 2009 Matthias Franz <matthias@ktug.or.kr>
19 // Copyright (C) 2009 David Benjamin <davidben@mit.edu>
20 // Copyright (C) 2012 Fabio D'Urso <fabiodurso@hotmail.it>
21 // Copyright (C) 2013, 2017 Adrian Johnson <ajohnson@redneon.com>
22 // Copyright (C) 2016 Alok Anand <alok4nand@gmail.com>
23 // Copyright (C) 2016 Thomas Freitag <Thomas.Freitag@alfa.de>
24 // Copyright (C) 2018 Adam Reichold <adam.reichold@t-online.de>
25 //
26 // To see a description of the changes please see the Changelog file that
27 // came with your tarball or type make ChangeLog if you are building from git
28 //
29 //========================================================================
30 
31 #include <config.h>
32 
33 #include <cstdint>
34 #include <cstring>
35 #include "goo/gmem.h"
36 #include "goo/grandom.h"
37 #include "Decrypt.h"
38 #include "Error.h"
39 
40 static void rc4InitKey(const unsigned char *key, int keyLen, unsigned char *state);
41 static unsigned char rc4DecryptByte(unsigned char *state, unsigned char *x, unsigned char *y, unsigned char c);
42 
43 static bool aesReadBlock(Stream *str, unsigned char *in, bool addPadding);
44 
45 static void aesKeyExpansion(DecryptAESState *s, const unsigned char *objKey, int objKeyLen, bool decrypt);
46 static void aesEncryptBlock(DecryptAESState *s, const unsigned char *in);
47 static void aesDecryptBlock(DecryptAESState *s, const unsigned char *in, bool last);
48 
49 static void aes256KeyExpansion(DecryptAES256State *s, const unsigned char *objKey, int objKeyLen, bool decrypt);
50 static void aes256EncryptBlock(DecryptAES256State *s, const unsigned char *in);
51 static void aes256DecryptBlock(DecryptAES256State *s, const unsigned char *in, bool last);
52 
53 static void sha256(unsigned char *msg, int msgLen, unsigned char *hash);
54 static void sha384(unsigned char *msg, int msgLen, unsigned char *hash);
55 static void sha512(unsigned char *msg, int msgLen, unsigned char *hash);
56 
57 static void revision6Hash(const GooString *inputPassword, unsigned char *K, const char *userKey);
58 
59 static const unsigned char passwordPad[32] = { 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08, 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80, 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a };
60 
61 //------------------------------------------------------------------------
62 // Decrypt
63 //------------------------------------------------------------------------
64 
makeFileKey(int encVersion,int encRevision,int keyLength,const GooString * ownerKey,const GooString * userKey,const GooString * ownerEnc,const GooString * userEnc,int permissions,const GooString * fileID,const GooString * ownerPassword,const GooString * userPassword,unsigned char * fileKey,bool encryptMetadata,bool * ownerPasswordOk)65 bool Decrypt::makeFileKey(int encVersion, int encRevision, int keyLength, const GooString *ownerKey, const GooString *userKey, const GooString *ownerEnc, const GooString *userEnc, int permissions, const GooString *fileID,
66                           const GooString *ownerPassword, const GooString *userPassword, unsigned char *fileKey, bool encryptMetadata, bool *ownerPasswordOk)
67 {
68     DecryptAES256State state;
69     unsigned char test[127 + 56], test2[32];
70     GooString *userPassword2;
71     unsigned char fState[256];
72     unsigned char tmpKey[16];
73     unsigned char fx, fy;
74     int len, i, j;
75 
76     *ownerPasswordOk = false;
77 
78     if (encRevision == 5 || encRevision == 6) {
79 
80         // check the owner password
81         if (ownerPassword) {
82             //~ this is supposed to convert the password to UTF-8 using "SASLprep"
83             len = ownerPassword->getLength();
84             if (len > 127) {
85                 len = 127;
86             }
87             memcpy(test, ownerPassword->c_str(), len);
88             memcpy(test + len, ownerKey->c_str() + 32, 8);
89             memcpy(test + len + 8, userKey->c_str(), 48);
90             sha256(test, len + 56, test);
91             if (encRevision == 6) {
92                 // test contains the initial SHA-256 hash as input K.
93                 revision6Hash(ownerPassword, test, userKey->c_str());
94             }
95             if (!memcmp(test, ownerKey->c_str(), 32)) {
96 
97                 // compute the file key from the owner password
98                 memcpy(test, ownerPassword->c_str(), len);
99                 memcpy(test + len, ownerKey->c_str() + 40, 8);
100                 memcpy(test + len + 8, userKey->c_str(), 48);
101                 sha256(test, len + 56, test);
102                 if (encRevision == 6) {
103                     // test contains the initial SHA-256 hash input K.
104                     revision6Hash(ownerPassword, test, userKey->c_str());
105                 }
106                 aes256KeyExpansion(&state, test, 32, true);
107                 for (i = 0; i < 16; ++i) {
108                     state.cbc[i] = 0;
109                 }
110                 aes256DecryptBlock(&state, (unsigned char *)ownerEnc->c_str(), false);
111                 memcpy(fileKey, state.buf, 16);
112                 aes256DecryptBlock(&state, (unsigned char *)ownerEnc->c_str() + 16, false);
113                 memcpy(fileKey + 16, state.buf, 16);
114 
115                 *ownerPasswordOk = true;
116                 return true;
117             }
118         }
119 
120         // check the user password
121         if (userPassword) {
122             //~ this is supposed to convert the password to UTF-8 using "SASLprep"
123             len = userPassword->getLength();
124             if (len > 127) {
125                 len = 127;
126             }
127             memcpy(test, userPassword->c_str(), len);
128             memcpy(test + len, userKey->c_str() + 32, 8);
129             sha256(test, len + 8, test);
130             if (encRevision == 6) {
131                 // test contains the initial SHA-256 hash input K.
132                 // user key is not used in checking user password.
133                 revision6Hash(userPassword, test, nullptr);
134             }
135             if (!memcmp(test, userKey->c_str(), 32)) {
136 
137                 // compute the file key from the user password
138                 memcpy(test, userPassword->c_str(), len);
139                 memcpy(test + len, userKey->c_str() + 40, 8);
140                 sha256(test, len + 8, test);
141                 if (encRevision == 6) {
142                     // test contains the initial SHA-256 hash input K.
143                     // user key is not used in computing intermediate user key.
144                     revision6Hash(userPassword, test, nullptr);
145                 }
146                 aes256KeyExpansion(&state, test, 32, true);
147                 for (i = 0; i < 16; ++i) {
148                     state.cbc[i] = 0;
149                 }
150                 aes256DecryptBlock(&state, (unsigned char *)userEnc->c_str(), false);
151                 memcpy(fileKey, state.buf, 16);
152                 aes256DecryptBlock(&state, (unsigned char *)userEnc->c_str() + 16, false);
153                 memcpy(fileKey + 16, state.buf, 16);
154 
155                 return true;
156             }
157         }
158 
159         return false;
160     } else {
161 
162         // try using the supplied owner password to generate the user password
163         if (ownerPassword) {
164             len = ownerPassword->getLength();
165             if (len < 32) {
166                 memcpy(test, ownerPassword->c_str(), len);
167                 memcpy(test + len, passwordPad, 32 - len);
168             } else {
169                 memcpy(test, ownerPassword->c_str(), 32);
170             }
171             md5(test, 32, test);
172             if (encRevision == 3) {
173                 for (i = 0; i < 50; ++i) {
174                     md5(test, keyLength, test);
175                 }
176             }
177             if (encRevision == 2) {
178                 rc4InitKey(test, keyLength, fState);
179                 fx = fy = 0;
180                 for (i = 0; i < 32; ++i) {
181                     test2[i] = rc4DecryptByte(fState, &fx, &fy, ownerKey->getChar(i));
182                 }
183             } else {
184                 memcpy(test2, ownerKey->c_str(), 32);
185                 for (i = 19; i >= 0; --i) {
186                     for (j = 0; j < keyLength; ++j) {
187                         tmpKey[j] = test[j] ^ i;
188                     }
189                     rc4InitKey(tmpKey, keyLength, fState);
190                     fx = fy = 0;
191                     for (j = 0; j < 32; ++j) {
192                         test2[j] = rc4DecryptByte(fState, &fx, &fy, test2[j]);
193                     }
194                 }
195             }
196             userPassword2 = new GooString((char *)test2, 32);
197             if (makeFileKey2(encVersion, encRevision, keyLength, ownerKey, userKey, permissions, fileID, userPassword2, fileKey, encryptMetadata)) {
198                 *ownerPasswordOk = true;
199                 delete userPassword2;
200                 return true;
201             }
202             delete userPassword2;
203         }
204 
205         // try using the supplied user password
206         return makeFileKey2(encVersion, encRevision, keyLength, ownerKey, userKey, permissions, fileID, userPassword, fileKey, encryptMetadata);
207     }
208 }
209 
makeFileKey2(int encVersion,int encRevision,int keyLength,const GooString * ownerKey,const GooString * userKey,int permissions,const GooString * fileID,const GooString * userPassword,unsigned char * fileKey,bool encryptMetadata)210 bool Decrypt::makeFileKey2(int encVersion, int encRevision, int keyLength, const GooString *ownerKey, const GooString *userKey, int permissions, const GooString *fileID, const GooString *userPassword, unsigned char *fileKey,
211                            bool encryptMetadata)
212 {
213     unsigned char *buf;
214     unsigned char test[32];
215     unsigned char fState[256];
216     unsigned char tmpKey[16];
217     unsigned char fx, fy;
218     int len, i, j;
219     bool ok;
220 
221     // generate file key
222     buf = (unsigned char *)gmalloc(72 + fileID->getLength());
223     if (userPassword) {
224         len = userPassword->getLength();
225         if (len < 32) {
226             memcpy(buf, userPassword->c_str(), len);
227             memcpy(buf + len, passwordPad, 32 - len);
228         } else {
229             memcpy(buf, userPassword->c_str(), 32);
230         }
231     } else {
232         memcpy(buf, passwordPad, 32);
233     }
234     memcpy(buf + 32, ownerKey->c_str(), 32);
235     buf[64] = permissions & 0xff;
236     buf[65] = (permissions >> 8) & 0xff;
237     buf[66] = (permissions >> 16) & 0xff;
238     buf[67] = (permissions >> 24) & 0xff;
239     memcpy(buf + 68, fileID->c_str(), fileID->getLength());
240     len = 68 + fileID->getLength();
241     if (!encryptMetadata) {
242         buf[len++] = 0xff;
243         buf[len++] = 0xff;
244         buf[len++] = 0xff;
245         buf[len++] = 0xff;
246     }
247     md5(buf, len, fileKey);
248     if (encRevision == 3) {
249         for (i = 0; i < 50; ++i) {
250             md5(fileKey, keyLength, fileKey);
251         }
252     }
253 
254     // test user password
255     if (encRevision == 2) {
256         rc4InitKey(fileKey, keyLength, fState);
257         fx = fy = 0;
258         for (i = 0; i < 32; ++i) {
259             test[i] = rc4DecryptByte(fState, &fx, &fy, userKey->getChar(i));
260         }
261         ok = memcmp(test, passwordPad, 32) == 0;
262     } else if (encRevision == 3) {
263         memcpy(test, userKey->c_str(), 32);
264         for (i = 19; i >= 0; --i) {
265             for (j = 0; j < keyLength; ++j) {
266                 tmpKey[j] = fileKey[j] ^ i;
267             }
268             rc4InitKey(tmpKey, keyLength, fState);
269             fx = fy = 0;
270             for (j = 0; j < 32; ++j) {
271                 test[j] = rc4DecryptByte(fState, &fx, &fy, test[j]);
272             }
273         }
274         memcpy(buf, passwordPad, 32);
275         memcpy(buf + 32, fileID->c_str(), fileID->getLength());
276         md5(buf, 32 + fileID->getLength(), buf);
277         ok = memcmp(test, buf, 16) == 0;
278     } else {
279         ok = false;
280     }
281 
282     gfree(buf);
283     return ok;
284 }
285 
286 //------------------------------------------------------------------------
287 // BaseCryptStream
288 //------------------------------------------------------------------------
289 
BaseCryptStream(Stream * strA,const unsigned char * fileKey,CryptAlgorithm algoA,int keyLength,Ref refA)290 BaseCryptStream::BaseCryptStream(Stream *strA, const unsigned char *fileKey, CryptAlgorithm algoA, int keyLength, Ref refA) : FilterStream(strA)
291 {
292     algo = algoA;
293 
294     // construct object key
295     for (int i = 0; i < keyLength; ++i) {
296         objKey[i] = fileKey[i];
297     }
298     for (std::size_t i = keyLength; i < sizeof(objKey); ++i) {
299         objKey[i] = 0;
300     }
301 
302     switch (algo) {
303     case cryptRC4:
304         if (likely(keyLength < static_cast<int>(sizeof(objKey) - 4))) {
305             objKey[keyLength] = refA.num & 0xff;
306             objKey[keyLength + 1] = (refA.num >> 8) & 0xff;
307             objKey[keyLength + 2] = (refA.num >> 16) & 0xff;
308             objKey[keyLength + 3] = refA.gen & 0xff;
309             objKey[keyLength + 4] = (refA.gen >> 8) & 0xff;
310             md5(objKey, keyLength + 5, objKey);
311         }
312         if ((objKeyLength = keyLength + 5) > 16) {
313             objKeyLength = 16;
314         }
315         break;
316     case cryptAES:
317         objKey[keyLength] = refA.num & 0xff;
318         objKey[keyLength + 1] = (refA.num >> 8) & 0xff;
319         objKey[keyLength + 2] = (refA.num >> 16) & 0xff;
320         objKey[keyLength + 3] = refA.gen & 0xff;
321         objKey[keyLength + 4] = (refA.gen >> 8) & 0xff;
322         objKey[keyLength + 5] = 0x73; // 's'
323         objKey[keyLength + 6] = 0x41; // 'A'
324         objKey[keyLength + 7] = 0x6c; // 'l'
325         objKey[keyLength + 8] = 0x54; // 'T'
326         md5(objKey, keyLength + 9, objKey);
327         if ((objKeyLength = keyLength + 5) > 16) {
328             objKeyLength = 16;
329         }
330         break;
331     case cryptAES256:
332         objKeyLength = keyLength;
333         break;
334     case cryptNone:
335         break;
336     }
337 
338     charactersRead = 0;
339     nextCharBuff = EOF;
340     autoDelete = true;
341 }
342 
~BaseCryptStream()343 BaseCryptStream::~BaseCryptStream()
344 {
345     if (autoDelete) {
346         delete str;
347     }
348 }
349 
reset()350 void BaseCryptStream::reset()
351 {
352     charactersRead = 0;
353     nextCharBuff = EOF;
354     str->reset();
355 }
356 
getPos()357 Goffset BaseCryptStream::getPos()
358 {
359     return charactersRead;
360 }
361 
getChar()362 int BaseCryptStream::getChar()
363 {
364     // Read next character and empty the buffer, so that a new character will be read next time
365     int c = lookChar();
366     nextCharBuff = EOF;
367 
368     if (c != EOF)
369         charactersRead++;
370     return c;
371 }
372 
isBinary(bool last) const373 bool BaseCryptStream::isBinary(bool last) const
374 {
375     return str->isBinary(last);
376 }
377 
setAutoDelete(bool val)378 void BaseCryptStream::setAutoDelete(bool val)
379 {
380     autoDelete = val;
381 }
382 
383 //------------------------------------------------------------------------
384 // EncryptStream
385 //------------------------------------------------------------------------
386 
EncryptStream(Stream * strA,const unsigned char * fileKey,CryptAlgorithm algoA,int keyLength,Ref refA)387 EncryptStream::EncryptStream(Stream *strA, const unsigned char *fileKey, CryptAlgorithm algoA, int keyLength, Ref refA) : BaseCryptStream(strA, fileKey, algoA, keyLength, refA)
388 {
389     // Fill the CBC initialization vector for AES and AES-256
390     switch (algo) {
391     case cryptAES:
392         grandom_fill(state.aes.cbc, 16);
393         break;
394     case cryptAES256:
395         grandom_fill(state.aes256.cbc, 16);
396         break;
397     default:
398         break;
399     }
400 }
401 
~EncryptStream()402 EncryptStream::~EncryptStream() { }
403 
reset()404 void EncryptStream::reset()
405 {
406     BaseCryptStream::reset();
407 
408     switch (algo) {
409     case cryptRC4:
410         state.rc4.x = state.rc4.y = 0;
411         rc4InitKey(objKey, objKeyLength, state.rc4.state);
412         break;
413     case cryptAES:
414         aesKeyExpansion(&state.aes, objKey, objKeyLength, false);
415         memcpy(state.aes.buf, state.aes.cbc, 16); // Copy CBC IV to buf
416         state.aes.bufIdx = 0;
417         state.aes.paddingReached = false;
418         break;
419     case cryptAES256:
420         aes256KeyExpansion(&state.aes256, objKey, objKeyLength, false);
421         memcpy(state.aes256.buf, state.aes256.cbc, 16); // Copy CBC IV to buf
422         state.aes256.bufIdx = 0;
423         state.aes256.paddingReached = false;
424         break;
425     case cryptNone:
426         break;
427     }
428 }
429 
lookChar()430 int EncryptStream::lookChar()
431 {
432     unsigned char in[16];
433     int c;
434 
435     if (nextCharBuff != EOF)
436         return nextCharBuff;
437 
438     c = EOF; // make gcc happy
439     switch (algo) {
440     case cryptRC4:
441         if ((c = str->getChar()) != EOF) {
442             // RC4 is XOR-based: the decryption algorithm works for encryption too
443             c = rc4DecryptByte(state.rc4.state, &state.rc4.x, &state.rc4.y, (unsigned char)c);
444         }
445         break;
446     case cryptAES:
447         if (state.aes.bufIdx == 16 && !state.aes.paddingReached) {
448             state.aes.paddingReached = !aesReadBlock(str, in, true);
449             aesEncryptBlock(&state.aes, in);
450         }
451         if (state.aes.bufIdx == 16) {
452             c = EOF;
453         } else {
454             c = state.aes.buf[state.aes.bufIdx++];
455         }
456         break;
457     case cryptAES256:
458         if (state.aes256.bufIdx == 16 && !state.aes256.paddingReached) {
459             state.aes256.paddingReached = !aesReadBlock(str, in, true);
460             aes256EncryptBlock(&state.aes256, in);
461         }
462         if (state.aes256.bufIdx == 16) {
463             c = EOF;
464         } else {
465             c = state.aes256.buf[state.aes256.bufIdx++];
466         }
467         break;
468     case cryptNone:
469         break;
470     }
471     return (nextCharBuff = c);
472 }
473 
474 //------------------------------------------------------------------------
475 // DecryptStream
476 //------------------------------------------------------------------------
477 
DecryptStream(Stream * strA,const unsigned char * fileKey,CryptAlgorithm algoA,int keyLength,Ref refA)478 DecryptStream::DecryptStream(Stream *strA, const unsigned char *fileKey, CryptAlgorithm algoA, int keyLength, Ref refA) : BaseCryptStream(strA, fileKey, algoA, keyLength, refA) { }
479 
~DecryptStream()480 DecryptStream::~DecryptStream() { }
481 
reset()482 void DecryptStream::reset()
483 {
484     int i;
485     BaseCryptStream::reset();
486 
487     switch (algo) {
488     case cryptRC4:
489         state.rc4.x = state.rc4.y = 0;
490         rc4InitKey(objKey, objKeyLength, state.rc4.state);
491         break;
492     case cryptAES:
493         aesKeyExpansion(&state.aes, objKey, objKeyLength, true);
494         for (i = 0; i < 16; ++i) {
495             state.aes.cbc[i] = str->getChar();
496         }
497         state.aes.bufIdx = 16;
498         break;
499     case cryptAES256:
500         aes256KeyExpansion(&state.aes256, objKey, objKeyLength, true);
501         for (i = 0; i < 16; ++i) {
502             state.aes256.cbc[i] = str->getChar();
503         }
504         state.aes256.bufIdx = 16;
505         break;
506     case cryptNone:
507         break;
508     }
509 }
510 
lookChar()511 int DecryptStream::lookChar()
512 {
513     unsigned char in[16];
514     int c;
515 
516     if (nextCharBuff != EOF)
517         return nextCharBuff;
518 
519     c = EOF; // make gcc happy
520     switch (algo) {
521     case cryptRC4:
522         if ((c = str->getChar()) != EOF) {
523             c = rc4DecryptByte(state.rc4.state, &state.rc4.x, &state.rc4.y, (unsigned char)c);
524         }
525         break;
526     case cryptAES:
527         if (state.aes.bufIdx == 16) {
528             if (aesReadBlock(str, in, false)) {
529                 aesDecryptBlock(&state.aes, in, str->lookChar() == EOF);
530             }
531         }
532         if (state.aes.bufIdx == 16) {
533             c = EOF;
534         } else {
535             c = state.aes.buf[state.aes.bufIdx++];
536         }
537         break;
538     case cryptAES256:
539         if (state.aes256.bufIdx == 16) {
540             if (aesReadBlock(str, in, false)) {
541                 aes256DecryptBlock(&state.aes256, in, str->lookChar() == EOF);
542             }
543         }
544         if (state.aes256.bufIdx == 16) {
545             c = EOF;
546         } else {
547             c = state.aes256.buf[state.aes256.bufIdx++];
548         }
549         break;
550     case cryptNone:
551         break;
552     }
553     return (nextCharBuff = c);
554 }
555 
556 //------------------------------------------------------------------------
557 // RC4-compatible decryption
558 //------------------------------------------------------------------------
559 
rc4InitKey(const unsigned char * key,int keyLen,unsigned char * state)560 static void rc4InitKey(const unsigned char *key, int keyLen, unsigned char *state)
561 {
562     unsigned char index1, index2;
563     unsigned char t;
564     int i;
565 
566     for (i = 0; i < 256; ++i)
567         state[i] = i;
568 
569     if (unlikely(keyLen == 0))
570         return;
571 
572     index1 = index2 = 0;
573     for (i = 0; i < 256; ++i) {
574         index2 = (key[index1] + state[i] + index2) % 256;
575         t = state[i];
576         state[i] = state[index2];
577         state[index2] = t;
578         index1 = (index1 + 1) % keyLen;
579     }
580 }
581 
rc4DecryptByte(unsigned char * state,unsigned char * x,unsigned char * y,unsigned char c)582 static unsigned char rc4DecryptByte(unsigned char *state, unsigned char *x, unsigned char *y, unsigned char c)
583 {
584     unsigned char x1, y1, tx, ty;
585 
586     x1 = *x = (*x + 1) % 256;
587     y1 = *y = (state[*x] + *y) % 256;
588     tx = state[x1];
589     ty = state[y1];
590     state[x1] = ty;
591     state[y1] = tx;
592     return c ^ state[(tx + ty) % 256];
593 }
594 
595 //------------------------------------------------------------------------
596 // AES decryption
597 //------------------------------------------------------------------------
598 
599 // Returns false if EOF was reached, true otherwise
aesReadBlock(Stream * str,unsigned char * in,bool addPadding)600 static bool aesReadBlock(Stream *str, unsigned char *in, bool addPadding)
601 {
602     int c, i;
603 
604     for (i = 0; i < 16; ++i) {
605         if ((c = str->getChar()) != EOF) {
606             in[i] = (unsigned char)c;
607         } else {
608             break;
609         }
610     }
611 
612     if (i == 16) {
613         return true;
614     } else {
615         if (addPadding) {
616             c = 16 - i;
617             while (i < 16) {
618                 in[i++] = (unsigned char)c;
619             }
620         }
621         return false;
622     }
623 }
624 
625 static const unsigned char sbox[256] = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
626                                          0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
627                                          0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
628                                          0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
629                                          0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
630                                          0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
631                                          0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
632                                          0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };
633 
634 static const unsigned char invSbox[256] = { 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
635                                             0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
636                                             0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
637                                             0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
638                                             0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
639                                             0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
640                                             0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
641                                             0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d };
642 
643 static const unsigned int rcon[11] = { 0x00000000, // unused
644                                        0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1b000000, 0x36000000 };
645 
subWord(unsigned int x)646 static inline unsigned int subWord(unsigned int x)
647 {
648     return (sbox[x >> 24] << 24) | (sbox[(x >> 16) & 0xff] << 16) | (sbox[(x >> 8) & 0xff] << 8) | sbox[x & 0xff];
649 }
650 
rotWord(unsigned int x)651 static inline unsigned int rotWord(unsigned int x)
652 {
653     return ((x << 8) & 0xffffffff) | (x >> 24);
654 }
655 
subBytes(unsigned char * state)656 static inline void subBytes(unsigned char *state)
657 {
658     int i;
659 
660     for (i = 0; i < 16; ++i) {
661         state[i] = sbox[state[i]];
662     }
663 }
664 
invSubBytes(unsigned char * state)665 static inline void invSubBytes(unsigned char *state)
666 {
667     int i;
668 
669     for (i = 0; i < 16; ++i) {
670         state[i] = invSbox[state[i]];
671     }
672 }
673 
shiftRows(unsigned char * state)674 static inline void shiftRows(unsigned char *state)
675 {
676     unsigned char t;
677 
678     t = state[4];
679     state[4] = state[5];
680     state[5] = state[6];
681     state[6] = state[7];
682     state[7] = t;
683 
684     t = state[8];
685     state[8] = state[10];
686     state[10] = t;
687     t = state[9];
688     state[9] = state[11];
689     state[11] = t;
690 
691     t = state[15];
692     state[15] = state[14];
693     state[14] = state[13];
694     state[13] = state[12];
695     state[12] = t;
696 }
697 
invShiftRows(unsigned char * state)698 static inline void invShiftRows(unsigned char *state)
699 {
700     unsigned char t;
701 
702     t = state[7];
703     state[7] = state[6];
704     state[6] = state[5];
705     state[5] = state[4];
706     state[4] = t;
707 
708     t = state[8];
709     state[8] = state[10];
710     state[10] = t;
711     t = state[9];
712     state[9] = state[11];
713     state[11] = t;
714 
715     t = state[12];
716     state[12] = state[13];
717     state[13] = state[14];
718     state[14] = state[15];
719     state[15] = t;
720 }
721 
722 // {02} \cdot s
723 struct Mul02Table
724 {
Mul02TableMul02Table725     constexpr Mul02Table() : values()
726     {
727         for (int s = 0; s < 256; s++) {
728             values[s] = (s & 0x80) ? ((s << 1) ^ 0x1b) : (s << 1);
729         }
730     }
731 
operator ()Mul02Table732     constexpr unsigned char operator()(uint8_t i) const { return values[i]; }
733 
734     unsigned char values[256];
735 };
736 
737 static constexpr Mul02Table mul02;
738 
739 // {03} \cdot s
740 struct Mul03Table
741 {
Mul03TableMul03Table742     constexpr Mul03Table() : values()
743     {
744         for (int s = 0; s < 256; s++) {
745             const unsigned char s2 = (s & 0x80) ? ((s << 1) ^ 0x1b) : (s << 1);
746             values[s] = s ^ s2;
747         }
748     }
749 
operator ()Mul03Table750     constexpr unsigned char operator()(uint8_t i) const { return values[i]; }
751 
752     unsigned char values[256];
753 };
754 
755 static constexpr Mul03Table mul03;
756 
757 // {09} \cdot s
758 struct Mul09Table
759 {
Mul09TableMul09Table760     constexpr Mul09Table() : values()
761     {
762         for (int s = 0; s < 256; s++) {
763             const unsigned char s2 = (s & 0x80) ? ((s << 1) ^ 0x1b) : (s << 1);
764             const unsigned char s4 = (s2 & 0x80) ? ((s2 << 1) ^ 0x1b) : (s2 << 1);
765             const unsigned char s8 = (s4 & 0x80) ? ((s4 << 1) ^ 0x1b) : (s4 << 1);
766             values[s] = s ^ s8;
767         }
768     }
769 
operator ()Mul09Table770     constexpr unsigned char operator()(uint8_t i) const { return values[i]; }
771 
772     unsigned char values[256];
773 };
774 
775 static constexpr Mul09Table mul09;
776 
777 // {0b} \cdot s
778 struct Mul0bTable
779 {
Mul0bTableMul0bTable780     constexpr Mul0bTable() : values()
781     {
782         for (int s = 0; s < 256; s++) {
783             const unsigned char s2 = (s & 0x80) ? ((s << 1) ^ 0x1b) : (s << 1);
784             const unsigned char s4 = (s2 & 0x80) ? ((s2 << 1) ^ 0x1b) : (s2 << 1);
785             const unsigned char s8 = (s4 & 0x80) ? ((s4 << 1) ^ 0x1b) : (s4 << 1);
786             values[s] = s ^ s2 ^ s8;
787         }
788     }
789 
operator ()Mul0bTable790     constexpr unsigned char operator()(uint8_t i) const { return values[i]; }
791 
792     unsigned char values[256];
793 };
794 
795 static constexpr Mul0bTable mul0b;
796 
797 // {0d} \cdot s
798 struct Mul0dTable
799 {
Mul0dTableMul0dTable800     constexpr Mul0dTable() : values()
801     {
802         for (int s = 0; s < 256; s++) {
803             const unsigned char s2 = (s & 0x80) ? ((s << 1) ^ 0x1b) : (s << 1);
804             const unsigned char s4 = (s2 & 0x80) ? ((s2 << 1) ^ 0x1b) : (s2 << 1);
805             const unsigned char s8 = (s4 & 0x80) ? ((s4 << 1) ^ 0x1b) : (s4 << 1);
806             values[s] = s ^ s4 ^ s8;
807         }
808     }
809 
operator ()Mul0dTable810     constexpr unsigned char operator()(uint8_t i) const { return values[i]; }
811 
812     unsigned char values[256];
813 };
814 
815 static constexpr Mul0dTable mul0d;
816 
817 // {0e} \cdot s
818 struct Mul0eTable
819 {
Mul0eTableMul0eTable820     constexpr Mul0eTable() : values()
821     {
822         for (int s = 0; s < 256; s++) {
823             const unsigned char s2 = (s & 0x80) ? ((s << 1) ^ 0x1b) : (s << 1);
824             const unsigned char s4 = (s2 & 0x80) ? ((s2 << 1) ^ 0x1b) : (s2 << 1);
825             const unsigned char s8 = (s4 & 0x80) ? ((s4 << 1) ^ 0x1b) : (s4 << 1);
826             values[s] = s2 ^ s4 ^ s8;
827         }
828     }
829 
operator ()Mul0eTable830     constexpr unsigned char operator()(uint8_t i) const { return values[i]; }
831 
832     unsigned char values[256];
833 };
834 
835 static constexpr Mul0eTable mul0e;
836 
mixColumns(unsigned char * state)837 static inline void mixColumns(unsigned char *state)
838 {
839     int c;
840     unsigned char s0, s1, s2, s3;
841 
842     for (c = 0; c < 4; ++c) {
843         s0 = state[c];
844         s1 = state[4 + c];
845         s2 = state[8 + c];
846         s3 = state[12 + c];
847         state[c] = mul02(s0) ^ mul03(s1) ^ s2 ^ s3;
848         state[4 + c] = s0 ^ mul02(s1) ^ mul03(s2) ^ s3;
849         state[8 + c] = s0 ^ s1 ^ mul02(s2) ^ mul03(s3);
850         state[12 + c] = mul03(s0) ^ s1 ^ s2 ^ mul02(s3);
851     }
852 }
853 
invMixColumns(unsigned char * state)854 static inline void invMixColumns(unsigned char *state)
855 {
856     int c;
857     unsigned char s0, s1, s2, s3;
858 
859     for (c = 0; c < 4; ++c) {
860         s0 = state[c];
861         s1 = state[4 + c];
862         s2 = state[8 + c];
863         s3 = state[12 + c];
864         state[c] = mul0e(s0) ^ mul0b(s1) ^ mul0d(s2) ^ mul09(s3);
865         state[4 + c] = mul09(s0) ^ mul0e(s1) ^ mul0b(s2) ^ mul0d(s3);
866         state[8 + c] = mul0d(s0) ^ mul09(s1) ^ mul0e(s2) ^ mul0b(s3);
867         state[12 + c] = mul0b(s0) ^ mul0d(s1) ^ mul09(s2) ^ mul0e(s3);
868     }
869 }
870 
invMixColumnsW(unsigned int * w)871 static inline void invMixColumnsW(unsigned int *w)
872 {
873     int c;
874     unsigned char s0, s1, s2, s3;
875 
876     for (c = 0; c < 4; ++c) {
877         s0 = w[c] >> 24;
878         s1 = w[c] >> 16;
879         s2 = w[c] >> 8;
880         s3 = w[c];
881         w[c] = ((mul0e(s0) ^ mul0b(s1) ^ mul0d(s2) ^ mul09(s3)) << 24) | ((mul09(s0) ^ mul0e(s1) ^ mul0b(s2) ^ mul0d(s3)) << 16) | ((mul0d(s0) ^ mul09(s1) ^ mul0e(s2) ^ mul0b(s3)) << 8) | (mul0b(s0) ^ mul0d(s1) ^ mul09(s2) ^ mul0e(s3));
882     }
883 }
884 
addRoundKey(unsigned char * state,const unsigned int * w)885 static inline void addRoundKey(unsigned char *state, const unsigned int *w)
886 {
887     int c;
888 
889     for (c = 0; c < 4; ++c) {
890         state[c] ^= w[c] >> 24;
891         state[4 + c] ^= w[c] >> 16;
892         state[8 + c] ^= w[c] >> 8;
893         state[12 + c] ^= w[c];
894     }
895 }
896 
aesKeyExpansion(DecryptAESState * s,const unsigned char * objKey,int,bool decrypt)897 static void aesKeyExpansion(DecryptAESState *s, const unsigned char *objKey, int /*objKeyLen*/, bool decrypt)
898 {
899     unsigned int temp;
900     int i, round;
901 
902     //~ this assumes objKeyLen == 16
903 
904     for (i = 0; i < 4; ++i) {
905         s->w[i] = (objKey[4 * i] << 24) + (objKey[4 * i + 1] << 16) + (objKey[4 * i + 2] << 8) + objKey[4 * i + 3];
906     }
907     for (i = 4; i < 44; ++i) {
908         temp = s->w[i - 1];
909         if (!(i & 3)) {
910             temp = subWord(rotWord(temp)) ^ rcon[i / 4];
911         }
912         s->w[i] = s->w[i - 4] ^ temp;
913     }
914 
915     /* In case of decryption, adjust the key schedule for the equivalent inverse cipher */
916     if (decrypt) {
917         for (round = 1; round <= 9; ++round) {
918             invMixColumnsW(&s->w[round * 4]);
919         }
920     }
921 }
922 
aesEncryptBlock(DecryptAESState * s,const unsigned char * in)923 static void aesEncryptBlock(DecryptAESState *s, const unsigned char *in)
924 {
925     int c, round;
926 
927     // initial state (input is xor'd with previous output because of CBC)
928     for (c = 0; c < 4; ++c) {
929         s->state[c] = in[4 * c] ^ s->buf[4 * c];
930         s->state[4 + c] = in[4 * c + 1] ^ s->buf[4 * c + 1];
931         s->state[8 + c] = in[4 * c + 2] ^ s->buf[4 * c + 2];
932         s->state[12 + c] = in[4 * c + 3] ^ s->buf[4 * c + 3];
933     }
934 
935     // round 0
936     addRoundKey(s->state, &s->w[0]);
937 
938     // rounds 1-9
939     for (round = 1; round <= 9; ++round) {
940         subBytes(s->state);
941         shiftRows(s->state);
942         mixColumns(s->state);
943         addRoundKey(s->state, &s->w[round * 4]);
944     }
945 
946     // round 10
947     subBytes(s->state);
948     shiftRows(s->state);
949     addRoundKey(s->state, &s->w[10 * 4]);
950 
951     for (c = 0; c < 4; ++c) {
952         s->buf[4 * c] = s->state[c];
953         s->buf[4 * c + 1] = s->state[4 + c];
954         s->buf[4 * c + 2] = s->state[8 + c];
955         s->buf[4 * c + 3] = s->state[12 + c];
956     }
957 
958     s->bufIdx = 0;
959 }
960 
aesDecryptBlock(DecryptAESState * s,const unsigned char * in,bool last)961 static void aesDecryptBlock(DecryptAESState *s, const unsigned char *in, bool last)
962 {
963     int c, round, n, i;
964 
965     // initial state
966     for (c = 0; c < 4; ++c) {
967         s->state[c] = in[4 * c];
968         s->state[4 + c] = in[4 * c + 1];
969         s->state[8 + c] = in[4 * c + 2];
970         s->state[12 + c] = in[4 * c + 3];
971     }
972 
973     // round 0
974     addRoundKey(s->state, &s->w[10 * 4]);
975 
976     // rounds 1-9
977     for (round = 9; round >= 1; --round) {
978         invSubBytes(s->state);
979         invShiftRows(s->state);
980         invMixColumns(s->state);
981         addRoundKey(s->state, &s->w[round * 4]);
982     }
983 
984     // round 10
985     invSubBytes(s->state);
986     invShiftRows(s->state);
987     addRoundKey(s->state, &s->w[0]);
988 
989     // CBC
990     for (c = 0; c < 4; ++c) {
991         s->buf[4 * c] = s->state[c] ^ s->cbc[4 * c];
992         s->buf[4 * c + 1] = s->state[4 + c] ^ s->cbc[4 * c + 1];
993         s->buf[4 * c + 2] = s->state[8 + c] ^ s->cbc[4 * c + 2];
994         s->buf[4 * c + 3] = s->state[12 + c] ^ s->cbc[4 * c + 3];
995     }
996 
997     // save the input block for the next CBC
998     for (i = 0; i < 16; ++i) {
999         s->cbc[i] = in[i];
1000     }
1001 
1002     // remove padding
1003     s->bufIdx = 0;
1004     if (last) {
1005         n = s->buf[15];
1006         if (n < 1 || n > 16) { // this should never happen
1007             n = 16;
1008         }
1009         for (i = 15; i >= n; --i) {
1010             s->buf[i] = s->buf[i - n];
1011         }
1012         s->bufIdx = n;
1013     }
1014 }
1015 
1016 //------------------------------------------------------------------------
1017 // AES-256 decryption
1018 //------------------------------------------------------------------------
1019 
aes256KeyExpansion(DecryptAES256State * s,const unsigned char * objKey,int objKeyLen,bool decrypt)1020 static void aes256KeyExpansion(DecryptAES256State *s, const unsigned char *objKey, int objKeyLen, bool decrypt)
1021 {
1022     unsigned int temp;
1023     int i, round;
1024 
1025     //~ this assumes objKeyLen == 32
1026 
1027     for (i = 0; i < 8; ++i) {
1028         s->w[i] = (objKey[4 * i] << 24) + (objKey[4 * i + 1] << 16) + (objKey[4 * i + 2] << 8) + objKey[4 * i + 3];
1029     }
1030     for (i = 8; i < 60; ++i) {
1031         temp = s->w[i - 1];
1032         if ((i & 7) == 0) {
1033             temp = subWord(rotWord(temp)) ^ rcon[i / 8];
1034         } else if ((i & 7) == 4) {
1035             temp = subWord(temp);
1036         }
1037         s->w[i] = s->w[i - 8] ^ temp;
1038     }
1039 
1040     /* In case of decryption, adjust the key schedule for the equivalent inverse cipher */
1041     if (decrypt) {
1042         for (round = 1; round <= 13; ++round) {
1043             invMixColumnsW(&s->w[round * 4]);
1044         }
1045     }
1046 }
1047 
aes256EncryptBlock(DecryptAES256State * s,const unsigned char * in)1048 static void aes256EncryptBlock(DecryptAES256State *s, const unsigned char *in)
1049 {
1050     int c, round;
1051 
1052     // initial state (input is xor'd with previous output because of CBC)
1053     for (c = 0; c < 4; ++c) {
1054         s->state[c] = in[4 * c] ^ s->buf[4 * c];
1055         s->state[4 + c] = in[4 * c + 1] ^ s->buf[4 * c + 1];
1056         s->state[8 + c] = in[4 * c + 2] ^ s->buf[4 * c + 2];
1057         s->state[12 + c] = in[4 * c + 3] ^ s->buf[4 * c + 3];
1058     }
1059 
1060     // round 0
1061     addRoundKey(s->state, &s->w[0]);
1062 
1063     // rounds 1-13
1064     for (round = 1; round <= 13; ++round) {
1065         subBytes(s->state);
1066         shiftRows(s->state);
1067         mixColumns(s->state);
1068         addRoundKey(s->state, &s->w[round * 4]);
1069     }
1070 
1071     // round 14
1072     subBytes(s->state);
1073     shiftRows(s->state);
1074     addRoundKey(s->state, &s->w[14 * 4]);
1075 
1076     for (c = 0; c < 4; ++c) {
1077         s->buf[4 * c] = s->state[c];
1078         s->buf[4 * c + 1] = s->state[4 + c];
1079         s->buf[4 * c + 2] = s->state[8 + c];
1080         s->buf[4 * c + 3] = s->state[12 + c];
1081     }
1082 
1083     s->bufIdx = 0;
1084 }
1085 
aes256DecryptBlock(DecryptAES256State * s,const unsigned char * in,bool last)1086 static void aes256DecryptBlock(DecryptAES256State *s, const unsigned char *in, bool last)
1087 {
1088     int c, round, n, i;
1089 
1090     // initial state
1091     for (c = 0; c < 4; ++c) {
1092         s->state[c] = in[4 * c];
1093         s->state[4 + c] = in[4 * c + 1];
1094         s->state[8 + c] = in[4 * c + 2];
1095         s->state[12 + c] = in[4 * c + 3];
1096     }
1097 
1098     // round 0
1099     addRoundKey(s->state, &s->w[14 * 4]);
1100 
1101     // rounds 13-1
1102     for (round = 13; round >= 1; --round) {
1103         invSubBytes(s->state);
1104         invShiftRows(s->state);
1105         invMixColumns(s->state);
1106         addRoundKey(s->state, &s->w[round * 4]);
1107     }
1108 
1109     // round 14
1110     invSubBytes(s->state);
1111     invShiftRows(s->state);
1112     addRoundKey(s->state, &s->w[0]);
1113 
1114     // CBC
1115     for (c = 0; c < 4; ++c) {
1116         s->buf[4 * c] = s->state[c] ^ s->cbc[4 * c];
1117         s->buf[4 * c + 1] = s->state[4 + c] ^ s->cbc[4 * c + 1];
1118         s->buf[4 * c + 2] = s->state[8 + c] ^ s->cbc[4 * c + 2];
1119         s->buf[4 * c + 3] = s->state[12 + c] ^ s->cbc[4 * c + 3];
1120     }
1121 
1122     // save the input block for the next CBC
1123     for (i = 0; i < 16; ++i) {
1124         s->cbc[i] = in[i];
1125     }
1126 
1127     // remove padding
1128     s->bufIdx = 0;
1129     if (last) {
1130         n = s->buf[15];
1131         if (n < 1 || n > 16) { // this should never happen
1132             n = 16;
1133         }
1134         for (i = 15; i >= n; --i) {
1135             s->buf[i] = s->buf[i - n];
1136         }
1137         s->bufIdx = n;
1138         if (n > 16) {
1139             error(errSyntaxError, -1, "Reducing bufIdx from {0:d} to 16 to not crash", n);
1140             s->bufIdx = 16;
1141         }
1142     }
1143 }
1144 
1145 //------------------------------------------------------------------------
1146 // MD5 message digest
1147 //------------------------------------------------------------------------
1148 
1149 // this works around a bug in older Sun compilers
rotateLeft(unsigned long x,int r)1150 static inline unsigned long rotateLeft(unsigned long x, int r)
1151 {
1152     x &= 0xffffffff;
1153     return ((x << r) | (x >> (32 - r))) & 0xffffffff;
1154 }
1155 
md5Round1(unsigned long a,unsigned long b,unsigned long c,unsigned long d,unsigned long Xk,unsigned long s,unsigned long Ti)1156 static inline unsigned long md5Round1(unsigned long a, unsigned long b, unsigned long c, unsigned long d, unsigned long Xk, unsigned long s, unsigned long Ti)
1157 {
1158     return b + rotateLeft((a + ((b & c) | (~b & d)) + Xk + Ti), s);
1159 }
1160 
md5Round2(unsigned long a,unsigned long b,unsigned long c,unsigned long d,unsigned long Xk,unsigned long s,unsigned long Ti)1161 static inline unsigned long md5Round2(unsigned long a, unsigned long b, unsigned long c, unsigned long d, unsigned long Xk, unsigned long s, unsigned long Ti)
1162 {
1163     return b + rotateLeft((a + ((b & d) | (c & ~d)) + Xk + Ti), s);
1164 }
1165 
md5Round3(unsigned long a,unsigned long b,unsigned long c,unsigned long d,unsigned long Xk,unsigned long s,unsigned long Ti)1166 static inline unsigned long md5Round3(unsigned long a, unsigned long b, unsigned long c, unsigned long d, unsigned long Xk, unsigned long s, unsigned long Ti)
1167 {
1168     return b + rotateLeft((a + (b ^ c ^ d) + Xk + Ti), s);
1169 }
1170 
md5Round4(unsigned long a,unsigned long b,unsigned long c,unsigned long d,unsigned long Xk,unsigned long s,unsigned long Ti)1171 static inline unsigned long md5Round4(unsigned long a, unsigned long b, unsigned long c, unsigned long d, unsigned long Xk, unsigned long s, unsigned long Ti)
1172 {
1173     return b + rotateLeft((a + (c ^ (b | ~d)) + Xk + Ti), s);
1174 }
1175 
1176 struct MD5State
1177 {
1178     unsigned long a, b, c, d;
1179     unsigned char buf[64];
1180     int bufLen;
1181     int msgLen;
1182     unsigned char digest[16];
1183 };
1184 
md5Start(MD5State * state)1185 static void md5Start(MD5State *state)
1186 {
1187     state->a = 0x67452301;
1188     state->b = 0xefcdab89;
1189     state->c = 0x98badcfe;
1190     state->d = 0x10325476;
1191     state->bufLen = 0;
1192     state->msgLen = 0;
1193 }
1194 
md5ProcessBlock(MD5State * state)1195 static void md5ProcessBlock(MD5State *state)
1196 {
1197     unsigned long x[16];
1198 
1199     for (int i = 0; i < 16; ++i) {
1200         x[i] = state->buf[4 * i] | (state->buf[4 * i + 1] << 8) | (state->buf[4 * i + 2] << 16) | (state->buf[4 * i + 3] << 24);
1201     }
1202 
1203     unsigned long a = state->a;
1204     unsigned long b = state->b;
1205     unsigned long c = state->c;
1206     unsigned long d = state->d;
1207 
1208     // round 1
1209     a = md5Round1(a, b, c, d, x[0], 7, 0xd76aa478);
1210     d = md5Round1(d, a, b, c, x[1], 12, 0xe8c7b756);
1211     c = md5Round1(c, d, a, b, x[2], 17, 0x242070db);
1212     b = md5Round1(b, c, d, a, x[3], 22, 0xc1bdceee);
1213     a = md5Round1(a, b, c, d, x[4], 7, 0xf57c0faf);
1214     d = md5Round1(d, a, b, c, x[5], 12, 0x4787c62a);
1215     c = md5Round1(c, d, a, b, x[6], 17, 0xa8304613);
1216     b = md5Round1(b, c, d, a, x[7], 22, 0xfd469501);
1217     a = md5Round1(a, b, c, d, x[8], 7, 0x698098d8);
1218     d = md5Round1(d, a, b, c, x[9], 12, 0x8b44f7af);
1219     c = md5Round1(c, d, a, b, x[10], 17, 0xffff5bb1);
1220     b = md5Round1(b, c, d, a, x[11], 22, 0x895cd7be);
1221     a = md5Round1(a, b, c, d, x[12], 7, 0x6b901122);
1222     d = md5Round1(d, a, b, c, x[13], 12, 0xfd987193);
1223     c = md5Round1(c, d, a, b, x[14], 17, 0xa679438e);
1224     b = md5Round1(b, c, d, a, x[15], 22, 0x49b40821);
1225 
1226     // round 2
1227     a = md5Round2(a, b, c, d, x[1], 5, 0xf61e2562);
1228     d = md5Round2(d, a, b, c, x[6], 9, 0xc040b340);
1229     c = md5Round2(c, d, a, b, x[11], 14, 0x265e5a51);
1230     b = md5Round2(b, c, d, a, x[0], 20, 0xe9b6c7aa);
1231     a = md5Round2(a, b, c, d, x[5], 5, 0xd62f105d);
1232     d = md5Round2(d, a, b, c, x[10], 9, 0x02441453);
1233     c = md5Round2(c, d, a, b, x[15], 14, 0xd8a1e681);
1234     b = md5Round2(b, c, d, a, x[4], 20, 0xe7d3fbc8);
1235     a = md5Round2(a, b, c, d, x[9], 5, 0x21e1cde6);
1236     d = md5Round2(d, a, b, c, x[14], 9, 0xc33707d6);
1237     c = md5Round2(c, d, a, b, x[3], 14, 0xf4d50d87);
1238     b = md5Round2(b, c, d, a, x[8], 20, 0x455a14ed);
1239     a = md5Round2(a, b, c, d, x[13], 5, 0xa9e3e905);
1240     d = md5Round2(d, a, b, c, x[2], 9, 0xfcefa3f8);
1241     c = md5Round2(c, d, a, b, x[7], 14, 0x676f02d9);
1242     b = md5Round2(b, c, d, a, x[12], 20, 0x8d2a4c8a);
1243 
1244     // round 3
1245     a = md5Round3(a, b, c, d, x[5], 4, 0xfffa3942);
1246     d = md5Round3(d, a, b, c, x[8], 11, 0x8771f681);
1247     c = md5Round3(c, d, a, b, x[11], 16, 0x6d9d6122);
1248     b = md5Round3(b, c, d, a, x[14], 23, 0xfde5380c);
1249     a = md5Round3(a, b, c, d, x[1], 4, 0xa4beea44);
1250     d = md5Round3(d, a, b, c, x[4], 11, 0x4bdecfa9);
1251     c = md5Round3(c, d, a, b, x[7], 16, 0xf6bb4b60);
1252     b = md5Round3(b, c, d, a, x[10], 23, 0xbebfbc70);
1253     a = md5Round3(a, b, c, d, x[13], 4, 0x289b7ec6);
1254     d = md5Round3(d, a, b, c, x[0], 11, 0xeaa127fa);
1255     c = md5Round3(c, d, a, b, x[3], 16, 0xd4ef3085);
1256     b = md5Round3(b, c, d, a, x[6], 23, 0x04881d05);
1257     a = md5Round3(a, b, c, d, x[9], 4, 0xd9d4d039);
1258     d = md5Round3(d, a, b, c, x[12], 11, 0xe6db99e5);
1259     c = md5Round3(c, d, a, b, x[15], 16, 0x1fa27cf8);
1260     b = md5Round3(b, c, d, a, x[2], 23, 0xc4ac5665);
1261 
1262     // round 4
1263     a = md5Round4(a, b, c, d, x[0], 6, 0xf4292244);
1264     d = md5Round4(d, a, b, c, x[7], 10, 0x432aff97);
1265     c = md5Round4(c, d, a, b, x[14], 15, 0xab9423a7);
1266     b = md5Round4(b, c, d, a, x[5], 21, 0xfc93a039);
1267     a = md5Round4(a, b, c, d, x[12], 6, 0x655b59c3);
1268     d = md5Round4(d, a, b, c, x[3], 10, 0x8f0ccc92);
1269     c = md5Round4(c, d, a, b, x[10], 15, 0xffeff47d);
1270     b = md5Round4(b, c, d, a, x[1], 21, 0x85845dd1);
1271     a = md5Round4(a, b, c, d, x[8], 6, 0x6fa87e4f);
1272     d = md5Round4(d, a, b, c, x[15], 10, 0xfe2ce6e0);
1273     c = md5Round4(c, d, a, b, x[6], 15, 0xa3014314);
1274     b = md5Round4(b, c, d, a, x[13], 21, 0x4e0811a1);
1275     a = md5Round4(a, b, c, d, x[4], 6, 0xf7537e82);
1276     d = md5Round4(d, a, b, c, x[11], 10, 0xbd3af235);
1277     c = md5Round4(c, d, a, b, x[2], 15, 0x2ad7d2bb);
1278     b = md5Round4(b, c, d, a, x[9], 21, 0xeb86d391);
1279 
1280     // increment a, b, c, d
1281     state->a += a;
1282     state->b += b;
1283     state->c += c;
1284     state->d += d;
1285 
1286     state->bufLen = 0;
1287 }
1288 
md5Append(MD5State * state,const unsigned char * data,int dataLen)1289 static void md5Append(MD5State *state, const unsigned char *data, int dataLen)
1290 {
1291     const unsigned char *p = data;
1292     int remain = dataLen;
1293     while (state->bufLen + remain >= 64) {
1294         const int k = 64 - state->bufLen;
1295         memcpy(state->buf + state->bufLen, p, k);
1296         state->bufLen = 64;
1297         md5ProcessBlock(state);
1298         p += k;
1299         remain -= k;
1300     }
1301     if (remain > 0) {
1302         memcpy(state->buf + state->bufLen, p, remain);
1303         state->bufLen += remain;
1304     }
1305     state->msgLen += dataLen;
1306 }
1307 
md5Finish(MD5State * state)1308 static void md5Finish(MD5State *state)
1309 {
1310     // padding and length
1311     state->buf[state->bufLen++] = 0x80;
1312     if (state->bufLen > 56) {
1313         while (state->bufLen < 64) {
1314             state->buf[state->bufLen++] = 0x00;
1315         }
1316         md5ProcessBlock(state);
1317     }
1318     while (state->bufLen < 56) {
1319         state->buf[state->bufLen++] = 0x00;
1320     }
1321     state->buf[56] = (unsigned char)(state->msgLen << 3);
1322     state->buf[57] = (unsigned char)(state->msgLen >> 5);
1323     state->buf[58] = (unsigned char)(state->msgLen >> 13);
1324     state->buf[59] = (unsigned char)(state->msgLen >> 21);
1325     state->buf[60] = (unsigned char)(state->msgLen >> 29);
1326     state->buf[61] = (unsigned char)0;
1327     state->buf[62] = (unsigned char)0;
1328     state->buf[63] = (unsigned char)0;
1329     state->bufLen = 64;
1330     md5ProcessBlock(state);
1331 
1332     // break digest into bytes
1333     state->digest[0] = (unsigned char)state->a;
1334     state->digest[1] = (unsigned char)(state->a >> 8);
1335     state->digest[2] = (unsigned char)(state->a >> 16);
1336     state->digest[3] = (unsigned char)(state->a >> 24);
1337     state->digest[4] = (unsigned char)state->b;
1338     state->digest[5] = (unsigned char)(state->b >> 8);
1339     state->digest[6] = (unsigned char)(state->b >> 16);
1340     state->digest[7] = (unsigned char)(state->b >> 24);
1341     state->digest[8] = (unsigned char)state->c;
1342     state->digest[9] = (unsigned char)(state->c >> 8);
1343     state->digest[10] = (unsigned char)(state->c >> 16);
1344     state->digest[11] = (unsigned char)(state->c >> 24);
1345     state->digest[12] = (unsigned char)state->d;
1346     state->digest[13] = (unsigned char)(state->d >> 8);
1347     state->digest[14] = (unsigned char)(state->d >> 16);
1348     state->digest[15] = (unsigned char)(state->d >> 24);
1349 }
1350 
md5(const unsigned char * msg,int msgLen,unsigned char * digest)1351 void md5(const unsigned char *msg, int msgLen, unsigned char *digest)
1352 {
1353     if (msgLen < 0) {
1354         return;
1355     }
1356     MD5State state;
1357     md5Start(&state);
1358     md5Append(&state, msg, msgLen);
1359     md5Finish(&state);
1360     for (int i = 0; i < 16; ++i) {
1361         digest[i] = state.digest[i];
1362     }
1363 }
1364 
1365 //------------------------------------------------------------------------
1366 // SHA-256 hash
1367 //------------------------------------------------------------------------
1368 
1369 static const unsigned int sha256K[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
1370                                           0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
1371                                           0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
1372                                           0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 };
1373 
rotr(unsigned int x,unsigned int n)1374 static inline unsigned int rotr(unsigned int x, unsigned int n)
1375 {
1376     return (x >> n) | (x << (32 - n));
1377 }
1378 
sha256Ch(unsigned int x,unsigned int y,unsigned int z)1379 static inline unsigned int sha256Ch(unsigned int x, unsigned int y, unsigned int z)
1380 {
1381     return (x & y) ^ (~x & z);
1382 }
1383 
sha256Maj(unsigned int x,unsigned int y,unsigned int z)1384 static inline unsigned int sha256Maj(unsigned int x, unsigned int y, unsigned int z)
1385 {
1386     return (x & y) ^ (x & z) ^ (y & z);
1387 }
1388 
sha256Sigma0(unsigned int x)1389 static inline unsigned int sha256Sigma0(unsigned int x)
1390 {
1391     return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
1392 }
1393 
sha256Sigma1(unsigned int x)1394 static inline unsigned int sha256Sigma1(unsigned int x)
1395 {
1396     return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
1397 }
1398 
sha256sigma0(unsigned int x)1399 static inline unsigned int sha256sigma0(unsigned int x)
1400 {
1401     return rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3);
1402 }
1403 
sha256sigma1(unsigned int x)1404 static inline unsigned int sha256sigma1(unsigned int x)
1405 {
1406     return rotr(x, 17) ^ rotr(x, 19) ^ (x >> 10);
1407 }
1408 
sha256HashBlock(const unsigned char * blk,unsigned int * H)1409 static void sha256HashBlock(const unsigned char *blk, unsigned int *H)
1410 {
1411     unsigned int W[64];
1412     unsigned int a, b, c, d, e, f, g, h;
1413     unsigned int T1, T2;
1414     unsigned int t;
1415 
1416     // 1. prepare the message schedule
1417     for (t = 0; t < 16; ++t) {
1418         W[t] = (blk[t * 4] << 24) | (blk[t * 4 + 1] << 16) | (blk[t * 4 + 2] << 8) | blk[t * 4 + 3];
1419     }
1420     for (t = 16; t < 64; ++t) {
1421         W[t] = sha256sigma1(W[t - 2]) + W[t - 7] + sha256sigma0(W[t - 15]) + W[t - 16];
1422     }
1423 
1424     // 2. initialize the eight working variables
1425     a = H[0];
1426     b = H[1];
1427     c = H[2];
1428     d = H[3];
1429     e = H[4];
1430     f = H[5];
1431     g = H[6];
1432     h = H[7];
1433 
1434     // 3.
1435     for (t = 0; t < 64; ++t) {
1436         T1 = h + sha256Sigma1(e) + sha256Ch(e, f, g) + sha256K[t] + W[t];
1437         T2 = sha256Sigma0(a) + sha256Maj(a, b, c);
1438         h = g;
1439         g = f;
1440         f = e;
1441         e = d + T1;
1442         d = c;
1443         c = b;
1444         b = a;
1445         a = T1 + T2;
1446     }
1447 
1448     // 4. compute the intermediate hash value
1449     H[0] += a;
1450     H[1] += b;
1451     H[2] += c;
1452     H[3] += d;
1453     H[4] += e;
1454     H[5] += f;
1455     H[6] += g;
1456     H[7] += h;
1457 }
1458 
sha256(unsigned char * msg,int msgLen,unsigned char * hash)1459 static void sha256(unsigned char *msg, int msgLen, unsigned char *hash)
1460 {
1461     unsigned char blk[64];
1462     unsigned int H[8];
1463     int blkLen, i;
1464 
1465     H[0] = 0x6a09e667;
1466     H[1] = 0xbb67ae85;
1467     H[2] = 0x3c6ef372;
1468     H[3] = 0xa54ff53a;
1469     H[4] = 0x510e527f;
1470     H[5] = 0x9b05688c;
1471     H[6] = 0x1f83d9ab;
1472     H[7] = 0x5be0cd19;
1473 
1474     blkLen = 0;
1475     for (i = 0; i + 64 <= msgLen; i += 64) {
1476         sha256HashBlock(msg + i, H);
1477     }
1478     blkLen = msgLen - i;
1479     if (blkLen > 0) {
1480         memcpy(blk, msg + i, blkLen);
1481     }
1482 
1483     // pad the message
1484     blk[blkLen++] = 0x80;
1485     if (blkLen > 56) {
1486         while (blkLen < 64) {
1487             blk[blkLen++] = 0;
1488         }
1489         sha256HashBlock(blk, H);
1490         blkLen = 0;
1491     }
1492     while (blkLen < 56) {
1493         blk[blkLen++] = 0;
1494     }
1495     blk[56] = 0;
1496     blk[57] = 0;
1497     blk[58] = 0;
1498     blk[59] = 0;
1499     blk[60] = (unsigned char)(msgLen >> 21);
1500     blk[61] = (unsigned char)(msgLen >> 13);
1501     blk[62] = (unsigned char)(msgLen >> 5);
1502     blk[63] = (unsigned char)(msgLen << 3);
1503     sha256HashBlock(blk, H);
1504 
1505     // copy the output into the buffer (convert words to bytes)
1506     for (i = 0; i < 8; ++i) {
1507         hash[i * 4] = (unsigned char)(H[i] >> 24);
1508         hash[i * 4 + 1] = (unsigned char)(H[i] >> 16);
1509         hash[i * 4 + 2] = (unsigned char)(H[i] >> 8);
1510         hash[i * 4 + 3] = (unsigned char)H[i];
1511     }
1512 }
1513 //------------------------------------------------------------------------
1514 // SHA-512 hash (see FIPS 180-4)
1515 //------------------------------------------------------------------------
1516 // SHA 384 and SHA 512 use the same sequence of eighty constant 64 bit words.
1517 static const uint64_t shaK[80] = { 0x428a2f98d728ae22ull, 0x7137449123ef65cdull, 0xb5c0fbcfec4d3b2full, 0xe9b5dba58189dbbcull, 0x3956c25bf348b538ull, 0x59f111f1b605d019ull, 0x923f82a4af194f9bull, 0xab1c5ed5da6d8118ull,
1518                                    0xd807aa98a3030242ull, 0x12835b0145706fbeull, 0x243185be4ee4b28cull, 0x550c7dc3d5ffb4e2ull, 0x72be5d74f27b896full, 0x80deb1fe3b1696b1ull, 0x9bdc06a725c71235ull, 0xc19bf174cf692694ull,
1519                                    0xe49b69c19ef14ad2ull, 0xefbe4786384f25e3ull, 0x0fc19dc68b8cd5b5ull, 0x240ca1cc77ac9c65ull, 0x2de92c6f592b0275ull, 0x4a7484aa6ea6e483ull, 0x5cb0a9dcbd41fbd4ull, 0x76f988da831153b5ull,
1520                                    0x983e5152ee66dfabull, 0xa831c66d2db43210ull, 0xb00327c898fb213full, 0xbf597fc7beef0ee4ull, 0xc6e00bf33da88fc2ull, 0xd5a79147930aa725ull, 0x06ca6351e003826full, 0x142929670a0e6e70ull,
1521                                    0x27b70a8546d22ffcull, 0x2e1b21385c26c926ull, 0x4d2c6dfc5ac42aedull, 0x53380d139d95b3dfull, 0x650a73548baf63deull, 0x766a0abb3c77b2a8ull, 0x81c2c92e47edaee6ull, 0x92722c851482353bull,
1522                                    0xa2bfe8a14cf10364ull, 0xa81a664bbc423001ull, 0xc24b8b70d0f89791ull, 0xc76c51a30654be30ull, 0xd192e819d6ef5218ull, 0xd69906245565a910ull, 0xf40e35855771202aull, 0x106aa07032bbd1b8ull,
1523                                    0x19a4c116b8d2d0c8ull, 0x1e376c085141ab53ull, 0x2748774cdf8eeb99ull, 0x34b0bcb5e19b48a8ull, 0x391c0cb3c5c95a63ull, 0x4ed8aa4ae3418acbull, 0x5b9cca4f7763e373ull, 0x682e6ff3d6b2b8a3ull,
1524                                    0x748f82ee5defb2fcull, 0x78a5636f43172f60ull, 0x84c87814a1f0ab72ull, 0x8cc702081a6439ecull, 0x90befffa23631e28ull, 0xa4506cebde82bde9ull, 0xbef9a3f7b2c67915ull, 0xc67178f2e372532bull,
1525                                    0xca273eceea26619cull, 0xd186b8c721c0c207ull, 0xeada7dd6cde0eb1eull, 0xf57d4f7fee6ed178ull, 0x06f067aa72176fbaull, 0x0a637dc5a2c898a6ull, 0x113f9804bef90daeull, 0x1b710b35131c471bull,
1526                                    0x28db77f523047d84ull, 0x32caab7b40c72493ull, 0x3c9ebe0a15c9bebcull, 0x431d67c49c100d4cull, 0x4cc5d4becb3e42b6ull, 0x597f299cfc657e2aull, 0x5fcb6fab3ad6faecull, 0x6c44198c4a475817ull };
1527 
rotr(uint64_t x,uint64_t n)1528 static inline uint64_t rotr(uint64_t x, uint64_t n)
1529 {
1530     return (x >> n) | (x << (64 - n));
1531 }
sha512Ch(uint64_t x,uint64_t y,uint64_t z)1532 static inline uint64_t sha512Ch(uint64_t x, uint64_t y, uint64_t z)
1533 {
1534     return (x & y) ^ (~x & z);
1535 }
sha512Maj(uint64_t x,uint64_t y,uint64_t z)1536 static inline uint64_t sha512Maj(uint64_t x, uint64_t y, uint64_t z)
1537 {
1538     return (x & y) ^ (x & z) ^ (y & z);
1539 }
sha512Sigma0(uint64_t x)1540 static inline uint64_t sha512Sigma0(uint64_t x)
1541 {
1542     return rotr(x, 28) ^ rotr(x, 34) ^ rotr(x, 39);
1543 }
sha512Sigma1(uint64_t x)1544 static inline uint64_t sha512Sigma1(uint64_t x)
1545 {
1546     return rotr(x, 14) ^ rotr(x, 18) ^ rotr(x, 41);
1547 }
sha512sigma0(uint64_t x)1548 static inline uint64_t sha512sigma0(uint64_t x)
1549 {
1550     return rotr(x, 1) ^ rotr(x, 8) ^ (x >> 7);
1551 }
sha512sigma1(uint64_t x)1552 static inline uint64_t sha512sigma1(uint64_t x)
1553 {
1554     return rotr(x, 19) ^ rotr(x, 61) ^ (x >> 6);
1555 }
1556 
sha512HashBlock(const unsigned char * blk,uint64_t * H)1557 static void sha512HashBlock(const unsigned char *blk, uint64_t *H)
1558 {
1559     uint64_t W[80];
1560     uint64_t a, b, c, d, e, f, g, h;
1561     uint64_t T1, T2;
1562     unsigned int t;
1563 
1564     // 1. prepare the message schedule
1565     for (t = 0; t < 16; ++t) {
1566         W[t] = (((uint64_t)blk[t * 8] << 56) | ((uint64_t)blk[t * 8 + 1] << 48) | ((uint64_t)blk[t * 8 + 2] << 40) | ((uint64_t)blk[t * 8 + 3] << 32) | ((uint64_t)blk[t * 8 + 4] << 24) | ((uint64_t)blk[t * 8 + 5] << 16)
1567                 | ((uint64_t)blk[t * 8 + 6] << 8) | ((uint64_t)blk[t * 8 + 7]));
1568     }
1569     for (t = 16; t < 80; ++t) {
1570         W[t] = sha512sigma1(W[t - 2]) + W[t - 7] + sha512sigma0(W[t - 15]) + W[t - 16];
1571     }
1572 
1573     // 2. initialize the eight working variables
1574     a = H[0];
1575     b = H[1];
1576     c = H[2];
1577     d = H[3];
1578     e = H[4];
1579     f = H[5];
1580     g = H[6];
1581     h = H[7];
1582 
1583     // 3.
1584     for (t = 0; t < 80; ++t) {
1585         T1 = h + sha512Sigma1(e) + sha512Ch(e, f, g) + shaK[t] + W[t];
1586         T2 = sha512Sigma0(a) + sha512Maj(a, b, c);
1587         h = g;
1588         g = f;
1589         f = e;
1590         e = d + T1;
1591         d = c;
1592         c = b;
1593         b = a;
1594         a = T1 + T2;
1595     }
1596 
1597     // 4. compute the intermediate hash value
1598     H[0] += a;
1599     H[1] += b;
1600     H[2] += c;
1601     H[3] += d;
1602     H[4] += e;
1603     H[5] += f;
1604     H[6] += g;
1605     H[7] += h;
1606 }
1607 
sha512(unsigned char * msg,int msgLen,unsigned char * hash)1608 static void sha512(unsigned char *msg, int msgLen, unsigned char *hash)
1609 {
1610     unsigned char blk[128];
1611     uint64_t H[8];
1612     int blkLen = 0, i;
1613     // setting the initial hash value.
1614     H[0] = 0x6a09e667f3bcc908ull;
1615     H[1] = 0xbb67ae8584caa73bull;
1616     H[2] = 0x3c6ef372fe94f82bull;
1617     H[3] = 0xa54ff53a5f1d36f1ull;
1618     H[4] = 0x510e527fade682d1ull;
1619     H[5] = 0x9b05688c2b3e6c1full;
1620     H[6] = 0x1f83d9abfb41bd6bull;
1621     H[7] = 0x5be0cd19137e2179ull;
1622 
1623     for (i = 0; i + 128 <= msgLen; i += 128) {
1624         sha512HashBlock(msg + i, H);
1625     }
1626     blkLen = msgLen - i;
1627     if (blkLen > 0) {
1628         memcpy(blk, msg + i, blkLen);
1629     }
1630 
1631     // pad the message
1632     blk[blkLen++] = 0x80;
1633     if (blkLen > 112) {
1634         while (blkLen < 128) {
1635             blk[blkLen++] = 0;
1636         }
1637         sha512HashBlock(blk, H);
1638         blkLen = 0;
1639     }
1640     while (blkLen < 112) {
1641         blk[blkLen++] = 0;
1642     }
1643     blk[112] = 0;
1644     blk[113] = 0;
1645     blk[114] = 0;
1646     blk[115] = 0;
1647     blk[116] = 0;
1648     blk[117] = 0;
1649     blk[118] = 0;
1650     blk[119] = 0;
1651     blk[120] = 0;
1652     blk[121] = 0;
1653     blk[122] = 0;
1654     blk[123] = 0;
1655     blk[124] = (unsigned char)(msgLen >> 21);
1656     blk[125] = (unsigned char)(msgLen >> 13);
1657     blk[126] = (unsigned char)(msgLen >> 5);
1658     blk[127] = (unsigned char)(msgLen << 3);
1659 
1660     sha512HashBlock(blk, H);
1661 
1662     // copy the output into the buffer (convert words to bytes)
1663     for (i = 0; i < 8; ++i) {
1664         hash[i * 8] = (unsigned char)(H[i] >> 56);
1665         hash[i * 8 + 1] = (unsigned char)(H[i] >> 48);
1666         hash[i * 8 + 2] = (unsigned char)(H[i] >> 40);
1667         hash[i * 8 + 3] = (unsigned char)(H[i] >> 32);
1668         hash[i * 8 + 4] = (unsigned char)(H[i] >> 24);
1669         hash[i * 8 + 5] = (unsigned char)(H[i] >> 16);
1670         hash[i * 8 + 6] = (unsigned char)(H[i] >> 8);
1671         hash[i * 8 + 7] = (unsigned char)H[i];
1672     }
1673 }
1674 
1675 //------------------------------------------------------------------------
1676 // SHA-384 (see FIPS 180-4)
1677 //------------------------------------------------------------------------
1678 // The algorithm is defined in the exact same manner as SHA 512 with 2 exceptions
1679 // 1.Initial hash value is different.
1680 // 2.A 384 bit message digest is obtained by truncating the final hash value.
sha384(unsigned char * msg,int msgLen,unsigned char * hash)1681 static void sha384(unsigned char *msg, int msgLen, unsigned char *hash)
1682 {
1683     unsigned char blk[128];
1684     uint64_t H[8];
1685     int blkLen, i;
1686     // setting initial hash values
1687     H[0] = 0xcbbb9d5dc1059ed8ull;
1688     H[1] = 0x629a292a367cd507ull;
1689     H[2] = 0x9159015a3070dd17ull;
1690     H[3] = 0x152fecd8f70e5939ull;
1691     H[4] = 0x67332667ffc00b31ull;
1692     H[5] = 0x8eb44a8768581511ull;
1693     H[6] = 0xdb0c2e0d64f98fa7ull;
1694     H[7] = 0x47b5481dbefa4fa4ull;
1695     // SHA 384 will use the same sha512HashBlock function.
1696     blkLen = 0;
1697     for (i = 0; i + 128 <= msgLen; i += 128) {
1698         sha512HashBlock(msg + i, H);
1699     }
1700     blkLen = msgLen - i;
1701     if (blkLen > 0) {
1702         memcpy(blk, msg + i, blkLen);
1703     }
1704 
1705     // pad the message
1706     blk[blkLen++] = 0x80;
1707     if (blkLen > 112) {
1708         while (blkLen < 128) {
1709             blk[blkLen++] = 0;
1710         }
1711         sha512HashBlock(blk, H);
1712         blkLen = 0;
1713     }
1714     while (blkLen < 112) {
1715         blk[blkLen++] = 0;
1716     }
1717     blk[112] = 0;
1718     blk[113] = 0;
1719     blk[114] = 0;
1720     blk[115] = 0;
1721     blk[116] = 0;
1722     blk[117] = 0;
1723     blk[118] = 0;
1724     blk[119] = 0;
1725     blk[120] = 0;
1726     blk[121] = 0;
1727     blk[122] = 0;
1728     blk[123] = 0;
1729     blk[124] = (unsigned char)(msgLen >> 21);
1730     blk[125] = (unsigned char)(msgLen >> 13);
1731     blk[126] = (unsigned char)(msgLen >> 5);
1732     blk[127] = (unsigned char)(msgLen << 3);
1733 
1734     sha512HashBlock(blk, H);
1735 
1736     // copy the output into the buffer (convert words to bytes)
1737     // hash is truncated to 384 bits.
1738     for (i = 0; i < 6; ++i) {
1739         hash[i * 8] = (unsigned char)(H[i] >> 56);
1740         hash[i * 8 + 1] = (unsigned char)(H[i] >> 48);
1741         hash[i * 8 + 2] = (unsigned char)(H[i] >> 40);
1742         hash[i * 8 + 3] = (unsigned char)(H[i] >> 32);
1743         hash[i * 8 + 4] = (unsigned char)(H[i] >> 24);
1744         hash[i * 8 + 5] = (unsigned char)(H[i] >> 16);
1745         hash[i * 8 + 6] = (unsigned char)(H[i] >> 8);
1746         hash[i * 8 + 7] = (unsigned char)H[i];
1747     }
1748 }
1749 
1750 //------------------------------------------------------------------------
1751 // Section 7.6.3.3 (Encryption Key algorithm) of ISO/DIS 32000-2
1752 // Algorithm 2.B:Computing a hash (for revision 6).
1753 //------------------------------------------------------------------------
revision6Hash(const GooString * inputPassword,unsigned char * K,const char * userKey)1754 static void revision6Hash(const GooString *inputPassword, unsigned char *K, const char *userKey)
1755 {
1756     unsigned char K1[64 * (127 + 64 + 48)];
1757     unsigned char E[64 * (127 + 64 + 48)];
1758     DecryptAESState state;
1759     unsigned char aesKey[16];
1760     unsigned char BE16byteNumber[16];
1761 
1762     int inputPasswordLength = inputPassword->getLength();
1763     int KLength = 32;
1764     const int userKeyLength = userKey ? 48 : 0;
1765     int sequenceLength;
1766     int totalLength;
1767     int rounds = 0;
1768 
1769     while (rounds < 64 || rounds < E[totalLength - 1] + 32) {
1770         sequenceLength = inputPasswordLength + KLength + userKeyLength;
1771         totalLength = 64 * sequenceLength;
1772         // a.make the string K1
1773         memcpy(K1, inputPassword->c_str(), inputPasswordLength);
1774         memcpy(K1 + inputPasswordLength, K, KLength);
1775         if (userKey) {
1776             memcpy(K1 + inputPasswordLength + KLength, userKey, userKeyLength);
1777         }
1778         for (int i = 1; i < 64; ++i) {
1779             memcpy(K1 + (i * sequenceLength), K1, sequenceLength);
1780         }
1781         // b.Encrypt K1
1782         memcpy(aesKey, K, 16);
1783         memcpy(state.cbc, K + 16, 16);
1784         memcpy(state.buf, state.cbc, 16); // Copy CBC IV to buf
1785         state.bufIdx = 0;
1786         state.paddingReached = false;
1787         aesKeyExpansion(&state, aesKey, 16, false);
1788 
1789         for (int i = 0; i < (4 * sequenceLength); i++) {
1790             aesEncryptBlock(&state, K1 + (16 * i));
1791             memcpy(E + (16 * i), state.buf, 16);
1792         }
1793         memcpy(BE16byteNumber, E, 16);
1794         // c.Taking the first 16 Bytes of E as unsigned big-endian integer,
1795         // compute the remainder,modulo 3.
1796         uint64_t N1 = 0, N2 = 0, N3 = 0;
1797         // N1 contains first 8 bytes of BE16byteNumber
1798         N1 = ((uint64_t)BE16byteNumber[0] << 56 | (uint64_t)BE16byteNumber[1] << 48 | (uint64_t)BE16byteNumber[2] << 40 | (uint64_t)BE16byteNumber[3] << 32 | (uint64_t)BE16byteNumber[4] << 24 | (uint64_t)BE16byteNumber[5] << 16
1799               | (uint64_t)BE16byteNumber[6] << 8 | (uint64_t)BE16byteNumber[7]);
1800         uint64_t rem = N1 % 3;
1801         // N2 contains 0s in higher 4 bytes and 9th to 12 th bytes of BE16byteNumber in lower 4 bytes.
1802         N2 = ((uint64_t)BE16byteNumber[8] << 24 | (uint64_t)BE16byteNumber[9] << 16 | (uint64_t)BE16byteNumber[10] << 8 | (uint64_t)BE16byteNumber[11]);
1803         rem = ((rem << 32) | N2) % 3;
1804         // N3 contains 0s in higher 4 bytes and 13th to 16th bytes of BE16byteNumber in lower 4 bytes.
1805         N3 = ((uint64_t)BE16byteNumber[12] << 24 | (uint64_t)BE16byteNumber[13] << 16 | (uint64_t)BE16byteNumber[14] << 8 | (uint64_t)BE16byteNumber[15]);
1806         rem = ((rem << 32) | N3) % 3;
1807 
1808         // d.If remainder is 0 perform SHA-256
1809         if (rem == 0) {
1810             KLength = 32;
1811             sha256(E, totalLength, K);
1812         }
1813         // remainder is 1 perform SHA-384
1814         else if (rem == 1) {
1815             KLength = 48;
1816             sha384(E, totalLength, K);
1817         }
1818         // remainder is 2 perform SHA-512
1819         else if (rem == 2) {
1820             KLength = 64;
1821             sha512(E, totalLength, K);
1822         }
1823         rounds++;
1824     }
1825     // the first 32 bytes of the final K are the output of the function.
1826 }
1827