Python基于pycrypto實(shí)現(xiàn)的AES加密和解密算法示例-創(chuàng)新互聯(lián)

本文實(shí)例講述了Python基于pycrypto實(shí)現(xiàn)的AES加密和解密算法。分享給大家供大家參考,具體如下:

創(chuàng)新互聯(lián)公司從2013年成立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站制作、做網(wǎng)站、外貿(mào)營銷網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元邵武做網(wǎng)站,已為上家服務(wù),為邵武各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220

一 代碼

# -*- coding: UTF-8 -*-
import string
import random
from Crypto.Cipher import AES
def keyGenerater(length):
  '''''生成指定長度的秘鑰'''
  if length not in (16, 24, 32):
    return None
  x = string.ascii_letters+string.digits
  return ''.join([random.choice(x) for i in range(length)])
def encryptor_decryptor(key, mode):
  return AES.new(key, mode, b'0000000000000000')
#使用指定密鑰和模式對(duì)給定信息進(jìn)行加密
def AESencrypt(key, mode, text):
  encryptor = encryptor_decryptor(key, mode)
  return encryptor.encrypt(text)
#使用指定密鑰和模式對(duì)給定信息進(jìn)行解密
def AESdecrypt(key, mode, text):
  decryptor = encryptor_decryptor(key, mode)
  return decryptor.decrypt(text)
if __name__ == '__main__':
  text = 'Python3.5 is excellent.'
  key = keyGenerater(16)
  #隨機(jī)選擇AES的模式
  mode = random.choice((AES.MODE_CBC, AES.MODE_CFB, AES.MODE_ECB, AES.MODE_OFB))
  if not key:
    print('Something is wrong.')
  else:
    print('key:', key)
    print('mode:', mode)
    print('Before encryption:', text)
    #明文必須以字節(jié)串形式,且長度為16的倍數(shù)
    text_encoded = text.encode()
    text_length = len(text_encoded)
    padding_length = 16 - text_length%16
    text_encoded = text_encoded + b'0'*padding_length
    text_encrypted = AESencrypt(key, mode, text_encoded)
    print('After encryption:', text_encrypted)
    text_decrypted =AESdecrypt(key, mode, text_encrypted)
    print('After decryption:', text_decrypted.decode()[:-padding_length])

網(wǎng)站欄目:Python基于pycrypto實(shí)現(xiàn)的AES加密和解密算法示例-創(chuàng)新互聯(lián)
鏈接分享:http://bm7419.com/article8/hsdop.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、定制網(wǎng)站、網(wǎng)站設(shè)計(jì)公司建站公司、網(wǎng)站導(dǎo)航、全網(wǎng)營銷推廣

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

綿陽服務(wù)器托管