473,383 Members | 1,877 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

Random passwords generation (Python vs Perl) =)

Perl:
@char=("A".."Z","a".."z",0..9);
do{print join("",@char[map{rand @char}(1..8)])}while(<>);

!!generate passwords untill U press ctrl-z

Python (from CookBook):

from random import choice
import string
print ''.join([choice(string.letters+string.digits) for i in
range(1,8)])

!!generate password once :(

who can write this smaller or without 'import'?

Jan 29 '07 #1
24 2700
NoName wrote:
from random import choice
import string
print ''.join([choice(string.letters+string.digits) for i in
range(1,8)])

!!generate password once :(
So add a while true: line.
who can write this smaller or without 'import'?
Why are those your goals?
Jan 29 '07 #2
"NoName" <za****@gmail.comwrites:
from random import choice
import string
print ''.join([choice(string.letters+string.digits) for i in
range(1,8)])

!!generate password once :(

who can write this smaller or without 'import'?
If you don't mind possibly getting a few nonalphanumeric characters:

import os,binascii
print binascii.b2a_base64(os.urandom(6))
Jan 29 '07 #3
On Jan 28, 10:58 pm, "NoName" <zaz...@gmail.comwrote:
Perl:
@char=("A".."Z","a".."z",0..9);
do{print join("",@char[map{rand @char}(1..8)])}while(<>);

!!generate passwords untill U press ctrl-z

Python (from CookBook):

from random import choice
import string
print ''.join([choice(string.letters+string.digits) for i in
range(1,8)])

!!generate password once :(

who can write this smaller or without 'import'?
from random import choice
pwdchars = ''.join(chr(c) for c in range(ord('a'),ord('z')+1)+
range(ord('A'),ord('Z')+1)+
range(ord('0'),ord('9')+1) )

while(True) : print ''.join(choice(pwdchars) for i in range(8))
(Note that you want to use range(8), not range(1,8), since range gives
you the values [a,b) if two arguments are given, or [0,a) if only one
is given, and it appears that you want 8-character passwords.)

But really, there's nothing wrong with using import, and reusing known
good code from the string module is better than reimplementing it in
new code as I have done (less code === fewer opportunities for bugs).
rand is not a built-in as it apparently is in Perl, but random is part
of the core library, so all Python installs will have it available -
likewise for string.

-- Paul

Jan 29 '07 #4
NoName wrote:
Perl:
@char=("A".."Z","a".."z",0..9);
do{print join("",@char[map{rand @char}(1..8)])}while(<>);

!!generate passwords untill U press ctrl-z

Python (from CookBook):

from random import choice
import string
print ''.join([choice(string.letters+string.digits) for i in
range(1,8)])

!!generate password once :(
Make a loop.
who can write this smaller
I won't write it for you, but I'll tell you how:

Write a function for the whole loop and the password generator and from
then on it will be a one-liner (as a function call).
or without 'import'?
Yes, make sure you do the import inside the function.

If you follow my advice, you will be able to get as many passwords as
you want with one line (and no spaces, even!):

generate_passwords()

It also reads much clearer than the perl version, don't you think?

By the way, you can also make a script. Call it "genpass", then at the
command prompt, it will be far less than one line:

% genpass

Or, if you are using DOS/Windows:

C:genpass

A lot of systems don't have a standard command called "g", so then you
can turn it into *ONE LETTER*!!! That beats the pants off perl!

% g

Or, of course, for DOS:

C:g

Good luck!

James
Jan 29 '07 #5
"Paul McGuire" <pt***@austin.rr.comwrites:
from random import choice
Security note: if you're trying to generate real passwords this way,
you're better off using os.urandom instead of the random module to
generate the random numbers. The random module's results are supposed
to be statistically uncorrelated (good for stuff like games and
simulations) but they don't try to resist guessing by malicious
attackers. os.urandom results are supposed to be unguessable.
Jan 29 '07 #6
Hmmm..
In the Perl example password generates after user hit ENTER not
continously like in Python you wrote... :)

i want see various ways to generate passwords even if they some
indirect like using BASE64

thanks all
p.s. sorry for my eng ;)

Jan 29 '07 #7
If you don't mind possibly getting a few nonalphanumeric characters:
>
import os,binascii
print binascii.b2a_base64(os.urandom(6))
what about

file('/dev/urandom').read(6).encode('base64')

(oneliner and without import sa op requested)

Jan 29 '07 #8
If you don't mind possibly getting a few nonalphanumeric characters:
>
import os,binascii
print binascii.b2a_base64(os.urandom(6))
what about

file('/dev/urandom').read(6).encode('base64')

(oneliner and without import as op requested)

Jan 29 '07 #9
"Szabolcs Nagy" <ns*******@gmail.comwrites:
file('/dev/urandom').read(6).encode('base64')
(oneliner and without import sa op requested)
Nice, though Un*x dependent (os.urandom is supposed to be portable).
Jan 29 '07 #10


On Jan 29, 4:08 pm, Paul Rubin <http://phr...@NOSPAM.invalidwrote:
"Szabolcs Nagy" <nszabo...@gmail.comwrites:
file('/dev/urandom').read(6).encode('base64')
(oneliner and without import sa op requested)Nice, though Un*x dependent (os.urandom is supposed to be portable).
Is os.urandom cryptographically strong on all platforms?

Jan 29 '07 #11
NoName írta:
Hmmm..
In the Perl example password generates after user hit ENTER not
continously like in Python you wrote... :)

i want see various ways to generate passwords even if they some
indirect like using BASE64
I copied this from a recipe, I do not remember which one. I like it very
much because it creates password that are easy to type in. You can type
every odd letter with your left hand and every even letter with your
right hand.

Best,

Leslie

from random import Random

PASSWORD_LENGTH = 10

rng = Random()

def generatePassword(length=PASSWORD_LENGTH,alternate_ hands=True):
righthand = '23456qwertasdfgzxcvbQWERTASDFGZXCVB'
lefthand = '789yuiophjknmYUIPHJKLNM'
allchars = righthand + lefthand
res = ""
for i in range(length):
if not alternate_hands:
res += rng.choice(allchars)
else:
if i%2:
res += rng.choice(lefthand)
else:
res += rng.choice(righthand)
return res
if __name__ == '__main__':
for i in range(10):
print generatePassword()
Jan 29 '07 #12
Is os.urandom cryptographically strong on all platforms?
http://docs.python.org/lib/os-miscfunc.html

"The returned data should be unpredictable enough for cryptographic
applications, though its exact quality depends on the OS
implementation."

Jan 29 '07 #13
NoName schrieb:
Perl:
@char=("A".."Z","a".."z",0..9);
do{print join("",@char[map{rand @char}(1..8)])}while(<>);

!!generate passwords untill U press ctrl-z

Python (from CookBook):

from random import choice
import string
print ''.join([choice(string.letters+string.digits) for i in
range(1,8)])

!!generate password once :(

who can write this smaller or without 'import'?
If you really want a hack, here it is:

while 1:print
''.join(__import__('random').choice(__import__('st ring').letters+'1234567890')
for x in xrange(8)),;n=raw_input()

This is a one-liner (though mail transmission may split it up), no
import statements. If someone can come up with an even smaller version,
feel free to post. :)

-- Stargaming
Jan 29 '07 #14
If you really want a hack, here it is:
>
while 1:print
''.join(__import__('random').choice(__import__('st ring').letters+'1234567890')
for x in xrange(8)),;n=raw_input()

This is a one-liner (though mail transmission may split it up), no
import statements. If someone can come up with an even smaller version,
feel free to post. :)
while
1:i=__import__;print''.join(i('random').choice(i(' string').letters
+'1234567890')for x in range(8)),;raw_input()

same but shorter:
i = __import__;
xrange -range (why use xrange? range is faster and simpler for small
ranges)
n =(not needed)

Jan 29 '07 #15
while
1:i=__import__;print''.join(i('random').choice(i(' string').letters
+'1234567890')for x in range(8)),;raw_input()
while
1:i=__import__;r='random';print''.join(i(r).choice (i('string').letters
+'1234567890')for x in`r`),;raw_input()

even shorter:
range -`'random'`

:)

Jan 29 '07 #16
Paul Rubin wrote:
"Szabolcs Nagy" <ns*******@gmail.comwrites:
>>file('/dev/urandom').read(6).encode('base64')
(oneliner and without import sa op requested)


Nice, though Un*x dependent (os.urandom is supposed to be portable).
Uh oh. I was looking at the Python "SSL" code recently, and
noted that OpenSSL initializes the keys with '/dev/urandom' if
available, and otherwise relies on the caller to seed it with
random data and to check that enough randomness has been input.

But the Python glue code for SSL doesn't seem to have the
machinery to seed SSL with randomness. I suspect that on
platforms without '/dev/urandom', Python's SSL package may
be using the same keys every time. This needs to be looked
at by a crypto expert.

John Nagle
Jan 29 '07 #17
WOW! :shock:

in this case:

while 1:i=__import__;print
i('binascii').b2a_base64(i('os').urandom(6)),;raw_ input()
On 30 ñÎ×., 04:06, "Szabolcs Nagy" <nszabo...@gmail.comwrote:
while
1:i=__import__;print''.join(i('random').choice(i(' string').letters
+'1234567890')for x in range(8)),;raw_input()while
1:i=__import__;r='random';print''.join(i(r).choice (i('string').letters
+'1234567890')for x in`r`),;raw_input()

even shorter:
range -`'random'`

:)
Jan 29 '07 #18
On Mon, 29 Jan 2007 16:24:18 +0100, Laszlo Nagy wrote:
NoName írta:
>Hmmm..
In the Perl example password generates after user hit ENTER not
continously like in Python you wrote... :)

i want see various ways to generate passwords even if they some
indirect like using BASE64
I copied this from a recipe, I do not remember which one. I like it very
much because it creates password that are easy to type in. You can type
every odd letter with your left hand and every even letter with your
right hand.
That weakens the password significantly. For a six character alpha-numeric
password with no special characters, you have (26*2+10)**6 possible
passwords, or 56,800,235,584.

Using your password generator, you have:
>>righthand = '23456qwertasdfgzxcvbQWERTASDFGZXCVB'
lefthand = '789yuiophjknmYUIPHJKLNM'
len(righthand)
35
>>len(lefthand)
23

and therefore only:

35*23*35*23*35*23 = (35*23)**3 = 521,660,125

possible passwords. That's about one percent of the earlier figure, so
you lose about 99% of the strength of the password. For eight character
passwords the difference is even more dramatic: you reduce the strength of
the password by a factor of roughly 99,999,995/100,000,000.

In my opinion, if you're going to accept such a drastic reduction in
password strength, better to go for a password that is easier to memorise
than a hard-to-memorise-but-easy-to-type weak password.

Here's one such algorithm:

* think of a meaningful phrase you won't forget: e.g. "Snow White and the
Seven Dwarves"

* take the first letter of each word: "swatsd"

* mix up the capitals and make it leet: "5Wat7D"

* add some special characters if you can: "5W&t7D"

* if it is not long enough, add a suffix or prefix or both: "p5W&t7D."

And now you have a strong password that you can remember but is unlikely
to be guessed.

--
Steven D'Aprano

Jan 30 '07 #19
On Mon, 29 Jan 2007 08:38:13 -0800, Szabolcs Nagy wrote:
>>why use xrange? range is faster and simpler for small ranges
That is not true.
>>import timeit
timeit.Timer("range(50)", "").repeat()
[2.8599629402160645, 2.8296849727630615, 2.8609859943389893]
>>timeit.Timer("xrange(50)", "").repeat()
[1.1806831359863281, 1.3563210964202881, 1.1632850170135498]
>>timeit.Timer("range(5)", "").repeat()
[1.7963159084320068, 1.5487189292907715, 1.5596699714660645]
>>timeit.Timer("xrange(5)", "").repeat()
[1.158560037612915, 1.1807279586791992, 1.1769890785217285]

There is very little reason to use range() unless you actually need the
entire list in one go. In fact, in Python 3.0, the existing range() will
be removed and xrange() will be renamed range().


--
Steven D'Aprano

Jan 30 '07 #20
En Mon, 29 Jan 2007 01:58:39 -0300, NoName <za****@gmail.comescribió:
Perl:
@char=("A".."Z","a".."z",0..9);
do{print join("",@char[map{rand @char}(1..8)])}while(<>);

!!generate passwords untill U press ctrl-z

Python (from CookBook):

from random import choice
import string
print ''.join([choice(string.letters+string.digits) for i in
range(1,8)])

!!generate password once :(

who can write this smaller or without 'import'?
Isn't it small enough? What's the point on being shorter?
I think you could avoid importing string (building the set of characters
like the Perl code) but anyway you will end importing random, or os.urandom
Do you want more than one password? Wrap the print inside a while True:
statement.
--
Gabriel Genellina

Jan 30 '07 #21
On Jan 30, 5:07 am, "NoName" <zaz...@gmail.comwrote:
WOW! :shock:

in this case:

while 1:i=__import__;print
i('binascii').b2a_base64(i('os').urandom(6)),;raw_ input()
:)
raw_input can do the job of print
while 1: raw_input(__import__('os').urandom(6).encode('base 64'))

And can anyone explain why this is so?
>>while 1: input(__import__('os').urandom(6).encode('base64') )
....
BgiWdv//

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 0

^
SyntaxError: unexpected EOF while parsing

Thank to all, I learned a lot of new things from this thread.

Hieu

Jan 31 '07 #22
En Wed, 31 Jan 2007 01:08:28 -0300, Hi**********@gmail.com
<Hi**********@gmail.comescribió:
raw_input can do the job of print
while 1: raw_input(__import__('os').urandom(6).encode('base 64'))

And can anyone explain why this is so?
>>>while 1: input(__import__('os').urandom(6).encode('base64') )
^
SyntaxError: unexpected EOF while parsing
input and raw_input are not the same, see the docs.

--
Gabriel Genellina

Jan 31 '07 #23
In <11**********************@v33g2000cwv.googlegroups .com>,
Hi**********@gmail.com wrote:
And can anyone explain why this is so?
>>>while 1: input(__import__('os').urandom(6).encode('base64') )
...
BgiWdv//

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 0

^
SyntaxError: unexpected EOF while parsing
It's `input()` that expects a valid Python expression. An empty one
doesn't work, it has to evaluate to something.

In [2]: input()

------------------------------------------------------------
File "<string>", line 0

^
SyntaxError: unexpected EOF while parsing

Ciao,
Marc 'BlackJack' Rintsch

Jan 31 '07 #24
NoName wrote:
Perl:
@char=("A".."Z","a".."z",0..9);
do{print join("",@char[map{rand @char}(1..8)])}while(<>);
If you generate passwords like that to normal computer
users, you'll end up with a lot of "my password doesn't
work" tickets. You should skip the symbols that are
easy to mistake for each other.

Skip at least Il1 and 0O. On the other hand, you could
probably use other characters besides letters and digits
to make the passwords stronger. Which ones to use is
unfortunately platform dependent.
Feb 1 '07 #25

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

Similar topics

1
by: Brandon Michael Moore | last post by:
I'm trying to test a web application using a tool written in python. I would like to be able to generate random values to put in fields. I would like to be able to generate random dates (in a...
14
by: Miranda | last post by:
Hi, I have a ASP/vbscript program that generates random passwords. The problem is I need to insert those passwords into an Access database of 327 clients. I have the random password program...
3
by: Mike Brown | last post by:
I have questions about thread safety in the 'random' module. When using the random.Random class (be it Mersenne Twister or Wichmann-Hill based), is it sufficiently thread-safe (preserving entropy...
15
by: Birahim FALL | last post by:
Hi, I'm very fresh to PostgreSQL, coming from Oracle. I want to developp web applications based on apache and postgresql. Is there an equivalent of OWA server (Oracle Web Application server) for...
2
by: Joe | last post by:
Hi, I am building web in ASP.NET using VB.NET to code the pages. I want to generate random passwords for users. I know that password hashing is built right into the .NET Framework. I was...
4
by: Dimos | last post by:
Hello All, I need some help with random number generation. What I need exactly is: To create a few thousand numbers, decimal and integers, between 5 and 90, and then to export them as a...
14
by: skulkrinbait | last post by:
I'm wanting to write a browser based wargame and am going to use PHP to it. The game requires a big map and I want to generate this randomly as it will be a lot of work to do it manually. My...
1
by: doll | last post by:
hi i'm working on a project where i need to generate random user id and passwords for the users..so please suggest me the coding for this in c#..please help with the code... thank you
31
by: eliben | last post by:
Hello, In a Python program I'm writing I need to dynamically generate functions and store them in a dict. eval() can't work for me because a function definition is a statement and not an...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.