diff --git a/nacl/__init__.py b/nacl/__init__.py index 53b5d256072ee8a76dbc59890b8f625206c161cd..70e7fe8727d617fd7c7b1693f002f88602d69b95 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 592b41738b2bce0e76212923632f16b3b73ed614..0d84edaee3d2516d70383ace642438929ff59d31 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 0000000000000000000000000000000000000000..18038a6311ee8926c665bcb861ba51a4953131f7 --- /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 0000000000000000000000000000000000000000..6c43388f908ec7c76134e1b5419d9e756cfe398e --- /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)