Skip to content

Instantly share code, notes, and snippets.

@devthue
Created October 19, 2016 02:17
Show Gist options
  • Save devthue/7a23d70cc4e8c3a8ec094892f947e8f3 to your computer and use it in GitHub Desktop.
Save devthue/7a23d70cc4e8c3a8ec094892f947e8f3 to your computer and use it in GitHub Desktop.
Mã hóa RSA với PHP
  • 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));
@datahtkg
Copy link

datahtkg commented Jun 7, 2024

@datahtkg
Copy link

datahtkg commented Jun 7, 2024

Hh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment