python 加密解密

Posted Demonson

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 加密解密相关的知识,希望对你有一定的参考价值。

# -*- coding: utf-8 -*-
import base64
from Crypto.Cipher import AES


#用aes加密,再用base64  encode
def aes_encrypt(data): 
    key='8888888888888888'  #加密时使用的key,只能是长度16,24和32的字符串
    BS = AES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
    cipher = AES.new(key)
    encrypted = cipher.encrypt(pad(data))  #aes加密
    result = base64.b64encode(encrypted)  #base64 encode
    return result 

#把加密的数据,用base64  decode,再用aes解密
def aes_decode(data):
    key='8888888888888888'
    # unpad = lambda s : s[0:-ord(s[-1])]
    unpad = lambda s : s[:-ord(s[len(s)-1:])]
    cipher = AES.new(key)
    result2 = base64.b64decode(data)
    decrypted = unpad(cipher.decrypt(result2))
    return  decrypted  

data = 'jibobo'  #需要加密的字符串
print(data)
res1 = aes_encrypt(data) #加密
res1 = str(res1,'utf-8')
print(res1)     #加密后的字符串
res2 = aes_decode(res1)  #解密
print(str(res2,'utf-8')) #解密后的字符串

 

以上是关于python 加密解密的主要内容,如果未能解决你的问题,请参考以下文章

python文件加密

为啥python不可加密

python爬虫之数据加密解密

利用以下python代码编写栏栅加密和解密

python实现aes加密解密

python3 AES加密解密