RSA实现数字签名并验证C语言代码
时间: 2024-01-09 10:03:46 浏览: 45
以下是RSA数字签名和验证的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#define KEY_LENGTH 2048
#define PUB_EXP 3
#define PRI_EXP 65537
#define BLOCK_SIZE 256
int main() {
RSA *rsa = RSA_new();
BIGNUM *bne = BN_new();
BIO *bio = NULL;
int ret = -1;
// 生成RSA密钥对
BN_set_word(bne, PUB_EXP);
rsa = RSA_new();
ret = RSA_generate_key_ex(rsa, KEY_LENGTH, bne, NULL);
if (ret != 1) {
printf("Failed to generate RSA key pair!\n");
return -1;
}
// 使用私钥进行数字签名
unsigned char msg[] = "Hello, world!";
unsigned char signature[BLOCK_SIZE] = {0};
unsigned int sig_len = 0;
bio = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(bio, rsa, NULL, NULL, 0, NULL, NULL);
sig_len = RSA_private_encrypt(sizeof(msg) - 1, msg, signature, rsa, RSA_PKCS1_PADDING);
BIO_free_all(bio);
// 使用公钥进行签名验证
bio = BIO_new(BIO_s_mem());
PEM_write_bio_RSA_PUBKEY(bio, rsa);
RSA *rsa_pubkey = RSA_new();
PEM_read_bio_RSA_PUBKEY(bio, &rsa_pubkey, NULL, NULL);
ret = RSA_public_decrypt(sig_len, signature, msg, rsa_pubkey, RSA_PKCS1_PADDING);
BIO_free_all(bio);
if (ret != sizeof(msg) - 1 || memcmp(msg, "Hello, world!", sizeof(msg) - 1) != 0) {
printf("Signature verification failed!\n");
return -1;
} else {
printf("Signature verification succeeded!\n");
}
RSA_free(rsa);
RSA_free(rsa_pubkey);
BN_free(bne);
return 0;
}
```
该示例代码使用OpenSSL库实现RSA数字签名和验证。首先,它生成一个2048位的RSA密钥对。然后,使用私钥对消息进行签名,使用公钥对签名进行验证。如果签名验证成功,则输出“Signature verification succeeded!”,否则输出“Signature verification failed!”。