Skip to content

Commit

Permalink
align with pull request submitted in PHPOffice/Commom
Browse files Browse the repository at this point in the history
  • Loading branch information
troosan committed Dec 13, 2017
1 parent 2e56251 commit 9e02941
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 41 deletions.
23 changes: 12 additions & 11 deletions src/PhpWord/Metadata/Protection.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
namespace PhpOffice\PhpWord\Metadata;

use PhpOffice\PhpWord\SimpleType\DocProtect;
use PhpOffice\PhpWord\Shared\Microsoft\PasswordEncoder;

/**
* Document protection class
Expand Down Expand Up @@ -50,11 +51,11 @@ class Protection
private $spinCount = 100000;

/**
* Cryptographic Hashing Algorithm (see to \PhpOffice\PhpWord\Writer\Word2007\Part\Settings::$algorithmMapping)
* Cryptographic Hashing Algorithm (see constants defined in \PhpOffice\PhpWord\Shared\Microsoft\PasswordEncoder)
*
* @var int
* @var string
*/
private $mswordAlgorithmSid = 4;
private $algorithm = PasswordEncoder::ALGORITHM_SHA_1;

/**
* Salt for Password Verifier
Expand Down Expand Up @@ -146,24 +147,24 @@ public function setSpinCount($spinCount)
}

/**
* Get algorithm-sid
* Get algorithm
*
* @return int
* @return string
*/
public function getMswordAlgorithmSid()
public function getAlgorithm()
{
return $this->mswordAlgorithmSid;
return $this->algorithm;
}

/**
* Set algorithm-sid (see \PhpOffice\PhpWord\Writer\Word2007\Part\Settings::$algorithmMapping)
* Set algorithm
*
* @param $mswordAlgorithmSid
* @param $algorithm
* @return self
*/
public function setMswordAlgorithmSid($mswordAlgorithmSid)
public function setMswordAlgorithmSid($algorithm)
{
$this->mswordAlgorithmSid = $mswordAlgorithmSid;
$this->algorithm = $algorithm;

return $this;
}
Expand Down
68 changes: 42 additions & 26 deletions src/PhpWord/Shared/Microsoft/PasswordEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,36 @@
*/
class PasswordEncoder
{
const ALGORITHM_MD2 = 'MD2';
const ALGORITHM_MD4 = 'MD4';
const ALGORITHM_MD5 = 'MD5';
const ALGORITHM_SHA_1 = 'SHA-1';
const ALGORITHM_SHA_256 = 'SHA-256';
const ALGORITHM_SHA_384 = 'SHA-384';
const ALGORITHM_SHA_512 = 'SHA-512';
const ALGORITHM_RIPEMD = 'RIPEMD';
const ALGORITHM_RIPEMD_160 = 'RIPEMD-160';
const ALGORITHM_MAC = 'MAC';
const ALGORITHM_HMAC= 'HMAC';

/**
* Mapping between algorithm name and algorithm ID
*
* @var array
* @see https://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.writeprotection.cryptographicalgorithmsid(v=office.14).aspx
*/
private static $algorithmMapping = array(
1 => 'md2',
2 => 'md4',
3 => 'md5',
4 => 'sha1',
5 => '', // 'mac' -> not possible with hash()
6 => 'ripemd',
7 => 'ripemd160',
8 => '',
9 => '', //'hmac' -> not possible with hash()
10 => '',
11 => '',
12 => 'sha256',
13 => 'sha384',
14 => 'sha512',
self::ALGORITHM_MD2 => array(1, 'md2'),
self::ALGORITHM_MD4 => array(2, 'md4'),
self::ALGORITHM_MD5 => array(3, 'md5'),
self::ALGORITHM_SHA_1 => array(4, 'sha1'),
self::ALGORITHM_MAC => array(5, ''), // 'mac' -> not possible with hash()
self::ALGORITHM_RIPEMD => array(6, 'ripemd'),
self::ALGORITHM_RIPEMD_160 => array(7, 'ripemd160'),
self::ALGORITHM_HMAC => array(9, ''), //'hmac' -> not possible with hash()
self::ALGORITHM_SHA_256 => array(12, 'sha256'),
self::ALGORITHM_SHA_384 => array(13, 'sha384'),
self::ALGORITHM_SHA_512 => array(14, 'sha512'),
);

private static $initialCodeArray = array(
Expand Down Expand Up @@ -82,12 +97,12 @@ class PasswordEncoder
* @see https://blogs.msdn.microsoft.com/vsod/2010/04/05/how-to-set-the-editing-restrictions-in-word-using-open-xml-sdk-2-0/
*
* @param string $password
* @param number $algorithmSid
* @param string $algorithmName
* @param string $salt
* @param number $spinCount
* @param integer $spinCount
* @return string
*/
public static function hashPassword($password, $algorithmSid = 4, $salt = null, $spinCount = 10000)
public static function hashPassword($password, $algorithmName = PasswordEncoder::ALGORITHM_SHA_1, $salt = null, $spinCount = 10000)
{
$origEncoding = mb_internal_encoding();
mb_internal_encoding('UTF-8');
Expand Down Expand Up @@ -118,7 +133,7 @@ public static function hashPassword($password, $algorithmSid = 4, $salt = null,
// Implementation Notes List:
// Word requires that the initial hash of the password with the salt not be considered in the count.
// The initial hash of salt + key is not included in the iteration count.
$algorithm = self::getAlgorithm($algorithmSid);
$algorithm = self::getAlgorithm($algorithmName);
$generatedKey = hash($algorithm, $salt . $generatedKey, true);

for ($i = 0; $i < $spinCount; $i++) {
Expand All @@ -134,12 +149,12 @@ public static function hashPassword($password, $algorithmSid = 4, $salt = null,
/**
* Get algorithm from self::$algorithmMapping
*
* @param int $sid
* @param string $algorithmName
* @return string
*/
private static function getAlgorithm($sid)
private static function getAlgorithm($algorithmName)
{
$algorithm = self::$algorithmMapping[$sid];
$algorithm = self::$algorithmMapping[$algorithmName][1];
if ($algorithm == '') {
$algorithm = 'sha1';
}
Expand All @@ -155,16 +170,17 @@ private static function getAlgorithm($sid)
*/
private static function buildCombinedKey($byteChars)
{
$byteCharsLength = count($byteChars);
// Compute the high-order word
// Initialize from the initial code array (see above), depending on the passwords length.
$highOrderWord = self::$initialCodeArray[count($byteChars) - 1];
$highOrderWord = self::$initialCodeArray[$byteCharsLength - 1];

// For each character in the password:
// For every bit in the character, starting with the least significant and progressing to (but excluding)
// the most significant, if the bit is set, XOR the key’s high-order word with the corresponding word from
// the Encryption Matrix
for ($i = 0; $i < count($byteChars); $i++) {
$tmp = self::$passwordMaxLength - count($byteChars) + $i;
for ($i = 0; $i < $byteCharsLength; $i++) {
$tmp = self::$passwordMaxLength - $byteCharsLength + $i;
$matrixRow = self::$encryptionMatrix[$tmp];
for ($intBit = 0; $intBit < 7; $intBit++) {
if (($byteChars[$i] & (0x0001 << $intBit)) != 0) {
Expand All @@ -177,12 +193,12 @@ private static function buildCombinedKey($byteChars)
// Initialize with 0
$lowOrderWord = 0;
// For each character in the password, going backwards
for ($i = count($byteChars) - 1; $i >= 0; $i--) {
for ($i = $byteCharsLength - 1; $i >= 0; $i--) {
// low-order word = (((low-order word SHR 14) AND 0x0001) OR (low-order word SHL 1) AND 0x7FFF)) XOR character
$lowOrderWord = (((($lowOrderWord >> 14) & 0x0001) | (($lowOrderWord << 1) & 0x7FFF)) ^ $byteChars[$i]);
}
// Lastly, low-order word = (((low-order word SHR 14) AND 0x0001) OR (low-order word SHL 1) AND 0x7FFF)) XOR strPassword length XOR 0xCE4B.
$lowOrderWord = (((($lowOrderWord >> 14) & 0x0001) | (($lowOrderWord << 1) & 0x7FFF)) ^ count($byteChars) ^ 0xCE4B);
$lowOrderWord = (((($lowOrderWord >> 14) & 0x0001) | (($lowOrderWord << 1) & 0x7FFF)) ^ $byteCharsLength ^ 0xCE4B);

// Combine the Low and High Order Word
return self::int32(($highOrderWord << 16) + $lowOrderWord);
Expand Down
2 changes: 1 addition & 1 deletion src/PhpWord/Writer/Word2007/Part/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ private function setDocumentProtection($documentProtection)
if ($documentProtection->getSalt() == null) {
$documentProtection->setSalt(openssl_random_pseudo_bytes(16));
}
$passwordHash = PasswordEncoder::hashPassword($documentProtection->getPassword(), $documentProtection->getMswordAlgorithmSid(), $documentProtection->getSalt(), $documentProtection->getSpinCount());
$passwordHash = PasswordEncoder::hashPassword($documentProtection->getPassword(), $documentProtection->getAlgorithm(), $documentProtection->getSalt(), $documentProtection->getSpinCount());
$this->settings['w:documentProtection'] = array(
'@attributes' => array(
'w:enforcement' => 1,
Expand Down
6 changes: 3 additions & 3 deletions tests/PhpWord/Shared/Microsoft/PasswordEncoderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public function testEncodePasswordWithSalt()
$salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA==');

//when
$hashPassword = PasswordEncoder::hashPassword($password, 4, $salt);
$hashPassword = PasswordEncoder::hashPassword($password, PasswordEncoder::ALGORITHM_SHA_1, $salt);

//then
TestCase::assertEquals('QiDOcpia1YzSVJPiKPwWebl9p/0=', $hashPassword);
Expand All @@ -67,7 +67,7 @@ public function testDafaultsToSha1IfUnsupportedAlgorithm()
$salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA==');

//when
$hashPassword = PasswordEncoder::hashPassword($password, 5, $salt);
$hashPassword = PasswordEncoder::hashPassword($password, PasswordEncoder::ALGORITHM_MAC, $salt);

//then
TestCase::assertEquals('QiDOcpia1YzSVJPiKPwWebl9p/0=', $hashPassword);
Expand All @@ -83,7 +83,7 @@ public function testEncodePasswordWithNullAsciiCodeInPassword()
$salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA==');

//when
$hashPassword = PasswordEncoder::hashPassword($password, 5, $salt, 1);
$hashPassword = PasswordEncoder::hashPassword($password, PasswordEncoder::ALGORITHM_MAC, $salt, 1);

//then
TestCase::assertEquals('rDV9sgdDsztoCQlvRCb1lF2wxNg=', $hashPassword);
Expand Down

0 comments on commit 9e02941

Please sign in to comment.