简体   繁体   中英

stuck in a python code for encryption. error is Unknown format code 'x' for object of type 'str'

I am very new to programming and cryptography, but I took part in a CTF competition where the provided us with a hex and we are supposed to crack it. Through some work and research, I got this code

import binascii
my_ciphertext =    "0f05080e1220360106190c3610061c360207061e361e01081d4e1a2e0600070e362607210c1b0c4814"
binary_rep_of_ciphertext = binascii.unhexlify(my_ciphertext)# makes it binary
array_of_ciphertext = bytearray(binary_rep_of_ciphertext)#makes binary things to array elements

def xor_string_and_char(my_char_value):
    result= ''.join([chr(cc ^ my_char_value) for cc in array_of_ciphertext])
    return '{:x}'.format(result)     # convert back to hexadecimal

x = 0 
assert x==0
while x in range(255):
    my_plaintext = xor_string_and_char(x)
    print('b' + my_plaintext)
    x=x+1

but I keep getting an error, and I dont know how to fix it. I am not sure what is wrong with the code cause I am not good at python at all (ps: please use newbie language to explain) error: Unknown format code 'x' for object of type 'str'

The problem is that the formatting to hexadecimals is not provided for strings, which are used to represent a single character / byte in your code. Actually, you should use integers to represent bytes, and integer arrays to represent multiple bytes where each integer is in the range 0..255 inclusive.

Strings in Python are fortunately used for text, consisting of characters rather than bytes, and they should not be used to represent bytes. If your cryptographic algorithm inputs / output bytes (which is the commonly the case if you use XOR) then strings should not be used other than for reporting / debugging purposes.

If you want to present a string as hex, then you can use hexlify which is the reverse of unhexlify used in your code. But it seems rather an old school method as Python >= 3.5 seems to supply other methods to handle byte arrays and hexadecimal encoding / decoding ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM