Vigenère шифр в JavaScript показывает или � символов - PullRequest
0 голосов
/ 24 февраля 2019

Я сделал шифр Vigenère в JavaScript.

, если я запускаю свой код в Firefox, я получаю следующий вывод:

�QZ4Sm0] m

в GoogleХром это выглядит так

QZ4Sm0] м

Как мне избежать этих символов или как сделать их видимыми?Что я делаю не так?

function vigenere(key, str, mode) {
  var output = [str.length];
  var result = 0;
  var output_str;

  for (var i = 0; i < str.length; i++) {

    if (mode == 1) {
      result = ((str.charCodeAt(i) + key.charCodeAt(i % key.length)) % 128);
      output[i] = String.fromCharCode(result);
    } else if (mode == 0) {
      if (str.charCodeAt(i) - key.charCodeAt(i % key.length) < 0) {
        result = (str.charCodeAt(i) - key.charCodeAt(i % key.length)) + 128;
      } else {
        result = (str.charCodeAt(i) - key.charCodeAt(i % key.length)) % 128;
      }
      output[i] = String.fromCharCode(result);
    }

  }
  output_str = output.join('');
  return output_str;
}

console.log(vigenere("Key", "Plaintext", 1))

1 Ответ

0 голосов
/ 24 февраля 2019

Ваш первый расчет дает Esc (# 27) во всех браузерах.Видимый в Firefox, но не видимый в Chrome

Этот дает Zpysrrobr: https://www.nayuki.io/page/vigenere-cipher-javascript

function vigenere(key, str, mode) {
  var output = [str.length];
  var result = 0;
  var output_str;

  for (var i = 0; i < str.length; i++) {
    if (mode == 1) {
      result = ((str.charCodeAt(i) + key.charCodeAt(i % key.length)) % 128);
      output[i] = String.fromCharCode(result);
      console.log( 
      str[i],key[i],result,output[i])

    } else if (mode == 0) {
      if (str.charCodeAt(i) - key.charCodeAt(i % key.length) < 0) {
        result = (str.charCodeAt(i) - key.charCodeAt(i % key.length)) + 128;
      } else {
        result = (str.charCodeAt(i) - key.charCodeAt(i % key.length)) % 128;
      }
      output[i] = String.fromCharCode(result);
    }

  }
  output_str = output.join('');
  return output_str;
}

console.log(vigenere("Key", "Plaintext", 1))
...