How to generate a random 128 bit strings using Python?

You can generate random 128-bit strings using Python's random module. The getrandbits() function accepts the number of bits as an argument and returns a random integer with that many bits.

Using random.getrandbits()

The getrandbits() method generates a random integer with exactly 128 bits ?

import random

hash_value = random.getrandbits(128)
print(hex(hash_value))

The output of the above code is ?

0xa3fa6d97f4807e145b37451fc344e58c

Converting to Different Formats

You can format the 128-bit random number in various ways ?

import random

# Generate 128-bit random number
random_bits = random.getrandbits(128)

# Hexadecimal format (with 0x prefix)
print("Hex with prefix:", hex(random_bits))

# Hexadecimal format (without prefix)
print("Hex without prefix:", format(random_bits, 'x'))

# Binary format
print("Binary:", bin(random_bits))

# Decimal format
print("Decimal:", random_bits)

The output of the above code is ?

Hex with prefix: 0x8f14e45fceea167a5a36dedd4bea2543
Hex without prefix: 8f14e45fceea167a5a36dedd4bea2543
Binary: 0b10001111000101001110010001011111110011101110101000010110011110100101101000110110110111101101010010111110101000100101010000110011
Decimal: 190141183460469231731687303715884105539

Generating Multiple Random Strings

You can generate multiple 128-bit random strings using a loop ?

import random

print("Five random 128-bit strings:")
for i in range(5):
    random_string = random.getrandbits(128)
    print(f"String {i+1}: {hex(random_string)}")

The output of the above code is ?

Five random 128-bit strings:
String 1: 0x7f9a21263b6fc85c92c70e7f2a0b4e3d
String 2: 0x1c8e4d9b2a6f0c3e8d5a7f2b9e4c6a1d
String 3: 0x9e2a7c5f1b8d4e6a3c9f0e2b8d5a7c4f
String 4: 0x4b8c2e9a6d1f5c3a8e7b0d4f2a9c6e1b
String 5: 0x6f1d3b9c4e8a2f7d0c5b8e3a7f1c4b9d

Conclusion

Use random.getrandbits(128) to generate random 128-bit integers. Convert to hexadecimal using hex() for string representation. Each call produces a unique random value suitable for cryptographic applications.

Updated on: 2026-03-24T20:41:31+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements