how to do bitwise exclusive or of two strings in python?

后端 未结 12 1783
攒了一身酷
攒了一身酷 2020-12-01 02:34

I would like to perform a bitwise exclusive or of two strings in python, but xor of strings are not allowed in python. How can I do it ?

12条回答
  •  暖寄归人
    2020-12-01 03:29

    Here is your string XOR'er, presumably for some mild form of encryption:

    >>> src = "Hello, World!"
    >>> code = "secret"
    >>> xorWord = lambda ss,cc: ''.join(chr(ord(s)^ord(c)) for s,c in zip(ss,cc*100))
    >>> encrypt = xorWord(src, code)
    >>> encrypt
    ';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
    >>> decrypt = xorWord(encrypt,code)
    >>> print decrypt
    Hello, World!
    

    Note that this is an extremely weak form of encryption. Watch what happens when given a blank string to encode:

    >>> codebreak = xorWord("      ", code)
    >>> print codebreak
    SECRET
    

提交回复
热议问题