#!/usr/bin/env php
<?php

$string = $argv[1];
$pwd = $argv[2];

$encrypted = encrypt($string, $pwd);

print 'Encrypted: "'.$encrypted."\"\n";

$decrypted = decrypt($encrypted, md5($pwd));
print "Decrypted '".$decrypted."'\n";


function encrypt($string, $pwd)
{
	$key = base64_encode(md5($pwd));  // Key string always 44 bytes
	// strlen(md5($anything)) == 36

	$str = base64_encode($string);
	$len = strlen($str);

	$enc_str = '';

	for ($i = 0; $i < $len; ++$i) {
		$enc_str .= chr(ord($str[$i]) ^ ord($key[$i % 44]));
	}

	return base64_encode($enc_str);
}

function decrypt($str, $pwd)
{
    $pwd = base64_encode($pwd);
    $str = base64_decode($str);
    $enc_chr = '';
    $enc_str = '';
    $i = 0;
    while ($i < strlen($str)) {
        for ($j = 0; $j < strlen($pwd); $j++) {
            $enc_chr = chr(ord($str[$i]) ^ ord($pwd[$j]));
            $enc_str .= $enc_chr;
            $i++;
            if ($i >= strlen($str)) {
                break;
            }
        }
    }
    return base64_decode($enc_str);
}
