linux生成rsa公钥,在Linux下如何使用openssl生成RSA公钥和私钥对

在《Java实现RSA密钥对并在加解密、加签验签中应用的实例》中,我们有用Java代码生成RSA密钥对,其实在Linux操作系统中,用openssl也是很容易生成密钥对的。

一.如果在ubuntu上要使用openssl的话需要先进行安装

命令如下:

sudo apt-get install openssl

安装完成就可以使用openssl了。

二.进入openssl的交互界面,在命令行了输入openssl即可

1.生成RSA私钥

该命令会生成1024位的私钥,生成成功的界面如上所示。

genrsa -out rsa_private_key.pem

此时我们就可以在当前路径下看到rsa_private_key.pem文件了,如下所示:

6483a80a22a808d4352af9e5ab615a81.png

2.把RSA私钥转换成PKCS8格式

输入命令如下命令回车

pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt

得到生成功的结果,这个结果就是PKCS8格式的私钥,如下图:

5cf941fe246a60cd8ee46016f59cdaa6.png

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA是一种非对称加密算法,其公钥私钥是成对生成的。以下是RSA生成公钥私钥以及加解密的步骤: 1. 生成RSA公钥私钥: 首先需要随机生成两个大素数p和q,计算n = p * q,再选取一个整数e(一般为65537),计算d = e^-1 mod ((p-1) * (q-1))。 生成公钥为(n, e),私钥为(n, d)。 2. RSA加密: 假设要将明文M加密为密文C,使用公钥(n, e)进行加密,计算C = M^e mod n。 3. RSA解密: 使用私钥(n, d)进行解密,计算M = C^d mod n。 以下是一个简单的RSA加解密的C语言实现示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/pem.h> int main() { // 生成RSA公钥私钥 RSA *rsa = RSA_generate_key(2048, 65537, NULL, NULL); if (rsa == NULL) { printf("Failed to generate RSA key pair.\n"); return -1; } // 获取公钥私钥 BIO *pubBio = BIO_new(BIO_s_mem()); BIO *priBio = BIO_new(BIO_s_mem()); PEM_write_bio_RSAPublicKey(pubBio, rsa); PEM_write_bio_RSAPrivateKey(priBio, rsa, NULL, NULL, 0, NULL, NULL); // 获取公钥私钥字符串 char pubKey[1024] = {0}; char priKey[4096] = {0}; BIO_read(pubBio, pubKey, sizeof(pubKey)); BIO_read(priBio, priKey, sizeof(priKey)); // 输出公钥私钥 printf("Public Key:\n%s\n", pubKey); printf("Private Key:\n%s\n", priKey); // 加密明文 char *plaintext = "Hello World!"; int plaintextLen = strlen(plaintext) + 1; char ciphertext[4096] = {0}; int ciphertextLen = RSA_public_encrypt(plaintextLen, (unsigned char *)plaintext, (unsigned char *)ciphertext, rsa, RSA_PKCS1_PADDING); if (ciphertextLen == -1) { printf("Failed to encrypt plaintext.\n"); return -1; } // 输出密文 printf("Ciphertext:\n"); for (int i = 0; i < ciphertextLen; i++) { printf("%02x", ciphertext[i]); } printf("\n"); // 解密密文 char decrypted[4096] = {0}; int decryptedLen = RSA_private_decrypt(ciphertextLen, (unsigned char *)ciphertext, (unsigned char *)decrypted, rsa, RSA_PKCS1_PADDING); if (decryptedLen == -1) { printf("Failed to decrypt ciphertext.\n"); return -1; } // 输出解密后的明文 printf("Decrypted plaintext: %s\n", decrypted); // 释放资源 RSA_free(rsa); BIO_free_all(pubBio); BIO_free_all(priBio); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值