前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3中Crypto的AES和RSA

python3中Crypto的AES和RSA

作者头像
静默加载
发布2020-05-29 10:56:04
1.4K0
发布2020-05-29 10:56:04
举报

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')

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 生产RSA的公钥和私钥
  • RSA加解密
  • AES加密
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档