#!/usr/bin/env python3
# coding=utf-8
# Author: yannanxiu
"""
create_rsa_key() - 创建RSA密钥
my_encrypt_and_decrypt() - 加密解密测试
"""
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_OAEP, PKCS1_v1_5
def create_rsa_key(password="123456"):
"""
创建RSA密钥
步骤说明:
1、从 Crypto.PublicKey 包中导入 RSA,创建一个密码
2、生成 1024/2048 位的 RSA 密钥
3、调用 RSA 密钥实例的 exportKey 方法,传入密码、使用的 PKCS 标准以及加密方案这三个参数。
4、将私钥写入磁盘的文件。
5、使用方法链调用 publickey 和 exportKey 方法生成公钥,写入磁盘上的文件。
"""
key = RSA.generate(1024)
encrypted_key = key.exportKey(passphrase=password, pkcs=8,
protection="scryptAndAES128-CBC")
with open("my_private_rsa_key.bin", "wb") as f:
f.write(encrypted_key)
with open("my_rsa_public.pem", "wb") as f:
f.write(key.publickey().exportKey())
def encrypt_and_decrypt_test(password="123456"):
# 加载公钥
recipient_key = RSA.import_key(
open("my_rsa_public.pem").read()
)
cipher_rsa = PKCS1_v1_5.new(recipient_key)
en_data = cipher_rsa.encrypt(b"123456")
print(len(en_data), en_data)
# 读取密钥
private_key = RSA.import_key(
open("my_private_rsa_key.bin").read(),
passphrase=password
)
cipher_rsa = PKCS1_v1_5.new(private_key)
data = cipher_rsa.decrypt(en_data, None)
print(data)
if __name__ == '__main__':
# create_rsa_key()
encrypt_and_decrypt_test()

最新文章

  1. php面向对象编程(一)
  2. navigator.userAgent.indexOf来判断浏览器类型
  3. 踏着前人的脚印学hadoop——ipc中的Server
  4. 清除浮动4-插入多余的div
  5. 图像质量评价指标之Matlab实现
  6. CoolShell Puzzle攻略[更新隐藏剧情]
  7. JS加载时间线
  8. jquery div层级选择器
  9. ASP.NET中处理异常的几种方式
  10. raywenderlich-iOS设计模式Part 1/2【译】
  11. (转)c#缓存介绍
  12. ASP.Net MVC @Html类
  13. Uva 10131 Is Bigger Smarter? (LIS,打印路径)
  14. vue——实例方法 / 数据
  15. Algorithm --> Dijkstra和Floyd最短路径算法
  16. Python全栈之路----函数----高阶函数
  17. 背水一战 Windows 10 (84) - 用户和账号: 微软账号的登录和注销
  18. [转帖]从1G到5G
  19. 2.如何导入Spring约束?
  20. K-means聚类算法原理和C++实现

热门文章

  1. docker学习之路-centos下安装docker
  2. Vert.x(vertx)发送 HTTP/HTTPS请求
  3. docker run VS docker exec 的区别
  4. JavaScript---Bom树的操作,内置方法和内置对象(window对象,location对象,navigator对象,history对象,screen对象)
  5. 基于elementUI创建的vue项目
  6. Python 的稀疏矩阵
  7. 【转】UCOSIII基础知识点
  8. Ansible--项目实战
  9. 算法——dfs 判断是否为BST
  10. php中的闭包类