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

后端 未结 12 1734
攒了一身酷
攒了一身酷 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:22

    If you want to operate on bytes or words then you'll be better to use Python's array type instead of a string. If you are working with fixed length blocks then you may be able to use H or L format to operate on words rather than bytes, but I just used 'B' for this example:

    >>> import array
    >>> a1 = array.array('B', 'Hello, World!')
    >>> a1
    array('B', [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33])
    >>> a2 = array.array('B', ('secret'*3))
    >>> for i in range(len(a1)):
        a1[i] ^= a2[i]
    
    
    >>> a1.tostring()
    ';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
    
    0 讨论(0)
  • 2020-12-01 03:23
    def strxor (s0, s1):
      l = [ chr ( ord (a) ^ ord (b) ) for a,b in zip (s0, s1) ]
      return ''.join (l)
    

    (Based on Mark Byers answer.)

    0 讨论(0)
  • 2020-12-01 03:25

    Do you mean something like this:

    s1 = '00000001'
    s2 = '11111110'
    int(s1,2) ^ int(s2,2)
    
    0 讨论(0)
  • 2020-12-01 03:25
    def xor_strings(s1, s2):
        max_len = max(len(s1), len(s2))
        s1 += chr(0) * (max_len - len(s1))
        s2 += chr(0) * (max_len - len(s2))
        return ''.join([chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(s1, s2)])
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-01 03:29

    Below illustrates XORing string s with m, and then again to reverse the process:

    >>> s='hello, world'
    >>> m='markmarkmark'
    >>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
    >>> s
    '\x05\x04\x1e\x07\x02MR\x1c\x02\x13\x1e\x0f'
    >>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
    >>> s
    'hello, world'
    >>>
    
    0 讨论(0)
提交回复
热议问题