Saturday, July 25, 2020

Implement Monoalphabetic cipher encryption-decryption in Python.

Monoalphabetic cipher in Python.


import sys, random
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def main():
    myMessage = 'All our dreams can come true, if we have the courage to pursue them'
    myKey = 'QWERTYUIOPASDFGHJKLZXCVBNM'
    myMode = 'encrypt' 

    checkValidKey(myKey)

    if myMode == 'encrypt':
        translated = encryptMessage(myKey, myMessage)
    elif myMode == 'decrypt':
        translated = decryptMessage(myKey, myMessage)
    print('Using key : %s' % (myKey))
    print('The %sed message is :' % (myMode))
    print(translated)


def checkValidKey(key):
    keyList = list(key)
    lettersList = list(LETTERS)
    keyList.sort()
    lettersList.sort()
    if keyList != lettersList:
        sys.exit('There is an error in the key or symbol sets.')


def encryptMessage(key, message):
    return translateMessage(key, message, 'encrypt')


def decryptMessage(key, message):
    return translateMessage(key, message, 'decrypt')


def translateMessage(key, message, mode):
    translated = ''
    chA = LETTERS
    chB = key
    if mode == 'decrypt':
    
        chA, chB = chB, chA

    
    for symbol in message:
        if symbol.upper() in chA:
           
            symIndex = chA.find(symbol.upper())
            if symbol.isupper():
                translated += chB[symIndex].upper()
            else:
                translated += chB[symIndex].lower()
        else:
            
            translated += symbol

    return translated


def getRandomKey():
    key = list(LETTERS)
    random.shuffle(key)
    return ''.join(key)

main()

OUTPUT

Using key : QWERTYUIOPASDFGHJKLZXCVBNM

The encrypted message is :

Qss gxk rktqdl eqf egdt zkxt, oy vt iqct zit egxkqut zg hxklxt zitd

 

No comments:

Post a Comment

Please do not any spam link in Comment Box