MCPcopy Create free account
hub / github.com/abbeycode/UnrarKit / hmac_sha256

Function hmac_sha256

Libraries/unrar/crypt5.cpp:1–79  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1static void hmac_sha256(const byte *Key,size_t KeyLength,const byte *Data,
2 size_t DataLength,byte *ResDigest,
3 sha256_context *ICtxOpt,bool *SetIOpt,
4 sha256_context *RCtxOpt,bool *SetROpt)
5{
6 const size_t Sha256BlockSize=64; // As defined in RFC 4868.
7
8 byte KeyHash[SHA256_DIGEST_SIZE];
9 if (KeyLength > Sha256BlockSize) // Convert longer keys to key hash.
10 {
11 sha256_context KCtx;
12 sha256_init(&KCtx);
13 sha256_process(&KCtx, Key, KeyLength);
14 sha256_done(&KCtx, KeyHash);
15
16 Key = KeyHash;
17 KeyLength = SHA256_DIGEST_SIZE;
18 }
19
20 byte KeyBuf[Sha256BlockSize]; // Store the padded key here.
21 sha256_context ICtx;
22
23 if (ICtxOpt!=NULL && *SetIOpt)
24 ICtx=*ICtxOpt; // Use already calculated first block context.
25 else
26 {
27 // This calculation is the same for all iterations with same password.
28 // So for PBKDF2 we can calculate it only for first block and then reuse
29 // to improve performance.
30
31 for (size_t I = 0; I < KeyLength; I++) // Use 0x36 padding for inner digest.
32 KeyBuf[I] = Key[I] ^ 0x36;
33 for (size_t I = KeyLength; I < Sha256BlockSize; I++)
34 KeyBuf[I] = 0x36;
35
36 sha256_init(&ICtx);
37 sha256_process(&ICtx, KeyBuf, Sha256BlockSize); // Hash padded key.
38 }
39
40 if (ICtxOpt!=NULL && !*SetIOpt) // Store constant context for further reuse.
41 {
42 *ICtxOpt=ICtx;
43 *SetIOpt=true;
44 }
45
46 sha256_process(&ICtx, Data, DataLength); // Hash data.
47
48 byte IDig[SHA256_DIGEST_SIZE]; // Internal digest for padded key and data.
49 sha256_done(&ICtx, IDig);
50
51 sha256_context RCtx;
52
53 if (RCtxOpt!=NULL && *SetROpt)
54 RCtx=*RCtxOpt; // Use already calculated first block context.
55 else
56 {
57 // This calculation is the same for all iterations with same password.
58 // So for PBKDF2 we can calculate it only for first block and then reuse
59 // to improve performance.
60

Callers 2

pbkdf2Function · 0.85
ConvertHashToMACFunction · 0.85

Calls 3

sha256_initFunction · 0.85
sha256_processFunction · 0.85
sha256_doneFunction · 0.85

Tested by

no test coverage detected