Tuesday, September 10, 2013

Encrypt URL parameters using AES in Java using Spring MVC

Why on earth would you want to do this...  Well, this is one of those crazy requirements that come up with limited resources.

Well.. I do charity work for a 5013C, which has limited resources and one of the requirements they asked of me was to be able to embed data in a static url..  Normally, this would just be a request parameter and my day would proceed on in a rather bland fashion.

This time, it was unique in that some of the data was sensitive (It applied a discount code to the price of a few items) - so manipulating that data would be impactful to the operational integrity of the application. So, how do you secure data when all you have is a url string (SSL and Post options were off the table as this was being embedded as a link in numerous other websites).

So, I decided to use a json payload and encrypt it using AES.. base64 encode it, urlEncode it... and dump that value along with the initial vector into the url as params. It was a rather small payload with only a few sensitive fields, so it was effective, yet crude..

I would be interested in knowing how others would handle this using only a url String making a RESTful call to a server.

The basic requirements:

1. It must be a RESTful url..  All the data is contained in the url.
2. Flat files and database stores are out of the question.. no way to persist data (This was the kicker for me)
3. It has to be embeddable and a direct call.. no middle man url's, etc..

I hope someone reads this and presents a graceful answer.. I don't feel that mine was the best answer, but given my tools in my toolbox.. I didn't see a better way.

Below is the code that does the lifting..  It's fairly straight forward:

Encrypting:
1. The object is serialized to a byte[]
2. Create a Cipher and a random initial vector
3. Hash the key using SHA-256 then trim it to 128-bit for the key
4. Base64 encode the encrypted value
5. Encode the Base64 value to a url friendly format
6. Return the encoded values to include as request parameters in the link

The link will look something like:
http://www.foo.com/view?a=PM90%2B0mzlDLpK5NKlG7CP5lgafMzn5qsrHulCRLR9ZkXnq9L5v7SMuEp%2BPWFtdNR1UxHGw%2Fxh7NzZSPtwSKNRCmQe8fNEMkJJuI4lJ3uvg0DrbI9xXALFZpUs6gAbO7SW5UCeHd6SYWMSWnM9agH9Mw13yfiCKNdiWPiW9j%2BhJa0J5lPraqF1x8srdfm48JaMEg1IaHtRLXukH3VjPTN8sGRUE8nzsu%2BGIyRLaHlXNKt5nZ4wAKtd9Dtfmwe4bgX4k7aEUpaYr90nCU67a%2BxX0NtDB6z7n5lkCQ7bQTNzSA%3D&b=Jux7I3tv%2Ff6HXXFrGOozZA%3D%3D

Decrypting:
1. We decode the request param from Base64 into the raw format. (The container takes care of the url encoding conversion.. so this is not a factor in TC Server)
2. Decode the intial vector value from Base64 into the raw format.
3. Configure the cipher using the secret and the initial vector that was passed in the url
4. Decrypt the encrypted data
5. Serialize the decrypted bytes back into the expected object

All this work.. due to a few limitations. Bleh.. But, it was a fun little traversal in cryptography in Java.

Below is a code sample setup to run in Spring MVC:

Wednesday, September 4, 2013

Dojo App - loading a template from a url.



One of the features that I would love to see added to the dojo app project is the ability to support restful templates. Currently, it only loads templates from inside a static directory versus fetching a template from a restful endpoint.

So, If you want to be able to add this functionality, below is an example of how to do it. It currently works with the 1.9 dojo version, and is an extension of the current functionality, so all current features will continue to work.

The idea is that if a template is prefixed with the dollar sign - such as:  template: "$/foo/view",  then it will use
dojo/request to do a get on that end point for the returned content and load it into the view. Otherwise, it will  process it normally.

A normal config.json file would look something like:

  "views": {
        "header": {
            "constraint": "top",
            "controller": "foo/controllers/header",
            "template": "foo/views/header.html",  
            "dependencies": [
                "dijit/layout/BorderContainer",
                "dijit/layout/ContentPane",
                "dojox/app/widgets/Container",
                "ontrac/widgets/Navigation"
            ]
        },
        "dashboard": {
            "constraint": "middle",
            "controller": "foo/controllers/dashboard",
            "template": "$/foo/view/dashboard",        
            "dependencies": [
                "dijit/layout/BorderContainer",
                "dijit/layout/ContentPane",
                "dojox/app/widgets/Container"
            ]
        }

Below is the Gist of the code - Hope it helps, as it wasn't difficult to add the functionality. I don't make guarantees on cross domain requests.. I've not tested that, so if you need that functionality, you'll need to handle the issues/security that is involved in that.

Make sure you include the following dependencies in the AMD loader when overloading:

"dojox/app/View", "dojo/Deferred", "dojo/when", "dojo/_base/lang", "dojo/request"


Thursday, July 18, 2013

JQuery UI - Date Range Selection

I spent the last few days playing around with changes to make the DatePicker in JQuery work a little more like a range selection tool.

I initially expected this to be a simple extension to JQuery UI's widget structure, but datepicker seems to be a variant and relies upon an instanced configuration. So, it took a bit more work than I originally anticipated.

There was a couple of posts on this, but nothing with a gist or fiddle project to actually learn from - so I've added a fiddle for anyone who would like to see it in action. Hopefully, it will assist anyone what wants a Hotel or Airport style date range selection tool using an existing datepicker configuration.

It's modified from it's base form a bit.. so you'll have to overlook the hacks in there (These were added to support some external requirements to the original design).


Hope it helps in building your little slice of heaven.

http://jsfiddle.net/dacrazycoder/4Fppd/

Monday, November 12, 2012

The best math teacher pickup line!

So.. This is what I do at work!

I'm currently dating a very cute math teacher - so being the fun guy, I found an interesting post showing that the function of e to the power of times y spells the word sexy and sent it over to her.

I was so impressed by my smooth moves, I decided to show it to some of the guys on my whiteboard and then noticed that.. while impressive.. it was lacking a bit! Thus, I've updated it to be the best pickup line for a math/intellectual lady.

 In order to pull this off.. start with U and I - u/i.. where i is the derivative of u. Then you can move in to throw down the sexy.. saying that u being sexy and i being the derivative of sexy, then I would always be able to lie tangent to your curves!

It's the perfect combination of two classic geek pickup lines.. combined with a bit of my own touch to become epic.. If she gets it, she sounds like a winner - if it flies over her head, well.. atleast she's cute!

Have fun in the world of dating!

Friday, September 28, 2012

Tweenable Slider

It's been a while.. but I figured I'd take the time to share one of my fiddle projects to build a simple, clean slider that translates based upon it's container. Here's the fiddle project - the code is pretty much self explanatory. http://jsfiddle.net/dacrazycoder/ZMXVu/25/

Friday, December 2, 2011

SmartFox Server + Unity3d + Hibernate + JPA

This is intended as a post for anyone who's familiar with Hibernate & JPA, as its not very obvious as to where everything goes, you can find all the info, but its spread across numerous posts that don't seem to include all of the relevant information.

So.. here's the quick and dirty of how to set this up to get it to work in SmartFox 2x.

1. Track down the following jars and place them in your SFS2X/lib directory.

antlr-2.7.6.jar
dom4j-1.6.1.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
hibernate3.jar
javassist-3.12.0.GA.jar
jta-1.1.jar

2. Add your jdbc driver to the SFS2X/lib directory

3. Create a new project to hold your entities and add your entities to it.

4. Export the Entity project as a jar to the SFS2X/lib directory.


5. Create a META-INF/Persistence.xml file under the SFS2X directory

6. Ensure that you add the jar-file attribute to the persistence.xml. It is referenced from theSFS2X root.. not the META-INF directory, so you simply need to reference the lib/foo.jar file in the persistence.xml in order for Hibernate to scan your classes.

<jar-file>lib/gameEntities.jar</jar-file>

7. Add your game project jar to the SFS2X/extensions/{project} directory.

8. Add an appender for hibernate to the log4j properties file at SFS2X/config/

log4j.category.org.hibernate=INFO,consoleAppender

It's really that simple... Hopefully, this will save a few others some time when working with this configuration.

If you notice a magic number exception.. you are probably running RC3, which seems to have a classfile conflict. Use RC1b and that should solve the problem..

Friday, August 12, 2011

JDBC - Default ResultSet Fetching Strategy

While working on a section of our companies application that handles migration between various database types, I ran into an interesting issue that I had not really noticed before. There has been a very wide desparity between how various jdbc driver implementations handle the fetching size in a result set.

For example..

MySQL will always return all rows for the query, while DB2 will default to returning exactly 32 rows. I found this odd and as I worked on the application, I noticed that the results seemed to be all across the board. One of the other major considerations when working with the fetching size was the type of data that I was migrating. Migrating smaller varchar based tables wasn't really an issue, however, I found that I had to check each table to ensure that there were not BLOB types present, as the size of those columns could vary greatly. (Between 2-3mb upwards of 1gb Thus, the data type for each column would greatly affect the fetching strategy for each table.

Then I hit some of the big kickers.. since I had to support older drivers, I found myself fighting the older MySQL driver. In order to do any type of streaming for this driver, you must set the fetchSize to Integer.MIN_VALUE, this seemed a bit of an odd selection and was very far off from the jdbc specification. Later builds did improve by allowing you to pass a useCursorFetch hint in the connetion string.

Ultimately, it was a bit of a struggle to make five very different database types migrate between one another in a seemless manner. However, it was a rewarding and challenging experience. In a world where I usually play thru abstractions such as Hibernate.. understanding what it really takes to make a database seamless/brandless/neutral is a very painful task.

Helpful Links:

Good advice for large result sets: http://nullpointer.ph/questions/1103/iterating-over-a-large-db-resultset
Lists a few brands defaults: http://webmoli.com/2009/02/01/jdbc-performance-tuning-with-optimal-fetch-size/