Skip to content

Instantly share code, notes, and snippets.

@rduarte
Created April 2, 2009 22:40
Show Gist options
  • Save rduarte/89542 to your computer and use it in GitHub Desktop.
Save rduarte/89542 to your computer and use it in GitHub Desktop.
algorithm based on base64 for general proposes
<?php
function codificar($valor, $chave){
if (($chave = codificacao_chave($chave)) !== false){
list($inicio, $fim) = $chave;
} else {
return false;
}
$base = base64_encode($valor);
$base = str_replace('=', '', $base);
$base = strrev($base);
$md5 = md5($valor);
$base = (substr($md5, 0, $inicio) . $base . substr($md5, -$fim));
return $base;
}
function decodificar($valor, $chave){
if (($chave = codificacao_chave($chave)) !== false){
list($inicio, $fim) = $chave;
} else {
return false;
}
$hash = (substr($valor, 0, $inicio) . substr($valor, -$fim));
$base = substr($valor, 0, -$fim);
$base = substr($base, $inicio);
$base = strrev($base);
$cmp = (strlen($base) % 4);
if ($cmp > 0) $base .= str_repeat('=', $cmp);
$base = base64_decode($base);
$md5 = md5($base);
$md5 = (substr($md5, 0, $inicio) . substr($md5, -$fim));
return (($md5 == $hash) ? $base : false);
}
function codificacao_chave($chave){
$valor = md5($chave);
$t = strlen($valor);
$dig1 = '';
$dig2 = '';
for ($i = 0; $i < $t; $i++){
$ch = substr($valor, $i, 1);
if (is_numeric($ch) && ($ch !== '0')){
if ($dig1 == ''){
$dig1 = $ch;
} elseif ($dig2 == ''){
$dig2 = $ch;
} else {
break;
}
}
}
return (($dig1 != '') && ($dig2 != '')) ? array($dig1, $dig2) : false;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment