k98kurz

chacha20 helper functions (php)

Sep 20th, 2020 (edited)
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.59 KB | None | 0 0
  1. /**
  2.  * Helper functions for easy and secure encryption: chacha20_encrypt and chacha20_decrypt.
  3.  * License: ISC
  4.  * Copyright 2020 Jonathan Voss
  5.  * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
  6.  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  7.  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  8.  * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  9. */
  10. function chacha20_encrypt($data, $key, $iv = '')
  11. {
  12.     $iv = !empty($iv) ? $iv : random_bytes(openssl_cipher_iv_length('chacha20-poly1305'));
  13.     $ct = openssl_encrypt($data, 'chacha20-poly1305', $key, 0, $iv);
  14.     $hash = base64_encode(hex2bin(openssl_digest($ct . $key . $iv, 'sha256')));
  15.     return "$ct." . base64_encode($iv) . ".$hash";
  16. }
  17.  
  18. function chacha20_decrypt($data, $key)
  19. {
  20.     $split = explode('.', $data);
  21.     $ct = $split[0];
  22.     $iv = base64_decode($split[1]);
  23.     $hash = $split[2];
  24.     $computed_hash = base64_encode(hex2bin(openssl_digest($ct . $key . $iv, 'sha256')));
  25.  
  26.     if ($computed_hash !== $hash)
  27.         throw new \Exception('hash mismatch');
  28.  
  29.     return openssl_decrypt($ct, 'chacha20-poly1305', $key, 0, $iv);
  30. }
Add Comment
Please, Sign In to add comment