vc++ openssl 程序签名

时间:2023-11-12 12:16:32

RSA一般有两种应用场景:
   1、公钥加密、私钥解密:这是数据安全通信领域最常见情形;
   2、私钥加验、公钥验签:这主要用于数字签名。

我们这里用到的是第二种情况:

这里是基于OpenSSL,首先安装OpenSSL工具,引用lib、.h文件,网上有很多例子这里就不在介绍

头文件:

#pragma once
#include <stdio.h>
#include<string.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
class test4
{
public:
test4(void);
~test4(void);
void print_hex(char* buff);
int rsa_verify(char *in, char *key_path, char* in2, int len);
int rsa_sign(char *in, char *key_path, char* out, int* plen);
int test();
};

cpp文件

#include "StdAfx.h"
#include "test4.h"
#include <stdio.h>
#include<string.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#define MSG_LEN (128+1)
test4::test4(void)
{
} test4::~test4(void)
{
}
void test4::print_hex(char* buff)
{
for (int i=;buff[i];i++)
printf("%02x",(unsigned char)buff[i]);
printf("\n");
}
int test4::rsa_verify(char *in, char *key_path, char* in2, int len)
{
RSA *p_rsa;
FILE *file;
if((file=fopen(key_path,"r"))==NULL)
{
perror("open key file error");
return ;
}
if((p_rsa=PEM_read_RSA_PUBKEY(file,NULL,NULL,NULL))==NULL)
//if((p_rsa=PEM_read_RSAPublicKey(file,NULL,NULL,NULL))==NULL)
{
ERR_print_errors_fp(stdout);
return ;
}
if(!RSA_verify(NID_md5,(unsigned char*)in,strlen(in),(unsigned char*)in2,len,p_rsa))
{
return ;
}
RSA_free(p_rsa);
fclose(file);
return ;
}
int test4::rsa_sign(char *in, char *key_path, char* out, int* plen)
{
RSA *p_rsa;
FILE *file;
if((file=fopen(key_path,"r"))==NULL)
{
perror("open key file error");
return ;
}
if((p_rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL))==NULL)
{
ERR_print_errors_fp(stdout);
return ;
}
if(!RSA_sign(NID_md5,(unsigned char*)in,strlen(in),(unsigned char*)out,(unsigned int*)plen,p_rsa))
{
return ;
}
RSA_free(p_rsa);
fclose(file);
return ;
}
int test4::test()
{
char text[MSG_LEN];
char sign[MSG_LEN];
int len=; memset((char*)text, ,MSG_LEN);
memset((char*)sign, ,MSG_LEN); strcpy((char*)text, "123456789 123456789 123456789 12a");
char pubkey[]="c:\\rsa_public_key.pem";
char prikey[]="c:\\rsa_private_key.pem";
if(!rsa_sign(text,prikey,sign,&len))
{
printf("sign error\n");
return -;
}
printf("sign %d:",strlen((char*)sign));
print_hex(sign);
if(!rsa_verify(text,pubkey,sign,len))
{
MessageBox(NULL,_T("verify error"),_T(""),);
printf("verify error\n");
return -;
}
printf("verify ok\n");
MessageBox(NULL,_T("verify ok"),_T(""),);
return ;
}

调用test()方法,提示"verify ok "代表成功。