HMAC Javascript function has different result than the PHP - php

I've got a javascript function that creates a Time Based One Time Password (TOTP).
Now I have to create that same TOTP at the server, using PHP.
I coded the same logic in PHP as in my javascript function.
For convenience, I created a javascript fiddle, and a PHP fiddle. So you can compare the codes and see the outputs.
Javascript version: (fiddle: https://jsfiddle.net/rrfk4ey9/1/)
var TOTP = function() {
var dec2hex = function(s) {
return (s < 15.5 ? "0" : "") + Math.round(s).toString(16);
};
var hex2dec = function(s) {
return parseInt(s, 16);
};
var leftpad = function(s, l, p) {
if(l + 1 >= s.length) {
s = Array(l + 1 - s.length).join(p) + s;
}
return s;
};
this.getOTP = function(secret) {
try {
var epoch = Math.round(new Date().getTime() / 1000.0);
// For testing, we take a fixed time. (same as in PHP version).
var time = "0000000002f3e3c9";//leftpad(dec2hex(Math.floor(epoch / 30)), 16, "0");
document.getElementById("key").innerHTML = secret;
document.getElementById("time").innerHTML = time;
var hmacObj = new jsSHA(time, "HEX");
var hmac = hmacObj.getHMAC(secret, "TEXT", "SHA-1", "HEX");
document.getElementById("hmac-out").innerHTML = hmac;
var offset = hex2dec(hmac.substring(hmac.length - 1));
var otp = (hex2dec(hmac.substr(offset * 2, 8)) & hex2dec("7fffffff")) + "";
otp = (otp).substr(otp.length - 6, 6);
} catch (error) {
alert("Error: " + error);
throw error;
}
return otp;
};
};
var totpObj = new TOTP();
document.getElementById("result").innerHTML = totpObj.getOTP("someSecret");
output {
font-family: monospace;
white-space: pre;
}
#result {
color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsSHA/1.6.0/sha.js"></script>
<body>
<aside>This snippet uses external library <b>jsSHA</b> version <b>1.6.0</b></aside>
<hr />
<output>
<div>Key: <b id="key"></b></div>
<div>Time: <b id="time"></b></div>
<div>HMAC: <b id="hmac-out"></b></div>
<div>code: <b id="result"></b></div>
</output>
</body>
PHP version: (http://ideone.com/s0Bwqu)
<?php
function leftPad($in, $len, $str) {
return str_pad($in, $len, $str, STR_PAD_LEFT);
}
$key = "someSecret";
$epoch = time();
// For testing, we take a fixed time. (same as in JS version).
$time = "0000000002f3e3c9";//leftPad(dechex(floor($epoch / 30)), 16, "0");
echo "Key: " . $key . "\n";
echo "Time: " . $time . "\n";
$hmac = hash_hmac("sha1", $time, $key, false);
echo "HMAC: " . $hmac . "\n";
$offset = hexdec(substr($hmac, strlen($hmac) - 1));
$otp = (hexdec(substr($hmac, $offset * 2, 8)) & hexdec("7fffffff")) . "";
$otp = substr($otp, strlen($otp) - 6, 6);
echo "Code: " . $otp . "\n";
?>
This yields:
Key: someSecret
Time: 0000000002f3e3c9
HMAC: 5dcab54740bdca71e706c7e38a5c59fec3cb9c1a
Code: 094428
Note that in both versions (JS and PHP) the time and key are the same.
The HMAC differs, and so in my understanding here starts the problem.
The javascript version is the one I created first, and is proven to be working correctly.
I am pretty sure the problem is caused by the behavior of the jsSHA library.
So I put some things in perspective:
jsSHA Library takes time in HEX format. Also in PHP the time is in HEX format when put in the hash_hmac function.
secret (the key) is in TEXT format put in jsSHA. Also in PHP.
Actually, the point is getting the same result in PHP as the jsSHA library in javascript.
I'm sure I'm missing something. I have long been trying, and even Google does't know the answer.

You tell that jsSHA library that the input is a hexadecimal string here:
var hmacObj = new jsSHA(time, "HEX");
But you're not doing anything equivalent on the PHP side before/inside the hash_hmac() call. That means that jsSHA gets raw binary data, while PHP's hash_hmac() gets the literal string of "0000000002f3e3c9".
Naturally, that won't produce the same result.
Apply hex2bin() to $time before passing it to hash_hmac().

Related

Is there a way to use GMP libraries in node.js to credentials with SRP6

I search a way to use the equivalent of the following PHP functions in Node.js after searching a while I found nothing working in my case:
gmp_init
gmp_import
gmp_powm
gmp_export
The idea is to rewrite this php code in js:
function CalculateSRP6Verifier($username, $password, $salt)
{
// algorithm constants
$g = gmp_init(7);
$N = gmp_init('894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7', 16);
// calculate first hash
$h1 = sha1(strtoupper($username . ':' . $password), TRUE);
// calculate second hash
$h2 = sha1($salt.$h1, TRUE);
// convert to integer (little-endian)
$h2 = gmp_import($h2, 1, GMP_LSW_FIRST);
// g^h2 mod N
$verifier = gmp_powm($g, $h2, $N);
// convert back to a byte array (little-endian)
$verifier = gmp_export($verifier, 1, GMP_LSW_FIRST);
// pad to 32 bytes, remember that zeros go on the end in little-endian!
$verifier = str_pad($verifier, 32, chr(0), STR_PAD_RIGHT);
// done!
return $verifier;
}
I found the answer to my question a while ago. This can be done in Node.js using the Buffer and the following libs bigint-buffer, big-integer as I did it below.
const bigintBuffer = require(`bigint-buffer`)
const BigInteger = require(`big-integer`)
const crypto = require(`crypto`)
/**
*
* #param {Buffer} salt
* #param {string} identity
* #param {string} password
* #return {Buffer}
*/
function computeVerifier (salt, identity, password) {
const hashIP = crypto.createHash(`sha1`)
.update(identity + `:` + password)
.digest()
const hashX = crypto.createHash(`sha1`)
.update(salt)
.update(hashIP)
.digest()
const x = bigintBuffer.toBigIntLE(hashX)
const g = BigInt(`0x7`)
const N = BigInt(`0x894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7`)
const verifier = BigInteger(g).modPow(x, N)
const lEVerifier = verifier.value.toString(16).match(/.{2}/g).reverse().join(``)
return Buffer.from(lEVerifier, `hex`)
}
// Test
crypto.randomBytes(32, (err, buf) => {
if (err) throw err;
computeVerifier(buf, `foo`, `bar`);
});
If you want to use directly a library I created one which works for TrinityCore and AzerothCore: https://www.npmjs.com/package/trinitycore-srp6

PHP REST Authentication token for Azure Cosmos DB

I'm building a PHP based webpage. I want to use REST APIs to store, read and update data in an AZURE Cosmos DB.
First challenge is to generate the authentication token with the masterkey. I used the Microsoft documentation: https://learn.microsoft.com/de-de/rest/api/cosmos-db/access-control-on-cosmosdb-resources
and a postman collection* as a reference to build the code below.
*see
https://www.youtube.com/watch?v=2ndj_-zp82Y
https://github.com/MicrosoftCSA/documentdb-postman-collection
I used the console log from postman to compare each step and figured out that there are different results** but I have no clue how to get the same results from my PHP like from Postman
**
key64 PHP:
WUtDMFF5VWZkZ1NsTFp5UmU5ZVBMbW9jV3ZSN.....==
key64 Postman:
60a0b443251f7604a52d9c917bd78f2e6a1c5af4790d3f67dc7dbd513d173418... NO == at the end
authstring PHP:
type%253Dmaster%2526ver%253D1.0%2526sig%.....
authstring POSTMAN:
type%3Dmaster%26ver%3D1.0%26sig%3.....
POSTMAN (JS)
// store our master key for documentdb
var mastKey = postman.getEnvironmentVariable("DocumentDBMasterKey");
console.log("mastKey = " + mastKey);
// store our date as RFC1123 format for the request
var today = new Date();
var UTCstring = today.toUTCString();
postman.setEnvironmentVariable("RFC1123time", UTCstring);
// Grab the request url
var url = request.url.trim();
console.log("request url = " + url);
// strip the url of the hostname up and leading slash
var strippedurl = url.replace(new RegExp('^https?://[^/]+/'),'/');
console.log ("stripped Url = " + strippedurl);
// push the parts down into an array so we can determine if the call is on a specific item
// or if it is on a resource (odd would mean a resource, even would mean an item)
var strippedparts = strippedurl.split("/");
var truestrippedcount = (strippedparts.length - 1);
console.log(truestrippedcount);
// define resourceId/Type now so we can assign based on the amount of levels
var resourceId = "";
var resType = "";
// its odd (resource request)
if (truestrippedcount % 2)
{
console.log("odd");
// assign resource type to the last part we found.
resType = strippedparts[truestrippedcount];
console.log("resType");
console.log(resType);
if (truestrippedcount > 1)
{
// now pull out the resource id by searching for the last slash and substringing to it.
var lastPart = strippedurl.lastIndexOf("/");
resourceId = strippedurl.substring(1,lastPart);
console.log(resourceId);
}
}
else // its even (item request on resource)
{
console.log("even");
// assign resource type to the part before the last we found (last is resource id)
resType = strippedparts[truestrippedcount - 1];
console.log("resType");
// finally remove the leading slash which we used to find the resource if it was
// only one level deep.
strippedurl = strippedurl.substring(1);
console.log("strippedurl");
// assign our resourceId
resourceId = strippedurl;
console.log("resourceId");
console.log(resourceId);
}
// assign our verb
var verb = request.method.toLowerCase();
// assign our RFC 1123 date
var date = UTCstring.toLowerCase();
// parse our master key out as base64 encoding
var key = CryptoJS.enc.Base64.parse(mastKey);
console.log("key = " + key);
// build up the request text for the signature so can sign it along with the key
var text = (verb || "").toLowerCase() + "\n" +
(resType || "").toLowerCase() + "\n" +
(resourceId || "") + "\n" +
(date || "").toLowerCase() + "\n" +
"" + "\n";
console.log("text = " + text);
// create the signature from build up request text
var signature = CryptoJS.HmacSHA256(text, key);
console.log("sig = " + signature);
// back to base 64 bits
var base64Bits = CryptoJS.enc.Base64.stringify(signature);
console.log("base64bits = " + base64Bits);
// format our authentication token and URI encode it.
var MasterToken = "master";
var TokenVersion = "1.0";
auth = encodeURIComponent("type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + base64Bits);
console.log("auth = " + auth);
// set our auth token enviornmental variable.
postman.setEnvironmentVariable("authToken", auth);
PHP CODE
#PHP Script
function generateAuthKey($url, $method){
$key = "****************";
$date = new DateTime('');
$date = $date->format('D, d M Y H:i:s O');
$ressourcetype = "";
$strippedurl = parse_url($url, PHP_URL_PATH);
$strippedparts = explode("/", $strippedurl);
$strippedurlcount = sizeof($strippedparts)-1;
#GET RESSOURCE TYPE
if ($strippedurlcount % 2){
$resType = $strippedparts[$strippedurlcount];
if ($strippedurlcount > 1){
$ressourcetype = $strippedparts[$strippedurlcount];
}
}
else{
$ressourcetype = $strippedparts[$strippedurlcount-1];
}
$sig = nl2br(strtolower($method)."\n".strtolower($ressourcetype)."\n".$strippedurl."\n".strtolower($date)."\n".""."\n");
$sig = utf8_encode($sig);
$key64 = base64_encode($key);
echo $key64."\n";
$hmac = hash_hmac('sha256',$sig,$key64);
$token = "type=master&ver=1.0&sig=".$hmac;
return urlencode($token);
}
How can I change the PHP script to provide the same output as Postman (JS)?
I believe the issue is with the following line of code:
$key64 = base64_encode($key);
As per the REST API documentation, you should be doing a base64_decode of your key as the key is already base64 encoded.
Please try by changing your code to:
$key64 = base64_decode($key);
While this is an old question, I'll note a couple issues with the author's code:
It was not necessary to utf8_encode() -- trying to utf8 encode a string that is already valid ISO-8859-1 can produce unexpected results. Also note that this method is deprecated as of PHP 8.2.0.
The author was returning the string output of hash_hmac(), rather than binary.
Here is how you correctly generate a signature in PHP. Bear in mind that all requests to the Cosmos REST API, needs to include an x-ms-date header, which matches the same date used to generate the token. It's up to you how to want to handle that, but in my case, I chose to return the date and token as an array from the function. You could also consider making the function return the entire header array all at once.
I am using Carbon and Guzzle in this example.
private function cosmosAuth(string $method, string $resourceType, string $resourceLink)
{
$date = Carbon::now()->toRfc7231String();
// alternatively: gmdate('D, d M Y H:i:s T')
$key = base64_decode(MY_COSMOS_KEY);
$body = $method . "\n" .
$resourceType . "\n" .
$resourceLink . "\n" .
$date . "\n" .
"\n";
$hash = hash_hmac('sha256', strtolower($body), $key, true);
$signature = base64_encode($hash);
$tokenType = "master";
$tokenVersion = "1.0";
$token = urlencode("type={$tokenType}&ver={$tokenVersion}&sig={$signature}");
return [
'date' => $date,
'token' => $token
];
}
Here is an example of a request to update a document. Note if you created your collection with a partition key, you also must pass the partition key value in the x-ms-documentdb-partitionkey header. The format here is a little janky, with Microsoft expecting a string representation of an array containing the value.
$resource = "dbs/{$database}/colls/{$collection}/docs/{$documentId}";
$auth = $this->cosmosAuth("PUT", "docs", $resource);
try {
$client = new \GuzzleHttp\Client();
$client->request("PUT", "https://{$account}.documents.azure.com/{$resource}", [
'headers' => [
'authorization' => $auth['token'],
'x-ms-date' => $auth['date'],
'x-ms-documentdb-partitionkey' => '["'.$documentId.'"]',
],
'json' => $documentData
]);
}
catch (Exception $e) {
$this->log("error: {$e->getMessage()}");
}
Microsoft resources:
Constructing a hashed token
Replace a document

Verifying HMAC from Microsoft Teams custom Bot in PHP

I am trying to authenticate a Microsoft Teams custom Bot with PHP, following the Microsoft instructions and read de C# example code.
Microsoft Intructions steps:
1. Generate the hmac from the request body of the message. There are standard libraries on most platforms. Microsoft Teams uses standard
SHA256 HMAC cryptography. You will need to convert the body to a byte
array in UTF8.
2. To compute the hash, provide the byte array of the shared secret.
3. Convert the hash to a string using UTF8 encoding.
4. Compare the string value of the generated hash with the value provided in the HTTP request.
I had write a small php script to test this in local:
<?php
//Function to generate C# byte[] equivalent
function unpak_str($val){
$b = unpack('C*', $val);
foreach ($b as $key => $value)
$byte_a .= $value;
return $byte_a;
}
//multi test outputs
function hasher($values=[], &$output){
//my secret share
$secret="ejWiKHgsKY1ZfpJwJ+wIiN4+bgsFad/lkpu9/MWNXgM=";
//diferent test
$secret_64=base64_decode($secret);
$secret_b=unpak_str($secret);
$secret_b_64=unpak_str(base64_decode($secret));
foreach($values as $msg){
$hs = hash_hmac("sha256",$msg,$secret, true);
$hs_64 = hash_hmac("sha256",$msg,$secret_64, true);
$hs_b = hash_hmac("sha256",$msg,$secret_b, true);
$hs_b_64 = hash_hmac("sha256",$msg,$secret_b_64, true);
$output.=base64_encode($hs)." <BR>";
$output.=base64_encode($hs_64)." <BR>";
$output.=base64_encode($hs_b)." <BR>";
$output.=base64_encode($hs_b_64)." <BR>";
}
}
//Get data
$data=file_get_contents('php://input');
//real data request content for test
$data ='{type":"message","id":"1512376018086","timestamp":"2017-12-04T08:26:58.237Z","localTimestamp":"2017-12-04T09:26:58.237+01:00","serviceUrl":"https://smba.trafficmanager.net/emea-client-ss.msg/","channelId":"msteams","from":{"id":"29:1aq6GCrC6lM9dv3YkAYi1gxTPiLnojGFgVr0_Th-2x6DhqmHAOhFwQHFzSyDy5RruXY4_FZjJebKHU7bpxfHpXA","name":"ROBERTO ALONSO FERNANDEZ","aadObjectId":"1e0dc7a0-9d5e-488b-bcf2-7e39c84076b8"},"conversation":{"isGroup":true,"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979#thread.skype;messageid=1512376018086","name":null},"recipient":null,"textFormat":"plain","attachmentLayout":null,"membersAdded":[],"membersRemoved":[],"topicName":null,"historyDisclosed":null,"locale":null,"text":"<at>PandoBot</at> fff","speak":null,"inputHint":null,"summary":null,"suggestedActions":null,"attachments":[{"contentType":"text/html","contentUrl":null,"content":"<div><span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">PandoBot</span> fff</div>","name":null,"thumbnailUrl":null}],"entities":[{"type":"clientInfo","locale":"es-ES","country":"ES","platform":"iOS"}],"channelData":{"teamsChannelId":"19:9e1c52275dfb4d0b873ddf34eb9f4979#thread.skype","teamsTeamId":"19:1e04f564ce5e4596bf2f266dbcff439e#thread.skype","channel":{"id":"19:9e1c52275dfb4d0b873ddf34eb9f4979#thread.skype"},"team":{"id":"19:1e04f564ce5e4596bf2f266dbcff439e#thread.skype"},"tenant":{"id":"9744600e-3e04-492e-baa1-25ec245c6f10"}},"action":null,"replyToId":null,"value":null,"name":null,"relatesTo":null,"code":null}';
//generate HMAC hash with diferent $data formats
$test = [$data, unpak_str($data), base64_encode($data), unpak_str(base64_encode($data))];
hasher($test, $output);
//microsoft provided HMAC
$output.="<HR>EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=";
echo $output;
/*
Calculates:
0HsKoHza/QBvdz+nZw9tOti/eSWjyMMt/U77bfDqiE8=
3jSq3I0HNQkjB9QfnnsxC1c3pF5PjqweHlSVcicrShY=
bTQcGVTHX8/Gh4xovnN0WiJUiNaOQwvUZnwyFfiCaJE=
qHBT2Y2ITyoxz2gmBbG8P1CrClvETus6dTffET3bAR8=
8BcrXEQDDi77qgxCZLYyb/6ez8p9Qg2ZhTyZPWkdn/g=
+8RSU5SSJKxqRLKkI+NkTE01xwu6PwPkKKMuvyyUvlo=
PdL5ZpEwcN6Fe5kfX7zeAZLJvt0uLNTzu7lhuoOcr2o=
s6M5pYruEgWeNMEOFfQRjVKQqtPBVaW3TJb2MzObF2c=
xOTLhddbAwczQVneuTDQhPzmoIXGQljpf27c+hlhQII=
aUMm5b2sKfmwGZOglfiu228fWqoLlwjc7z1QRdIbakE=
5a7bAj9tzqhP9l85OvfVasURW0GSV5rykRutFFPO2fk=
kwg6P2LoDL9rc3SSwJxQeoYJzZYlh+FHFefe38UokBM=
eHeAzI7TV6vYDzxTxwyKWxMeVKFiFlIffWRiIMAk6fk=
ZCyj2UppacQOTXogLPMFLDeMArQg03rhhlIwhynDvng=
uQYK+7u9fppb62zXqtVYfkNK9wVawB3g+BlTyu4dc74=
vjOFA3fqpwUx/VO9dQv3XviNhpjTNQsUwaJIwH4JjdY=
------------ MS PROVIDED HMAC ---------------
EW2993goL1q7nGhytIb3jKmV6luXLz15Bq2aYwuCeiE=
*/
I've zero hash matching...
Finally after lots of trial, it maked me crazy and decided to start a new bot with a new secret. Now works fine. I'm human while MS Teams no... I suppos that was my fault with copy/paste but is a really stranger thing and the other hand old bot fails a lot of times with no response and the newest no
Full example validation HMAC in PHP for Microsoft Teams Custom Bot:
<?php
//The secret share with Microsoft Teams
$secret="jond3021g9imMkrt8txF5AVPIwPFouNV/I72cQFii18=";
//get headers
$a = getallheaders();
$provided_hmac=substr($a['Authorization'],5);
//Get data from request
$data=file_get_contents('php://input');
//json decode into array
$json=json_decode($data, true);
//hashing
$hash = hash_hmac("sha256",$data,base64_decode($secret), true);
$calculated_hmac = base64_encode($hash);
//start log var
$log = "\n========".date("Y-m-d H:i:s")."========\n".$provided_hmac."\n".$calculated_hmac."\n";
try{
//compare hashs
if(!hash_equals($provided_hmac,$calculated_hmac))
throw new Exception("No hash matching");
//response text
$txt="Hi {$json["from"]["name"]} welcome to your custom bot";
echo '{
"type": "message",
"text": "'.$txt.'"
}';
$log .= "Sended: {$txt}";
}catch (Exception $e){
$log .= $e->getMessage();
}
//write log
$fp = fopen("log.txt","a");
fwrite($fp, $log . PHP_EOL);
fclose($fp);
I'm not a PHP expert, and your logic to cover all the cases is a bit convoluted, but I'm pretty sure your problem is that you aren't converting the message ($data) from UTF8 before computing the HMAC.
Here's a simple custom echo bot in Node that shows how to compute and validate the HMAC:
const util = require('util');
const crypto = require('crypto');
const sharedSecret = "+ZaRRMC8+mpnfGaGsBOmkIFt98bttL5YQRq3p2tXgcE=";
const bufSecret = Buffer(sharedSecret, "base64");
var http = require('http');
var PORT = process.env.port || process.env.PORT || 8080;
http.createServer(function(request, response) {
var payload = '';
request.on('data', function (data) {
// console.log("Chunk size: %s bytes", data.length)
payload += data;
});
request.on('end', function() {
try {
// Retrieve authorization HMAC information
var auth = this.headers['authorization'];
// Calculate HMAC on the message we've received using the shared secret
var msgBuf = Buffer.from(payload, 'utf8');
var msgHash = "HMAC " + crypto.createHmac('sha256', bufSecret).update(msgBuf).digest("base64");
console.log("Computed HMAC: " + msgHash);
console.log("Received HMAC: " + auth);
response.writeHead(200);
if (msgHash === auth) {
var receivedMsg = JSON.parse(payload);
var responseMsg = '{ "type": "message", "text": "You typed: ' + receivedMsg.text + '" }';
} else {
var responseMsg = '{ "type": "message", "text": "Error: message sender cannot be authenticated." }';
}
response.write(responseMsg);
response.end();
}
catch (err) {
response.writeHead(400);
return response.end("Error: " + err + "\n" + err.stack);
}
});
}).listen(PORT);
console.log('Listening on port %s', PORT);
You don't need unpack(), or that unpak_str() function (which is also broken because it just overwrites each byte with the next one, not appending them).
Byte arrays are not a thing in PHP - the language doesn't have different string types; how strings are interpreted is entirely up to the functions using them. That is, your shared secret should be just the result of base64_encode($secret).

Node.js `crypto.final` make the encrypted result is different to PHP `mcrypt_encrypt`

At first, Node.js crypto.
// Both of key and IV are hex-string, but I hide them in Stackoverflow.
var secretKey = new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), // 48 chars
iv = new Buffer('bbbbbbbbbbbbbbbb', 'hex'); // 16 chars
var str = 'This string will be encrypted.';
var cipher = crypto.createCipheriv('des-ede3-cbc', secretKey, iv),
cryptedStr = cipher.update(str, 'utf8', 'base64') + cipher.final('base64');
Then, PHP mcrypt.
$key = pack('H*', "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
$iv = pack('H*', "bbbbbbbbbbbbbbbb");
$string = 'This string will be encrypted.';
$text = mcrypt_encrypt(MCRYPT_3DES, $key, $string, MCRYPT_MODE_CBC, $iv);
$text_base64 = base64_encode($text);
Problem.
In the same string, same algorithm and same encoding.
Still there is a little part not match that is cipher.final().
Below is the real sample output.
// Node.js output.
UKBI17EIHKNM2EU48ygsjil5r58Eo1csByAIFp9GhUw=
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Same part
// PHP output.
UKBI17EIHKNM2EU48ygsjil5r58Eo1csAY4C0JZoyco=
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Same part
Why cipher.final() make results different?
How could make the same results in Node.js on condition that don't modify PHP code.
Since you can't change your PHP code, you will need to modify the node.js code.
The problem is that node.js' crypto module uses only PKCS#7 padding, whereas PHP uses only zero padding. You can however disable padding in node.js (setAutoPadding(false)) to implement your own zero padding:
function zeroPad(buf, blocksize){
if (typeof buf === "string") {
buf = new Buffer(buf, "utf8");
}
var pad = new Buffer((blocksize - (buf.length % blocksize)) % blocksize);
pad.fill(0);
return Buffer.concat([buf, pad]);
}
And use it like this:
var secretKey = new Buffer('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'hex'), // 48 chars
iv = new Buffer('bbbbbbbbbbbbbbbb', 'hex'); // 16 chars
var str = 'This string will be encrypted.';
var cipher = crypto.createCipheriv('des-ede3-cbc', secretKey, iv);
cipher.setAutoPadding(false);
var cryptedStr = cipher.update(zeroPad(str, 8), 'utf8', 'base64') + cipher.final('base64');
console.log(cryptedStr);
Output:
UKBI17EIHKNM2EU48ygsjil5r58Eo1csAY4C0JZoyco=
Here is an implementation of a matching unpad function:
function zeroUnpad(buf, blocksize){
var lastIndex = buf.length;
while(lastIndex >= 0 && lastIndex > buf.length - blocksize - 1) {
lastIndex--;
if (buf[lastIndex] != 0) {
break;
}
}
return buf.slice(0, lastIndex + 1).toString("utf8");
}

convert some AS functions to php

I converting a swf project to php, I'm not good with actionscript much so I need help to convert functions Hex.toArray, Hex.fromString, Base64.encodeByteArray in actionscript3 to php.
ActionScript
public function spawn(query_str:String, key:String, token:String = "") : String{
var tmp1:* = key + "&" + token;
var tmp2:* = Crypto.getHMAC("sha1");
var tmp3:* = Hex.toArray(Hex.fromString(tmp1));
var tmp4:* = Hex.toArray(Hex.fromString(query_str));
var tmp5:* = tmp2.compute(tmp3, tmp4);
return Base64.encodeByteArray(tmp5);
}
This is PHP function I converted, but results of two functions are different
function spawn($query_str, $key, $token = ''){
$tmp1 = $key . "&" . $token;
$tmp3 = pack("H*" , bin2hex($tmp1));
$tmp4 = pack("H*" , bin2hex($query_str));
$tmp5 = hash_hmac('sha1', $tmp4, $tmp3);
return base64_encode($tmp5);
}
You can use bin2hex in PHP, and pack("H*", ...) in lieu of hex2bin. The primarily used base64 functions in PHP are base64_encode and base64_decode.
Arrays are seldomly used for data representation; binary data is generally kept in strings in PHP. But if really needed $array = array_map("ord", str_split($string)); would do.

Categories