tero.co.uk

DES Source Code

This page shows how to use this DES function, and provides the source code in Javascript, Perl and PHP.

Usage
des (string key, string message, boolean encrypt, [integer mode, string iv, integer padding])

The des function accepts an 8 character string as the key (this is 64 bits, but the algorithm only uses 56) for normal DES or a 24 character string for triple DES, a message string, a boolean to say whether the data should be encrypted or decrypted, an optional mode (0 for ECB and 1 for CBC, ECB is the default), an optional 8 character string input vector (not used in ECB mode), and the type of padding (0 for null or zero bytes, 1 for PKCS7, 2 for spaces and 3 for no padding at all). It returns the cipher text as a string.

Here are several examples showing how it can be used:

//encrypt using single DES (with an 8 byte key) in CBC mode
//with the given input vector and PKCS7 padding
des ("8bytekey", "This is the message.", 1, 1, "inputvec", 1);
//encrypt using triple DES (with a 24 byte key) in ECB mode
des ("this is a 24 byte key !!", "This is the message.", 1);
//decrypt using single DES in ECB mode
des ("8bytekey", "2384lf&*£90LSdsf", 0);

Source Code
There is no warranty for this code and I cannot be held responsible for any problems arising from using it (including those caused by bugs). It has been tested to see if it produces correct output, but has not been robustly tested on different browsers, processors, or with a wide range of keys and messages. Any modifications to this code must be posted on this site. If you find any errors, bugs, security holes, or have any questions or comments please email us.

Here is the corresponding script again, this time in Perl (and suitable for running as CGI on servers for talking to the Javascript client version). It does not require any additional libraries. Many thanks to Chris Drake for the conversion. Please contact if you have any comments or problems with the Perl code. Please note that the Perl version does not have the padding options.

Here is the script again in PHP, also not requiring any additional libraries. Many thanks to Jim Gibbs for the conversion.