[PATCH 01/11] crypto: rng - Add crypto_stdrng_get_bytes()
From: Eric Biggers
Date: Wed Mar 25 2026 - 20:16:54 EST
All callers of crypto_get_default_rng() use the following sequence:
crypto_get_default_rng()
crypto_rng_get_bytes(crypto_default_rng, ...)
crypto_put_default_rng()
While it may have been intended that callers amortize the cost of
getting and putting the "default RNG" (i.e. "stdrng") over multiple
calls, in practice that optimization is never used. The callers just
want a function that gets random bytes from the "stdrng".
Therefore, add such a function: crypto_stdrng_get_bytes().
Importantly, this decouples the callers from the crypto_rng API. That
allows a later commit to make this function simply call
get_random_bytes_wait() unless the kernel is in "FIPS mode".
Signed-off-by: Eric Biggers <ebiggers@xxxxxxxxxx>
---
crypto/rng.c | 14 ++++++++++++++
include/crypto/rng.h | 13 +++++++++++++
2 files changed, 27 insertions(+)
diff --git a/crypto/rng.c b/crypto/rng.c
index c6165c8eb387..53a268ad5104 100644
--- a/crypto/rng.c
+++ b/crypto/rng.c
@@ -143,10 +143,24 @@ void crypto_put_default_rng(void)
crypto_default_rng_refcnt--;
mutex_unlock(&crypto_default_rng_lock);
}
EXPORT_SYMBOL_GPL(crypto_put_default_rng);
+int crypto_stdrng_get_bytes(void *buf, unsigned int len)
+{
+ int err;
+
+ err = crypto_get_default_rng();
+ if (err)
+ return err;
+
+ err = crypto_rng_get_bytes(crypto_default_rng, buf, len);
+ crypto_put_default_rng();
+ return err;
+}
+EXPORT_SYMBOL_GPL(crypto_stdrng_get_bytes);
+
#if defined(CONFIG_CRYPTO_RNG) || defined(CONFIG_CRYPTO_RNG_MODULE)
int crypto_del_default_rng(void)
{
int err = -EBUSY;
diff --git a/include/crypto/rng.h b/include/crypto/rng.h
index d451b54b322a..db6c3962a7df 100644
--- a/include/crypto/rng.h
+++ b/include/crypto/rng.h
@@ -60,10 +60,23 @@ struct crypto_rng {
extern struct crypto_rng *crypto_default_rng;
int crypto_get_default_rng(void);
void crypto_put_default_rng(void);
+/**
+ * crypto_stdrng_get_bytes() - get cryptographically secure random bytes
+ * @buf: output buffer holding the random numbers
+ * @len: length of the output buffer
+ *
+ * This function fills the caller-allocated buffer with random numbers using the
+ * highest-priority "stdrng" algorithm in the crypto_rng subsystem.
+ *
+ * Context: May sleep
+ * Return: 0 function was successful; < 0 if an error occurred
+ */
+int crypto_stdrng_get_bytes(void *buf, unsigned int len);
+
/**
* DOC: Random number generator API
*
* The random number generator API is used with the ciphers of type
* CRYPTO_ALG_TYPE_RNG (listed as type "rng" in /proc/crypto)
--
2.53.0