如何使用特定于用户的密钥 - PHP 创建两种编码/解码方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15884248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:07:52  来源:igfitidea点击:

How to create two way encode/decode methods using use-specific key - PHP?

phpencryptionencodesalt

提问by Jason Silberman

I need two functions/methods, one to encode, one to decode. This is not for storing passwords. Each user will have a specific key/salt to encode the data.

我需要两种功能/方法,一种用于编码,一种用于解码。这不是用于存储密码。每个用户都有一个特定的密钥/盐来编码数据。

This is how I would like it to work:

这就是我希望它工作的方式:

function encode($str, $key) {
    // something fancy
}

function decode($str, $key) {
    // something fancy
}

$key = $logged_in_user->get_key();
$plain = 'abc abc 123 123';
$encoded_data = encode($plain, $key);
// some_fancy_encrypted_data_that_is_really_cooooool
$decoded_data = decode($encoded_data, $key);
// abc abc 123 123

Another thing is that every time I use this function it needs to return the same thing every time I use the encodefunction with the same user key.

另一件事是,每次我使用这个函数时,每次我用encode相同的用户密钥使用该函数时,它都需要返回相同的内容。

How would I do this??

我该怎么做??

回答by rinchik

$myVarIWantToEncodeAndDecode

Define key (salt, broth etc..): $key = "#&$sdfdfs789fs7d";

定义关键(盐、肉汤等): $key = "#&$sdfdfs789fs7d";

To encode:

编码:

$encoded = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $myVarIWantToEncodeAndDecode, MCRYPT_MODE_CBC, md5(md5($key))));

To decode:

解码:

$decoded = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encoded), MCRYPT_MODE_CBC, md5(md5($key))), "##代码##");

Note: mcrypt_decrypt has been DEPRECATED as of PHP 7.1.0. Relying on this function is highly discouraged.

注意:自 PHP 7.1.0 起,mcrypt_decrypt 已被弃用。强烈建议不要依赖此功能。