Decryption in PHP - php

I am trying to decrypt data being communicated to our server. Its a certain 8 digit number which is encrypted using a scheme. I have the encryption and integrity keys with me. I have a documentation on how to decrypt it which says -
The value is encrypted using a custom encryption scheme. The
encryption scheme uses a keyed HMAC-SHA1 algorithm to generate a
secret pad based on the unique event ID. The encrypted value has a
fixed length of 28 bytes. It is comprised of a 16-byte initialization
vector, 8 bytes of ciphertext, and a 4-byte integrity signature. The
encrypted value is web-safe base-64-encoded, according to RFC 3548,
with padding characters omitted. Thus, the 28-byte encrypted value is
encoded as a 38 character web-safe base-64 string. The value is
encrypted as:
value xor HMAC-SHA1(encryption_key, initialization_vector)>
so decryption calculates:
HMAC-SHA1(encryption_key, initialization_vector)
and xor's with the encrypted value to reverse the encryption. The
integrity stage takes 4 bytes of
HMAC-SHA1(integrity_key, value||initialization_vector)>
where || is concatenation.
So i wrote the following PHP Code.
$value= "[VALUE]"; //38 character base64
$ekey=hextostr("[ENCRYPTIONKEY]"); //64 byte hex encoded key . 32 byte key
$ikey=hextostr("[INTEGRITYKEY]"); //64 byte hex encoded key . 32 byte key
$value=str_replace("-","+",$value);
$value=str_replace("_","/",$value);
$value=$value."==";
$dvalue=base64_decode($value); //Gets a 28 byte encrypted string.
$initvec=substr($dvalue,0,16);
$ciphertext=substr($dvalue,16,8);
$integritysig=substr($dvalue,24,4);
$pad=hash_hmac("sha1",$initvec,$ekey); //Generates 40 byte pad
$uncipher=$ciphertext^$pad;
print($uncipher); //This is 8 byte binary. Dumps some binary on screen. Result should be a 8 byte number
Unable to get around this problem. Please advice.

$pad=hash_hmac("sha1",$initvec,$ekey); // returns a hexstring, but XOR interprets
// as ASCII string and converts to binary
// accordingly
$ciphertext=substr($dvalue,16,8); // this is ASCII, converted to binary by XOR
$uncipher=$ciphertext^$pad; // so the XOR operation is confused in interpretation.
try changing it to,
function bin2asc($in)#syntax - bin2asc("binary to convert");
{
$out = '';
for ($i = 0, $len = strlen($in); $i < $len; $i += 8)
{
$out .= chr(bindec(substr($in,$i,8)));
}
return $out;
}
$pad= hash_hmac("sha1",$initvec,$ekey, true); // now it will return in binary
$pad = bin2asc($pad);
$uncipher=$ciphertext^$pad;
hope this solve your problem.

Your posted code should look like this
$value= "[VALUE]"; //38 character base64
$ekey=hextostr("[ENCRYPTIONKEY]"); //64 byte hex encoded key . 32 byte key
$ikey=hextostr("[INTEGRITYKEY]"); //64 byte hex encoded key . 32 byte key
$value=str_replace("-","+",$value);
$value=str_replace("_","/",$value);
$value=$value."==";
$dvalue=base64_decode($value); //Gets a 28 byte encrypted string.
$initvec=substr($dvalue,0,16);
$ciphertext=substr($dvalue,16,8);
$integritysig=substr($dvalue,24,4);
//here is the change
$pad=hash_hmac("sha1",$initvec,$ekey, true);
$uncipher=$ciphertext^$pad;
print(hexdec(strToHex($uncipher))); //This is 8 byte binary. Dumps some binary on screen. Result should be a 8 byte number

Try this
function decrypt_google_winning_price($value, $ekey, $ikey, &$reason = '') {
if (strlen($value) != 38)
{
$reason = "Wrong encrypted value length";
return false;
}
$ekey = base64_decode($ekey);
$ikey = base64_decode($ikey);
$value = strtr($value, '-_,', '+/=') . "==";
$enc_value = base64_decode($value); //Gets a 28 byte encrypted string.
if (strlen($enc_value) != 28)
{
$reason = "Wrong encrypted value length after base64_decode()";
return false;
}
$iv = substr($enc_value, 0, 16);// initialization vector (16 bytes - unique to the impression)
$p = substr($enc_value, 16, 8); // encryption key (32 bytes - provided at account set up)
$sig = substr($enc_value, 24, 4);// integrity signature (4 bytes)
$price_pad = hash_hmac("sha1", $iv, $ekey, true);
$price = $p ^ $price_pad;// XOR
$conf_sig = substr(hex2bin(hash_hmac("sha1", $price . $iv, $ikey)), 0, 4);
if ($sig !== $conf_sig)
{
$reason = "Signature is not valid";
return false;
}
return hexdec(bin2hex($price)); //This is 8 byte binary. Dumps some binary on screen. Result should be a 8 byte number
}
$value = "[VALUE]"; //38 character base64
$ekey = "[ENCRYPTIONKEY]"; //64 byte hex encoded key . 32 byte key
$ikey "[INTEGRITYKEY]"; //64 byte hex encoded key . 32 byte key
var_dump(decrypt_google_winning_price($value, $ekey, $ikey));

Related

Node.js AES-256-CBC encryption issue

I'm trying to create an encrypted string according to one sample code which is given in PHP, my main problem is Node.js crypto module doesn't accept keys with more than 32 bytes length but PHP openssl_encrypt does, it seems that's why I'm getting Invalid key size error.
here is my js code:
let iv = sha1(await HelpersService.makeRandomNumber(null, null, 16));
iv = iv.substr(0, 16);
const text = bundledData;
const password = sha1(this.credentials.appSecret);
let salt = sha1(await HelpersService.makeRandomNumber(null, null, 4));
salt = salt.substr(0, 4);
const key = crypto.createHash('sha256').update(password + salt).digest('hex');
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encoded = cipher.update(text, 'utf8', 'hex');
encoded += cipher.final('hex');
and this is the PHP sample:
function generateCashOutAPIHashKey($app_secret ){
//remove plus(+) sign from gsm number.
$data = 'text';
$iv = substr(sha1(mt_rand()), 0, 16);
$password = sha1($app_secret);
$salt = substr(sha1(mt_rand()), 0, 4);
$saltWithPassword = hash('sha256', $password . $salt);
$encrypted = openssl_encrypt("$data", 'aes-256-cbc', "$saltWithPassword", null, $iv );
return $encrypted;
}
The key generated in the PHP and NodeJS code has a length of 64 bytes. The used encryption AES-256 needs a 32 bytes key. In the PHP code, openssl_encrypt() implicitly shortens the 64 bytes key to 32 bytes. In the NodeJS code this has to be done explicitly:
const key = crypto.createHash('sha256').update(password + salt).digest('hex').substr(0, 32);
Also, openssl_encrypt() returns the ciphertext Base64 encoded by default. In the NodeJS code the result is returned hex encoded. Here you have to change the output encoding from 'hex' to 'base64' in the update() and final() call:
let encoded = cipher.update(text, 'utf8', 'base64');
encoded += cipher.final('base64');
Please note that the PHP reference code has a number of vulnerabilities:
mt_rand() is not a cryptographically secure pseudorandom number generator (CSPRNG). PHP provides cryptographically secure methods for deriving a random IV / salt, e.g. random_bytes() or random_int().
The key is inferred using SHA-256. It is more secure to use a reliable key derivation function such as PBKDF2. A 4 bytes salt is generally too small.
SHA1 is considered insecure in most contexts and must no longer be used.
Anyone have a problem with the following ?
crypto.createHash('sha256').update(password +
salt).digest('hex').substr(0, 32);
I understand the intent of needing a 32 byte value produced by sha256 but if you hex encode and then take the first 32 characters of the string you have SIGNIFICANTLY reduced the value of this. You now have a string 32 characters long that has only 16 possible values (0-9a-f) for each character. You really want a 32 byte value that has 256 possible values for each byte. You have changed your key security of your encryption key from the intended 256^32 (1.1E77) to 16^32 (3.4E38).
crypto.createHash('sha256').update('').digest('hex');
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
crypto.createHash('sha256').update('').digest('hex').substr(0,32);
'e3b0c44298fc1c149afbf4c8996fb924'
Find a way to use the byte values produced by SHA256.

Encryption: with vb.net I get a different result than php

I have this php code
$plain_text = "abc";
$salt = "123";
echo $encrypted_text = openssl_encrypt($plain_text, "AES-128-ECB", $salt);
// result: kR/1uaFarptS5+n951MVsQ==
I have tried several methods (classes and functions) on vb.net, but the result of the encryption with this language is everytime not the same as above using php.
For example this one:
Public Function AES_Encrypt (ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash (31) As Byte
Dim temp As Byte () = Hash_AES.ComputeHash (System.Text.ASCIIEncoding.ASCII.GetBytes (pass))
Array.Copy (temp, 0, hash, 0, 16)
Array.Copy (temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte () = System.Text.ASCIIEncoding.ASCII.GetBytes (input)
encrypted = Convert.ToBase64String (DESEncrypter.TransformFinalBlock (Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
End Try
End Function
sEnc = AES_Encrypt("abc", "123")
Console.WriteLine(sEnc)
'result: Z3hCHcS0b2zJ7fEod3jcrw==
Please, with vb.net (no C#), how can I get the result "kR/1uaFarptS5+n951MVsQ==" which encryption of the text "abc" and salt "123" using the algorithm "AES-128-ECB"?
Due to the specification AES-128-ECB in the PHP code, AES-128 is used in ECB mode, i.e. the key is 16 bytes long. But since only a 3 bytes large key is applied (123), PHP pads to the necessary size of 16 bytes with 0x00 values. Note that if the key is too long, it will be truncated.
In the VB code a 32 bytes key is used. Since in .NET the keysize determines the AES variant, AES-256 is applied. Moreover, the passed key is not used directly, but the actual key is derived from the passed value with the digest MD5.
So that the VB code returns the result of the PHP code, the logic of the PHP code must be implemented in the VB code:
...
'Dim hash(31) As Byte
'Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
'Array.Copy(temp, 0, hash, 0, 16)
'Array.Copy(temp, 0, hash, 15, 16)
'AES.Key = hash
Dim keyPadded(15) As Byte
Dim key = System.Text.ASCIIEncoding.ASCII.GetBytes(pass)
Array.Copy(key, 0, keyPadded, 0, Math.Min(16, key.Length))
AES.Key = keyPadded
...
A few remarks:
In the PHP code the key is called $salt. This is misleading, because a salt has a different meaning.
The ECB mode is generally insecure.
AES-128 uses a 16 bytes key. 123 is not a strong key (but maybe this is just a dummy value).
If 123 does not represent a key, but a password from which a key is derived, then in general you should not use MD5, but specially designed algorithms like PBKDF2 or Argon2, see also here.

Translate Windows RC4 CryptDeriveKey to PHP for openssl

This is the second component of the legacy system translation we’ve been trying to do. We have managed to match exactly the initial binary password/key that Windows ::CryptHashData generates.
That password/key is passed to ::CryptDeriveKey where it performs a number of steps to create the final key to be used by ::CryptEncrypt. My research has led me to the CryptDeriveKey documentation where it clearly describes the steps required to derive the key for ::CryptEncrypt but so far I haven’t been able to get it to decrypt the file on the PHP side.
https://learn.microsoft.com/en-us/windows/desktop/api/wincrypt/nf-wincrypt-cryptderivekey
Based on the ::CryptDeriveKey documentation there may be some additional undocumented steps for our specific legacy key size that may not be well understood. The current Windows ::CryptDeriveKey is set for ZERO SALT by default which is apparently different from NO_SALT somehow. See salt value functionality here:
https://learn.microsoft.com/en-us/windows/desktop/SecCrypto/salt-value-functionality
The parameters on the CryptAPI for our legacy system are as follows:
Provider type: PROV_RSA_FULL
Provider name: MS_DEF_PROV
Algo ID CALG_RC4
Description RC4 stream encryption algorithm
Key length: 40 bits.
Salt length: 88 bits. ZERO_SALT
Special Note: A 40-bit symmetric key with zero-value salt, however, is not equivalent to a 40-bit symmetric key without salt. For interoperability, keys must be created without salt. This problem results from a default condition that occurs only with keys of exactly 40 bits.
I’m not looking to export the key, but reproduce the process that creates the final encryption key that is passed to ::CryptEncrypt for the RC4 encryption algorithm and have it work with openssl_decrypt.
Here is the current windows code that’s working fine for encrypt.
try {
BOOL bSuccess;
bSuccess = ::CryptAcquireContextA(&hCryptProv,
CE_CRYPTCONTEXT,
MS_DEF_PROV_A,
PROV_RSA_FULL,
CRYPT_MACHINE_KEYSET);
::CryptCreateHash(hCryptProv,
CALG_MD5,
0,
0,
&hSaveHash);
::CryptHashData(hSaveHash,
baKeyRandom,
(DWORD)sizeof(baKeyRandom),
0);
::CryptHashData(hSaveHash,
(LPBYTE)T2CW(pszSecret),
(DWORD)_tcslen(pszSecret) * sizeof(WCHAR),
0);
::CryptDeriveKey(hCryptProv,
CALG_RC4,
hSaveHash,
0,
&hCryptKey);
// Now Encrypt the value
BYTE * pData = NULL;
DWORD dwSize = (DWORD)_tcslen(pszToEncrypt) * sizeof(WCHAR);
// will be a wide str
DWORD dwReqdSize = dwSize;
::CryptEncrypt(hCryptKey,
NULL,
TRUE,
0,
(LPBYTE)NULL,
&dwReqdSize, 0);
dwReqdSize = max(dwReqdSize, dwSize);
pData = new BYTE[dwReqdSize];
memcpy(pData, T2CW(pszToEncrypt), dwSize);
if (!::CryptEncrypt(hCryptKey,
NULL,
TRUE,
0,
pData,
&dwSize,
dwReqdSize)) {
printf("%l\n", hCryptKey);
printf("error during CryptEncrypt\n");
}
if (*pbstrEncrypted)
::SysFreeString(*pbstrEncrypted);
*pbstrEncrypted = ::SysAllocStringByteLen((LPCSTR)pData, dwSize);
delete[] pData;
hr = S_OK;
}
Here is the PHP code that tries to replicate the ::CryptDeriveKey function as described in the documentation.
Let n be the required derived key length, in bytes. The derived key is the first n bytes of the hash value after the hash computation has been completed by CryptDeriveKey. If the hash is not a member of the SHA-2 family and the required key is for either 3DES or AES, the key is derived as follows:
Form a 64-byte buffer by repeating the constant 0x36 64 times. Let k be the length of the hash value that is represented by the input parameter hBaseData. Set the first k bytes of the buffer to the result of an XOR operation of the first k bytes of the buffer with the hash value that is represented by the input parameter hBaseData.
Form a 64-byte buffer by repeating the constant 0x5C 64 times. Set the first k bytes of the buffer to the result of an XORoperation of the first k bytes of the buffer with the hash value that is represented by the input parameter hBaseData.
Hash the result of step 1 by using the same hash algorithm as that used to compute the hash value that is represented by the hBaseData parameter.
Hash the result of step 2 by using the same hash algorithm as that used to compute the hash value that is represented by the hBaseData parameter.
Concatenate the result of step 3 with the result of step 4.
Use the first n bytes of the result of step 5 as the derived key.
PHP Version of ::CryptDeriveKey.
function cryptoDeriveKey($key){
//Put the hash key into an array
$hashKey1 = str_split($key,2);
$count = count($hashKey1);
$hashKeyInt = array();
for ($i=0; $i<$count; $i++){
$hashKeyInt[$i] = hexdec($hashKey1[$i]);
}
$hashKey = $hashKeyInt;
//Let n be the required derived key length, in bytes. CALG_RC4 = 40 bits key or 88 salt bytes
$n = 40/8;
//Let k be the length of the hash value that is represented by the input parameter hBaseData
$k = 16;
//Step 1 Form a 64-byte buffer by repeating the constant 0x36 64 times
$arraya = array_fill(0, 64, 0x36);
//Set the first k bytes of the buffer to the result of an XOR operation of the first k bytes of the buffer with the hash value
for ($i=0; $i<$k; $i++){
$arraya[$i] = $arraya[$i] ^ $hashKey[$i];
}
//Hash the result of step 1 by using the same hash algorithm as hBaseData
$arrayPacka = pack('c*', ...$arraya);
$hashArraya = md5($arrayPacka);
//Put the hash string back into the array
$hashKeyArraya = str_split($hashArraya,2);
$count = count($hashKeyArraya);
$hashKeyInta = array();
for ($i=0; $i<$count; $i++){
$hashKeyInta[$i] = hexdec($hashKeyArraya[$i]);
}
//Step 2 Form a 64-byte buffer by repeating the constant 0x5C 64 times.
$arrayb = array_fill(0, 64, 0x5C);
//Set the first k bytes of the buffer to the result of an XOR operation of the first k bytes of the buffer with the hash value
for ($i=0; $i<$k; $i++){
$arrayb[$i] = $arrayb[$i] ^ $hashKey[$i];
}
//Hash the result of step 2 by using the same hash algorithm as hBaseData
$arrayPackb = pack('c*', ...$arrayb);
$hashArrayb = md5($arrayPackb);
//Put the hash string back into the array
$hashKeyArrayb = str_split($hashArrayb,2);
$count = count($hashKeyArrayb);
$hashKeyIntb = array();
for ($i=0; $i<$count; $i++){
$hashKeyIntb[$i] = hexdec($hashKeyArrayb[$i]);
}
//Concatenate the result of step 3 with the result of step 4.
$combined = array_merge($hashKeyInta, $hashKeyIntb);
//Use the first n bytes of the result of step 5 as the derived key.
$finalKey = array();
for ($i=0; $i <$n; $i++){
$finalKey[$i] = $combined[$i];
}
$key = $finalKey;
return $key;
}
PHP Decrypt Function
function decryptRC4($encrypted, $key){
$opts = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING;
$cypher = ‘rc4-40’;
$decrypted = openssl_decrypt($encrypted, $cypher, $key, $opts);
return $decrypted;
}
So here are the big questions:
Has anyone been able to successfully replicate ::CryptDeriveKey with RC4 on another system?
Does anyone know what is missing from the PHP script we created that prevents it from creating the same key and decrypt the Windows CryptoAPI encrypted file with openssl_decrypt?
Where and how do we create the 88 bit zero-salt that is required for the 40bit key?
What are the correct openssl_decrypt parameters that would accept this key and decrypt what was generated by ::CryptDeriveKey?
Yes, we know this isn’t secure and its not being used for passwords or PII. We would like to move away from this old and insecure method, but we need take this interim step of translating the original encryption to PHP first for interoperability with the existing deployed systems. Any help or guidance would be appreciated.
Just in case anyone else wanders down this path here are the answers to all the questions above.
You can replicate ::CryptDeriveKey on PHP using openssl but there are some prerequisites that have to be met on the windows side first.
CryptDeriveKey MUST be set to CRYPT_NO_SALT as follows:
::CrypeDeriveKey(hCryptProv, CALG_RC4, hSaveHash, CRYPT_NO_SALT, &hCryptKey)
This will allow you to create a key from your hash and generate a matching key in PHP that will work on openssl. If you don't set any salt parameters you will get a key that is created with an unknown proprietary salt algorithm that cant be matched on another system.
The reason that you have to set CRYPT_NO_SALT is because both the CryptAPI and openssl have proprietary salt algorithms and there is no way to get them to match. So you should do your salting separately. There are more details about this salt value functionality here: https://learn.microsoft.com/en-us/windows/desktop/SecCrypto/salt-value-functionality
Here is what the PHP script needs to look like to create an equivalent passkey for for openssl to use.
<?php
$random = pack('c*', 87,194,...........);
$origSecret = 'ASCII STRING OF CHARACTERS AS PASSWORD';
//Need conversion to match format of Windows CString or wchar_t*
//Windows will probably be UTF-16LE and LAMP will be UTF-8
$secret = iconv('UTF-8','UTF-16LE', $origSecret);
//Create hash key from Random and Secret
//This is basically a hash and salt process.
$hash = hash_init("md5");
hash_update($hash, $random);
hash_update($hash, $secret);
$key = hash_final($hash);
$key = cryptoDeriveKey($key);
//Convert the key hex array to a hex string for openssl_decrypt
$count = count($key);
$maxchars = 2;
for ($i=0; $i<$count; $i++){
$key .= str_pad(dechex($key[$i]), $maxchars, "0", STR_PAD_LEFT);
}
IMPORTANT: OpenSSL expects the key to be the raw hex values that are derived from the hash, unfortunately openssl_decrypt() wants the same value as a string or password. Therefor you have to do a hex to string conversion at this point. There is a great write up here on why you have to do this.
http://php.net/manual/en/function.openssl-encrypt.php
$opts = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING;
//Convert key hex string to a string for openssl_decrypt
//Leave it as it is for openssl command line.
$key = hexToStr($key);
$cipher = 'rc4-40';
$encrypted = “the data you want to encrypt or decrypt”;
$decrypted = openssl_decrypt($encrypted, $cipher, $key, $opts);
echo $decrypted; //This is the final information you’re looking for
function cryptoDeriveKey($key){
//convert the key into hex byte array as int
$hashKey1 = str_split($key,2);
$count = count($hashKey1);
$hashKeyInt = array();
for ($i=0; $i<$count; $i++){
$hashKeyInt[$i] = hexdec($hashKey1[$i]);
}
$hashKey = $hashKeyInt;
//Let n be the required derived key length, in bytes. CALG_RC4 = 40 bits key with 88 salt bits
$n = 40/8;
//Chop the key down to the first 40 bits or 5 bytes.
$finalKey = array();
for ($i=0; $i <$n; $i++){
$finalKey[$i] = $hashKey[$i];
}
return $finalKey;
}
function hexToStr($hex){
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2){
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
?>
If you’re having trouble getting the correct values after using the code above you can try exporting your key value from CryptoAPI and testing it with openssl command line.
First you have to set CryptDeriveKey to allow the key to be exported with CRYPT_EXPORTABLE and CRYPT_NO_SALT
::CrypeDeriveKey(hCryptProv, CALG_RC4, hSaveHash, CRYPT_EXPORTABLE | CRYPT_NO_SALT, &hCryptKey)
If you want to know how to display a PLAINTEXTKEYBLOB from the exported key follow this link.
https://learn.microsoft.com/en-us/windows/desktop/seccrypto/example-c-program--importing-a-plaintext-key
Here is an example exported key blob
0x08 0x02 0x00 0x00 0x01 0x68 0x00 0x00 0x05 0x00 0x00 0x00 0xAA 0xBB 0xCC 0xDD 0xEE
0x08 0x02 0x00 0x00 0x01 0x68 0x00 0x00 //BLOB header matches almost exactly
0x05 0x00 0x00 0x00 //Key length in bytes is correct 5 bytes
0xAA 0xBB 0xCC 0xDD 0xEE //First 5 bytes of our created hash key!!
Use your exported key value from the BLOB as the Hex Key Value in the openssl enc command below.
openssl enc -d -rc4-40 -in testFile-NO_SALT-enc.txt -out testFile-NO_SALT-dec.txt -K "Hex Key Value" -nosalt -nopad
This will decrypt the file that was encrypted on the Windows machine using CryptEncrypt.
As you can see, when you set the CryptDeriveKey to CRYPT_NO_SALT all you need for the openssl password or key is the first “keylength” bits of your CryptHashData password. Simple enough to say but a real pain to get to. Good luck and hope this helps someone else with legacy Windows translation issues.

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.

openssl_public_encrypt method doesn't encrypt beyond 118 chracters

I can encrypt small strings but when it exceeds 118 characters it doesn't seems to work ? any idea ?
private function encryptData($plaintext) {
$plaintext = '{ "id":"1" "name":"Bottled Beer" "description":"" "parent_id":"111" "taxonomy":"SIMPLE_PLU" },{ "id":"2" "name":"Stout" }';
$publicKey = "../ssh_keys/coasts/public/pub.pem";
$fp=fopen($publicKey,"r");
$pub_key_string=fread($fp,8192);
fclose($fp);
$pubKey = openssl_pkey_get_public($pub_key_string);
openssl_public_encrypt($plaintext, $encrypted, $pubKey);
return $encrypted;
}
The length of plain data used to encrypt depends on the length of your key, it must be not bigger than the number the length of key subtract 11. For example, if your use a 2048bit key, the maximum length is 2048/8 - 11 = 245.
If you need to process data more than that limit, you could separate you plain data into blocks, encrypt them each and concatenate the cipher blocks(their lengths always equals the length of your key in byte). of course, you have to do the same while decrypting the concatenated cipher data.

Categories