简体   繁体   English

Python Openssl生成rsa密钥对并写入文件

[英]Python Openssl generate rsa key pair and write to a file

I want to generate a private , public key pair and put them into private.key and public.key files respectively. 我想生成一个private,public key对,并将它们分别放入private.keypublic.key文件中。 I have the following code. 我有以下代码。

from OpenSSL import crypto, SSL

def gen_rsa_key_pair():
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 1024)
    open("Priv.key", "wt").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))

crypto.dump_publickey() is not available. crypto.dump_publickey()不可用。

How do I dump public key to a file? 如何将公钥转储到文件?

The OpenSSL functions to print the public RSA key do not seem to be exported by the Python OpenSSL wrapper. Python OpenSSL包装器似乎未导出用于打印公共RSA密钥的OpenSSL函数。 By accessing the internals of the crypto module, you could still do it yourself (assuming that you have this package installed locally), as this code snippet shows: 通过访问crypto模块的内部结构,您仍然可以自己进行操作(假设您已在本地安装此软件包),如以下代码片段所示:

>>> bio = crypto._new_mem_buf()
>>> rsa = crypto._lib.EVP_PKEY_get1_RSA(k._pkey)
>>> crypto._lib.PEM_write_bio_RSAPublicKey(bio, rsa)
1
>>> s = crypto._bio_to_string(bio)
>>> print(s)
-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBANF1gYh10F8HTQdM6+bkwAwJ0Md6bMciKbP3qS6KTki3v3m+cM17Szqq
Mp4xxWbvnS2oeotYfn8eaZg0QUTOVDd1F7tuOxVEdvQ9ZEp1aeOCRU3b9QZSmVfg
wJrqDG3f149mNdexI12plwaxyt6odonv6+fEQJrbhrV/nIA8N/EFAgMBAAE=
-----END RSA PUBLIC KEY-----

This is just for illustration purposes. 这仅出于说明目的。 A proper solution should be added to the crypto module itself, via a new method dump_publickey() or the like. 应通过新方法dump_publickey()等将适当的解决方案添加到crypto模块本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM