Skip to content

Commit

Permalink
Small secure random changes
Browse files Browse the repository at this point in the history
  • Loading branch information
yoniko committed Jan 26, 2023
1 parent 06e208d commit ce9bc85
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/common/random.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
#ifndef ZSTD_RANDOM_H
#define ZSTD_RANDOM_H

#include "mem.h"

/*
* Portability helpers for secure random, exposes the following:
* - `HAS_SECURE_RANDOM` a macro that determines if secure random API is available on
Expand All @@ -24,10 +26,11 @@

#define HAS_SECURE_RANDOM
#include <sys/random.h>
static size_t getSecureRandom(void *buf, size_t buflen) {
MEM_STATIC size_t getSecureRandom(void *buf, size_t buflen) {
return getrandom(buf, buflen, GRND_NONBLOCK) != (ssize_t) buflen;
}


#endif


Expand Down
4 changes: 4 additions & 0 deletions lib/compress/zstd_compress.c
Original file line number Diff line number Diff line change
Expand Up @@ -1910,6 +1910,10 @@ ZSTD_reset_matchState(ZSTD_matchState_t* ms,
int needTagTableInit = 1;
#ifdef HAS_SECURE_RANDOM
if(forWho == ZSTD_resetTarget_CCtx) {
/* TODO: We might not need to generate secure random everytime. For example,
* we could generate 256 bit of secure random and roll it using a cryptographic
* hash function. This optimization could lend some performance wins for very
* small inputs. */
size_t randomGenerated = getSecureRandom(&ms->hashSalt, sizeof(ms->hashSalt));
if (!randomGenerated) {
/* We've successfully generated secure random, so we don't need to explicitly memset
Expand Down

0 comments on commit ce9bc85

Please sign in to comment.