all files / core/security/ encryptor.js

9.18% Statements 27/294
0% Branches 0/138
13.64% Functions 3/22
9.22% Lines 27/293
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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
define(["require", "exports", "./../pdf-primitives", "./../utils", "./encryptors/messageDigest5", "./encryptors/basic-encryption", "./encryptors/normal-cipher", "./encryptors/cipher-tranform", "./encryptors/advance-cipher"], function (require, exports, pdf_primitives_1, utils_1, messageDigest5_1, basic_encryption_1, normal_cipher_1, cipher_tranform_1, advance_cipher_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var _PdfEncryptor = (function () {
        function _PdfEncryptor(dictionary, id, password) {
            this._isUserPassword = true;
            this._hasUserPasswordOnly = false;
            this._encryptOnlyAttachment = false;
            this._encryptMetaData = true;
            this._defaultPasswordBytes = new Uint8Array([0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, 0x64, 0x00, 0x4e, 0x56, 0xff,
                0xfa, 0x01, 0x08, 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80, 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a]);
            if (password === null || typeof password === 'undefined') {
                password = '';
            }
            var filter = dictionary.get('Filter');
            if (!pdf_primitives_1._isName(filter, 'Standard')) {
                throw new utils_1.FormatError('unknown encryption method');
            }
            this._filterName = filter.name;
            this._dictionary = dictionary;
            var algorithm = dictionary.get('V');
            if (!Number.isInteger(algorithm) || (algorithm !== 1 && algorithm !== 2 && algorithm !== 4 && algorithm !== 5)) {
                throw new utils_1.FormatError('unsupported encryption algorithm');
            }
            this._algorithm = algorithm;
            var keyLength = dictionary.get('Length');
            if (!keyLength) {
                if (algorithm <= 3) {
                    keyLength = 40;
                }
                else {
                    var cfDictionary = dictionary.get('CF');
                    var streamCryptoName = dictionary.get('StmF');
                    if (cfDictionary && streamCryptoName) {
                        cfDictionary.suppressEncryption = true;
                        var handlerDictionary = cfDictionary.get(streamCryptoName.name);
                        keyLength = (handlerDictionary && handlerDictionary.get('Length')) || 128;
                        if (keyLength < 40) {
                            keyLength <<= 3;
                        }
                    }
                }
            }
            if (!Number.isInteger(keyLength) || keyLength < 40 || keyLength % 8 !== 0) {
                throw new utils_1.FormatError('invalid key length');
            }
            var ownerPassword = utils_1._stringToBytes(dictionary.get('O'), false, true).subarray(0, 32);
            var userPassword = utils_1._stringToBytes(dictionary.get('U'), false, true).subarray(0, 32);
            var flag = dictionary.get('P');
            var revision = dictionary.get('R');
            this._encryptMetaData = (algorithm === 4 || algorithm === 5) && dictionary.get('EncryptMetadata') !== false;
            var fileIdBytes = utils_1._stringToBytes(id, false, true);
            var passwordBytes;
            if (password) {
                if (revision === 6) {
                    password = encodeURIComponent(password);
                }
                passwordBytes = utils_1._stringToBytes(password, false, true);
            }
            var encryptionKey;
            if (algorithm !== 5) {
                encryptionKey = this._prepareKeyData(fileIdBytes, passwordBytes, ownerPassword, userPassword, flag, revision, keyLength, this._encryptMetaData);
                if (encryptionKey) {
                    this._isUserPassword = true;
                    if (password) {
                        var decodedPassword = this._decodeUserPassword(passwordBytes, ownerPassword, revision, keyLength);
                        var ownerEncryptionKey = this._prepareKeyData(fileIdBytes, decodedPassword, ownerPassword, userPassword, flag, revision, keyLength, this._encryptMetaData);
                        if (ownerEncryptionKey && utils_1._areArrayEqual(ownerEncryptionKey, encryptionKey)) {
                            this._hasUserPasswordOnly = true;
                        }
                    }
                }
            }
            else {
                var ownerValidationKey = utils_1._stringToBytes(dictionary.get('O'), false, true);
                var ownerValidationSalt = ownerValidationKey.subarray(32, 40);
                var ownerKeySalt = ownerValidationKey.subarray(40, 48);
                var userValidationKey = utils_1._stringToBytes(dictionary.get('U'), false, true);
                var uBytes = userValidationKey.subarray(0, 48);
                var userValidationSalt = userValidationKey.subarray(32, 40);
                var userKeySalt = userValidationKey.subarray(40, 48);
                var ownerEncryption = utils_1._stringToBytes(dictionary.get('OE'), false, true);
                var userEncryption = utils_1._stringToBytes(dictionary.get('UE'), false, true);
                var algorithm_1;
                if (revision === 6) {
                    algorithm_1 = new basic_encryption_1._AdvancedEncryption();
                }
                else {
                    algorithm_1 = new basic_encryption_1._BasicEncryption();
                }
                var p = void 0;
                if (passwordBytes) {
                    p = passwordBytes.subarray(0, Math.min(127, passwordBytes.length));
                }
                else {
                    p = new Uint8Array([]);
                }
                if (algorithm_1._checkUserPassword(p, userValidationSalt, userPassword)) {
                    encryptionKey = this._createEncryptionKey(true, p, ownerKeySalt, uBytes, userKeySalt, ownerEncryption, userEncryption, algorithm_1);
                    this._isUserPassword = true;
                    if (password.length && algorithm_1._checkOwnerPassword(p, ownerValidationSalt, uBytes, ownerPassword)) {
                        this._hasUserPasswordOnly = true;
                    }
                }
                else if (password.length && algorithm_1._checkOwnerPassword(p, ownerValidationSalt, uBytes, ownerPassword)) {
                    encryptionKey = this._createEncryptionKey(false, passwordBytes, ownerKeySalt, uBytes, userKeySalt, ownerEncryption, userEncryption, algorithm_1);
                    this._isUserPassword = false;
                }
            }
            if (!encryptionKey) {
                if (password) {
                    var decodedPassword = this._decodeUserPassword(passwordBytes, ownerPassword, revision, keyLength);
                    encryptionKey = this._prepareKeyData(fileIdBytes, decodedPassword, ownerPassword, userPassword, flag, revision, keyLength, this._encryptMetaData);
                    this._isUserPassword = false;
                }
                else {
                    throw new Error('Cannot open an encrypted document. The password is invalid.');
                }
            }
            if (algorithm >= 4) {
                var cipherDictionary = dictionary.get('CF');
                if (cipherDictionary) {
                    cipherDictionary.suppressEncryption = true;
                    if (cipherDictionary.has('StdCF')) {
                        var standardCryptFilter = cipherDictionary.get('StdCF');
                        if (standardCryptFilter && standardCryptFilter.has('AuthEvent')) {
                            var event_1 = standardCryptFilter.get('AuthEvent');
                            if (event_1 && event_1.name === 'EFOpen') {
                                this._encryptOnlyAttachment = true;
                            }
                        }
                    }
                }
                this._cipherDictionary = cipherDictionary;
                this._stream = dictionary.get('StmF') || pdf_primitives_1._PdfName.get('Identity');
                this._string = dictionary.get('StrF') || pdf_primitives_1._PdfName.get('Identity');
                this._eff = dictionary.get('EFF') || this._stream;
            }
            if (!encryptionKey && !this._encryptOnlyAttachment) {
                throw new Error('Cannot open an encrypted document. The password is invalid.');
            }
            this._encryptionKey = encryptionKey;
        }
        Object.defineProperty(_PdfEncryptor.prototype, "_md5", {
            get: function () {
                if (typeof this._messageDigest === 'undefined' || this._messageDigest === null) {
                    this._messageDigest = new messageDigest5_1._MD5();
                }
                return this._messageDigest;
            },
            enumerable: true,
            configurable: true
        });
        _PdfEncryptor.prototype._createEncryptionKey = function (isUserKey, password, ownerKeySalt, uBytes, userKeySalt, ownerEncryption, userEncryption, algorithm) {
            if (isUserKey) {
                return algorithm._getUserKey(password, userKeySalt, userEncryption);
            }
            else {
                return algorithm._getOwnerKey(password, ownerKeySalt, uBytes, ownerEncryption);
            }
        };
        _PdfEncryptor.prototype._prepareKeyData = function (id, password, ownerPassword, userPassword, flags, revision, keyLength, encryptMetaData) {
            var hashData = new Uint8Array(40 + ownerPassword.length + id.length);
            var i = 0;
            var j = 0;
            var n;
            if (password) {
                n = Math.min(32, password.length);
                for (; i < n; ++i) {
                    hashData[i] = password[i];
                }
            }
            while (i < 32) {
                hashData[i++] = this._defaultPasswordBytes[j++];
            }
            for (j = 0, n = ownerPassword.length; j < n; ++j) {
                hashData[i++] = ownerPassword[j];
            }
            hashData[i++] = flags & 0xff;
            hashData[i++] = (flags >> 8) & 0xff;
            hashData[i++] = (flags >> 16) & 0xff;
            hashData[i++] = (flags >>> 24) & 0xff;
            for (j = 0, n = id.length; j < n; ++j) {
                hashData[i++] = id[j];
            }
            if (revision >= 4 && !encryptMetaData) {
                hashData[i++] = 0xff;
                hashData[i++] = 0xff;
                hashData[i++] = 0xff;
                hashData[i++] = 0xff;
            }
            var hash = this._md5.hash(hashData, 0, i);
            var keyLengthInBytes = keyLength >> 3;
            if (revision >= 3) {
                for (j = 0; j < 50; ++j) {
                    hash = this._md5.hash(hash, 0, keyLengthInBytes);
                }
            }
            var encryptionKey = hash.subarray(0, keyLengthInBytes);
            var cipher;
            var checkData;
            if (revision >= 3) {
                for (i = 0; i < 32; ++i) {
                    hashData[i] = this._defaultPasswordBytes[i];
                }
                for (j = 0, n = id.length; j < n; ++j) {
                    hashData[i++] = id[j];
                }
                cipher = new normal_cipher_1._NormalCipherFour(encryptionKey);
                checkData = cipher._encryptBlock(this._md5.hash(hashData, 0, i));
                n = encryptionKey.length;
                var derivedKey = new Uint8Array(n);
                for (j = 1; j <= 19; ++j) {
                    for (var k = 0; k < n; ++k) {
                        derivedKey[k] = encryptionKey[k] ^ j;
                    }
                    cipher = new normal_cipher_1._NormalCipherFour(derivedKey);
                    checkData = cipher._encryptBlock(checkData);
                }
                for (j = 0, n = checkData.length; j < n; ++j) {
                    if (userPassword[j] !== checkData[j]) {
                        return null;
                    }
                }
            }
            else {
                cipher = new normal_cipher_1._NormalCipherFour(encryptionKey);
                checkData = cipher._encryptBlock(this._defaultPasswordBytes);
                for (j = 0, n = checkData.length; j < n; ++j) {
                    if (userPassword[j] !== checkData[j]) {
                        return null;
                    }
                }
            }
            return encryptionKey;
        };
        _PdfEncryptor.prototype._decodeUserPassword = function (password, ownerPassword, revision, keyLength) {
            var hashData = new Uint8Array(32);
            var i = 0;
            var j = 0;
            var n = Math.min(32, password.length);
            for (; i < n; ++i) {
                hashData[i] = password[i];
            }
            while (i < 32) {
                hashData[i++] = this._defaultPasswordBytes[j++];
            }
            var hash = this._md5.hash(hashData, 0, i);
            var keyLengthInBytes = keyLength >> 3;
            if (revision >= 3) {
                for (j = 0; j < 50; ++j) {
                    hash = this._md5.hash(hash, 0, hash.length);
                }
            }
            var cipher;
            var userPassword;
            if (revision >= 3) {
                userPassword = ownerPassword;
                var derivedKey = new Uint8Array(keyLengthInBytes);
                for (j = 19; j >= 0; j--) {
                    for (var k = 0; k < keyLengthInBytes; ++k) {
                        derivedKey[k] = hash[k] ^ j;
                    }
                    cipher = new normal_cipher_1._NormalCipherFour(derivedKey);
                    userPassword = cipher._encryptBlock(userPassword);
                }
            }
            else {
                cipher = new normal_cipher_1._NormalCipherFour(hash.subarray(0, keyLengthInBytes));
                userPassword = cipher._encryptBlock(ownerPassword);
            }
            return userPassword;
        };
        _PdfEncryptor.prototype._createCipherTransform = function (objectNumber, generationNumber) {
            if (this._algorithm === 4 || this._algorithm === 5) {
                var stringCipher = this._buildCipherConstructor(this._cipherDictionary, this._string, objectNumber, generationNumber, this._encryptionKey);
                var streamCipher = this._buildCipherConstructor(this._cipherDictionary, this._stream, objectNumber, generationNumber, this._encryptionKey);
                return new cipher_tranform_1._CipherTransform(stringCipher, streamCipher);
            }
            var key = this._buildObjectKey(objectNumber, generationNumber, this._encryptionKey, false);
            return new cipher_tranform_1._CipherTransform(new normal_cipher_1._NormalCipherFour(key), new normal_cipher_1._NormalCipherFour(key));
        };
        _PdfEncryptor.prototype._buildCipherConstructor = function (cipherDictionary, name, objectNumber, generationNumber, key) {
            var cryptFilter = cipherDictionary.get(name.name);
            var cfm;
            if (cryptFilter) {
                cfm = cryptFilter.get('CFM');
            }
            if (!cfm) {
                return new normal_cipher_1._NullCipher();
            }
            switch (cfm.name) {
                case 'None':
                    return new normal_cipher_1._NullCipher();
                case 'AESV2':
                    return new advance_cipher_1._AdvancedEncryption128Cipher(this._buildObjectKey(objectNumber, generationNumber, key, true));
                case 'AESV3':
                    return new advance_cipher_1._AdvancedEncryption256Cipher(key);
                case 'V2':
                    return new normal_cipher_1._NormalCipherFour(this._buildObjectKey(objectNumber, generationNumber, key, false));
            }
            throw new utils_1.FormatError('Unknown cryptography method');
        };
        _PdfEncryptor.prototype._buildObjectKey = function (objectNumber, generationNumber, encryptionKey, isAdvancedEncryption) {
            if (isAdvancedEncryption === void 0) { isAdvancedEncryption = false; }
            var key = new Uint8Array(encryptionKey.length + 9);
            var i;
            for (i = 0; i < encryptionKey.length; ++i) {
                key[i] = encryptionKey[i];
            }
            key[i++] = objectNumber & 0xff;
            key[i++] = (objectNumber >> 8) & 0xff;
            key[i++] = (objectNumber >> 16) & 0xff;
            key[i++] = generationNumber & 0xff;
            key[i++] = (generationNumber >> 8) & 0xff;
            if (isAdvancedEncryption) {
                key[i++] = 0x73;
                key[i++] = 0x41;
                key[i++] = 0x6c;
                key[i++] = 0x54;
            }
            var hash = this._md5.hash(key, 0, i);
            return hash.subarray(0, Math.min(encryptionKey.length + 5, 16));
        };
        return _PdfEncryptor;
    }());
    exports._PdfEncryptor = _PdfEncryptor;
    var _Word64 = (function () {
        function _Word64(high, low) {
            this.high = high | 0;
            this.low = low | 0;
        }
        _Word64.prototype.and = function (word) {
            this.high &= word.high;
            this.low &= word.low;
        };
        _Word64.prototype.or = function (word) {
            this.high |= word.high;
            this.low |= word.low;
        };
        _Word64.prototype.not = function () {
            this.high = ~this.high;
            this.low = ~this.low;
        };
        _Word64.prototype.xor = function (word) {
            this.high ^= word.high;
            this.low ^= word.low;
        };
        _Word64.prototype.shiftRight = function (places) {
            if (places >= 32) {
                this.low = (this.high >>> (places - 32)) | 0;
                this.high = 0;
            }
            else {
                this.low = (this.low >>> places) | (this.high << (32 - places));
                this.high = (this.high >>> places) | 0;
            }
        };
        _Word64.prototype.shiftLeft = function (places) {
            if (places >= 32) {
                this.high = this.low << (places - 32);
                this.low = 0;
            }
            else {
                this.high = (this.high << places) | (this.low >>> (32 - places));
                this.low <<= places;
            }
        };
        _Word64.prototype.rotateRight = function (places) {
            var low;
            var high;
            if (places & 32) {
                high = this.low;
                low = this.high;
            }
            else {
                low = this.low;
                high = this.high;
            }
            places &= 31;
            this.low = (low >>> places) | (high << (32 - places));
            this.high = (high >>> places) | (low << (32 - places));
        };
        _Word64.prototype.add = function (word) {
            var lowAdd = (this.low >>> 0) + (word.low >>> 0);
            var highAdd = (this.high >>> 0) + (word.high >>> 0);
            if (lowAdd > 0xffffffff) {
                highAdd += 1;
            }
            this.low = lowAdd | 0;
            this.high = highAdd | 0;
        };
        _Word64.prototype.copyTo = function (bytes, offset) {
            bytes[offset] = (this.high >>> 24) & 0xff;
            bytes[offset + 1] = (this.high >> 16) & 0xff;
            bytes[offset + 2] = (this.high >> 8) & 0xff;
            bytes[offset + 3] = this.high & 0xff;
            bytes[offset + 4] = (this.low >>> 24) & 0xff;
            bytes[offset + 5] = (this.low >> 16) & 0xff;
            bytes[offset + 6] = (this.low >> 8) & 0xff;
            bytes[offset + 7] = this.low & 0xff;
        };
        _Word64.prototype.assign = function (word) {
            this.high = word.high;
            this.low = word.low;
        };
        return _Word64;
    }());
    exports._Word64 = _Word64;
});