I'm trying to verify an external call to one of our endpoints, this endpoint is triggered by a third party, we receive a transaction data and a signature based on that transaction information, with that, we need to decrypt the signature and compare the result to verify the authenticity.
I'm trying to use openssl_public_decrypt to decrypt the signature using the provider's public key.
This is how I'm trying:
$signature = 'GcTtinhU0YgwGbZPtBwLdh+zdEe0w0W95TFPggeHMCjeDUBWgZfCZ6ZDRUk7DfT5BkKsbAi8/4o60Krcwz1JMdRjmsPf7vj33heVIB2PZJaf8eFR1jijLIsyl4vgH7BbbQ2I6kk6IcYXYWPVAHYRWxl1pJwOyNxZPr49fdW+hcw2zbpkEmj2114QBSiV6eHLowVYKLvpuiT8zLc6DN/wVzCYBuR/cg+CPHgYMeWFsuvu9J46hm6Hij00E68ldYAqVwImlmHPqfqvdEItg3Oi0ac4tXH2nCNgLPHcyU/H32NzTYC9iT1YZkoInqsU6Qv64vbU9lSMS91EQBEa5UQkUg==';
$pubKey = openssl_pkey_get_public('file://path/to/public.pem');
if( openssl_public_decrypt(base64_decode($signature), $data, $pubKey)){
echo $data;
}else{
echo 'Error';
}
I don't get any error but the $data value is not what I expect, is something like this
v_~�#&�W��q�&Ș�uQ���֔�
I'm sure I'm missing something but I can't find out what is it, due to the $data value looks like is encrypted.
The result that I expect from the decrypt is 167619085f7ed94026e357930b18dc011971f226c898ef7551cdf6ec9ad694cf this is the result of the following code
$canonical = 'c328e942-8be8-4104-abbe-048254f893dc|9687|2874.30|52409|BP1381|550bd8439cd1f41691671cdd4e8c6ae6';
$hashed = hash('sha256', $canonical);
That last part is how the provider generates the signature.
For the given example, canonic form is as follows:
cec4b9bf-5a39-4bd7-bc8b826ebc18208d|Internal_0005|12|39679|BP7610|947d589a40dece13c28f2b63c41ae451
We sign the response by hashing the canonic form with SHA-256 and encrypting the
resulting bytes with our private key.
RSA_ENCRYPT(SHA256(canonicForm), privkey.key)
To verify the payload, you must recalculate the canonic form and apply SHA-256 to the
result. The resulting value must be compared with the result of decrypting the signature
parameter with our public key.
Any hint would be appreciated.
perhaps post the public key and some valid test data so we can test ourselves?
anyway, v_~�#&�W��q�&Ș�uQ���֔� could be a valid signature, remember that SHA256 is 256 random bits, it's binary data, not ascii data, not hex, and not printable. SHA256 is also exactly 32 bytes long (256 bits, and 1 byte is 8 bits, and 256/8 is 32 bytes), so if you run var_dump(strlen($data)) after decryption, it should print 32, if it does not print 32, it implies they're using a padding scheme, try checking the strlen of both OPENSSL_PKCS1_PADDING and OPENSSL_NO_PADDING , when you get the correct padding scheme, strlen($data) after decryption should be int(32)
but my best guess is:
$signature = 'GcTtinhU0YgwGbZPtBwLdh+zdEe0w0W95TFPggeHMCjeDUBWgZfCZ6ZDRUk7DfT5BkKsbAi8/4o60Krcwz1JMdRjmsPf7vj33heVIB2PZJaf8eFR1jijLIsyl4vgH7BbbQ2I6kk6IcYXYWPVAHYRWxl1pJwOyNxZPr49fdW+hcw2zbpkEmj2114QBSiV6eHLowVYKLvpuiT8zLc6DN/wVzCYBuR/cg+CPHgYMeWFsuvu9J46hm6Hij00E68ldYAqVwImlmHPqfqvdEItg3Oi0ac4tXH2nCNgLPHcyU/H32NzTYC9iT1YZkoInqsU6Qv64vbU9lSMS91EQBEa5UQkUg==';
$canonical = 'c328e942-8be8-4104-abbe-048254f893dc|9687|2874.30|52409|BP1381|550bd8439cd1f41691671cdd4e8c6ae6';
$pubKey = openssl_pkey_get_public('file://path/to/public.pem');
if( openssl_public_decrypt(base64_decode($signature), $data, $pubKey)){
echo "signature decryption success! ";
if(hash_equals(hash("sha256",$canonical,true),$data)){
echo "checksum verification success!";
} else{
echo "checksum verification failed (after decryption was successful..)";
}
}else{
echo 'checksum decryption error';
}
but again, experiment with both
if( openssl_public_decrypt(base64_decode($signature), $data, $pubKey, OPENSSL_PKCS1_PADDING)){
and
if( openssl_public_decrypt(base64_decode($signature), $data, $pubKey, OPENSSL_NO_PADDING)){
1 of them is probably correct (and when it is correct, var_dump(strlen($data)) should print int(32) )
Related
I have this code in PHP (can't modify)
<?php
$myPlain = "123456789012345678900000";
$myKey = md5($myPlain, true);
$myKey .= substr($myKey, 0,8);
$encrypted = openssl_encrypt($myPlain, 'des-ede3', $myKey, OPENSSL_RAW_DATA);
print(base64_encode($encrypted));
This code returns
FTYDrZTZMjVBv5Fk/xcfFxJASaizzrmoPts7fGDvWjc=
When I try to replicate this in NodeJS
function testEde3(myKey, myPlain) {
try {
let md5Key = crypto.createHash('md5').update(myKey, 'utf-8').digest("base64").substr(0, 24);
console.log(md5Key); //outputs 4o1aJrSWN3bSfjuIX6VXgA==
console.log(md5Key.length); //outputs 24
const cipher = crypto.createCipheriv('des-ede3', md5Key, null);
let encrypted = cipher.update(myPlain, 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
} catch ( ex ) {
return ex;
}
}
const myKey = "123456789012345678900000";
const myPlain = "123456789012345678900000";
const hash = testEd3(myKey, myPlain);
console.log(`Hash is: ${hash}`);
The output is
Hash is: lDQX9OGsopKOt6P9WQwekGsKDQGFpfGW50zbs3HrOfQ=
I'm thinking the problem is on MD5. If I try to encrypt without md5, the results are the same.
Thanks
The key in Php code consists of the 16 bytes of the MD5 hash, to which the first 8 bytes of the MD5 hash are appended, resulting in a 24 bytes key (as required for 3DES). This is currently not implemented in the NodeJS code, but can be achieved e.g. by:
let md5Key = crypto.createHash('md5').update(myKey, 'utf-8').digest();
md5Key = Buffer.concat([md5Key, md5Key.slice(0, 8)]);
With this change, the NodeJS code generates the ciphertext of the PHP code with the same input data.
des-ede3 means 3DES in ECB mode. Note that 3DES is outdated and slow and should be replaced by AES. ECB mode is generally insecure. Encrypting the key also makes little sense (but may only be for testing purposes).
Setup:
session_start();
function set_encryption_method() {
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity']) > 3600) {
unset($_SESSION['cipher']);
unset($_SESSION['iv']);
unset($_SESSION['last_activity']);
}
$cipher = 'aes-256-cbc';
$iv = random_bytes(16);
if (in_array($cipher, openssl_get_cipher_methods())) {
if (!isset($_SESSION['cipher'])) {
$_SESSION['cipher'] = $cipher;
}
if (!isset($_SESSION['iv'])) {
$_SESSION['iv'] = $iv;
}
$_SESSION['last_activity'] = time();
} else {
die('Encryption method not supported!');
}
}
set_encryption_method();
Encrypt:
function encrypt_string($key, $string) {
// $key is a constant stored in a database
return rawurlencode(base64_encode(openssl_encrypt($string, $_SESSION['cipher'], $key, 0, $_SESSION['iv'])));
}
Decrypt:
function decrypt_string($key, $encrypted) {
// $key is a constant stored in a database
return openssl_decrypt(rawurldecode(base64_decode($encrypted)), $_SESSION['cipher'], $key, 0, $_SESSION['iv']);
}
When decrypt_string() is called with the appropriate parameters, it throws this error: digital envelope routines evp_decrypt_final_ex: bad decrypt. If I hardcode the iv, then it works correctly.
What am I doing wrong?
The error message is (indirectly) caused by the fact that your are using different IVs for encryption and decryption. From your description it is not clear how that can happen, but let me propose some suggestions that will avoid your issue altogether.
First, with EAS-CBC it is not a good idea to use the same IV + key combination multiple times. You can find some discussion on that in the answers to Is AES in CBC mode secure if a known and/or fixed IV is used?. You did not mention how you are using the different functions, but during 3600 seconds, you are using the same IV + key combinations.
To work around this, you could generate a random IV for every encryption that you do. You could then store the IV together with the encrypted data; the IV is not required or supposed to be secret. The following two functions are modifications of yours that do exactly that, by concatenating the two after encryption and splitting the two before decryption:
function encrypt_string($key, $string) {
// $key is a constant stored in a database
$iv = random_bytes(16);
$ciphtxt = openssl_encrypt($string, $_SESSION['cipher'], $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv.$ciphtxt);
}
function decrypt_string($key, $encrypted) {
// $key is a constant stored in a database
$combo = base64_decode($encrypted);
$iv = substr($combo, 0, 16);
$ciphtxt= substr($combo, 16);
return openssl_decrypt($ciphtxt, $_SESSION['cipher'], $key, OPENSSL_RAW_DATA, $iv);
}
Note the use of the flag OPENSSL_RAW_DATA. As the documentation for openssl_encrypt mentions (not too clearly), the result will be base64-ed if you do not give that flag. You were doing the base64-ing yourself so I added the flag. This also makes it a little easier to handle the (de-)concatenation of the IV and the ciphertext.
A few words about the occurrence of that bad decrypt error: that is emitted when the padding bytes are different than expected. Since you were using an incorrect IV for decryption, the AES decryption did not result in the original data, with a high probability that the padding bytes therefore did not have the right value.
First point to address: Why are you using URL encode/decode?
Those are for passing parameters through browsers; and the browser generally does the decoding for you so as a base rule - if you've written "urldecode" in your PHP, you've probably gone wrong as you're possibly decoding something already decoded. (Or are not using in the right place, or using when unnecessary)
However, Base64 is (or should be) url-safe, so I'd suggest knocking out the urlencode/decode and see what happens.
Second point to address: you need to undo the urlencode/base64 conversion in the reverse order you set.
So rawurlencode(base64_encode(openssl_encrypt( reversed is openssl_decrypt(base64_encode(rawurldecode (you have the base64 and url decode flipped). But knocking out the urlencode/decode entirely (unless you're adamant you need it) will rectify this too.
I have code which first I encrypted using mcrypt_ecb and hten then i send the value to another page using file_get_contents. but when I echo receive data, it only print half of it. I have attached my code and result below:
Client
$mac="B8-AC-6F-2D-5C-23";
// encrpt the max address
$key_value = pack('H*', "bcb04b7e103a0c");
$plain_text = $mac;
$encrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $plain_text, MCRYPT_ENCRYPT);
echo ("<p><b> Text after encryption : </b>");
echo ( $encrypted_text );
// send encrypted mac address to bridge for verification
$response = file_get_contents('http://localhost/scale/check.php?mac='.$encrypted_text);
print_r( $response );
Host
if (isset($_GET['mac']) && $_GET['mac']) {
$mac = $_GET['mac'];
echo "<br/>";
echo $mac;
//decrypted recieve data
$key_value = pack('H*', "bcb04b7e103a0c");
/* #var $encrypted_text type */
$encrypted_text = $mac;
$decrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text, MCRYPT_DECRYPT);
echo ("<p><b> Text after decryption : </b>");
echo ( $decrypted_text );
}
Result:
B8-AC-6F-2D-5C-23
Text after encryption : 5"ÆfÛkã–]» º"÷5Ù(Ÿ©U
_5"ÆfÛk_ã–]»
Text after decryption : 9Bþ‚î10tçæÇ|¤
The output of mcrypt_ecb is binary data, its bytes can contain arbitrary values. If you want to transfer it as an url parameter you have to encode it first. The general problem is that the url parameter parsing assumes a certain structure of the url. For example if you write http://localhost/scale/check.php?mac=abc123&foo=bar then PHP will see two parameters, the first one being mac with value abc123, the second being foo with value bar. But in the way you just concatenate the ciphertext to the url you could end up with the same url even if you really meant to have a parameter mac with the value abc123&foo=bar. To prevent such confusions all values have to be encoded so that certain characters do not appear. In your example the space seems to be problematic.
You can find some background on url encoding here: https://en.wikipedia.org/wiki/Percent-encoding .
By the way: It is generally appreciated if you only post a minimal example of your problem. Given that you have issues with the transmission of your data you could remove all the encryption code. But as I've seen it now, I can't help but notice that the algorithm DES and the block cipher mode ECB is generally a very insecure choice. If you want to protect your data during transmission you can avoid all the usual issues with home grown crypto schemes by using an https connection (notice the "s" for "secure", which forces your http client to connect to the server using TLS).
I have a signed PDF document. It was signed by using TCPDF. Now I want to verify it. This is my solution:
Get content of signed pdf.
Get original content and signature value base on /ByRange field.
Get encrypted digest message from signature value. It's octet string at the end of signature value.
Use Openssl_public_decrypt() function to decrypt the encrypted digest message with public key. Then we have a string which has a prefix ("3021300906052b0e03021a05000414"). This prefix denotes the hash function used is SHA-1. After removing the prefix, we obtain digest message D1.
Use SHA1() function to hash original content, we obtain digest message D2.
Compare D1 with D2. If D1 = D2 then signature is valid and vice versa.
My problem is in last step, when I compare D1 with D2, they are not equal. I don't know why.
Thanks for any help.
You should try based on following example
<?php
// $data and $signature are assumed to contain the data and the signature
// fetch public key from certificate and ready it
$pubkeyid = openssl_pkey_get_public("file://src/openssl-0.9.6/demos/sign/cert.pem");
// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
echo "good";
} elseif ($ok == 0) {
echo "bad";
} else {
echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>
more Examples ad explanation
http://www.php.net/manual/en/function.openssl-verify.php
Using the blowfish cbc mode, I want to create an encrypted token. When I create the token and immediately decrypt it, it works correctly. However, if I place the encrypted token in SESSION and try to decrypt it during a subsequent request, the decryption produces garbage.
This is my code. I am using SESSION for testing; eventually, I'll be storing these strings in a database instead.
session_start();
define("key","v8nga4r76qlipm111jnioool");
define("iv",substr(md5(uniqid(rand(),1)),0,8));
require_once("Crypt/Blowfish.php");
$str = "Blowfish_test";
// encode start!!
$blowfish = Crypt_Blowfish::factory("cbc", key, iv);
$encrypt = $blowfish->encrypt($str);
$encrypt64 = base64_encode($encrypt);
$_SESSION["test"] = $encrypt64;
So far, everything is correct. If, on the same request, I immediately decode it (from SESSION), the results are as expected:
// decode start!!
$blowfish = Crypt_Blowfish::factory("cbc", key, iv);
$decrypt64 = base64_decode($_SESSION["test"]);
$decrypt = $blowfish->decrypt($decrypt64);
$trim_decrypt = rtrim($decrypt, "\0");
echo "Before encryption : " . $str ."<br>";
echo "Encrypted string   : " .$encrypt64. "<br>";
echo "decrypted string   : " .$trim_decrypt. "<br>";
If I place only the second block of code on a different page (so a previously generated string is being decrypted), the decrypted string is garbage.
Encryption -> session["test"] -> Decryption --- no problem
session["test"] -> Decryption --- problem
What's happening here?
I'm sorry for this super delay.
I solved this problem by the comment at that time, so I close this question using community wiki.
--- add ---
problem is solved
// encode
// At the same time save the initialization vector
$_SESSION["test"] = $encrypt64;
$_SESSION["iv"] = iv;
--- other file ---
// decode
$blowfish = Crypt_Blowfish::factory("cbc", key, $_SESSION["iv"]);