I need to encrypt a message using a secret key and return the message. I tried this and I got the correct output.
def my_encryption(some_string):
character_set= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "
secret_key=" Dd18Abz2EqNPW hYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
m=some_string
k=m.translate({ord(x): y for (x, y) in zip(character_set,secret_key )})
return m
print(my_encryption("Lets meet at the usual place at 9 am"))
The output I got is
oABjMWAABMDBMB2AMvjvDPMYPD1AMDBMGMDWB
and this is correct. I would like to know, will there be any other way to do this with out using translate?. I am curious to know the alternate ways. I will be glad to know. Thank you.
you can use a simple dictionary
def my_encryption(some_string):
character_set= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "
secret_key= "Dd18Abz2EqNPW hYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
table = {x: y for (x, y) in zip(character_set,secret_key )}
return "".join( map(lambda x:table.get(x,x),some_string) )
the get method can receive 2 arguments, the first is the key to search and the second is a value to return in case that the key is not present, in this case assign that as x to leave that unchanged
here a test
>>> my_encryption("Lets meet at the usual place at 9 am")
'oABjMWAABMDBMB2AMvjvDPMYPD1AMDBMGMDW'
>>>
this is usually the first thing that come to my mind when I want to do this simple substitution cipher.
and the inverse is as simple as invert key-value
def my_decription(some_string):
character_set= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "
secret_key= "Dd18Abz2EqNPW hYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
table = {x: y for (x, y) in zip(character_set,secret_key )}
return "".join( map(lambda x:table.get(x,x),some_string) )
>>> my_decription('oABjMWAABMDBMB2AMvjvDPMYPD1AMDBMGMDW')
'Lets meet at the usual place at 9 am'
>>>
A simple solution I use when making things less plain text is base64 module. This is not encryption by any means. Just makes the text a little harder to read:
>>> import base64
>>> base64.b64encode(b'This is a secret.')
b'VGhpcyBpcyBhIHNlY3JldC4='
>>> base64.b64decode(b'VGhpcyBpcyBhIHNlY3JldC4=').decode('utf-8')
'This is a secret.'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With