JavaScript解密功能

JavaScript Decrypt Function

本文关键字:功能 解密 JavaScript      更新时间:2023-09-26

我试图在JavaScript中编写一个简单的解密函数,该函数将输入字符串并通过ASCII中的字母表找到代码的所有26个变体。我知道如何做正常解密,但它只是通过一次迭代,只给一个变化,而不是所有的26。我该如何改变它?

var count = 0;
function inputData(buttonPress)
{
var stringData = document.getElementById("stringData").value;
    var splitStr = stringData.toLowerCase();
    var sendStr = (splitStr).split("");
     shift= 26;
     decrypt(sendStr, shift);
    }
function decrypt(newStr, shift)
{
    if(count < newStr.length)
    { 
      var strAscii = newStr[count].charCodeAt(0);
      strAscii=parseInt(strAscii);
      var newStrAscii= ((strAscii -97 -shift) % 26) + 97;
      newStr[count] = String.fromCharCode(newStrAscii);
      count++;
      decrypt(newString,shift-1);
    }
     newStr= newStr.join("");
     alert(newStr);
}

我将假设您的函数只执行ROT13。如果它只是字母偏移量的+1,则可以使用for循环,每次取之前的输出并一次又一次地传递它。

这是我能想到的最简洁、最优雅的编码方式:

var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
function nextLetter(letter) {
    var index = alphabet.indexOf(letter)
    return alphabet[(index+1) % 26]
}
function caesarShiftBy1(text) {
    return text.split('').map(nextLetter).join('')
}
function allCaesarShifts(text) {
    var temp = text.toLowerCase();
    for (var i=0; i<26; i++) {
        console.log(temp);
        temp = caesarShiftBy1(temp);
    }
}

导致:

allCaesarShifts('abcdefghijklmnopqrstuvwxyz')
abcdefghijklmnopqrstuvwxyz
bcdefghijklmnopqrstuvwxyza
cdefghijklmnopqrstuvwxyzab
defghijklmnopqrstuvwxyzabc
efghijklmnopqrstuvwxyzabcd
fghijklmnopqrstuvwxyzabcde
ghijklmnopqrstuvwxyzabcdef
hijklmnopqrstuvwxyzabcdefg
ijklmnopqrstuvwxyzabcdefgh
jklmnopqrstuvwxyzabcdefghi
klmnopqrstuvwxyzabcdefghij
lmnopqrstuvwxyzabcdefghijk
mnopqrstuvwxyzabcdefghijkl
nopqrstuvwxyzabcdefghijklm
opqrstuvwxyzabcdefghijklmn
pqrstuvwxyzabcdefghijklmno
qrstuvwxyzabcdefghijklmnop
rstuvwxyzabcdefghijklmnopq
stuvwxyzabcdefghijklmnopqr
tuvwxyzabcdefghijklmnopqrs
uvwxyzabcdefghijklmnopqrst
vwxyzabcdefghijklmnopqrstu
wxyzabcdefghijklmnopqrstuv
xyzabcdefghijklmnopqrstuvw
yzabcdefghijklmnopqrstuvwx
zabcdefghijklmnopqrstuvwxy

编辑:现在递归的请求:

function allCaesarShifts(text) {
    var toReturn = [];
    function helper(text, offset) {
        toReturn +=[ caesarShift(text,offset) ];
        if (offset>0)
            helper(text, offset-1);
    }
    helper(text, 26);
    return toReturn;
}

更优雅的方法是创建一个函数shiftLetter(letter,offset=1), caesarShiftBy(text,offset=1),然后在范围1,2,…26上映射一个caesarShifyBy(text=text,N)的curry版本(但是没有jquery的javascript还没有很好的原语来处理这些东西)

要将字符串中的所有数字字符实体转换为它们的等效字符,可以这样做:

str.replace(/&#('d+);/g, function (m, n){返回String.fromCharCode(n);})