凯撒密码字符串长度问题

Caesar Cipher string length issue

本文关键字:问题 字符串 密码 凯撒      更新时间:2023-09-26

我正在尝试构建一个加密程序&基于凯撒密码的uni任务解密器。

我已经做了一个不错的开始,但每当我试图返回字符串长度以便为每个字符循环加密器时,它都会将其返回为null。

这是我的代码

编辑:我已经包括了完成的代码,工作

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Encryption version 0</title> 
<style>
body { 
margin-left: 15%;
margin-right: 15%;
}
#description {
font-style: italic;
font-size: 18px;
}
#instruction {
font-weight: bold;
color: red;
font-size: 18px;
}
</style>
</head>
<body>
<h1>Welcome to the encryptor</h1>
<p id="description">Please type below the text you wish to encript</p>
  <input name="txt" type="text" maxlength="512" id="txt" />
    <p>And pick an encryption key</p>
      <input name="key1" type="text" maxlength="512" id="key1" />
    <button onclick= "enrypt()">Submit</button>
    <p id="word"></p>

<h1>Welcome to the decrypter</h1>
<p id="description">Please type below the text you wish to decrypt</p>
  <input name="txt2" type="text" maxlength="512" id="txt2" />
    <p>And your encryption key</p>
      <input name="key" type="text" maxlength="512" id="key" />
    <button onclick= "decrypt()">Submit</button>
    <p id="word2"></p>
  <script type="text/javascript">
      //Script 1
      function enrypt() {
  var text, additon, encrypted, numb;
  text, encrypted = "";
  text     = document.getElementById('txt').value;
  additon = document.getElementById('key1').value;
  for (i = 0; i < text.length; i++) {
    numb = text.charCodeAt(i);
    key = parseFloat(additon) + parseFloat(numb);
    encrypted += String.fromCharCode(key)
  }
    document.getElementById("word").innerHTML = 'Your encrypted word is: ' + encrypted;
}
      //Script 2
        function decrypt() {
  var text2, additon2, encrypted2, numb2;
  text2, encrypted2 = "";
  text2     = document.getElementById('txt2').value;
  addition2 = document.getElementById('key').value;

  for (i = 0; i < text2.length; i++) {
    numb2 = text2.charCodeAt(i);
    key = parseFloat(numb2) - parseFloat(addition2);
    encrypted2 += String.fromCharCode(key)
  }
    document.getElementById("word2").innerHTML = 'Your encrypted word is: ' + encrypted2;
}
</script>
</body>
</html>

我知道我使用的是内联css,这只是临时的

这是您的固定函数:

function enrypt() {
  var text, additon, encrypted, numb;
  text, encrypted = "";
  text     = document.getElementById('txt').value;
  addition = Math.floor(Math.random() * (122 - 97 + 1)) + 97;
  window.alert('Your encryption key is: ' + addition);
  window.alert('Your original  word is: ' + text);
  for (i = 0; i < text.length; i++) {
    numb = text.charCodeAt(i);
    key = addition + numb;
    encrypted += String.fromCharCode(key)
  }
    window.alert('Your encrypted word is: ' + encrypted);
}

旧答案:

您正在尝试读取未初始化变量txt:的值

letter = document.getElementById(txt.value);

你可能想先初始化它:

txt = document.getElementById("txt");
letter = document.getElementById(txt.value);

此外,检查输入文本长度的长度,而不是DOM元素:

while (i < txt.value.length) {