Django中Python3安装Crypto使用RSA

邰胤
2023-12-01

环境python版本:python3.7.1,win10,Django

1.安装

pip install pycryptodome

或者

在pycharm中,file->settings->project->project interpreter,点击+号,搜索pycryptodome安装

 

注:pycrypto、pycrytodome和crypto是一个东西

 

2.运行代码会提示“ No module named Crypto”,需要将Django项目中的\venv\Lib\site-packages\crypto文件夹的名字修改为Crypto。

参考文章:https://www.cnblogs.com/fawaikuangtu123/p/9761943.html

 

3.RSA算法示例

# -*- coding: utf-8 -*-


from Crypto import Random
from Crypto.PublicKey import RSA

print("1. generate private key and pulic key")

# 参考 C:\Python27\Lib\site-packages\Crypto\PublicKey\RSA.py

######################################################

# 利用伪随机数来生成私钥和公钥
random_generator = Random.new().read

rsa = RSA.generate(2048, random_generator)

private_pem = rsa.exportKey()
print(private_pem)
f = open('MY_KEY1_pri.pem', 'wb+')
f.write(private_pem)
f.close()

public_pem = rsa.publickey().exportKey()
print(public_pem)
f = open('MY_KEY1_pub.pem', 'wb+')
f.write(public_pem)
f.close()

######################################################

print("2. generate private key and pulic key")

# 利用默认的generate来生成私钥和公钥
rsa = RSA.generate(2048)
private_pem = rsa.exportKey('PEM')
f = open('MY_KEY2_pri.pem', 'wb+')
f.write(private_pem)
f.close()

public_pem = rsa.publickey().exportKey()
f = open('MY_KEY2_pub.pem', 'wb+')
f.write(public_pem)
f.close()

######################################################

print("3. generate private key and pulic key")

# 根据已有的RSA私钥来生成公钥
f = open('MY_KEY2_pri.pem', 'rb+')
rsa = RSA.importKey(f.read())
f.close()

public_pem = rsa.publickey().exportKey()
f = open('MY_KEY3_pub.pem', 'wb+')
f.write(public_pem)
f.close()

######################################################

print("4. generate private key and pulic key")

# 根据已有的RSA PEM格式的私钥来转换成DER格式的私钥
f = open('MY_KEY2_pri.pem', 'rb+')
rsa = RSA.importKey(f.read())
f.close()

private_der = rsa.exportKey('DER')
f = open('MY_KEY3_pri.der', 'wb+')
f.write(private_der)
f.close()

参考文章:https://blog.csdn.net/cfl927096306/article/details/79888428

 

 类似资料: