Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing pfx certificate in a R code or converting pfx certificate into pem in R

So I am calling an API that requires me to have a pfx certificate linked either to my browser or to Postman if I am calling that API. I want to do this programmatically. If there is a code in R that let's me use my existing pfx certificate while passing the post request or a function that I can use to convert my existing pfx certificate to pem certificate. Kindly help me in solving the issue.

like image 689
Mave Avatar asked Jan 20 '26 02:01

Mave


2 Answers

I had the same problem and solved it this way:

library(openssl)
library(httr)
library(usethis)

# set up openssl in .Renviron
usethis::edit_r_environ() #opens .Renviron file in Rstudio
# include this line into .Renviron file:
CURL_SSL_BACKEND="openssl"

# read your pfx certificate 
cert <- openssl::read_p12(file = ".../yourCertificate.pfx", password = "yourKey")

# convert pfx to cert and key pem files to use in httr calls
openssl::write_pem(cert$cert, "my_cert.pem")
openssl::write_pem(cert$key, "my_key.pem")

# send request
GET("https://...", config = config(sslcert =  "my_cert.pem", sslkey = "my_key.pem"), verbose())
like image 144
NinaO Avatar answered Jan 22 '26 21:01

NinaO


As of April 2023 the get method returns an error:

schannel: Failed to import cert file my_cert.pem, last error is 0x80092002

This seems to be linked to the issue introduced in curl in 7.55.1 (see https://stackoverflow.com/a/71496170/5956120) In curl 8.0.1 using the certificate works again.

A workaround could be implemented in R:

# request via external tool curl (https://curl.se/windows/)
responseText <- system("<pathToCurl>/curl-8.0.1_6-win64-mingw/bin/curl.exe --cert my_cert.pem --key my_key.pem https://... -sS", intern = TRUE)
responseJson <- paste(responseText, collapse = '')
like image 33
Peter Drabik Avatar answered Jan 22 '26 21:01

Peter Drabik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!