Python3.7 基于 pycryptodome 的AES加密解密、RSA加密解密、加签验签
2020-06-25 08:07:29 来源:易采站长站 作者:易采站长站整理
return bytes.decode(self.pkcs5_unpad(plain_text))
def aes_decrypt(ciphertext, secret=None, prefix='aes:::'):
secret = secret if secret else settings.default_aes_secret
cipher = AESEncrypter(secret)
prefix_len = len(prefix)
if ciphertext[0:prefix_len]==prefix:
return cipher.decrypt(ciphertext[prefix_len:])
else:
return ciphertext
def aes_encrypt(plaintext, secret=None, prefix='aes:::'):
secret = secret if secret else settings.default_aes_secret
cipher = AESEncrypter(secret)
encrypted = cipher.encrypt(plaintext)
return '%s%s' % (prefix, encrypted)
if __name__ == "__main__":
try:
# for RSA test
ciphertext = 'Qa2EU2EF4Eq4w75TnA1IUw+ir9l/nSdW3pMV+a6FkzV9bld259DxM1M4RxYkpPaVXhQFol04yFjuxzkRg12e76i6pkDM1itQSOy5hwmrud5PQvfnBf7OmHpOpS6oh6OQo72CA0LEzas+OANmRXKfn5CMN14GsmfWAn/F6j4Azhs='
public_key = '/Users/leeyi/workspace/joywin_staff/joywin_staff_api/datas/public.pem'
private_key = '/Users/leeyi/workspace/joywin_staff/joywin_staff_api/datas/private.pem'
ciphertext = RSAEncrypter.encrypt('admin888中国', public_key)
print("ciphertext: ", ciphertext)
plaintext = RSAEncrypter.decrypt(ciphertext, private_key)
print("plaintext: ", type(plaintext))
print("plaintext: ", plaintext)
# for AES test
key = 'abc20304050607081q2w3e4r*1K|j!ta'
cipher = AESEncrypter(key)
plaintext = '542#1504'
encrypted = cipher.encrypt(plaintext)
print('Encrypted: %s' % encrypted)
ciphertext = 'EPLtushldq9E1U8vG/sL3g=='
assert encrypted == ciphertext
plaintext = '542#1504你好'
encrypted = '+YGDvnakKi77SBD6GXmThw=='
decrypted = cipher.decrypt(encrypted)
print('Decrypted: %s' % decrypted)
assert decrypted == plaintext
except KeyboardInterrupt:
sys.exit(0)
ps:Python3 RSA加密解密加签验签示例代码
本代码引入Pycryptodome基于Python3.50版本编译库
#!/usr/bin/env python3
# coding=utf-8
# Author: Luosu201803
"""
create_rsa_key() - 创建RSA密钥
my_encrypt_and_decrypt() - 测试加密解密功能
rsa_sign() & rsa_signverify() - 测试签名与验签功能
"""
from binascii import unhexlify
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP, PKCS1_v1_5
import base64
from Crypto.Hash import SHA1
from Crypto.Signature import pkcs1_15
def create_rsa_key(password="123456"):
"""
创建RSA密钥,步骤说明:
1、从 Crypto.PublicKey 包中导入 RSA,创建一个密码(此密码不是RSA秘钥对)
2、生成 1024/2048 位的 RSA 密钥对(存储在私钥文件和公钥文件)
3、调用 RSA 密钥实例的 exportKey 方法(传入"密码"、"使用的 PKCS 标准"、"加密方案"这三个参数)得到私钥。
4、将私钥写入磁盘的文件。
暂时禁止评论













闽公网安备 35020302000061号