1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include <stdlib.h> #include <stdio.h> #include <string.h> #include <openssl/pem.h> #include <openssl/rsa.h>
int main() { char plain[256]="0123456789";
char encrypted[1024];
char decrypted[1024];
const char* pub_key="public.pem"; const char* priv_key="private.pem";
FILE* pub_fp=fopen(pub_key,"r"); if(pub_fp==NULL){ printf("failed to open pub_key file %s!\n", pub_key); return -1; }
RSA* rsa1=PEM_read_RSA_PUBKEY(pub_fp, NULL, NULL, NULL); if(rsa1==NULL){ printf("unable to read public key!\n"); return -1; } if(strlen(plain)>=RSA_size(rsa1)-41){ printf("failed to encrypt\n"); return -1; } fclose(pub_fp);
int len=RSA_public_encrypt(strlen(plain), plain, encrypted, rsa1, RSA_PKCS1_PADDING); if(len==-1 ){ printf("failed to encrypt\n"); return -1; } FILE* fp=fopen("out.txt","w"); if(fp){ fwrite(encrypted,len,1,fp); fclose(fp); } FILE* priv_fp=fopen(priv_key,"r"); if(priv_fp==NULL){ printf("failed to open priv_key file %s!\n", priv_key); return -1; }
RSA *rsa2 = PEM_read_RSAPrivateKey(priv_fp, NULL, NULL, NULL); if(rsa2==NULL){ printf("unable to read private key!\n"); return -1; } len=RSA_private_decrypt(len, encrypted, decrypted, rsa2, RSA_PKCS1_PADDING); if(len==-1){ printf("failed to decrypt!\n"); return -1; } fclose(priv_fp);
decrypted[len]=0; printf("%s\n",decrypted);
}
|