Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
1.3 KiB

  1. <?php
  2. require_once('Crypto.php');
  3. try {
  4. $key = Crypto::CreateNewRandomKey();
  5. // WARNING: Do NOT encode $key with bin2hex() or base64_encode(),
  6. // they may leak the key to the attacker through side channels.
  7. } catch (CryptoTestFailedException $ex) {
  8. die('Cannot safely create a key');
  9. } catch (CannotPerformOperationException $ex) {
  10. die('Cannot safely create a key');
  11. }
  12. $message = "ATTACK AT DAWN";
  13. try {
  14. $ciphertext = Crypto::Encrypt($message, $key);
  15. } catch (CryptoTestFailedException $ex) {
  16. die('Cannot safely perform encryption');
  17. } catch (CannotPerformOperationException $ex) {
  18. die('Cannot safely perform decryption');
  19. }
  20. try {
  21. $decrypted = Crypto::Decrypt($ciphertext, $key);
  22. } catch (InvalidCiphertextException $ex) { // VERY IMPORTANT
  23. // Either:
  24. // 1. The ciphertext was modified by the attacker,
  25. // 2. The key is wrong, or
  26. // 3. $ciphertext is not a valid ciphertext or was corrupted.
  27. // Assume the worst.
  28. die('DANGER! DANGER! The ciphertext has been tampered with!');
  29. } catch (CryptoTestFailedException $ex) {
  30. die('Cannot safely perform encryption');
  31. } catch (CannotPerformOperationException $ex) {
  32. die('Cannot safely perform decryption');
  33. }
  34. ?>