From a86b6052f2600785ed19c446380a4c6b09780961 Mon Sep 17 00:00:00 2001 From: Michele Guerini Rocco Date: Wed, 11 Mar 2015 23:25:47 +0100 Subject: [PATCH] Improve RNG --- crypto/numbers.py | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/crypto/numbers.py b/crypto/numbers.py index eebe5fc..5c653b5 100644 --- a/crypto/numbers.py +++ b/crypto/numbers.py @@ -1,7 +1,9 @@ import math -import random -import itertools import pyaudio +from struct import unpack +from random import shuffle, sample + + opzioni = { "format": pyaudio.paFloat32, @@ -65,26 +67,35 @@ class primes: class generator: - def random(start, stop, n): + def _nums(l, n): """ - Returns n random integers in the range [start, end). + Split bytes l into n 32-bit unsigned int. + [Generator] + """ + for i in range(0, len(l), n): + chunk = l[i:i+n] + if any(chunk): # throw away initial zeros + yield unpack('>L', chunk)[0] + + def random(a, b, n): + """ + Returns n random 32-bit float in the range [a, b). [Generator] """ audio = pyaudio.PyAudio() - input = audio.open(**opzioni) - dati = input.read( + raw_data = audio.open(**opzioni).read( opzioni["rate"] // opzioni["frames_per_buffer"] * - int(math.log(n)) + 500) - input.close() + int(10*math.log(n))) audio.terminate() - dati = [i for i in dati if i != 0] - dati = [i for i in dati if i in range(start, stop)] - random.shuffle(dati) - for i in range(n): - yield dati[i] + + sequence = generator._nums(raw_data, 4) + sequence = sample(list(sequence), n) + m = max(sequence) + + return map(lambda x: a + (b-a) * (x/m), sequence) def onetimepad(l): """ Return an l-uple of random integers for a one-time-pad. """ - return tuple(generator.random(0, 2 * 16, l)) + return tuple(map(int, generator.random(0, 2*16, l)))