i am tring to validate my openmoney webhook url but it is not working,i am getting all in $payload and then remove hash from $payload them convert it in string . and then hash_hmac but don't know what is problem ..
$hashed_expected = $request->hash;
$payload = $request->all(); // get all body
unset($payload['hash']);
$str = json_encode($payload); // Convert in string
$string = preg_replace('/\s+/', '', $str); // remove white space
$service = DepositServices::where('type','open_money')->first();
$apiSecret = $service->details->api_secret; // open money API Secret
$hashed_value = hash_hmac('sha256',$string,$apiSecret);
$data['hashed_value']=$hashed_value;
$data['hashed_expected']=$hashed_expected;
$data['string'] = $string;
if (hash_equals($hashed_expected, $hashed_value) ) {
$data['status'] = "Match";
dd( $data);
}else{
$data['status'] = "Not Match";
dd( $data);
}
When creating and comparing your hashed values, the payload needs to be identical as it was when the sender created and sent it. My guess is that the encoding and preg_replacing is mutating the payload.
Something like this should get you the original, unaltered payload body.
json_encode($request->all(), JSON_UNESCAPED_SLASHES);
Related
in Facebook validation documentation
Please note that we generate the signature using an escaped unicode
version of the payload, with lowercase hex digits. If you just
calculate against the decoded bytes, you will end up with a different
signature. For example, the string äöå should be escaped to
\u00e4\u00f6\u00e5.
I'm trying to make a unittest for the validation that I have, but I don't seem to be able to produce the signutre because I can't escape the payload. I've tried
mb_convert_encoding($payload, 'unicode')
But this encodes all the payload, and not just the needed string, as Facebook does.
My full code:
// on the unittest
$content = file_get_contents(__DIR__.'/../Responses/whatsapp_webhook.json');
// trim whitespace at the end of the file
$content = trim($content);
$secret = config('externals.meta.config.app_secret');
$signature = hash_hmac(
'sha256',
mb_convert_encoding($content, 'unicode'),
$secret
);
$response = $this->postJson(
route('whatsapp.webhook.message'),
json_decode($content, true),
[
'CONTENT_TYPE' => 'text/plain',
'X-Hub-Signature-256' => $signature,
]
);
$response->assertOk();
// on the request validation
/**
* #var string $signature
*/
$signature = $request->header('X-Hub-Signature-256');
if (!$signature) {
abort(Response::HTTP_FORBIDDEN);
}
$signature = Str::after($signature, '=');
$secret = config('externals.meta.config.app_secret');
/**
* #var string $content
*/
$content = $request->getContent();
$payloadSignature = hash_hmac(
'sha256',
$content,
$secret
);
if ($payloadSignature !== $signature) {
abort(Response::HTTP_FORBIDDEN);
}
For one, mb_convert_encoding($payload, 'unicode') converts the input to UTF-16BE, not UTF-8. You would want mb_convert_encoding($payload, 'UTF-8').
For two, using mb_convert_encoding() without specifying the source encoding causes the function to assume that the input is using the system's default encoding, which is frequently incorrect and will cause your data to be mangled. You would want mb_convert_encoding($payload, 'UTF-8', $source_encoding). [Also, you cannot reliably detect string encoding, you need to know what it is.]
For three, mb_convert_encoding() is entirely the wrong function to use to apply the desired escape sequences to the data. [and good lord are the google results for "php escape UTF-8" awful]
Unfortunately, PHP doesn't have a UTF-8 escape function that isn't baked into another function, but it's not terribly difficult to write in userland.
function utf8_escape($input) {
$output = '';
for( $i=0,$l=mb_strlen($input); $i<$l; ++$i ) {
$cur = mb_substr($input, $i, 1);
if( strlen($cur) === 1 ) {
$output .= $cur;
} else {
$output .= sprintf('\\u%04x', mb_ord($cur));
}
}
return $output;
}
$in = "asdf äöå";
var_dump(
utf8_escape($in),
);
Output:
string(23) "asdf \u00e4\u00f6\u00e5"
Instead of trying to re-assemble the payload from the already decoded JSON, you should take the data directly as you received it.
Facebook sends Content-Type: application/json, which means PHP will not populate $_POST to begin with - but you can read the entire request body using file_get_contents('php://input').
Try and calculate the signature based on that, that should work without having to deal with any hassles of encoding & escaping.
I am writing a PHP code for AMAZON WEB SERVICES. This is my code.
<?php
function amazonEncode($text) {
$encodedText = "";
$j = strlen($text);
for ($i = 0; $i < $j; $i++) {
$c = substr($text, $i, 1);
if (!preg_match("/[A-Za-z0-9-_.~]/", $c)) {
$encodedText .= sprintf("%%%02X", ord($c));
} else {
$encodedText .= $c;
}
}
return $encodedText;
}
function amazonSign($url, $secretAccessKey) {
// 0. Append Timestamp parameter
$url .= "&Timestamp=" . gmdate("Y-m-dTH:i:sZ");
// 1a. Sort the UTF-8 query string components by parameter name
$urlParts = parse_url($url);
parse_str($urlParts["query"], $queryVars);
ksort($queryVars);
// 1b. URL encode the parameter name and values
$encodedVars = array();
foreach ($queryVars as $key => $value) {
$encodedVars[amazonEncode($key)] = amazonEncode($value);
}
// 1c. 1d. Reconstruct encoded query
$encodedQueryVars = array();
foreach ($encodedVars as $key => $value) {
$encodedQueryVars[] = $key . "=" . $value;
}
$encodedQuery = implode("&", $encodedQueryVars);
// 2. Create the string to sign
$stringToSign = "GET";
$stringToSign .= "n" . strtolower($urlParts["host"]);
$stringToSign .= "n" . $urlParts["path"];
$stringToSign .= "n" . $encodedQuery;
// 3. Calculate an RFC 2104-compliant HMAC with the string you just created,
// your Secret Access Key as the key, and SHA256 as the hash algorithm.
if (function_exists("hash_hmac")) {
$hmac = hash_hmac("sha256", $stringToSign, $secretAccessKey, TRUE);
} elseif (function_exists("mhash")) {
$hmac = mhash(MHASH_SHA256, $stringToSign, $secretAccessKey);
} else {
die("No hash function available!");
}
// 4. Convert the resulting value to base64
$hmacBase64 = base64_encode($hmac);
// 5. Use the resulting value as the value of the Signature request parameter
// (URL encoded as per step 1b)
$url .= "&Signature=" . amazonEncode($hmacBase64);
echo $url;
}
$url = 'http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=something&AssociateTag=something&Operation=ItemSearch&Keywords=Mustang&SearchIndex=Blended&Condition=Collectible&Timestamp=2016-08-08T12%3A00%3A00Z&Version=2013-08-01';
$SECRET_KEY = 'my_secret_key';
$url = amazonSign($url, $SECRET_KEY);
?>
This code returns me a URL. I use that URL inside my browser so that I can get my search results but using that URL gives me this error.
SignatureDoesNotMatchThe request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
I am using these as AWSAccessKeyId and SECRET_KEY.
It's probably $stringToSign .= "n" should be $stringToSign .= "\n" but this might not be the only problem. If you use the official PHP SDK from Amazon instead of relying on custom scripts you'll have less issues.
The error you are seeing is usually a mistyped Access Key or Secret Access Key.
or the issue may be non-UTF-8 encoded string. Once i UTF-8 encoded it, the error will disappeared.
or if you sending a metadata with an empty value,than it will not work.
or if you not providing the Content-Length parameter than also such kind of issue can happen.
i'm trying android in app billing v3 verifying on my remote php server.
but, it seems something is wrong at my codes.
i think this openssl_verify function is problem.
result is always failed!
i can't find what first parameter to verify with openssl_verify. actually, i 'm confuse what's reasonable format to place at first parameter :(
could you help me to solve it?
$result = openssl_verify($data["purchaseToken"], base64_decode($signature), $key); // original // failed
belows full test codes.
<?php
$responseCode = 0;
$encoded='{
"orderId":"12999763169054705758.1111111111111",
"packageName":"com.xxx.yyy",
"productId":"test__100_c",
"purchaseTime":1368455064000,
"purchaseState":0,
"purchaseToken":"tcmggamllmgqiabymvcgtfsj.AO-J1OwoOzoFd-G-....."
}';
$data = json_decode($encoded,true);
$signature = "tKdvc42ujbYfLl+3sGdl7RAUPlNv.....";
$publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2kMri6mE5+.....";
$key = "-----BEGIN PUBLIC KEY-----\n" . chunk_split($publicKey, 64, "\n") . "-----END PUBLIC KEY-----";
$key = openssl_get_publickey($key);
if (false === $key) {
exit("error openssl_get_publickey");
}
var_dump($key);
$result = openssl_verify($data["purchaseToken"], base64_decode($signature), $key); // original // failed
//$result = openssl_verify($data, base64_decode($signature), $key); // failed
//$result = openssl_verify($encoded, base64_decode($signature), $key); // failed
//$result = openssl_verify(base64_decode($data["purchaseToken"]), base64_decode($signature), $key); // failed
//$result = openssl_verify(base64_decode($signature),$data["purchaseToken"], $key,OPENSSL_ALGO_SHA512 ); // failed
if ($result == 1) {
echo "good";
} elseif ($result == 0) {
echo "bad";
} else {
echo "error";
}
echo($result);
thanks :)
You are passing the wrong $data value into openssl_verify(). This value should be the full JSON string you get from Google Play, not the purchase token inside it. It is important that the JSON string is untouched, as even if you were to add a space or newlines to it, the signature would no longer work.
All you need to do in your code above is to change this line:
$result = openssl_verify($data["purchaseToken"], base64_decode($signature), $key);
to
$result = openssl_verify($data, base64_decode($signature), $key);
And you should get a success, assuming you're using the correct public key and the JSON purchase string is valid. I'm pretty sure your JSON string is not the original string from Google however, as the ones from Google do not contain newlines. It will be one long line of JSON text. Make sure that's what you are passing to openssl_verify().
Problem with base64
$data = 'my data';
echo $encryptedData = base64_encode($data);
// Output :
bXkgZGF0YQ==
I added some more characters to the token
$encryptedData = $encryptedData . 'sdfsdfasdfsd';
echo $data = base64_decode($encryptedData);
// Output :
my data~Ç_jÇ_±
Now i got actual data + junk data. i dont want any of the data or only the data if there is any change in the token. is there any method to implement this ?
you should add token while encoding instead decoding
$data = 'my data'.'sdfsdfasdfsd';
$encryptedData = base64_encode($data);
than
echo $data = base64_decode($encryptedData);
and to remove the token
$trimmed = rtrim($data, "sdfsdfasdfsd");
echo $trimmed;
Codepad
and as Jon Skeet said base64 is in no way encryption .It doesn't make the contents secret at all
To make sure changes to the base64 encoded string can only be made by changing the $data, you will need to add a verification token.
An easy way to add such verification is by using a keyed hash whereby the key is secret:
$data = 'this product sells for 5 dollars';
$enc = base64_encode($data);
$token = base64_encode(hash_hmac('sha256', $enc, 'your secret key here', true));
$my_token = $token . ':' . $enc;
Output:
ZMkqZIa6UazMhbYDiPqjdS1NmU1ulh+Gi2tgWHRKKpQ=:dGhpcyBwcm9kdWN0IHNlbGxzIGZvciA1IGRvbGxhcnM=
When you receive such token, you first split on : and then use the first part (keyed hash) to verify the contents of the second part (data). Only if it matches, you can be (relatively) sure that the data has not been tampered with.
Im trying to encrypt data through a custom function i created... (based on base64)
The code works but to a degree... it gives random results (sometimes work and sometimes doesn't).
<?php
set_time_limit(0);
class encryptor{
function encrypt($data){
$all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?#,.&*()$; ";
$chars = str_split($all, 1); // Split $all to array of single characters
$text_chars = str_split($data, 1); // Split $data to array of single characters
// Create array of unique results based on the characters from $all
foreach($chars as $char){
$array[$char] = md5(uniqid(rand(), true));
}
// Replace the input text with the results from $array
foreach($text_chars as $text_char){
$data = str_replace($text_char,$array[$text_char], $data);
}
// Encode and compress $array as $solution
$solution = gzcompress(base64_encode(json_encode($array)),9);
// Return the encoded solution + Breaker + encoded and compressed input text
return $solution."BREAKHERE".gzcompress(base64_encode($data),9);
}
function decrypt($data){
// Break the encrypted code to two parts
$exploded = explode('BREAKHERE', $data);
// Decoding the contents
$contents = base64_decode(gzuncompress($exploded[1]));
// Decoding solution ($array)
$solves = json_decode(base64_decode(gzuncompress($exploded[0])),true);
$fliped = array_flip($solves);
// Replace the encrypted data with the solution
foreach($solves as $solve){
$contents = str_replace($solve,$fliped[$solve], $contents);
}
return($contents); // Return decoded data
}
}
$text = "11 1";
$enc = new encryptor();
$encrypted = $enc->encrypt($text);
$decrypted = $enc->decrypt($encrypted);
echo $decrypted;
?>
Since its just for fun, this change appears to make it work:
// Replace the input text with the results from $array
$encrypted = '';
foreach($text_chars as $text_char){
//$data = str_replace($text_char,$array[$text_char], $data);
$encrypted .= $array[$text_char];
}
Running str_replace in the loop results in substitutions of data that have been previously substituted.
Aside from that, to make transport of the encrypted data easier, I'd change:
return $solution."BREAKHERE".gzcompress(base64_encode($data),9);
to:
return base64_encode($solution."BREAKHERE".gzcompress($data,9);
and then make the appropriate changes in the decryptor. The compress data can have null characters and non-printable characters so if you base64 encode the entire result you can pass it around more easily.