stevennathaniel

PHP AES 256 CBC : Mengenkripsi Plain Text

Jan 3rd, 2021
59
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3.     $key = "74b8d8e7f552f49a9f59642db34ce5601dcb726b52e0";
  4.  
  5.     $plaintext = "mencoba belajar crypthography menggunakan bahasa PHP";
  6.  
  7.     $ivlen = openssl_cipher_iv_length($cipher="AES-256-CBC");
  8.  
  9.     $iv = openssl_random_pseudo_bytes($ivlen);
  10.  
  11.     $ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $option=OPENSSL_RAW_DATA, $iv);
  12.  
  13.     $hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
  14.  
  15.     $ciphertext = base64_encode($iv.$hmac.$ciphertext_raw);
  16.  
  17.     echo $ciphertext."\n";
  18.  
  19.  
  20.     // decrypt text ...
  21.    
  22.     $c = base64_decode($ciphertext);
  23.  
  24.     $ivlen = openssl_cipher_iv_length($cipher="AES-256-CBC");
  25.  
  26.     $iv = substr($c, 0, $ivlen);
  27.  
  28.     $hmac = substr($c, $ivlen, $sha2len=32);
  29.  
  30.     $ciphertext_raw = substr($c, $ivlen+$sha2len);
  31.  
  32.     $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
  33.  
  34.     $calmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
  35.  
  36.     if (hash_equals($hmac, $calmac)){
  37.  
  38.         echo $original_plaintext."\n";
  39.     }
  40.  
  41. ?>
RAW Paste Data