CoolFace
Apppublic

krish07211/encryption-decryption-tool

sourceHugging Facemitupdated 8mo agoView on Hugging Face
0likes
app.py227 linesDownload Raw Back to root
1import streamlit as st2import numpy as np3import random4import string5 6# ---------------- Caesar Cipher ----------------7def caesar_encrypt(text, shift):8    result = ""9    for char in text:10        if char.isalpha():11            base = ord('A') if char.isupper() else ord('a')12            result += chr((ord(char) - base + shift) % 26 + base)13        else:14            result += char15    return result16 17def caesar_decrypt(text, shift):18    return caesar_encrypt(text, -shift)19 20 21# ---------------- Playfair Cipher ----------------22def generate_playfair_matrix(key):23    key = "".join(dict.fromkeys(key.upper().replace("J", "I")))24    alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"25    matrix = key + "".join([c for c in alphabet if c not in key])26    return np.array(list(matrix)).reshape(5,5)27 28def playfair_encrypt_pair(pair, matrix):29    pos = {matrix[i,j]: (i,j) for i in range(5) for j in range(5)}30    a, b = pair31    ra, ca = pos[a]; rb, cb = pos[b]32    if ra == rb:  33        return matrix[ra,(ca+1)%5] + matrix[rb,(cb+1)%5]34    elif ca == cb:  35        return matrix[(ra+1)%5,ca] + matrix[(rb+1)%5,cb]36    else:  37        return matrix[ra,cb] + matrix[rb,ca]38 39def playfair_decrypt_pair(pair, matrix):40    pos = {matrix[i,j]: (i,j) for i in range(5) for j in range(5)}41    a, b = pair42    ra, ca = pos[a]; rb, cb = pos[b]43    if ra == rb:  44        return matrix[ra,(ca-1)%5] + matrix[rb,(cb-1)%5]45    elif ca == cb:  46        return matrix[(ra-1)%5,ca] + matrix[(rb-1)%5,cb]47    else:  48        return matrix[ra,cb] + matrix[rb,ca]49 50def playfair_encrypt(text, key):51    if not key: return "Please enter a keyword"52    matrix = generate_playfair_matrix(key)53    text = "".join([c for c in text.upper().replace("J","I") if c.isalpha()])54    pairs = []55    i = 056    while i < len(text):57        a = text[i]58        if i+1 < len(text):59            b = text[i+1]60            if a == b:61                pairs.append((a,"X"))62                i += 163            else:64                pairs.append((a,b))65                i += 266        else:67            pairs.append((a,"X"))68            i += 169    return "".join(playfair_encrypt_pair(p,matrix) for p in pairs)70 71def playfair_decrypt(text, key):72    if not key: return "Please enter a keyword"73    matrix = generate_playfair_matrix(key)74    text = "".join([c for c in text.upper().replace("J","I") if c.isalpha()])75    if len(text) % 2 != 0: return "Invalid Ciphertext length"76    77    pairs = [(text[i], text[i+1]) for i in range(0, len(text), 2)]78    decrypted_text = "".join(playfair_decrypt_pair(p, matrix) for p in pairs)79    80    final_result = ""81    for i in range(len(decrypted_text)):82        if i > 0 and i < len(decrypted_text) - 1:83            if decrypted_text[i] == 'X' and decrypted_text[i-1] == decrypted_text[i+1]:84                continue # Skip the X85        final_result += decrypted_text[i]86    87    return final_result.rstrip('X')88 89 90# ---------------- Hill Cipher (Improved Math) ----------------91def modInverse(a, m):92    for x in range(1, m):93        if (((a % m) * (x % m)) % m == 1):94            return x95    return -196 97def mod_inverse_matrix(matrix, modulus=26):98    # For 2x2 matrix: [[a, b], [c, d]]99    a, b, c, d = matrix[0,0], matrix[0,1], matrix[1,0], matrix[1,1]100    det = (a*d - b*c) % modulus101    det_inv = modInverse(det, modulus)102    if det_inv == -1:103        return None104    # Adjugate matrix mod 26105    inv_matrix = np.array([[d, -b], [-c, a]]) * det_inv106    return inv_matrix % modulus107 108def hill_encrypt(text, key_matrix):109    text = "".join([c for c in text.upper() if c.isalpha()])110    while len(text) % 2 != 0:111        text += "X"112    result = ""113    for i in range(0, len(text), 2):114        vec = np.array([ord(text[i])-65, ord(text[i+1])-65])115        enc = np.dot(key_matrix, vec) % 26116        result += chr(int(enc[0])+65) + chr(int(enc[1])+65)117    return result118 119def hill_decrypt(cipher, key_matrix):120    inv_matrix = mod_inverse_matrix(key_matrix, 26)121    if inv_matrix is None: return "Matrix is not invertible!"122    cipher = "".join([c for c in cipher.upper() if c.isalpha()])123    result = ""124    for i in range(0, len(cipher), 2):125        vec = np.array([ord(cipher[i])-65, ord(cipher[i+1])-65])126        dec = np.dot(inv_matrix, vec) % 26127        result += chr(int(dec[0])+65) + chr(int(dec[1])+65)128    129    # This line removes the padding 'X' at the very end130    return result.rstrip('X')131 132 133# ---------------- One-Time Pad ----------------134def generate_key(length):135    return ''.join(random.choice(string.ascii_uppercase) for _ in range(length))136 137def otp_encrypt(message, key):138    message = "".join([c for c in message.upper() if c.isalpha()])139    key = "".join([c for c in key.upper() if c.isalpha()])140    if len(key) < len(message): return "Key is too short!"141    result = ""142    for m,k in zip(message,key):143        result += chr(((ord(m)-65)+(ord(k)-65))%26 + 65)144    return result145 146def otp_decrypt(cipher, key):147    cipher = "".join([c for c in cipher.upper() if c.isalpha()])148    key = "".join([c for c in key.upper() if c.isalpha()])149    if len(key) < len(cipher): return "Key is too short!"150    result = ""151    for c,k in zip(cipher,key):152        result += chr(((ord(c)-65)-(ord(k)-65))%26 + 65)153    return result154 155 156# ---------------- Streamlit GUI ----------------157st.set_page_config(page_title="Cipher GUI", layout="wide")158st.title("๐Ÿ” Substitution Cipher GUI")159 160cipher_choice = st.sidebar.radio("Select Cipher:", 161                                 ["Caesar Cipher", "Playfair Cipher", "Hill Cipher", "One-Time Pad"])162 163col1, col2 = st.columns(2)164 165if cipher_choice == "Caesar Cipher":166    with col1:167        st.header("Encrypt")168        msg = st.text_area("Message to encrypt:", key="caesar_enc")169        shift = st.number_input("Shift:", min_value=0, max_value=25, value=3, key="caesar_enc_shift")170        if st.button("Encrypt", key="caesar_enc_btn"):171            st.success(caesar_encrypt(msg, shift))172    with col2:173        st.header("Decrypt")174        msg = st.text_area("Message to decrypt:", key="caesar_dec")175        shift = st.number_input("Shift:", min_value=0, max_value=25, value=3, key="caesar_dec_shift")176        if st.button("Decrypt", key="caesar_dec_btn"):177            st.success(caesar_decrypt(msg, shift))178 179elif cipher_choice == "Playfair Cipher":180    with col1:181        st.header("Encrypt")182        msg = st.text_area("Message to encrypt:", key="playfair_enc")183        key = st.text_input("Keyword:", key="playfair_key_enc")184        if st.button("Encrypt", key="playfair_enc_btn"):185            st.success(playfair_encrypt(msg, key))186    with col2:187        st.header("Decrypt")188        msg = st.text_area("Message to decrypt:", key="playfair_dec")189        key = st.text_input("Keyword:", key="playfair_key_dec")190        if st.button("Decrypt", key="playfair_dec_btn"):191            st.success(playfair_decrypt(msg, key))192 193elif cipher_choice == "Hill Cipher":194    with col1:195        st.header("Encrypt")196        msg = st.text_area("Message to encrypt:", key="hill_enc")197        st.write("Using fixed key matrix [[3,3],[2,5]]")198        key_matrix = np.array([[3,3],[2,5]])199        if st.button("Encrypt", key="hill_enc_btn"):200            st.success(hill_encrypt(msg, key_matrix))201    with col2:202        st.header("Decrypt")203        msg = st.text_area("Message to decrypt:", key="hill_dec")204        st.write("Using fixed key matrix [[3,3],[2,5]]")205        key_matrix = np.array([[3,3],[2,5]])206        if st.button("Decrypt", key="hill_dec_btn"):207            st.success(hill_decrypt(msg, key_matrix))208 209elif cipher_choice == "One-Time Pad":210    with col1:211        st.header("Encrypt")212        msg = st.text_area("Message to encrypt:", key="otp_enc")213        if st.button("Generate Key", key="otp_key_btn"):214            st.session_state['otp_key'] = generate_key(len(msg))215            st.info(f"Generated Key: {st.session_state['otp_key']}")216        217        current_key = st.session_state.get('otp_key', "")218        key = st.text_input("Key:", value=current_key, key="otp_key_enc")219        220        if st.button("Encrypt", key="otp_enc_btn"):221            st.success(otp_encrypt(msg, key))222    with col2:223        st.header("Decrypt")224        msg = st.text_area("Message to decrypt:", key="otp_dec")225        key = st.text_input("Key:", value=st.session_state.get('otp_key', ""), key="otp_key_dec")226        if st.button("Decrypt", key="otp_dec_btn"):227            st.success(otp_decrypt(msg, key))