Issue
I have made a string encryption method, but i can't find out how to make a decryption method. My encryption function is below (in python)
def encrypt(text, key):
cmp=["q","w","e","r","t","y","i","u","p","o","s","a","f","d","h","g","k","j","k","l","z","x","c","v","b","n","m","Q","l","E","W","T","R","U","Y","O","I","A","P","D","S","G","F","J","H","L","K","X","Z","V","C","N","B","`","M","2","1","4","3","6","5","8","7","0","9","=","-","!","~","#","@","%","$","&","^","(","*","_",")"," ","+","[","]","\\","{","}","|",",",".","/","<",">","/"]
md={}
c=0
for id in cmp:
md[id]=c
c+=1
keyInFigs=0
for char in key:
keyInFigs+=md[char]
textObj=text
textInFigs=""
for char in textObj:
textInFigs+=str(md[char])+" "
textInFigs=textInFigs.removesuffix(" ")
output=""
for char in textInFigs.split():
output += str(int(char) * keyInFigs) + " "
return output
Solution
Let's start by re-writing parts of your algorithm, for clarity:
# these will be needed to decrypt as well
# strings are iterables, no need for a list
cmp = "qwertyiupo" + "safdhgkjkl" + "zxcvbnm" + "QlEWTRUYOIAP" + "DSGFJHLK" + "XZVCNB`M" + "2143658709" + "=-!~#@%$&^(*_)" + " +[]\\{}|,./<>/"
# enumerate is simpler
md = {char: index for index, char in enumerate(cmp)}
def encrypt(text, key):
# sum is clearer
keyInFigs = sum(md[char] for char in key)
# no need to loop twice, both operations can be combined
output = " ".join(str(md[char] * keyInFigs) for char in text)
return output
From there, we can decrypt, simply applying the same steps in the reverse order:
def decrypt(text, key):
# this is also needed to decrypt
keyInFigs = sum(md[char] for char in key)
# the text looks like "1234 4324 545365"
parts = text.split()
# divide by the key as int, and find the corresponding character
decoded_values = [cmp[int(part) // keyInFigs] for part in parts]
output = "".join(decoded_values)
return output
>>> k = "foobar"
>>> e = encrypt("Hello world!", k)
>>> e
'2992 136 1904 1904 612 5372 68 612 204 1904 884 4556'
>>> decrypt(e, k)
'Hello world!'
Answered By - njzk2
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.