Clés RSA, chiffrement et déchiffrement avec openssl

Petit code pour chiffrer et déchiffrer des fichiers en RSA avec openssl
Le code génère une paire de clef 4096 bits (qui sont écrites en pem dans le répertoire courant), chiffre un fichier, et le déchiffre (histoire de montrer que ça fonctionne pour de vrai)
gcc -lcrypto -std=gnu99
#include <openssl/rsa.h> #include <glib.h> #include <openssl/pem.h> gboolean encRSA (RSA *rsa, FILE *fpClr, FILE *fpEnc) { unsigned char *buffRead, *buffWrite; int size; gboolean ret = FALSE; buffRead = g_malloc(sizeof(unsigned char)*RSA_size(rsa)); buffWrite = g_malloc(sizeof(unsigned char)*RSA_size(rsa)); while ((size = fread(buffRead, 1, RSA_size(rsa)-11, fpClr)) > 0) { size = RSA_private_encrypt (size, buffRead, buffWrite, rsa, RSA_PKCS1_PADDING); fwrite (buffWrite, 1, size, fpEnc); } ret = TRUE; return ret; } gboolean decRSA (RSA *rsa, FILE *fpEnc, FILE *fpClr) { unsigned char *buffRead, *buffWrite; int size; gboolean ret = FALSE; buffRead = g_malloc(sizeof(unsigned char)*RSA_size(rsa)); buffWrite = g_malloc(sizeof(unsigned char)*RSA_size(rsa)); while ((size = fread(buffRead, 1, RSA_size(rsa), fpEnc)) > 0) { size = RSA_public_decrypt (size, buffRead, buffWrite, rsa, RSA_PKCS1_PADDING); fwrite (buffWrite, 1, size, fpClr); } ret = TRUE; return ret; } int main(int argc, char *argv[]){ FILE *fpPriv, *fpPub; FILE *fpLicenceClr, *fpLicenceEnc, *fpLicenceDbg; RSA *rsaPub = NULL; RSA *rsaPriv = NULL; if (argc != 6){ fprintf(stderr, "USAGE : %s filePubKey filePrivKey clearLicence cypheredLience testClrLience\n", argv[0]); return -1; } if((fpPub = fopen(argv[1], "r")) == NULL){ fprintf(stderr, "Could not open %s\n", argv[1]); return -1; } if((fpPriv = fopen(argv[2], "r")) == NULL){ fprintf(stderr, "Could not open %s\n", argv[2]); return -1; } if((fpLicenceClr = fopen(argv[3], "r")) == NULL){ fprintf(stderr, "Could not open %s\n", argv[3]); return -1; } if((fpLicenceEnc = fopen(argv[4], "w")) == NULL){ fprintf(stderr, "Could not open %s\n", argv[4]); return -1; } if((fpLicenceDbg = fopen(argv[5], "w")) == NULL){ fprintf(stderr, "Could not open %s\n", argv[5]); return -1; } PEM_read_RSAPrivateKey (fpPriv, &rsaPriv, 0, NULL); PEM_read_RSAPublicKey (fpPub, &rsaPub, 0, NULL); printf(">>%p %p\n", rsaPub, rsaPriv); encRSA (rsaPriv, fpLicenceClr, fpLicenceEnc); fclose(fpLicenceEnc); if((fpLicenceEnc = fopen(argv[4], "r")) == NULL){ fprintf(stderr, "Could not open %s\n", argv[4]); return -1; } decRSA (rsaPub, fpLicenceEnc, fpLicenceDbg); fclose(fpPub); fclose(fpPriv); fclose(fpLicenceClr); fclose(fpLicenceEnc); fclose(fpLicenceDbg); return 0; }
Domaine: