I'm trying to get this working in flutter and i cant get the same outcome.
My php code prints a diffrent hash then my flutter code. Is it posible to do this in a flutter app?
i have tried to achieve this by running this flutter code. But after 5 hours of reading i gave up and created a stack overflow account.
import 'package:crypto/crypto.dart';
import 'dart:convert'; // for the utf8.encode method
import 'package:http/http.dart' as http;
void main() {
var api = 'https://app.repricer.nl';
var endpoint = '/api/v1/channels/all.json';
var method = 'GET';
var public_key = '';
var private_key = '';
var data = '';
var ms = (new DateTime.now()).millisecondsSinceEpoch;
var timestamp = ms / 1000;
var hash_string = public_key + '|' + method + '|' + endpoint + '|' + data + '|' + timestamp.toString();
var key = utf8.encode(private_key);
var bytes = utf8.encode(hash_string);
var hmacSha256 = new Hmac(sha512, key); // HMAC-SHA256
var digest = hmacSha256.convert(bytes);
print(digest);
}
This is the PHP code that i want to convert to flutter:
$api = 'https://app.repricer.nl';
$endpoint = '/api/v1/channels/all.json';
$method = 'GET';
$public_key = '';
$private_key = '';
// Generate the CURL headers to authenticate our request
$headers = generateHash($public_key, $private_key, $method, $endpoint, $data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$api.$endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
function generateHash($public_key, $private_key, $method, $endpoint, $data)
{
$timestamp = date("U");
$hash_string = array($public_key,$method,$endpoint,$data,$timestamp);
$hash = hash_hmac('sha512',implode('|',$hash_string),$private_key);
print ($hash);
return array('X-Auth: '.$public_key, 'X-Hash: '.$hash, 'X-Date: '.$timestamp);
}
I expect the output is the same exept from the timestamp. But i ran it in the same second and it are 2 completly diffrent outcomes.
Your code is correct.
Small fix is just replacing:
ms / 1000 to (ms / 1000).toInt()
I don't see other flaw in Your code.
I've came to that answer after doing test run with constant timestamp parameter: 1572731120
PHP:
$timestamp = 1572731120; //date("U");
$hash_string = array($public_key,$method,$endpoint,$data,$timestamp);
$hash = hash_hmac('sha512',implode('|',$hash_string),$private_key);
Dart
var ms = (new DateTime.now()).millisecondsSinceEpoch;
var timestamp = 1572731120;//(ms / 1000).toInt();
var hash_string = public_key + '|' + method + '|' + endpoint + '|' + data + '|' + timestamp.toString();
var key = utf8.encode(private_key);
var bytes = utf8.encode(hash_string);
var hmacSha256 = new Hmac(sha512, key); // HMAC-SHA256
var digest = hmacSha256.convert(bytes);
which proves that results are equal:
Related
I need help translating this Node.js code into PHP. It's basically for authenticating whether the signature on my header is the same as the signature that has been encoded using base64 and HMAC-SHA256.
const crypto = require('crypto');
const timestamp = "1570350275357";
const msg = {'key1':'world','key2':'world'};
const secretKey = "mysecretsecret";
const decodedKey = Buffer.from(secretKey, 'base64').toString('utf8');
const signature = crypto.createHmac('SHA256', decodedKey).update(timestamp + '.' + msg).digest('base64');
const signatureHeader = "+DCfT1wIMUiaZnlZB4u59/d5wkXKA89lv67Ov66vnyc=";
assert(signature === signatureHeader);
So I have my request body which is {'key1':'world','key2':'world'} , the timestamp (x-duda-signature-timestamp header) is 1570350275357 and a secret key which is mysecretsecret.
It also calculates for my signature base64(hmac-sha256(secret-key, timestamp + "." + message)) which results in +DCfT1wIMUiaZnlZB4u59/d5wkXKA89lv67Ov66vnyc= , which is also the value to be found on this x-duda-signature header of the request.
I've already tried putting the pieces together on PHP and it just won't return a signature that is similar to my signature header which is +DCfT1wIMUiaZnlZB4u59/d5wkXKA89lv67Ov66vnyc=.
$getHeaders = apache_request_headers();
$timestamp = "1570350275357";
$signatureHeader = "+DCfT1wIMUiaZnlZB4u59/d5wkXKA89lv67Ov66vnyc=";
$secretKey = "mysecretsecret";
//Request Body
$message = '{'key1':'world','key2':'world'}';
$signature = base64_encode(hash_hmac('sha256',$timestamp.".".$message,$secretKey));
print_r($signature); // the value should be equal to ```$signatureHeader```
Any idea on where I went wrong? Thanks in advance!
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
I am trying to follow part of a tutorial for an API written in PHP. They show the following example:
$public = 'JkAFq7M47kLN0xVD';
$private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB';
$url = 'https://pterodactyl.local/api/admin/users';
$body = '';
$hmac = hash_hmac('sha256', $url . $body, $private, true);
return $public . '.' . base64_encode($hmac);
// Should return the string below:
//
// JkAFq7M47kLN0xVD.wgIxj+V8RHgIetcQg2lRM0PRSH/y5M21cPz9zVhfFaQ=
But my method doesn't return the proper value. Instead it returns the following:
JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
Here is my code:
hmac = crypto.createHmac('sha256', private_key);
hmac.write(url+body);
hmac.end();
hash = hmac.read().toString('base64');
console.log(hash);
EDIT: I think the example they provided was invalid because as everyone is saying my code is almost identical and the PHP code outputs a different value then it said it should in the documentation.
ok so, i used this tool writephponline to run this php code:
$public = 'JkAFq7M47kLN0xVD';
$private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB';
$url = 'https://pterodactyl.local/api/admin/users';
$body = '';
$hmac = hash_hmac('sha256', $url . $body, $private, true);
echo $public . '.' . base64_encode($hmac);
and returns:
JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
So i used that as a parameter, then i made a little nodejs script:
var crypto = require('crypto');
var public = 'JkAFq7M47kLN0xVD';
var private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB';
var url = 'https://pterodactyl.local/api/admin/users';
var body = '';
var hmac = crypto.createHmac('sha256', private).update(url+body).digest('base64');
console.log(public + '.' + hmac);
and returns:
JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
Hope it helps.
I am prefer use crypto-js library of crypto standards. This library is keep maintaining.
const crypto = require('crypto-js')
const public = 'JkAFq7M47kLN0xVD'
const private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB'
const url = 'https://pterodactyl.local/api/admin/users'
const body = ''
const hmac = crypto.HmacSHA256(url + body, private).toString(crypto.enc.Base64)
console.log(public + '.' + hmac)
// Print value:
// JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
everyone!
I have some PHP code to sign some text and it works fine. I need to have equivalent of this code on actionscript 3. I need your help.
$privateKeyPath = "private.key";
$message = "hello";
$privateKey = file_get_contents($privateKeyPath);
openssl_sign($message, $signature, $privateKey);
echo base64_encode($signature);
In AS3 I using as3crypto library to make sign:
private function readPrivateKey():String {
var f:File = new File("/Users/ivan/Desktop/private.key");
var fs:FileStream = new FileStream();
fs.open(f,FileMode.READ);
var key:String = fs.readUTFBytes(fs.bytesAvailable);
fs.close();
return key;
}
private function getSign():void {
var message:String = "hello";
var privateKey:String = readPrivateKey();
var srcBA:ByteArray = new ByteArray();
var resultBA:ByteArray = new ByteArray();
var rsaKey:RSAKey;
var base64encoder:Base64Encoder = new Base64Encoder();
srcBA.writeUTFBytes(message);
rsaKey = PEM.readRSAPrivateKey(privateKey);
rsaKey.sign(srcBA, resultBA, srcBA.length);
b64encoder.encodeBytes(resultBA);
trace(b64encoder.toString());
}
I have same private key file. I expect that the output values are equals. But these values are different =(
What am I doing wrong?
UPDATE: I tried to verify my encoded base64 string using public key and verify method - everything is ok inside Actionscript.
Example:
var text:String = "hello";
var srcBA:ByteArray;
var desBA:ByteArray;
var rsaKey:RSAKey;
var encodedB64:String;
// ENCODING
srcBA = new ByteArray();
srcBA.writeUTFBytes(text);
desBA = new ByteArray();
rsaKey = PEM.readRSAPrivateKey( readPrivateKey() );
rsaKey.sign(srcBA, desBA, srcBA.length);
encodedB64 = Base64.encodeByteArray(desBA);
trace("Original: " + text);
trace("Encoded: " + encodedB64 );
// DECODING
var srcBA2:ByteArray = new ByteArray();
var desBA2:ByteArray = new ByteArray();
var rsaKey2:RSAKey = PEM.readRSAPublicKey( readPublicKey() );
srcBA2 = Base64.decodeToByteArray( encodedB64 );
rsaKey2.verify(srcBA2, desBA2, srcBA2.length);
trace("Decoded: " + desBA2.toString() );
My original text and decoded value are equals. So, I conclude that AS3 signing methods are different than PHP.
Is anyone have idea to make it equals?
Thanks.
Maybe it's late answer, but anyway...
AS3 works fine in your second code, PHP needs some tweaks, like this:
$privateKeyPath = "private.key";
$message = "hello";
$privateKey = openssl_pkey_get_private(file_get_contents($privateKeyPath));
openssl_private_encrypt($message, $signature, $privateKey);
echo base64_encode($signature);
I just checked with key genereted on this site:
http://www.selfsignedcertificate.com/ and everything works fine, I'm getting similar results in both PHP and AS3 versions.
I'm working on an RSA sign() function for generating a signed URL for private streaming. I was testing on PHP code, but I want to re-code that in Flex. Here is the part of PHP code:
function getCannedPolicy($resource, $expires, $key, $privatekeyfile){
$priv_key = file_get_contents($privatekeyfile);
$pkeyid = openssl_get_privatekey($priv_key);
$policy_str = '{"Statement":[{"Resource":"'.$resource.'","Condition":{"DateLessThan":{"AWS:EpochTime":'.$expires.'}}}]}';
$policy_str = trim( preg_replace( '/\s+/', '', $policy_str ) );
$res = openssl_sign($policy_str, $signature, $pkeyid, OPENSSL_ALGO_SHA1);
$signature_base64 = (base64_encode($signature));
$repl = array('+' => '-','=' => '_','/' => '~');
$signature_base64 = strtr($signature_base64,$repl);
$url = $resource . '?Expires='.$expires. '&Signature=' . $signature_base64 . '&Key-Pair-Id='. $key;
return $url;
}
I write the same function in Flex. Here is the code:
private function getCannedPolicy(resource:String, expires:uint, key:String, privatekey:String):String{
var unsigned:String = '{"Statement":[{"Resource":"' +resource+ '","Condition":{"DateLessThan":{"AWS:EpochTime":' +expires+ '}}}]}';
var signed:String = '';
var signature:String = '';
var regex:RegExp = /\s+/g;
unsigned = unsigned.replace(regex,'');
var src:ByteArray = new ByteArray();
src.writeUTFBytes(unsigned);
var dst:ByteArray = new ByteArray();
var hash:SHA1 = new SHA1();
src = hash.hash(src);
var rsa:RSAKey = PEM.readRSAPrivateKey(privatekey);
trace(rsa.dump());
rsa.sign(src, dst, src.length);
dst.position = 0;
signature = Base64.encodeByteArray(dst);
signature = signature.split("+").join("-");
signature = signature.split("=").join("_");
signature = signature.split("\/").join("~");
signed = resource+'?Expires=' +expires+ '&Signature=' +signature+ '&Key-Pair-Id=' +key;
return signed;
}
The outputs from the two functions (the PHP and the Flex) are the same format. But, when I'm using the signed URL from the Flex function, the stream not work.
The alternative I'm using for openssl_sign() php function is sign() function from as3crypto library. Maybe here is the problem? Maybe the encryption is different.
Unfortunately, the as3crypto's RSAKey.sign() is not the same function as php's openssl_sign(). Their outputs are different signatures. For that reason I decide to call remote php function to generated my signature. It works now!