# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# The goal is to use matrix for encryption and decryption. We can use a matrix as an encryption key and it's inverse matrix as decryption 
# key. In the following post illustrate the process. 

import numpy as np

ak = np.matrix = [ [2,1], [3,2]]  # Encryption key

dk = np.matrix= [ [2, -1], [-3, 2] ] # Decryption key

# Each character will represent with numbers as follows
repres_num = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13,
     'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26, ' ': 27}

# Following is our plaintext message
plain_text = 'prepare to negotiate'

# +
# Let's represent our plain_text with corresponding number value
# We will create list with number values
# Then we will create numpy array and will reshape according to our need
# as our Encryption matrix is 2 x 2. So we need to create 2 x n matrix in order 
# generate encrypted matrix by multiplying with the encryption key

hold = []
for i in plain_text:
    hold.append(repres_num[i])
trans = np.asarray(hold).reshape(2, len(hold)//2)
# -

trans

cipher = np.dot(ak, trans)

cipher  # this is our cipher text matrix

# we can decrypt with the decryption key
decipher = np.dot(dk, cipher)

decipher

# Above we got back our original translated palintext matrix.
# we can get back the plain text using the dictionary we created 
dec = decipher.ravel().tolist()

dec

PT = ""
for i in dec:
    PT += list(repres_num.keys())[list(repres_num.values()).index(i)]
    

PT

StarcoderdataJupyterScriptsDedupFiltered