Security and Cryptography in Python - Substitution Cipher
A Substitution Cipher has
[26! = 403291461126605635584000000
]
possible permutations / possible keys.
[26! = 403291461126605635584000000
]
[2^88 = 309485009821345068724781056
]
Hence a 88 bit security.
Encryption
import random
def generate_key():
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
cletters = list(letters)
key = {}
for c in letters:
key[c] = cletters.pop(random.randint(0,len(cletters) - 1))
return key
key = generate_key()
print(key)
First Running Result:
Second Running Result:
import random
def generate_key():
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
cletters = list(letters)
key = {}
for c in letters:
key[c] = cletters.pop(random.randint(0,len(cletters) - 1))
return key
def encrypt(key, message):
cipher = ""
for c in message:
if c in key:
cipher += key[c]
else:
cipher += c
return cipher
key = generate_key()
print(key)
message = "YOU ARE AWESOME"
cipher = encrypt(key, message)
print(cipher)
First Running Result:
Second Running Result:
Decryption
import random
def generate_key():
letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
cletters = list(letters)
key = {}
for c in letters:
key[c] = cletters.pop(random.randint(0,len(cletters) - 1))
return key
def encrypt(key, message):
cipher = ""
for c in message:
if c in key:
cipher += key[c]
else:
cipher += c
return cipher
def get_decrypt_key(key):
dkey = {}
for k in key:
dkey[key[k]] = k
return dkey
key = generate_key()
print(key)
message = "YOU ARE AWESOME"
cipher = encrypt(key, message)
print(cipher)
dkey = get_decrypt_key(key)
message = encrypt(dkey, cipher)
print(message)
First Running Result:
Second Running Result: