如何使用 OpenSSL 生成 RSA 私钥?
我想知道如何使用 C 源文件中的 OpenSSL 库生成 RSA 私钥。我知道如何使用终端命令生成它。
实际上,我的 server.c
文件将生成一个私钥并将其发送到 client.c
。
如果可能的话,请帮助我提供一些源代码,也感谢任何其他帮助。
我在一台 Linux 机器上。
I want to know how to generate an RSA private key using the OpenSSL library in my C source file. I know how to generate it using terminal commands.
Actually, my server.c
file will generate a private key and send it to client.c
.
Please help me with some source code if possible, any other help is appreciated as well.
I'm on a Linux machine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
生成密钥很容易。只需使用 RSA_generate_key_ex 即可。下面的程序向您展示了如何做到这一点。
保存公钥和私钥是另一回事,因为您需要知道格式。下面的程序向您展示了如何以多种格式执行此操作。
以下是各种功能和格式。
相关请参见“BEGIN RSA PRIVATE KEY”和“BEGIN PRIVATE KEY”有什么区别。它讨论了 SubjectPublicKeyInfo、PrivateKeyInfo 以及公钥和私钥之间的区别。
PEM_write_bio_RSAPublicKey(PKCS PEM 格式)。注意
BEGIN RSA PUBLIC KEY
:PEM_write_bio_PUBKEY(传统PEM格式)。注意
BEGIN PUBLIC KEY
:PEM_write_bio_PrivateKey (PEM)。注意
BEGIN PRIVATE KEY
:PEM_write_bio_PKCS8PrivateKey (PEM)。注意
BEGIN PRIVATE KEY
:PEM_write_bio_RSAPrivateKey (PEM)。注意
BEGIN RSA PRIVATE KEY
:i2d_RSAPublicKey_bio (ASN.1/DER):
i2d_RSAPrivateKey_bio > (ASN.1/DER):
该程序是用 C++ 编写的,即使您有 C 标记。它使我们能够避免大量的错误检查和清理,因为它是自动的。而且很容易转换回 C。
Generating the key is easy. Just use
RSA_generate_key_ex
. The program below shows you how to do it.Saving the public and private key is a different matter because you need to know the format. The program below shows you how to do it in a number of formats.
Here are the various functions and formats.
Related, see What is the differences between “BEGIN RSA PRIVATE KEY” and “BEGIN PRIVATE KEY”. It dicusses the difference between SubjectPublicKeyInfo, PrivateKeyInfo, and the public and private keys.
PEM_write_bio_RSAPublicKey (PKCS PEM format). Notice
BEGIN RSA PUBLIC KEY
:PEM_write_bio_PUBKEY (Traditional PEM format). Notice
BEGIN PUBLIC KEY
:PEM_write_bio_PrivateKey (PEM). Notice
BEGIN PRIVATE KEY
:PEM_write_bio_PKCS8PrivateKey (PEM). Notice
BEGIN PRIVATE KEY
:PEM_write_bio_RSAPrivateKey (PEM). Notice
BEGIN RSA PRIVATE KEY
:i2d_RSAPublicKey_bio (ASN.1/DER):
i2d_RSAPrivateKey_bio (ASN.1/DER):
The program is written in C++, even though you have a C tag. It allows us to avoid a lot of error checking and cleanup because its automatic. And its easy enough to convert back to C.
在正确播种使用
RAND_add
进行 PRNG。编辑:
虽然最初编写此答案时需要调用
RAND_add
,但当前版本的 OpenSSL 不再需要手动播种 PRNG。You would use
RSA_generate_key_ex
, after properly seeding the PRNG usingRAND_add
.Edit:
While calling
RAND_add
was needed when this answer was originally written, current versions of OpenSSL no longer require manual seeding of the PRNG.