openssl从证书读取公钥然后验证签名,c语言代码怎么实现
时间: 2023-06-04 07:03:23 浏览: 469
下面是一个简单的示例代码:
```
#include <openssl/pem.h>
#include <openssl/err.h>
int verify_signature(X509 *cert, EVP_PKEY *pubkey, unsigned char *msg, size_t msglen, unsigned char *sig, size_t siglen) {
EVP_MD_CTX *ctx;
int ret = 0;
// create the digest context
ctx = EVP_MD_CTX_create();
if (!ctx) {
return -1;
}
// initialize the digest context with the appropriate hash function
if (EVP_VerifyInit(ctx, EVP_sha256()) != 1) {
EVP_MD_CTX_destroy(ctx);
return -1;
}
// add the message to the digest context
if (EVP_VerifyUpdate(ctx, msg, msglen) != 1) {
EVP_MD_CTX_destroy(ctx);
return -1;
}
// perform the signature verification using the public key
if (EVP_VerifyFinal(ctx, sig, siglen, pubkey) != 1) {
ret = -1;
}
// cleanup
EVP_MD_CTX_destroy(ctx);
return ret;
}
int main() {
X509 *cert;
EVP_PKEY *pubkey;
unsigned char msg[] = "hello world";
unsigned char sig[] = "... signature ...";
int siglen = sizeof(sig);
char *certfile = "cert.pem";
// load the certificate from file
cert = X509_new();
if (!cert) {
ERR_print_errors_fp(stderr);
return -1;
}
FILE *fp = fopen(certfile, "r");
if (!fp) {
ERR_print_errors_fp(stderr);
X509_free(cert);
return -1;
}
PEM_read_X509(fp, &cert, NULL, NULL);
fclose(fp);
// extract the public key from the certificate
pubkey = X509_get_pubkey(cert);
if (!pubkey) {
ERR_print_errors_fp(stderr);
X509_free(cert);
return -1;
}
// verify the signature
if (verify_signature(cert, pubkey, msg, sizeof(msg)-1, sig, siglen) == 1) {
printf("signature verification succeeded\n");
} else {
printf("signature verification failed\n");
}
// cleanup
EVP_PKEY_free(pubkey);
X509_free(cert);
return 0;
}
```
请注意,此示例代码不包括错误处理代码。实际代码应该检查调用函数的返回值,并使用 OpenSSL 中的错误管理机制(例如 ERR_print_errors_fp)来打印有用的错误信息。
阅读全文
相关推荐















