0
votes

I've to encrypt in PHP a 16 chars string by the RSA algoritm and PKCS#1 pattern with a public key included in a certificate (called SanitalCF.cer). Finally have to encode in base64.

I tryed this code, what's wrong?

function EncryptData($source) 
{ 
  $fp=fopen("cert/SanitelCF.cer","r"); 
  $pub_key=fread($fp,8192); 
  fclose($fp); 

  openssl_public_encrypt($source,$crypttext, $pub_key ); 

  return(base64_encode($crypttext)); 
}
1
I don't know, what happens when you run it? - President James K. Polk
Please include your certificate as well, PEM encoded (you can use the openssl command line to convert it, when required). - Maarten Bodewes
Why do you want to use the insecure PKCS#1 padding format? See also: ROBOT. You want libsodium or OAEP instead. - Scott Arciszewski

1 Answers

0
votes

First of all, make sure your certifiate is in PEM format (not DER format). You can do this using file <file>.cer. If it isn't, convert it using mv <file>.cer <file>.der; openssl x509 -inform DER -in <file>.der -out <file>.cer. Substitute your own certificate file name of course.

Now the certificate isn't a public key, it contains a public key, so you should do something like this:

<?php
function EncryptData($source) 
{ 
  $fp=fopen("<file>.cer","r"); 
  $cert_data=fread($fp,8192); 
  fclose($fp); 

  $cert = openssl_x509_read($cert_data);
  $pub_key = openssl_get_publickey($cert);
  openssl_public_encrypt($source, $crypttext, $pub_key ); 

  return(base64_encode($crypttext)); 
}

EncryptData("owlstead");
?>