PHP 通过 URL 发送加密数据

2022-01-21 00:00:00 encryption base64 php mcrypt url-encoding

我正在尝试通过 url 将加密数据发送到另一个站点(使用 file_get_contents("anotherUrl.php?hash=$encryptedString").问题是,有时,加密包含一些特殊字符,如 +,这会导致解密失败.

I'm trying to send encrypted data over the url to another site (using file_get_contents("anotherUrl.php?hash=$encryptedString"). The problem is, sometimes, the encryption contains some special characters, like +, and this causes the decryption to fail.

这是我的加密/解密方法:

Here are my encryption / decryption methods:

public function encrypt($string, $key)
{
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
}

public function decrypt($encrypted, $key)
{
    return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "");
}

这是一个包含 + 的示例加密字符串,我猜这会导致解密失败.

Here's an example encrypted string which contains a +, and I'm guessing that this causes the decryption to fail.

oWCrVPaS+5GbxcQFc0fulUk/zRAkDD60av4zlPiWskE=

任何想法我应该如何解决这个问题?我尝试对哈希执行 urlencode()urldecode() ,但这似乎也会导致加密中断.有没有办法改变加密算法让它只返回 url 安全字符?

Any ideas how I should solve this? I've tried to do urlencode() and urldecode() on the hash, however that also seems to cause the encryption to break. Is there a way to change the encryption algorithm to get it to only return url safe characters?

推荐答案

看看这个帖子:

在 URL 中传递 base64 编码字符串

基本上你DO想要在发送字符串之前urlencode(),但是你确实不想要urldecode() 在另一端.

Essentially you DO want to urlencode() before sending the string, however you do NOT want to urldecode() at the other end.

相关文章