V
V
Vitaly2020-09-13 13:19:29
JavaScript
Vitaly, 2020-09-13 13:19:29

How to write an encryption function using the encode substitution method?

Add the encryption function using the substitution method encode(text, openAlph, secureAlph).

Encode function arguments:
text - text to be encrypted
openAlph - open alphabet
secureAlph - encrypted alphabet
Return value — string (encrypted text).

For encryption, each character of the open alphabet must be replaced by the corresponding character of the closed alphabet. If there are non-alphabetic characters in the text, then they should be left unchanged.

For example:
encode(
"message",
"abcdefghijklmnopqrstuvwxyz",
"rsyxuqldnmzvpofceiwktjgabh",
); // should return "puwwrlu"

function encode(text, openAlph, secureAlph) {
  let result = "";

  return result;
}


I have been sitting for the third day, looking for a solution, unfortunately I did not find similar ones on the forum.
Please tell me where to start the solution, as I understand the logic of the function .... you need to split the message "text" character by character, then find this character in the open alphabet and determine its id and replace it with a character with the same id of only the encrypted alphabet and write it down, let's say in an array of it, but I don't know how to implement it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AbramovKS, 2020-09-13
@vitas1693

function encode(text, openAlph, secureAlph) {
    let result = ""
    text = text.split("") //превращаем строку в массив
     text.forEach(char => { //бежим по массиву
        let upper = false
        if(char != char.toLowerCase()){ //превращаем в строчную и запоминаем
            upper = true
            char = char.toLowerCase()
        }
        
        if(char.match(/^[A-Za-z]$/)){ 
            let oIndex = openAlph.indexOf(char) //индекс в открытом алфавите алфавите
            if( oIndex == -1){ //если индекс не нашелся
                throw new Error('Не найден символ "'+char+'" в открытом алфавите'); 
            } 
            if( !secureAlph[oIndex] ){
                throw new Error('Не найден индекс "'+oIndex+'" в закрытом алфавите'); 
            }
            char = secureAlph[oIndex] //по индексу берем букву в закрытом алфавите 
        } 
        if(upper){
            char = char.toUpperCase()
        }
        result += char
     }); 
  return result;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question