python中的字节运算(XOR) [英] byte operations (XOR) in python

查看:1036
本文介绍了python中的字节运算(XOR)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    #!/usr/bin/env python3

import binascii


var=binascii.a2b_qp("hello")
key=binascii.a2b_qp("supersecretkey")[:len(var)]

print(binascii.b2a_qp(var))
print(binascii.b2a_qp(key))


#here i want to do an XOR operation on the bytes in var and key and place them in 'encryption': encryption=var XOR key

print(binascii.b2a_qp(encrypted))

如果有人能启发我如何实现这一目标,我将非常高兴.对整个数据类型转换来说,这是一个非常新的东西,是的...通过python Wiki读取并不太像我想要的:(.

If someone could enlighten me on how I could accomplish this I would be very happy. Very new to the whole data-type conversions so yeah...reading through the python wiki is not as clear as I would like :(.

推荐答案

您似乎需要做的是将消息中的每个字符与密钥中的相应字符进行异或.但是,要做到这一点,您需要使用ordchr进行一些相互转换,因为您只能对数字进行异或运算,而不能对字符串进行

It looks like what you need to do is XOR each of the characters in the message with the corresponding character in the key. However, to do that you need a bit of interconversion using ord and chr, because you can only xor numbers, not strings:

>>> encrypted = [ chr(ord(a) ^ ord(b)) for (a,b) in zip(var, key) ] 
>>> encrypted
['\x1b', '\x10', '\x1c', '\t', '\x1d']

>>> decrypted = [ chr(ord(a) ^ ord(b)) for (a,b) in zip(encrypted, key) ]
>>> decrypted
['h', 'e', 'l', 'l', 'o']

>>> "".join(decrypted)
'hello'

请注意,binascii.a2b_qp("hello")只是将一个字符串转换为另一个字符串(尽管可能使用不同的编码).

Note that binascii.a2b_qp("hello") just converts a string to another string (though possibly with different encoding).

仅当密钥至少与消息一样长时,您的方法以及上面的代码才有效.但是,如果需要,您可以使用itertools.cycle轻松重复该键:

Your approach, and my code above, will only work if the key is at least as long as the message. However, you can easily repeat the key if required using itertools.cycle:

>>> from itertools import cycle
>>> var="hello"
>>> key="xy"

>>> encrypted = [ chr(ord(a) ^ ord(b)) for (a,b) in zip(var, cycle(key)) ]
>>> encrypted
['\x10', '\x1c', '\x14', '\x15', '\x17']

>>> decrypted = [ chr(ord(a) ^ ord(b)) for (a,b) in zip(encrypted, cycle(key)) ]
>>> "".join(decrypted)
'hello'

要解决unicode/多字节字符的问题(在下面的评论中提出),可以将字符串(和键)转换为字节,将它们压缩在一起,然后执行XOR,例如:

To address the issue of unicode/multi-byte characters (raised in the comments below), one can convert the string (and key) to bytes, zip these together, then perform the XOR, something like:

>>> var=u"hello\u2764"
>>> var
'hello❤'

>>> encrypted = [ a ^ b for (a,b) in zip(bytes(var, 'utf-8'),cycle(bytes(key, 'utf-8'))) ]
>>> encrypted
[27, 16, 28, 9, 29, 145, 248, 199]

>>> decrypted = [ a ^ b for (a,b) in zip(bytes(encrypted), cycle(bytes(key, 'utf-8'))) ]
>>> decrypted
[104, 101, 108, 108, 111, 226, 157, 164]

>>> bytes(decrypted)
b'hello\xe2\x9d\xa4'

>>> bytes(decrypted).decode()
'hello❤'

这篇关于python中的字节运算(XOR)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆