Python中异或加密要将str 转为 bitarray, 提示: int类型和纯数字的字符串也可以异或处理, 可能更方便
from bitarray import bitarray
def str2bitarray(msg): # msg 为str
msg_2 = “” # 转为1010拼接成字符串
for a in msg.encode(‘utf-8’):
a_16 = hex(a)[2:] # ascll 码16进制 str
a_10 = int(“1” + a_16, 16) # 10进制 int, 防止转二进制最高为0丢失, 所以最高位前加1 , 10进制 int
a_2 = bin(a_10)[3:] # 二进制 str, 利用ascll码值是8bit, 最前面可以加1, 在切片,去掉
msg_2 += a_2
return bitarray(msg_2)
def bitarray2str(bitarray_obj): # bitarray 转str
return bitarray_obj.tostring()
def str_to_hex(s):
return ‘ ‘.join([hex(ord(c)).replace(‘0x’, ”) for c in s])
def hex_to_str(s):
return ”.join([chr(i) for i in [int(b, 16) for b in s.split(‘ ‘)]])
def str_to_bin(s):
return ‘ ‘.join([bin(ord(c)).replace(‘0b’, ”) for c in s])
def bin_to_str(s):
return ”.join([chr(i) for i in [int(b, 2) for b in s.split(‘ ‘)]])
def encryption_bit(msg): # 利用 异或运算 加密
# i_key为 int 任意值
# msg 为 str 任意值
i_plain = int(“1″ + ”.join([bin(int(‘1’ + hex(c)[2:], 16))[3:] for c in msg.encode(‘utf-8’)])) # 要加密的str 转int
s_cipher = str(i_plain ^ i_key)
return s_cipher
def decryption_bit(s_cipher): # 解密, i_key 要和加密的一样
s_plain = str(int(s_cipher) ^ i_key)[1:]
msg = bitarray(s_plain).tostring()
return msg