当前位置:   article > 正文

python aes new_python AES 加密

python aes.new

pad: ZeroPadding

mode: cbc

#!/usr/bin/env python

# -*- coding:utf-8 -*-

# 这里使用pycrypto‎库

# 按照方法:easy_install pycrypto‎

from Crypto.Cipher import AES

import base64

class prpcrypt():

def __init__(self, key, iv):

self.key = key

self.mode = AES.MODE_CBC

self.iv = iv

# 加密函数,如果text不足16位就用空格补足为16位,

# 如果大于16当时不是16的倍数,那就补足为16的倍数。

def encrypt(self, text):

cryptor = AES.new('123454536f667445454d537973576562',

self.mode, IV=self.iv)

# 这里密钥key 长度必须为16(AES-128),

# 24(AES-192),或者32 (AES-256)Bytes 长度

# 目前AES-128 足够目前使用

length = 16

count = len(text)

if count < length:

add = (length - count)

#\0 backspace

text = text + ('\0' * add)

elif count > length:

add = (length - (count % length))

text = text + ('\0' * add)

self.ciphertext = cryptor.encrypt(text)

# 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题

# 所以这里统一把加密后的字符串转化为16进制字符串

return base64.b64encode(self.ciphertext)

# 解密后,去掉补足的空格用strip() 去掉

def decrypt(self, text):

cryptor = AES.new(self.key, self.mode, IV=self.iv)

plain_text = cryptor.decrypt(base64.b64decode(text))

return plain_text.rstrip('\0')

if __name__ == '__main__':

pc = prpcrypt('123454536f667445454d537973576562',

'1234577290ABCDEF1264147890ACAE45'[0:16]) # 初始化密钥

e = pc.encrypt('T10515') # 加密

print "加密:", e

d = pc.decrypt(e) # 解密

print "解密:", d

AES:

pad pkcs7

mode cbc

# -*- coding: utf-8 -*-

from Crypto.Cipher import AES

import base64

import os

BS = AES.block_size

pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

unpad = lambda s: s[0:-ord(s[-1])]

key = os.urandom(16) # the length can be (16, 24, 32)

text = '123456'

cipher = AES.new(key)

cipher = AES.new('33b21adee1b8620a7ba81aea1a80c724',

AES.MODE_CBC, IV='1234567812345678')

encrypted = cipher.encrypt(pad(text))

encrypted = base64.b64encode(encrypted)

print encrypted # will be something like 'f456a6b0e54e35f2711a9fa078a76d16'

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/800357
推荐阅读
相关标签
  

闽ICP备14008679号