- Tạo cặp khóa Publickey và Private key
// Config RSA
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
// Create the private and public key
$res = openssl_pkey_new($config);
// Extract the private key from $res to $privateKey
openssl_pkey_export($res, $privateKey);
// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$publicKey = $pubKey['key'];
-
$privateKey
: Là private key -
$publicKey
: Public key -
Decrypt data:
function decrypt($message, $rsaId){
$rsa = Rsa::findOne(['id' => $rsaId]);
if(!$rsa){
return false;
}
openssl_private_decrypt($message, $decrypted, $rsa->privateKey);
return $decrypted;
}
- Encrypt data:
openssl_public_encrypt($data, $encrypted, $rsa->publicKey);
- Trong đó:
$data
: Là dữ liệu cần mã hóa.$encrypted
: Dữ liệu đã được mã hóa
- Muốn truyền
$encrypted
qua URL thì sử dụng hàm mã hóa sau:
$url = urlencode(base64_encode($encrypted));
Hh