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.
Related
So I have made an encryption middleware in laravel that encrypts data using the following code
public function handle($request, Closure $next)
{
return response()->json(encrypt($response->content()),$response->status());
}
I ran the command
php artisan:generate key
So now I'm trying to decrypt this data from flutter I tried using encrypt package in flutter but still no luck in making it work.
I feel the problem is the following:
1- The key used in encryption ni laravel is APP_KEY right it is in the format base64:random string this should be my key without base64?
2- Flutter encryption package needs IV I keep trying to set it from the key but still failing would really appreciate any help.
I have never done this between laravel and dart, but i have between two laravel apps.
// bits stolen from the laravel EncryptionServiceProvider.php
if (Str::startsWith($key = env('OTHER_APPS_API_APP_KEY'), 'base64:')) {
$key = base64_decode(substr($key, 7));
}
$encrypter = new Encrypter($key, config('app.cipher')); // probably AES-256-CBC
// decrypt the data
$encrypter->decrypt($theDataToDecrypt);
If you can find a library in dart that supports the same ciper you shoud be able to do the same
I am new to the Codeigniter 4 framework and I am trying to use the Encryption Service.
I want to generate a key for encryption to store in the app/Config/Encryption.php file using the code:
$key = Encryption::createKey();
I am trying to create a key because the documentation says:
The key should be as random as possible, and it must not be a regular
text string, nor the output of a hashing function, etc. To create a
proper key, you can use the Encryption library’s createKey() method.
But when I am trying out the code given in the above link, VSCode gives me an error saying:
Undefined type 'App\Controllers\Encryption'.
And Codeigniter gives me the error: Class 'App\Controllers\Encryption' not found.
How do I use the Encryption library and solve the above error and generate a key using Encryption::createKey()?
You have to pay attention to the namespaces. Use the full namespace:
$key = \CodeIgniter\Encryption\Encryption::createKey();
or use the use keyword to first "include" the class:
use CodeIgniter\Encryption\Encryption; // usually to be put at the top after the namespace `declaration`
...
$key = Encryption::createKey();
from laravel docs
Application Key The next thing you should do after installing Laravel
is set your application key to a random string. If you installed
Laravel via Composer or the Laravel installer, this key has already
been set for you by the php artisan key:generate command.
Typically, this string should be 32 characters long. The key can be
set in the .env environment file. If you have not renamed the
.env.example file to .env, you should do that now. If the application
key is not set, your user sessions and other encrypted data will not
be secure!
What I know about application key is: If the application key is not set, generally I do get an exception.
How do this random string help to secure the session?
What are the other uses of this application key?
If I use the same application key everywhere (like staging, production etc..) does it make the application less secure?
what are some best practices for this key
As we can see its used in EncryptionServiceProvider:
public function register()
{
$this->app->singleton('encrypter', function ($app) {
$config = $app->make('config')->get('app');
// If the key starts with "base64:", we will need to decode the key before handing
// it off to the encrypter. Keys may be base-64 encoded for presentation and we
// want to make sure to convert them back to the raw bytes before encrypting.
if (Str::startsWith($key = $this->key($config), 'base64:')) {
$key = base64_decode(substr($key, 7));
}
return new Encrypter($key, $config['cipher']);
});
}
So every component that uses encryption: session, encryption (user scope), csrf token benefit from the app_key.
Rest of the questions can be answered by "how encryption" (AES) works, just open up Encrypter.php, and confirm that Laravel uses AES under the hood and encodes the result to base64.
Further more we can see how its all done by using tinker:
➜ laravel git:(staging) ✗ art tinker
Psy Shell v0.8.17 (PHP 7.1.14 — cli) by Justin Hileman
>>> encrypt('Hello World!')
=> "eyJpdiI6ImgzK08zSDQyMUE1T1NMVThERjQzdEE9PSIsInZhbHVlIjoiYzlZTk1td0JJZGtrS2luMlo0QzdGcVpKdTEzTWsxeFB6ME5pT1NmaGlQaz0iLCJtYWMiOiI3YTAzY2IxZjBiM2IyNDZiYzljZGJjNTczYzA3MGRjN2U3ZmFkMTVmMWRhMjcwMTRlODk5YTg5ZmM2YjBjMGNlIn0="
Note: I used this key: base64:Qc25VgXJ8CEkp790nqF+eEocRk1o7Yp0lM1jWPUuocQ= to encrypt Hello World!
After decoding the result we get (you can try decode your own cookie with session):
{"iv":"h3+O3H421A5OSLU8DF43tA==","value":"c9YNMmwBIdkkKin2Z4C7FqZJu13Mk1xPz0NiOSfhiPk=","mac":"7a03cb1f0b3b246bc9cdbc573c070dc7e7fad15f1da27014e899a89fc6b0c0ce"}
to understand above json (iv, value, mac) you need to understand AES:
https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
Best practices for application key
do store it in .env file only
do not store it in app.php, in fact in any git tracked file
do not change it unless you really want to
invalidate sessions/cookies (user logout)
invalidate password reset tokens
invalidate signed urls
Obvious Note: Changing application key has no effect on hashed passwords since hashing algorithms do not require encryption keys.
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();
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);
?>