Skip to content

Latest commit

 

History

History
61 lines (50 loc) · 1.7 KB

887.md

File metadata and controls

61 lines (50 loc) · 1.7 KB

Playfair Cipher

Python script:

PLAYFAIR_CIPHER_GRID =[
    'Q', 'W', 'E', 'R', 'T',
    'Y', 'U', 'I', 'O', 'P',
    'A', 'S', 'D', 'F', 'G',
    'H', 'K', 'L', 'Z', 'X',
    'C', 'V', 'B', 'N', 'M'
]

ciphertext="MQDzqdor{Ix4Oa41W_1F_B00h_m1YlqPpPP}"

def find_next_alpha(p):
    while p < len(ciphertext) and not ciphertext[p].isalpha():
        p+=1
    return p

i = 0
while True:
    start = i
    i = find_next_alpha(i)
    j = find_next_alpha(i+1)
    if i >= len(ciphertext) or j >= len(ciphertext):
        for k in range(start,len(ciphertext)):
            print(ciphertext[k], end="")
        break

    x,y = ciphertext[i], ciphertext[j]
    posx, posy = PLAYFAIR_CIPHER_GRID.index(x.upper()), PLAYFAIR_CIPHER_GRID.index(y.upper())
    rowx, colx = divmod(posx, 5)
    rowy, coly = divmod(posy, 5)

    pr=[]
    if rowx == rowy and colx == coly:
        pr = [PLAYFAIR_CIPHER_GRID[(rowx+4)%5*5+(colx+4)%5], PLAYFAIR_CIPHER_GRID[(rowy+4)%5*5+(coly+4)%5]]
    elif colx == coly:
        pr = [PLAYFAIR_CIPHER_GRID[(rowx+4)%5*5+colx], PLAYFAIR_CIPHER_GRID[(rowy+4)%5*5+coly]]
    elif rowx == rowy:
        pr = [PLAYFAIR_CIPHER_GRID[rowx*5+(colx+4)%5], PLAYFAIR_CIPHER_GRID[rowy*5+(coly+4)%5]]
    else:
        pr = [PLAYFAIR_CIPHER_GRID[rowx*5+coly], PLAYFAIR_CIPHER_GRID[rowy*5+colx]]

    if x.islower():
        pr[0] = pr[0].lower()
    if y.islower():
        pr[1] = pr[1].lower()
    
    for k in range(start,i):
        print(ciphertext[k], end="")
    print(pr[0], end="")
    for k in range(i+1,j):
        print(ciphertext[k], end="")
    print(pr[1], end="")

    i = j+1