mcrypt_decrypt() error change key size - php

mcrypt_decrypt(): Key of size 15 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported
How Can I fix this issue? my key is set - can not change it.
It has to be a local change, I think my local PHP version is too advanced for the project I loaded.
How can I fix this?

Did you update to 5.6? It says
Invalid key and iv sizes are no longer accepted. mcrypt_decrypt() will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.
Reference
Read the last line of that quote, and there you will find your solution :)
mcrypt_decrypt(): Key of size 15 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported
That means you need to pad your key with \0 (that's what previous versions were doing for you)
$key=$key."\0";

I went ahead and created a function based on Hanky 웃 Panky's answer.
This can be used with any key length to make sure it's the correct size.
function pad_key($key){
// key is too large
if(strlen($key) > 32) return false;
// set sizes
$sizes = array(16,24,32);
// loop through sizes and pad key
foreach($sizes as $s){
while(strlen($key) < $s) $key = $key."\0";
if(strlen($key) == $s) break; // finish if the key matches a size
}
// return
return $key;
}

For Laravel 5
Just run php artisan key:generate:
Application key [EaaJgaD0uFDEg7tpvMOqKfAQ46Bqi8Va] set successfully.
If you don't see your key updated, just paste it in your .env file.
APP_KEY=EaaJgaD0uFDEg7tpvMOqKfAQ46Bqi8Va
Refresh your page

I had this issue with OSTicket 1.6 ST (yes old version I know). Hosting company just went to PHP 5.6 and it broke the Mail Fetch for cron.php. I'm posting this hoping it helps others fix this issue faster.
You have to edit the file "include/class.misc.php".
Add the function "pad_key" provided in the answer authored by #troskater to the "include/class.misc.php" file and then on line 51 in the function "decrypt" change
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt,...
to instead use
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, pad_key($salt),...

You can just use str_pad() for this. In its simplest form, this will suffice.
function padKey($key)
{
// Get the current key size
$keySize = strlen($key);
// Set an array containing the valid sizes
$validSizes = [16,24,32];
// Loop through sizes and return correct padded $key
foreach($validSizes as $validSize) {
if ($keySize <= $validSize) return str_pad($key, $validSize, "\0");
}
// Throw an exception if the key is greater than the max size
throw new Exception("Key size is too large");
}
The other answers will do just fine. I'm just taking advantage of the built in PHP function str_pad here instead of appending "\0" in a loop.

You don't need to pad the key with "\0".
I had the same issue when migrating to a new PHP 7 server and I got the message :
mcrypt_decrypt(): Key of size 19 not supported by this algorithm. Only
keys of sizes 16, 24 or 32 supported.
The key I had in the code was a string of 19 characters, I simply changed it to a string of 32 characters and everything was fine again.
So as the error message suggests, use a valid size key.

I had the same problem, but fixed it with this
public function setKey($key) {
$len = strlen($key);
if($len < 24 && $len != 16){
$key = str_pad($key, 24, "\0", STR_PAD_RIGHT);
} elseif ($len > 24 && $len < 32) {
$key = str_pad($key, 32, "\0", STR_PAD_RIGHT);
}elseif ($len > 32){
$key = substr($key, 0, 32);
}
$this->key = $key;
}

If your encryption code looks like this:
<?php
function encryptCookie($value){
if(!$value){return false;}
$key = 'aNdRgUkXp2s5v8y/B?E(H+MbQeShVmYq';
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
return trim(base64_encode($crypttext)); //encode for cookie
}
function decryptCookie($value){
if(!$value){return false;}
$key = 'aNdRgUkXp2s5v8y/B?E(H+MbQeShVmYq';
$crypttext = base64_decode($value); //decode cookie
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
?>
You will want to change the $key to a 128 or 256 bit encrypted code. I simply copied a code that I generated from here: Generate Code
I created a 256 bit code for mine which consists of 32 characters and thus fixes the issue of the invalid key size of 15 or whatever number is causing the error. So whatever is set for $key you need to change that to a valid code and then it should work fine.

Related

Warning: mcrypt_decrypt(): Key of size 21 not supported..Only keys of sizes 16, 24 or 32 supported [duplicate]

mcrypt_decrypt(): Key of size 15 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported
How Can I fix this issue? my key is set - can not change it.
It has to be a local change, I think my local PHP version is too advanced for the project I loaded.
How can I fix this?
Did you update to 5.6? It says
Invalid key and iv sizes are no longer accepted. mcrypt_decrypt() will now throw a warning and return FALSE if the inputs are invalid. Previously keys and IVs were padded with '\0' bytes to the next valid size.
Reference
Read the last line of that quote, and there you will find your solution :)
mcrypt_decrypt(): Key of size 15 not supported by this algorithm. Only keys of sizes 16, 24 or 32 supported
That means you need to pad your key with \0 (that's what previous versions were doing for you)
$key=$key."\0";
I went ahead and created a function based on Hanky 웃 Panky's answer.
This can be used with any key length to make sure it's the correct size.
function pad_key($key){
// key is too large
if(strlen($key) > 32) return false;
// set sizes
$sizes = array(16,24,32);
// loop through sizes and pad key
foreach($sizes as $s){
while(strlen($key) < $s) $key = $key."\0";
if(strlen($key) == $s) break; // finish if the key matches a size
}
// return
return $key;
}
For Laravel 5
Just run php artisan key:generate:
Application key [EaaJgaD0uFDEg7tpvMOqKfAQ46Bqi8Va] set successfully.
If you don't see your key updated, just paste it in your .env file.
APP_KEY=EaaJgaD0uFDEg7tpvMOqKfAQ46Bqi8Va
Refresh your page
I had this issue with OSTicket 1.6 ST (yes old version I know). Hosting company just went to PHP 5.6 and it broke the Mail Fetch for cron.php. I'm posting this hoping it helps others fix this issue faster.
You have to edit the file "include/class.misc.php".
Add the function "pad_key" provided in the answer authored by #troskater to the "include/class.misc.php" file and then on line 51 in the function "decrypt" change
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt,...
to instead use
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, pad_key($salt),...
You can just use str_pad() for this. In its simplest form, this will suffice.
function padKey($key)
{
// Get the current key size
$keySize = strlen($key);
// Set an array containing the valid sizes
$validSizes = [16,24,32];
// Loop through sizes and return correct padded $key
foreach($validSizes as $validSize) {
if ($keySize <= $validSize) return str_pad($key, $validSize, "\0");
}
// Throw an exception if the key is greater than the max size
throw new Exception("Key size is too large");
}
The other answers will do just fine. I'm just taking advantage of the built in PHP function str_pad here instead of appending "\0" in a loop.
You don't need to pad the key with "\0".
I had the same issue when migrating to a new PHP 7 server and I got the message :
mcrypt_decrypt(): Key of size 19 not supported by this algorithm. Only
keys of sizes 16, 24 or 32 supported.
The key I had in the code was a string of 19 characters, I simply changed it to a string of 32 characters and everything was fine again.
So as the error message suggests, use a valid size key.
I had the same problem, but fixed it with this
public function setKey($key) {
$len = strlen($key);
if($len < 24 && $len != 16){
$key = str_pad($key, 24, "\0", STR_PAD_RIGHT);
} elseif ($len > 24 && $len < 32) {
$key = str_pad($key, 32, "\0", STR_PAD_RIGHT);
}elseif ($len > 32){
$key = substr($key, 0, 32);
}
$this->key = $key;
}
If your encryption code looks like this:
<?php
function encryptCookie($value){
if(!$value){return false;}
$key = 'aNdRgUkXp2s5v8y/B?E(H+MbQeShVmYq';
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv);
return trim(base64_encode($crypttext)); //encode for cookie
}
function decryptCookie($value){
if(!$value){return false;}
$key = 'aNdRgUkXp2s5v8y/B?E(H+MbQeShVmYq';
$crypttext = base64_decode($value); //decode cookie
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
?>
You will want to change the $key to a 128 or 256 bit encrypted code. I simply copied a code that I generated from here: Generate Code
I created a 256 bit code for mine which consists of 32 characters and thus fixes the issue of the invalid key size of 15 or whatever number is causing the error. So whatever is set for $key you need to change that to a valid code and then it should work fine.

Decrypt data with python, encrypt in php

I get the necrypted string to pycrypto ,but it returned a incorrect result.
<?php
define('MCRYPT_SECRET_KEY', '1d46a31baeab9cf69184d1f92ba5b9f8');
function decode($encode_str) {
$key = pack('H*',MCRYPT_SECRET_KEY);
//var_dump($key);echo "\n";
$iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
//var_dump($iv_size);echo "\n";
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
//var_dump($iv);echo "\n";
$encode_str = str_replace(['-', '_'], ['+', '/'], $encode_str);
$mod4 = strlen($encode_str) % 4 and $encode_str .= substr('====', $mod4);
//var_dump($encode_str);echo "\n";
$decrypt = base64_decode($encode_str);
//var_dump($decrypt);echo "\n";
$decrypt = mcrypt_decrypt(MCRYPT_3DES, $key, $decrypt, MCRYPT_MODE_ECB);
return $decrypt;
}
echo "aFOYNZB4Ye4 : ".decode("aFOYNZB4Ye4")."\n";
result:
aFOYNZB4Ye4 : 13455
but when I use python,I could not get the correct result.
# coding: utf-8
import sys,os,base64
from Crypto.Cipher import DES3
key = "1d46a31baeab9cf69184d1f92ba5b9f8".decode("hex")
def urlsafe_mcryptdecode(idstr):
try:
print len(key),key,'\n'
idstr = idstr.replace('-','+').replace('_','/')
mod4 = len(idstr) % 4
data=idstr+"===="[mod4:]
#print len(data),data,'\n'
base64_str = base64.b64decode(data)
#print len(base64_str),base64_str,'\n'
cipher = DES3.new(key, DES3.MODE_ECB)
id_ = cipher.decrypt(base64_str)
#print len(id_),id_,'\n'
return id_
except Exception,e:
print "ERROR",e
return idstr+"#error"
print urlsafe_mcryptdecode("aFOYNZB4Ye4")
result is not 13455.
Before the decrypt,every result of all output is same. What's wrong with my code? Thanks.
The problem is that prior to PHP 5.6.0 the function mcrypt_decrypt() silently pads the key. Your key is 16 bytes, however, the key needs to be 24 bytes, and so it is padded internally to 24 bytes with trailing NUL bytes. This is mentioned in the newer PHP documentation for mcrypt_decrypt() - see the Changelog section.
You need to take this into account when decrypting in Python. You can do that by appending NUL bytes to the end of the decoded key using ljust():
key = "1d46a31baeab9cf69184d1f92ba5b9f8".decode("hex").ljust(24, '\0')
or
key = "1d46a31baeab9cf69184d1f92ba5b9f8".decode("hex") + ('\0' * 8)
I noticed that your PHP code generates an IV which it does not use. That's fine, it's not causing a problem, just thought I'd point that out in case you think that it's being used.
Incidentally, if you are using PHP >= 5.6.0, you need to explicitly pad the key, or use a 24 byte key in the first place. In your code you can pad like this:
$key = pack('H*x8', MCRYPT_SECRET_KEY);
which will append an additional 8 NUL bytes to the end of the key.

Decrypt random chunk of an encrypted AES-CTR file in PHP's mcrypt

I have a 1MB test file and I want to decrypt it starting from its 500KB, not from the beginning. It doesn't need to start exactly from 500KB of the file, it can start at the beginning of any chunk as long as it's not the first, I just want to learn how to do it.
With this script I can decrypt the file as long as its starts from 0KB.
$file = file_get_contents("file.dat");
$aeskey = base64_decode("sVv2g7boc/pzCDepDfV1VA==");
$iv = base64_decode("A5chWWE3D4cAAAAAAAAAAA==");
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'ctr', '');
mcrypt_generic_init($td, $aeskey, $iv);
echo mdecrypt_generic($td, $file);
Could someone please explain me if it is at least possible?
In CTR mode, a counter (128 bit for AES) is encrypted to produce a key stream that is then XORed with the plaintext or ciphertext. Usually, it is assumed that the IV is either 64 bit or 96 bit and the remaining bits are actually set to 0. The initial 64 or 96 bit are called nonce.
The size of the nonce determines how much data can be encrypted in one go without creating a many-time pad: the larger the nonce, the smaller the safe message length, but also lower probability of collisions of two nonces when they are generated randomly. Since there is no specification how big the nonce is, many frameworks don't limit the size of a nonce to a specific size.
You can use the full block size for a nonce in mcrypt.
You can
take the IV that was used from the beginning,
parse that IV as a big integer (it doesn't fit into the PHP integer type),
add to it a number, which represents as many blocks (16 byte blocks for AES) as you want to skip,
convert the number back to a binary representation and
begin decrypting from a later byte.
Steps 2-4 are accomplished by the add function in the following code.
Let's say you have a big file but want to decrypt from byte 512 (multiple of the block size for simplicity). You would add 512/16=32 to the IV.
Here is some example code:
<?php
$d = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
$k = "k0k1k2k3k4k5k6k7"; // 16 byte AES key
$bs = 16; // 16 byte block size
$iv = mcrypt_create_iv($bs);
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'ctr', '');
mcrypt_generic_init($td, $k, $iv);
$ct = mcrypt_generic($td, $d);
$dec_offset = 32;
$ct_slice = substr($ct, $dec_offset);
$iv_slice = add($iv, $dec_offset / $bs);
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'ctr', '');
mcrypt_generic_init($td, $k, $iv_slice);
$d_slice = mdecrypt_generic($td, $ct_slice);
var_dump($d_slice);
function add($big_num_str, $to_add){
$big_num = str_split(strrev($big_num_str));
for($i = 0; $i < count($big_num) ; $i++){
$tmp = ord($big_num[$i]) + $to_add;
$big_num[$i] = $tmp % 256;
$to_add = floor( $tmp / 256 );
}
while($to_add){
$big_num[$i++] = $to_add % 256;
$to_add = floor( $to_add / 256 );
}
for($i = 0; $i < count($big_num) ; $i++){
$big_num[$i] = chr($big_num[$i]);
}
return strrev(implode('', $big_num) );
}
Output:
string(32) "101112131415161718191a1b1c1d1e1f"
This also work in the exact same way for the OpenSSL extension in PHP. Here is the code.
Of course, this would be a little more complicated if you want to get a chunk that doesn't begin on a block boundary. You would have to start a block earlier and remove the excess bytes.

manipulating bytes in a binary string

I have some encryption code that works fine. In order to make it a bit sneakier, I wanted to tweak the byte array after its encrypted and un-tweak it on the other side before decryption. This way if somebody gets my encryption key, just maybe they won't figure out why its not working.
However whenever I manipulate the bytes it breaks things, which to me means I am not correctly modifying the string byte array. Here is my implementation as suggested below. Its doing the encrypt and decrypt directly after each other for testing purposes.
$string = "My Test String";
$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($size, MCRYPT_RAND);
$key = pack('H*', encryptKey());
$result = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, addpadding($string), MCRYPT_MODE_CBC, $iv);
$ordVal = ord($result[5]);
if($ordVal == 0)
{
$ordVal = 255;
}
else
{
$ordVal--;
}
//$result[5] = $ordVal;
$data = base64_encode($iv . $result);
$str = base64_decode($data);
if(!str)
{
dieEncrypted("Unable to base64 decode string");
}
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = substr($str,0,$ivSize);
$str = substr($str,$ivSize);
$ordVal = ord($str[5]);
if($ordVal == 255)
{
$ordVal = 0;
}
else
{
$ordVal++;
}
//$str[5] = $ordVal;
$key = pack('H*', encryptKey());
$result = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $str, MCRYPT_MODE_CBC, $iv);
if(!$result)
{
dieEncrypted("Unable to unencrypt string");
}
$result = strippadding($result);
echo "The result is: $result|";
If $iv[5] is really a numeric character(0-9), it should work. But otherwise, it wont because php will cast the letter / character to a numeric so that adding 1 to it makes sense. Letters numerically cast to 0, so the result will always be 0 + 1 = 1, which isn't what you want.
If you want to increment the ascii code by one, try this.
$iv[5] = ord($iv[5]) + 1;
// undo it
$iv[5] = chr($iv[5]) - 1;
Let's disregard the fact that security by obscurity doesn't work and answer your question.
Guess:
255 + 1 = 256 (or 0 for single-byte-characters). That would change zero-terminated string length.
Try base64 encoding actual byte array, and then decode it, so you don't loose anything.
Ok I figured this out. It looks like the string format of this data is such that you can't manipulate a single character. Perhaps its multi byte characters or something. Anyhow the solution was to encode to base64 as suggested above, then perform the byte manipulation using a rollover logic since base64 is not linear. This combines the ord\chr solution mentioned in the 2nd answer. So both answers put together in this manner seemed to do the trick. Thanks all!

PHP secured code with SHA1 and AES256

I have one issue, that I'm not able to solve...
Instructions:
Create hash with SHA1 from string
Take first 16 bytes from string and encode them with AES256 and KEY
You get 16 bytes signature. You have to convert this signature to 32-bytes string, which represent signature in hexadecimal
My function:
public function GetSign($str) {
$strSIGN = sha1($str, true);
$strSIGN = substr($strSIGN, 0, 16);
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, self::KEY, $iv);
$strSIGN = mcrypt_generic($td, substr($strSIGN, 0, 16));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$strSIGNhex = '';
for ($i = 0; $i < strlen($strSIGN); $i++)
{
$ord = ord($strSIGN[$i]);
$hexCode = dechex($ord);
$strSIGNhex .= ((strlen($hexCode) == 1) ? '0' : '') . $hexCode;
}
return $strSIGNhex;
}
But the result is incorrect...
Any suggestions?
Are you sure, the result is incorrect? AES256 returns different values based on the iv, which is in your case random.
Its completely acceptable to have different signatures after different executions - the only requirement is, you can verify, that the output is correct.
I'm not sure what problem this instructions should solve. As far as i understand, you want to generate a signature, using a hash and a key. This problem is normally solved with a HMAC.
With your code you won't be able to recreate the signature to do a verification, because you used the CBC mode with an IV (initialisation vector). This is actually a good thing, but you would have to store the IV too, so you could use the same IV to encrypt another string and do the verification. Of course storing the IV would result in a much longer string than 16 bytes.
Either you use the ECB mode, which doesn't need an IV, or you use the HMAC which is made for such situations.

Categories