Generate Nonce (Python)

Despite the more colloquial meaning that most are more familiar with, nonce is an important definition within computing, and particularly crypto

Literally N-once, a nonce is an arbitrary number intended to be used just once during a communication - it's often used as a sort of salt to ensure that replay attacks cannot simply use old communications, as well as for IVs etc when encryption

This short snippet will generate a nonce in both Python2 and Python3

Details

  • Language: Python

Snippet

import random

def generate_nonce(length=12):
    """Generate a pseudorandom number."""
    return ''.join([str(random.randint(0, 9)) for i in range(length)])

Usage Example

>>> print(generate_nonce(32))
77758613503377936448500832627705