Php openSLL 加密 - 防止特殊字符

Cri*_*an 5 php encryption

我想创建和加密获取在 url 中传递的变量和异步调用

例如:

$textToEncrypt = "Hello World";
$encryptionMethod = "AES-256-CBC";
$secretHash = "cVb67YtfAz328oOikl96vBn";
$iv = "adfrf54dmnlo09ax";
$encryptedText = openssl_encrypt($textToEncrypt,$encryptionMethod,$secretHash, 0, $iv);
Run Code Online (Sandbox Code Playgroud)

结果是:W2p0S2qlSierJnIcA/AM3g==

有一些特殊字符, == 总是在最后。我要防止这种情况!如何仅输出 0-9 和 AZ 和 az 字符?

谢谢

小智 5

我遇到过同样的问题。我想删除特殊字符。所以,这就是我所做的。使用 将加密文本转换为十六进制值base64_encode($encryptedText)。所以,不会有特殊字符。然后对于还原,base64_decode在传递给之前使用openssl_decrypt


Swi*_*Pro 0

我注意到我的加密字符串末尾也恰好有 2 个等号。末尾似乎总是有两个等号。这是我的解决方案

function encryptString($string, $action, $baseIP = 'false', $extraKey = ''){
    global $flag;

    $encryptedIP = '';

    if($baseIP){
        $encryptedIP = encryptString($_SERVER['REMOTE_ADDR'], 'encrypt', false);
    }

    $output = false;

    $encrypt_method = "AES-256-CBC";
    $secret_key = $flag['2nd-encrypt-key'].$encryptedIP.'-'.$extraKey;
    $secret_iv = $flag['2nd-encrypt-secret'].$encryptedIP.'-'.$extraKey;

    $key = hash('sha256', $secret_key);
    $iv = substr(hash('sha256', $secret_iv), 0, 16);

    $output;

    if($action == 'encrypt'){
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
        //replace equal signs with char that hopefully won't show up
        $output = str_replace('=', '[equal]', $output);
    }else if($action == 'decrypt'){
        //put back equal signs where your custom var is
        $setString = str_replace('[equal]', '=', $string);
        $output = openssl_decrypt(base64_decode($setString), $encrypt_method, $key, 0, $iv);
    }

    return $output;
}
Run Code Online (Sandbox Code Playgroud)