Skip to content

Commit a080a53

Browse files
committed
wip: add HMAC to crypto.timingSafeEqual()
Refs: #38226
1 parent c7ccab3 commit a080a53

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/crypto/crypto_timing.cc

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
#include "node.h"
77

88
#include <openssl/crypto.h>
9+
#include <openssl/hmac.h>
10+
#include <openssl/sha.h>
911

1012
namespace node {
1113

@@ -42,8 +44,45 @@ void TimingSafeEqual(const FunctionCallbackInfo<Value>& args) {
4244
return;
4345
}
4446

47+
uint16_t bufKey[8];
48+
CHECK(crypto::EntropySource(reinterpret_cast<unsigned char*>(bufKey),
49+
sizeof(bufKey)));
50+
char key[kKeySize];
51+
snprintf(key, sizeof(key), "%04x%04x%04x%04x%04x%04x%04x%04x",
52+
bufKey[0],
53+
bufKey[1],
54+
bufKey[2],
55+
bufKey[3],
56+
bufKey[4],
57+
bufKey[5],
58+
bufKey[6],
59+
bufKey[7]);
60+
61+
std::array<unsigned char, EVP_MAX_MD_SIZE> hash1;
62+
std::array<unsigned char, EVP_MAX_MD_SIZE> hash2;
63+
unsigned int hash1Len;
64+
unsigned int hash2Len;
65+
66+
HMAC(EVP_sha256(),
67+
key,
68+
kKeySize,
69+
reinterpret_cast<unsigned char const*>(buf1.data()),
70+
static_cast<int>(buf1.size()),
71+
hash1.data(),
72+
&hash1Len);
73+
74+
HMAC(EVP_sha256(),
75+
key,
76+
kKeySize,
77+
reinterpret_cast<unsigned char const*>(buf2.data()),
78+
static_cast<int>(buf2.size()),
79+
hash2.data(),
80+
&hash2Len);
81+
82+
assert(hash1Len == hash2Len);
83+
4584
return args.GetReturnValue().Set(
46-
CRYPTO_memcmp(buf1.data(), buf2.data(), buf1.size()) == 0);
85+
CRYPTO_memcmp(hash1.data(), hash2.data(), hash1Len) == 0);
4786
}
4887

4988
void Initialize(Environment* env, Local<Object> target) {

src/crypto/crypto_timing.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ namespace crypto {
1111
namespace Timing {
1212
void Initialize(Environment* env, v8::Local<v8::Object> target);
1313

14+
static const int kKeySize = 256;
15+
1416
} // namespace Timing
1517
} // namespace crypto
1618
} // namespace node

0 commit comments

Comments
 (0)