日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python aes_python AES 加密

發布時間:2025/4/5 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python aes_python AES 加密 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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'

總結

以上是生活随笔為你收集整理的python aes_python AES 加密的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。