您的位置:首页 > 运维架构

openssl rsa+sha

2016-07-28 19:46 363 查看
//openssl genrsa -out test.key 1024
//openssl rsa -in test.key -pubout -out test_pub.key

#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#include <openssl/sha.h>
#include <openssl/aes.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>

#define PUBKEYFILE "test_pub.key"
#define OPENSSLKEY "test.key"

int pipefd[2];

void *server()
{
int len, i;
char sha256[32];
char buf[1024];
char buf2[1024];

RSA *p_rsa;
FILE *file;
int rsa_len;

if((file = fopen(OPENSSLKEY, "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);

while(1){
count = 0;
memset(buf,0,sizeof(buf));
len = read(pipefd[0],buf,sizeof(buf));

int packsize = *(int *)buf;
for(i=0; i < len; i += rsa_len){
if(RSA_private_decrypt(rsa_len,buf + 4 + i,buf2 + i, p_rsa, RSA_NO_PADDING) < 0){
return NULL;
}
}

SHA256(buf2, packsize - sizeof(sha256), sha256);
for(i=0; i < 32; i++){
printf("%02X", sha256[i]);
}
printf("\n");
if(memcmp(sha256, buf2 + packsize - sizeof(sha256), sizeof(sha256)) == 0){
printf("~~~i ,server read %d bytes :\n%s\n",len,buf2);
}
}
RSA_free(p_rsa);
fclose(file);
}

int
main(int argc, char *argv[])
{
int i;

if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}

pthread_t threadid;
pthread_create(&threadid, NULL, server, NULL);

RSA *p_rsa;
FILE *file;
int flen,rsa_len;

if((file = fopen(PUBKEYFILE, "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;
}

rsa_len = RSA_size(p_rsa);

char buf[1024];
char buf2[1024];
char sha256[32];
while(1){

memset(buf,0,sizeof(buf));
gets(buf);
int len = strlen(buf);

SHA256(buf, len + 1, sha256);
for(i=0; i < 32; i++){
printf("%02X", sha256[i]);
}
printf("\n");

memcpy(buf+len+1, sha256, sizeof(sha256));

int packsize = len + 1 + sizeof(sha256);
int hole = rsa_len - ((packsize % rsa_len == 0) ? 16 : rsa_len % 16);

*(int *)buf2 = packsize;
packsize = packsize + hole;

for(i=0; i < packsize; i += rsa_len){
if(RSA_public_encrypt(rsa_len, buf + i, buf2 + sizeof(int) + i, p_rsa, RSA_NO_PADDING) < 0){
return NULL;
}
}

write(pipefd[1], buf2, packsize + sizeof(int));
}

RSA_free(p_rsa);
fclose(file);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: