Completed
Push — master ( 7e41c9...ce0f57 )
by Michael
04:14 queued 49s
created

OneTimePad::crypt()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
ccs 8
cts 8
cp 1
cc 2
nc 2
nop 3
crap 2
1
<?php declare(strict_types=1);
2
3
/**
4
 * OneTimePad.php
5
 * 
6
 * PHP version 7
7
 * 
8
 * @category Dcrypt
9
 * @package  Dcrypt
10
 * @author   Michael Meyer (mmeyer2k) <[email protected]>
11
 * @license  http://opensource.org/licenses/MIT The MIT License (MIT)
12
 * @link     https://github.com/mmeyer2k/dcrypt
13
 */
14
15
namespace Dcrypt;
16
17
/**
18
 * A one time pad stream encryption class.
19
 * 
20
 * @category Dcrypt
21
 * @package  Dcrypt
22
 * @author   Michael Meyer (mmeyer2k) <[email protected]>
23
 * @license  http://opensource.org/licenses/MIT The MIT License (MIT)
24
 * @link     https://github.com/mmeyer2k/dcrypt
25
 * @link     http://en.wikipedia.org/wiki/Stream_cipher
26
 */
27
class OneTimePad
28
{
29
    /**
30
     * Encrypt or decrypt a binary input string.
31
     * 
32
     * @param string $input Input data to encrypt
33
     * @param string $key   Encryption/decryption key to use on input
34
     * @param string $algo  Hashing algo to generate keystream
35
     * @return string
36
     */
37 2
    public static function crypt(string $input, string $key, string $algo = 'sha3-512'): string
38
    {
39 2
        $chunks = \str_split($input, Str::hashSize($algo));
40
41 2
        $length = Str::strlen($input);
42
43 2
        $key = new OpensslKey($algo, $key, '');
44
45 2
        foreach ($chunks as $i => &$chunk) {
46 2
            $info = $length . $i;
47 2
            $chunk = $chunk ^ $key->deriveKey($info);
48
        }
49
50 2
        return \implode($chunks);
51
    }
52
}
53