Design a Product Cipher using Substitution Ciphers || Python
In this we are going to see a basic example to design a product cipher using substitution ciphers in Python Programming Language.



from ctypes import sizeof
import math

small = list(map(chr,range(ord('a'),ord('z')+1)))
caps = list(map(chr,range(ord('A'),ord('Z')+1)))
alphabets = small+caps
spch=[" ","%"]

def getSbCipher(pt, sbk):
    sbCipher=""
    for alph in pt:
        if alph not in spch:
            sbCipher+=alphabets[(alphabets.index(alph)+sbk)%52]
        else:
            sbCipher+=spch[1]

    print(sbCipher)
    return sbCipher

def getTCipherMatrix(sbCipher, tk):
    row=math.ceil(len(sbCipher)/tk)
    col=tk
    TCipherMat=[]
    c=tk
    #print(TCipher)
    k=0
    for i in range(0,row):
        rows=[]
        for j in range(0,col):
            #k=(i*(tk-1))+j
            if (k<=len(sbCipher)):
                #print(sbCipher[k], i, j)
                rows.append(sbCipher[k])
                k+=1
            else:
                break
        TCipherMat.append(rows)
    print("Transpose matrix = ", TCipherMat)
    return TCipherMat,len(TCipherMat)

def Encode(tCipher, row, col):
    cipher = ""
    for r in range(col):
        for c in range(row):
            cipher += tCipher[c][r]
    return cipher

def decrypt(tCipher):
    pt = ""
    for i in range(len(tCipher)):
        for j in range(len(tCipher[i])):
            pt += tCipher[i][j]
    return pt

def Decode(tCipher, key=2):
    dt = ""
    for ciph in tCipher:
        if ciph == "%":
            dt += " "
        else:
            pos = alphabets.index(ciph)
            dt += alphabets[(pos-key) % 52]
    return dt


def main():
    pt = input("Enter Plaintext: ")
    sbk = int(input("Enter Substitution key: "))
    SbCipher=getSbCipher(pt,sbk)
    tk = int(input("Enter Transposition key: "))
    tCipher,row = getTCipherMatrix(SbCipher, tk)
    #getTCipher(SbCipher, tk)
    # print("rows = ",row)
    print("Transposition Cipher = ",Encode(tCipher, row, tk))
    dt = decrypt(tCipher)
    print("Decoded Plaintext = ", Decode(dt, sbk))


main()



#ENJOY CODING


Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post