Skip to content

Commit

Permalink
blake2: avoid writing to output buffer when using default digest length
Browse files Browse the repository at this point in the history
Signed-off-by: Antoine Salon <[email protected]>

Reviewed-by: Richard Levitte <[email protected]>
Reviewed-by: Matt Caswell <[email protected]>
(Merged from openssl#7726)
  • Loading branch information
Antoine Salon authored and mattcaswell committed Feb 6, 2019
1 parent b215db2 commit 8269e44
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
17 changes: 12 additions & 5 deletions crypto/blake2/blake2b.c
Original file line number Diff line number Diff line change
Expand Up @@ -304,19 +304,26 @@ int BLAKE2b_Update(BLAKE2B_CTX *c, const void *data, size_t datalen)
int BLAKE2b_Final(unsigned char *md, BLAKE2B_CTX *c)
{
uint8_t outbuffer[BLAKE2B_OUTBYTES] = {0};
uint8_t *target = outbuffer;
int iter = (c->outlen + 7) / 8;
int i;

/* Avoid writing to the temporary buffer if possible */
if ((c->outlen % sizeof(c->h[0])) == 0)
target = md;

blake2b_set_lastblock(c);
/* Padding */
memset(c->buf + c->buflen, 0, sizeof(c->buf) - c->buflen);
blake2b_compress(c, c->buf, c->buflen);

/* Output full hash to temp buffer */
for (i = 0; i < 8; ++i) {
store64(outbuffer + sizeof(c->h[i]) * i, c->h[i]);
}
/* Output full hash to buffer */
for (i = 0; i < iter; ++i)
store64(target + sizeof(c->h[i]) * i, c->h[i]);

if (target != md)
memcpy(md, target, c->outlen);

memcpy(md, outbuffer, c->outlen);
OPENSSL_cleanse(c, sizeof(BLAKE2B_CTX));
return 1;
}
17 changes: 12 additions & 5 deletions crypto/blake2/blake2s.c
Original file line number Diff line number Diff line change
Expand Up @@ -295,19 +295,26 @@ int BLAKE2s_Update(BLAKE2S_CTX *c, const void *data, size_t datalen)
int BLAKE2s_Final(unsigned char *md, BLAKE2S_CTX *c)
{
uint8_t outbuffer[BLAKE2S_OUTBYTES] = {0};
uint8_t *target = outbuffer;
int iter = (c->outlen + 3) / 4;
int i;

/* Avoid writing to the temporary buffer if possible */
if ((c->outlen % sizeof(c->h[0])) == 0)
target = md;

blake2s_set_lastblock(c);
/* Padding */
memset(c->buf + c->buflen, 0, sizeof(c->buf) - c->buflen);
blake2s_compress(c, c->buf, c->buflen);

/* Output full hash to temp buffer */
for (i = 0; i < 8; ++i) {
store32(outbuffer + sizeof(c->h[i]) * i, c->h[i]);
}
/* Output full hash to buffer */
for (i = 0; i < iter; ++i)
store32(target + sizeof(c->h[i]) * i, c->h[i]);

if (target != md)
memcpy(md, target, c->outlen);

memcpy(md, outbuffer, c->outlen);
OPENSSL_cleanse(c, sizeof(BLAKE2S_CTX));
return 1;
}

0 comments on commit 8269e44

Please sign in to comment.