Python使用PyCrypto實現(xiàn)AES加密功能示例
本文實例講述了Python使用PyCrypto實現(xiàn)AES加密功能。分享給大家供大家參考,具體如下:
#!/usr/bin/env python
from Crypto.Cipher import AES
import base64
import os
# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 32
# the character used for padding--with a block cipher such as AES, the value
# you encrypt must be a multiple of BLOCK_SIZE in length. This character is
# used to ensure that your value is always a multiple of BLOCK_SIZE
PADDING = '{'
# one-liner to sufficiently pad the text to be encrypted
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
# generate a random secret key
secret = os.urandom(BLOCK_SIZE)
# create a cipher object using the random secret
cipher = AES.new(secret)
# encode a string
encoded = EncodeAES(cipher, 'password')
print 'Encrypted string:', encoded
# decode the encoded string
decoded = DecodeAES(cipher, encoded)
print 'Decrypted string:', decoded
PS:關于加密解密感興趣的朋友還可以參考本站在線工具:
文字在線加密解密工具(包含AES、DES、RC4等):
http://tools.jb51.net/password/txt_encode
MD5在線加密工具:
http://tools.jb51.net/password/CreateMD5Password
在線散列/哈希算法加密工具:
http://tools.jb51.net/password/hash_encrypt
在線MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.jb51.net/password/hash_md5_sha
在線sha1/sha224/sha256/sha384/sha512加密工具:
http://tools.jb51.net/password/sha_encode
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python編碼操作技巧總結》、《Python數(shù)據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python+OpenCV 實現(xiàn)簡單的高斯濾波(推薦)
這篇文章主要介紹了Python+OpenCV 實現(xiàn)簡單的高斯濾波,在文中需要注意的是,這里我沒有特判當sigma = 0的時候的情況,具體實現(xiàn)過程跟隨小編一起看看吧2021-09-09
PyCharm+Qt Designer+PyUIC安裝配置教程詳解
這篇文章主要介紹了PyCharm+Qt Designer+PyUIC安裝配置教程詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-06-06
pandas數(shù)據清洗,排序,索引設置,數(shù)據選取方法
下面小編就為大家分享一篇pandas數(shù)據清洗,排序,索引設置,數(shù)據選取方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05

