forked from defuse/php-encryption
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample.php
40 lines (35 loc) · 1.28 KB
/
example.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
use \Defuse\Crypto\Crypto;
use \Defuse\Crypto\Exception as Ex;
require_once 'autoload.php';
try {
$key = Crypto::createNewRandomKey();
// WARNING: Do NOT encode $key with bin2hex() or base64_encode(),
// they may leak the key to the attacker through side channels.
} catch (Ex\CryptoTestFailedException $ex) {
die('Cannot safely create a key');
} catch (Ex\CannotPerformOperationException $ex) {
die('Cannot safely create a key');
}
$message = "ATTACK AT DAWN";
try {
$ciphertext = Crypto::encrypt($message, $key);
} catch (Ex\CryptoTestFailedException $ex) {
die('Cannot safely perform encryption');
} catch (Ex\CannotPerformOperationException $ex) {
die('Cannot safely perform encryption');
}
try {
$decrypted = Crypto::decrypt($ciphertext, $key);
} catch (Ex\InvalidCiphertextException $ex) { // VERY IMPORTANT
// Either:
// 1. The ciphertext was modified by the attacker,
// 2. The key is wrong, or
// 3. $ciphertext is not a valid ciphertext or was corrupted.
// Assume the worst.
die('DANGER! DANGER! The ciphertext has been tampered with!');
} catch (Ex\CryptoTestFailedException $ex) {
die('Cannot safely perform decryption');
} catch (Ex\CannotPerformOperationException $ex) {
die('Cannot safely perform decryption');
}