利用Crypto模块实现

python3需要安装pycryptodome
pip install pycryptodome

注意: windows环境下可能会有找不到Crypto的情况,这里有个小BUG,windows环境下安装完pycryptodome后在你python的根目录下如:
Python\Python36\Lib\site-packages
里面有一个文件夹叫做crypto,将首字母小写c改成大写C即可解决.

生成代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from Crypto import Random
from Crypto.PublicKey import RSA


def main():
random_generator = Random.new().read
rsa = RSA.generate(2048, random_generator)
# 私钥
private_pem = rsa.exportKey()
with open("private.pem", "wb") as f:
f.write(private_pem)
# 公钥
public_pem = rsa.publickey().exportKey()
with open("public.pem", "wb") as f:
f.write(public_pem)


if __name__ == '__main__':
main()

参考文章