Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. <?php
  2. // DEFINE our cipher
  3. define('AES_256_CBC', 'aes-256-cbc');
  4.  
  5. // Generate a 256-bit encryption key
  6. // This should be stored somewhere instead of recreating it each time
  7. $encryption_key = openssl_random_pseudo_bytes(32);
  8.  
  9. // Generate an initialization vector
  10. // This *MUST* be available for decryption as well
  11. $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC));
  12.  
  13. // Create some data to encrypt
  14. $data = "Encrypt me, please!";
  15. echo "Before encryption: $data\n";
  16.  
  17. // Encrypt $data using aes-256-cbc cipher with the given encryption key and
  18. // our initialization vector. The 0 gives us the default options, but can
  19. // be changed to OPENSSL_RAW_DATA or OPENSSL_ZERO_PADDING
  20. $encrypted = openssl_encrypt($data, AES_256_CBC, $encryption_key, 0, $iv);
  21. echo "Encrypted: $encrypted\n";
  22.  
  23. // If we lose the $iv variable, we can't decrypt this, so append it to the
  24. // encrypted data with a separator that we know won't exist in base64-encoded
  25. // data
  26. $encrypted = $encrypted . $iv;
  27.  
  28. // To decrypt, separate the encrypted data from the initialization vector ($iv)
  29. $parts=[];
  30.  
  31. //extract the last 16 characters.
  32. $IV = substr($encrypted, -16);
  33. array_push($parts,$IV);
  34.  
  35. //remove the IV from the data string.
  36. $encrypteddata = str_replace($IV,"",$encrypted);
  37. array_push($parts,$encrypteddata);
  38.  
  39. $decrypted = openssl_decrypt($parts[1], AES_256_CBC, $encryption_key, 0, $parts[0]);
  40.  
  41. echo "Decrypted: $decrypted\n";
  42. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement