Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.50% covered (success)
97.50%
39 / 40
75.00% covered (warning)
75.00%
3 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
PasswordEncoder
97.50% covered (success)
97.50%
39 / 40
75.00% covered (warning)
75.00%
3 / 4
15
0.00% covered (danger)
0.00%
0 / 1
 hashPassword
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
5
 getAlgorithm
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getAlgorithmId
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 buildCombinedKey
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 int32
n/a
0 / 0
n/a
0 / 0
2
1<?php
2
3/**
4 * This file is part of PHPWord - A pure PHP library for reading and writing
5 * word processing documents.
6 *
7 * PHPWord is free software distributed under the terms of the GNU Lesser
8 * General Public License version 3 as published by the Free Software Foundation.
9 *
10 * For the full copyright and license information, please read the LICENSE
11 * file that was distributed with this source code. For the full list of
12 * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
13 *
14 * @see         https://github.com/PHPOffice/PHPWord
15 *
16 * @license     http://www.gnu.org/licenses/lgpl.txt LGPL version 3
17 */
18
19namespace PhpOffice\PhpWord\Shared\Microsoft;
20
21use PhpOffice\PhpWord\Exception\Exception;
22
23/**
24 * Password encoder for microsoft office applications.
25 */
26class PasswordEncoder
27{
28    const ALGORITHM_MD2 = 'MD2';
29    const ALGORITHM_MD4 = 'MD4';
30    const ALGORITHM_MD5 = 'MD5';
31    const ALGORITHM_SHA_1 = 'SHA-1';
32    const ALGORITHM_SHA_256 = 'SHA-256';
33    const ALGORITHM_SHA_384 = 'SHA-384';
34    const ALGORITHM_SHA_512 = 'SHA-512';
35    const ALGORITHM_RIPEMD = 'RIPEMD';
36    const ALGORITHM_RIPEMD_160 = 'RIPEMD-160';
37    const ALGORITHM_MAC = 'MAC';
38    const ALGORITHM_HMAC = 'HMAC';
39
40    private const ALL_ONE_BITS = (PHP_INT_SIZE > 4) ? 0xFFFFFFFF : -1;
41    private const HIGH_ORDER_BIT = (PHP_INT_SIZE > 4) ? 0x80000000 : PHP_INT_MIN;
42
43    /**
44     * Mapping between algorithm name and algorithm ID.
45     *
46     * @var array
47     *
48     * @see https://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.writeprotection.cryptographicalgorithmsid(v=office.14).aspx
49     */
50    private static $algorithmMapping = [
51        self::ALGORITHM_MD2 => [1, 'md2'],
52        self::ALGORITHM_MD4 => [2, 'md4'],
53        self::ALGORITHM_MD5 => [3, 'md5'],
54        self::ALGORITHM_SHA_1 => [4, 'sha1'],
55        self::ALGORITHM_MAC => [5, ''], // 'mac' -> not possible with hash()
56        self::ALGORITHM_RIPEMD => [6, 'ripemd'],
57        self::ALGORITHM_RIPEMD_160 => [7, 'ripemd160'],
58        self::ALGORITHM_HMAC => [9, ''], //'hmac' -> not possible with hash()
59        self::ALGORITHM_SHA_256 => [12, 'sha256'],
60        self::ALGORITHM_SHA_384 => [13, 'sha384'],
61        self::ALGORITHM_SHA_512 => [14, 'sha512'],
62    ];
63
64    private static $initialCodeArray = [
65        0xE1F0,
66        0x1D0F,
67        0xCC9C,
68        0x84C0,
69        0x110C,
70        0x0E10,
71        0xF1CE,
72        0x313E,
73        0x1872,
74        0xE139,
75        0xD40F,
76        0x84F9,
77        0x280C,
78        0xA96A,
79        0x4EC3,
80    ];
81
82    private static $encryptionMatrix = [
83        [0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09],
84        [0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF],
85        [0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0],
86        [0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40],
87        [0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5],
88        [0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A],
89        [0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9],
90        [0x47D3, 0x8FA6, 0x0F6D, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0],
91        [0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC],
92        [0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10],
93        [0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168],
94        [0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C],
95        [0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD],
96        [0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC],
97        [0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4],
98    ];
99
100    private static $passwordMaxLength = 15;
101
102    /**
103     * Create a hashed password that MS Word will be able to work with.
104     *
105     * @see https://blogs.msdn.microsoft.com/vsod/2010/04/05/how-to-set-the-editing-restrictions-in-word-using-open-xml-sdk-2-0/
106     *
107     * @param string $password
108     * @param string $algorithmName
109     * @param string $salt
110     * @param int $spinCount
111     *
112     * @return string
113     */
114    public static function hashPassword($password, $algorithmName = self::ALGORITHM_SHA_1, $salt = null, $spinCount = 10000)
115    {
116        $origEncoding = mb_internal_encoding();
117        mb_internal_encoding('UTF-8');
118
119        $password = mb_substr($password, 0, min(self::$passwordMaxLength, mb_strlen($password)));
120
121        //   Get the single-byte values by iterating through the Unicode characters of the truncated password.
122        //   For each character, if the low byte is not equal to 0, take it. Otherwise, take the high byte.
123        $passUtf8 = mb_convert_encoding($password, 'UCS-2LE', 'UTF-8');
124        if (!is_string($passUtf8)) {
125            throw new Exception('Failed to convert password to UCS-2LE');
126        }
127
128        $byteChars = [];
129        for ($i = 0; $i < mb_strlen($password); ++$i) {
130            $byteChars[$i] = ord(substr($passUtf8, $i * 2, 1));
131
132            if ($byteChars[$i] == 0) {
133                $byteChars[$i] = ord(substr($passUtf8, $i * 2 + 1, 1));
134            }
135        }
136
137        // build low-order word and hig-order word and combine them
138        $combinedKey = self::buildCombinedKey($byteChars);
139        // build reversed hexadecimal string
140        $hex = str_pad(strtoupper(dechex($combinedKey & self::ALL_ONE_BITS)), 8, '0', \STR_PAD_LEFT);
141        $reversedHex = $hex[6] . $hex[7] . $hex[4] . $hex[5] . $hex[2] . $hex[3] . $hex[0] . $hex[1];
142
143        $generatedKey = mb_convert_encoding($reversedHex, 'UCS-2LE', 'UTF-8');
144
145        // Implementation Notes List:
146        //   Word requires that the initial hash of the password with the salt not be considered in the count.
147        //   The initial hash of salt + key is not included in the iteration count.
148        $algorithm = self::getAlgorithm($algorithmName);
149        $generatedKey = hash($algorithm, $salt . $generatedKey, true);
150
151        for ($i = 0; $i < $spinCount; ++$i) {
152            $generatedKey = hash($algorithm, $generatedKey . pack('CCCC', $i, $i >> 8, $i >> 16, $i >> 24), true);
153        }
154        $generatedKey = base64_encode($generatedKey);
155
156        mb_internal_encoding($origEncoding);
157
158        return $generatedKey;
159    }
160
161    /**
162     * Get algorithm from self::$algorithmMapping.
163     *
164     * @param string $algorithmName
165     *
166     * @return string
167     */
168    private static function getAlgorithm($algorithmName)
169    {
170        $algorithm = self::$algorithmMapping[$algorithmName][1];
171        if ($algorithm == '') {
172            $algorithm = 'sha1';
173        }
174
175        return $algorithm;
176    }
177
178    /**
179     * Returns the algorithm ID.
180     *
181     * @param string $algorithmName
182     *
183     * @return int
184     */
185    public static function getAlgorithmId($algorithmName)
186    {
187        return self::$algorithmMapping[$algorithmName][0];
188    }
189
190    /**
191     * Build combined key from low-order word and high-order word.
192     *
193     * @param array $byteChars byte array representation of password
194     *
195     * @return int
196     */
197    private static function buildCombinedKey($byteChars)
198    {
199        $byteCharsLength = count($byteChars);
200        // Compute the high-order word
201        // Initialize from the initial code array (see above), depending on the passwords length.
202        $highOrderWord = self::$initialCodeArray[$byteCharsLength - 1];
203
204        // For each character in the password:
205        //   For every bit in the character, starting with the least significant and progressing to (but excluding)
206        //   the most significant, if the bit is set, XOR the key’s high-order word with the corresponding word from
207        //   the Encryption Matrix
208        for ($i = 0; $i < $byteCharsLength; ++$i) {
209            $tmp = self::$passwordMaxLength - $byteCharsLength + $i;
210            $matrixRow = self::$encryptionMatrix[$tmp];
211            for ($intBit = 0; $intBit < 7; ++$intBit) {
212                if (($byteChars[$i] & (0x0001 << $intBit)) != 0) {
213                    $highOrderWord = ($highOrderWord ^ $matrixRow[$intBit]);
214                }
215            }
216        }
217
218        // Compute low-order word
219        // Initialize with 0
220        $lowOrderWord = 0;
221        // For each character in the password, going backwards
222        for ($i = $byteCharsLength - 1; $i >= 0; --$i) {
223            // low-order word = (((low-order word SHR 14) AND 0x0001) OR (low-order word SHL 1) AND 0x7FFF)) XOR character
224            $lowOrderWord = (((($lowOrderWord >> 14) & 0x0001) | (($lowOrderWord << 1) & 0x7FFF)) ^ $byteChars[$i]);
225        }
226        // Lastly, low-order word = (((low-order word SHR 14) AND 0x0001) OR (low-order word SHL 1) AND 0x7FFF)) XOR strPassword length XOR 0xCE4B.
227        $lowOrderWord = (((($lowOrderWord >> 14) & 0x0001) | (($lowOrderWord << 1) & 0x7FFF)) ^ $byteCharsLength ^ 0xCE4B);
228
229        // Combine the Low and High Order Word
230        return self::int32(($highOrderWord << 16) + $lowOrderWord);
231    }
232
233    /**
234     * Simulate behaviour of (signed) int32.
235     *
236     * @codeCoverageIgnore
237     *
238     * @param int $value
239     *
240     * @return int
241     */
242    private static function int32($value)
243    {
244        $value = $value & self::ALL_ONE_BITS;
245
246        if ($value & self::HIGH_ORDER_BIT) {
247            $value = -((~$value & self::ALL_ONE_BITS) + 1);
248        }
249
250        return $value;
251    }
252}