一,环境
windows + php7.2
二,方法实现
$config = array(
'config' =>'D:phpwwwrootphpextrassslopenssl.cnf', //安装PHP7会自带这个配置文件
'digest_alg' => 'sha256', //可以用openssl_get_md_methods() 查看支持的加密方法
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config);
openssl_pkey_export($res, $private_key_pem,null,$config);
$details = openssl_pkey_get_details($res);
$public_key_pem = $details['key'];
echo '<pre>';
var_dump(array('privKey' => $private_key_pem, 'pubKey' => $public_key_pem));
三,生成的公钥私钥验证
$data = "PHP";
openssl_sign($data, $signature, $private_key_pem, OPENSSL_ALGO_SHA256);
$r = openssl_verify($data, $signature, $public_key_pem, OPENSSL_ALGO_SHA256);
var_dump($r);
四,用OPENSSL实现可逆的加密运算替代php7.1之前的mcrypt
$iv = openssl_random_pseudo_bytes(16);
function encrypt($input) {
$data = openssl_encrypt($input, 'AES-256-CBC', 'password', OPENSSL_RAW_DATA,$iv));
$data = base64_encode($data);
return $data;
}
function decrypt($input) {
$decrypted = openssl_decrypt(base64_decode($input), 'AES-256-CBC', 'password', OPENSSL_RAW_DATA,$iv);
return $decrypted;
}