Encode and decot URL

Asked

Viewed 1,731 times

4

I have an application that I need to send links with user information, basic example below:

https://www.meusite.com.br/[email protected]&token=token

I want to encode the part [email protected]&token=token when send email and take off when receive. I saw that I can do this process with Base64, the doubt is as follows, is there another method other than Base64? Because Base64 is easier to read by third parties.

  • mcrypt may be an alternative. I suggest you take a look at: http://php.net/manual/en/book.mcrypt.php

  • Mcrypt unfortunately is deprecated and is not recommended to use

1 answer

1

Use $_GET only for data that has no problem being exposed in the URL, as search parameters, where the user can copy the URL and send it to someone else, who will see exactly the same page as it.

When dealing with user data, the most recommended is to use $_POST with HTTPS encryption. Encrypting and decrypting strings in PHP is complicated, because you will usually need libraries that are not available at all hosts, such as Openssl, etc. See: https://stackoverflow.com/questions/9262109/simplest-two-way-encryption-using-php

Follow a functional example with Openssl:

<?php

$chave = 'AlgumaStringAleatóriaSegura';
$texto = "minha mensagem";

function encriptar($texto, $chave)
{
    $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
    $iv = openssl_random_pseudo_bytes($ivlen);
    $ciphertext_raw = openssl_encrypt($texto, $cipher, $chave, $options=OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext_raw, $chave, $as_binary=true);
    return $ciphertext = base64_encode($iv.$hmac.$ciphertext_raw);
}

function desencriptar($textoCodificado, $chave)
{
    $c = base64_decode($textoCodificado);
    $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
    $iv = substr($c, 0, $ivlen);
    $hmac = substr($c, $ivlen, $sha2len=32);
    $ciphertext_raw = substr($c, $ivlen+$sha2len);
    $texto_original = openssl_decrypt($ciphertext_raw, $cipher, $chave, $options=OPENSSL_RAW_DATA, $iv);
    $calcmac = hash_hmac('sha256', $ciphertext_raw, $chave, $as_binary=true);
    if (hash_equals($hmac, $calcmac)) {//PHP 5.6+ timing attack safe comparison
        return $texto_original."\n";
    }
}

// Texto encriptado
$textoEncriptado = encriptar($texto, $chave);
echo $textoEncriptado.'<br>';

// Texto desencriptado
$textoDesencriptado = desencriptar($textoEncriptado, $chave);
echo $textoDesencriptado.'<br>';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.