Well, hello everybody. this is my very first piece of code i've ever written, but i am willing to learn. basically i want to generate random numbers/passwords. The script should ask at first some things (have not implemented all right now).
length = length of generated passwords (fixed value)
pmaximum = amount of generated passwords
chars = which chars should be used for generating (i want to short this one so i can choose between LC, UC and numbers)
Choosing between:
string.letters[0:52] + string.digits + string.punctuation
this is my code right now, generating a valueerror;
#! /usr/bin/python
import string, random
#=============== Router Password Generator ==============
print 'Welcome to passwordlist generator'
length=input('length of generated passwords: ')
pmaximum=input('maximum amount of generated passwords: ')
chars=raw_input('which chars to use: ')
string=''
filename = raw_input('assign wordlist name: ')
f_extns = filename.split('.')
for count in xrange(0,pmaximum):
for x in random.sample(chars,length):
string+=x
file.write(string+'\n')
string=''
file.close()
print 'Done'
#================ RPG END ===============
i've wrote this using snippets from the web, i have a bit understanding of coding but i am here to learn, if someone could've explain some things i would be very happy so i can understand this code better if it works.
Related
I've recently been having trouble writing a program that involves taking the password and username from a .txt file. So far I have written:
username_file = open("usernameTest1.txt","rt")
name = username_file.readlines()
username_file.close()
print(username_file)
print(name)
print(name[0])
print()
print(name[1])
Player1Name = name[0]
print(Player1Name)
nametry = ""
while nametry != (name[0]):
while True:
try:
nametry = input("What is your Username player1?: ")
break
except ValueError:
print("Not a valid input")
(The various prints are to help me to see what the error is)
The password is successfully extracted from the file however when it is put into a variable and put through an if statement, it doesn't work!
Any help would be much appreciated!
Hopefully this is a simple fix!
Your problem is that readlines() function lets the \n character remain in your text lines and that causes the texts to not match. You can use this instead when opening the file:
name = username_file.read().splitlines()
give it a try.
the readlines function doen't strip the newline character from the end of the lines, so eventough you wrote "samplename" as input, it won't equal "samplename\n".
You can try this:
name = [x.rstrip() for x in username_file.readlines()]
Just trimmed this down big time
I have an overall assignment that must read a file, encrypt it and then write the encrypted data to a new file.
what i've tried is this:
filename=input("Enter file name:")
fr=open(filename)
keep_going=0
data = fr.readline()
fw=open('encrypted_file.txt', 'w')
for x in range(len(data)):
fw.write(data[x])
fw.close()
fr.close()
If your goal is just to exchange the letters in a string with others that you specify, then the solution is the following:
decrypted = 'abcdefghijklmnopqrstuvwxyz' #normal alphabet
encrypted = 'MNBVCXZLKJHGFDSAPOIUYTREWQ' #your "crypted" alphabet
#Encription
text = 'cryptme' #the string to be crypted
encrypted_text = ''
for letter in text:
encrypted_text += encrypted[decrypted.find(letter)]
print encrypted_text
#will print BOWAUFC
#Decription
text = encrypted_text #"BOWAUFC" in this example
decrypted_text = ''
for letter in text:
decrypted_text += decrypted[encrypted.find(letter)]
print decrypted_text
#will print cryptme
Note that your "crypted alphabet" do not convert any white space or any symbols but the lowercase letters, if you have other symbols in your text you have to include them as well.
However, this is not the proper way to encrypt anything! As suggested by others already, look up for a proper encryption algorithm.
I would suggest you look into Simple Crypt, this all depends on the level of security you want.
If I understand your question enough, Simple Crypt should do the job that you need.
https://pypi.python.org/pypi/simple-crypt
Here's a very simple implementation of the Vigenère Cipher I made:
from string import ascii_uppercase as alphabet
val = {}
for x in xrange(len(alphabet)):
val[alphabet[x]] = x
val[x] = alphabet[x]
encrypt = lambda a, b: ''.join(val[(val[a[i]]+val[b[i%len(b)]])%26] for i in xrange(len(a)))
decrypt = lambda a, b: ''.join(val[(val[a[i]]-val[b[i%len(b)]])%26] for i in xrange(len(a)))
Where a is the message and b is the key (I know it's written a bit tersely, but it was for a code golf competition). There are plenty of ciphers out there; you don't have to use this one, and probably shouldn't. It is just meant to get you thinking about possible ways to go about doing this. A very simple cipher that I think is good for your purposes is the Caesar Cipher.
One other thing that I'd like to point out is that your code doesn't look to modular -- one of your teacher's requirements -- right now. I'd recommend breaking it down to a function to open a file, a function to perform the actual **cryption, and a "main" function to take the user's input and call the other functions.
Best of luck to you!
Hey guys so I 'm trying to make a cipher following these sets of instructions:
Print a header.
Prompt the user to enter the name of the file with the encrypted message, the decode
key (the shift number), and the name of the file to store the decrypted message.
Read the encrypted message from the file.
Use the decode key to shift each character in the encrypted message by the
appropriate number to generate the new string corresponding to the decrypted message.
Save the decrypted message in the second file.
Print the encypted and decrypted messages on the screen.
I'm not allowed to use the ord() or chr() functions.
What really confuses me is the encrypted and decrypted files part. I don't really know how to code for this.
I'm pretty new to this so any help would be greatly appreciated.
Thanks in advance.
Note: It sounds like you're probably doing this as a school assignment. I highly recommend that you use the code below only as an example and not as a full solution. I would hate for there to be plagiarism issues surrounding your assignment and I'm sure your professor/teacher is knowledgeable at Googling for prior work. Good luck on your assignment!
I wrote a quick example of how I might try and tackle your problem. The example has a few known issues:
It doesn't deal with capital letters. (Other than to convert them to their lowercase counterparts.)
It doesn't deal with punctuation or non alphanumeric characters. (Numbers, spaces or line endings.)
There is no error checking.
If you try to convert a number < -25 it will throw up on you.
Probably the biggest problem that needed to be solved was the limitation of not using ord() and chr(). I bypassed that limitation by creating my own conversion list of letters to numbers and vice versa. A tricky corner case to make sure you deal with is what happens if the shift moves a letter outside of the conversion range [0,25].
As a side note if you want to decrypt a file you can simply open it up as the plaintext and use a negative offset whose absolute value is equal to the encrypting offset. Or in plain English, if you use the parameters:
infile = clear.txt, offset = 1, outfile = encrypted.txt
To decrypt you can use:
infile = encrypted.txt, offset = -1, outfile = decrypted.txt
caesarcipher.py
import itertools
letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q',
'r','s','t','u','v','w','x','y','z']
numbers = range(26) # Numbers 0 - 25
lettersToNumbers = dict(zip(letters, numbers))
numbersToLetters = dict(zip(numbers, letters))
def printHeader():
""" Print the program informational header """
print """=======================================
Welcome to CaesarCipher - The unbreakable
Roman cipher.
======================================="""
def convertToNumber(letter):
""" Convert a letter to a number using our predefined conversion table
#param letter: The letter to convert to an integer value
#type letter: str
#rtype: int
"""
return lettersToNumbers[letter]
def convertToLetter(number):
""" Convert a number to a letter using our predefined conversion table
#param number: The number to convert to a letter
#type number: int
#rtype: str
"""
# If we shift outside of our range make sure to wrap
if number > 25:
return numbersToLetters[number%25]
elif number < 0:
return numbersToLetters[number+25]
else:
return numbersToLetters[number]
def shiftUp(letter, shift):
""" Shift letter up a given number of positions
#param letter: The letter we're shifting
#param shift: The number of positions to shift up
#type letter: str
#type shift: int
#note: For simplicity we encode both capital and lowercase letters
to the same values
"""
number = convertToNumber(letter.lower())
number += shift
return convertToLetter(number)
def prompt():
""" Prompt for user input
#rtype: tuple of str, int, str
"""
infile = raw_input("File to encrypt: ")
offset = int(raw_input("Encoding number: "))
outfile = raw_input("Encrypted file destination: ")
return (infile, offset, outfile)
def encrypt(infile, offset, outfile):
""" Encrypt the file using the given offset """
print "=== Plaintext input ==="
printFile(infile)
with open(infile) as red_file:
with open(outfile, 'w') as black_file:
for line in red_file:
for letter in line:
# Only convert alphabetic characters
if letter.isalpha():
black_file.write(shiftUp(letter, offset))
else:
black_file.write(letter)
print "=== Ciphertext output ==="
printFile(outfile)
def printFile(path):
""" Print the data in the given file """
with open(path) as print_file:
for line in print_file:
print line
printHeader()
encrypt(*prompt()) # `*` unpacks the tuple returned by `prompt()` into
# three separate arguments.
test.txt
abcdef
ABCDEF
This is some text I want to try and encrypt.
Example run:
mike#test:~$ python caesarcipher.py
=======================================
Welcome to CaesarCipher - The unbreakable
Roman cipher.
=======================================
File to encrypt: test.txt
Encoding number: 1
Encrypted file destination: test.out
=== Plaintext input ===
abcdef
ABCDEF
This is some text I want to try and encrypt.
=== Ciphertext output ===
bcdefg
bcdefg
uijt jt tpnf ufyu j xbou up usz boe fodszqu.
Since you say the file bits is your biggest problem, I assume function like:
def decaesar(message, shift):
pass
that does the decyphering for you on a string basis - that is, it takes the encrypted message as a string and gives you back the decrypted message as a string. If you haven't written that already, do that first, and test it with hard-coded strings. Ignore the "encrypted and decrypted files" bit at this stage - programming is all about solving one problem at a time.
Once you have that function and you're happy that it works, extending your program to deal with files instead of strings is as simple as asking:
Can I get a string with the contents of a file, given the file's name? , and conversely,
Can I write a string into a file with a given name?
If you can answer both of those with 'yes', then you can extend your program in this way without changing your decaesar function - your logic looks like this:
# Print header
encrypted_filename, decrypted_filename, shift = # get from user input
encrypted_message = # get the contents of encrypted_filename as a string
decrypted_message = decaesar(encrypted_message, shift)
# write decrypted_message to decrypted_filename
# print encrypted_message and decrypted_message
Usefully, Python's file IO works on exactly this principle of converting between strings and files. If you have a file open for reading:
in_file = open(filename)
, then the return value of:
in_file.read()
is exactly the string to answer the first point. Likewise, if you have a file open for writing:
out_file = open(filename, 'w')
. then:
out_file.write(my_string)
will put my_string into that file.
So that means that if you do already have your decaeser function, then you can slip this code into the pseudocode above at the appropriate places, and you will have a mostly working solution.
I am trying to encrypt all possible strings in a defined character set then compare them to a hash given by user input.
This is what I currently have
import string
from itertools import product
import crypt
def decrypt():
hash1 = input("Please enter the hash: ")
salt = input("Please enter the salt: ")
charSet = string.ascii_letters + string.digits
for wordchars in product(charSet, repeat=2):
hash2 = crypt.METHOD_CRYPT((wordchars), (salt))
print (hash2)
Obviously its not finished yet but I am having trouble encrypting "wordchars"
Any help is appreciated
crypt.METHOD_CRYPT is not callable so the traceback that you provided doesn't correspond to the code in your question. crypt.METHOD_CRYPT could be used as the second parameter for crypt.crypt() function.
Also as #martineau pointed out wordchars is a tuple but you need a string to pass to the crypt.crypt() function.
From the docs:
Since a few crypt(3) extensions allow different values, with different
sizes in the salt, it is recommended to use the full crypted password
as salt when checking for a password.
To find a plain text from a defined character set given its crypted form: salt plus hash, you could:
from crypt import crypt
from itertools import product
from string import ascii_letters, digits
def decrypt(crypted, charset=ascii_letters + digits):
# find hash for all 4-char strings from the charset
# and compare with the given hash
for candidate in map(''.join, product(charset, repeat=4)):
if crypted == crypt(candidate, crypted):
return candidate
Example
salt, hashed = 'qb', '1Y.qWr.DHs6'
print(decrypt(salt + hashed))
# -> e2e4
assert crypt('e2e4', 'qb') == (salt + hashed)
The assert line makes sure that calling crypt with the word e2e4 and the salt qb produces qb1Y.qWr.DHs6 where qb is the salt.
Hmm may be better use bcrypt?
https://github.com/fwenzel/python-bcrypt
Below is a simple program that does what you asked:
def gen_word(charset, L):
if L == 1:
for char in charset:
yield char
raise StopIteration
for char in charset:
for word in gen_word(charset, L - 1):
yield char + word
def encrypt(word):
'''Your encrypt function, replace with what you wish'''
return word[::-1]
charset = ['1', '2', '3']
user_word = '12'
user_hash = encrypt(user_word)
max_length = 3
for length in range(1, max_length):
for word in gen_word(charset, length):
if encrypt(word) == user_hash:
print 'Word found: %s' % word
Basically, it uses a python generator for generating words from the charset of fixed length. You can replace the encrypt function with whatever you want (in the example is string reversal used as hash).
Note that with actual modern hashing methods, it'll take forever to decrypt an ordinary password, so I don't think you could actually use this.
Here's my completely different answer based on J.F. Sebastian's answer and comment about my previous answer. The most important point being that crypt.METHOD_CRYPT is not a callable even though the documentation somewhat confusingly calls a hashing method as if it were a method function of a module or an instance. It's not -- just think of it as an id or name of one of the various kinds of encryption supported by the crypt module.
So the problem with you code is two-fold: One is that you were trying to use wordchars as a string, when it actually a tuple produced by product() and second, that you're trying to call the id crypt.METHOD_CRYPT.
I'm at a bit of a disadvantage answering this because I'm not running Unix, don't have Python v3.3 installed, and don't completely understand what you're trying to accomplish with your code. Given all those caveats, I think something like the following which is derived from you code ought to at least run:
import string
from itertools import product
import crypt
def decrypt():
hash1 = input("Please enter the hash: ")
salt = input("Please enter the salt: ")
charSet = string.ascii_letters + string.digits
for wordchars in product(charSet, repeat=2):
hash2 = crypt.crypt(''.join(wordchars), salt=salt) # or salt=crypt.METHOD_CRYPT
print(hash2)
I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.
I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.