python pycrypto_Python使用PyCrypto AE加密

from hashlib import md5

from Crypto.Cipher import AES

from Crypto import Random

import base64

def derive_key_and_iv(password, salt, key_length, iv_length):

d = d_i = ''

while len(d) < key_length + iv_length:

d_i = md5(d_i + password + salt).digest()

d += d_i

return d[:key_length], d[key_length:key_length+iv_length]

def encrypt(in_file, out_file, password, key_length=32):

bs = AES.block_size

salt = Random.new().read(bs - len('Salted__'))

key, iv = derive_key_and_iv(password, salt, key_length, bs)

cipher = AES.new(key, AES.MODE_CBC, iv)

#print in_file

in_file = file(in_file, 'rb')

out_file = file(out_file, 'wb')

out_file.write('Salted__' + salt)

finished = False

while not finished:

chunk = in_file.read(1024 * bs)

if len(chunk) == 0 or len(chunk) % bs != 0:

padding_length = bs - (len(chunk) % bs)

chunk += padding_length * chr(padding_length)

finished = True

out_file.write(cipher.encrypt(chunk))

in_file.close()

out_file.close()

def decrypt(in_file, out_file, password, key_length=32):

bs = AES.block_size

in_file = file(in_file, 'rb')

out_file = file(out_file, 'wb')

salt = in_file.read(bs)[len('Salted__'):]

key, iv = derive_key_and_iv(password, salt, key_length, bs)

cipher = AES.new(key, AES.MODE_CBC, iv)

next_chunk = ''

finished = False

while not finished:

chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs))

if len(next_chunk) == 0:

padding_length = ord(chunk[-1])

if padding_length < 1 or padding_length > bs:

raise ValueError("bad decrypt pad (%d)" % padding_length)

# all the pad-bytes must be the same

if chunk[-padding_length:] != (padding_length * chr(padding_length)):

# this is similar to the bad decrypt:evp_enc.c from openssl program

raise ValueError("bad decrypt")

chunk = chunk[:-padding_length]

finished = True

out_file.write(chunk)

in_file.close()

out_file.close()

def encode(in_file, out_file):

in_file = file(in_file, 'rb')

out_file = file(out_file, 'wb')

data = in_file.read()

out_file.write(base64.b64encode(data))

in_file.close()

out_file.close()

def decode(in_file, out_file):

in_file = file(in_file, 'rb')

out_file = file(out_file, 'wb')

data = in_file.read()

out_file.write(base64.b64decode(data))

in_file.close()

out_file.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值