|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Btccom\JustEncrypt; |
|
4
|
|
|
|
|
5
|
|
|
use BitWasp\Buffertools\Buffer; |
|
6
|
|
|
use BitWasp\Buffertools\BufferInterface; |
|
7
|
|
|
use BitWasp\Buffertools\Parser; |
|
8
|
|
|
|
|
9
|
|
|
class Encryption |
|
10
|
|
|
{ |
|
11
|
|
|
|
|
12
|
|
|
const TAGLEN_BITS = 128; |
|
13
|
|
|
const IVLEN_BYTES = 16; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* @param BufferInterface $plainText |
|
17
|
|
|
* @param BufferInterface $passphrase |
|
18
|
|
|
* @param int $iterations |
|
19
|
|
|
* @return EncryptedBlob |
|
20
|
|
|
*/ |
|
21
|
1 |
|
public static function encrypt(BufferInterface $plainText, BufferInterface $passphrase, $iterations = KeyDerivation::DEFAULT_ITERATIONS) |
|
22
|
|
|
{ |
|
23
|
1 |
|
$salt = KeyDerivation::generateSalt(); |
|
24
|
1 |
|
$iv = new Buffer(random_bytes(self::IVLEN_BYTES)); |
|
25
|
1 |
|
return self::encryptWithSaltAndIV($plainText, $passphrase, $salt, $iv, $iterations); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @param BufferInterface $plainText |
|
30
|
|
|
* @param BufferInterface $password |
|
31
|
|
|
* @param BufferInterface $salt |
|
32
|
|
|
* @param BufferInterface $iv |
|
33
|
|
|
* @param int $iterations |
|
34
|
|
|
* @return EncryptedBlob |
|
35
|
|
|
*/ |
|
36
|
3 |
|
public static function encryptWithSaltAndIV(BufferInterface $plainText, BufferInterface $password, BufferInterface $salt, BufferInterface $iv, $iterations) |
|
37
|
|
|
{ |
|
38
|
3 |
|
$header = new HeaderBlob($salt->getSize(), $salt, $iterations); |
|
39
|
3 |
|
$blob = $header->encrypt($plainText, $password, $iv); |
|
40
|
3 |
|
return $blob; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @param BufferInterface $cipherText |
|
45
|
|
|
* @param BufferInterface $password |
|
46
|
|
|
* @return BufferInterface |
|
47
|
|
|
*/ |
|
48
|
3 |
|
public static function decrypt(BufferInterface $cipherText, BufferInterface $password) |
|
49
|
|
|
{ |
|
50
|
3 |
|
return EncryptedBlob::fromParser(new Parser($cipherText))->decrypt($password); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|