Prac 2:Ins
1.Vernam cipher
 Code:-
def vernam_encrypt(plaintext, key):
    if len(plaintext)!=len(key):
        raise ValueError("key must be same length as plaintext.")
    return ''.join(chr(ord(p)^ ord(k)) for p,k in zip(plaintext,key))
def vernam_decrypt(ciphertext,key):
    return vernam_encrypt(ciphertext,key)
plaintext=input("enter text to encrypt:")
key=input("please enter key same length as text:")
ciphertext=vernam_encrypt(plaintext,key)
print("Encrypted:",ciphertext)
decrypt=vernam_decrypt(ciphertext,key)
print("Decrypted:",decrypt)
Output:-
2.Playfair cipher
Code:-
def prepare_key_matrix(key):
    key=key.upper().replace("J","I")
    seen=set()
    key_matrix=[]
    for char in key:
        if char not in seen and char.isalpha():
            seen.add(char)
            key_matrix.append(char)
    for char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
        if char not in seen:
            seen.add(char)
            key_matrix.append(char)
    return [key_matrix[i:i+5] for i in range (0,25,5)]
def find_position(matrix,char):
    for row_idx,row in enumerate(matrix):
        if char in row:
            return row_idx,row.index(char)
    return None,None
def encrypt_digraph(digraph,matrix):
    a,b=digraph
    row1,col1=find_position(matrix, a)
    row2,col2=find_position(matrix, b)
    if row1== row2:
        return matrix[row1][(col1 +1)%5] +matrix[row2][(col2 +1)%5]
    elif col1 == col2:
        return matrix[(row1 +1)%5][col1] +matrix[(row2+1)%5][col2]
    else:
        return matrix[row1][col2]+matrix[row2][col1]
def prepare_plaintext(text)    :
    text=text.upper().replace("J","I").replace(" ","")
    cleaned=[]
    i=0
    while i<len(text):
        a=text[i]
        b=text[i+1] if i+1 <len(text) else "X"
        if a==b:
            cleaned.append(a +"X")
            i+=1
        else:
            cleaned.append(a+b)
            i+=2
    if len(cleaned[-1]) ==1:
        cleaned[-1] +="X"
    return cleaned
def playfair_encrypt(plaintext,key):
    matrix=prepare_key_matrix(key)
    digraphs=prepare_plaintext(plaintext)
    ciphertext=''.join(encrypt_digraph(pair,matrix) for pair in digraphs)
    return ciphertext
cipher=playfair_encrypt("hell o","monarchy")
print(cipher)
Output:-
