I want to implement a CSPRNG for a stream cipher. I've tried implementing the BBS, but I've heard that it needs very big seeds to be secure.

Is there a function in some library for Python 3 that adds a pseudo-random number generator that is secure and gives same outputs for every seed?

  • However, you can implement a PRNG (or a stream cipher even more easily) using the secure hashes in hashlib. There are also plans to add a CSPRNG to the standard library in 3.6 IIRC.
    – otus
    Nov 26, 2015 at 19:46

3 Answers 3


What you are looking for is really a DRBG (deterministic random bit generator) rather than a CSPRNG, as the latter need not be reproducible or even carry observable state. DRBG's are defined to take a seed and return a stream of cryptographically secure bits based on that seed (that is, DRBG's are technically a subset of all CSPRNG's, but when people say CSPRNG they generally mean the "entropy pool" kind of nondeterministic designs).

There is nothing inside Python itself for this, as the only source of cryptographically secure bytes that Python provides is ultimately the OS's own nondeterministic generator which does not meet your needs.

You could use PyCrypto cryptographic primitives to implement a known good DRBG such as HMAC-DRBG. There is also this Github repo which implements HMAC-SHA512-DRBG with test vectors. There might also be Python bindings to crypto libraries like SSL which may provide a DRBG ready for use (though I don't know if OpenSSL's cryptographic layer provides such a thing).

  • HMAC is in the standard libraries, so no need to use PyCrypto.
    – otus
    Nov 26, 2015 at 19:51
  • @otus Good point, you can do it out of the box if you only need hash function or HMAC primitives for your construction. As soon as you need any kind of encryption scheme though you're out of luck!
    – Thomas
    Nov 27, 2015 at 4:09

I have a Python code implementing a PRBG based on RSA, available at http://s13.zetaboards.com/Crypto/topic/7234475/1/ Hope that it could be of some use to you in one sense or the other.


The best CSPRNG to implement a stream cipher is - wait for it - a stream cipher or block cipher in stream cipher mode such as AES in counter (CTR) mode. Such a thing is theoretically speaking a CS-PRNG.

Actual random number generator implementations may change in how they return bits / bytes, they may use a random seed or they may reseed. They have been designed to provide random output after all. So I'd not use those for where a stream cipher is perfectly fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.