-1

I try to use PyCryptodome for producing RSA key with a call to os.urandom to first get som random numbers. I must do some statistical testing and processing on the random data before i generate the RSA keys. I can use a file object to for loading the random numbers from file. I'm really scratching my head on this one..

fx = open("rnd.dat", "rb")
key = RSA.generate(1024, fx.read)

The code below works.

key = RSA.generate(1024, v1.readstd()) #Works! 

The code here doesn't .

key = RSA.generate(1024, v1.read())    #Not working....

I have included the source.

from Crypto.PublicKey import RSA # PyCryptodome
from Crypto import Random
import os

class trng:
   def __init__(self, rngval): 
      self.rngval = rngval 
   def read(self):
      return self.rngval 
   def readstd(self):
      return Random.get_random_bytes

rngbuff=os.urandom(1024)
#....Here will go some processing
#..
#....end
v1 = trng(rngbuff)

key1 = RSA.generate(1024, v1.readstd()) #Works! 

fx = open("rnd.dat", "rb")  
key2 = RSA.generate(1024, fx.read) #Works! 

key3 = RSA.generate(1024, v1.read())    #Not working....

1 Answers1

0

The problem in your code is that RSA.generate takes randfunc as a function object while in your code you call the function itself resulting in self.rngval to be passed to the function as a parameter which itself is the random bytes returned by os.urandom which doesn't have a read method so this will fail. so you need to call function as

key3 = RSA.generate(1024, v1.read)

As a side note I don't see how you can use this return value from os.urandom as the input to RSA.generate since RSA.generate randfunc is supposed to be used as a function that return a random number which is kept calling until it returns a prime random number. unless you make sure that this number (rngbuff) is a valid prime number of needed length.

KMG
  • 1,433
  • 1
  • 8
  • 19
  • I didn't understand that RSA.generate repeatably keeps calling until it finds a prime number. – Mats Stenfeldt Oct 03 '21 at 16:14
  • @MatsStenfeldt It does that since these prime numbers need to be generated randomly. But if you are sure that ```rngbuff``` is a prime number of ```size >= key bits``` I guess this can work although i didn't try that – KMG Oct 03 '21 at 18:36
  • Yes i'm sure of that. I'm reading from a binary file that is produced by a true random number generator and it is checked in accordance to FIPS 140-2 on-line tests. Monobit, Poker and Runs. – Mats Stenfeldt Oct 18 '21 at 18:28