The cryptopals crypto challenges——Set 1-2

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’, ’ ‘)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值