标签:perror har bsp signed 头文件 def ike amp style
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 "代表成功。
标签:perror har bsp signed 头文件 def ike amp style
原文地址:https://www.cnblogs.com/lvlv/p/8850219.html