generated from mwc/lab_encryption
79 lines
2.3 KiB
Python
79 lines
2.3 KiB
Python
test_str = "abc"
|
|
|
|
bytes_lst = []
|
|
for item in test_str:
|
|
bytes_lst.append(bytes(item,'utf-8'))
|
|
print("As bytes, the string is:")
|
|
print(bytes_lst)
|
|
|
|
encoded_lst = []
|
|
for item in test_str:
|
|
encoded_lst.append(item.encode())
|
|
print("Encoding the characters in the string also gives:")
|
|
print(encoded_lst)
|
|
|
|
hex_lst=[]
|
|
for item in encoded_lst:
|
|
hex_lst.append(list(item)[0])
|
|
print("The hex values associated with those bytes is:")
|
|
print(hex_lst)
|
|
|
|
def numerify(message):
|
|
"""Converts the characters in a String to their hex values, returns a list of hex values.
|
|
"""
|
|
letterBytes = [item.encode() for item in message]
|
|
hexResult = [list(letterByte)[0] for letterByte in letterBytes]
|
|
return hexResult
|
|
|
|
def encrypt(numeric_message):
|
|
secretNumber = 1
|
|
newMessage = []
|
|
for value in numeric_message:
|
|
newMessage.append((value + secretNumber) % 256)
|
|
return newMessage
|
|
|
|
def decrypt(encrypted_message):
|
|
secretNumber = 78
|
|
newMessage = []
|
|
for value in encrypted_message:
|
|
newMessage.append((value + (256 - secretNumber)) % 256)
|
|
return newMessage
|
|
|
|
def wordify(decrypted_message):
|
|
message = [chr(item) for item in decrypted_message]
|
|
finalMessage = ''.join(message)
|
|
return finalMessage
|
|
|
|
import statistics
|
|
def decrypt_unknown(encrypted_message):
|
|
"""Makes the assumption that the space character is going to be the most common character in the message. This obviously wouldn't work with a shorter message consisting of just a word or even handful of words, where I would swap my strategy to something like the letter "e" instead.
|
|
"""
|
|
space = statistics.mode(encrypted_message)
|
|
cipher = space - 32
|
|
newMessage = []
|
|
for value in encrypted_message:
|
|
newMessage.append((value + (256 - cipher)) % 256)
|
|
return newMessage
|
|
|
|
file1 = open("xfile.txt", "r")
|
|
file2 = open("personal_poetry.txt", "r")
|
|
file3 = open("answers19.txt", "r")
|
|
|
|
def parseFile(file):
|
|
data = file.read()
|
|
#print(data)
|
|
data = data.split(', ')
|
|
#print(data)
|
|
data[0] = data[0][1:]
|
|
data[len(data)-1] = data[len(data)-1][:-1]
|
|
#print(data)
|
|
newData = []
|
|
for datum in data:
|
|
newData.append(int(datum))
|
|
#print(newData)
|
|
return newData
|
|
|
|
message = parseFile(file3)
|
|
print(wordify(decrypt_unknown(message)))
|
|
|
|
#print(wordify(decrypt(encrypt(numerify('abc'))))) |