1<html><head><meta http-equiv="Content-Type" content="text/html; charset=ANSI_X3.4-1968"><title>Code Example For Random Number Generator Usage</title><meta name="generator" content="DocBook XSL Stylesheets V1.78.1"><link rel="home" href="index.html" title="Linux Kernel Crypto API"><link rel="up" href="Code.html" title="Chapter&#160;6.&#160;Code Examples"><link rel="prev" href="ch06s03.html" title="Code Example For Use of Operational State Memory With SHASH"></head><body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">Code Example For Random Number Generator Usage</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="ch06s03.html">Prev</a>&#160;</td><th width="60%" align="center">Chapter&#160;6.&#160;Code Examples</th><td width="20%" align="right">&#160;</td></tr></table><hr></div><div class="sect1"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a name="idp1098432196"></a>Code Example For Random Number Generator Usage</h2></div></div></div><pre class="programlisting">
2
3static int get_random_numbers(u8 *buf, unsigned int len)
4{
5	struct crypto_rngrng = NULL;
6	chardrbg = "drbg_nopr_sha256"; /* Hash DRBG with SHA-256, no PR */
7	int ret;
8
9	if (!buf || !len) {
10		pr_debug("No output buffer provided\n");
11		return -EINVAL;
12	}
13
14	rng = crypto_alloc_rng(drbg, 0, 0);
15	if (IS_ERR(rng)) {
16		pr_debug("could not allocate RNG handle for %s\n", drbg);
17		return -PTR_ERR(rng);
18	}
19
20	ret = crypto_rng_get_bytes(rng, buf, len);
21	if (ret &lt; 0)
22		pr_debug("generation of random numbers failed\n");
23	else if (ret == 0)
24		pr_debug("RNG returned no data");
25	else
26		pr_debug("RNG returned %d bytes of data\n", ret);
27
28out:
29	crypto_free_rng(rng);
30	return ret;
31}
32    </pre></div><div class="navfooter"><hr><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="ch06s03.html">Prev</a>&#160;</td><td width="20%" align="center"><a accesskey="u" href="Code.html">Up</a></td><td width="40%" align="right">&#160;</td></tr><tr><td width="40%" align="left" valign="top">Code Example For Use of Operational State Memory With SHASH&#160;</td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top">&#160;</td></tr></table></div></body></html>
33