Challenge 2:Fixed XOR
题目
If your function works properly, then when you feed it the string:
1c0111001f010100061a024b53535009181c
… after hex decoding, and when XOR’d against:
686974207468652062756c6c277320657965
… should produce:
746865206b696420646f6e277420706c6179
代码
def RawToHex(s): #转16进制
"""Return a hexadecimal strong from raw bytes."""
h = s.encode("hex")
return h
def HexToRaw(s): #转字符
h = s.decode("hex")
return h
def XORHex(s1, s2): #将两个字符串的各位进行异或
"""Calculate the XOR from two equal length strings."""
if len(s1) != len(s2):
return Null
r1 =HexToRaw(s1) #将16进制解码
r2 =HexToRaw(s2)
result = ''
for x,y in zip(r1,r2):#将解码后的字符转换为十进制异或然后在转为字符
result += chr(ord(x) ^ ord(y))
return RawToHex(result)#将字符转为16进制数输出
if __name__ == "__main__":
t1 = "1c0111001f010100061a024b53535009181c"
t2 = "686974207468652062756c6c277320657965"
print XORHex(t1,t2).strip()
说明
zip函数:接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。
chr()函数:参数是0 - 256 的一个整数,返回值是当前整数对应的ascii 字符 。参数可以是10进制也可以是16进制的形式
ord()函数:参数是一个ascii字符,返回值是对应的十进制整数
strip()函数:删除空白符(包括’\n’, ‘\r’, ‘\t’, ’ ‘)