Неверная длина массива при использовании Cryptojs - PullRequest
0 голосов
/ 21 октября 2019

Я пытаюсь транспонировать код ac # в javascript, используя cryptojs, а в коде c # он использует TripleDESCryptoServiceProvider. Я могу получить все точно значения C # в моем коде JavaScript, за исключением части шифрования. Я получаю сообщение об ошибке «Недопустимая длина массива». Это полное сообщение об ошибке:

"RangeError: Invalid array length
    at WordArray.init.clamp (http://localhost:8100/auth-login-login-module.js:1392:27)
    at WordArray.init.concat (http://localhost:8100/auth-login-login-module.js:1357:19)
    at Object.pad (http://localhost:8100/auth-login-login-module.js:652:19)
    at Object._doFinalize (http://localhost:8100/auth-login-login-module.js:729:26)
    at Object.finalize (http://localhost:8100/auth-login-login-module.js:400:44)
    at Object.encrypt (http://localhost:8100/auth-login-login-module.js:912:41)
    at Object.encrypt (http://localhost:8100/auth-login-login-module.js:438:59)
    at AuthService.encryptText (http://localhost:8100/auth-login-login-module.js:6745:83)
    at LoginPage.ngOnInit (http://localhost:8100/auth-login-login-module.js:6939:26)
    at checkAndUpdateDirectiveInline (http://localhost:8100/vendor.js:65455:19)"

Пожалуйста, смотрите мой код на C # и JavaScript.

C #

public static string EncryptTxt(string key, string msg, CipherMode mode, Int16 KeyOffSet)
{
    SHA512CryptoServiceProvider sha = new SHA512CryptoServiceProvider();
    byte[] newKey = new byte[23];

    using (var tdes = new TripleDESCryptoServiceProvider())
    {
        byte[] Results;
        System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
        byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(key));
        TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

        byte[] keybyte = sha.ComputeHash(Encoding.UTF8.GetBytes(key));
        byte[] newKeyx = new byte[24];

        Array.Copy(keybyte, KeyOffSet, newKeyx, 0, newKeyx.Length);

        TDESAlgorithm.Key = newKeyx;
        TDESAlgorithm.Mode = mode;
        TDESAlgorithm.Padding = PaddingMode.PKCS7;
        byte[] DataToEncrypt = UTF8.GetBytes(msg);
        try
        {
            ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
            Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
        }
    finally
    {
        TDESAlgorithm.Clear();
        HashProvider.Clear();
    }
    return Convert.ToBase64String(Results);
}

javascript

encryptText = () => {
    debugger;
    const msg = 'xxx:juan:201910181809:12345678';
    let key = crypto.enc.Utf8.parse('xxx');
    key = crypto.MD5(key);
    key.words.push(key.words[0], key.words[1]);
    const iv = crypto.enc.Utf8.parse('xxx');

    // MD5CryptoServiceProvider
    const hashProvider = crypto.MD5(iv);
    const TDESKey = this.wordArrayToByteArray(hashProvider, 8);

    const keybyte = this.wordArrayToByteArray(crypto.SHA512(iv), 16);
    const newKeyx = new Uint8Array(24);

    const newkeybyte = keybyte.slice(10, 34);
    Object.assign(newKeyx, newkeybyte);

    const TDESAlgorithmKey = newkeybyte;

    const DataToEncrypt = this.wordArrayToByteArray(crypto.enc.Utf8.parse(msg), 40);
    const dteLength = DataToEncrypt.length;

    const encrypted = crypto.TripleDES.encrypt(DataToEncrypt, key, {
      keySize: dteLength,
      mode: crypto.mode.ECB,
      padding: crypto.pad.Pkcs7,
      algo: TDESAlgorithmKey
    });
    const result = this.wordArrayToByteArray(encrypted.ciphertext, dteLength);
    console.log(encrypted);
    return encrypted;
}

wordToByteArray(word: any, length: any) {
    const ba = [], xFF = 0xFF;
    if (length > 0) {
      // tslint:disable-next-line:no-bitwise
      ba.push(word >>> 24);
    }
    if (length > 1) {
      // tslint:disable-next-line:no-bitwise
      ba.push((word >>> 16) & xFF);
    }
    if (length > 2) {
      // tslint:disable-next-line:no-bitwise
      ba.push((word >>> 8) & xFF);
    }
    if (length > 3) {
      // tslint:disable-next-line:no-bitwise
      ba.push(word & xFF);
    }
    return ba;
}

Подскажите, пожалуйста, как это правильно сделать. Я действительно ценю это!

...