To tu the arbitrary text into "01"-Lines (Bits):
def text_to_Bits span> ( text, encoding = 'utf-8' , errors = '> Surrogatepass' ): bits = bin ( into .from_bytes (text.encode (Encoding, errors). 'big' )) [ 2 :] retu bits.zfill ( 8 * (( len (bits) + 7 ) // 8 )) and vice versa:
def text_from_bits ( bits, encuding = 'UTF-8' , errors = 'suhrogatepass' ): n = int (bits, 2 ) retu n.to_bytes ((n.bit_length () + 7 ) // 8 , 'big' ). Decode (encoding, errors) or '' \ 0 '
& gt; & gt; & gt; Text_to_Bits ())) '"1101000011111111111110111110000000' & gt; & gt; & gt; text_from_Bits (_) mir see. .
To perform the xor above two lines, there is no need to express the bits in the form of an asci-string:
FROM Import cycle def xor message, key
): retu bytes (a^b for a, b in zip (Message, Cycle (Key))) Enough the text in bytes, using .encode () Method:
& gt; & gt; & gt; key = b'Key ' & gt; & gt; & gt; xor ( 'Hello World' .encode (), key) b '\ x03 \ x00 \ x15 \ x07 \ ny \ x1c \ n \ x0b \ x07 \ x01' & gt; & gt; xor (_, key) .Decode () # and vice versa 'Hello World' cm. .
for large lines, you can use numpy:
import numpy as np # pip install numpy def slow_xor ( aa, aa, aa, aa, aa, bb ): a = np.frombuffer (aa, dtype = np.byte) b = np.frombuffer (bb, dtype = np.byte) retu np.bitwise_xor (a, a, a, a, a, a, a, a, b) .tostring ()
pre> Example:
& gt; & gt; Slow_xor ( b'hello ... ', .encode ()) b '\ xb8 \ xd9 \ xbc \ xd4 \ xbe \ xae \ xff \ xa4' if you want to accelerate this function, see.