public
Last active

  • Download Gist
base62_functions.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
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;
}
enc+dec.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
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;
}
test_base62.txt
1 2 3 4 5 6 7 8 9 10
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
test_enc+dec.txt
1 2 3
100000 equivale 1wADMwATM6c65b (usando a chave 'chave-secreta')
200000 equivale 0wADMwAjM3f793 (usando a chave 'chave-secreta')
(...)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.