AS3 HMAC SHA-256 for Adobe AIR (desktop) - actionscript-3

in Actionscript 3 i need to compute data (a string, utf-8), using a secret key (a string, utf-8).
This is the data (string) "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559"
This is the secret key (string) "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j"
This is the result it must come out (string) "c8db56825ae71d6d79447849e617115f4a920fa2acdcab2b053c4b2838bd6b71"
Can someone solve this? (the result is correct, but i don't know the code to arrive at the result).
This is what i have tried so far:
// THE DATA
var dataToEncode:String = "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559";
var byteArrayOfDataToEncode:ByteArray = new ByteArray();
byteArrayOfDataToEncode.writeUTF(dataToEncode); // we write the string into the ByteArray
// THE SECRET KEY
var secretKey:String = "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j";
var byteArrayOfSecretKey:ByteArray = new ByteArray();
byteArrayOfSecretKey.writeUTF(secretKey); // we write the secret key into the ByteArray
// WE COMPUTE THE SIGNATURE
var HMAC_SHA256:HMAC = new HMAC(new SHA256());
var byteArrayOfResultSignature:ByteArray = HMAC_SHA256.compute(byteArrayOfSecretKey, byteArrayOfDataToEncode);
var resultSignature:String = byteArrayOfResultSignature.readUTF();
// WE SHOW THE RESULT SIGNATURE
trace("The result signature is: "+resultSignature);
This HMAC class is created using this library (AS3Crypto):
https://github.com/Atmosphere/ActionScript/blob/master/src/com/hurlant/crypto/hash/HMAC.as

I found, thanks to the commentors, the asnwer to this.
The solution is com.adobe.crypto .
There is a class in the As3corelib (that you can download here
https://code.google.com/archive/p/as3corelib/downloads). You have to import those folders by going to "File-> Actionscript settings", and the click on the source path and then add the "com" folder there.
You will also need to download the Adobe Flex SDK (because some classes in As3corelib use some utility classes in the Flex SDK), unzip it, and then include the framework.swc file (search in the folders of adobe flex, it is in the frameworks/libs folder), going to "File-> Actionscript settings", and the click on the library path and then add the framework.swf there.
Now you are ready to do it, like this:
import com.adobe.crypto.*; // import this, to have access to the classes we need.
// then this code where you need it
var message:String = "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000&timestamp=1499827319559";
var secretKey:String = "NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j";
var signature:String = HMAC.hash(secretKey, message, SHA256) ;
trace("The signature is: "+signature);
Hope it helps, have a beautiful day!

Related

as3 PNGEncoder error

I am trying to save my graphics using the PNG encoder, and I get two errors.
Scene 1, Layer 'canvas', Frame 2, Line 42, Column 12 1172: Definition PNGEncoder could not be found.
Scene 1, Layer 'canvas', Frame 2, Line 965, Column 24 1120: Access of undefined property PNGEncoder.
Here is all the code revolving saving:
import PNGEncoder; [Recieves the first error]
function export():void
{
var bmd:BitmapData = new BitmapData(board.width, board.height);
bmd.draw(board);
var ba:ByteArray = PNGEncoder.encode(bmd); [Recieves the second error]
var file:FileReference = new FileReference();
file.save(ba, "MyDrawing.png");
}
saveButton.addEventListener(MouseEvent.CLICK,save)
function save(e:MouseEvent):void
{
export();
}
I got this code from a tutorial, so I can't be too sure it is formated right. The tut said that PNGEncoder was an import but according to flash cs3 it is not. Can someone help me straighten this out? I labeled the parts giving me an error, thanks.
You need to download the PNG Encoder and setup Flash to know where to find the new library (the process below can be used for any other externally downloaded SWC's you need to use in future)
1) Create a new folder called Flash_Addons
(the path would be C:\Flash_Addons\ it's just to get you started for now, later change the setup to a prefered folder name/location)
2) Download the AS3 CoreLib (the "Download ZIP" option at bottom/right-hand side
3) Inside the Zip is a folder (I think its called "as3corelib-.93") copy that to your Flash_Addons folder so it's now a sub-folder.
4) Now to tell Flash where to find it.. In your CS got to Edit-->Preferences (CTRL+U shortcut) and click on "ActionScript" in Category list then when shown click ActionScript 3.0 Settings
Now you will see three boxes (Source path/ Library path/ External path).
(for these below, click "+" to add new entry, then either type path or click the folder icon to browse)
Source path: You want it to add.. C:\Flash_Addons\
Library path: You want it to add.. C:\Flash_Addons\as3corelib-.93\lib
(note: the "lib" folder contains the actual as3corelib.SWC file, that's why we put direct path to it. When you want to add any new SWC library just add path to the list of entries (example):
C:\Flash_Addons\as3corelib-.93\lib
C:\Flash_Addons\Useful_Library_Folder_of_SWC_file\
etc... etc..
Now you're ready to export PNG..
import com.adobe.images.PNGEncoder; //fixes the errors
saveButton.addEventListener(MouseEvent.CLICK, save)
function save(e:MouseEvent):void
{ export(); }
function export():void
{
var bmd:BitmapData = new BitmapData(board.width, board.height);
bmd.draw(board);
var ba:ByteArray = PNGEncoder.encode(bmd);
var file:FileReference = new FileReference();
file.save(ba, "MyDrawing.png");
}

Saving customized movieclip as an image to local disk (diy generator)

dropbox.com/s/77euop1luqjreos/FINAL.fla
Ok i just gave up with this already. I cant think of any way to save the image created by a user. Its hard to explain but please check out the fla file of my work. Basically its a diy generator. The only thing missing is a save function. Ive read filereference but its always in a document class. My code is in the timeline. Please help I'm really stuck.
edit: I got a download button that is working now!! But it only saves a small part of the movieclip: Imgur
In order to create images, you need to access the pixel data of the MovieClip object. The data can be obtained by rendering a MovieClip into a BitmapData object and using this data, you can write your own encoder to convert it to any image format you’d like. Writing such encoder is not a trivial task and requires understanding of the image format algorithm, or you can use pre-written libraries. You can download the PNGEncoder and JPGEncoder , which is part of as3corelib, an open source project library.
Using the JPGEncoder, we can convert DisplayObject into ByteArray, suitable for saving into file. If using the JPGEncoder, it’ll look like this:
import com.adobe.images.JPGEncoder;
var jpgEncoder:JPGEncoder = new JPGEncoder(quality);
//remember bitmapData here is just an example (do not try to compile this code without declare this particular variable)
var byteArray:ByteArray = jpgEncoder.encode(bitmapData);
With the PNGEncoder, it’ll look like this:
import com.adobe.images.PNGEncoder;
//remember bitmapData here is just an example (do not try to compile this code without declare this particular variable)
var byteArray:ByteArray = PNGEncoder.encode(bitmapData);
Saving Into User’s Hard Drive
Using the FileReference.save() function, we can prompt the user to save the file with the following call.
var fileReference:FileReference=new FileReference();
//in case of JPGEncoder
fileReference.save(byteArray, ".jpg");
With the two combined, here’s an example how to use:
//remember to import
import flash.net.FileReference;
import com.adobe.images.JPGEncoder; //or import com.adobe.images.PNGEncoder;
import flash.utils.ByteArray;
import flash.display.BitmapData;
//where mc_canvas will be your MovieClip instance name
var bitmapData:BitmapData = new BitmapData(mc_canvas.width, mc_canvas.height);
bitmapData.draw(mc_canvas);
var jpgEncoder:JPGEncoder = new JPGEncoder(quality_slider.value);
var byteArray:ByteArray = jpgEncoder.encode(bitmapData);
//if you want to use PNGEncoder
//var byteArray:ByteArray = PNGEncoder.encode(bitmapData);
var fileReference:FileReference = new FileReference();
fileReference.save(byteArray, ".jpg");

Modifying an external XML from within AS3

Can anybody show me some easy to understand guides on how to modify and update an external XML file from within ActionScript 3. I've been looking into it for a long time now, but haven't found a tutorial that I was able to understand. My goal is to create a really basic database.. Let's say, a Database of Contacts.. I want to load those contacts through an xml file. but I also want to be able to add new contacts and modify the existing ones. How do I do that?
I want to that in an Desktop AIR Application.
An easy task:
First, load the external XML. For the sake of an example let's imagine the XML to be of this structure:
<contactData>
<contact firstName="John" lastName="Smith" phone="285-493-5421-793" email="example#mail.com"/>
<contact firstName="Jane" lastName="Roberts" phone="285-493-5421-214" email="example#gmail.com"/>
</contactData>
Second, parse that XML. For that create a value object type of a class, let's call it ContactData. It might look something like this:
package
{
public class ContactData
{
public var firstName:String;
public var lastName:String;
public var email:String;
public var phone:String;
public var id:int; // always nice to store an ID
}
}
Loop through your XML - for every contact node create a ContactData class object and fill it the data from the XML.
Store an array with your ContactData objects somewhere, you'll need them later.
Third, edit the ContactData object, or even remove it from an array if you will. Adding is not a problem too.
Fourth and last, create a new xml with AS3 and loop through the ContactData object array to add contact nodes, then save the XML. Use File and FileStream classes to save the file on the hard drive or URLLoader to pass it to the server.
This is how a primitive XML creation code could look like:
var xml:XML = <contactData></contactData>;
for (var i:int = 0; i < contactDataArray.length; i++)
{
var cd:ContactData = contactDataArray[i];
xml.appendChild(<contact></contact>);
xml.contact[i].#firstName = cd.firstName;
xml.contact[i].#lastName = cd.lastName;
xml.contact[i].#phone = cd.phone;
xml.contact[i].#email = cd.email;
}
I hope it's helpful and easy to understand. Good luck!

How to duplicate loaded *.swf without setting a class name

I have read this article about abstracting assets from ActionScript:
Abstracting Assets from Actionscript in AS3.0 – Asset Libraries and DuplicateMovieClip
But it requires to set the Linkage Class name. How can I get the same result without setting the linkage class name?
What I want to do is to cache a loaded asset, and use the cached version every time I request the same URL. A solution is to clone the loaded DisplayObject, but I think it's unnecessary since I only want a new copy.
I think the way to do that is to use byte arrays
here's a quick sample
// once you load your data...
private function loaderComplete(event:Event):void
{
var loaderInfo:LoaderInfo = LoaderInfo(event.target);
var byteArray:ByteArray = loaderInfo.bytes; //<- this will create your byte array
}
you can then use byteArray.readObject(); to generate the new class;
look at senocular's post at http://www.kirupa.com/forum/showthread.php?p=1897368
where he's got a function like this:
function clone(source:Object):* {
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return(copier.readObject());
}
//that you use with
newObjectCopy = clone(originalObject);
hope this gets you started
As of Flash 11.3, there's a function named getQualifiedDefinitionNames that tells me exactly what linkage names should I use with getDefinition, so there's no need to know the values beforehand.

ActionScript: How to Import XML data as a variable (not as an Event)

I am attempting to import some simple XML data into Flash ActionScript 3.0. I can easily do this as an import that is posted to the stage, but I want to save it as a global variable instead. Here is the XML file that I am pulling from:
<utilitySavings>
<nameof file="academicWaterSavings">
<waterValue>100</waterValue>
<elecValue>200</elecValue>
</nameof>
<nameof file="dormWaterSavings">
<waterValue>300</waterValue>
<elecValue>400</elecValue>
</nameof>
<nameof file="greekWaterSavings">
<waterValue>500</waterValue>
<elecValue>600</elecValue>
</nameof>
<nameof file="totalWaterSavings">
<waterValue>1500</waterValue>
<elecValue>1600</elecValue>
</nameof>
...and here is the actionscript:
var req:URLRequest = new URLRequest("data.xml");
var loader:URLLoader = new URLLoader();
var utilitySavings:XML;
function xmlLoaded(event:Event):void
{
utilitySavings = new XML(loader.data);
academicWater.text = utilitySavings.nameof[0].waterValue;
academicElec.text = utilitySavings.nameof[0].elecValue;
var dormWater:String = utilitySavings.nameof[1].waterValue;
trace (dormWater);
}
loader.addEventListener(Event.COMPLETE, xmlLoaded);
loader.load(req);
trace(academicWater.text);
Notice the 'trace (dormWater)' I want to trace this outside of the function so it is accessible in later in my script. I can trace within the function, but this does me no good. I also am able to get the dynamic text to show up on the stage but, likewise, this does me little good.
I appreciate any help or insights.
I can see a couple of ways of achieving this , if you want to create a globally accessible Object, create a Singleton( not recommended ) , load your XML data into it then every object in your app will be able to access the loaded XML data.
http://www.gskinner.com/blog/archives/2006/07/as3_singletons.html
The resulting code would give you something like this:
//Available throughout your app after the XML has been loaded & parsed
var dormWater:String = Singleton.dormWater;
Although you state you don't want Events, I think that using Signals could be a better approach. Load your XML and dispatch a Signal containing the relevant String to the object that needs it, when receiving the Signal , assign the String to a variable.
http://www.peterelst.com/blog/2010/01/22/as3-signals-the-best-thing-since-sliced-bread/
//In a specific class
private var _dormWater:String;
private function signalListener(value:Object ):void
{
_dormWater = value.dormWater;
}