samedi 29 janvier 2022

How to generate a byte string consisting of random nonzero bytes using Python?

As part of implementing the PKCS #1 v1.5 padding scheme for RSA, I need to generate an octet string of length n consisting of pseudo-randomly generated nonzero octets. I'm looking for the best way to do this using Python.

This is what my current implementation looks like:

def nonzero_random_bytes(n: int) -> bytes:
    values = [x.to_bytes(1, "big") for x in range(1, 256)]
    seq = [secrets.choice(values) for _ in range(n)]
    return b"".join(seq)

I've looked at generating the byte string with secrets.token_bytes(n), filtering the result, and generating nonzero values to backfill the string. I know I can also do something secrets.token_bytes(2 * n), filter, and trim the result but that doesn't strike me as an elegant solution.

I've also looked into how PyCryptodome and python-pkcs1 do this but I'm thinking there must be a better way (I poked around pyca/cryptography but couldn't find how they did it).

Disclaimer: I am aware that I shouldn't use PKCS1 v1.5, much less be rolling out any cryptography code myself. This purely an academic exercise. :)




Aucun commentaire:

Enregistrer un commentaire