[英]Looking for a Caesar's cipher script in JavaScript I can modify to allow all (typeable) ASCII characters
I've been working on a data encryption program in my spare time.我在业余时间一直在研究数据加密程序。 I've added my own layer of encryption, and I'm attempting to add a modified Caesar's cipher that, when shifting, shifts spaces, numbers, and other characters from the ASCII characters list.
我已经添加了自己的加密层,并且正在尝试添加修改后的凯撒密码,该密码在移动时会从 ASCII 字符列表中移动空格、数字和其他字符。
I've modified two scripts already:我已经修改了两个脚本:
Neither works properly.两者都不能正常工作。
Text is the inputted characters, c
is a single character in ASCII, result is the result. text是输入的字符,
c
是ASCII中的单个字符,result就是结果。
var result = "";
for (var i = 0; i < text.length;) {
var c = text.charCodeAt(i);
if (32<=c&&c<=126){result+=String.fromCharCode((c-32+key)%94+32);}
else throw("character not within range");i++};
I have modified this code so it uses special characters but when decrypting, if I have special characters and a key higher than about 20, characters go out of range and return blanks.我已修改此代码,使其使用特殊字符,但在解密时,如果我有特殊字符和高于约 20 的密钥,则字符 go 超出范围并返回空白。
actually I've just checked your script and it works.实际上我刚刚检查了你的脚本并且它有效。 I've put it inside a function:
我把它放在 function 里面:
const text = 'abcABC';
const key = 10;
function caesar(text, key) {
var result = '';
for (var i = 0; i < text.length; ) {
var c = text.charCodeAt(i);
if (32 <= c && c <= 126) {
result += String.fromCharCode(((c - 32 + key) % 94) + 32);
} else throw 'character not within range';
i++;
}
return result;
}
const x = caesar(text, key);
console.log(x); // -> klmKLM
const y = caesar(x, -key);
console.log(y); // -> abcABC
Found my own fix,找到了我自己的修复,
var result = ``;
for (var i = 0; i < text.length;) {
var c = text.charCodeAt(i);
for (var a = 0; a < key;){
c=c-1;
if (c<32){
c=c+94;
};
a++;
console.log(a);
}
result+=String.fromCharCode(c);
i++;
}
works perfectly and even supports multiline!完美运行,甚至支持多行!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.