我正在尝试建立一个加密器& amp;解密器用于基于凯撒密码的单一任务。
我做了一个不错的开始但是每当我尝试返回字符串长度以便我可以为每个字符循环加密器时它将它返回为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,这只是暂时的
答案 0 :(得分:0)
以下是您的固定功能:
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) {