加密解密之AES算法

AES加密的数据块长度为128(16字节),长度不足需要填充。密码长度可以为16,24,32字节。

from Crypto.Cipher import AES
from Crypto import Random

bs = AES.block_size
pad = lambda s: s + (bs - (len(s) % bs)) * chr(bs - len(s) % bs)
unpad = lambda s: s[:-ord(s[len(s)-1:])]

class AESCipher:
    def __init__(self, key):
        self.key = key

    def encrypt(self, rawdata):
        rawdata = pad(rawdata)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return (iv + cipher.encrypt(rawdata))

    def decrypt(self, enc):
        iv = enc[:bs]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return unpad(cipher.decrypt(enc[16:]))

def main():
    key = Random.new().read(32)
    cipher = AESCipher(key)

    msg = 'message to be encrypted'
    encrypted = cipher.encrypt(msg)
    print 'encrypted data: ', encrypted

    decrypted = cipher.decrypt(encrypted)
    print 'decrypted data: ', decrypted

if __name__ == '__main__':
    main()



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值