OpenSSL数字签名测试

#include
#include
#include
#include

#include


/*数字签名*/
void signature_test() {
uint8_t sign_value[1024];
uint32_t sign_len;
EVP_MD_CTX md_ctx;
char* msg = "Test Message";
EVP_PKEY* evp_key = NULL;


RSA *rsa = NULL;
printf("正在产生rsa...\n");
rsa = RSA_generate_key(1024, RSA_F4, NULL, NULL);
if (rsa == NULL) {
printf("RSA_generate_key_ex error\n");
return;
}
printf("产生rsa成功\n");

evp_key = EVP_PKEY_new();
if (evp_key == NULL) {
printf("EVP_PKEY_new error\n");
RSA_free(rsa);
return;
}


if (!EVP_PKEY_set1_RSA(evp_key, rsa)) {
RSA_free(rsa);
EVP_PKEY_free(evp_key);
}


EVP_MD_CTX_init(&md_ctx);


EVP_SignInit_ex(&md_ctx, EVP_md5(), NULL);


EVP_SignUpdate(&md_ctx, msg, strlen(msg));


EVP_SignFinal(&md_ctx, sign_value, &sign_len, evp_key);


printf("签名信息:");


for (int i = 0 ; i < sign_len; i++) {
if (i%16 == 0)
printf("\n%08xH: ", i);
printf("0x%02x ", sign_value[i]);
}
printf("\n");


EVP_MD_CTX_cleanup(&md_ctx);


EVP_MD_CTX_init(&md_ctx);


EVP_VerifyInit(&md_ctx, EVP_md5());


EVP_VerifyUpdate(&md_ctx, msg, strlen(msg));


printf("开始验证...\n");
int ret = EVP_VerifyFinal(&md_ctx, sign_value, sign_len, evp_key);
printf("验证结果: ");
if (ret == 1) {
printf("签名验证正确\n");
} else {
printf("签名验证错误\n");
}


EVP_PKEY_free(evp_key);
RSA_free(rsa);
EVP_MD_CTX_cleanup(&md_ctx);
return;
}

你可能感兴趣的:(PKI基础知识)