rsa为非对称算法,加密和解密的密钥是不同的,一个密钥进行加密,另一个密钥进行解密。这个过程是相互的,用私钥加密,公钥解密,被称为签名。用公钥加密,用私钥解密,就是通常说的加密。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#define OPENSSLKEY "test.key"
#define PUBLICKEY "test_pub.key"
#define BUFFSIZE 1024
char* STR = "abcdefghigklm";
char* my_encrypt(char *str,char *path_key);//加密
char* my_decrypt(char *str,char *path_key);//解密
long get_mesl() {
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec*1000 + tv.tv_usec/1000;
}
long get_trick() {
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec*1000000 + tv.tv_usec;
}
int main(void){
char *source = STR;
char *ptr_en,*ptr_de;
printf("source is:%s, len:%d\n",source, strlen(source));
long start = get_trick();
ptr_en=my_encrypt(source,PUBLICKEY);
long spend = get_trick() - start;
printf("spend:%ld\n", spend);
printf("after encrypt len:%d\n", strlen(ptr_en));
start = get_trick();
ptr_de=my_decrypt(ptr_en,OPENSSLKEY);
spend = get_trick() - start;
printf("spend:%ld\n", spend);
printf("after decrypt:%s, len:%d\n",ptr_de, strlen(ptr_de));
if(ptr_en!=NULL){
free(ptr_en);
}
if(ptr_de!=NULL){
free(ptr_de);
}
return 0;
}
char *my_encrypt(char *str,char *path_key){
char *p_en;
RSA *p_rsa;
FILE *file;
int flen,rsa_len;
if((file=fopen(path_key,"r"))==NULL){
perror("open key file error");
return NULL;
}
if((p_rsa=PEM_read_RSA_PUBKEY(file,NULL,NULL,NULL))==NULL){
ERR_print_errors_fp(stdout);
return NULL;
}
flen=strlen(str);
rsa_len=RSA_size(p_rsa);
p_en=(unsigned char *)malloc(rsa_len+1);
memset(p_en,0,rsa_len+1);
if(RSA_public_encrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_en,p_rsa,RSA_NO_PADDING)<0){
return NULL;
}
RSA_free(p_rsa);
fclose(file);
return p_en;
}
char *my_decrypt(char *str,char *path_key){
char *p_de;
RSA *p_rsa;
FILE *file;
int rsa_len;
if((file=fopen(path_key,"r"))==NULL){
perror("open key file error");
return NULL;
}
if((p_rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL))==NULL){
ERR_print_errors_fp(stdout);
return NULL;
}
rsa_len=RSA_size(p_rsa);
p_de=(unsigned char *)malloc(rsa_len+1);
memset(p_de,0,rsa_len+1);
if(RSA_private_decrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_de,p_rsa,RSA_NO_PADDING)<0){
return NULL;
}
RSA_free(p_rsa);
fclose(file);
return p_de;
}
测算的数据显示无论加密还是解密都耗时了1000微妙以上,详细数据调用指令也可以,openssl speed rsa ,这指令的输出很直观,不再赘述。