python 中的 XOR 密码 - 奇数长度字符串
XOR cipher in python - odd length string
我正在尝试使用异或运算符进行加密。现在这就是我所拥有的:
from binascii import hexlify, unhexlify
from itertools import cycle
s = '636174'
key = '13'
def cipherkey(s, key):
bin_key = bin(int(key))[2:]
bin_s = bin(int(s, 16))[2:]
k = []
if len(bin_key) < len(bin_s):
for i, j in zip(cycle(bin_key), bin_s):
k.append('{}'.format(i))
else:
for i, j in zip(bin_key, cycle(bin_s)):
k.append('{}'.format(i))
return int("".join(k),2)
def xor_cipher(s,key):
n = cipherkey(s, key)
out = n ^ int(s,16)
return hex(out)
print(unhexlify(xor_cipher(s, key)))
我确定这是非常低效的代码,但我想尽可能多地保留它。我已经开始思考这个问题一段时间了,还没有发现 mistake.There 一定是我迭代 zip(cycle(bin_key), bin_s)
.
的错误
尝试替换最后一行:
print(unhexlify(xor_cipher(s, key)))
使用此代码:
res=xor_cipher(s, key)[2:] # remove '0x' from the begining of the hex code
if res.__len__()%2 ==1: # if res length is odd,
res="0{}".format(res) # append '0' at the begining to make it even
print unhexlify(res)
我遇到了问题,因为我不正确地实施了密码。这样做的方法就是:
def xor_cipher(s, hexkey):
key = ''
for i,j in zip(s, cycle(hexkey)):
key += j
return hex(int(s,16)^int(key,16))[2:]
这就解决了所有问题。
我正在尝试使用异或运算符进行加密。现在这就是我所拥有的:
from binascii import hexlify, unhexlify
from itertools import cycle
s = '636174'
key = '13'
def cipherkey(s, key):
bin_key = bin(int(key))[2:]
bin_s = bin(int(s, 16))[2:]
k = []
if len(bin_key) < len(bin_s):
for i, j in zip(cycle(bin_key), bin_s):
k.append('{}'.format(i))
else:
for i, j in zip(bin_key, cycle(bin_s)):
k.append('{}'.format(i))
return int("".join(k),2)
def xor_cipher(s,key):
n = cipherkey(s, key)
out = n ^ int(s,16)
return hex(out)
print(unhexlify(xor_cipher(s, key)))
我确定这是非常低效的代码,但我想尽可能多地保留它。我已经开始思考这个问题一段时间了,还没有发现 mistake.There 一定是我迭代 zip(cycle(bin_key), bin_s)
.
尝试替换最后一行:
print(unhexlify(xor_cipher(s, key)))
使用此代码:
res=xor_cipher(s, key)[2:] # remove '0x' from the begining of the hex code
if res.__len__()%2 ==1: # if res length is odd,
res="0{}".format(res) # append '0' at the begining to make it even
print unhexlify(res)
我遇到了问题,因为我不正确地实施了密码。这样做的方法就是:
def xor_cipher(s, hexkey):
key = ''
for i,j in zip(s, cycle(hexkey)):
key += j
return hex(int(s,16)^int(key,16))[2:]
这就解决了所有问题。