Skip to content Skip to sidebar Skip to footer

How Would I Make A Simple Encryption/decryption Program?

I'd like to know (just as the question says) how to make a simple encryption and decryption program. letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' encryption_code = 'LFWOAYUISVKMNXPBDCRJ

Solution 1:

Use two dicts to do the mapping, one from letters to encryption_code and the reverse to decrypt:

letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'

enc = dict(zip(letters,encryption_code))

dec = dict(zip(encryption_code, letters))


s = "HELLO WORLD"

encr = "".join([enc.get(ch, ch) for ch in s])
decr = "".join([dec.get(ch, ch) for ch in encr])

print(encr)
print(decr)

Output:

IAMMP EPCMO 
HELLO WORLD

Using your method your input will have to be uppercase and the user is restricted to A-Z for the letters to be encrypted, if you want to allow other characters just add the mapping to the dicts.

letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
letters += letters.lower()
encryption_code += encryption_code.lower()
enc = dict(zip(letters,encryption_code))

dec = dict(zip(encryption_code, letters))


s = "HELLO world"

encr = "".join([enc.get(ch, ch) for ch in s])
decr = "".join([dec.get(ch, ch) for ch in encr])

print(encr)
print(decr)

Output:

IAMMP epcmo
HELLO world

Any characters not in letters will be the same in encr and decr i.e:

 s = "HELLO world!#}%"
 IAMMP epcmo!#}% # encr
 HELLO world!#}% # decr

Solution 2:

you create an encoder and a decoder:

enc = str.maketrans(letters, encryption_code)
dec = str.maketrans(encryption_code, letters)

and use them:

encr = 'HELLO WORLD'.translate(enc)
decr = encr.translate(dec)

Post a Comment for "How Would I Make A Simple Encryption/decryption Program?"