




Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!





Criptografia i Seguretat
1. We have an encrypted message “𝑉 𝑅𝐵𝑋𝑄𝑆𝐻𝑆𝐿𝑄𝐿𝑂𝑂𝑅” , which has been encrypted using a simple substitution (mono-alphabetic) cipher, as 𝑐𝑖 = 𝑚𝑖 + 𝑘(𝑚𝑜𝑑𝑛) with an unkown 𝑘 and 𝑛 = 26. The alphabet used is:
[1]: import matplotlib.pyplot as plt import matplotlib.image as mpimg
image = mpimg.imread("img1.png") plt.imshow(image) plt.axis('off') plt.show()
Find the value for k and the original message.
[2]: import string
#crear diccionari de lletres abc. dic = {} i= 0 for letter in list(string.ascii_uppercase): dic[i] = letter i+= 1
def decrypt(encrypted, n, k): #n= espai / k= núm de claus a provar (màx = n) original = ''
while k > 0 :
for letter in encrypted: indx = list(dic.values()).index(letter) #index de la lletra m_letter = indx - k % n #càlcul amb cèsar if m_letter < 0 : #en cas de tenir negatiu m_letter = n - abs(m_letter) original += dic[m_letter]
print('Original message with k =',k,':',original) original = '' k-= 1
[3]: decrypt('VRBXQSHSLQLOOR',n = 26 , k= 10 )
Original message with k = 10 : LHRNGIXIBGBEEH Original message with k = 9 : MISOHJYJCHCFFI Original message with k = 8 : NJTPIKZKDIDGGJ Original message with k = 7 : OKUQJLALEJEHHK Original message with k = 6 : PLVRKMBMFKFIIL Original message with k = 5 : QMWSLNCNGLGJJM Original message with k = 4 : RNXTMODOHMHKKN Original message with k = 3 : SOYUNPEPINILLO Original message with k = 2 : TPZVOQFQJOJMMP Original message with k = 1 : UQAWPRGRKPKNNQ
[4]: decrypt('EHFJEQZHEKTPEXH', n = 26 , k= 10 )
Original message with k = 10 : UXVZUGPXUAJFUNX Original message with k = 9 : VYWAVHQYVBKGVOY Original message with k = 8 : WZXBWIRZWCLHWPZ Original message with k = 7 : XAYCXJSAXDMIXQA Original message with k = 6 : YBZDYKTBYENJYRB Original message with k = 5 : ZCAEZLUCZFOKZSC Original message with k = 4 : ADBFAMVDAGPLATD Original message with k = 3 : BECGBNWEBHQMBUE Original message with k = 2 : CFDHCOXFCIRNCVF Original message with k = 1 : DGEIDPYGDJSODWG
[5]: import time
i_time = time.time()
Tant la lletra 𝑎 com el diagrama 𝑛𝑦 mantenen la seva freqüència ja que apareixeran el mateix nombre de vegades al text xifrat (no hi hauria canvis). Tot i així, el diagrama 𝑛𝑦 pot no mantenir la seva freqüència original ja que la tranposició canvia la posició de les lletres i pot trencar amb la seqüència.
[6]: key_space_size = pow( 26 , 5 ) #fer la potència amb qualsevol exponent print(key_space_size)
11881376 ANSWER: La mida de l’espai de claus són les diferents combinacions possibles de claus que hi podem tenir respecte l’espai modular que hi treballem. Per tant, per 𝑛 = 26 i 𝑟 = 5, l’espai actual és 11881376 claus possibles.
[7]: #funció per encriptar amb cèsar def encrypt(m, n, k):
for letter in m: indx = list(dic.values()).index(letter) #index de la lletra k = list(dic.values()).index(k) #index de la clau m_letter = (indx + k) % n #càlcul amb cèsar
m_letter = dic[m_letter]
return m_letter
[8]: def encrypt_vigenere(message, n, seq): new_seq = '' encrypted = ''
for letter in range(len(message)): new_seq += seq[letter % len(seq)] #print(new_seq)
pairs = zip(message, new_seq) #per visualitzar --> list #print(list(pair))
for pair in pairs: m=pair[ 0 ] k=pair[ 1 ] encrypted += encrypt(m,n,k) return 'Encrypted message: '+str(encrypted)
[9]: encrypt_vigenere('VOLANDOVOYVOLANDOVENGO', 26 , 'CAMARON')
[9]: 'Encrypted message: XOXAERBXOKVFZNPDAVVBTQ'
[10]: def find_key(message, encrypted, n): seq = '' pairs = zip(message, encrypted) for pair in pairs: a = pair[ 0 ] b = pair[ 1 ]
indx_a = list(dic.values()).index(a) indx_b = list(dic.values()).index(b)
key = (indx_b - indx_a) % n if key < 0 : key = n - key seq += dic[key]
return seq
11: find_key("COMELVALLESNOHIHARES", "OCXEXJLLXSDNAVTHMFPS", 26 )
ANSWER: The key is MOLA
5. The Hill cipher is a substitution cipher based on the use of matrices. * (a) Encrypt the message “BARCELONA” using the Hill cipher with the same key K as the previous example.
# calcular la matriu adjunta i multiplicar-la per la inversa modular ␣ ↪ del determinant adjugate = np.round(det_k * np.linalg.inv(key)).astype(int) key_inv = (det_k_inv * adjugate) % n # matriu inversa
print(f"ÈXIT: Determinant : { det_k } :)") else : print("ERROR: Matriu no invertible :(") key_inv = None
return key_inv
def hill_decrypt(encrypted, key, n):
message = '' encrypted_message = [] key_sizes = key.shape[ 1 ] #de la col k_inv = inv_matrix(key,n)
for letter in encrypted: encrypted_message.append(list(dic.values()).index(letter))
encrypted_message = [encrypted_message[i:i+key_sizes] for i in ␣ ↪range( 0 ,len(encrypted_message),key_sizes)]
for block in encrypted_message: array = np.array(block).reshape(- 1 , 1 ) mi = (np.dot(k_inv,array)% n ).astype(int) mi.tolist() for digit in mi: message += dic[int(digit)]
return 'Decrypted message: '+str(message)
[15]: hill_decrypt('XELOEKSVVRQXAMQSZIEGCMGSULBYZYQDRKYEQKKUQEIEH', key, 26 )
ÈXIT: Determinant : -25 :)
[15]: 'Decrypted message: PERQUELESTEVESCARICIESSONMESDELICIOSESQUEELVI'
[16]: #comprovar que realment funciona -> agafem el missatge encriptat de l'apartat ␣ ↪ anterior (BARCELONA) hill_decrypt('BKLFDICFW', key, 26 )
ÈXIT: Determinant : -25 :)
[16]: 'Decrypted message: BARCELONA'
6. In a Hill cipher using matrices, Alice wants to use the key “POOL” while Bob wants to use “SWIM.” Who should we trust?
[17]: import math
#comprovarem si alguna de les dues claus és invertible o no per tal de decidir ␣ ↪ si realment són bones claus o no
def convert_to_matrix(key):
matrix_key = []
for letter in key: matrix_key.append(list(dic.values()).index(letter)) matrix_key= np.array(matrix_key).reshape(int(math.sqrt(len(key))), int(math. ↪sqrt(len(key))))
return matrix_key
[18]: matrix_key = convert_to_matrix("POOL") inv_matrix(matrix_key,n= 26 )
ÈXIT: Determinant : -31 :)
[18]: array([[ 3, 8], [ 8, 23]])
[19]: matrix_key2 = convert_to_matrix("SWIM") inv_matrix(matrix_key2,n= 26 )
ERROR: El determinant 40 no té inversa modular en mod 26. ANSWER: Per tant, la clau 𝑘 que s’hauria d’agafar pel Hill cipher serà 𝑃 𝑂𝑂𝐿.