473,800 Members | 2,518 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cryptographical ly random numbers

Okay, I'm working on devoloping a simple, cryptographical ly secure
number, from a range of numbers (As one might do for finding large
numbers, to test if they are prime). My function looks like this:

def cran_rand(min,m ax):
if(min>max):
x=max
max=min
min=x
range=round(log (max-min)/log(256))
if range==0:
range=1
num=max+1
while(num>max):
num=min+s2num(u random(range))
return num

Any comments on this? I think it should hold up to a test, it seems to
work alright. Thanks!

Mar 4 '06
24 1949
Wow, that would have been nice to know... Oh well, I've already got the
function, might as well use it... I'm starting to learn alot more of
the standard libraries that exist for alot of the little functions. It
seems like every project I have I build a misc.py file that contains
several small, but useful functions, and quite often I discover there
is a system library function to do just that. Oh well. Still, I've gone
a long ways in my Python skills since I started 6 months ago:-)

Mar 7 '06 #11
Tuvas wrote:
[...]
As to the s2num(text), well, that looks really neat. Is there an easy
way to do the reverse of that? Thanks!


Easy? Well, you be the judge:

def num2string(n):
""" Pass a non-negative int or long n.
Returns a string with bytes holding the big-endian base-256
representation of n. Zero is represented by the empty string.
"""
h = hex(n).lstrip(' 0x').rstrip('Ll ')
if len(h) % 2:
h = '0' + h
return unhexlify(h)

I did a little testing:

for i in xrange(300):
assert s2num(num2strin g(i)) == i
for i in xrange(1, 20):
for _ in xrange(100):
r = os.urandom(i)
assert num2string(s2nu m(r)) == r.lstrip(chr(0) )

--
--Bryan
Mar 7 '06 #12
Thanks for the function Paul, it works alot nicer than the one I had in
my program... Now, with all of this knowledge, I'm going to be brave
and try out everything with AES. It seems to be working alright, I'll
debug this more on my own than I did with my RSA code, which turned out
to be full of bugs... I know the program sends the blocks in the
reverse order that would be expected, but, well, I'll get there.
Cryptology is fun:-)

Mar 7 '06 #13
Bryan Olson wrote:
Tuvas wrote:
Ahh, you are correct, that is a large bug... How about this one?

Much better. Do note the comments from Emile van Sebille and Paul
Rubin. There are some minor style and efficiency points, but it
looks reasonable.

Incidentally, as of Python 2.4, the standard library offers
random.SystemRa ndom, which will generate integers in any desired
range using os.urandom as the entropy source.


How can I generate a random string containing digits, symbols and
letters? I will use this random string for the key of a cryptographic
algorithm.
Thanks

Mar 7 '06 #14
from os import urandom
def cstring(bytes):
ret=''
while(len(ret)< bytes):
c=os.urandom(1)
if c>'0' and c<'z':
ret=ret+c
return ret

That should do it, though I bet there might be a more efficient way. I
don't know if that's the set of characters you want to use, but... If
you want a better answer, you'd have to be more specific.

Mar 7 '06 #15
Gervasio Bernal <ge************ @speedy.com.ar> writes:
How can I generate a random string containing digits, symbols and
letters? I will use this random string for the key of a cryptographic
algorithm.


Generally if this is a string that some human user has to type in,
it's preferable to select some words randomly from a dictionary rather
than use an easily-garbled string of symbols. If the string will be
handled entirely by computers, just use a random string of bytes (like
os.urandom(20)) without worrying about whether they're printable
characters. If you really want a random-looking string of specific
characters, a simple way is:

usable_characte rs = string.letters + string.digits
...
# generate one character from the set (repeat as needed)
a,b = map(ord, os.urandom(2))
c = (a*256 + b) % len(usable_char acters)

Notice that the characters will have slightly unequal probability
(unless the usable character set's size is a power of 2), but the
effect on the output entry is insignificant.
Mar 7 '06 #16
Tuvas wrote:
from os import urandom
def cstring(bytes):
ret=''
while(len(ret)< bytes):
c=os.urandom(1)
if c>'0' and c<'z':
ret=ret+c
return ret

That should do it, though I bet there might be a more efficient way. I
don't know if that's the set of characters you want to use, but... If
you want a better answer, you'd have to be more specific.

Thanks a lot, that is what I need.
If someone else have a more efficient way I will appreciate.
Mar 7 '06 #17
I will admit though, I have the same question as Paul, why do you want
a random string of numbers, letters, and symbols? But, you asked for
it, so, that'll do.

Mar 7 '06 #18
"Tuvas" <tu*****@gmail. com> writes:
from os import urandom
def cstring(bytes):
ret=''
while(len(ret)< bytes):
c=os.urandom(1)
if c>'0' and c<'z':
ret=ret+c
return ret

That should do it, though I bet there might be a more efficient way.


One efficiency issue is that almost 90% of the os.urandom output gets
discarded. The other is more generic so I thought I'd mention it:

ret = ret + c

builds up a new string one character longer than the old value of ret,
then assigns ret to the new string. That is, the first time through
the loop (when ret is empty) it builds a 1-char string, the next time
it builds a 2-char string, etc. The total number of characters copied
around is approx 1+2+3+...+n where n is the final length, so it is
O(n**2). If n is very large (not the case for something like a password)
this gets expensive.

The usual Python idiom for building up a string in approx linear time
is:

def cstring(n):
ret = []
while (something):
ret.append(gene rate_another_ch aracter())
return ''.join(ret)

Python lists have a special efficiency hack so that ret.append doesn't
copy the whole list around, but rather, allocates space in bigger
chunks so that appending usually takes constant time. I don't think
this is part of the official specification but it's deeply ingrained
in Python culture and all kinds of Python code relies on it.

Another approach is to use Python's StringIO class (like Java
StringBuffer objects), but that's never been popular.
Mar 7 '06 #19
Paul Rubin wrote:
The usual Python idiom for building up a string in approx linear time
is:

def cstring(n):
ret = []
while (something):
ret.append(gene rate_another_ch aracter())
return ''.join(ret)

Python lists have a special efficiency hack so that ret.append doesn't
copy the whole list around, but rather, allocates space in bigger
chunks so that appending usually takes constant time.


in 2.4 and later, += on strings does the operation in place when
possible. this means that += is often faster than append/join.

</F>

Mar 7 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
11962
by: Nicholas Geraldi | last post by:
Im looking for a decent random number generator. Im looking to make a large number of random numbers (100 or so, if not more) in a short period of time (as fast as possible). the function i was using to get random numbers was Random rn = new Random(System.currentTimeMillis()); but it seems that the system doesn't update the milliseconds often enough to cause a true randomaziation (i ran just the System.currentTimeMillis() in a
21
3028
by: Marc Dansereau | last post by:
Hi all I am new to this forum and to the c programming language. If I understand, the random() function in C return numbers that follow a uniform distribution U(0,1). Can somebody know how to generate a set of random number that follow a normal distribution N(0,1) ? I am develloping on power4 machine running AIX. Thank you for your help
5
2401
by: cvnweb | last post by:
I am trying to generate 2 random numbers that are diffrent, in order to add them to existing numbers to generate numbers that start out the same, but are randomly added and subtracted so that they can go down similar paths, but not be the same. I will implement code later to make sure i they go more than 10 apart from each other that they are moved closer together, but this is what I have so far, and when the program is run, the two random...
104
5200
by: fieldfallow | last post by:
Hello all, Is there a function in the standard C library which returns a prime number which is also pseudo-random? Assuming there isn't, as it appears from the docs that I have, is there a better way than to fill an array of range 0... RAND_MAX with pre-computed primes and using the output of rand() to index into it to extract a random prime.
12
5231
by: Jim Michaels | last post by:
I need to generate 2 random numbers in rapid sequence from either PHP or mysql. I have not been able to do either. I get the same number back several times from PHP's mt_rand() and from mysql's RAND(). any ideas? I suppose I could use the current rancom number as the seed for the next random number. but would that really work?
21
13517
by: chico_yallin | last post by:
I just wana make a random id number based on4 digits-for examples?? Thanks in Advance Ch.Yallin
13
2817
by: Peter Oliphant | last post by:
I would like to be able to create a random number generator that produces evenly distributed random numbers up to given number. For example, I would like to pick a random number less than 100000, or between 0 and 99999 (inclusive). Further, the I want the range to be a variable. Concretely, I would like to create the following method: unsigned long Random( unsigned long num )
6
11753
by: badcrusher10 | last post by:
Hello. I'm having trouble figuring out what to do and how to do.. could someone explain to me what I need to do in order to work? THIS IS WHAT I NEED TO DO: Professor Snoop wants a program that will randomly generate 10 unique random numbers. Your job is to write a program that produces random permutations of the numbers 1 to 10. “Permutation” is a mathematical name for an arrangement. For example, there are six permutations of the...
24
7236
by: pereges | last post by:
I need to generate two uniform random numbers between 0 and 1 in C ? How to do it ? I looked into rand function where you need to #define RAND_MAX as 1 but will this rand function give me uniformly distributed and unique numbers ?
0
9690
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10273
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10250
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9085
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7574
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6811
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5469
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2944
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.