"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var sha_hasher_1 = require("../../core/crypto/sha-hasher");
var crypto_js_1 = require("crypto-js");
var byte_buffer_1 = require("../../core/buffer/byte-buffer");
var format_1 = require("../../core/format");
var CryptoHelper = /** @class */ (function () {
    function CryptoHelper() {
    }
    CryptoHelper.sanitizeInput = function (input) {
        if (input instanceof Uint8Array) {
            return CryptoHelper.byteArrayToWordArray(input);
        }
        else {
            return input;
        }
    };
    CryptoHelper.byteArrayToWordArray = function (ba) {
        var wa = [], i;
        for (i = 0; i < ba.length; i++) {
            wa[(i / 4) | 0] |= ba[i] << (24 - 8 * i);
        }
        var result = crypto_js_1.lib.WordArray.create(wa);
        result.sigBytes = ba.length;
        return result;
    };
    CryptoHelper.getAlgoImpl = function (type) {
        switch (type) {
            case 'sha1':
                return crypto_js_1.algo.SHA1;
            case 'sha256':
                return crypto_js_1.algo.SHA256;
            default:
                throw new Error('Unknown algo type: ' + type);
        }
    };
    CryptoHelper.wordToByteArray = function (word, length) {
        var ba = [], i, xFF = 0xFF;
        if (length > 0)
            ba.push(word >>> 24);
        if (length > 1)
            ba.push((word >>> 16) & xFF);
        if (length > 2)
            ba.push((word >>> 8) & xFF);
        if (length > 3)
            ba.push(word & xFF);
        return Uint8Array.from(ba);
    };
    CryptoHelper.libWordArrayToByteArray = function (libWordArray, length) {
        if (!length) {
            length = libWordArray.sigBytes;
        }
        var wordArray = libWordArray.words;
        var result = [], bytes, i = 0;
        while (length > 0) {
            bytes = CryptoHelper.wordToByteArray(wordArray[i], Math.min(4, length));
            length -= bytes.length;
            result.push(bytes);
            i++;
        }
        return byte_buffer_1.ByteBuffer.merge.apply(byte_buffer_1.ByteBuffer, result).data;
    };
    CryptoHelper.wordArrayToByteArray = function (input) {
        return format_1.FormatHelper.hexStringToBuffer(input.toString(crypto_js_1.enc.Hex));
    };
    CryptoHelper.ALGO_TYPE = 'sha1';
    CryptoHelper.ITERATION_NUMBER = 4096;
    CryptoHelper.KEY_SIZE = 128;
    CryptoHelper.DEFAULT_SALT = 'n0 salt in 1oTi2e'; // TODO read from iotize ...
    CryptoHelper.passwordHasher = new sha_hasher_1.ShaHasher({
        type: CryptoHelper.ALGO_TYPE,
        iterations: CryptoHelper.ITERATION_NUMBER,
        salt: CryptoHelper.DEFAULT_SALT,
        keySize: CryptoHelper.KEY_SIZE
    });
    return CryptoHelper;
}());
exports.CryptoHelper = CryptoHelper;
