Encrypting POST Data with JavaScript
The standard for encrypting data in transmission over the interwebs is obviously SSL (Secure Socket Layer). But what if you want a simple way to encrypt data without the cost of an SSL? Why not encrypt it client-side with JavaScript, pass a key, and decrypt it server-side?
Go from this...

To this...

Still not clicking? Check out my demo...
The Biggest Hurdle - Translation.
Keep in mind that the challenge here from a programming standpoint is the fact that you're encrypting in JavaScript and decrypting (for this example) in PHP. There are functions in PHP that make this sort of encryption very easy but are not available in JavaScript (or return slightly different results). How did I overcome this? Simple - PHP.js. If you haven't seen it yet it allows you to embed PHP functions into your javascript. Very nice utility and something every developer should have in their bag-o-tricks.
Step One - The JavaScript
On the JS side we're simply applying a (simple) algorithm to encrypt the data for each form field using a value:
function c2sencrypt(s,k){
k = str_split(str_pad('',strlen(s),k));
sa = str_split(s);
for(var i in sa){
t = ord(sa[i])+ord(k[i]);
sa[i] = chr(t > 255 ?(t-256):t);
}
return escape(join('', sa));
}
Step Two - The PHP
Now we simply decrypt it on the other side using a PHP function that reverses the encryption applied by the JavaSCript:
function c2sdecrypt($s,$k){
$s = urldecode($s);
$k = str_split(str_pad('', strlen($s), $k));
$sa = str_split($s);
foreach($sa as $i=>$v){
$t = ord($v)-ord($k[$i]);
$sa[$i] = chr( $t < 0 ?($t+256):$t);
}
return join('', $sa);
}
Putting It All Together
Pretty simple, right? All I did was on submission of the form replace the contents of the form fields with data run through the encryption system and used the key on the PHP-side to decrypt it.
There's a Plugin For That...
Want a simple way (using jQuery) to implement this without much thinking? Check out my jqCrypt plugin.
Special Note:
This is NOT a replacement for SSL's. This is a good way for paranoid people like myself to add some additional protection to things like login and sign-up forms. If you're working with sensitive data or processing online transactions please spend the money and buy an SSL. This is more obfuscation than encryption, and while it's a handy trick to prevent most MITM captures it can be broken a lot more easily than an SSL and doesn't provide any verification to your visitors that their data is protected.
Responses to this Article:
Loading Comments...
I am a web developer, designer, and consultant located in the La Crosse / Onalaska Wisconsin region with
over twelve years experience developing and managing projects ranging from large applications and cloud-based
business solutions to social/new media campaigns, to complete system and infrastructure implementation.