我正在尝试使用PHP的openssl_decrypt和openssl_encrypt在服务器上加密和解密字符串。
示例代码:
// code for encrypting the string
function encrypt($textToBeEncrypted){
$cipher = file_get_contents('the_cipher_file', FILE_USE_INCLUDE_PATH);
$iv = file_get_contents('the_iv_file', FILE_USE_INCLUDE_PATH);
$key = file_get_contents('the_key_file', FILE_USE_INCLUDE_PATH);
if (in_array($cipher, openssl_get_cipher_methods())){
$ciphertext = openssl_encrypt($textToBeEncrypted, $cipher, $key, $options=0, $iv, $tag);
file_put_contents("the_tag_file", $tag);
if($ciphertext){
return $ciphertext;
}else{
return null;
}
}
return null;
}
// code for decrypting the string
function decrypt($textToBeDecrypted){
$cipher = file_get_contents('the_cipher_file', FILE_USE_INCLUDE_PATH);
$iv = file_get_contents('the_iv_file', FILE_USE_INCLUDE_PATH);
$key = file_get_contents('the_key_file', FILE_USE_INCLUDE_PATH);
$tag = file_get_contents( "the_tag_file");
if (in_array($cipher, openssl_get_cipher_methods())){
$decrypted= openssl_encrypt($textToBeDecrypted, $cipher, $key, $options=0, $iv, $tag);
if($decrypted){
return $decrypted;
}else{
return null;
}
}
return null;
}
此方法的问题在于,每次加密都会生成一个唯一的标签。例如:
$encrypted = encrypt("Hello World"); // creates tag on file "the_tag_file"
echo decrypt($encrypted); // uses tag from "the_tag_file" and decryption works fine
但是:
$encrypted_A = encrypt("Hello USA"); // creates tag A on "the_tag_file"
$encrypted_B = encrypt("Hello CANADA"); // overrides tag A on "the_tag_file" with new tag B
$encrypted_C = encrypt("Hello GERMANY"); // overrides tag B on "the_tag_file" with new tag C
echo decrypt($encrypted_A); // uses tag C instead of A and prints null
echo decrypt($encrypted_B); // uses tag C instead of B and prints null
echo decrypt($encrypted_C); // uses tag C and prints "Hello GERMANY"
因此,我的问题出现了,如何为不同的字符串维护不同的标签,即对于每次解密,我都需要在加密阶段生成的特定标签。我的目的是能够从服务器后端使用加密的字符串更新数据库内容,还可以接收加密的内容,然后在服务器后端对其进行解密,然后继续。