Challenge: Implementing XOR Encryption
Taak
Swipe to start coding
Now, we will create a simple function that implements XOR encoding.
Your task is to use the XOR operation inside the xor_encode()
function to provide encoding.
Oplossing
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
# Example usage:
plaintext_message = "Hello, XOR Encoding!"
encryption_key = "secretkey"
# XOR Encoding
encoded_message = xor_encode(plaintext_message, encryption_key)
print(f"Original Message: {plaintext_message}")
print(f"Encoded Message: {encoded_message}")
Was alles duidelijk?
Bedankt voor je feedback!
Sectie 3. Hoofdstuk 5
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
# Example usage:
plaintext_message = "Hello, XOR Encoding!"
encryption_key = "secretkey"
# XOR Encoding
encoded_message = xor_encode(plaintext_message, encryption_key)
print(f"Original Message: {plaintext_message}")
print(f"Encoded Message: {encoded_message}")
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.