Skip to content

Commit bd1cc0a

Browse files
committed
Add cryptor code and example.
1 parent eed91c3 commit bd1cc0a

File tree

2 files changed

+198
-0
lines changed

2 files changed

+198
-0
lines changed

cryptor.php

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
<?php
2+
3+
/**
4+
* Simple example of using the openssl encrypt/decrypt functions that
5+
* are inadequately documented in the PHP manual.
6+
*
7+
* Available under the MIT License
8+
*
9+
* The MIT License (MIT)
10+
* Copyright (c) 2016 ionCube Ltd.
11+
*
12+
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
13+
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
14+
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
15+
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
16+
*
17+
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
18+
* the Software.
19+
*
20+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
21+
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
22+
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
23+
* OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24+
*/
25+
26+
class Cryptor
27+
{
28+
private $cipher_algo;
29+
private $hash_algo;
30+
private $iv_num_bytes;
31+
private $format;
32+
33+
const FORMAT_RAW = 0;
34+
const FORMAT_B64 = 1;
35+
const FORMAT_HEX = 2;
36+
37+
/**
38+
* Construct a Cryptor, using aes256 encryption, sha256 key hashing and base64 encoding.
39+
* @param string $cipher_algo The cipher algorithm.
40+
* @param string $hash_algo Key hashing algorithm.
41+
* @param [type] $fmt Format of the encrypted data.
42+
*/
43+
public function __construct($cipher_algo = 'aes-256-ctr', $hash_algo = 'sha256', $fmt = Cryptor::FORMAT_B64)
44+
{
45+
$this->cipher_algo = $cipher_algo;
46+
$this->hash_algo = $hash_algo;
47+
$this->format = $fmt;
48+
49+
if (!in_array($cipher_algo, openssl_get_cipher_methods(true)))
50+
{
51+
throw new \Exception("Cryptor:: - unknown cipher algo {$cipher_algo}");
52+
}
53+
54+
if (!in_array($hash_algo, openssl_get_md_methods(true)))
55+
{
56+
throw new \Exception("Cryptor:: - unknown hash algo {$hash_algo}");
57+
}
58+
59+
$this->iv_num_bytes = openssl_cipher_iv_length($cipher_algo);
60+
}
61+
62+
/**
63+
* Encrypt a string.
64+
* @param string $in String to encrypt.
65+
* @param string $key Encryption key.
66+
* @param int $fmt Optional override for the output encoding. One of FORMAT_RAW, FORMAT_B64 or FORMAT_HEX.
67+
* @return string The encrypted string.
68+
*/
69+
public function encryptString($in, $key, $fmt = null)
70+
{
71+
if ($fmt === null)
72+
{
73+
$fmt = $this->format;
74+
}
75+
76+
// Build an initialisation vector
77+
$iv = mcrypt_create_iv($this->iv_num_bytes, MCRYPT_DEV_URANDOM);
78+
79+
// Hash the key
80+
$keyhash = openssl_digest($key, $this->hash_algo, true);
81+
82+
// and encrypt
83+
$opts = OPENSSL_RAW_DATA;
84+
$encrypted = openssl_encrypt($in, $this->cipher_algo, $keyhash, $opts, $iv);
85+
86+
if ($encrypted === false)
87+
{
88+
throw new \Exception('Cryptor::encryptString() - Encryption failed: ' . openssl_error_string());
89+
}
90+
91+
// The result comprises the IV and encrypted data
92+
$res = $iv . $encrypted;
93+
94+
// and format the result if required.
95+
if ($fmt == Cryptor::FORMAT_B64)
96+
{
97+
$res = base64_encode($res);
98+
}
99+
else if ($fmt == Cryptor::FORMAT_HEX)
100+
{
101+
$res = unpack('H*', $res)[1];
102+
}
103+
104+
return $res;
105+
}
106+
107+
/**
108+
* Decrypt a string.
109+
* @param string $in String to decrypt.
110+
* @param string $key Decryption key.
111+
* @param int $fmt Optional override for the input encoding. One of FORMAT_RAW, FORMAT_B64 or FORMAT_HEX.
112+
* @return string The decrypted string.
113+
*/
114+
public function decryptString($in, $key, $fmt = null)
115+
{
116+
if ($fmt === null)
117+
{
118+
$fmt = $this->format;
119+
}
120+
121+
$raw = $in;
122+
123+
// Restore the encrypted data if encoded
124+
if ($fmt == Cryptor::FORMAT_B64)
125+
{
126+
$raw = base64_decode($in);
127+
}
128+
else if ($fmt == Cryptor::FORMAT_HEX)
129+
{
130+
$raw = pack('H*', $in);
131+
}
132+
133+
// and do an integrity check on the size.
134+
if (strlen($raw) < $this->iv_num_bytes)
135+
{
136+
throw new \Exception('Cryptor::decryptString() - ' .
137+
'data length ' . strlen($raw) . " is less than iv length {$this->iv_num_bytes}");
138+
}
139+
140+
// Extract the initialisation vector and encrypted data
141+
$iv = substr($raw, 0, $this->iv_num_bytes);
142+
$raw = substr($raw, $this->iv_num_bytes);
143+
144+
// Hash the key
145+
$keyhash = openssl_digest($key, $this->hash_algo, true);
146+
147+
// and decrypt.
148+
$opts = OPENSSL_RAW_DATA;
149+
$res = openssl_decrypt($raw, $this->cipher_algo, $keyhash, $opts, $iv);
150+
151+
if ($res === false)
152+
{
153+
throw new \Exception('Cryptor::decryptString - decryption failed: ' . openssl_error_string());
154+
}
155+
156+
return $res;
157+
}
158+
159+
/**
160+
* Static convenience method for encrypting.
161+
* @param string $in String to encrypt.
162+
* @param string $key Encryption key.
163+
* @param int $fmt Optional override for the output encoding. One of FORMAT_RAW, FORMAT_B64 or FORMAT_HEX.
164+
* @return string The encrypted string.
165+
*/
166+
public static function Encrypt($in, $key, $fmt = null)
167+
{
168+
$c = new Cryptor();
169+
return $c->encryptString($in, $key, $fmt);
170+
}
171+
172+
/**
173+
* Static convenience method for decrypting.
174+
* @param string $in String to decrypt.
175+
* @param string $key Decryption key.
176+
* @param int $fmt Optional override for the input encoding. One of FORMAT_RAW, FORMAT_B64 or FORMAT_HEX.
177+
* @return string The decrypted string.
178+
*/
179+
public static function Decrypt($in, $key, $fmt = null)
180+
{
181+
$c = new Cryptor();
182+
return $c->decryptString($in, $key, $fmt);
183+
}
184+
}

example.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
include_once 'cryptor.php';
4+
5+
$data = 'Good things come in small packages.';
6+
$key = '9901:io=[<>602vV03&Whb>9J&M~Oq';
7+
8+
$encrypted = Cryptor::Encrypt($data, $key);
9+
10+
echo "'$data' (" . strlen($data) . ") => '$encrypted'\n\n";
11+
12+
$decrypted = Cryptor::Decrypt($encrypted, $key);
13+
14+
echo "'$encrypted' => '$decrypted' (" . strlen($decrypted) . ")\n";

0 commit comments

Comments
 (0)