Padding   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
eloc 15
dl 0
loc 56
c 0
b 0
f 0
ccs 17
cts 17
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A remove() 0 15 5
A add() 0 4 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Sop\PKCS5;
6
7
/**
8
 * Implements PKCS#5 padding.
9
 *
10
 * @see https://tools.ietf.org/html/rfc8018#section-6.1.1
11
 */
12
class Padding
13
{
14
    /**
15
     * Padding blocksize.
16
     *
17
     * @var int
18
     */
19
    protected $_blocksize;
20
21
    /**
22
     * Constructor.
23
     *
24
     * @param int $blocksize Blocksize
25
     */
26 17
    public function __construct(int $blocksize = 8)
27
    {
28 17
        $this->_blocksize = $blocksize;
29 17
    }
30
31
    /**
32
     * Add padding.
33
     *
34
     * @param string $data
35
     *
36
     * @return string Data padded to blocksize
37
     */
38 11
    public function add(string $data): string
39
    {
40 11
        $n = $this->_blocksize - strlen($data) % $this->_blocksize;
41 11
        return $data . str_repeat(chr($n), $n);
42
    }
43
44
    /**
45
     * Remove padding.
46
     *
47
     * @param string $data
48
     *
49
     * @throws \UnexpectedValueException
50
     *
51
     * @return string
52
     */
53 15
    public function remove(string $data): string
54
    {
55 15
        $len = strlen($data);
56 15
        if (!$len) {
57 1
            throw new \UnexpectedValueException('No padding.');
58
        }
59 14
        $n = ord($data[$len - 1]);
60 14
        if ($len < $n || $n > $this->_blocksize) {
61 3
            throw new \UnexpectedValueException('Invalid padding length.');
62
        }
63 11
        $ps = substr($data, -$n);
64 11
        if ($ps !== str_repeat(chr($n), $n)) {
65 1
            throw new \UnexpectedValueException('Invalid padding string.');
66
        }
67 10
        return substr($data, 0, -$n);
68
    }
69
}
70