1 #include <Rinternals.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <openssl/crypto.h>
5 #include <openssl/pem.h>
6 #include "utils.h"
7 
R_rsa_encrypt(SEXP data,SEXP keydata)8 SEXP R_rsa_encrypt(SEXP data, SEXP keydata) {
9   const unsigned char *ptr = RAW(keydata);
10   RSA *rsa = d2i_RSA_PUBKEY(NULL, &ptr, LENGTH(keydata));
11   bail(!!rsa);
12   int keysize = RSA_size(rsa);
13   unsigned char* buf = OPENSSL_malloc(keysize);
14   int len = RSA_public_encrypt(LENGTH(data), RAW(data), buf, rsa, RSA_PKCS1_PADDING);
15   bail(len > 0);
16   RSA_free(rsa);
17   SEXP res = allocVector(RAWSXP, len);
18   memcpy(RAW(res), buf, len);
19   OPENSSL_free(buf);
20   return res;
21 }
22 
R_rsa_decrypt(SEXP data,SEXP keydata)23 SEXP R_rsa_decrypt(SEXP data, SEXP keydata){
24   const unsigned char *ptr = RAW(keydata);
25   RSA *rsa = d2i_RSAPrivateKey(NULL, &ptr, LENGTH(keydata));
26   bail(!!rsa);
27   int keysize = RSA_size(rsa);
28   unsigned char* buf = OPENSSL_malloc(keysize);
29   int len = RSA_private_decrypt(LENGTH(data), RAW(data), buf, rsa, RSA_PKCS1_PADDING);
30   bail(len > 0);
31   RSA_free(rsa);
32   SEXP res = allocVector(RAWSXP, len);
33   memcpy(RAW(res), buf, len);
34   OPENSSL_free(buf);
35   return res;
36 }
37