Skip to content

Instantly share code, notes, and snippets.

@rduarte
Created June 7, 2010 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rduarte/429339 to your computer and use it in GitHub Desktop.
Save rduarte/429339 to your computer and use it in GitHub Desktop.
function base62_encode($num){
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$base = 62;
$result = '';
while($num >= $base) {
$r = $num%$base;
$result = $chars[$r].$result;
$num = $num/$base;
}
return $chars[$num].$result;
}
function base62_decode($id){
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$base = 62;
for ($i=0; $i<strlen($id); $i++) {
$value = strpos($chars, $id[$i]);
$num = $value * pow($base, strlen($id)-($i+1));
$final += $num;
}
return $final;
}
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;
}
8 equivale 8
9 equivale 9
10 equivale a
11 equivale b
12 equivale c
(...)
1033 equivale gF
1034 equivale gG
1035 equivale gH
1036 equivale gI
100000 equivale 1wADMwATM6c65b (usando a chave 'chave-secreta')
200000 equivale 0wADMwAjM3f793 (usando a chave 'chave-secreta')
(...)
ID:1000 http://url.com/u/1wADMwATM6c65b
ID:2000 http://url.com/u/0wADMwAjM3f793
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment