From b2d863c4147501294de4f7f3a8a74916ea4a1972 Mon Sep 17 00:00:00 2001
From: Donald Stufft <donald.stufft@gmail.com>
Date: Sat, 23 Feb 2013 04:15:57 -0500
Subject: [PATCH] Add nacl.random(N) to generate a random N bytes

---
 nacl/__init__.py     |  3 ++-
 nacl/nacl.py         | 10 ++++++++++
 nacl/random.py       |  7 +++++++
 tests/test_random.py |  9 +++++++++
 4 files changed, 28 insertions(+), 1 deletion(-)
 create mode 100644 nacl/random.py
 create mode 100644 tests/test_random.py

diff --git a/nacl/__init__.py b/nacl/__init__.py
index 53b5d256..70e7fe87 100644
--- a/nacl/__init__.py
+++ b/nacl/__init__.py
@@ -1,8 +1,9 @@
 from . import __about__
 from . import hash  # pylint: disable=W0622
+from .random import random
 
 
-__all__ = ["hash"] + __about__.__all__
+__all__ = ["hash", "random"] + __about__.__all__
 
 
 # - Meta Information -
diff --git a/nacl/nacl.py b/nacl/nacl.py
index 592b4173..0d84edae 100644
--- a/nacl/nacl.py
+++ b/nacl/nacl.py
@@ -23,6 +23,11 @@ ffi.cdef(
         int crypto_hash_sha256(unsigned char *out, const unsigned char *in, unsigned long long inlen);
         int crypto_hash_sha512(unsigned char *out, const unsigned char *in, unsigned long long inlen);
     """
+
+    # Secure Random
+    """
+        void randombytes(unsigned char * const buf, const unsigned long long buf_len);
+    """
 )
 
 
@@ -37,6 +42,11 @@ try:
             #include "crypto_hash.h"
             #include "crypto_hash_sha256.h"
             #include "crypto_hash_sha512.h"
+        """
+
+        # Secure Random
+        """
+            #include "randombytes.h"
         """,
         libraries=["nacl"],
     )
diff --git a/nacl/random.py b/nacl/random.py
new file mode 100644
index 00000000..18038a63
--- /dev/null
+++ b/nacl/random.py
@@ -0,0 +1,7 @@
+from . import nacl
+
+
+def random(size=32):
+    data = nacl.ffi.new("unsigned char[]", size)
+    nacl.lib.randombytes(data, size)
+    return nacl.ffi.string(data)
diff --git a/tests/test_random.py b/tests/test_random.py
new file mode 100644
index 00000000..6c43388f
--- /dev/null
+++ b/tests/test_random.py
@@ -0,0 +1,9 @@
+import nacl
+
+
+def test_random_bytes_produces():
+    assert len(nacl.random(16)) == 16
+
+
+def test_random_bytes_produces_different_bytes():
+    assert nacl.random(16) != nacl.random(16)
-- 
GitLab