heyuntao
2023-06-12 6d5bda47851782efcf5743ef591a6e423b837c04
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
<?php
 
namespace PhpZip\IO\Filter\Cipher\WinZipAes;
 
use PhpZip\Exception\RuntimeException;
use PhpZip\Exception\ZipAuthenticationException;
use PhpZip\Util\CryptoUtil;
 
/**
 * WinZip Aes Encryption.
 *
 * @see https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT APPENDIX E
 * @see https://www.winzip.com/win/en/aes_info.html
 *
 * @author Ne-Lexa alexey@nelexa.ru
 * @license MIT
 *
 * @internal
 */
class WinZipAesContext
{
    /** @var int AES Block size */
    const BLOCK_SIZE = self::IV_SIZE;
 
    /** @var int Footer size */
    const FOOTER_SIZE = 10;
 
    /** @var int The iteration count for the derived keys of the cipher, KLAC and MAC. */
    const ITERATION_COUNT = 1000;
 
    /** @var int Password verifier size */
    const PASSWORD_VERIFIER_SIZE = 2;
 
    /** @var int IV size */
    const IV_SIZE = 16;
 
    /** @var string */
    private $iv;
 
    /** @var string */
    private $key;
 
    /** @var \HashContext|resource */
    private $hmacContext;
 
    /** @var string */
    private $passwordVerifier;
 
    /**
     * WinZipAesContext constructor.
     *
     * @param int    $encryptionStrengthBits
     * @param string $password
     * @param string $salt
     */
    public function __construct($encryptionStrengthBits, $password, $salt)
    {
        $encryptionStrengthBits = (int) $encryptionStrengthBits;
 
        if ($password === '') {
            throw new RuntimeException('$password is empty');
        }
 
        if (empty($salt)) {
            throw new RuntimeException('$salt is empty');
        }
 
        // WinZip 99-character limit https://sourceforge.net/p/p7zip/discussion/383044/thread/c859a2f0/
        $password = substr($password, 0, 99);
 
        $this->iv = str_repeat("\0", self::IV_SIZE);
        $keyStrengthBytes = (int) ($encryptionStrengthBits / 8);
        $hashLength = $keyStrengthBytes * 2 + self::PASSWORD_VERIFIER_SIZE * 8;
 
        $hash = hash_pbkdf2(
            'sha1',
            $password,
            $salt,
            self::ITERATION_COUNT,
            $hashLength,
            true
        );
 
        $this->key = substr($hash, 0, $keyStrengthBytes);
        $sha1Mac = substr($hash, $keyStrengthBytes, $keyStrengthBytes);
        $this->hmacContext = hash_init('sha1', \HASH_HMAC, $sha1Mac);
        $this->passwordVerifier = substr($hash, 2 * $keyStrengthBytes, self::PASSWORD_VERIFIER_SIZE);
    }
 
    /**
     * @return string
     */
    public function getPasswordVerifier()
    {
        return $this->passwordVerifier;
    }
 
    public function updateIv()
    {
        for ($ivCharIndex = 0; $ivCharIndex < self::IV_SIZE; $ivCharIndex++) {
            $ivByte = \ord($this->iv[$ivCharIndex]);
 
            if (++$ivByte === 256) {
                // overflow, set this one to 0, increment next
                $this->iv[$ivCharIndex] = "\0";
            } else {
                // no overflow, just write incremented number back and abort
                $this->iv[$ivCharIndex] = \chr($ivByte);
 
                break;
            }
        }
    }
 
    /**
     * @param string $data
     *
     * @return string
     */
    public function decryption($data)
    {
        hash_update($this->hmacContext, $data);
 
        return CryptoUtil::decryptAesCtr($data, $this->key, $this->iv);
    }
 
    /**
     * @param string $data
     *
     * @return string
     */
    public function encrypt($data)
    {
        $encryptionData = CryptoUtil::encryptAesCtr($data, $this->key, $this->iv);
        hash_update($this->hmacContext, $encryptionData);
 
        return $encryptionData;
    }
 
    /**
     * @param string $authCode
     *
     * @throws ZipAuthenticationException
     */
    public function checkAuthCode($authCode)
    {
        $hmac = $this->getHmac();
 
        // check authenticationCode
        if (strcmp($hmac, $authCode) !== 0) {
            throw new ZipAuthenticationException('Authenticated WinZip AES entry content has been tampered with.');
        }
    }
 
    /**
     * @return string
     */
    public function getHmac()
    {
        return substr(
            hash_final($this->hmacContext, true),
            0,
            self::FOOTER_SIZE
        );
    }
}