31.7.07

Super secret decoder ring... in php



It's time for a wee bit of code. The following is a simple php class to encrypt/decrypt strings. This is useful when you need to pass around secret documents but are out of microfiche and fake lipstick tubes.

To use:


<?php
require_once('secretdecoderring.php');

$dr = new SecretDecoderRing();
$enc = $dr->encode($argv[1]);
$dec = $dr->decode($enc);
var_dump($argv[1]);
var_dump($enc);
var_dump($dec);
?>




<?php

class SecretDecoderRing
{
private $key = "supersecret";
private $td;

function __construct()
{
$this->td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($this->td), MCRYPT_RAND);
mcrypt_generic_init($this->td, $this->key, $iv);
}

function __deconstruct()
{
mcrypt_generic_deinit($this->td);
mcrypt_module_close($this->td);
}

function encode($string)
{
$enc = mcrypt_generic($this->td, $string);
return base64_encode($enc);
}

function decode($string)
{
$enc = base64_decode($string);
$dec = mdecrypt_generic($this->td, $enc);
// It's padded. Really. Security is such a waste of time.
return rtrim($dec, ((ord(substr($dec, strlen($dec)-1, 1)) >= 0 and ord(substr($dec, strlen($dec)-1, 1)) <= 16) ? c
hr(ord(substr($dec, strlen($dec)-1, 1))): null));
}
}

?>