Passing .PEM and .KEY as string in Curl using PHP

2019-04-04 01:54发布

I've a CERT and private key files. I'm using cUrl and PHP to connect to another service. At the moment, I've cert and key in files and it works perfectly fine with following code:

$pemfile = "cert.pem";
$keyfile = "private_key.key";
$url = "someTestUrl";
$requestXml = "requestData";

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_VERBOSE, 1); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); 
curl_setopt($ch, CURLOPT_FAILONERROR, 1); 
curl_setopt($ch, CURLOPT_SSLCERT, $pemfile); 
curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM'); 
curl_setopt($ch, CURLOPT_SSLKEY, $keyfile); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXml);
$ret = curl_exec($ch);

My question is: Can I pass cert and key as strings rather passing them as files? I tried simply passing contents of respective files as strings like this:

$pemfile = "-----BEGIN CERTIFICATE-----CERTDATAASSTRING-----END CERTIFICATE-----";
$keyfile = "-----BEGIN RSA PRIVATE KEY-----PRIVATEKEYINCODE-----END RSA PRIVATE KEY-----";

...and needless to say...it didn't work :(

Any ideas? pointers? suggestions???

4条回答
ら.Afraid
2楼-- · 2019-04-04 02:39

I'm not SSL Expert but CURLOPT_SSLKEY is private.pem file of the CURLOPT_SSLCERT public.pem file?

My parameters

CURLOPT_CAINFO => /path/cacert.pem
CURLOPT_SSLKEY => /path/private.pem
CURLOPT_SSLCERT => /path/public.pem

Try my suggested answer and let me know if it is helpful or not.

查看更多
在下西门庆
3楼-- · 2019-04-04 02:52

The answer is unfortunately as easy as it is simple: No, it is not possible.

The underlying libcurl has no API for providing keys as strings, only as files!

Bonus material:

If you're sure that your libcurl is built with OpenSSL, you can actually use the CURLOPT_SSL_CTX_FUNCTION option to do it. However:

  1. that makes it an libcurl+OpenSSL specific solution

  2. I don't think PHP/CURL exposes that function (enough) to allow this. You would probably need to extend the binding code first...

(I should add that I am the main author and maintainer of libcurl.)

查看更多
唯我独甜
4楼-- · 2019-04-04 02:54

Using tmpfile() might suffice as a workaround.

$tempPemFile = tmpfile();
fwrite($tempPemFile, $pemfile);
$tempPemPath = stream_get_meta_data($tempPemFile);
$tempPemPath = $tempPemPath['uri'];

and then:

curl_setopt($ch, CURLOPT_SSLCERT, $tempPemPath); 

but make sure you close it after so the tmp file is delete

fclose($tempPemFile);
查看更多
混吃等死
5楼-- · 2019-04-04 02:54

You could create temporary files, write the strings into the files and then point to the temp files...

查看更多
登录 后发表回答