Encoding numbers the Geek Times way

Categories: uncategorized

Date: 23 September 2005 13:22:38

Working from home has it's good and bad points. Good points: music, food, comfortable surroundings. Bad points: distractions, the huge list of jobs la inamorata has left me to do while I'm here. Perhaps she doesn't quite get the "working" bit in "working from home"!

But I have at least come up with a slightly different way of encoding a number. Let's say, for example, you have a number you want to save in a secure form. Normal encryption/decryption techniques are all very well, but most of the famous ones (Blowfish, AES, MD5 etc) can be hacked. What we need is something new and fresh.

Anyway, this is what I came up with late on Thursday night.

Step 1:

Take your number, in our example "1234" and pad it to a silly length with zeroes:

1234 -> 0000001234

Step 2:

Make up a random array of numbers; the array should have the same number of elements as the string we've just created above (in our example 10):

array(42,94,76,1,24,85,43,67,54,55)

That will be our "key".

Step 3:

Split up your first string into individual characters, and between each character place a random string of numbers the same length as the corresponding item in the key array. I know that's complex, so I'll demonstrate:

Start loop x

Get string character x
Get array element x

Output = string(x) then (array(x) random numbers)

If you're still scratching your head over this, here's a couple of little functions I whipped up to do the whole lot:

function randomise($length){
$return = "";
for($i=0; $i<$length; $i++){
$return .= mt_rand(0,9);
}
return $return;
}

function encodeNumber($number){
for ($i=strlen($number); $i<10; $i++){
$userid = "0".$number;
}
$encid = randomise(42).substr($number,0,1);
$encid .= randomise(94).substr($number,1,1);
$encid .= randomise(76).substr($number,2,1);
$encid .= randomise(1).substr($number,3,1);
$encid .= randomise(24).substr($number,4,1);
$encid .= randomise(85).substr($number,5,1);
$encid .= randomise(43).substr($number,6,1);
$encid .= randomise(67).substr($number,7,1);
$encid .= randomise(54).substr($number,8,1);
$encid .= randomise(55).substr($number,9,1);
return $encid;
}

What you'd end up with is a seemingly random string of numbers. Neat, eh? Then all you need is a bit of string maniuplation based around the values of your key array to get the original numbers back. It may not be the most secure system, but for a quick and simple encoding mechanism I'm quite happy with it.