Is there any simpler way to make this password generator program? - python-2.x

# Password Generator Program
import random
print'''############################################################################
# PASSWORD GENEREATOR SYSTEM #
#############################################################################'''
print"Hey, I can generate strong passwords for you \nJust give me two inputs:"
a=input("Enter the length of password you want:\n")
b=input("How many passwords you want?\n")
li=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','W','X','Y','Z',1,2,3,4,5,6,7,8,9,0,'#','#','$','%','&',]
for i in range(1,a+1):
print "\n"
for j in range(1,b+1):
print random.choice(li),
I have defined a list and put all the uppercase, lowercase, 0 to 9, special characters in them. But this was very time consuming, so is there any other way to implement the same?

Related

ruby - How to decrypt MD5 digested 5 digit PIN in ruby?

So let's say I have a md5 hash of a five digits long PIN. It is given as string.
The only way is cracking it, means try every combination, hash it and compare it with the hash you want to crack. I'm trying to return the cracked PIN as string. Given the initial hash input is the md5 digest of the PIN (in a string). Here's my code:
require 'digest'
def crack_PIN(hash)
md5 = Digest::MD5.new
permutations = [0,1,2,3,4,5,6,7,8,9].permutation(5).to_a
perm_digest = permutations.map{|element| md5.hexdigest(element.map{|num| "#{num}"}.join)}
x = perm_digest.index(hash)
permutations[x].map{|num| "#{num}"}.join
end
The problem with this code is that it only uses each number once (it can't repeat each number as many times as it wants). I'm trying to figure out what I can do to alter this code that would make it work for any amount of repetition of each number. Thanks :-)
Minimal change:
permutations = '00000'..'99999'
That will get you the full list of all strings in the range. You can then just try running md5.hexdigest on each of them.
Also note: Your method is going to perform the exact same series of calculations every time you run it!! You would improve the performance by caching the calculated result somehow, (i.e. generating a lookup table of PIN --> md5 sum) and just referencing this in your code.
Combining Tom and Cary's suggestions into a simplified version that needs less memory than your example because it does not store all hashes in memory. Furthermore, it returns the PIN as soon as it was found and does not generate all hashes upfront.
require 'digest'
def crack_PIN(hash)
md5 = Digest::MD5.new
('00000'..'99999').find { |pin| md5.hexdigest(pin) == hash }
end
crack_PIN("c4ded2b85cc5be82fa1d2464eba9a7d3")
#=> "45678"

Ruby BCrypt salting/hashing seems ... wrong?

I've been creating salted passwords in a ruby app what I thought was the standard way:
password_salt = BCrypt::Engine.generate_salt
password_hash = BCrypt::Engine.hash_secret(params[:pword], password_salt)
But on examining a test case, it looks like the salt is just being prepended to the hashed password:
Now, as I understand the point of salt, it's supposed to be concatenated onto the password BEFORE hashing, to push the password out of the size range that any pre-computed lookup-table, rainbow-table, etc.. could ever include. The point is, if someone gets your user database, they still can't crack the passwords using a lookup table. If the salt is prepended onto the password AFTER the hashing, and the hacker has downloaded the user table, it's not doing anything to secure the passwords. The hacker can just clip the salt off the front, get the original hash back, and then run a rainbow table on the hashes as if they were never salted.
Is this as much of a salt-fail as it appears to be? Is the problem in my code? Or is this Working As Expected And Secure for reasons I need to read up on? (Link, please.)
1) Salt is necessary for verification, and thus must be stored alongside the hashed cyphertext. Whether it's two fields in a database or one smushed-together string, is immaterial.
2) One salt = one rainbow table. Sure, attacker could generate a new rainbow table for your salt; however, since time to build a rainbow table is basically equivalent to time to try all passwords the rainbow table is to cover, it is not a weakness as long as you don't reuse salts.
The use case for rainbow tables is it allows you to compute it once, then quickly test multiple passwords. A rainbow table typically covers all the passwords up to certain length, or at least with some restriction (e.g. with certain alphabet, or using a certain vocab list). Let's say you have a rainbow table that covers all the passwords up to 8 characters. So if someone has password "password", rainbow table will know what its hashed form would be (e.g. "WASSPORD" - using caps for cyphertext and lowercase for plaintext for readability of the example), and you can look up "WASSPORD" in the rainbow table and see the password is "password" extremely quickly.
However, say you have salt "peanuts". The password becomes "peanutspassword", and if you then encrypt it, lets say you get "WASSUPMYCRACKER". Ruby would print "peanutsWASSUPMYCRACKER" as the salted hash. At verification time, you separate "peanutsWASSUPMYCRACKER" into "peanuts" (salt) and "WASSUPMYCRACKER" (hash); append "peanuts" to the user's input of "password" to form "peanutspassword", and encrypt it again - you get "WASSUPMYCRACKER", which is a match, and the user is logged in. However, note that "peanutspassword" is longer than 8 characters, and will not be in the up-to-8-characters rainbow table.
Now, you can generate a "peanuts" rainbow table, by taking the same dictionary as the original rainbow table, prepending "peanuts", and encrypting it, but it would typically take longer than just brute-forcing the password ("peanuts"+"a"? "peanuts"+"aardvark"?...) because, at least when you brute-force, you would stop when you find the correct password.
However, if you knew that a certain application always used "peanuts" as its salt, you could make a "peanuts" rainbow table, and that application is toast, and its owners in a real jam.
tl;dr: Salt can be public; it just can't be reused.
EDIT: You seem to be under the impression that Ruby just pastes salt onto the hash of the unsalted plaintext. If it did that, then one would expect that for the same plaintext, the result's hind end (the cyphertext) would be the same, no matter the salt. It is easy to see that's not how it works:
3.times { puts BCrypt::Engine.hash_secret("password", BCrypt::Engine.generate_salt) }
# $2a$10$jxUToaac5UUzVRH9SnllKe52W1JMLu5tm0LwyrZ4x4e75O1FCn9Ea
# $2a$10$oBs3TyhgR/r12.cz2kdzh.O9WHVZifDPqTEg0.hGOMn7Befv.8hSy
# $2a$10$8rfQA5nzCZ74DwNrmhAhdOmoQOVhJnBfh0ikiOB0W7ZptwsLPGUwi
As the salt changes, the cyphertext also changes. Thus, you can't "just clip the salt off the front, get the original hash back, and then run a rainbow table on the hashes as if they were never salted."
I had the same Problem in Python:
passw = "qay123"
salt = bcrypt.gensalt(14)
hashedpw = bcrypt.hashpw(passw, salt)
print salt
print hashedpw
Output:
$2b$14$fG3IoYLeIaf6gxZTHVR7eO <--- salt
$2b$14$fG3IoYLeIaf6gxZTHVR7eOVOC08a77IDOiu4At4FKKecw1xBYKXyG <-- salt + hashedpw
So, the hashpw-function just concatenates the salt value with the hash value which is insecure, because the hacker can split salt+hashpw at position 30
and so eliminates the salt.
For rainbow-tables the hacker must be able to read the hashes, so the cutting isn't a problem. The only problem he could have, would be when the length of the salt would vary.
My thought is that you follow your own thought and use bscrypt as seemingly not intended.

Aix: How to generate valid sha1/sha256/sha512 password hash on AIX /etc/security/passwd?

AIX, like other Unix, only store a salted hash of user password.
In the old days, it uses to use DES crypt, and then a (slighty different version of) MD5 Crypt, the same that you will find on Linux.
With more recent version of AIX and the use of /etc/security/passwd, you can use new SHA1/SHA256/SHA512 hashes. They look like that (with example hash string result for the password "secret"):
- salted sha1 : {ssha1}12$tyiOfoE4WXucUfh/$1olYn48enIIKGOOs0ve/GE.k.sF
- salted ssha256: {ssha256}12$tyiOfoE4WXucUfh/$YDkcqbY5oKk4lwQ4pVKPy8o4MqcfVpp1ZxxvSfP0.wS
- salted ssha512: {ssha512}10$tyiOfoE4WXucUfh/$qaLbOhKx3fwIu93Hkh4Z89Vr.otLYEhRGN3b3SAZFD3mtxhqWZmY2iJKf0KB/5fuwlERv14pIN9h4XRAZtWH..
The config file /etc/security/pwdalg.cfg explain the the number after {algo_name} is the "num_cost", and we can get the number of iteration used in the hashing function with 2^num_cost.
I need to generate valid hash from a Scala application that are latter place in /etc/security/passwd.
I tried to adapt commons-codec Sha2Crypt (https://commons.apache.org/proper/commons-codec/apidocs/src-html/org/apache/commons/codec/digest/Sha2Crypt.html) witch implements the official Sha-Crypt algorithm (https://www.akkadia.org/drepper/SHA-crypt.txt), but that give the wrong hash.
Anybody knows what should be done ?
The short answer is that, appart for md5, which is the standard unix implementation and differs only for the prefix ({smd5} in place of "$1", the other implementations differ SIGNIFICANTLY from standard Unix crypt described at https://www.akkadia.org/drepper/SHA-crypt.txt. In fact, they only kept:
the number of bytes (and so chars) for the hash: 20 for ssha1, 32 for ssha256, 64 for ssh512
the base64 encoding table (which is not the standard one but starts with "./012" etc
What changed is:
they use PBKDF2 HMAC-(sha1, sha256, sha512) in place of Sha-Crypt,
they use a different padding table
the number of iterations, named "rounds" in Unix crypt vocabulary, is not the number N found at the begining of the hash string (after the algo name). The number of iteration is actually 2^N, and N is called in /etc/security/pwdalg.cfg the "cost"
A valid Scala implementation can be found in Rudder's AixPasswordHashAlgo.scala here: https://github.com/Normation/rudder/blob/master/webapp/sources/rudder/rudder-core/src/main/scala/com/normation/cfclerk/domain/AixPasswordHashAlgo.scala

Encrypt passwords in human-readable format

I'm looking for one or more encryption algorithms that can encrypt passwords in a way that the encrypted text must be readable by humans.
For example if I give as password:
StackOverflow
The algorithm should gives me:
G0aThiR4i s0ieFer
So I want to get an encrypted password easily readable by humans (not strange strings with special chars or thousand of characters).
There are algorithms that fit this need?
RFC 1751, which defines a "Convention for Human-Readable 128-bit Keys" – basically just a mapping of blocks of bits to strings of English words.
For example, the 128-bit key of:
CCAC 2AED 5910 56BE 4F90 FD44 1C53 4766
would become
RASH BUSH MILK LOOK BAD BRIM AVID GAFF BAIT ROT POD LOVE
Algorithm is used for fixed-length 128-bit keys, that's a base for data size. Source data can be truncated or expanded to match the base.
Spec & implementation in C # https://www.rfc-editor.org/rfc/rfc1751
It ain't well known. I couldn't find implementation mention apart from one in spec & references to lost python library.
Your question puzzled me in many ways, leading to the hare-brained idea of creating a completely human-readable paragraph from a base 16 hash result. What's more readable than English sentences?
To maintain the security of a hashed password, the algorithm is as follows:
Hash a user's password using any of the basic techniques.
Run the hash through my special HashViewer
Enjoy the Anglicized goodness.
For example, if this Base16 hash is the input:
c0143d440bd61b33a65bfa31ac35fe525f7b625f10cd53b7cac8824d02b61dfc
the output from HashViewer would be this:
Smogs enjoy dogs. Logs unearth backlogs. Logs devour frogs. Grogs decapitate clogs and dogs conceptualize fogs. Fogs greet clogs. Cogs conceptualize warthogs. Bogs unearth dogs despite bogs squeeze fogs. Cogs patronize catalogs. Cogs juggle cogs. Warthogs debilitate grogs; unfortunately, clogs juggle cogs. Warthogs detest frogs; conversely, smogs decapitate cogs. Fogs conceptualize balrogs. Smogs greet smogs whenever polywogs accost eggnogs. Logs decapitate frogs. Eggnogs conceptualize clogs. Dogs decapitate warthogs. (smogs )
(The last words in parenthesis were words that were left over)
In this glorious paragraph form, we can look at two separate hashes and easily compare them to see if they are different.
As an extra feature, there is a function to convert the English text back in to the hash string.
Enjoy!
Step 1) Apply regular encryption algorithm.
Step 2) Base 26-encode it using letters a thru z
Step 3) ???
Step 4) Profit!
Even cooler would be to get a letter-bigraph distribution for the english language. Pick a simple pseudo-random-number algorithm and seed it with the non-human-readable password hash. Then use the algorithm to make up a word according to how likely a letter is to follow the letter before it in the english language. You'll get really english-sounding words, and consistently from the same seed. The chance for collisions might be unseasonably high, though.
EncryptedPassword = Base64(SHA1(UTF8(Password) + Salt))
Password is string
Salt is cryptographically strong random byte[]
UTF8: string -> byte[]
SHA1: byte[] -> byte[]
Base64: byte[] -> string
EncryptedPassword is string
Store (EncryptedPassword, Salt).
Throw in whatever encryption algorithm you want instead of SHA1.
For example, if password is StackOverflow you get the encrypted password LlijGz/xNSRXQXtbgNs+UIdOCwU.

How do you generate passwords? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
How do you generate passwords?
Random Characters?
Passphrases?
High Ascii?
Something like this?
cat /dev/urandom | strings
Mac OS X's "Keychain Access" application gives you access to the nice OS X password generator. Hit command-N and click the key icon. You get to choose password style (memorable, numeric, alphanumeric, random, FIPS-181) and choose the length. It also warns you about weak passwords.
Use this & thumps up :)
cat /dev/urandom | tr -dc 'a-zA-Z0-9-!##$%^&*()_+~' | fold -w 10 | head -n 1
Change the head count to generate number of passwords.
A short python script to generate passwords, originally from the python cookbook.
#!/usr/bin/env python
from random import choice
import getopt
import string
import sys
def GenPasswd():
chars = string.letters + string.digits
for i in range(8):
newpasswd = newpasswd + choice(chars)
return newpasswd
def GenPasswd2(length=8, chars=string.letters + string.digits):
return ''.join([choice(chars) for i in range(length)])
class Options(object):
pass
def main(argv):
(optionList,args) = getopt.getopt(argv[1:],"r:l:",["repeat=","length="])
options = Options()
options.repeat = 1
options.length = 8
for (key,value) in optionList:
if key == "-r" or key == "--repeat":
options.repeat = int(value)
elif key == "-l" or key == "--length":
options.length = int(value)
for i in xrange(options.repeat):
print GenPasswd2(options.length)
if __name__ == "__main__":
sys.exit(main(sys.argv))
The open source Keepass tool has some excellent capabilities for password generation, including enhanced randomization.
I use password safe to generate and store all my passwords, that way you don't have to remember super strong passwords (well except the one that unlocks your safe).
An slight variation on your suggestion:
head -c 32 /dev/random | base64
Optionally, you can trim the trailing = and use echo to get a newline:
echo $(head -c 32 /dev/random | base64 | head -c 32)
which gives you a more predictable output length password whilst still ensuring only printable characters.
The standard Unix utility called pwgen.
Available in practically any Unix-like distribution.
The algorithm in apg is pretty cool. But I mostly use random characters from a list which I've defined myself. It is mostly numbers, upper- and lowercase letters and some punctuation marks. I've eliminated chars which are prone to getting mistaken for another character like '1', 'l', 'I', 'O', '0' etc.
I don't like random character passwords. They are difficult to remember.
Generally my passwords fall into tiers based on how important that information is to me.
My most secure passwords tend to use a combination of old BBS random generated passwords that I was too young and dumb to know how to change and memorized. Appending a few of those together with liberal use of the shift key works well. If I don't use those I find pass phrases better. Perhaps a phrase from some book that I enjoy, once again with some mixed case and special symbols put it. Often I'll use more than 1 phrase, or several words from one phrase, concatenated with several from another.
On low priority sites my passwords are are pretty short, generally a combination of a few familiar tokens.
The place I have the biggest problem is work, where we need to change our password every 30 days and can't repeat passwords. I just do like everyone else, come up with a password and append an ever increasing index to the end. Password rules like that are absurd.
For web sites I use SuperGenPass, which derives a site-specific password from a master password and the domain name, using a hash function (based on MD5). No need to store that password anywhere (SuperGenPass itself is a bookmarklet, totally client-side), just remember your master password.
I think it largely depends on what you want to use the password for, and how sensitive the data is. If we need to generate a somewhat secure password for a client, we typically use an easy to remember sentence, and use the first letters of each word and add a number. Something like 'top secret password for use on stackoverflow' => 'tspfuos8'.
Most of the time however, I use the 'pwgen' utility on Linux to create a password, you can specify the complexity and length, so it's quite flexible.
I use KeePass to generate complex passwords.
I use https://www.grc.com/passwords.htm to generate long password strings for things like WPA keys. You could also use this (via screenscraping) to create salts for authentication password hashing if you have to implement some sort of registration site.
In some circumstances, I use Perl's Crypt::PassGen module, which uses Markov chain analysis on a corpus of words (e.g. /usr/share/dict/words on any reasonably Unix system). This allows it to generate passwords that turn out to be reasonably pronounceable and thus remember.
That said, at $work we are moving to hardware challenge/response token mechanisms.
Pick a strong master password how you like, then generate a password for each site with cryptohash(masterpasword+sitename). You will not lose your password for site A if your password for site B gets in the wrong hands (due to an evil admin, wlan sniffing or site compromise for example), yet you will only have to remember a single password.
Having read and tried out some of the great answers here, I was still in search of a generation technique that would be easy to tweak and used very common Linux utils and resources.
I really liked the gpg --gen-random answer but it felt a bit clunky?
I found this gem after some further searching
echo $(</dev/urandom tr -dc A-Za-z0-9 | head -c8)
I used an unusual method of generating passwords recently. They didn't need to be super strong, and random passwords are just too hard to remember. My application had a huge table of cities in North America. To generate a password, I generated a random number, grabbed a randon city, and added another random number.
boston9934
The lengths of the numbers were random, (as was if they were appended, prepended, or both), so it wasn't too easy to brute force.
Well, my technique is to use first letters of the words of my favorite songs. Need an example:
Every night in my dreams, I see you, I feel you...
Give me:
enimdisyify
... and a little of insering numbers e.g. i=1, o=0 etc...
en1md1sy1fy
... capitalization? Always give importance to yourself :)
And the final password is...
en1Md1sy1fy
Joel Spolsky wrote a short article: Password management finally possible
…there's finally a good way to
manage all your passwords. This system
works no matter how many computers you
use regularly; it works with Mac,
Windows, and Linux; it's secure; it
doesn't expose your passwords to any
internet site (whether or not you
trust it); it generates highly secure,
random passwords for each and every
site, it's fairly easy to use once you
have it all set up, it maintains an
automatic backup of your password file
online, and it's free.
He recommends using DropBox and PasswordSafe or Password Gorilla.
import random
length = 12
charset = "abcdefghijklmnopqrstuvwxyz0123456789"
password = ""
for i in range(0, length):
token += random.choice(charset)
print password
passwords:
$ gpg --gen-random 1 20 | gpg --enarmor | sed -n 5p
passphrases:
http://en.wikipedia.org/wiki/Diceware
Mostly, I type dd if=/dev/urandom bs=6 count=1 | mimencode and save the result in a password safe.
On a Mac I use RPG.
In PHP, by generating a random string of characters from the ASCII table. See Generating (pseudo)random alpha-numeric strings
I start with the initials of a sentence in a foreign language, with some convention for capitalizing some of them. Then, I insert in a particular part of the sentence a combination of numbers and symbols derived from the name of the application or website.
This scheme generates a unique password for each application that I can re-derive each time in my head with no trouble (so no memorization), and there is zero chance of any part of it showing up in a dictionary.
You will have to code extra rules to check that your password is acceptable for the system you are writing it for. Some systems have policies like "two digits and two uppercase letters minimum" and so on. As you generate your password character by character, keep a count of the digits/alpha/uppercase as required, and wrap the password generation in a do..while that will repeat the password generation until (digitCount>1 && alphaCount>4 && upperCount>1), or whatever.
http://www.wohmart.com/ircd/pub/irc_tools/mkpasswd/mkpasswd+vms.c
http://www.obviex.com/Samples/Password.aspx
https://www.uwo.ca/its/network/security/passwd-suite/sample.c
Even in Excel!
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1032050.html
http://webnet77.com/cgi-bin/helpers/crypthelp.pl
Password Monkey, iGoogle widget!
The Firefox-addon Password Hasher is pretty awesome for generating passwords: Password Hasher
The website also features an online substitute for the addon:
Online Password Hasher
I generate random printable ASCII characters with a Perl program and then tweak the script if there's extra rules to help me generate a more "secure" password. I can keep the password on a post-it note and then destroy it after one or two days; my fingers will have memorized it, and my password will be completely unguessable.
This is for my primary login password, something I use every day, and in fact many times a day as I sit down and unlock my screen. This makes it easy to memorize fast. Obviously passwords for other situations have to use a different mechanism.

Resources