Skip to content

Commit b686f37

Browse files
authored
common/crypto_openssl: pad DH key buffers with leading zeros for smaller keys
Re: #493 Re: bk138/multivnc#202
1 parent 6408d56 commit b686f37

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

common/crypto_openssl.c

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,15 @@ int encrypt_aes128ecb(void *out, int *out_len, const unsigned char key[16], cons
156156
return result;
157157
}
158158

159+
static void pad_leading_zeros(uint8_t *out, const size_t current_len, const size_t expected_len) {
160+
if (current_len >= expected_len || expected_len < 1)
161+
return;
162+
163+
size_t diff = expected_len - current_len;
164+
memmove(out + diff, out, current_len);
165+
memset(out, 0, diff);
166+
}
167+
159168
int dh_generate_keypair(uint8_t *priv_out, uint8_t *pub_out, const uint8_t *gen, const size_t gen_len, const uint8_t *prime, const size_t keylen)
160169
{
161170
int result = 0;
@@ -184,6 +193,9 @@ int dh_generate_keypair(uint8_t *priv_out, uint8_t *pub_out, const uint8_t *gen,
184193
goto out;
185194
if(BN_bn2bin(dh->pub_key, pub_out) == 0)
186195
goto out;
196+
197+
pad_leading_zeros(priv_out, BN_num_bytes(dh->priv_key), keylen);
198+
pad_leading_zeros(pub_out, BN_num_bytes(dh->pub_key), keylen);
187199
#else
188200
DH_get0_key(dh, &pub_key, &priv_key);
189201
if(BN_bn2binpad(priv_key, priv_out, keylen) == -1)
@@ -216,9 +228,11 @@ int dh_compute_shared_key(uint8_t *shared_out, const uint8_t *priv, const uint8_
216228
if(!DH_set0_key(dh, NULL, BN_bin2bn(priv, keylen, NULL)))
217229
goto out;
218230
#endif
219-
if(DH_compute_key(shared_out, BN_bin2bn(pub, keylen, NULL), dh) == -1)
220-
goto out;
231+
int shared_len = DH_compute_key(shared_out, BN_bin2bn(pub, keylen, NULL), dh);
232+
if(shared_len == -1)
233+
goto out;
221234

235+
pad_leading_zeros(shared_out, shared_len, keylen);
222236
result = 1;
223237

224238
out:

0 commit comments

Comments
 (0)