简体   繁体   English

python中的xor函数

[英]xor function in python

I'll be happy if someone can help with XOR function in python. 如果有人可以在python中使用XOR功能,我会很高兴。

for example, I have two quite big messages (about 300 symbols) that is writteb by hex code how can I XOR them properly? 例如,我有两个相当大的消息(大约300个符号),它们是用十六进制代码写的,我如何正确地对它们进行XOR? I tried use general functions and converted to another types, but I wasn't able to do that( 我尝试使用通用函数并将其转换为其他类型,但我无法做到这一点(

I don't know which type of data I need to convert for? 我不知道我需要转换哪种数据类型?

If I get your question correctly, if you have 2 hex numbers represented as string: 如果我的问题正确无误,如果您有2个十六进制数字表示为字符串:

a = "e877a5e68bea88d61b93ac5ee0d562e8e9"
b = "23fe3231699ade23482"

you can xor any of them with some mask, by converting to int, and applying bitwise xor operator: 您可以通过将其转换为int并应用按位xor运算符来使用掩码对它们中的任何一个进行异或:

xor_result = int(a, 16) ^ int(b, 16)

print '%x' % xor_result

and, if you want to keep the original format 并且,如果您想保留原始格式

string_xor_result = hex(xor_result)[2:]

Iterate over the string chars, then convert each char to int ( int(a,16) ), then apply xor, reconvert to hex with hex , strip the leading '0x' with [2:] , and finally join everything 遍历字符串chars,然后将每个char转换为int( int(a,16) ),然后应用xor,用hex转换为hex,用[2:]去除开头的“ 0x”,最后加入所有内容

stra = 'abc'
strb = 'abd'
''.join(hex( int(a,16) ^ int(b,16) )[2:] for a,b in zip(stra, strb))

Note that, as pointed in the comments, it will work only if the two strings have the same length. 请注意,正如注释中指出的那样,仅当两个字符串的长度相同时,它才有效。 Otherwise some chars of the longer string will be ignored. 否则,较长字符串的一些字符将被忽略。

If two strings do not have the same length you can add one line, cycle() 如果两个字符串的长度不同,则可以添加一行cycle()

stra = raw_input("msg: ")
strb = raw_input("key: ")
strb = cycle(strb)

print ''.join(hex( int(a,16) ^ int(b,16) )[2:] for a,b in zip(stra, strb))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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