openssl用公钥加密passwd.txt文件输出passwd.rsa
时间: 2024-05-28 21:09:41 浏览: 12
好的,我明白了。针对您的问题,可以使用以下命令:openssl rsautl -encrypt -inkey publickey.pem -pubin -in passwd.txt -out passwd.rsa。此命令将使用公钥publickey.pem对passwd.txt进行加密,并将加密结果输出到passwd.rsa文件中。希望能对您有所帮助!
相关问题
openssl用私钥解密passwd.rsa文件输出passwd.txt
我了解你要询问的问题,并且已经注意到你的要求。回答你的问题,首先需要使用openssl命令行工具,执行以下命令:openssl rsautl -decrypt -inkey private_key.pem -in passwd.rsa -out passwd.txt。其中,private_key.pem是你的私钥文件,passwd.rsa是需要解密的文件,passwd.txt是解密后的输出文件。
openssl RSA公钥加密代码
以下是使用 OpenSSL 库进行 RSA 公钥加密的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
int rsa_public_encrypt(const unsigned char *plaintext, int plaintext_len, const char *public_key_path, unsigned char *encrypted_data) {
FILE *public_key_file = fopen(public_key_path, "rb");
if (public_key_file == NULL) {
fprintf(stderr, "Failed to open public key file.\n");
return -1;
}
RSA *rsa = RSA_new();
if (PEM_read_RSA_PUBKEY(public_key_file, &rsa, NULL, NULL) == NULL) {
fprintf(stderr, "Failed to read public key from file.\n");
fclose(public_key_file);
return -1;
}
fclose(public_key_file);
int encrypted_data_len = RSA_public_encrypt(plaintext_len, plaintext, encrypted_data, rsa, RSA_PKCS1_PADDING);
if (encrypted_data_len == -1) {
fprintf(stderr, "Failed to encrypt data.\n");
RSA_free(rsa);
return -1;
}
RSA_free(rsa);
return encrypted_data_len;
}
int main() {
const char *public_key_path = "public_key.pem"; // 替换为您的公钥文件路径
const char *plaintext = "Hello, World!";
int plaintext_len = strlen(plaintext);
unsigned char encrypted_data[256];
int encrypted_data_len = rsa_public_encrypt((unsigned char *)plaintext, plaintext_len, public_key_path, encrypted_data);
if (encrypted_data_len == -1) {
fprintf(stderr, "Failed to encrypt data.\n");
return 1;
}
printf("Encrypted data: ");
for (int i = 0; i < encrypted_data_len; i++) {
printf("%02X ", encrypted_data[i]);
}
printf("\n");
return 0;
}
```
请注意,您需要将 "public_key.pem" 替换为您实际的公钥文件路径。
这段代码首先打开公钥文件并将其读取到 RSA 结构体中。然后,它使用 `RSA_public_encrypt` 函数对明文进行加密。加密后的数据将存储在 `encrypted_data` 数组中。最后,它打印加密后的数据的十六进制表示。
请确保在编译时链接正确的 OpenSSL 库,并在运行代码之前将正确的公钥文件路径替换到代码中。