openssl_decrypt_basic.phpt 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. --TEST--
  2. openssl_decrypt() tests dependent on openssl_encrypt
  3. --EXTENSIONS--
  4. openssl
  5. --FILE--
  6. <?php
  7. $data = "openssl_encrypt() and openssl_decrypt() tests";
  8. $method = "AES-128-CBC";
  9. $password = "openssl";
  10. $ivlen = openssl_cipher_iv_length($method);
  11. $iv = '';
  12. srand(time() + ((int)(microtime(true) * 1000000) % 1000000));
  13. while(strlen($iv) < $ivlen) $iv .= chr(rand(0,255));
  14. $encrypted = openssl_encrypt($data, $method, $password, 0, $iv);
  15. $output = openssl_decrypt($encrypted, $method, $password, 0, $iv);
  16. var_dump($output);
  17. $encrypted = openssl_encrypt($data, $method, $password, OPENSSL_RAW_DATA, $iv);
  18. $output = openssl_decrypt($encrypted, $method, $password, OPENSSL_RAW_DATA, $iv);
  19. var_dump($output);
  20. // if we want to manage our own padding
  21. $padded_data = $data . str_repeat(' ', 16 - (strlen($data) % 16));
  22. $encrypted = openssl_encrypt($padded_data, $method, $password, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
  23. $output = openssl_decrypt($encrypted, $method, $password, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
  24. var_dump(rtrim($output));
  25. $output2 = openssl_decrypt($encrypted, $method, $password, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv, tag: '');
  26. var_dump($output2 === $output);
  27. $output3 = openssl_decrypt($encrypted, $method, $password, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv, tag: null);
  28. var_dump($output3 === $output);
  29. if (in_array("bf-ecb", openssl_get_cipher_methods())) {
  30. // if we want to prefer variable length cipher setting
  31. $encrypted = openssl_encrypt($data, "bf-ecb", $password, OPENSSL_DONT_ZERO_PAD_KEY);
  32. $output = openssl_decrypt($encrypted, "bf-ecb", $password, OPENSSL_DONT_ZERO_PAD_KEY);
  33. var_dump($output === $data);
  34. } else {
  35. var_dump(true);
  36. }
  37. // It's okay to pass $tag for a non-authenticated cipher.
  38. // It will be populated with null in that case.
  39. openssl_encrypt($data, $method, $password, 0, $iv, $tag);
  40. var_dump($tag);
  41. ?>
  42. --EXPECT--
  43. string(45) "openssl_encrypt() and openssl_decrypt() tests"
  44. string(45) "openssl_encrypt() and openssl_decrypt() tests"
  45. string(45) "openssl_encrypt() and openssl_decrypt() tests"
  46. bool(true)
  47. bool(true)
  48. bool(true)
  49. NULL