Search code examples
javascriptencryptioncryptographyvigenere

Vigenère cipher in JavaScript showing or � characters


I made the Vigenère cipher in JavaScript.

if I run my Code in Firefox I'm getting the follow output:

�QZ4Sm0]m

in Google Chrome it looks like this

QZ4Sm0]m

How can I avoid those symbols or how can I make them visible? What am I doing wrong?

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


Solution

  • Your first calculation gives an esc (#27) in all browsers. Visible in Firefox, but not visible in Chrome

    This one gives 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))