Secure Javascript-PHP Client-server communication
Encryption vs Hashing
In
hashing, a code is computed from
data in such a way that it is exceedingly difficult for anyone to find
data that produces the same code. Agents exchange the code for
verification over an unreliable network (such as internet). For
instance, in a user authentication situation the server may issue a
challenge (a random number). The client obtains the password and
transmits the hash of the challenge and the password, which the server
compares to its hash of that data. Well known algorithms are SHA1, MD4 and MD5.
Background information and JavaScript implementations of SHA1, MD4,
MD5 and RSA can be found in Paul Johnston's
excellent website on cryptography.
Modern PHP implementations (as of 4.3) have SHA1 and MD5 algorithms
built-in.
In encryption, a code is computed from data using a key in
such a way that it is difficult for anyone to find the data without
having the key. If one has the key, the original data can be easily obtained
from the code. Agents exchange data over an unreliable network
by encrypting it. In asymmetric encryption different keys are
used for en/de-cryption. For example, PGP uses a public encryption key
with a private decryption key, based on the RSA algorithm. In
symmetric encryption the same key is used either way, so the
agents must share a secret. A fast encryption
algorithm with a footprint suitable for web programming is the Tiny
Encryption Algorithm (TEA) by Wheeler & Needham.
Simon Shepherd maintains an extensive
website on TEA with a number of implementations in C and
various assemblers. Unfortunately the JavaScript implementations shown
there (October 15, 2006) are flawed. An explanation is here. Note that the algorithms below are most likely
suboptimal; they are adaptations of an algorithgm suitable for 32-bit
arithmetic.
Two encryption/decryption algorithms based on
TEA
Function
cryptN en/decrypts a string of
characters (of which the lower 8 bits are used) using a 16-character
key. Argument 3 is
true for encryption,
false for the reverse. Argument 4 defines the number of
iterations, which define a level of security (32: tight, 16:
reasonable and 8: superficial). Functions
hexify and
dehexify convert a string of characters, using 8
significant bits, to and from hexadecimal representation, for instance
for embedding in XML, in a HTTP request.
This code is distributed under the
Mozilla Public License Version 1.1, which (briefly)
grants right to use and distribute this code royalty-free.
JavaScript
tea.js
PHP
tea.php