RSA typically has two scenarios:
1, public key encryption, private key decryption: This is the most common situation in the field of data security communication;
2, private key verification, public key check: This is mainly used for digital signature.
Here we use the second case:
This is based on OpenSSL, first installs the OpenSSL tool, references Lib,. h files, there are many examples on the net here is not the introduction
Header file:
#pragmaOnce#include<stdio.h>#include<string.h>#include<openssl/bio.h>#include<openssl/rsa.h>#include<openssl/pem.h>#include<openssl/err.h>classtest4{ Public: Test4 (void); ~test4 (void); voidPrint_hex (Char*buff); intRsa_verify (Char*inch,Char*key_path,Char* in2,intLen); intRsa_sign (Char*inch,Char*key_path,Char* out,int*Plen); inttest ();};
CPP file
#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>#defineMsg_len (128+1)Test4::test4 (void) {}test4::~test4 (void){}voidTest4::p Rint_hex (Char*buff) { for(intI=0; buff[i];i++) printf ("%02x", (unsignedChar) buff[i]); printf ("\ n");}intTest4::rsa_verify (Char*inch,Char*key_path,Char* in2,intLen) {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, (unsignedChar*)inch, strlen (inch), (unsignedChar*) (In2,len,p_rsa)) {return 0; } rsa_free (P_RSA); fclose (file); return 1;}intTest4::rsa_sign (Char*inch,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, (unsignedChar*)inch, strlen (inch), (unsignedChar*) out, (unsignedint*) (Plen,p_rsa)) {return 0; } rsa_free (P_RSA); fclose (file); return 1;}inttest4::test () {CharText[msg_len]; CharSign[msg_len]; intlen=0; memset ((Char*) Text,0, Msg_len); memset ((Char*) sign,0, Msg_len); strcpy ((Char*) Text,"123456789 123456789 123456789 12a"); Charpubkey[]="C:\\rsa_public_key.pem"; Charprikey[]="C:\\rsa_private_key.pem"; if(!rsa_sign (text,prikey,sign,&len)) {printf ("Sign error\n"); return-1; } printf ("Sign %d:", strlen (Char*)) ; 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;}
Call the test () method to indicate that "verify OK" stands for success.
VC + + OpenSSL program signature