Google-App-Script vs php in encoding base64 - php

This php code decodes the secret key before hashing with SHA 512
$API_SECRET_KEY="W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg=";
$BDAPI_SECRET_KEY=base64_decode($API_SECRET_KEY);
$HMAC_SIGN = base64_encode(hash_hmac('sha512',$MESSAGE,$BDAPI_SECRET_KEY,true));
echo $HMAC_SIGN;
BfVNi21gY09c8M18cWBRBgo1W9pAlXM99ZVoF7Kz2ETFnIuvXjj8NRvRgn/GaT/m6YJ8efsr5s9EDbIhznAaag==
I want to replicate this in google app script
var Secret = "W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg="
var BDSecret= Utilities.base64Decode(Secret)
var hmac = Utilities.base64Encode(Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, BDSecret ));
Logger.log(hmac)
ew5KhLWSJixn8zw4s6VkpYIwvGBjrmjY3LhNWZr9CVEw6W22LOGg+lVzA3uQgOVyICSCffw2bzTepnBdoYtldw==
If I do not decode the API before hashing they return the same result. But for this particular purpose, the key needs to be decoded. The message variable is just my first name "Parit" in case someone wants to replicate.

I thought that Utilities.computeHmacSignature() might not be able to use []byte for the value. So as a workaround, how about using jsSHA? I think that in your case, you can use https://github.com/Caligatio/jsSHA/blob/master/src/sha512.js.
The flow for using jsSHA is as follows.
Flow :
Download sha512.js.
On script editor, create new script as for example, the filename of sha512.js.
Copy and paste the script of sha512.js to the created script.
Copy and paste the sample script to Code.gs of the script editor.
Run myFunction() of the sample script.
Sample script :
function myFunction() {
var message = "Parit";
var secret = "W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg=";
var obj = new jsSHA("SHA-512", "TEXT");
obj.setHMACKey(secret, "B64");
obj.update(message);
Logger.log(obj.getHMAC("B64"))
}
Note :
When I tested Parit for message, I got BfVNi21gY09c8M18cWBRBgo1W9pAlXM99ZVoF7Kz2ETFnIuvXjj8NRvRgn/GaT/m6YJ8efsr5s9EDbIhznAaag==.
It this was not useful for you, I'm sorry.
Update :
By the Google's update at June 19, 2018, Utilities.computeHmacSignature() got to be able to use the byte arrays. By this, using only native Google Apps Scvript, the result can be retrieved without using jsSHA. So I would like to update my answer.
Modified script :
function myFunction() {
var message = "Parit";
var secret = "W0+m0Dc9GMN9yDVeq3GMDsJ49WasEhQHkNHNuDw3wNg=";
var value = Utilities.base64Decode(Utilities.base64Encode(message));
var key = Utilities.base64Decode(secret);
var out = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, value, key);
var res = Utilities.base64Encode(out)
Logger.log(res)
}
Result :
BfVNi21gY09c8M18cWBRBgo1W9pAlXM99ZVoF7Kz2ETFnIuvXjj8NRvRgn/GaT/m6YJ8efsr5s9EDbIhznAaag==

Related

Delete a data of my database from AS3

I'm trying to delete a data from my database with ActionScript 3.
I've created a php on my server :
<?php
include ("shared/connect.php");
$idToDelete = $_POST['idToDelete'];
$result = mysqli_query($conn,"
DELETE FROM `annoncesNew` WHERE id=$idToDelete");
?>
Then I have to send the variable idToDelete to this php in order to delete the entry.
So I did :
deleteBtn.addEventListener(MouseEvent.CLICK, deleteThisAnnonce);
function deleteThisAnnonce(event:MouseEvent):void {
trace("deleteThisAnnonce");
var variablesDelete:URLVariables = new URLVariables();
var varDelete:URLRequest = new URLRequest("http://www.***com/***/deleteAnnonce.php");
varDelete.method=URLRequestMethod.POST;
varDelete.data=variablesDelete;
var varLoaderDelete:URLLoader = new URLLoader;
varLoaderDelete.dataFormat=URLLoaderDataFormat.VARIABLES;
varLoaderDelete.addEventListener(Event.COMPLETE,completeHandlerDelete);
ValidateAndSendDelete();
function completeHandlerDelete(event:Event):void{
trace("Data Sent");
}
function ValidateAndSendDelete():void{
trace("deleting"+item.id); //item.id is my the ID. When I trace the output is 144 so it's good.
variablesDelete.idToDelete = item.id;
varLoaderDelete.load(varDelete);
}
}
So, with this code, it's supposed to delete the data where id = 144. But I've got this error when click on the deleteBtn : Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs..
(all the traces are working correctly but my data isn't delete).
I've tried my php by changing DELETE FROMannoncesNew WHERE id=$idToDelete");withDELETE FROM annoncesNew WHERE id=144"); and execute it on my webbrowser and it worked (the line with the id 144 was deleted).
Weirdly, the line is delete with my AS3 code (so the code is working) but it throws this error 2101 anyway. Any idea why ?
Thx
I believe the problem is not in your AS3 code but that your PHP script is not returning any values back to Flash. Try to add this to your PHP script:
echo "Status=true";
And you might need this in your AS3:
varLoaderDelete.dataFormat = URLLoaderDataFormat.TEXT;

Calling data from Javascript through a proxy server

We have the following code in Javascript:
var speakMe = function (text) {
var key, lang, url, audio;
key = "key=1234567890";
lang = "sv_se";
url = "http://api.ttsengine.com/api/read?" + key + "&lang=en_us&voice=male1&speed=100&audioformat=ogg&oggbitrate=100&text=" + text;
audio = new Audio(url);
audio.play();
};
It functions well. However, I would like to mask the key. For this I have been advised to use a PHP proxy script.
I found this proxy but I don't know how to implement it. How do I get the data I normally get, but through this proxy?
Per the documentation of your proxy script. you can call your script and pass a url argument which then it will return the content back. you must also set mode=native as another url parameter.
// > ba-simple-proxy.php?url=http://example.com/&mode=native
//
// Response:
//
// > <html>...</html>
//
// Topic: Notes
//
// * Assumes magic_quotes_gpc = Off in php.ini

Pass Arrays from PHP file to JS file

I would like to pass an array I have in my PHP file to another file that is written in java script.
This is my array:
$pictures = array(
"1" => array("caption" => "1920x1200px", "tag" => "wallpaper", "link" => "#"),
);
And in my java script file this is the place where I want to call the array:
(At the place where they shall be in the code I wrote TAG, LINK and CAPTION.
Sry if this is a stupid question, but as you see, I have no idea about PHP and java script)
F.helpers.title = {
beforeShow: function (opts) {
var text = F.current.title,
type = opts.type,
title,
target;
if (!isString(text) || $.trim(text) === '') {
return;
}
title = $('<div class="fancybox-title fancybox-title-' + type + '-wrap"><h1>' + text + '</h1><p>CAPTION</p></div><div class="fancybox-title fancydownload" ><img src="../../../slider/img/download.png" alt=""/></div><div class="fancybox-title fancytag"><h2>TAG</h2></div>');
switch (type) {
case 'inside':
target = F.skin;
break;
case 'outside':
target = F.wrap;
break;
case 'over':
target = F.inner;
break;
default: // 'float'
target = F.skin;
title
.appendTo('body')
.width(title.width()) //This helps for some browsers
.wrapInner('<span class="child"></span>');
//Increase bottom margin so this title will also fit into viewport
F.current.margin[2] += Math.abs( getScalar(title.css('margin-bottom')) );
break;
}
if (opts.position === 'top') {
title.prependTo(target);
} else {
title.appendTo(target);
}
}
};
Try it using JSON. There are quite a few JSON parsers available
Encode it as JSON to convert it into a JavaScript literal, then access the resultant value as normal.
var data = <?php echo json_encode(array('foo' => 'bar')); ?>;
console.log(data['foo']);
The lifecycle of your PHP script (on the server side) is different from that of JS (on the client side). If you want to pass some information from PHP to client side, you can do one of the following:
You should print this information into the HTML file on the server side itself using your template engine.
You should return this information through another API by converting it into JSON format that is easy to browse through on the javascript side, and call your API using AJAX.
use an ajax call, something like $.post to get the array as a json array,
add an echo json_encode($picture) at the end of your PHP script.
PHP just generates files which then you send to the client. JavaScript is executed on the client side. So you should generate in php something like
var pictures = {'1': {caption: '1920x1200px', tag: 'wallpaper', link: '#'}};
and place it in html in script tag for example.
As a variant you may do it this way:
var pictures = <?= json_encode($pictures); ?>;

Flex 4,image create snapshoot from video display?

my code works on localhost,but not on the server,what could be the problem?I also want to return some string back from php to flex app but I can't solve that.
Here is my code :
[Bindable]
public var encodedString:String;
[Bindable]
public var img_name:String;
[Bindable]
public var pid:int;
[Bindable]
public var url_string:String;
protected function btn_save_clickHandler(event:MouseEvent):void
{
var bmpData:BitmapData = new BitmapData(videoDisplay.width,videoDisplay.height-25);
bmpData.draw(videoDisplay);
var bm:Bitmap = new Bitmap(bmpData);
img.source = bm;
var jpg_e:JPEGEncoder = new JPEGEncoder();
var bytes:ByteArray = new ByteArray();
bytes = jpg_e.encode(bmpData);
var b64e:Base64Encoder = new Base64Encoder()
b64e.encodeBytes(bytes);
encodedString = b64e.flush();
}
protected function btn_save_image_clickHandler(event:MouseEvent):void
{
// TODO Auto-generated method stub
save_img.send();
}
<mx:request xmlns="">
<img_data>
{encodedString}
</img_data>
<image_name>
{img_name}
</image_name>
<post_id>
{pid}
</post_id>
</mx:request>
</mx:HTTPService>
When click save,I want to save snapshoot from videodisplay to img.Also I send image to php,and want to get simple text answer that is done,but I always get object returned.
and I save image with php,and just print message,like this :
print "this is message!";
I think the problem is when I need to save image from control(video display) to image control,but this problem only occure on server but not on localhost
You need to change the last line from:
str = b64e;
To:
str = b64e.toString();
Note that calling toString() will clear the b64e object.
Update:
Let's try placing the video in a container, and then doing the .draw() on that, we'll add some additional content to it so that we can get that if the video doesn't show up.
<s:Group id="videoContainer">
<mx:Label text="Hello" />
<mx:VideoDisplay id="videoDisplay" />
</s:Group>
Hopefully you are already doing the VideoDisplay part of this, and you can update your code to add the containing group.
When you do the .draw() use videoContainer instead of videoDisplay ie. :
bmpData.draw(videoContainer);
This is just to test, if there is a sandbox issue, which it defintely seems to be, only "Hello" will show up in the bitmap, and the video will still not be seen.
Where does that video come from? Camera? FMS?
It might be either a crossdomain issue or something related to FMS (or another streaming server).
This post could help you : How do I specify a crossdomain policy file to allow Flash to grab a bitmap from an RTMP (Wowza) video stream?

PHP to JSON on client side

I'm using Rob Monies 'Jquery Week Calendar' to build a calendar application.
I have a MSSQL DB a with table named 'dates' and the following fields:
id
start
end
title
I would like to query this DB in PHP and then pass the results to Javascript, Javascript will then render the events in the browser.
The Javascript needs to receive the event details in JSON format as per the following example:
{"id":1,"start": 2010-10-09T13:00:00,"end":2010-10-09T14:00:00,"title":"Lunch with Mike"},
{"id":2,"start": 2010-10-10T13:00:00,"end": 2010-10-10T14:00:00, "title":"Dev Meeting"}
So far, to keep things simple I've just returned one row from the DB at a time, however - I will need the application to be able to render multiple events, as stored in the database.
I've tried using json_encode() to put the values into a var and pass them to a Javascript var called DB_events - if I return the DB_events in an alert box on the client side I see the following;
{"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"}
which looks ok, but when I do this in my code:
events : [DB_events]
It doesn't work :(
If I take PHP out of the equation, and just do the following on the client side:
var DB_events = {"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"};
and return DB_events in an alert box, I get:
[object] [Object]
But when I do this:
events : [DB_events]
it works!
Back to PHP …
If I put the SQL result into PHP vars as follows:
$id = id;
$start = start;
$end = end;
$title = title;
and pass those vars to the following JS vars:
JS_id
JS_start
JS_end
JS_title
and do this on the client side:
var DB_events = {"id":JS_id, "start":JS_start, "end":JS_end,"title":JS_title};
events : [DB_events]
that also works.
As you can probably tell - I'm new to this and probably missing something very basic.
Any help, advice or information would be very much appreciated :)
Many Thanks
Tim
when you get a string representation of your object it means that you've exported it as a string not as an object.
when you get [object] [Object] it means that it is now an object, which is right!
You can do this with JSONP if you get JSON from an URL:
// send the request via <script> tag
var src = "..."; // url of the JSON output
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", src);
head.appendChild(script);
Or parse it as a string with JSON parser:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
var DB_events = JSON.parse( ...JSON output as a string... );
Or by directly passing it from PHP with an inline <script> block in your page:
echo "<script>";
echo "var DB_events = " . json_encode( ... ) . ";";
echo "</script>";
​
Did you use jsocn decode
http://php.net/manual/en/function.json-decode.php
You can split the result and make it differenct variables like start ,end , events etc
http://php.net/manual/en/function.explode.php

Categories