This is what I have so far for the cipher code I keep on having errors when I try to type a word that has spaces in it, since it is not a character, my code can't process the spaces and how should I attack this problem?!
message = open("file_test").read()
print(message)
key = str(input("Enter any key\n"))
code = " "
for ch in message:
ord_value = ord(ch)
cipherValue = ord_value + key
if cipherValue > ord('z'):
cipherValue -= 26
code += chr(cipherValue)
print(code)
new_file = open("encrypted", "w")
new_file.write(code)
You can use an if/else statement.
for ch in message:
if ch.isalpha(): #If the character is a letter
ord_value = ord(ch)
cipherValue = ord_value + key
...
else:
code += chr #If the character is not a letter, just append it to the string.
isalpha is a string method that returns True if the string contains only letters.
I am in an into to Programming class and the assignment is in part to shift the letters of a valid password by +1 if it is a letter or number and -1 if it is a !##$ special character. I have most of it working with my below code but I always get the wrong output for the special characters. If I use to the code of anything high like 128 then I get the wrong symbol.
I am using the code from an encryption program from the other week and slowly changing things but I feel like this is too involved for something simple
If I enter the password UMA#augusta2020 I need to get the output VNB?bvhvtub3131 but I either end up with a space, b, or wrong symbol when I change the code input between 26,64,96,128, etc.
I have updated the code to fix small errors
def main():
print("This program validates and encrypts a password")
print()
main()
# The Encryption Function
def cipher_encrypt(plain_text):
encrypted = ""
for c in plain_text:
if c.isupper(): #check if it's an uppercase character
c_index = ord(c) - ord('A')
# shift the current character by key positions
c_shifted = (c_index + 1) % 26 + ord('A')
c_new = chr(c_shifted)
encrypted += c_new
elif c.islower(): #check if its a lowecase character
c_index = ord(c) - ord('a')
c_shifted = (c_index + 1) % 26 + ord('a')
c_new = chr(c_shifted)
encrypted += c_new
elif c.isdigit():
# if it's a number,shift its value
c_new = (int(c) + 1) % 10
encrypted += str(c_new)
else:
# if its neither alphabetical nor a number, -1
c_shifted = (c_index - 1) % 128 + ord('a')
c_new = chr(c_shifted)
encrypted += c_new
return encrypted
plain_text =input("Enter your Password: ")
print()
ciphertext = cipher_encrypt(plain_text)
print()
print("Your Password: ", plain_text)
print()
print("Your password is valid and encrypted it is: ", ciphertext)
print()
Here is a much cleaner approach:
def cipher_encrypt(plain_text):
alpha = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
puncs = '!"#$%&\'()*+,-./:;<=>?#[\\]^_`{|}~'
encrypted_text = ''
for c in plain_text:
if c.lower() in alpha:
c_index = alpha.index(c.lower())
e_index = (c_index + 1)%len(alpha)
if c == c.lower():
encrypted_text += alpha[e_index]
else:
encrypted_text += alpha[e_index].upper()
elif c in digits:
c_index = digits.index(c)
e_index = (c_index + 1)%len(digits)
encrypted_text += digits[e_index]
else:
c_index = puncs.index(c)
e_index = (c_index +len(puncs) - 1)%len(puncs)
encrypted_text += puncs[e_index]
return encrypted_text
In this approach I deal with each caharcter in plain text by:
Determining idf the char is part of alpha by making use of the c.lower() function to isolate alpha chars and then find an index modulo the len of alpha. Then I determine if I need an uppercase char or lower case in the encrypted text.
I use the same modulo approach for digits, but don't have to worry about upper and lower, finally
I find the index for the punctuations found in the plain_text
For my programming class, I've been instructed to create two programs, each using the same two helper functions: alphabet_position(letter) and rotate_character(char, rot). One function uses the Caesar cipher to encrypt a message with a number of rotations, each given from the command line. The second program is meant to put more use to my Caesar program by turning it into the Vigenere Cipher. Both programs are meant to ignore (i.e., not rotate) special characters and I don't think numbers matter either. However, if the input letter is capitalized, the rotated output letter should be as well.
I've run into several issues with my code: My Caesar program only prints some capital letters. For example, with the arguments Hello, World! and 4, I receive an output of Lipps, svph! and I cannot figure out why that last capital letter isn't printing. When I attempt to pass in pYthon with 26 rotations, my program prints nothing.
My Vigenere program is also doing an odd thing with capital letters: with the passed arguments being Hello, World! and boom, I receive Iszxp, mr!.
Assignment is due in 48 hours and I'm kind of freaking out. π¬ Any and all help, criticism, etc. is welcome!
def alphabet_position(letter):
"""receives a letter and returns the 0-based numerical position of that letter within the alphabet."""
letter = letter.lower()
alphabet = "abcdefghijklmnopqrstuvwxyz"
numerical_pos = alphabet.find(letter)
return numerical_pos
def rotate_character(char, rot):
"""receives a character and an int 'rot', and rotates char by rot number of places to the right."""
alphabet = "abcdefghijklmnopqrstuvwxyz"
alpha_dict = dict(enumerate(alphabet))
new_char = ""
# ignore and return non-alphabetic characters
if char not in alphabet:
return char
# temporarily convert case to locate in alphabet
temp_char = char.lower()
if temp_char in alphabet:
# get original position of letter
orig_pos = alphabet_position(temp_char)
# take char, add rot to its index, mod 25 - 1
new_pos = (int(orig_pos) + int(rot))
if new_pos > 25:
new_pos = (new_pos % 25) - 1
elif new_pos < 0:
# avoid negative index error when rot is 26
new_char = char
# converting new_pos back to alpha
else:
new_char = alpha_dict[new_pos]
# if original char was upper/lower, return corresponding case for new_char
if char.islower():
new_char.lower()
else:
new_char.upper()
return new_char
from helpers import alphabet_position, rotate_character
# ------
# caesar cipher
# ------
def encrypt(text, rot):
new_text = ""
for char in text:
new_char = rotate_character(char, rot)
new_text += str(new_char)
return new_text
def main():
input_text = input("Enter a sentence to encrypt: ")
input_rot = int(input("Number of rotations: "))
print(encrypt(input_text, input_rot))
if __name__ == "__main__":
main()
from helpers import alphabet_position, rotate_character
# ------
# vigenere cipher
# ------
def encrypt(text, rot):
lower_alphabet = "abcdefghijklmnopqrstuvwxyz"
upper_alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
keystream = 0
encrypted = ""
rot.lower()
for i in range(len(text)):
keychar = keystream % len(rot)
if text[i] in lower_alphabet:
new_char = rotate_character(text[i], alphabet_position(rot[keychar]))
new_char.lower()
encrypted += new_char
keystream += 1
elif text[i] in upper_alphabet:
new_char = rotate_character(text[i], alphabet_position(rot[keychar]))
new_char.upper()
encrypted += new_char
keystream += 1
else:
encrypted += text[i]
# stuck around here... vigenere isn't printing shifted capital letters and I
# can't figure out why.
return encrypted
def main():
input_text = input("Enter a sentence to encrypt: ")
input_rot = input("Enter your keyword: ")
print(encrypt(input_text, input_rot))
if __name__ == "__main__":
main()
Edit: helper functions edited to make code cleaner... Now it's only printing the one capital letter when I input pYthon with 4 rotations in Caesar. I'm lost.
I have a code and I'm having trouble making it interactive.
Here's the problem:
"""Write a function called rot13 that uses the Caesar cipher to encrypt a message. The Caesar cipher works like a substitution cipher but each character is replaced by the character 13 characters to βits rightβ in the alphabet. So for example the letter βaβ becomes the letter βnβ. If a letter is past the middle of the alphabet then the counting wraps around to the letter βaβ again, so βnβ becomes βaβ, βoβ becomes βbβ and so on. Hint: Whenever you talk about things wrapping around its a good idea to think of modulo arithmetic (using the remainder operator)."""
Here's the code to this problem:
def rot13(mess):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for char in mess:
if char == ' ':
encrypted = encrypted + ' '
else:
rotated_index = alphabet.index(char) + 13
if rotated_index < 26:
encrypted = encrypted + alphabet[rotated_index]
else:
encrypted = encrypted + alphabet[rotated_index % 26]
return encrypted
def main():
print(rot13('abcde'))
print(rot13('nopqr'))
print(rot13(rot13('since rot thirteen is symmetric you should see this message')))
if __name__ == "__main__":
main()
I want to make it interactive where you can input any message and you can rotate the letters however many times as you want. Here is my attempt. I understand you'd need two parameters to pass, but I'm clueless as to how to replace a few items.
Here's my attempt:
def rot13(mess, char):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for char in mess:
if char == ' ':
encrypted = encrypted + ' '
else:
rotated_index = alphabet.index(char) + mess
if rotated_index < 26:
encrypted = encrypted + alphabet[rotated_index]
else:
encrypted = encrypted + alphabet[rotated_index % 26]
return encrypted
def main():
messy_shit = input("Rotate by: ")
the_message = input("Type a message")
print(rot13(the_message, messy_shit))
if __name__ == "__main__":
main()
I don't know where my input should be taking place in the function. I have a feeling it could be encrypted?
This is probably what you're looking for. It rotates the message by the messy_shit input.
def rot13(mess, rotate_by):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for char in mess:
if char == ' ':
encrypted = encrypted + ' '
else:
rotated_index = alphabet.index(char) + int(rotate_by)
if rotated_index < 26:
encrypted = encrypted + alphabet[rotated_index]
else:
encrypted = encrypted + alphabet[rotated_index % 26]
return encrypted
def main():
messy_shit = input("Rotate by: ")
the_message = input("Type a message")
print(rot13(the_message, messy_shit))
def rot(message, rotate_by):
'''
Creates a string as the result of rotating the given string
by the given number of characters to rotate by
Args:
message: a string to be rotated by rotate_by characters
rotate_by: a non-negative integer that represents the number
of characters to rotate message by
Returns:
A string representing the given string (message) rotated by
(rotate_by) characters. For example:
rot('hello', 13) returns 'uryyb'
'''
assert isinstance(rotate_by, int) == True
assert (rotate_by >= 0) == True
alphabet = 'abcdefghijklmnopqrstuvwxyz'
rotated_message = []
for char in message:
if char == ' ':
rotated_message.append(char)
else:
rotated_index = alphabet.index(char) + rotate_by
if rotated_index < 26:
rotated_message.append(alphabet[rotated_index])
else:
rotated_message.append(alphabet[rotated_index % 26])
return ''.join(rotated_message)
if __name__ == '__main__':
while True:
# Get user input necessary for executing the rot function
message = input("Enter message here: ")
rotate_by = input("Enter your rotation number: ")
# Ensure the user's input is valid
if not rotate_by.isdigit():
print("Invalid! Expected a non-negative integer to rotate by")
continue
rotated_message = rot(message, int(rotate_by))
print("rot-ified message:", rotated_message)
# Allow the user to decide if they want to continue
run_again = input("Continue? [y/n]: ").lower()
while run_again != 'y' and run_again != 'n':
print("Invalid! Expected 'y' or 'n'")
run_again = input("Continue? [y/n]: ")
if run_again == 'n':
break
Note: It's more efficient to create a list of characters then join them to produce a string instead of using string = string + char. See Method 6 here and the Python docs here. Also, be aware that our rot function only works for lowercase letters of the alphabet. It'll break if you try to rot a message with uppercase characters or any character that isn't in alphabet.
as a school work, I am trying to make a password encryption/decryption program.
I need consider the following rules:
Ensure that every password contains at least one letter (A-Z) or (a-z), one nonalphabetic character (from #, #, %), and at least one digit. The program must reject passwords that violate this rule.
Restrict the characters that are allowed in a password to letters (A-Z) and (a-z), digits (0-9) and the three characters (#, #, %). The program must reject passwords that violate this rule.
If the password violates those conditions, I will terminate the program with:
print('Invalid password!')
sys.exit()
I've been stuck for hours trying to add these conditions... I don't get where to add these conditions, wherever I add them, my program just terminates even though I've input a valid password T-T
Here is what I have so far (I've removed the part for decryption so that I can try to figure out that part for myself afterwards):
# import sys module for termination
import sys
# init
password_out = ''
case_changer = ord('a') - ord('A')
encryption_key = (('a','m'), ('b','h'), ('c','t'), ('d','f'), ('e','g'),
('f','k'), ('g','b'), ('h','p'), ('i','j'), ('j','w'), ('k','e'),('l','r'),
('m','q'), ('n','s'), ('o','l'), ('p','n'), ('q','i'), ('r','u'), ('s','o'),
('t','x'), ('u','z'), ('v','y'), ('w','v'), ('x','d'), ('y','c'), ('z','a'),
('#', '!'), ('#', '('), ('%', ')'), ('0'), ('1'), ('2'), ('3'), ('4'), ('5'),
('6'), ('7'), ('8'), ('9'))
encrypting = True
# get password
password_in = input('Enter password: ')
# perform encryption / decryption
if encrypting:
from_index = 0
to_index = 1
else:
from_index = 1
to_index = 0
case_changer = ord('a') - ord('A')
for ch in password_in:
letter_found = False
for t in encryption_key:
if ('a' <= ch and ch <= 'z') and ch == t[from_index]:
password_out = password_out + t[to_index]
letter_found = True
elif ('A' <= ch and ch <= 'Z') and chr(ord(ch) + 32) == t[from_index]:
password_out = password_out + chr(ord(t[to_index]) - case_changer)
letter_found = True
elif (ch == '#' or ch == '#' or ch == '%') and ch == t[from_index]:
password_out = password_out + t[to_index]
elif (ch >= '0' and ch <= '9') and ch == t[from_index]:
password_out = password_out + ch
# output
if encrypting:
print('Your encrypted password is:', password_out)
else:
print('Your decrypted password is:', password_out)
No regular expressions required
import string
import sys
NON_ALPHABETIC_CHARACTERS = {'#', '#', '%'}
DIGITS_CHARACTERS = set(string.digits)
LETTERS_CHARACTERS = set(string.ascii_letters)
def validate_password_1(password,
non_alphabetic_characters=NON_ALPHABETIC_CHARACTERS,
digits_characters=DIGITS_CHARACTERS,
letters_characters=LETTERS_CHARACTERS):
if not any(character in password
for character in non_alphabetic_characters):
err_msg = ('Password should contain at least '
'one non-alphabetic character.')
print(err_msg)
print('Invalid password!')
sys.exit()
if not any(character in password
for character in digits_characters):
err_msg = ('Password should contain at least '
'one digit character.')
print(err_msg)
print('Invalid password!')
sys.exit()
if not any(character in password
for character in letters_characters):
err_msg = ('Password should contain at least '
'one letter character.')
print(err_msg)
print('Invalid password!')
sys.exit()
ALLOWED_CHARACTERS = (NON_ALPHABETIC_CHARACTERS
| DIGITS_CHARACTERS
| LETTERS_CHARACTERS)
def validate_password_2(password,
allowed_characters=ALLOWED_CHARACTERS):
if not all(character in allowed_characters
for character in password):
print('Invalid password!')
sys.exit()
Added additional messages to see what exactly is wrong with given password
This certainly won't qualify as answer for your homework, but you can test that kind of conditions easily with sets:
import string
alpha = set(string.ascii_lowercase + string.ascii_uppercase)
digits = set(string.digits)
non_alpha = set('##%')
def is_valid(password):
password_chars = set(password)
# We substract the set of letters (resp. digits, non_alpha)
# from the set of chars used in password
# If any of the letters is used in password, this should be
# smaller than the original set
all_classes_used = all([len(password_chars - char_class) != len(password_chars)
for char_class in [alpha, digits, non_alpha] ])
# We remove all letters, digits and non_alpha from the
# set of chars composing the password, nothing should be left.
all_chars_valid = len(password_chars - alpha - digits - non_alpha) == 0
return all_classes_used and all_chars_valid
for pw in ['a', 'a2', 'a2%', 'a2%!']:
print(pw, is_valid(pw))
# a False
# a2 False
# a2% True
# a2%! False
One possible way to check for both cases would be to do the following:
if password == password.lower() or password == password.upper():
# Reject password here.
We're not going to write the rest of the encryption for you, though!
I will do something like that using regexp:
import re
def test(x):
regexp = r'[##%]+[0-9]+#*[a-zA-Z]+'
sorted_x = ''.join(sorted(x))
if '#' in sorted_x:
sorted_x = '#%s' % sorted_x
p = re.compile(regexp)
return p.match(sorted_x) is not None
Then the function gives :
In [34]: test("dfj")
Out[34]: False
In [35]: test("dfj23")
Out[35]: False
In [36]: test("dfj23#")
Out[36]: True
If you need one upper AND one lower case letter you can change the regexp to:
regexp = r'[##%]+[0-9]+#*[A-Z]+[a-z]+'
The sorted function will put the # and the % first, then the numbers, then the # and finally the letters (first the uper case and then the lower case). Because the # is put in the middle, I put one first if I find one in the string.
So at the end you want a string with at least a special character : [##%]+, at least a number [0-9]+, optionally there can be a # in the middle, and finally a letter [a-zA-Z]+ (or if you want upper and lower [A-Z]+[a-z]+).