Contenu du cours
Fondamentaux de la Cybersécurité
Fondamentaux de la Cybersécurité
Décryptage XOR
Nous avons déjà examiné comment fournir un chiffrement XOR dans le chapitre précédent. Mais qu'en est-il du déchiffrement ?
Voyons le code suivant:
# Encoding function def xor_encode(text, key): # Convert text and key to binary strings binary_text = ''.join(format(ord(char), '08b') for char in text) binary_key = ''.join(format(ord(char), '08b') for char in key) # Repeat the key to match the length of the text repeated_key = (binary_key * (len(binary_text) // len(binary_key) + 1))[:len(binary_text)] # XOR each bit of the text with the corresponding bit of the key encoded_text = ''.join(str(int(bit_text) ^ int(bit_key)) for bit_text, bit_key in zip(binary_text, repeated_key)) return encoded_text # Decoding function def xor_decode(encoded_text, key): # Convert encoded text and key to binary strings binary_encoded_text = encoded_text binary_key = ''.join(format(ord(char), '08b') for char in key) # Repeat the key to match the length of the encoded text repeated_key = (binary_key * (len(binary_encoded_text) // len(binary_key) + 1))[:len(binary_encoded_text)] # XOR each bit of the encoded text with the corresponding bit of the key decoded_text = ''.join(str(int(bit_encoded) ^ int(bit_key)) for bit_encoded, bit_key in zip(binary_encoded_text, repeated_key)) # Convert the binary string back to characters decoded_text = ''.join(chr(int(decoded_text[i:i+8], 2)) for i in range(0, len(decoded_text), 8)) return decoded_text # Example usage: encoded_message = xor_encode("Hello, XOR Decoding!", "secretkey") # XOR Decoding decoded_message = xor_decode(encoded_message, "secretkey") print(f"Encoded Message : {encoded_message}") print(f"Decoded Message : {decoded_message}")
La fonction de décodage est presque identique à l'encodage ; la seule différence est la présence de la ligne supplémentaire qui décode la représentation binaire au format texte (ligne 28
).
Tout était clair ?
Merci pour vos commentaires !
Section 3. Chapitre 6