1

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.

5
  • Check where is the set up for seeding. Make sure you seed the algorithm always differently Commented Dec 9, 2017 at 0:35
  • I hate to ask if it might just be a simple answer, but how would you go about doing that. That seems to be the problem I'm having, I've been searching through the documentation but can't find it. Commented Dec 9, 2017 at 0:45
  • Refer your documentation and check for function 'seed' or something similar to that. Usually pass current time to this function. Commented Dec 9, 2017 at 0:46
  • What specific module are you using? Can you provide a link to the documentation and post your code? Commented Dec 9, 2017 at 0:50
  • Im using the 'Cryptography' module. website is cryptography.io, my code is pretty much identical to the rsa generation example that they give Commented Dec 9, 2017 at 0:56

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

I copied and pasted exactly what you typed and I keep getting the same keys :/
Oh, im sorry, I was just not looking close enough, i just looked at the first few characters and didnt see it changes later on. Thanks!
Oh yeah, the .exportKey() makes it a little more cryptic and hard to read. But i came in handy for my program
I copied the exact code and I waited for like 5 minutes after running the program but there is not output on the terminal

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.