Jonathan Sanchez
Jonathan Sanchez

Reputation: 33

How to XOR a hex string with a literal string in Python?

My ultimate goal is to encrypt/decrypt a string with a hex string using a linear congruence generator.

I have a list of 'keys' that I want to XOR with a string. For example, the list of keys are ['0x92', '0xe3', 0x18'...] and the string I want to XOR with the keys is 'apple'. The length of the keys list is the same length of the string.

I want to be able to produce a result such as "\xF3\x93\x68...".

I'm not sure how to begin this approach. Should I turn every character in the string to binary and also turn each hex string in binary and XOR them together?

The result that I am looking for (xF3..), is that unicode?

Upvotes: 1

Views: 951

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

Given the length of the keys is equal to the length of the text can simply use a zip and use a join to generate a string:

keys = ['\x92', '\xe3', '\x18']
text = 'app'
result = ''.join(chr(ord(key)^ord(tex)) for key,tex in zip(keys,text))

The code works as follows: zip emits tuples of elements in keys and text: so the result of zip(keys,text) is roughly:

list(zip(keys,text)) == [('\x92', 'a'), ('ã', 'p'), ('\x18', 'p')]

Now we unify key and tex with each of these tuples, so in the first iteration key is '\x92' and tex is 'a'. By calling ord(..) on these elements, we obtain the ASCII code. Next we perform a XOR (^) operation on these ASCII codes and convert this back to the corresponding char(..). We use ''.join(..) to concatenate all these characters together into the resulting string, which is:

result == 'ó\x93h'

Upvotes: 1

Him
Him

Reputation: 5549

Use ord and chr

>>> a = 0x22
>>> a
34
>>> b = ord('Z')
>>> b
90
>>> a^b
120
>>> chr(a^b)
'x'

Upvotes: 0

Related Questions