Skip to content
Advertisement

Why is my decryption function not working?

I created a function to encrypt and decrypt messages. the encrypting works fine. but when I try to log encrypted Hello World! it just logs H.

const chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".split("");
const numbs = "0123456789".split("");
const symbols = "!@#$%^&*()_+-=[]{}|;':,./<>?" ".split("");

function encrypt(message) {
  message = message.split("")
  var output = []
  message.forEach(element => {
    if (chars.includes(element)) {
      output.push("c" + chars.indexOf(element))
    } else if (numbs.includes(element)) {
      output.push("n" + numbs.indexOf(element))
    } else if (symbols.includes(element)) {
      output.push("s" + symbols.indexOf(element))
    } else {
      console.log(element)
      throw new Error(`Unknown character`)
    }
  });
  return output.join("")
}

function decrypt(message) {
  message = message.split("");
  var output = [];
  var prevDeter;
  var prevNumbs = [];
  message.forEach(element => {
    if (element == "c") {
      prevDeter = "c"
      if (prevNumbs.length > 0) {
        output.push(chars[parseInt(prevNumbs.join(""))])
      }
    } else if (element == "n") {
      prevDeter = "n"
      if (prevNumbs.length > 0) {
        output.push(numbs[parseInt(prevNumbs.join(""))])
      }
    } else if (element == "s") {
      prevDeter = "s"
      if (prevNumbs.length > 0) {
        output.push(symbols[parseInt(prevNumbs.join(""))])
      }
    } else {
      prevNumbs.push(element)
    }
  });
  return output.join("")
}

//expected to log Hello World! but logs H and when starting the message with a symbol or number it just logs nothing
console.log(decrypt(encrypt("Hello World!")))

Fixed it, i edited the encoding system to place a – between chars and the decoding system to just split the message at – and check if the element starts with c n or s. and then i just used substring to get the number and decrypt it

const chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".split("");
const numbs = "0123456789".split("");
const symbols = "!@#$%^&*()_+-=[]{}|;':,./<>?" ".split("");

function encrypt(message) {
    message = message.split("");
    var output = [];
    message.forEach(element => {
        if(chars.includes(element)) {
            output.push("-c" + chars.indexOf(element));
        }else if(numbs.includes(element)) {
            output.push("-n" + numbs.indexOf(element));
        }else if(symbols.includes(element)) {
            output.push("-s" + symbols.indexOf(element));
        }else{
            console.log(element);
            throw new Error(`Unknown character`);
        };
    });
    return output.join("");
};

function decrypt(message) {
    message = message.split("-");
    console.log(message)
    var output = [];
    message.forEach(element => {
        if(element.startsWith("c")) {
            output.push(chars[element.substring(1)]);
        }else if(element.startsWith("n")) {
            output.push(numbs[element.substring(1)]);
        }else if(element.startsWith("s")) {
            output.push(symbols[element.substring(1)]);
        }else if(element.length < 1){
            
        }else{
            throw new Error(`Invalid message`);
        }
    });
    return output.join("");
};

console.log(decrypt(encrypt("Hello World!")));

Advertisement

Answer

You need to split the encoded string based on set/index pairs. This is easy enough to do with a look-ahead regular expression and splitting before a c, n or an s. /(?=[cns])/

const chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz".split("");
const numbs = "0123456789".split("");
const symbols = "!@#$%^&*()_+-=[]{}|;':,./<>?" ".split("");

function encrypt(message) {
  message = message.split("")
  var output = []
  message.forEach(element => {
    if (chars.includes(element)) {
      output.push("c" + chars.indexOf(element))
    } else if (numbs.includes(element)) {
      output.push("n" + numbs.indexOf(element))
    } else if (symbols.includes(element)) {
      output.push("s" + symbols.indexOf(element))
    } else {
      console.log(element)
      throw new Error(`Unknown character`)
    }
  });
  return output.join("")
}

function decrypt(message) {
  message = message.split(/(?=[cns])/);
  var output = [];
  message.forEach(element => {
    let set;
    switch(element[0]){
      case 'c':
        set = chars;
        break;
      case 'n':
        set = numbs;
        break;
      case 's':
        set = symbols;
        break;
    }
    const index = parseInt(element.substring(1));
    output.push(set[index]);
  });
  return output.join('');
}
const encrypted = encrypt("Hello World!");
console.log(encrypted);
//expected to log Hello World! but logs H and when starting the message with a symbol or number it just logs nothing
console.log(decrypt(encrypted));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement