python3中Crypto的AES和RSA

2020-05-29 10:56:04 浏览数 (1)

RSA加密一般使用RSA/ECB/PKCS1Padding(算法/工作模式/填充方式),AES加密一般使用AES/ECB/PKCS5Padding。但python中的补码需要自己进行填充。

生产RSA的公钥和私钥

代码语言:javascript复制
# -*- coding: utf-8 -*-
import rsa

# 先生成一对密钥,然后保存.pem格式文件,当然也可以直接使用
(pubkey, privkey) = rsa.newkeys(1024)

pub = pubkey.save_pkcs1()
pubfile = open('public.pem','w ')
pubfile.write(pub)
pubfile.close()

pri = privkey.save_pkcs1()
prifile = open('privateKey.pem','w ')
prifile.write(pri)
prifile.close()

RSA加解密

代码语言:javascript复制
# rsa加密
def rsa_encrypt(message):
    with open('pubkey.pem') as f:
        key = f.read()
        rsakey = RSA.importKey(key)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        cipher_text = base64.b64encode(cipher.encrypt(message))
        return cipher_text

# rsa解密
def rsa_decrypt(message):
    with open('privateKey.pem') as f:
        key = f.read()
        rsakey = RSA.importKey(key)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        message = message.encode("ascii")
        byte_msg = base64.b64decode(message)
        random_generator = Random.new().read
        return cipher.decrypt(byte_msg, random_generator)

AES加密

代码语言:javascript复制
BLOCK_SIZE = 16  # Bytes
# 填充补码,不足16*N个字节,填充字符为chr(填充个数)
pad = lambda s: s   (BLOCK_SIZE - len(s) % BLOCK_SIZE) * 
                chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
# 去掉填充的补码
unpad = lambda s: s[:-ord(s[len(s) - 1:])]


def aes_encrpty(key, message):
    message = pad(message)
    cipher = AES.new(key, AES.MODE_ECB)
    aessource = cipher.encrypt(message)
    return base64.b64encode(aessource)


def aes_decrpty(key, message):
    cipher = AES.new(key, AES.MODE_ECB)
    aessource = cipher.decrypt(base64.b64decode(message))
    return unpad(aessource).decode('utf8')

文章到这里就全部讲述完啦,若有其他需要交流的可以留言哦!!

0 人点赞