1<?php
2use Crypto\Cipher;
3use Crypto\AlgorihtmException;
4
5$algorithm = 'aes-256-cbc';
6
7if (!Cipher::hasAlgorithm($algorithm)) {
8	die("Algorithm $algorithm not found" . PHP_EOL);
9}
10
11try {
12	$cipher = new Cipher($algorithm);
13
14	// Algorithm method for retrieving algorithm
15	echo "Algorithm: " . $cipher->getAlgorithmName() . PHP_EOL;
16
17	// Params
18	$key_len = $cipher->getKeyLength();
19	$iv_len = $cipher->getIVLength();
20
21	echo "Key length: " . $key_len . PHP_EOL;
22	echo "IV length: "  . $iv_len . PHP_EOL;
23	echo "Block size: " . $cipher->getBlockSize() . PHP_EOL;
24
25	// This is just for this example. You should never use such key and IV!
26	$key = str_repeat('x', $key_len);
27	$iv = str_repeat('i', $iv_len);
28
29	// Test data
30	$data1 = "Test";
31	$data2 = "Data";
32	$data = $data1 . $data2;
33
34	// Simple encryption
35	$sim_ct = $cipher->encrypt($data, $key, $iv);
36
37	// init/update/finish encryption
38	$cipher->encryptInit($key, $iv);
39	$iuf_ct  = $cipher->encryptUpdate($data1);
40	$iuf_ct .= $cipher->encryptUpdate($data2);
41	$iuf_ct .= $cipher->encryptFinish();
42
43	// Raw data output (used base64 format for printing)
44	echo "Ciphertext (sim): " . base64_encode($sim_ct) . PHP_EOL;
45	echo "Ciphertext (iuf): " . base64_encode($iuf_ct) . PHP_EOL;
46	// $iuf_out == $sim_out
47	$ct = $sim_ct;
48
49	// Another way how to create a new cipher object (using the same algorithm and mode)
50	$cipher = Cipher::aes(Cipher::MODE_CBC, 256);
51
52	// Simple decryption
53	$sim_text = $cipher->decrypt($ct, $key, $iv);
54
55	// init/update/finish decryption
56	$cipher->decryptInit($key, $iv);
57	$iuf_text = $cipher->decryptUpdate($ct);
58	$iuf_text .= $cipher->decryptFinish();
59
60	// Raw data output ($iuf_out == $sim_out)
61	echo "Text (sim): " . $sim_text . PHP_EOL;
62	echo "Text (iuf): " . $iuf_text . PHP_EOL;
63}
64catch (AlgorithmException $e) {
65	echo $e->getMessage() . PHP_EOL;
66}
67