使用openssl编写RSA加解密算法和RSA签名验证算法,用C语言实现
时间: 2024-03-05 18:53:39 浏览: 19
以下是使用 OpenSSL 库编写 RSA 加解密算法和 RSA 签名验证算法的示例代码,使用的是 C 语言:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
int main() {
RSA *rsa = NULL;
unsigned char *data = (unsigned char *)"Hello, world!";
unsigned char encrypted[2048] = {0};
unsigned char decrypted[2048] = {0};
unsigned char sig[2048] = {0};
unsigned int sig_len = 0;
int ret = 0;
// 生成 RSA 密钥对
rsa = RSA_new();
BIGNUM *e = BN_new();
int bits = 2048;
unsigned long exponent = RSA_F4;
BN_set_word(e, exponent);
RSA_generate_key_ex(rsa, bits, e, NULL);
// RSA 加密
int data_len = strlen((const char *)data);
int len = RSA_public_encrypt(data_len, data, encrypted, rsa, RSA_PKCS1_PADDING);
if (len < 0) {
printf("RSA encryption failed\n");
return -1;
}
// RSA 解密
len = RSA_private_decrypt(len, encrypted, decrypted, rsa, RSA_PKCS1_PADDING);
if (len < 0) {
printf("RSA decryption failed\n");
return -1;
}
printf("Decrypted data: %s\n", decrypted);
// RSA 签名
ret = RSA_sign(NID_sha256, data, data_len, sig, &sig_len, rsa);
if (ret != 1) {
printf("RSA signature failed\n");
return -1;
}
// RSA 验证签名
ret = RSA_verify(NID_sha256, data, data_len, sig, sig_len, rsa);
if (ret != 1) {
printf("RSA signature verification failed\n");
return -1;
}
printf("RSA signature verification succeeded\n");
RSA_free(rsa);
return 0;
}
```
需要注意的是,在实际使用时需要根据具体情况进行修改和完善,例如读取密钥文件、处理加密后的数据、处理签名数据等。另外,需要链接 OpenSSL 库,可以使用以下命令进行编译:
```sh
gcc -o rsa rsa.c -lssl -lcrypto
```
其中,`-lssl` 表示链接 OpenSSL 的 SSL 库,`-lcrypto` 表示链接 OpenSSL 的 Crypto 库。