Docsity
Docsity

Prepara tus exámenes
Prepara tus exámenes

Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity


Consigue puntos base para descargar
Consigue puntos base para descargar

Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium


Orientación Universidad
Orientación Universidad


Problemes I Criptografia, Ejercicios de Criptografía y Seguridad del Sistema

Problemes de part del tema 1 d'Enginyeria de Dades

Tipo: Ejercicios

2024/2025

Subido el 04/11/2025

odette-16
odette-16 🇪🇸

2 documentos

1 / 8

Toggle sidebar

Esta página no es visible en la vista previa

¡No te pierdas las partes importantes!

bg1
problemes 1
March 5, 2025
Criptografia i Seguretat
### Exercises Classical Cryptography
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:
1
pf3
pf4
pf5
pf8

Vista previa parcial del texto

¡Descarga Problemes I Criptografia y más Ejercicios en PDF de Criptografía y Seguridad del Sistema solo en Docsity!

problemes 1

March 5, 2025

Criptografia i Seguretat

Exercises Classical Cryptography

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

  • ANSWER: El valor de 𝑘 per a aquest missatge xifrat és 𝑘 = 3 i el missatge original és: 𝑆𝑂𝑌 𝑈 𝑁 𝑃 𝐸𝑃 𝐼𝑁 𝐼𝐿𝐿𝑂 2. If now the encrypted message is “𝐸𝐻𝐹 𝐽 𝐸𝑄𝑍𝐻𝐸𝐾𝑇 𝑃 𝐸𝑋𝐻” , use the same program to find the worst time to find the original message. Can we find the 𝑘 used? Is this cryptographic method secure?

[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.

  • What happens if we use a simple or monoaphabetic substitution? Will the sub- stituted symbols keep the same frequency in both cases? Hauríem de considerar primer la diferència entre substitució monoalfabètica i polialfabètica ja que els efectes sobre la freqüència de lletres i diagrames són diferents. Substitució monoalfabètica: tant la freqüència de les lletres com la dels diagrames es mantenen perquè cada lletra del text original es reemplaça sempre per la mateixa lletra en el text xifrat. Substitució polialfabètica: al utilitzar múltiples alfabetitzacions, la substituciño de les lletres dependrà de la seva posició en el text. En el cas d’una lletra com la 𝑎, no es manté la mateixa freqüència perquè una mateixa lletra pot ser substituïda per molts símbols segons el context, mentre que amb els diagrames no passa això. 4. The Vigenère method is a polyalphabetic substituion cipher with a variable length key.
  • (a) If n = 26 and r = 5, what is the size of the key space?

[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.

  • (b) Encrypt the message “𝑉 𝑂𝐿𝐴𝑁 𝐷𝑂𝑉 𝑂𝑌 𝑉 𝑂𝐿𝐴𝑁 𝐷𝑂𝑉 𝐸𝑁 𝐺𝑂” (without spaces) with the key “𝐶𝐴𝑀𝐴𝑅𝑂𝑁 ” using the Vigenère cipher and the previous alphabet of size 𝑛 = 26.

[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'

  • (c) We know that the cleartext “𝐶𝑂𝑀𝐸𝐿𝑉 𝐴𝐿𝐿𝐸𝑆𝑁 𝑂𝐻𝐼𝐻𝐴𝑅𝐸𝑆” has been encrypted as the cipher text “𝑂𝐶𝑋𝐸𝑋𝐽 𝐿𝐿𝑋𝑆𝐷𝑁 𝐴𝑉 𝑇 𝐻𝑀𝐹 𝑃 𝑆”. We also know that the key length is 𝑟 = 4. Can you f ind the key?

[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à 𝑃 𝑂𝑂𝐿.