Dynamic Encryption key in CodeIgniter 3 config - php

I am trying to follow the instruction of CI 3 docs about encryption https://codeigniter.com/userguide3/libraries/encryption.html#setting-your-encryption-key I apply the instruction but it won't make pretty output like I want, here is the standard code
$this->load->library('encryption');
$key = $this->encryption->create_key(16);
// Get a hex-encoded representation of the key:
$key = bin2hex($this->encryption->create_key(16));
// Put the same value in your config with hex2bin(),
// so that it is still passed as binary to the library:
$config['encryption_key'] = hex2bin(<your hex-encoded key>);
but i am getting this error
how to solve this error? or I am writing some wrong code?

If you use the Encryption class, you must set an encryption key. and dynamic Encryption key must be set on indivisible controller file.single Encryption key set on config.php file
//single encryption key
$config['encryption_key'] = '';
//dynamic encryption key
$this->load->library('encryption'); //load encryption library in your controller
$key = bin2hex($this->encryption->create_key(16));
$config['encryption_key'] = hex2bin();

Related

Decrypt with different key in Laravel

I am using Laravel to decrypt a string encrypted from another application (also in Laravel) but I have a problem at the beginning.
I created a new object from \Illuminate\Encryption\Encrypter class in this way in order to use a different key instead the default one:
$new_encypter = new \Illuminate\Encryption\Encrypter("base64:ABCDEFGHIJKLF=", config('app.cipher'));
but I have this error:
The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.
The key that I used is a valid key because is from another Laravel application that works correctly and used the same encryption configuration.
The cipher passed to the constructor is correct because in the exception trace there is this line of code:
Illuminate\Encryption\Encrypter::__construct("base64:ABCDEFGHIJKLF=", "AES-256-CBC")
Where is the error?
I am using Laravel 6.
The key is base64 encoded and prefixed with base64:. You would have to remove the prefix and base64 decode it.
This is how the EncryptionServiceProvider does it:
// get the app config
$config = $app->make('config')->get('app');
// see if the key starts with 'base64:'
if (Str::startsWith($key = $this->key($config), 'base64:')) {
// decode the key
$key = base64_decode(substr($key, 7));
}
return new Encrypter($key, $config['cipher']);
$this->key() just retrieves the key key from the config array.

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

Encrypt database connection .env in laravel

When we put laravel project to localhost. Anyone can view our project .env file and they can view our database password DB_USERNAME= DB_PASSWORD= how can we encrypt it??
You can just set a encrypted string as password in the '.env' file and decrypt it in your code. But I dont think that it will increase the security level on your system. Much more important is set the right configuration on the server (permissions, file locations, etc.).
You can access environment variables using $_SERVER , $_ENV (PHP super global variables) and env helper and after this encrypt your environment variables value and decrypt when assign value to a variable . For more information laravel docs
If you have not enough time than you also find this package to make it easy to add encrypted environment variables BaglerIT package
This worked for me:
In your database.php:
use Illuminate\Encryption\Encrypter;
$key = 'a3c4b614a1f072e0f968c2712a36323f'; //A md5 hash (length 32)
$encrypter = new Encrypter($key, 'AES-256-CBC');
//encrypt test:
//$str = $encrypter->encryptString('your_password');
//die($str);
...
'connections' => [
'oracle' => [
...
'password' => $encrypter->decryptString(env('DB_PASSWORD')),
...
],
...
then you can set DB_PASSWORD in your .env file encrypted as this:
// Code to get the encrypted value
use Illuminate\Encryption\Encrypter;
$key = 'a3c4b614a1f072e0f968c2712a36323f'; // same key is used for decrypt
$encrypter = new Encrypter($key, 'AES-256-CBC'); // same key and cipher used for decrypt
$str = $encrypter->encryptString('your_password'); // <- THIS IS YOUR DB_PASSWORD VALUE

Session class error that requires an encryption key in codeigniter

I'm new to codeigniter and have an okay experience with php. I recently encountered an error where codeigniter tells me
"In order to use the Session class you are required to set an encryption key in your config file."
And I heard the solution was to paste in
$config['encryption_key'] = 'your_encryption_key_here';
in the config file.
Now I have absolutely no idea what just happened here. What is this encryption key? Why is it required for session class and what's the point?
Thank you everyone.
From the Session class documentation:
Note: Even if you are not using encrypted sessions, you must set an encryption key in your config file which is used to aid in preventing session data manipulation.
Also, you shouldn't need to paste anything. $config['encryption_key'] already exists in config.php but is set to an empty string:
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class or the Session class you
| MUST set an encryption key. See the user guide for info.
|
*/
$config['encryption_key'] = '';

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