Advertisement
Guest User

Untitled

a guest
Oct 7th, 2015
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. $store_me = Sodiumcrypto_box_seal(
  2. $plaintext,
  3. $recipient_public_key
  4. );
  5.  
  6. $visible = Sodiumcrypto_box_seal_open(
  7. $store_me,
  8. $recipient_keypair
  9. );
  10.  
  11. /**
  12. * A human-usable variant of openssl_seal()
  13. *
  14. * @param string $plaintext Your message
  15. * @param string $publickey_string PEM-encoded RSA public key
  16. * @param boolean $encode Hex-encode the output?
  17. *
  18. * @return string
  19. */
  20. function easy_seal($plaintext, $publickey_string, $encode = false)
  21. {
  22. $pubkey = openssl_get_publickey($publickey_string);
  23. if ($pubkey === false) {
  24. throw new Exception('Could not load public key');
  25. }
  26. $sealed = '';
  27. $ekeys = [];
  28. $result = openssl_seal($plaintext, $sealed, $ekeys, [$pubkey], 'aes-256-gcm');
  29. if ($result === false) {
  30. throw new Exception('openssl_seal failed!');
  31. }
  32. if ($encode) {
  33. $sealed = bin2hex($sealed);
  34. foreach ($ekeys as $i => $key) {
  35. $ekeys[$i] = bin2hex($key);
  36. }
  37. }
  38. return json_encode([$sealed, $ekeys]);
  39. }
  40.  
  41. /**
  42. * Inverse operation of easy_seal()
  43. *
  44. * @param string $ciphertext (the output of easy_seal())
  45. * @param string $privatekey_string PEM-encoded RSA private key
  46. * @param boolean $encoded Do we need to decode from hex?
  47. *
  48. * @return string
  49. */
  50. function easy_unseal($ciphertext, $privatekey_string, $encoded = false)
  51. {
  52. list($sealed, $ekeys) = json_decode($ciphertext, true);
  53. if ($encoded) {
  54. $sealed = hex2bin($sealed);
  55. foreach ($ekeys as $i => $key) {
  56. $ekeys[$i] = hex2bin($key);
  57. }
  58. }
  59. $open_data = '';
  60. $privkey = openssl_get_privatekey($privatekey_string);
  61. if ($privkey === false) {
  62. throw new Exception('Could not load public key');
  63. }
  64.  
  65. $result = openssl_open($sealed, $open_data, $ekeys, $privkey, 'aes-256-gcm');
  66. if ($result === false) {
  67. throw new Exception('openssl_open failed!');
  68. }
  69. return $open_data;
  70. }
  71.  
  72. $public_key = file_get_contents('/path/to/publickey.pem');
  73. $plaintext = 'Something something dark side';
  74. $store_me = easy_seal($plaintext, $public_key);
  75.  
  76. // Elsewhere:
  77. $secret_key = file_get_contents('/path/to/secretkey.pem');
  78. $visible = easy_unseal($store_me, $secret_key);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement