【问题标题】:Vigenère cipher in JavaScript showing or � charactersJavaScript 中的 Vigenère 密码显示或 � 字符
【发布时间】:2019-02-24 17:06:30
【问题描述】:

我用 JavaScript 制作了 Vigenère 密码。

如果我在 Firefox 中运行我的代码,我会得到以下输出:

�QZ4Sm0]m

在谷歌浏览器中看起来像这样

QZ4Sm0]m

如何避免这些符号或如何使它们可见? 我做错了什么?

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))

【问题讨论】:

  • 我给你做了一个 sn-p 并删除了你多余的)
  • 您在 Chrome 中也是如此。它只是在控制台中不可见
  • 如果您更改为output[i] = String.fromCharCode(result); console.log(JSON.stringify(output[i])),您将看到u\001b 作为第一个字符

标签: javascript encryption cryptography vigenere


【解决方案1】:

您的第一个计算在所有浏览器中都会给出 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))

【讨论】:

    【解决方案2】:

    尝试使用这段代码。它更简单且可读性强

    function vigenereFunc(plainText, key) {
       const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
       let cipherText = "";
       for (let i = 0, j = 0; i < plainText.length; i++) {
         if (!letters.includes(plainText[i])) {
           cipherText += plainText[i];
              continue;
         }
         cipherText += letters[(letters.indexOf(plainText[i]) + letters.indexOf(key[j])) % 26];
    
         if(j === key.length - 1) j = -1;
         return cipherText;
      }
    

    【讨论】:

      最近更新 更多