Шифрование с помощью Crypto JS в JavaScript дает мне отличные результаты от шифрования Java - PullRequest
0 голосов
/ 25 марта 2020

Я пытаюсь повторить с помощью Crypto JS шифрование, выполненное в Java с использованием другой библиотеки. Результат шифрования в Java равен [111,60,-98,107,-60,5,-17,91,-52,60,-105,64,-88,31,97,-102,118,-39,-28,3,70,-12,21,-69,70,-22,-12,-91,102,-21,-88,5,82,-66,-122,34,14,-115,7,82,-55,38,-90,74,-4,62,104,104,61,-78,57,59,-51,31,84,-115,-45,-98,-87,-11,53,98,45,2,-52], и я знаю, что это правильная полезная нагрузка. Итак, я реплицирую то же шифрование с теми же значениями, но я не получаю тот же массив байтов. Шаги:

  • Я преобразую строковое сообщение в byteArray, используя utf-8
  • Если byteArray не делится на 16, я добавляю нули, пока не прибуду к кратному 16 (это запрос)
  • Я шифрую байтовый массив, используя AES \ ECB \ NoPadding
  • Я преобразую результат 'encrypted' в byteArray

Здесь мой код:

encryption() {
    let message = '{"cks":223,"com":31,token":1585040712404}'
    let shared1 = "24c27d724b86353c23390799bfc917f2679c96902f8280bd9926ce4a1ee0c23b"
    const shared = CryptoJS.SHA256(shared1);
    let byteMessage = new Buffer(message, 'utf8')
    if (byteMessage.length % 16 !== 0) {
        let emptyByte = new Buffer((Math.trunc(byteMessage.length / 16) + 1) * 16);
        for (let j = 0; j < byteMessage.length; j++) {
            emptyByte[j] = byteMessage[j] ? byteMessage[j] : 0
        }
        byteMessage = emptyByte;
    }
    let encrypted = CryptoJS.AES.encrypt(byteMessage.toString(), shared,
        {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.NoPadding,
        });
    return this.wordArrayToByteArray(encrypted, 1);
}

wordArrayToByteArray(wordArray, length): Promise<any> {
    if (wordArray.hasOwnProperty("ciphertext") && wordArray.ciphertext.hasOwnProperty('sigBytes') && wordArray.ciphertext.hasOwnProperty('words')) {
        length = wordArray.ciphertext.sigBytes;
        wordArray = wordArray.ciphertext.words;
    }

    var result = [],
        bytes,
        i = 0;
    while (length > 0) {
        bytes = this.wordToByteArray(wordArray[i], Math.min(4, length));
        length -= bytes.length;
        result.push(bytes);
        i++;
    }
    return [].concat.apply([], result);
}


wordToByteArray(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 ba;
}

Результатом этой функции является [252, 55, 222, 129, 178, 237, 141, 108, 104, 113, 232, 152, 168, 114, 250, 185, 198, 211, 105, 25, 4, 141, 152, 14, 177, 251, 109, 160, 70, 119, 253, 204, 126, 211, 250, 96, 114, 151, 196, 180, 238, 94, 11, 68, 44, 166, 158, 47], которая полностью отличается от правильной.

Что я делаю не так? Спасибо

...