PasswordEncoder.php 9.1 KB

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