Skip to content

Commit d489595

Browse files
authored
Merge pull request #15 from troosan/add_password_hash
Utility to get an Office compatible hash of a password
2 parents 2cf7240 + b77fa41 commit d489595

File tree

6 files changed

+370
-2
lines changed

6 files changed

+370
-2
lines changed

CHANGELOG.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,10 @@
4242
## 0.2.6
4343

4444
### Changes
45-
- `\PhpOffice\Common\Text::utf8ToUnicode()` became `public`.
45+
- `\PhpOffice\Common\Text::utf8ToUnicode()` became `public`.
46+
47+
## 0.2.7
48+
49+
### Features
50+
- Added `\PhpOffice\Common\File::fileGetContents()` (with support of zip://)
51+
- Added Support for PHP 7.1

VERSION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
0.2.6
1+
0.2.7

src/Common/File.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,33 @@ public static function fileExists($pFilename)
5151
// Regular file_exists
5252
return file_exists($pFilename);
5353
}
54+
/**
55+
* Returns the content of a file
56+
*
57+
* @param string $pFilename Filename
58+
* @return string
59+
*/
60+
public static function fileGetContents($pFilename)
61+
{
62+
if (!self::fileExists($pFilename)) {
63+
return false;
64+
}
65+
if (strtolower(substr($pFilename, 0, 3)) == 'zip') {
66+
// Open ZIP file and verify if the file exists
67+
$zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6);
68+
$archiveFile = substr($pFilename, strpos($pFilename, '#') + 1);
69+
70+
$zip = new \ZipArchive();
71+
if ($zip->open($zipFile) === true) {
72+
$returnValue = $zip->getFromName($archiveFile);
73+
$zip->close();
74+
return $returnValue;
75+
}
76+
return false;
77+
}
78+
// Regular file contents
79+
return file_get_contents($pFilename);
80+
}
5481

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

tests/Common/Tests/FileTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,18 @@ public function testFileExists()
3737
$this->assertFalse(File::fileExists('zip://'.$pathResources.'files'.DIRECTORY_SEPARATOR.'404.pptx#404.xml'));
3838
}
3939

40+
/**
41+
*/
42+
public function testGetFileContents()
43+
{
44+
$pathResources = PHPOFFICE_COMMON_TESTS_BASE_DIR.DIRECTORY_SEPARATOR.'resources'.DIRECTORY_SEPARATOR;
45+
$this->assertInternalType('string', File::fileGetContents($pathResources.'images'.DIRECTORY_SEPARATOR.'PHPPowerPointLogo.png'));
46+
$this->assertFalse(File::fileGetContents($pathResources.'images'.DIRECTORY_SEPARATOR.'PHPPowerPointLogo_404.png'));
47+
$this->assertInternalType('string', File::fileGetContents('zip://'.$pathResources.'files'.DIRECTORY_SEPARATOR.'Sample_01_Simple.pptx#[Content_Types].xml'));
48+
$this->assertFalse(File::fileGetContents('zip://'.$pathResources.'files'.DIRECTORY_SEPARATOR.'Sample_01_Simple.pptx#404.xml'));
49+
$this->assertFalse(File::fileGetContents('zip://'.$pathResources.'files'.DIRECTORY_SEPARATOR.'404.pptx#404.xml'));
50+
}
51+
4052
/**
4153
*/
4254
public function testRealPath()
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
<?php
2+
/**
3+
* This file is part of PHPOffice Common
4+
*
5+
* PHPOffice Common is free software distributed under the terms of the GNU Lesser
6+
* General Public License version 3 as published by the Free Software Foundation.
7+
*
8+
* For the full copyright and license information, please read the LICENSE
9+
* file that was distributed with this source code. For the full list of
10+
* contributors, visit https://github.com/PHPOffice/Common/contributors.
11+
*
12+
* @link https://github.com/PHPOffice/Common
13+
* @copyright 2009-2016 PHPOffice Common contributors
14+
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
15+
*/
16+
17+
namespace PhpOffice\Common\Tests\Microsoft;
18+
19+
use PhpOffice\Common\Microsoft\PasswordEncoder;
20+
21+
/**
22+
* Test class for PhpOffice\Common\PasswordEncoder
23+
* @coversDefaultClass \PhpOffice\Common\PasswordEncoder
24+
*/
25+
class PasswordEncoderTest extends \PHPUnit_Framework_TestCase
26+
{
27+
/**
28+
* Test that a password can be hashed without specifying any additional parameters
29+
*/
30+
public function testEncodePassword()
31+
{
32+
//given
33+
$password = 'test';
34+
35+
//when
36+
$hashPassword = PasswordEncoder::hashPassword($password);
37+
38+
//then
39+
$this->assertEquals('M795/MAlmGU8RIsY9Q9uDLHC7bk=', $hashPassword);
40+
}
41+
42+
/**
43+
* Test that a password can be hashed with a custom salt
44+
*/
45+
public function testEncodePasswordWithSalt()
46+
{
47+
//given
48+
$password = 'test';
49+
$salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA==');
50+
51+
//when
52+
$hashPassword = PasswordEncoder::hashPassword($password, PasswordEncoder::ALGORITHM_SHA_1, $salt);
53+
54+
//then
55+
$this->assertEquals('QiDOcpia1YzSVJPiKPwWebl9p/0=', $hashPassword);
56+
}
57+
58+
/**
59+
* Test that the encoder falls back on SHA-1 if a non supported algorithm is given
60+
*/
61+
public function testDefaultsToSha1IfUnsupportedAlgorithm()
62+
{
63+
//given
64+
$password = 'test';
65+
$salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA==');
66+
67+
//when
68+
$hashPassword = PasswordEncoder::hashPassword($password, PasswordEncoder::ALGORITHM_MAC, $salt);
69+
70+
//then
71+
$this->assertEquals('QiDOcpia1YzSVJPiKPwWebl9p/0=', $hashPassword);
72+
}
73+
74+
/**
75+
* Test that the encoder falls back on SHA-1 if a non supported algorithm is given
76+
*/
77+
public function testEncodePasswordWithNullAsciiCodeInPassword()
78+
{
79+
//given
80+
$password = 'test' . chr(0);
81+
$salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA==');
82+
83+
//when
84+
$hashPassword = PasswordEncoder::hashPassword($password, PasswordEncoder::ALGORITHM_MAC, $salt, 1);
85+
86+
//then
87+
$this->assertEquals('rDV9sgdDsztoCQlvRCb1lF2wxNg=', $hashPassword);
88+
}
89+
}

0 commit comments

Comments
 (0)