欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

openssl 生成摘要、签名和验签接口使用

程序员文章站 2022-07-08 14:23:41
...

1、生成摘要

int getDigest(const char* source, int source_len, unsigned char *digest_data, unsigned int *digest_len)
{
	EVP_MD_CTX *mdctx;
	if((mdctx = EVP_MD_CTX_create()) == NULL) {
		return -1;
	}
    
	if(1 != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL)) {
		return -1;
	}

	if(1 != EVP_DigestUpdate(mdctx, source, source_len)) {
		return -1;
	}
    
	if(1 != EVP_DigestFinal_ex(mdctx, digest_data, digest_len)) {
		return -1;
	}
   
	EVP_MD_CTX_destroy(mdctx);
	
	return 0;
}


2、签名

int signData(EVP_PKEY * key, unsigned char *data, unsigned int data_len, 
                     unsigned char *sign, unsigned int *sign_len)
{
    EVP_MD_CTX *ctx = EVP_MD_CTX_create();
	const EVP_MD* digestAlg = EVP_sha256();
    
	if(1 != EVP_SignInit(ctx, digestAlg))
		goto err_exit;  

	if(1 != EVP_SignUpdate(ctx, data, data_len))
		goto err_exit;

	if(1 != EVP_SignFinal(ctx, sign, sign_len, key))
		goto err_exit;

    EVP_MD_CTX_free(ctx);

    return 0;
err_exit:
    EVP_MD_CTX_free(ctx);
    return -1;
    
}

3、验签

int verify(EVP_PKEY * key, unsigned char * sign_data, unsigned int sign_data_len, 
            unsigned char * original, unsigned int original_len)
{
    EVP_MD_CTX *ctx = EVP_MD_CTX_create();
	const EVP_MD* digestAlg = EVP_sha256();

	if(1 != EVP_VerifyInit(ctx, digestAlg))
		goto err_exit; 

	if(1 != EVP_VerifyUpdate(ctx, original, original_len))
		goto err_exit;    

	if(1 != EVP_VerifyFinal(ctx, sign_data, sign_data_len, key))
		goto err_exit; 

	EVP_MD_CTX_free(ctx);

    return 0;
err_exit:
    EVP_MD_CTX_free(ctx);
    return -1;
}

二、demo

int main(void)
{	
    FILE *sfd = fopen("/home/opensslapi/pfx_pri.pem", "r");
    FILE *pfd = fopen("/home/opensslapi/pfx_pub.pem", "r");
    EVP_PKEY *sk = PEM_read_PrivateKey(sfd, NULL, NULL, NULL);
    EVP_PKEY *pk = PEM_read_PUBKEY(pfd, NULL, NULL, NULL);

    fclose(sfd);
    fclose(pfd);

	char src_data[64] = "123qwet";
    unsigned int sign_len = 0, digest_len = 0;
    unsigned char sign[512] = {0};
    unsigned char hash_str[512] = {0};


	getDigest(src_data, strlen(src_data), hash_src, &digest_len);

    signData(sk, src_data, strlen(src_data), sign, &sign_len);
    
    if(0 == verify(pk, sign, sign_len, src_data, strlen(src_data)))
        printf("verify success\n");
    else
        printf("verify failed\n");

	EVP_PKEY_free(sk);
	EVP_PKEY_free(pk);
    return 0;
}

相关标签: openssl arm