Failed Conditions
Push — master ( b0e729...072e31 )
by Florent
02:37 queued 58s
created

AESKW::checkInitialValue()   C

Complexity

Conditions 8
Paths 7

Size

Total Lines 34
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 34
rs 5.3846
cc 8
eloc 17
nc 7
nop 3
1
<?php
2
3
/*
4
 * The MIT License (MIT)
5
 *
6
 * Copyright (c) 2014-2016 Spomky-Labs
7
 *
8
 * This software may be modified and distributed under the terms
9
 * of the MIT license.  See the LICENSE file for details.
10
 */
11
12
namespace AESKW;
13
14
use Assert\Assertion;
15
16
trait AESKW
17
{
18
    /**
19
     * The initial value used to wrap the key and check the integrity when unwrapped.
20
     * The RFC3394 set this value to 0xA6A6A6A6A6A6A6A6
21
     * The RFC5649 set this value to 0xA65959A6XXXXXXXX (The part with XXXXXXXX is the MLI, depends on the padding).
22
     *
23
     * @param string $key             The key
24
     * @param bool   $padding_enabled Enable padding (RFC5649)
25
     *
26
     * @return string
27
     *
28
     * @see https://tools.ietf.org/html/rfc3394#section-2.2.3.1
29
     */
30
    private static function getInitialValue(&$key, $padding_enabled)
31
    {
32
        if (false === $padding_enabled) {
33
            return hex2bin('A6A6A6A6A6A6A6A6');
34
        }
35
36
        $MLI = mb_strlen($key, '8bit');
37
        $iv = hex2bin('A65959A6').self::toXBits(32, $MLI);
38
39
        $n = intval(ceil($MLI / 8));
40
        $key = str_pad($key, 8 * $n, "\0", STR_PAD_RIGHT);
41
42
        return $iv;
43
    }
44
45
    /**
46
     * @param string $key
47
     * @param bool   $padding_enabled
48
     * @param string $iv
49
     *
50
     * @return bool
51
     */
52
    private static function checkInitialValue(&$key, $padding_enabled, $iv)
53
    {
54
        // RFC3394 compliant
55
        if ($iv === hex2bin('A6A6A6A6A6A6A6A6')) {
56
            return true;
57
        }
58
59
        // The RFC3394 is required but the previous check is not satisfied => invalid
60
        if (false === $padding_enabled) {
61
            return false;
62
        }
63
64
        // The high-order half of the AIV according to the RFC5649
65
        if (hex2bin('A65959A6') !== self::getMSB($iv)) {
66
            return false;
67
        }
68
69
        $n = mb_strlen($key, '8bit') / 8;
70
        $MLI = hexdec(bin2hex(ltrim(self::getLSB($iv), "\0")));
71
72
        if (!(8 * ($n - 1) < $MLI && $MLI <= 8 * $n)) {
73
            return false;
74
        }
75
76
        $b = 8 * $n - $MLI;
77
        for ($i = 0; $i < $b; ++$i) {
78
            if ("\0" !== mb_substr($key, $MLI + $i, 1, '8bit')) {
79
                return false;
80
            }
81
        }
82
        $key = mb_substr($key, 0, $MLI, '8bit');
83
84
        return true;
85
    }
86
87
    /**
88
     * @param string $key             The Key to wrap
89
     * @param bool   $padding_enabled
90
     */
91
    private static function checkKeySize($key, $padding_enabled)
92
    {
93
        Assertion::false(false === $padding_enabled && 0 !== mb_strlen($key, '8bit') % 8, 'Bad key size');
94
        Assertion::greaterOrEqualThan(mb_strlen($key, '8bit'), 1, 'Bad key size');
95
    }
96
97
    /**
98
     * @param string $kek             The Key Encryption Key
99
     * @param string $key             The key to wrap
100
     * @param bool   $padding_enabled If false, the key to wrap must be a sequence of one or more 64-bit blocks (RFC3394 compliant), else the key size must be at least one octet (RFC5649 compliant)
101
     *
102
     * @return string The wrapped key
103
     */
104
    public static function wrap($kek, $key, $padding_enabled = false)
105
    {
106
        self::checkKEKSize($kek);
107
        $A = self::getInitialValue($key, $padding_enabled);
108
        self::checkKeySize($key, $padding_enabled);
109
        $P = str_split($key, 8);
110
        $N = count($P);
111
        $C = [];
112
113
        $encryptor = self::getEncryptor($kek);
114
        if (1 === $N) {
115
            $B = $encryptor->encrypt($A.$P[0]);
116
            $C[0] = self::getMSB($B);
117
            $C[1] = self::getLSB($B);
118
        } elseif (1 < $N) {
119
            $R = $P;
120
            for ($j = 0; $j <= 5; ++$j) {
121
                for ($i = 1; $i <= $N; ++$i) {
122
                    $B = $encryptor->encrypt($A.$R[$i - 1]);
123
                    $t = $i + $j * $N;
124
                    $A = self::toXBits(64, $t) ^ self::getMSB($B);
125
                    $R[$i - 1] = self::getLSB($B);
126
                }
127
            }
128
            $C = array_merge([$A], $R);
129
        }
130
131
        return implode('', $C);
132
    }
133
134
    /**
135
     * @param string $kek             The Key Encryption Key
136
     * @param string $key             The key to unwrap
137
     * @param bool   $padding_enabled If false, the AIV check must be RFC3394 compliant, else it must be RFC5649 or RFC3394 compliant
138
     *
139
     * @return string The key unwrapped
140
     */
141
    public static function unwrap($kek, $key, $padding_enabled = false)
142
    {
143
        self::checkKEKSize($kek);
144
        $P = str_split($key, 8);
145
        $A = $P[0];
146
        $N = count($P);
147
148
        Assertion::greaterThan($N, 1, 'Bad data');
149
        $encryptor = self::getEncryptor($kek);
150
151
        if (2 === $N) {
152
            $B = $encryptor->decrypt($P[0].$P[1]);
153
            $unwrapped = self::getLSB($B);
154
            $A = self::getMSB($B);
155
        } else {
156
            $R = $P;
157
            for ($j = 5; $j >= 0; --$j) {
158
                for ($i = $N - 1; $i >= 1; --$i) {
159
                    $t = $i + $j * ($N - 1);
160
                    $B = $encryptor->decrypt((self::toXBits(64, $t) ^ $A).$R[$i]);
161
                    $A = self::getMSB($B);
162
                    $R[$i] = self::getLSB($B);
163
                }
164
            }
165
            unset($R[0]);
166
167
            $unwrapped = implode('', $R);
168
        }
169
        Assertion::true(self::checkInitialValue($unwrapped, $padding_enabled, $A), 'Integrity check failed');
170
171
        return $unwrapped;
172
    }
173
174
    /**
175
     * @param int $bits
176
     * @param int $value
177
     *
178
     * @return string
179
     */
180
    private static function toXBits($bits, $value)
181
    {
182
        return hex2bin(str_pad(dechex($value), $bits / 4, '0', STR_PAD_LEFT));
183
    }
184
185
    /**
186
     * @param string $value
187
     *
188
     * @return string
189
     */
190
    private static function getMSB($value)
191
    {
192
        return mb_substr($value, 0, mb_strlen($value, '8bit') / 2, '8bit');
193
    }
194
195
    /**
196
     * @param string $value
197
     *
198
     * @return string
199
     */
200
    private static function getLSB($value)
201
    {
202
        return mb_substr($value, mb_strlen($value, '8bit') / 2, null, '8bit');
203
    }
204
205
    /**
206
     * @param string $kek
207
     *
208
     * @return \AESKW\EncryptorInterface
209
     */
210
    private static function getEncryptor($kek)
211
    {
212
        if (extension_loaded('openssl')) {
213
            return new OpenSSLEncryptor($kek);
214
        }
215
216
        throw new \RuntimeException('Please install OpenSSL extension.');
217
    }
218
}
219