在Android上重建Angular加密

时间:2018-12-28 19:27:31

标签: java android angular encryption

我想从我的Android应用程序的角度库中重建对称加密,以解密消息。

这些是角度库(https://www.npmjs.com/package/angular-encryption-service)的功能:

EncryptionService.prototype.generateKey = function (passphrase) {
        return this.config.getSalt().then(function (salt) {
            var /** @type {?} */ passphraseBytes = new textEncodingUtf8.TextEncoder().encode(passphrase);
            var /** @type {?} */ importedKeyPromise = window.crypto.subtle.importKey('raw', passphraseBytes, { 'name': 'PBKDF2' }, false, ['deriveKey']);
            var /** @type {?} */ derivedKeyPromise = importedKeyPromise.then(function (key) {
                return window.crypto.subtle.deriveKey({
                    'name': 'PBKDF2',
                    'salt': typescriptBase64Arraybuffer.decode(salt),
                    // This should take around 0.5s to 1s
                    'iterations': 1000000,
                    'hash': 'SHA-256'
                }, key, { 'name': 'AES-CBC', 'length': 256 }, false, ['encrypt', 'decrypt']);
            });
            return derivedKeyPromise;
        });
    };
    /**
     * @param {?} text
     * @param {?} key
     * @return {?}
     */
    EncryptionService.prototype.encrypt = function (text, key) {
        var /** @type {?} */ iv = new Uint8Array(16);
        window.crypto.getRandomValues(iv);
        return (window.crypto.subtle.encrypt({ 'name': 'AES-CBC', 'iv': iv }, key, new textEncodingUtf8.TextEncoder().encode(text)).then(function (cipherBuffer) {
            // Need to implement base64 stuff here:
            return typescriptBase64Arraybuffer.encode(iv.buffer) + ':' + typescriptBase64Arraybuffer.encode(cipherBuffer);
        }));
    };
    /**
     * @param {?} cipherText
     * @param {?} key
     * @return {?}
     */
    EncryptionService.prototype.decrypt = function (cipherText, key) {
        try {
            var /** @type {?} */ pieces = cipherText.split(':');
            if (pieces.length !== 2) {
                return Promise.reject(new Error('encrypted text not formatted properly; missing ":"'));
            }
            var /** @type {?} */ iv = typescriptBase64Arraybuffer.decode(pieces[0]);
            var /** @type {?} */ buffer = typescriptBase64Arraybuffer.decode(pieces[1]);
            return (window.crypto.subtle.decrypt({ 'name': 'AES-CBC', 'iv': iv }, key, buffer).then(function (decryptedBuffer) {
                return new textEncodingUtf8.TextDecoder().decode(new Uint8Array(decryptedBuffer));
            }));
        }
        catch (e) {
            return Promise.reject(e);
        }
    };

我偶然发现了这个答案: PBKDF2 with SHA256 on android

但是在我的手机上无法执行1000000次迭代(应用程序会在一分钟后死亡)。

所以我有两个选择-切换角度库或找到在android中执行此操作的方法。哪种方法是最好的方法?

0 个答案:

没有答案