JavaScript中的Caesar密码返回意外结果

Caesar cipher in JavaScript returning unexpected results

本文关键字:意外 结果 返回 密码 中的 Caesar JavaScript      更新时间:2023-09-26

我正在创建一个网页,在不使用jquery的情况下计算一个简单的Caesar密码。我找不到错误,也不知道如何将新字符串返回到文本区域。

HTML:

 <input type="button" value="Encrypt value = 1" onclick ="caesarEncipher(shift, text)"/>

javascript:

function caesarEncipher(shift, plaintext) {
  this.shift = shift;
  this.plaintext = plaintext;
  var ciphertext
  for (var i = 0; i < plaintext.length; i++) {
    // ASCII value - get numerical representation
    // 65 = 'A' 90 = 'Z'
    var encode = plaintext.charCodeAt(i);
    if (encode >= 65 && encode <= 90)
      // Uppercase
      ciphertext += String.fromCharCode((encode - 65 + shift) % 26 + 65);
      // 97 = 'a' 122 = 'z'
    else if (encode >= 97 && encode <= 122)
      // Lowercase
      ciphertext += String.fromCharCode((encode - 97 + shift) % 26 + 97);
    else
      ciphertext += input.charAt(i);
  }
  return document.getElementById = ciphertext; <-- Not sure about this
}

http://jsfiddle.net/y9rv6bux/

function encrypt(id, shiftId)
{
   var t = document.getElementById(id), out = '';
   var shift = parseInt(document.getElementById(shiftId).value);
   var txt = t.value, ranges = [[65,90],[97,122]];
    
   for(var i = 0; i < txt.length; i++)
   {
       var code = txt.charCodeAt(i);   
       for(var j = 0; j < ranges.length; j++)
       {
           if (code >= ranges[j][0] && code <= ranges[j][1])
           {
                code = ((code - ranges[j][0] + shift) %
                   (ranges[j][1] - ranges[j][0] + 1)) + ranges[j][0];
                break;
           }
       }
       out += String.fromCharCode(code);
   }
   t.value = out;
}
<textarea id='t'></textarea><br><input type='text' id='s' value='1'><br>
<input type='button' onclick='encrypt("t", "s")' value='Go'>