align with pull request submitted in PHPOffice/Commom

This commit is contained in:
troosan 2017-12-13 23:17:01 +01:00
parent 2e562512f4
commit 9e029415cc
4 changed files with 58 additions and 41 deletions

View File

@ -18,6 +18,7 @@
namespace PhpOffice\PhpWord\Metadata; namespace PhpOffice\PhpWord\Metadata;
use PhpOffice\PhpWord\SimpleType\DocProtect; use PhpOffice\PhpWord\SimpleType\DocProtect;
use PhpOffice\PhpWord\Shared\Microsoft\PasswordEncoder;
/** /**
* Document protection class * Document protection class
@ -50,11 +51,11 @@ class Protection
private $spinCount = 100000; 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 * Salt for Password Verifier
@ -146,24 +147,24 @@ class Protection
} }
/** /**
* 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 * @return self
*/ */
public function setMswordAlgorithmSid($mswordAlgorithmSid) public function setMswordAlgorithmSid($algorithm)
{ {
$this->mswordAlgorithmSid = $mswordAlgorithmSid; $this->algorithm = $algorithm;
return $this; return $this;
} }

View File

@ -22,21 +22,36 @@ namespace PhpOffice\PhpWord\Shared\Microsoft;
*/ */
class PasswordEncoder 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( private static $algorithmMapping = array(
1 => 'md2', self::ALGORITHM_MD2 => array(1, 'md2'),
2 => 'md4', self::ALGORITHM_MD4 => array(2, 'md4'),
3 => 'md5', self::ALGORITHM_MD5 => array(3, 'md5'),
4 => 'sha1', self::ALGORITHM_SHA_1 => array(4, 'sha1'),
5 => '', // 'mac' -> not possible with hash() self::ALGORITHM_MAC => array(5, ''), // 'mac' -> not possible with hash()
6 => 'ripemd', self::ALGORITHM_RIPEMD => array(6, 'ripemd'),
7 => 'ripemd160', self::ALGORITHM_RIPEMD_160 => array(7, 'ripemd160'),
8 => '', self::ALGORITHM_HMAC => array(9, ''), //'hmac' -> not possible with hash()
9 => '', //'hmac' -> not possible with hash() self::ALGORITHM_SHA_256 => array(12, 'sha256'),
10 => '', self::ALGORITHM_SHA_384 => array(13, 'sha384'),
11 => '', self::ALGORITHM_SHA_512 => array(14, 'sha512'),
12 => 'sha256',
13 => 'sha384',
14 => 'sha512',
); );
private static $initialCodeArray = array( private static $initialCodeArray = array(
@ -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/ * @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 string $password
* @param number $algorithmSid * @param string $algorithmName
* @param string $salt * @param string $salt
* @param number $spinCount * @param integer $spinCount
* @return string * @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(); $origEncoding = mb_internal_encoding();
mb_internal_encoding('UTF-8'); mb_internal_encoding('UTF-8');
@ -118,7 +133,7 @@ class PasswordEncoder
// Implementation Notes List: // Implementation Notes List:
// Word requires that the initial hash of the password with the salt not be considered in the count. // 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. // 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); $generatedKey = hash($algorithm, $salt . $generatedKey, true);
for ($i = 0; $i < $spinCount; $i++) { for ($i = 0; $i < $spinCount; $i++) {
@ -134,12 +149,12 @@ class PasswordEncoder
/** /**
* Get algorithm from self::$algorithmMapping * Get algorithm from self::$algorithmMapping
* *
* @param int $sid * @param string $algorithmName
* @return string * @return string
*/ */
private static function getAlgorithm($sid) private static function getAlgorithm($algorithmName)
{ {
$algorithm = self::$algorithmMapping[$sid]; $algorithm = self::$algorithmMapping[$algorithmName][1];
if ($algorithm == '') { if ($algorithm == '') {
$algorithm = 'sha1'; $algorithm = 'sha1';
} }
@ -155,16 +170,17 @@ class PasswordEncoder
*/ */
private static function buildCombinedKey($byteChars) private static function buildCombinedKey($byteChars)
{ {
$byteCharsLength = count($byteChars);
// Compute the high-order word // Compute the high-order word
// Initialize from the initial code array (see above), depending on the passwords length. // 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 each character in the password:
// For every bit in the character, starting with the least significant and progressing to (but excluding) // 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 keys high-order word with the corresponding word from // the most significant, if the bit is set, XOR the keys high-order word with the corresponding word from
// the Encryption Matrix // the Encryption Matrix
for ($i = 0; $i < count($byteChars); $i++) { for ($i = 0; $i < $byteCharsLength; $i++) {
$tmp = self::$passwordMaxLength - count($byteChars) + $i; $tmp = self::$passwordMaxLength - $byteCharsLength + $i;
$matrixRow = self::$encryptionMatrix[$tmp]; $matrixRow = self::$encryptionMatrix[$tmp];
for ($intBit = 0; $intBit < 7; $intBit++) { for ($intBit = 0; $intBit < 7; $intBit++) {
if (($byteChars[$i] & (0x0001 << $intBit)) != 0) { if (($byteChars[$i] & (0x0001 << $intBit)) != 0) {
@ -177,12 +193,12 @@ class PasswordEncoder
// Initialize with 0 // Initialize with 0
$lowOrderWord = 0; $lowOrderWord = 0;
// For each character in the password, going backwards // 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 // 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]); $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. // 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 // Combine the Low and High Order Word
return self::int32(($highOrderWord << 16) + $lowOrderWord); return self::int32(($highOrderWord << 16) + $lowOrderWord);

View File

@ -193,7 +193,7 @@ class Settings extends AbstractPart
if ($documentProtection->getSalt() == null) { if ($documentProtection->getSalt() == null) {
$documentProtection->setSalt(openssl_random_pseudo_bytes(16)); $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( $this->settings['w:documentProtection'] = array(
'@attributes' => array( '@attributes' => array(
'w:enforcement' => 1, 'w:enforcement' => 1,

View File

@ -51,7 +51,7 @@ class PasswordEncoderTest extends \PHPUnit\Framework\TestCase
$salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA=='); $salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA==');
//when //when
$hashPassword = PasswordEncoder::hashPassword($password, 4, $salt); $hashPassword = PasswordEncoder::hashPassword($password, PasswordEncoder::ALGORITHM_SHA_1, $salt);
//then //then
TestCase::assertEquals('QiDOcpia1YzSVJPiKPwWebl9p/0=', $hashPassword); TestCase::assertEquals('QiDOcpia1YzSVJPiKPwWebl9p/0=', $hashPassword);
@ -67,7 +67,7 @@ class PasswordEncoderTest extends \PHPUnit\Framework\TestCase
$salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA=='); $salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA==');
//when //when
$hashPassword = PasswordEncoder::hashPassword($password, 5, $salt); $hashPassword = PasswordEncoder::hashPassword($password, PasswordEncoder::ALGORITHM_MAC, $salt);
//then //then
TestCase::assertEquals('QiDOcpia1YzSVJPiKPwWebl9p/0=', $hashPassword); TestCase::assertEquals('QiDOcpia1YzSVJPiKPwWebl9p/0=', $hashPassword);
@ -83,7 +83,7 @@ class PasswordEncoderTest extends \PHPUnit\Framework\TestCase
$salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA=='); $salt = base64_decode('uq81pJRRGFIY5U+E9gt8tA==');
//when //when
$hashPassword = PasswordEncoder::hashPassword($password, 5, $salt, 1); $hashPassword = PasswordEncoder::hashPassword($password, PasswordEncoder::ALGORITHM_MAC, $salt, 1);
//then //then
TestCase::assertEquals('rDV9sgdDsztoCQlvRCb1lF2wxNg=', $hashPassword); TestCase::assertEquals('rDV9sgdDsztoCQlvRCb1lF2wxNg=', $hashPassword);