Thursday, July 16, 2009

Flex As3crypto + php + rsa + openssl

Flex As3crypto + php + rsa + openssl
Well damn, all I wanted to do was encrypt a little data in my flex application upload it to php and decrypt it there. Of course that turns out to be incredibly complicated. So to all those who will come after me here’s an example of how I generated a 1024 bit RSA key pair with openssl, and used the public key to encrypt a phrase in flex, and the private key to decrypt the phrase in php. First a disclaimer though, I don’t know a lot about encryption or even a lot about what I’m doing but it seems to work and maybe you’ll find it useful.

PHP and openssl
If you want to play along you’re going to need php installed with openssl support. If you make a php file and put this in it:

and you scroll through the php info page and you don’t see this: Then you don’t have php and openssl working together, if you want to continue you’ll need to figure that out on your own. It’s not too hard though.

As3Crypto Build and Install
I’ll assume you’ve figured out your php and openssl configuration, so now it’s time to get the as3crypto library. DON’T JUST DOWNLOAD THE BINARY VERSION. I can’t stress that enough don’t just go to Hurlant’s website and get he latest binary version. Instead use svn to get the latest code base:

svn checkout as3crypto-read-only

If you don’t have svn or you don’t want to compile it yourself… you’ll be sad that you didn’t. Believe me I tried the easy way and it just didn’t work.

Once you get it downloaded get a command line or terminal window and go to the download directory. You can compile with this command:

compc -load-config=build-swc.xml

You’ll probably have to find out where your compc is located if it’s not in your path, and instead run something like:

/pathToCompC/compc –load-config=build-swc.xml

I also ran into the problem of it not knowing where playerglobal.swc was so I ended up editing that line in build-swc.xml to fit my installation. For me it was:


When you finally get it to compile it will put the file as3crypto.swc in the bin folder where you found build-swc.xml. Either leave that file there or copy it somewhere you like to keep these things.

Make yourself some keys
The next thing you’re going to want is a key pair. I made mine on my linux server using openssl. For me this is the same server I’m running php on. I’m sure there are a bunch of ways to generate the key pair but I followed the advice found here:

To make a private key just do:

openssl genrsa -out private.pem 1024

Then to extract the public key out of that private key do this:
openssl rsa -in private.pem -out public.pem -outform PEM -pubout

Now you have two files private.pem, and public.pem that we’ll use in the next section.

Flex Code
All right enough BS here’s the code I used to encrypt a small phrase in my Flex-Air application.

            import com.hurlant.crypto.symmetric.ICipher;
            import com.hurlant.crypto.prng.Random;
            import com.hurlant.crypto.Crypto;
            //import com.hurlant.util.Base64;
            import mx.utils.Base64Encoder;
            import com.hurlant.util.Hex;
            import com.hurlant.util.der.PEM;
            import com.hurlant.crypto.rsa.RSAKey;

            private function sign():void
             var publicKey:String = "-----BEGIN PUBLIC KEY-----\n" +
                 "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIyrrhK7L1JQATG1zu/4ktyDdj\n" +
                 "Y41EIZxa5vUiq+ejUlQXNWmQZw8ATDGV2x/xJEcsZSbPqcxgyqDPQ8kGjQkv1kS/\n" +
                 "5ZP3oru5WSEypVPq1nfMCBoGTspyYIRpS+MjhhhN2X5y0NzR08kQQA81GRvBpmxM\n" +
                 "-----END PUBLIC KEY-----\n";

                //var rsa:RSAKey = RSAKey.parsePublicKey(getModulus(), exponent.text);
                var rsaPublicKey:RSAKey = PEM.readRSAPublicKey(publicKey);
                var data:ByteArray = new ByteArray;

                data.writeUTFBytes("fuck this crazy ass crap");
                var dst:ByteArray = new ByteArray;
                rsaPublicKey.encrypt(data, dst, data.length);
                var Enc64:Base64Encoder = new Base64Encoder;
                //use this on linux side to test
                //openssl rsautl -decrypt -inkey mykey.pem -in test.out -out decrypted.txt
                ///usr/bin/openssl enc -base64 -d -in test.64 -out test.out


The first thing you’ll notice is my public key that I got in the previous step. I have no idea if the \n’s are necessary but I put them there because I saw other people do that so monkey see monkey do.

Next I read the key into an RSAKey.

Then you make yourself a new Byte array to store the phrase you want to encrypt . In this example it’s called data.

Then you write the phrase into the byte array.

Now you make yourself another byte array called dst, this is where the encrypted data will go.

Next you base64 encode the data so you can easily copy and paste it. Base64 encoding just encodes all that encrypted data into normal text characters that you can safely drag around.

Finally you output that data with a trace so you can get it easily. For me the trace outputs:

XTLpqt9mNtyFchsjvFnffEplqaa+LHXCh52DpLi9CxvED4fUq5cWPuTX/1tHeG7deNBiGBiRW02r +LfW3JreVSkkc+sH6rq4ggKWi+1iPZoQd45f2VmwHVTvgC/IQX4eRuyFtSVoheHSLRL8zRO2/M27 K2jx49V+4JFVhtFAbQw=

This is your encrypted base64 encoded data, that we’ll decrypt in the next section.

PHP Time
I don’t know how you plan on getting your encrypted phrase to php, and frankly I don’t care. For me I just wanted to see it work so all I did was copy and paste. Here’s the PHP code I used to decrypt the phrase:

$privkey3 = "-----BEGIN RSA PRIVATE KEY-----

$result = openssl_pkey_get_private($privkey3);

if ($result)
        print "\nPrivate Key OK\n\n";
} else {
        print "\nPrivate key NOT OK\n\n";

$crypttext = "XTLpqt9mNtyFchsjvFnffEplqaa+LHXCh52DpLi9CxvED4fUq5cWPuTX/1tHeG7deNBiGBiRW02r

$crypttext = base64_decode($crypttext);

echo "
String decrypt : $newsource
"; while ($msg = openssl_error_string()) echo $msg . "

First you’ll see that I took the private key from the keys we made earlier and put it in this file. Make sure yours looks the same, if you paste your private key without the right new lines it won’t work. At least it didn’t for me so must make sure you format it like you see in the code.

Next we call openssl_pkey_get_private on that private key.

Now you’ll see the encrypted phrase from our Air application in the $crypttext variable.

We base64 decode that to get back to the raw data.

Then we run it through openssl_private_decrypt to decrypt the data.

Finally we just output the data to the screen.

That last little while loop will output any openssl errors that might have occurred, and can be at least a little useful in debugging.

The End
Well I hope that helps someone else who comes along and tries to do the same thing. It was a pain in the ass to figure this all out especially because as3crypto has no documentation. I’m not knocking it though I mean you just got a completely free cryptography library for your flash project right.

One last thing if you, like me, know about as much about cryptography as you do about how to win the lottery, then you may be disappointed to find out you can only use RSA to encrypt a relatively small amount of data (it’s dependant on your key size). So most people use this to either exchange keys, or make a hash of what they’re sending and encrypt that.

Of course if you happen to know a lot about how to win the lottery... drop me an email with some tips.

Monday, March 30, 2009

datepicker is not a function

AUGGGHH! Why doesn't this work! Such is the cry of any hacky developer running around cobbling together pieces of code and examples to get something to work. All while trying to learn whatever he's working on at the same time. Anyway recently I tried to use jQuery's datepicker function in one of my pages. I consistently got the error datepicker is not a function. I tried all sorts of things but nothing worked. Well it turns out I was using prototype and another javascript library called tablekit. Now they both use the $ as a shortcut to refer to themselves, and so does jquery. So when you try to use them together there's a conflict. Fortunately jQuery provides a very nice solution to this (you can read more about it here.

Here's what I ended up doing:
<!-- jQuery JS Includes -->
<script src="javascripts/prototype.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery/jquery-1.3.2.js"></script>

  var $j = jQuery.noConflict();

<script type="text/javascript" src="jquery/ui.core.js"></script>
<script type="text/javascript" src="jquery/ui.datepicker.js"></script>
<script src="javascripts/scriptaculous.js?load=effects,builder,dragdrop" type="text/javascript"></script>

Now to you use $j instead of $ in all your jQuery code.
     // Use jQuery via $j(...)
     // Use Prototype with $(...), etc.

Sunday, March 15, 2009

Part 3 LCDS Insync Example, it works and I'm fed up.

Ok so I got this example to work and there was much rejoicing, followed by much disappointment but I'll save that for the end. There are a ton of steps, and missing one means it's not going to work so I'll try to lay it out for you.
  • Step One: First you need to create a project in flex builder. This really isn't that hard, just start a new air project and call it insync. When it's done just drag everything from the flex source into the src directory of your new project. Let it overwrite insync.mxml. There now you should have your very own project to play with.
  • Step Two: It's been a while since the original author wrote this insync sample so if you don't want an error that says:"error while loading initial content" then you need to go into your insync-app.xml. At the second line there is an application block, change it to say .
  • Step Two:Ok now you need the lcds libraries in your path or else you won't be able to compile against them. If you try you'll just get a bunch of errors which I forget at the moment but they basically say "GET THE LIBRARIES" :) So where are they? If you're like me they're hidden in the war files. Go to your lcds-samples.war file, and unzip it again. Now under the WEB-INF directory you just made by unzipping the file, there is a flex directory. Under that directory are two folders libs and locale. That's where your libraries are. You can copy them someplace else or leave them where they are that's up to you. Next you need to add them to your path. In Flex Builder go to project properties, then go to the Flex Build Path tab. Now you need to add two SWC folders, just click on the SWC folder button and add libs and locale. Now you need to add two SWC files. The first is the airfds.swc file, it's in that libs folder you just added, in the air directory. The last file you need to add is in the locale directory, under the en_US directory, and it's called fds_rb.swc. Just add that file and you're good to go
  • Step Three: At this point you should be able to build. So give it a shot. If you start up your jboss server from part two and start the sample database, then try to run your application you'll get this error: Error: Unable to initialize destinations on server: ["nameOfDataService"] Sigh more errors, unfortunately this one is a bug in lcds, and it's documented here You'll notice there are others that feel our pain, and at the bottom Jeff from Adobe invites people to email him to receive a fixed copy of a library. Which I did yesterday, which was Saturday so we'll see what I get back. In the meantime his advice to compile in your services descriptions led me to come up with the following modifications to the compiler command line. Just go back to Project --> properties in Flex Builder. Now under the Flex Compiler tab, add this to Additional Compiler Arguments: Fill in your directory paths: -locale en_US -services {your path to jboss}/jboss-4.2.2.GA/server/default/deploy/{your directory you unziped lcds-samples.war to}/WEB-INF/flex/services-config.xml -context-root=http://localhost/ Mine looks like this: -locale en_US -services /Users/Downloads/jboss-4.2.2.GA/server/default/deploy/test26/WEB-INF/flex/services-config.xml -context-root=http://localhost/
Ok well now at this point you should be able to compile and run the program yourself. You should see the data populate into the application, and if you see the little green online light in the bottom corner you should be able to make changes. I was pretty happy at this point so I decided to try a little testing, and of course more issues. I don't think it's the original authors design, but more some lingering issues with LCDS but that's just one mans opinion. Try this little test, start your application with the server running and get the contact data, then shutdown the server to simulate a loss of connection. Now add a contact in the insyc application and close it. Now according to the theory when we start up I'd think it would load the contacts from cache since it's offline and if the server is online it should update the sampledb. Not so, if you try to startup with the server started you'll get a couldn't fill message. If you're inclined to dig a little further and debug it you'll see messages about it not being able to initialize the datasource. If you want to fix your problem just go delete the sqlite database it's using. On a mac that's under. /Users/username/Library/Preferences/insync/Local Store/_ds_localstore You'll see the file you want is named after the datacache id set in your insync program. So this is where I stopped, lcds was incredibility complicated to setup, and it seems like there are still bugs to be worked out. These are exactly the type of problems I'd hoped to avoid by using it. So my conclusion is that for what I want to do it's a lot easier to just write it myself. I'm thinking I'll just post signed XML requests to a PHP script for proof of concept, then when I want it to go faster I'll just write a server in C. I hope this helps at least someone out there. Good Luck

Saturday, March 14, 2009

Using a Wii with a PC monitor and keeping your PC sound

Recently a friend of mine presented me with a problem and asked me to help. He had and his wife were both using the Wii and Wii fit to exercise. They had moved their Wii to their upstairs office / exercise room and wanted to hook it up to their PC monitor. Then they'd gone to Best Buy who sold them a video capture card and told them they could use that to hook it up to their PC. That's where I came into the situation. Well you probably won't be surprised to learn that that worked about as well as a marketing guy trying to use an oscilloscope. The quality was terrible, there was significant lag from the time it took the card to process the video, the resolution was poor and finally the program that displayed the video was complicated and crashed a lot. The first part of the solution was to take that video card back where it came from. Next we ordered a Wii cable that converted the component video output to a vga output. I didn't take it apart since it wasn't mine but there isn't much too it, and you could probably make your own but for $35 it's not worth the effort. Plus it was for non technical people so the easier the better. The only issue we had was the cable only worked in 480p mode. Not a big deal but if you don't have a component cable already then the Wii won't go into 480p mode. They didn't have a cable, but I did so with two more trips the problem was solved. The nice thing was they had an lcd monitor with two inputs which meant I could leave both hooked up and they could just switch them whenever they wanted. Of course they only had one set of speakers so I left that hooked up to the Wii. It wasn't long before I got the call, "so how do we get sound out of the PC and the Wii?". Now the simple answer is swap plugs, but that's a pain. I want this to be easy. My next instinct was, "ah we just need to buy a y adapter". When you think about it that's a pretty bad idea too. Yeah it will work, there's a pretty good chance you'll get some feed back noise. Even worse is now you have the possibility of two output drivers competing with one another. That should work for a while, heck it might even work forever, but if a year from now the output driver on the Wii dies we'll all know who's fault it is. Also what if you want to exercise but also listen to some mp3s at the same time? Well I thought back to the first electronic product I ever made and tried to sell myself (note the tried part :). It was called the Audiovive and the idea was simple. I was in college and I wanted to play video games and listen to my music at the same time. Like most techy guys I had a tv, a receiver, some surround sound and more importantly a soldering iron. The solution was the little guy below: It's nothing more than a passive two channel mixer, nothing fancy and it gets the job done. I was going to just give them this, but it was the only one I had left and being a little sentimental I decided I'd rather just build them another one. So for a few bucks in parts from digikey I whipped up a simpler version that I'll go through below. First off I ordered the following:
  • 3 of these headphone jacks CP1-3523N-ND
  • 1 of these pots P2B6203-ND
I chose headphone jacks because I have a ton of 3.5mm jack to RCA converters in my garage from the Audiovive project. I chose that pot because it was cheap, had two elements, and was logarithmic so we'd have better volume control. This is just your basic resistive mixer, no input caps no nothing. Here's the schematic. That's about it. It's pretty simple to wire up. When you're done you can turn the pot and it will balance the amount of sound sent from the two inputs to the output.

Part Three Getting a sample flex app to work

Well prior to all this some googling had brought me to Christophe Coenraets great page on getting LCDS to work with a Flex application. He was nice enough to write an AIR based contact management application that uses LCDS to connect to the sample database. He includes all his source code, a compiled version of the application, as well as the server side code and compiled java classes. I highly recommend reading through all of this as it helped me understand how all this works. Check it out here. Now download all the project files, and install the air application. We'll use that as our litmus test to whether this works or not. Since I'm using JBoss my setup was a bit different than his. I don't have any of the directories he's talking about and just dumping the files into the deploy directory doesn't work. This brings me to the point of actually learning what a .war file is. I'm sure there's a complex explination but it turns out it's just a zipped up collection of files. In there are the java classes, some configuration xml files, you name it. JBoss seems to like to use those so that's what we'll have to do. Now since you've been following along you have an lcds-samples.war file in your deploy directory. This part took a while for me to understand, maybe I was just slow that day. What the example wants you to do is take his files and put them in the classes directory. But where is that directory? Try searching for it you won't find it. The ah ha moment for me was when I realized that it was "inside" the lcds-samples.war file. Maybe that's obvious to some people but not to me. So how to we get in there? It's pretty simple just unzip the .war file. Watch it thought it just expands into whatever directory you're in. What I did was create another directory called test, still under the JBoss default/deploy directory and then I moved lcds-samples.ware into test. Then I opened up another termial window and navigated to that directory. Now just type unzip lcds-samples.war and behold it creates the whole directory structure before your very eyes. You'll find the folder to put Christophe's example under WEB-INF-->flex-->classes. Just drag his lcds folder into here. But wait you're not done yet, go back up one directory level to WEB-INF-->flex. Here you'll find the data-managment-config.xml file that he and most other examples are asking you to add some description code to. If you don't add this when you run his program you'll get an error saying can't fill, and you'll see an exception on your JBoss terminal window. I don't know too much about this but it appears to be a description that tells JBoss how to handle an incoming request and what program to pass it on to. Once you've done all that you need to pack it back up into a war file. I removed the original lcds-samples.war file, you may want to move it to lcds-samples.bak. Just go up to the test directory in your terminal window and type "jar -cvf lcds-samples.war *". That should create the new lcds-samples.war file that you need. Think you're done? Not so fast, this example also needs some data. That data is put in the same sample database application that we started up before. Just take the files in his sampledb and copy them into yours. It will want to overwrite which is ok. If you compare the files you'll see his contains everything the default one does plus his example. So do that restart the database, restart jboss, and try to run his air application. If you see names and contact information appear in the application, then congratulations you got it to work. Next up is getting the flex application code to compile so I can make changes. When I figure that out I'll add it here.

Part Two Getting LCDS

At this point I really didn't quite get what LCDS was. I mean I know what it does, I know it's some sort of libraries, but what "is" it. So far I'd gathered that it was a set of libraries and some example java applications that run on your JAVA application server. Those JAVA applications can have access to server resources like my MySQL server, and they can run as little servers that respond to request from my Flex applications. So a little complicated but not to bad. The first nice surprise about LCDS is although it isn't free, Adobe does have a non expiring one CPU license for developers to use. So that's what you're going to want to get. Now the first time around I installed this on my Ubuntu box, only to find that all of the sample code was set to connect to local host. The next logical step was to install it on my Mac Book but, ahhhhhggg! Adobe doesn't offically support it for the Mac platform. Now I won't rant and rave about that I know there aren't as many Macs out there etc etc, and I do have Windows installed here as a Virtual Machine, but did I really want to do that? No, and thankfully nickul over at adobe was nice enough to post this article on how to install LCDS on a MAC anyway. You can read the original article here, although it didn't quite work for me it inspired me to try. First you need to get LCDS from Adobe and as Nick points out you need the AIX version (the Java Version). I got mine here You'll need a free Adobe ID which you should already have if you've downloaded Flex Builder. Make sure you remember to copy down the serial number they give you, it's the first thing you'll need at install. When the file is done downloading just double click on it to start the install, enter your serial number, agree to it's terms and it should finish up on it's own. It will install your new LCDS files in a folder called Adobe, but it puts that folder at the root of your filesystem. To find it just click on your hard drive icon in finder and you'll see it there at the very top level. Well now you've installed it, now what? Well now you need to "deploy" it to your jboss folder. Remember before when I said I have no idea what I'm doing? Yeah well here we are. What you need to do is copy the .war files that are in your new Adobe/LiveCycle Data Services ES 2.5 folder to your JBOSS deploy folder. As I found out JBOSS has several folders where it goes to run java applications with the default one being called... well default. You can find this folder under your root JBOSS folder: JBOSS FOLDER | |---Server| |--default| |--deploy If you put those .war files in that folder and then start up your server you can then go to http://localhost:8080/lcds-samples/ and you should see the LCDS samples page. At this point you can look at the samples but they don't work. That's because they're trying to connect to the sample database that comes with LCDS, and we haven't started it up yet. It wasn't really clearly explained to me that the sample database was actually a sample database server that you need to run but it is, and you'll find docs telling you it's no where close to being the kind of thing you'd want to base a product on but it works. Anyway just open up another terminal window or tab and go back to the Adobe/LiveCycle Data Services ES 2.5 directory. Under here you'll find a directory called sampledb, and inside sampledb is a script called That's what you're looking for, just start that with a ./, then restart your jboss server. Now you should be able to go to http://localhost:8080/lcds-samples/ and all the samples should be working for you.

Part One Installing JBOSS

Well the very first thing I did was read through the docs on LCDS on Adobe's website. That convinced me that I needed a JBOSS server if this was going to work. Now later I found that's not entirely true, but I'm not sad that I did it since eventually I want this application to be able to server thousands of people. The next thing I did was to install JBOSS on my UBUNTU server, but that's another story. Before we start you should realize I have absolutely no idea what I'm doing. I can't remember when the last time I wrote JAVA was. Heck I didn't even know what JBOSS was two days ago, and I only vaguely remembered the idea of what a JAVA applications server was. Why let that stop us though? The first step is to go out and get JBOSS for your mac. At the time I'm writing this you can find it here It's pretty easy, you just download it, let stuffit automatically decompress it and you've got JBOSS. In fact I'm so lazy I'm still running it out of my Download folder. So this is great now you have jboss but how the heck do you run it? Well in your new jboss directory (mines jboss-4.2.2.GA) there are a lot of directories. The one you're looking for is the "bin" directory. Inside the bin directory are several scripts, and if you just run the file, your new jboss server will begin to start up. Just do a "./". You should now see a bunch of console output from the server and at the very end it will say something like: "19:12:57,095 INFO [Server] JBoss (MX MicroKernel) [4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)] Started in 21s:313ms" That means you're good to go. Now open up your favorite browser and go to http://localhost:8080 and you should see the JBoss welcome page.

Installing Adobe Live Cycle Data Services, with JBOSS, and getting an example to work in FlexBuilder All while on a MAC Introduction

Ok, first the disclaimer. I'm a hardware engineer, I shouldn't be writing code to begin with, but I do on the side. Now if you're like me whenever you're trying to learn something new it's a mixture of trying, and googling, lots of googling. So I decided that after years of leaching off of others posts and instructions that I'd start writing down what worked for me. At worst it's just a record for me, at best maybe it helps someone. I'd been learning to write AIR applications using Adobe's Flex Builder and I was just at the point where I wanted to store things in my Mysql database on my server. My first instinct was to just write some PHP code and call it from the air app, but I wanted more than that. I wanted everything to work while I was offline too, and thats when I came across Adobe Live Cycle Data Services. I even found some great sample code out there that should run in flex buiilder. So I embarked on a journey to get this all installed.