Trying to decrypt data sent from U2 subroutine in PHP - php

I am being sent encrypted test data from a U2 system to see if it can be handled and utilised to increase security.
The SUBROUTINE generating the encrypted test data in U2 is:
RESULT=''
ALGORITHM="rc2-cbc" ; * 128 bit rc2 algorithm in CBC mode
MYKEY="23232323" ; * HEX - Actual Key
IV= "12121212" ; * HEX - Initialization Vector
DATALOC=1 ; * Data in String
KEYLOC=1 ; * Key in String
ACTION=5 ; * Base64 encode after encryption
KEYACTION=1 ; * KEY_ACTUAL_OPENSSL
SALT='' ; * SALT not used
RESULTLOC=1 ; * Result in String RESULT
OPSTRING = ''
RETURN.CODE=ENCRYPT(ALGORITHM,ACTION,DATASTRING,DATALOC,MYKEY,KEYLOC,KEYACTION,SALT,IV,OPSTRING,RESULTLOC)
RETURN.CODE = OPSTRING
The data being generated and encrypted is:
[RAWDATA] => Array
(
[196346] => 05FOAA
[196347] => 05KI
[196328] => 99FOZZ16S10
)
[ENCRYPTED] => Array
(
[196346] => e0XB/jyE9ZM=
[196347] => iaYoHzxYlmM=
[196328] => BS/YmNtlzI95c9NLpl4JVHLJwI/MO3zJm6FKVqu2tcM=
)
I am using the same information in PHP using openssl_decrypt:
$encdata = array_value;
$encryptionMethod = ALGORITHM; //"rc2-cbc"
$encryptionKey = MYKEY;//"23232323"
$options = 0;
$iv = IV; //"12121212"
$decryptedMessage = openssl_decrypt( $encdata, $encryptionMethod, $encryptionKey, $options, $iv );
Return value: bool(false)
I have tried different combinations of $options and tried encrypting the same data myself and I get different results.
I have to wait 24 hours to get a new file with any changes so I wanted to cover off as many problems as possible.
I have read over the documentation and I feel that the following could potentially be issues:
ACTION=5 which I can only find 4 potential options from U2 docs - 1 - Encrypt, 2 - Encrypt, the Base64 encode, 3 - Decrypt, 4 - Base64 decode, then decrypt - Is it as simple as this being wrong? I hope so but want to cover of any other possible problems
$encdata - I have tried with OPENSSL_RAW_DATA and 0 which I can't tell because the ACTION=5 which is neither Encrypt OR Encrypt & base64 encode
$encryptionMethod - I don't think rc2-cbc is a valid option in PHP on my server but can't say categorically - I have suggested to change this to AES256
$encryptionKey - is this ok to be a string of 8 chars? Does it need to be a specific length and does it need to be in binary? (Docs have conflicting info)
$iv - same as above - is 8 chars and non-binary ok?
Any other insights before I send this off for overnight updates would be greatly appreciated.
PHP Fiddle with testing: http://phpfiddle.org/main/code/ixax-umq3

Related

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.

PHP blowfish cbc VS Perl Crypt

I'm encrypting client numbers in PHP using openssl_encrypt.
$value = '01715034842';
$key = 'pi3kn3W#k#cj3';
$iv = 'Toy#dtv!';
$cipher = 'bf-cbc';
$crypted = openssl_encrypt($value, $cipher, $key, true, $iv);
$hashValue = unpack('H*',$crypted);
The result is: 0b6b81176ac7c298ebcb294f0a581539
Also my friend programmed the other part in Perl. And he also encoded the same number using same keys and using Blowfish to (he is using Perl library: https://metacpan.org/pod/release/LDS/Crypt-CBC-2.30/CBC.pm ):
use Crypt::CBC;
use Crypt::Blowfish;
## szyfrowanie
my $key = 'pi3kn3W#k#cj3';
my $iv = 'Toy#dtv!';
my $cipher = Crypt::CBC->new( -key => $key,
-iv => $iv,
-header => 'none',
-cipher => 'Blowfish'
);
sub mkHash {
my $crypt = $cipher->encrypt_hex($_[0]);
# print 'Hash: '.$crypt."\n";
return $crypt;
}
sub deHash {
my $crypt = $cipher->decrypt_hex($_[0]);
# print 'string: '.$crypt."\n";
return $crypt;
}
my $clientHash = mkHash($smc);
And getting a different result for the same set of data:
c5377bcf0f55af641709c35928350576
So we can't use this language.
Does it depend on programming language differences? Is this is a bug in my code or language?
I think that when using the same set of data and the same encrypting (BlowFish CBC) we should get the same results in every language.
Looking forward for opinion on this case.
The working scripts
The following PHP and Perl scripts show how to achieve the same output for the two languages. I will explain some of the details below that.
PHP:
$value = '01715034842';
$cipher = 'bf-cbc';
$key = '12345678901234567890123456789012345678901234567890123456';
$option = OPENSSL_RAW_DATA;
$iv = 'Toy#dtv!';
$crypted = openssl_encrypt($value, $cipher, $key, $option, $iv);
echo($crypted)
Perl:
use Crypt::CBC;
use Crypt::Blowfish;
my $value = '01715034842';
my $key = '12345678901234567890123456789012345678901234567890123456';
my $iv = 'Toy#dtv!';
my $cipher = Crypt::CBC->new( -literal_key => 1,
-key => $key,
-iv => $iv,
-header => 'none',
-cipher => 'Blowfish'
);
my $crypted = $cipher->encrypt($value);
print $crypted;
Using diff on the two outputs results in no difference, showing they are the same:
$ diff <(php encrypt.php) <(perl encrypt.pl)
$
Details explaining the required changes
The following sections explain the required changes, compared to your original code.
Encryption key
The PHP openssl_encrypt() function always expects a raw key. The bytes that you give it, are the bytes used as the encryption key. The Perl CBC class on the other hand expects a passphrase by default, from which it will derive the encryption key by doing an MD5 hash. If you want the class to use your raw bytes as the encryption key, you have to set the parameter literal_key to 1.
After you have done that, the CBC class expects the key to be the exact number of bytes needed for the encryption scheme, which the CBC class assumes to be 56 for the Crypt::Blowfish implementation. Hence the adjusted key in the scripts. The error you will get otherwise is If specified by -literal_key, then the key length must be equal to the chosen cipher's key length of 56 bytes
Output format
The PHP openssl_encrypt() function by default returns a base64 encoded string, the CBC class returns the raw bytes. One way to make this consistent is by setting the OPENSSL_RAW_DATA option in PHP.
Inspecting the ciphertext
If you want to inspect the ciphertext in a readable format, you can add your own print routines at the end or pipe the output into a tool like hexdump or xxd
$ php encrypt.php | xxd
00000000: 5f35 3205 74e8 dcaa 2f05 9aa4 366e ef8b _52.t.../...6n..
$ perl encrypt.pl | xxd
00000000: 5f35 3205 74e8 dcaa 2f05 9aa4 366e ef8b _52.t.../...6n..

Decrypt a des string in to plain text

I need to decrypt a string encrypted with des algorithm. How can I do in PHP? I have real test cases as follows:
key ='0123456789abcdef'
encryptedValue = '88C10F0B8C084E5F'; //hex value
decodedValue = '2020202039353538'; // this is hex
I've tried
$keyValue ='0123456789abcdef';
$encryptedValue = '88C10F0B8C084E5F'; //hex value
$decodedValue = '2020202039353538'; // this is hex
$decryptedData = mcrypt_decrypt( MCRYPT_DES, $keyValue, $encryptedValue , 'ecb');
var_dump($decryptedData);
var_dump($decodedValue);
Output of decryptedData is null. I checked this solution. Please suggest me a solution.
Update:2017 Jan 18:
Many people are suggeting me not use des or mcrypt. I need to decrypt this because my API provider reponds me with this algorithm. And about mcrypt_decrypt function, I did not find an alternative. Now please suggest me more.
I tried according to #duskwuff, I made modifications as.
$decryptedData = mcrypt_decrypt( MCRYPT_DES, $keyValue, hex2bin($encryptedValue) 'ecb');
var_dump(bin2hex($decryptedData));
Output is empty string which is obviously binary representation of bool false
For you convenience I want to share the result of crypto calculator.
I'm getting this warning as well:Warning: mcrypt_decrypt(): Key of size 16 not supported by this algorithm. Only keys of size 8 supported in /var/www/html/encdec/enc.phtml on line 13
The values you're passing into mcrypt_decrypt() look like they're intended to be a representation of hexadecimal data, not passed in directly. Use hex2bin() on the inputs to convert them to binary data, and bin2hex() to convert the output back to the expected representation.
Also, stop using mcrypt. It's old and broken, and has been removed from PHP 7.2.
I solved my issue by using following code:
$keyValue ='0123456789abcdef'; //hex value
$encryptedOrderId = '88C10F0B8C084E5F'; //hex value
$decodeValueByOnlineTool = '2020202039353538'; // this is hex
$opensslDecrypt = openssl_decrypt( hex2bin($encryptedOrderId) , 'des-ecb' , hex2bin($keyValue) , OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING , '' );
var_dump($opensslDecrypt);

Encrypting in Coldfusion and then decrypting in PHP

I have a problem reproducing the same result generated in PHP vs Coldfusion.
In PHP encrypting this way:
<?php
$key = "$224455#";
$Valor = "TESTE";
$base = chop(base64_encode(mcrypt_encrypt(MCRYPT_DES, $key, $Valor, MCRYPT_MODE_ECB)));
?>
I have the result:
TzwRx5Bxoa0=
In Coldfusion did so:
<cfset Valor = "TESTE">
<cfset Key = "$224455#">
<cfset base = Encrypt(Valor,ToBase64(Key),"DES/ECB/PKCS5Padding","BASE64")>
Result:
qOQnhdxiIKs=
What isn't ColdFusion yielding the same value as PHP?
Thank you very much
(Too long for comments)
Artjom B. already provided the answer above. Artjom B. wrote
The problem is the padding. The mcrypt extension of PHP only uses
ZeroPadding [...] you either need to pad the plaintext in php [...] or
use a different cipher in ColdFusion such as "DES/ECB/NoPadding". I
recommend the former, because if you use NoPadding, the plaintext must
already be a multiple of the block size.
Unfortunately, it is difficult to produce a null character in CF. AFAIK, the only technique that works is to use URLDecode("%00"). If you cannot modify the PHP code as #Artjom B. suggested, you could try using the function below to pad the text in CF. Disclaimer: It is only lightly tested (CF10), but seemed to produce the same result as above.
Update:
Since the CF encrypt() function always interprets the plain text input as a UTF-8 string, you can also use charsetEncode(bytes, "utf-8") to create a null character from a single element byte array, ie charsetEncode( javacast("byte[]", [0] ), "utf-8")
Example:
Valor = nullPad("TESTE", 8);
Key = "$224455#";
result = Encrypt(Valor, ToBase64(Key), "DES/ECB/NoPadding", "BASE64");
// Result: TzwRx5Bxoa0=
WriteDump( "Encrypted Text = "& Result );
Function:
/*
Pads a string, with null bytes, to a multiple of the given block size
#param plainText - string to pad
#param blockSize - pad string so it is a multiple of this size
#param encoding - charset encoding of text
*/
string function nullPad( string plainText, numeric blockSize, string encoding="UTF-8")
{
local.newText = arguments.plainText;
local.bytes = charsetDecode(arguments.plainText, arguments.encoding);
local.remain = arrayLen( local.bytes ) % arguments.blockSize;
if (local.remain neq 0)
{
local.padSize = arguments.blockSize - local.remain;
local.newText &= repeatString( urlDecode("%00"), local.padSize );
}
return local.newText;
}
The problem is the padding. The mcrypt extension of PHP only uses ZeroPadding. It means that the plaintext is filled up with 0x00 bytes until the multiple of the block size is reached.
PKCS#5/PKCS#7 padding on the other hand fills it up with bytes that denote the number of bytes missing until the next multiple of the block size. The block size for DES is 8 bytes.
So you either need to pad the plaintext in php (See this drop-in code: A: How to add/remove PKCS7 padding from an AES encrypted string?) or use a different cipher in ColdFusion such as "DES/ECB/NoPadding". I recommend the former, because if you use NoPadding, the plaintext must already be a multiple of the block size.
$key = "$224455#";
$Valor = "TESTE";
function pkcs7pad($plaintext, $blocksize)
{
$padsize = $blocksize - (strlen($plaintext) % $blocksize);
return $plaintext . str_repeat(chr($padsize), $padsize);
}
$base = chop(base64_encode(mcrypt_encrypt(MCRYPT_DES, $key, pkcs7pad($Valor, 8), MCRYPT_MODE_ECB)));
Result:
qOQnhdxiIKs=
Don't forget to unpad the recovered plaintext if you are decrypting in PHP.

php rsa encryption function returning nothing

I am using phpseclib for RSA encryption http://phpseclib.sourceforge.net/.
This is my php code:
include('Math/BigInteger.php');
include('Crypt/RSA.php');
$message="123456";
$private_modulus = "272435F22706FA96DE26E980D22DFF67";
$private_exponent = "158753FF2AF4D1E5BBAB574D5AE6B54D";
$rsa = new Crypt_RSA();
$message = new Math_BigInteger(base64_decode($message), 256);
$private_modulus = new Math_BigInteger(base64_decode($private_modulus), 256);
$private_exponent = new Math_BigInteger(base64_decode($private_exponent), 256);
$rsa->loadKey(array('n' => $private_modulus, 'e' => $private_exponent));
$encryptedText=$rsa->encrypt($message);
echo $encryptedText;
However, encryptedText is blank. Any help?
You have some issues with public/private keys. By the look of the function $rsa->loadKey() comment, first parameter is string, but you have assigned some strange array...
/**
* Loads a public or private key
*
* Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
*
* #access public
* #param String $key
* #param Integer $type optional
*/
function loadKey($key, $type = false)
Example of working encrypt/decrypt with random public/private keys :
include('_seclib/Math/BigInteger.php');
include('_seclib/Crypt/RSA.php');
$rsa = new Crypt_RSA();
extract($rsa->createKey());
# encrypt
$message = '123456';
$rsa->loadKey($publickey);
$ciphertext = $rsa->encrypt($message);
var_dump($ciphertext);
# decrypt
$rsa->loadKey($privatekey);
var_dump($rsa->decrypt($ciphertext));
See documentation for more info.
When an encryption mode isn't explicitely defined it defaults to OAEP. OAEP requires the key be at least 2 * the hash size + 2. The default hash phpseclib uses is sha1, which has a length of 20 bytes. So the key needs to be at least 22 bytes long or 176 bits.
Yours is 16 bytes long or 128 bits.
So you either need to use a larger key or change the encryption mode to use PKCS1 padding. PKCS1 padding requires the modulo be at least 11 bytes.
It'd probably be useful if phpseclib displayed an error when the length of the chosen modulo was insufficient. I'll try to suggeste that to him.
Also, FWIW, textbook RSA doesn't impose any minimum length requirements, but phpseclib doesn't currently implement textbook RSA. I guess you can kinda get it by calling _exponentiate directly but that's the only way.
Textbook RSA is bad because it's vulnerable to certain types of attacks that randomized padding like PKCS1 / OAEP protect against.

Categories