Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $store_me = Sodiumcrypto_box_seal(
- $plaintext,
- $recipient_public_key
- );
- $visible = Sodiumcrypto_box_seal_open(
- $store_me,
- $recipient_keypair
- );
- /**
- * A human-usable variant of openssl_seal()
- *
- * @param string $plaintext Your message
- * @param string $publickey_string PEM-encoded RSA public key
- * @param boolean $encode Hex-encode the output?
- *
- * @return string
- */
- function easy_seal($plaintext, $publickey_string, $encode = false)
- {
- $pubkey = openssl_get_publickey($publickey_string);
- if ($pubkey === false) {
- throw new Exception('Could not load public key');
- }
- $sealed = '';
- $ekeys = [];
- $result = openssl_seal($plaintext, $sealed, $ekeys, [$pubkey], 'aes-256-gcm');
- if ($result === false) {
- throw new Exception('openssl_seal failed!');
- }
- if ($encode) {
- $sealed = bin2hex($sealed);
- foreach ($ekeys as $i => $key) {
- $ekeys[$i] = bin2hex($key);
- }
- }
- return json_encode([$sealed, $ekeys]);
- }
- /**
- * Inverse operation of easy_seal()
- *
- * @param string $ciphertext (the output of easy_seal())
- * @param string $privatekey_string PEM-encoded RSA private key
- * @param boolean $encoded Do we need to decode from hex?
- *
- * @return string
- */
- function easy_unseal($ciphertext, $privatekey_string, $encoded = false)
- {
- list($sealed, $ekeys) = json_decode($ciphertext, true);
- if ($encoded) {
- $sealed = hex2bin($sealed);
- foreach ($ekeys as $i => $key) {
- $ekeys[$i] = hex2bin($key);
- }
- }
- $open_data = '';
- $privkey = openssl_get_privatekey($privatekey_string);
- if ($privkey === false) {
- throw new Exception('Could not load public key');
- }
- $result = openssl_open($sealed, $open_data, $ekeys, $privkey, 'aes-256-gcm');
- if ($result === false) {
- throw new Exception('openssl_open failed!');
- }
- return $open_data;
- }
- $public_key = file_get_contents('/path/to/publickey.pem');
- $plaintext = 'Something something dark side';
- $store_me = easy_seal($plaintext, $public_key);
- // Elsewhere:
- $secret_key = file_get_contents('/path/to/secretkey.pem');
- $visible = easy_unseal($store_me, $secret_key);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement