1. 程式人生 > >vc++ openssl 程序簽名

vc++ openssl 程序簽名

加密 key fop OS HA 情況 mes define pri

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=0;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 0; } 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 0; } if(!RSA_verify(NID_md5,(unsigned char*)in,strlen(in),(unsigned char*)in2,len,p_rsa)) { return 0; } RSA_free(p_rsa); fclose(file); return 1; } 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 0; } if((p_rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL))==NULL) { ERR_print_errors_fp(stdout); return 0; } if(!RSA_sign(NID_md5,(unsigned char*)in,strlen(in),(unsigned char*)out,(unsigned int*)plen,p_rsa)) { return 0; } RSA_free(p_rsa); fclose(file); return 1; } int test4::test() { char text[MSG_LEN]; char sign[MSG_LEN]; int len=0; memset((char*)text, 0 ,MSG_LEN); memset((char*)sign, 0 ,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 -1; } printf("sign %d:",strlen((char*)sign)); print_hex(sign); if(!rsa_verify(text,pubkey,sign,len)) { MessageBox(NULL,_T("verify error"),_T("111"),1); printf("verify error\n"); return -1; } printf("verify ok\n"); MessageBox(NULL,_T("verify ok"),_T("111"),1); return 0; }

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

vc++ openssl 程序簽名