我需要借助一个秘密静态密钥来解密加密的POST值字符串。
我看过crypt()(但它只是单程)和Mcrypt,GnuPG,......但我对它们不满意。我认为他们应该为我的简单问题复杂化。我该怎么用?我不需要IV形状或超级安全算法。有没有基本的PHP函数,我还不知道呢?
我只需要像这样隐藏用户的图像: ImageJPEG(ImageCreateFromJPEG(decode($ _ REQUEST ['encryptedImage'],'secret Key')));
答案 0 :(得分:4)
由于mcrypt_encrypt从 PHP 7.1.0 开始已弃用。我使用openssl添加了一个简单的加密/解密。
function encrypt($string, $key = 'PrivateKey', $secret = 'SecretKey', $method = 'AES-256-CBC') {
// hash
$key = hash('sha256', $key);
// create iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $secret), 0, 16);
// encrypt
$output = openssl_encrypt($string, $method, $key, 0, $iv);
// encode
return base64_encode($output);
}
function decrypt($string, $key = 'PrivateKey', $secret = 'SecretKey', $method = 'AES-256-CBC') {
// hash
$key = hash('sha256', $key);
// create iv - encrypt method AES-256-CBC expects 16 bytes
$iv = substr(hash('sha256', $secret), 0, 16);
// decode
$string = base64_decode($string);
// decrypt
return openssl_decrypt($string, $method, $key, 0, $iv);
}
$str = 'Encrypt this text';
echo "Plain: " .$str. "\n";
// encrypt
$encrypted_str = encrypt($str);
echo "Encrypted: " .$encrypted_str. "\n";
// decrypt
$decrypted_str = decrypt($encrypted_str);
echo "Decrypted: " .$decrypted_str. "\n";
原始答案:
这样可以变得更简单:(PHP <7.1.0):
<?php
define('SECRET',md5('Some secret key'));
function encrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SECRET, $value, MCRYPT_MODE_ECB, $iv);
}
function decrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SECRET, $value, MCRYPT_MODE_ECB, $iv));
}
?>
答案 1 :(得分:0)
你可以结束内置函数,使它们更友好。与mcrypt_cbc的文档页面上的第二篇用户帖子一样:
<?php
$stuff="String to enc/enc/dec/dec =,=,";
$key="XiTo74dOO09N48YeUmuvbL0E";
function nl() {
echo "<br/> \n";
}
$iv = mcrypt_create_iv (mcrypt_get_block_size (MCRYPT_TripleDES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM);
// Encrypting
function encrypt($string, $key) {
$enc = "";
global $iv;
$enc=mcrypt_cbc (MCRYPT_TripleDES, $key, $string, MCRYPT_ENCRYPT, $iv);
return base64_encode($enc);
}
// Decrypting
function decrypt($string, $key) {
$dec = "";
$string = trim(base64_decode($string));
global $iv;
$dec = mcrypt_cbc (MCRYPT_TripleDES, $key, $string, MCRYPT_DECRYPT, $iv);
return $dec;
}
$encrypted = encrypt($stuff, $key);
$decrypted = decrypt($encrypted, $key);
echo "Encrypted is ".$encrypted . nl();
echo "Decrypted is ".$decrypted . nl();
?>
答案 2 :(得分:0)
这是我所知道的唯一基本内置功能。
$string = "/path/img.jpg";
$scramble = str_rot13($string);
echo "<p>Scrambled: ".$scramble;
echo "<p>Unscrambled: ".str_rot13($scramble);