当前位置: 动力学知识库 > 问答 > 编程问答 >

python - How to XOR literal with a string

问题描述:

I'm trying to implement the Blowfish algorithm in Python. The way I understand it, I have to use a key like "abcd" and then XOR it with a hexadecimal array (cycling the key if necessary)

P = (

0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,

0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,

0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b,

)

The data types here have me very confused. I saw somewhere that 'abcd' = 0x61626364. In that case, XORing the first element of P would simply be 0x61626364 ^ 0x243f6a88.

So, how do I convert a string like 'abcd' to the format 0x?????. or perhaps there's a better way? Any light on this would be very appreciated!

网友答案:

To convert a string to an array of bytes:

b = bytes('abcd', 'ascii')

To convert array of bytes to int:

i = int.from_bytes(b, byteorder='big', signed=False)
网友答案:

Two hexadecimal digits can encode exactly one byte. This makes sense, because each hexadecimal digit can be in 16 different states, so two hexadecimal digits can be in 16 * 16 = 256 different states, which is exactly the same as the number of states representable in a single byte.

Because ASCII characters can also be encoded in a single byte, any ASCII character can be encoded as two hexadecimal digits.

For example, the letter a has character code 97 in ASCII. Converting the decimal number 97 to base 16 (hexadecimal) gives you 0x61.

You can therefore take any string and convert it into a hexadecimal number by taking every character and representing it as two hex digits in your number. Looking at your example above, a = 0x61, b = 0x62, c = 0x63, and d = 0x64. Putting these all together gives you the representation abcd = 0x61626364.

分享给朋友:
您可能感兴趣的文章:
随机阅读: