I am using the python Cryptography module and I have generated private and public keys using examples from the documentation. The problem I am having is that I want to be able to generate different key pairs. Like I generate one but it is always the same one being generated every time I run it. I've tried reading through the documentation as much as I cam but cannot find any kind of solution to this problem. Thanks.
I actually did that a while ago, so i'll just copy/paste my solution :)
import os
from Cryptodome.PublicKey import RSA
from Cryptodome import Random
def generate_keypair(bits=2048):
random_generator = Random.new().read
rsa_key = RSA.generate(bits, random_generator)
return rsa_key.exportKey(), rsa_key.publickey().exportKey()
To genarate a random key, you have to include a random generator in RSA.generate.
A little more human readable:
from Cryptodome.PublicKey import RSA
from Cryptodome import Random
def generate_keypair(bits=2048):
random_generator = Random.new().read
rsa_key = RSA.generate(bits, random_generator)
print(repr(rsa_key))
print(repr(rsa_key.publickey()))
generate_keypair()