Call to undefined function openssl_public_encrypt() in PHP - php

I am using WAMP 2.4.4. To encrypt a String I used the "MyEncryption" class, but the error is:
Call to undefined function openssl_public_encrypt()
Is there any special library that i must add before using openssl_public_encrypt()
class MyEncryption
{
public $pubkey = '...public key here...';
public $privkey = '...private key here...';
function encrypt($data)
{
if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
$data = base64_encode($encrypted);
else
throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');
return $data;
}
}
$url = new MyEncryption();
$d = "Hello World";
$enc = $url->encrypt($d);
echo "Encryption is: ", $enc;

Is there any special library that i must add before using openssl_public_encrypt()?
Yes there is, it is called OpenSSL and you find it documented in the PHP manual here:
http://php.net/book.openssl
Depending on your operating system flavor the package is called php-openssl and all you need to do is to install it. Then it should be automatically available in PHP.
This is similar in the WAMP UI, which you can use to enable php_openssl as well. Only in case you're concerned for the commandline you need to do more work, see the related question:
Composer Warning: openssl extension is missing. How to enable in WAMP

Please enable the php_openssl extension in the WAMP -> PHP -> PHP Extensions.

PHP Documentation provides useful information on how to make it work on Windows

You can use phpseclib, a pure PHP RSA implementation, instead of openssl_public_encrypt. eg.
<?php
include_once('Crypt/RSA.php');
$pubkey = file_get_contents('/path/to/public.key');
$rsa = new Crypt_RSA();
$rsa->loadKey($pubkey);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt('ddd');

To use the openssl_ functions, you have to
a) have OpenSSL installed, and
b) build PHP with OpenSSL support.
See the PHP OpenSSL docs.
answer taken from Why can't I use openssl_encrypt?

Related

Generating URL safe encrypted ids in Codeigniter

For encryption of parameters in url, I am using codeigniter encrypt class after extending it. The purpose of extending was to remove /+- from encryption. This was working fine. But after upgrading to PHP 7.1 it is showing deprecation error of mcrypt related methods and documentation is also recommending to use openssl provided in Encryption library. So I implemented it
$this->load->library('encryption');
$this->encryption->initialize(
array('driver' => 'openssl')
);
$this->encryption->encrypt($vendor->vid);
But its generating encrypted ids with / in it.
8da179e79fee45aa3c569d6c54653c99626d57b074fa599f8a109cb0c5f2edb6d7def3f1a6daf5b449d467976a8a32de0819b9af6d84b068f9ec903d41c2bcb9H/eQluY5LUANEDwmCh+/trIvaJu2Bemj2p9J2MnEMII=
How to generate url safe encrypted parameters using openssl in CI ?
A simple solution to this problem is to replace the delimiters that you don't want with another url safe delimiters by extending the core encryption library as you did and use something like this:
function encode($string)
{
$encrypted = parent::encrypt($string);
if ( !empty($string) )
{
$encrypted = strtr($encrypted, array('/' => '~'));
}
return $encrypted;
}
function decode($string)
{
$string = strtr($string, array('~' => '/'));
return parent::decrypt($string);
}
maybe not answering your question but can solve in way obfuscating url safe id
for generate encrypt id just like Youtube watch id i use Hashids Spark for CodeIgniter
https://github.com/sekati/codeigniter-hashids
the purpose of this helper is implementing Hashids to generate hashes (like YouTube or Bitly) from numbers to obfuscate database IDs.
installation just like at instruction i modify the hashids_helper.php at line 20
require_once FCPATH . 'sparks/sk-hashids/' . HASHIDS_VERSION . '/vendor/Hashids.php';
to
require_once FCPATH . 'vendor/Hashids.php'; //according to your Hashids path

phpseclib 2.0.12 SFTP with private RSA key login failure

I use phpseclib to log in to an SFTP server using a RSA private key. I'm upgrading from phpseclib 1.0 on PHP 5.3 to phpseclib 2.0.12 on PHP 7.2. The old code on PHP5 works just fine, but the upgraded version fails to log in, resulting in the following error message: 1024 Connection closed prematurely in SSH2.php on line 3939. Here are the two different versions:
OLD phpseclib1.0 on PHP5.3 CODE (working):
$key = new Crypt_RSA();
$key->loadKey(file_get_contents('rsaprivate.key'));
$sftp = new Net_SFTP('urltosftpserver');
$sftp->login('username', $key)
NEW phpseclib 2.0.12 on PHP7.2 CODE (failing):
$key = new phpseclib\Crypt\RSA();
$key->loadKey(file_get_contents(__DIR__.'/rsaprivate.key'));
$sftp = new phpseclib\Net\SFTP('urltosftpserver');
$sftp->_privatekey_login("username", $key);
When I look at the value of $key, they don't match in the two different versions of my code. phpseclib1.0 creates integers for value, and phpseclib2.0 creates hex numbers. When I convert the pubseclib 2.0 hex numbers to to integers, they don't match the integers created by pubseclib 1.0. But I am not sure if this has anything to do with my problem.
SNIPPLET FROM pubseclib1.0 var_dump($key):
[value] => 42318...
[is_negative] =>
[generator] => mt_rand
[precision] => -1
[bitmask] =>
[hex] =>
SNIPPLET FROM pubseclib2.0 var_dump($key):
[value] => 0x60f23...
[engine] => bcmath (OpenSSL)
I don't know it it's the RSA key that causes the problem or the _privatekey_login method.
Short Answer
From your 2.0 code:
$sftp->_privatekey_login("username", $key);
Don't do that. Do this:
$sftp->login("username", $key);
Long Answer
login calls _login, which calls _connect and _login_helper. _connect is where fsockopen is called. _login_hepler then conditionally calls _privatekey_login. By calling _privatekey_login directly you're bypassing all the steps that phpseclib normally does.
The documentation does not tell you to do this. The only way you could have even learned about that method is by looking at the source code. Per the PHPDoc comments above _privatekey_login it's clear that that method is intended to be a private method and yet you're still calling it. Indeed, it's comparable method is private in the master branch.

OpenSSL only generates public key [duplicate]

Okay, well, this is my first time working with encryption on a project. I am using my hosting provider for SSL, but I also want to encrypt portions of the database that are sensitive. For this, I was told to use OpenSSL. I am testing it on my localhost (WAMP), and have installed OpenSSL and turned on the PHP and Apache SSL mods. Okay, so i've been following tutorials and, using several suggested methods, have been able to generate the public key and store it as a file. For some reason, I can't seem to generate the private key. I will post two versions of code that i've tried:
// generate private key
$privateKey = openssl_pkey_new(array(
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');
// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);
// write public key to file
file_put_contents('public.key', $publicKey['key']);
// clear key
echo $privateKey;
?>
This generates a public.key file, but provides me the warnings "openssl_pkey_export_to_file(): cannot get key from parameter 1:" and " openssl_pkey_get_details() expects parameter 1 to be resource, boolean."
I also tried an alternative method:
$config = array(
"config" => "E:/wamp/bin/apache/apache2.2.22/conf/openssl.cnf",
"digest_alg" => "sha512",
"private_key_bits" => 1024,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
// Create the private and public key
$res = openssl_pkey_new($config);
// Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey, NULL);
echo "Private Key: ".$privKey;
// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];
echo "Public Key: ".$pubKey;
$data = 'plaintext data goes here';
echo "Data: ".$data;
// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);
echo "Encrypted: ".$encrypted;
// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey);
echo "Decrypted: ".$decrypted;
This was supposed to echo everything, unfortunately my result was a blank private key, a fine public key, plaintext, and encrypted text, and an error when trying to decrypt: "openssl_private_decrypt(): key parameter is not a valid private key"
Clearly, i'm having a problem with private key creation. I've searched the internet thoroughly and haven't been able to fix it, even though I've implemented simple code that seems to work for everyone else.
Thanks in advance,
Elie Zeitouni
I know that it has been a while and you may have already solved it but I think that my answer can be helpful for other people who faced the same problem (Like I did).
So if you take a look at the openssl_pkey_export() documentation you can find that it takes four different parameters. If we take a look at your second implementation we can see that you have only provided three.
openssl_pkey_export($res, $privKey, NULL);
This would be just as fine if only your server have the right environment variables for OPENSSL_CONF. Linking to the openssl.cnf file, which as quoted in the README-SSL.txt file that is downloaded with XAMPP is required to make use of CSR and key generation functions from PHP.
To use the CSR and key generation functions from PHP, you will need to install an openssl.cnf file. We have included a sample file that can be used for this purpose in this folder alongside this readme file.
For this reason just as you did for the openssl_pkey_new($config); you must create a associative array containing the config => '/path/to/openssl.cnf'. Just like this:
openssl_pkey_export($res, $privKey, NULL, $config);
I would like to also add that the path of openssl.cnf in my case is inside:
C:\xampp\php\extras\openssl\openssl.cnf
Inside here you will also be able to find a README-SSL.txt file which give a good explaination of how to configure OPENSSL.
Hope it helps. :)
I think you might have an easier time with phpseclib, a pure PHP RSA implementation. The following example will create a 1024-bit RSA private / public key:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
extract($rsa->createKey());
echo $privatekey . '<br/>' . $publickey;
?>
Banged around my head with getting this to work on windows10 with xampp php 5.5. Finally figured tabone's answer above was in the right direction EXCEPT path format needed to be forward slashed!
C:/xampp/php/extras/openssl/openssl.cnf
Hope this helps someone.
I Had the same problem.
And it is Windows problem's !!!
It won't happen on unix base systems.
And, If like me you use Windows only for Development, you use PuTTYGen to generate a key, and use it, static, in dev enviroment !
OR
OpenSSL not working on Windows, errors 0x02001003 0x2006D080 0x0E064002
use : openssl_pkey_export_to_file($result, 'privkey.pem', null, $config);
This worked for wampp/php 7.0.4
$privateKey = openssl_pkey_new(array(
'config' => 'C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf',
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');
// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);
// write public key to file
file_put_contents('public.key', $publicKey['key']);
// clear key
echo $privateKey;

OpenSSL won't create private keys?

Okay, well, this is my first time working with encryption on a project. I am using my hosting provider for SSL, but I also want to encrypt portions of the database that are sensitive. For this, I was told to use OpenSSL. I am testing it on my localhost (WAMP), and have installed OpenSSL and turned on the PHP and Apache SSL mods. Okay, so i've been following tutorials and, using several suggested methods, have been able to generate the public key and store it as a file. For some reason, I can't seem to generate the private key. I will post two versions of code that i've tried:
// generate private key
$privateKey = openssl_pkey_new(array(
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');
// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);
// write public key to file
file_put_contents('public.key', $publicKey['key']);
// clear key
echo $privateKey;
?>
This generates a public.key file, but provides me the warnings "openssl_pkey_export_to_file(): cannot get key from parameter 1:" and " openssl_pkey_get_details() expects parameter 1 to be resource, boolean."
I also tried an alternative method:
$config = array(
"config" => "E:/wamp/bin/apache/apache2.2.22/conf/openssl.cnf",
"digest_alg" => "sha512",
"private_key_bits" => 1024,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
// Create the private and public key
$res = openssl_pkey_new($config);
// Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey, NULL);
echo "Private Key: ".$privKey;
// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];
echo "Public Key: ".$pubKey;
$data = 'plaintext data goes here';
echo "Data: ".$data;
// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);
echo "Encrypted: ".$encrypted;
// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey);
echo "Decrypted: ".$decrypted;
This was supposed to echo everything, unfortunately my result was a blank private key, a fine public key, plaintext, and encrypted text, and an error when trying to decrypt: "openssl_private_decrypt(): key parameter is not a valid private key"
Clearly, i'm having a problem with private key creation. I've searched the internet thoroughly and haven't been able to fix it, even though I've implemented simple code that seems to work for everyone else.
Thanks in advance,
Elie Zeitouni
I know that it has been a while and you may have already solved it but I think that my answer can be helpful for other people who faced the same problem (Like I did).
So if you take a look at the openssl_pkey_export() documentation you can find that it takes four different parameters. If we take a look at your second implementation we can see that you have only provided three.
openssl_pkey_export($res, $privKey, NULL);
This would be just as fine if only your server have the right environment variables for OPENSSL_CONF. Linking to the openssl.cnf file, which as quoted in the README-SSL.txt file that is downloaded with XAMPP is required to make use of CSR and key generation functions from PHP.
To use the CSR and key generation functions from PHP, you will need to install an openssl.cnf file. We have included a sample file that can be used for this purpose in this folder alongside this readme file.
For this reason just as you did for the openssl_pkey_new($config); you must create a associative array containing the config => '/path/to/openssl.cnf'. Just like this:
openssl_pkey_export($res, $privKey, NULL, $config);
I would like to also add that the path of openssl.cnf in my case is inside:
C:\xampp\php\extras\openssl\openssl.cnf
Inside here you will also be able to find a README-SSL.txt file which give a good explaination of how to configure OPENSSL.
Hope it helps. :)
I think you might have an easier time with phpseclib, a pure PHP RSA implementation. The following example will create a 1024-bit RSA private / public key:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
extract($rsa->createKey());
echo $privatekey . '<br/>' . $publickey;
?>
Banged around my head with getting this to work on windows10 with xampp php 5.5. Finally figured tabone's answer above was in the right direction EXCEPT path format needed to be forward slashed!
C:/xampp/php/extras/openssl/openssl.cnf
Hope this helps someone.
I Had the same problem.
And it is Windows problem's !!!
It won't happen on unix base systems.
And, If like me you use Windows only for Development, you use PuTTYGen to generate a key, and use it, static, in dev enviroment !
OR
OpenSSL not working on Windows, errors 0x02001003 0x2006D080 0x0E064002
use : openssl_pkey_export_to_file($result, 'privkey.pem', null, $config);
This worked for wampp/php 7.0.4
$privateKey = openssl_pkey_new(array(
'config' => 'C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf',
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');
// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);
// write public key to file
file_put_contents('public.key', $publicKey['key']);
// clear key
echo $privateKey;

PHP rsa get public key from pem file

How can i get publickey from pem file which is created based on rsa 364.
installed crypt(RSA.php) library still getting below error
Fatal error: Call to undefined method Crypt_RSA::loadKey() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\rsa.php
$file = "C:\key_file.pem";
$keypair = Crypt_RSA_KeyPair::fromPEMString(file_get_contents($file));
$public_key = $keypair->getPublicKey();
$rsa_pub_key = Crypt_RSA_Key::fromString($public_key->toString());
$rsa_obj = new Crypt_RSA;
$verify_status = $rsa_obj->validateSign($text,$recieved_signed_sign, $rsa_pub_key) ? 'valid' : 'invalid';
getting error as Fatal error: Call to undefined method PEAR_Error::getPublicKey() in C:\Program Files\xxxx\rsa.php
Tried same thing openssl_verify. verify is rturning 0
Trying to verify sign received with base64_encode with 384 rsa key.
**$base64DecodedStr = base64_decode("A1a0o8JzF7q12Sr4gJvYjslhg5XVA2fWy28.JyohJ05uyiZGyBpqazqb");
$status = openssl_verify($msg,$base64DecodedStr,$pub_key);**
Please help me to resolve this issue. Thanks a lot.
According to the Crypt_RSA documentation, the Crypt_RSA class doesn't have a loadKey() method. You pass the public key to the constructor as part of an associative array of parameters:
$rsa_obj = new Crypt_RSA(array('public_key' => $publickey));
My recommendation: don't use PEAR's Crypt_RSA but rather phpseclib's Crypt_RSA.
PEAR's Crypt_RSA isn't PKCS#1 compliant, meaning signatures or ciphertexst's generated with it are not going to be interoperable with other languages, it doesn't support passworded private keys, and hasn't been actively maintained for years.
More info on phpseclib:
http://phpseclib.sourceforge.net/
this is how to load public key in a php and how to know the number of bits used in its encryption and how to encrypt data. remember to split the data into chunks with maximum size of key bytes size.
<?php
// Get the public Key
$pubKey = file_get_contents("public.key");
//echo $pubKey; echo "<br>";
$res=openssl_get_publickey($pubKey); //convert pubkey into resource
$array=openssl_pkey_get_details($res); //read the resource details
$chunksize= $array['bits']; //this is the chunk size 4096
$data = 'plaintext data goes here, please encrypt and decrypt the following data';
openssl_public_encrypt($data, $encrypted, $pubKey);
?>

Categories