Php openSLL加密 - 防止特殊字符

时间:2016-10-18 14:06:54

标签: php encryption

我想为在url中传递的变量值和异步调用

创建和加密

例如:

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

结果是:W2p0S2qlSierJnIcA / AM3g ==

有一些特殊字符,==总是在最后。我想阻止这个!如何仅输出0-9和A-Z和a-z字符?

感谢

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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;
}