PHP 對稱加密和非對稱性加密

對稱加密就是用同樣的加密手段去解密.PHP中加密使用到了opensll系列函數(shù),需要開啟openssl擴展.

加密方法
function encrypt1($id)
{
$key = "1112121212121212121212";
$data['iv'] = 'fdakieli;njajdj1';
$data['value'] = openssl_encrypt($id, 'AES-256-CBC', $key, 0, $data['iv']);
$encrypt = base64_encode(json_encode($data));
return $encrypt;
}
解密方法
function decrypt2($encrypt)
{
$key = '1112121212121212121212';//解密鑰匙
$encrypt = json_decode(base64_decode($encrypt), true);
#$iv = base64_decode($encrypt['iv']);
$iv = ($encrypt['iv']);
$id = openssl_decrypt($encrypt['value'], 'AES-256-CBC', $key, 0, $iv);
if ($id) {
return $id;
} else {
return 0;
}
}
非對稱性加密:加密和解密用不同的秘鑰.成為公鑰和私鑰,如果用公鑰加密,那么就得用私鑰解密;反過來,用私鑰加密,就要用公鑰解密

非對稱性加密呢

$config = array(
"config" => "D:/phpStudy/PHPTutorial/Apache/conf/openssl.cnf",#這個路徑是openssl.cnf文件的路徑
"digest_alg" => "sha512",
"private_key_bits" => 1024,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
// Create the private and public key
$res = openssl_pkey_new($config);

// Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey, NULL, $config);
echo "Private Key: ".$privKey. '<br />';
// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];

$data = '我是要加密的數(shù)據(jù)';
echo "Data: ".$data. '<br />';
// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);
$encrypted = base64_encode($encrypted);
echo "Encrypted:加密后的數(shù)據(jù) ".$encrypted. '<br />';
// Decrypt the data using the private key and store the results in $decrypted
$encrypted = base64_decode($encrypted);
openssl_private_decrypt($encrypted, $decrypted, $privKey);

echo "Decrypted:解密后的數(shù)據(jù) ".$decrypted. '<br />';
需要注意的一點是, 私鑰公鑰的格式要正確,

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容