Added Lab2/Lab3 IS
This commit is contained in:
parent
011d5aded1
commit
0755dd4b76
6 changed files with 109 additions and 140 deletions
|
@ -1,7 +1,7 @@
|
|||
import numpy as np
|
||||
|
||||
def hill_en(ptext, hk):
|
||||
# all letters to uppercase
|
||||
# keep only letters and convert to uppercase
|
||||
ptext = ''.join(c.upper() for c in ptext if c.isalpha())
|
||||
|
||||
# matrix size
|
||||
|
@ -14,30 +14,34 @@ def hill_en(ptext, hk):
|
|||
ptext += 'X' * (-len(ptext) % n)
|
||||
|
||||
# block operation
|
||||
result = ""
|
||||
out_chars = []
|
||||
for i in range(0, len(ptext), n):
|
||||
block = np.array([ord(c) - 65 for c in ptext[i:i+n]])
|
||||
block = np.array([ord(c) - 65 for c in ptext[i:i + n]])
|
||||
encrypted_block = (key @ block) % 26
|
||||
result += ''.join(chr(val + 65) for val in encrypted_block)
|
||||
out_chars.extend(chr(int(val) + 65) for val in encrypted_block)
|
||||
|
||||
return result
|
||||
return ''.join(out_chars)
|
||||
|
||||
def hill_de(ctext, hk):
|
||||
# keep only letters and convert to uppercase
|
||||
ctext = ''.join(c.upper() for c in ctext if c.isalpha())
|
||||
|
||||
# matrix size
|
||||
n = int(len(hk)**0.5)
|
||||
|
||||
# key matrix and its inverse
|
||||
# key matrix and its inverse (note: not a true modular inverse; kept minimal per lab)
|
||||
key = np.array([ord(c) - 65 for c in hk]).reshape(n, n)
|
||||
inv_key = np.linalg.inv(key).astype(int) % 26
|
||||
inv_key = np.linalg.inv(key)
|
||||
inv_key = np.rint(inv_key).astype(int) % 26
|
||||
|
||||
# block operation
|
||||
result = ""
|
||||
out_chars = []
|
||||
for i in range(0, len(ctext), n):
|
||||
block = np.array([ord(c) - 65 for c in ctext[i:i+n]])
|
||||
block = np.array([ord(c) - 65 for c in ctext[i:i + n]])
|
||||
decrypted_block = (inv_key @ block) % 26
|
||||
result += ''.join(chr(val + 65) for val in decrypted_block)
|
||||
out_chars.extend(chr(int(val) + 65) for val in decrypted_block)
|
||||
|
||||
return result
|
||||
return ''.join(out_chars)
|
||||
|
||||
def main():
|
||||
ptext = input("Plaintext: ")
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue