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

OneTimePad   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 2
lcom 0
cbo 2
dl 0
loc 26
rs 10
c 0
b 0
f 0
ccs 8
cts 8
cp 1

1 Method

Rating   Name   Duplication   Size   Complexity  
A crypt() 0 15 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