Timothy Waters
Timothy Waters

Reputation: 73

Why am I getting random undefined chars in my decryption output in my Vigenere Cipher algorithm?

I am working on my own Vigenere Cipher in JavaScript. I enjoy it. Anyway, the encryption and decryption is the same except decrypt() is '-' keyStr instead of '+' towards the bottom. The encryption works perfectly. But, for some reason, when decrypting, some of the chars come out as undefined randomly. I know the algorithm works for C++, Python, Java, and Swift. What is the error here?

I have tried printing the char indices in the alphabet array and the index values in decrypt() come out odd and I can't figure out why.

function ascii(x) {
return x.charCodeAt(0);
}

function decrypt() {
var alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var msgStr = "";
var keyTemp = "";
var keyStr = "";
var output = "";
var input = document.getElementById("inMsg").value;
var key = document.getElementById("key").value;

input = input.toUpperCase();
key = key.toUpperCase();

for(let i = 0; i < input.length; i++) {
    for(let x = 0; x < alpha.length; x++) {
        if (input[i] == alpha[x]) {
            msgStr += alpha[x];
        }
    }
}

for(let i = 0; i < msgStr.length; i++) {
    keyTemp += key[i % key.length]
}

for(let i = 0; i < keyTemp.length; i++) {
    for(let x = 0; x < alpha.length; x++) {
        if (keyTemp[i] == alpha[x]) {
            keyStr += alpha[x];
        }
    }
}

for(let i = 0; i < msgStr.length; i++) {
    let x = (ascii(msgStr[i]) - ascii(keyStr[i])) % 26;
    output += alpha[x];
}

document.getElementById("outMsg").value = output;
}

Upvotes: 2

Views: 152

Answers (1)

DoughnutDayDevotee
DoughnutDayDevotee

Reputation: 111

The problem you are having is being caused by this line:

let x = (ascii(msgStr[i]) - ascii(keyStr[i])) % 26;

because

ascii(msgStr[i]) - ascii(keyStr[i])

can be negative.

The % operator isn't really a modulus operator in javascript its a remainder operator and it works a little differently.

From the link above, you should be able to do something more like this to get it to work:

 let x = ((ascii(msgStr[i]) - ascii(keyStr[i])) % 26) + 26) % 26

Upvotes: 3

Related Questions