cryptopals crypto challenges(set 1)

1.Convert hex to base64

The string:

49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d

Should produce:

SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t

python3脚本

import base64
from Crypto.util.number import long_to_bytes
s="49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
l=int(s,16)
res=base64.b64encode(l).decode("utf-8")
print(res)

python2 脚本

s='49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d'
res=s.decode('hex').encode("base64")
print res

2.Fixed XOR

Write a function that takes two equal-length buffers and produces their XOR combination.

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

pytohn3

import Crypto
from Crypto.Util.number import long_to_bytes,bytes_to_long
str1="1c0111001f010100061a024b53535009181c"
str2="686974207468652062756c6c277320657965"
str3=long_to_bytes(int(str1,16))
str4=long_to_bytes(int(str2,16))
#print(str3,str4)
def xor(a,b):
    length=len(a)
    res=bytearray(len(a))
    for i in range(length):
        res[i]=a[i]^b[i]
    return res
ress=xor(str3,str4)
#print(ress)
print(hex(bytes_to_long(ress))[2:])

python2

def xor(b1,b2):
    b=bytearray(len(b1))
    length=len(b1)
    for i in range(length):
        b[i]=b1[i]^b2[i]
    return b
b1=bytearray.fromhex("1c0111001f010100061a024b53535009181c")
b2=bytearray.fromhex("686974207468652062756c6c277320657965")
res=bytes(xor(b1,b2))
print res.encode('hex')

bytes类型是不可变序列,bytearray是可变的bytes数据类型;

bytes对象只负责以字节(二进制格式)序列来记录数据,以字节为单位进行操作. 例如字节序列b’\x01\x02’,其中\x01为一个字节,\x 表示十六进制,01表示十六进制数
有三种方式将字符串转换成bytes对象:

  • 如果字符串内容都是ascii字符,可直接在字符串前加b,例如b’abc’
  • 调用bytes()函数,例如bytes(‘abc’, encoding=‘utf-8’)
  • 调用字符串的encode()方法,例如’abc’.encode(‘utf-8’)

bytearray(int) :创建一个int位的全为0的bytearray:

>>> a = bytearray(10)
>>> a
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> a[0] = 7
>>> a
bytearray(b'\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> a[0] = 97
>>> a
bytearray(b'a\x00\x00\x00\x00\x00\x00\x00\x00\x00')

如果for循环作用于bytearray,那么得到的是bytearray字节的10进制ascii码:

>>> a
bytearray(b'a\xff\x00\x00\x00\x00\x00\x00\x00\x00')
>>> for i in a:
...     print(i)
... 
97
255
0
0
0
0
0
0
0
0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值