-
Notifications
You must be signed in to change notification settings - Fork 0
/
cycle-crypt.php
42 lines (35 loc) · 1.18 KB
/
cycle-crypt.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
41
42
<?php
declare(strict_types=1);
namespace duzun;
use duzun\CycleCrypt;
// ---------------------------------------------------------------
/**
* Variable size symmetric key encryption algorithm.
*
* @param string $key The encryption key
* @param string $data Data to encrypt
* @param string|bool $salt
* If a string, use it as salt.
* If TRUE, generate salt and prepend it to the encrypted data.
* If FALSE, get the salt from the data.
* @param int $saltRounds Number of rounds of initial state generated from $salt ⊕ $key
*
* @return string The encrypted data. If $salt is TRUE, the generated salt is prepended to the result.
*/
function cycleCrypt($key, $data, $salt = true, $saltRounds = 1)
{
// Use the salt prepended to the data
if ($salt === false) {
$i = ord($data[0]);
$salt = substr($data, 1, $i);
$data = substr($data, $i + 1);
}
$cc = new CycleCrypt($key, $salt, $saltRounds);
$ret = $cc($data);
// Generate salt and prepend it to the result
if ($salt === true) {
$salt = $cc->getSalt();
$ret = chr(strlen($salt)) . $salt . $ret;
}
return $ret;
}