Author Photo
Christopher Unum I am a software Developer, I write web development tutorials, I also mentor aspiring web developers. s

how to encrypt and decrypt text using javascript





Adding another layer of security to messages you send over the internet might just keep away the noisy siblings snooping through your messages. In this tutorial we will create a simple text encoder and decoder with the help of a password. Look above for the finished product of this tutorial.

Prerequisite

We will be completing the task at hand using Html, CSS and JavaScript, so having some basic knowledge of these technology will come in handy.

Html

Below is the html code for the encoder and decoder

<div id="encrypt-out">
  <div id="encrypt-in">
    <div id="encrypt-head">
      <label for="pass">Enter Password</label>
      <input type="text" id="pass" />
      <label>Enter Text</label>
      <textarea style="height: 200px;" id="encrypt-text"></textarea>
      <button id="encrypt-button" onclick="encode()">Encrypt</button>
      <button id="encrypt-button" onclick="decode()">Decrypt</button
      ><br /><br />
      <label id="encrypted-label">Encrypted Text</label>
      <textarea style="height: 200px;" id="encrypted-text"></textarea>
    </div>
  </div>
</div>

CSS

Now we style the encoder and decoder.

#encrypt-out {
  max-width600px;
  margin20px auto;
  font-family"Fira Sans"sans-serif;
}
#encrypt-in {
  width95%;
  margin0 auto;
}
#encrypt-head {
  padding20px;
  background#1a75aa;
}

label {
  colorwhite;
  margin-top10px;
}
#pass,
#encrypt-text,
#encrypted-text {
  width100%/* Full width */
  padding12px/* Some padding */
  border1px solid #ccc/* Gray border */
  border-radius4px/* Rounded borders */
  box-sizingborder-box/* Make sure that padding and width stays in place */
  margin-top6px/* Add a top margin */
  margin-bottom16px/* Bottom margin */
  resizevertical/* Allow the user to vertically resize the textarea (not horizontally) */
}
#encrypt-button {
  background-color: rgb(165165165);
  colorwhite;
  padding12px 20px;
  bordernone;
  border-radius4px;
  cursorpointer;
}
#encrypted-text,
#encrypted-label {
  displaynone;
}

JavaScript

Below is the JavaScript code for the encoder and decoder

//an object containing all the letters in an alphabets and their positions
const alpha = {
  a: 0,
  b: 1,
  c: 2,
  d: 3,
  e: 4,
  f: 5,
  g: 6,
  h: 7,
  i: 8,
  j: 9,
  k: 10,
  l: 11,
  m: 12,
  n: 13,
  o: 14,
  p: 15,
  q: 16,
  r: 17,
  s: 18,
  t: 19,
  u: 20,
  v: 21,
  w: 22,
  x: 23,
  y: 24,
  z: 25,
};

//all aphabets
const alphabets = "abcdefghijklmnopqrstuvwxyz";

//makes the password equal length with the text to be encrypted
function makeKey() {
  const word = document.querySelector("#pass").value;
  const sentence = document.querySelector("#encrypt-text").value;
  if (word.trim() == "" || sentence.trim() == "") {
    alert("Password and Text are required");
    return "";
  } else {
    let holder = "";
    let x = 0;
    for (let i = 0; i < sentence.length; i++) {
      holder += word.charAt(x);
      x++;
      if (x == word.length) {
        x = 0;
      }
    }
    return holder;
  }
}

//encrypts the text using key generated from password
function encode() {
  const sentence = document.querySelector("#encrypt-text").value;
  const key = makeKey();

  if (key == "" || sentence.trim() == "") {
  } else {
    let encoded = "";

    for (let i = 0; i < sentence.length; i++) {
      let character = sentence.charAt(i);
      if (alphabets.includes(character)) {
        let characterNumber = alpha[character];
        let keyCharacter = key.charAt(i);
        let keyNumber = alpha[keyCharacter];
        let encodedNumber = characterNumber + keyNumber;
        encoded += alphabets.charAt(encodedNumber % 26);
      } else {
        encoded += character;
      }
    }
    document.querySelector("#encrypted-label").style.display = "block";
    document.querySelector("#encrypted-text").style.display = "block";
    document.querySelector("#encrypted-label").textContent =
      "Encrypted Text";
    document.querySelector("#encrypted-text").value = encoded;
  }
}

//decrypts the encoded text using key generated from password
function decode() {
  const sentence = document.querySelector("#encrypt-text").value;
  const key = makeKey();

  if (key == "" || sentence.trim() == "") {
  } else {
    let decoded = "";

    for (let i = 0; i < sentence.length; i++) {
      let character = sentence.charAt(i);
      if (alphabets.includes(character)) {
        let characterNumber = alpha[character];
        let keyCharacter = key.charAt(i);
        let keyNumber = alpha[keyCharacter];
        let decodedNumber = characterNumber - keyNumber;
        decoded += alphabets.charAt(
          decodedNumber < 0 ? decodedNumber + 26 : decodedNumber
        );
      } else {
        decoded += character;
      }
    }
    document.querySelector("#encrypted-label").style.display = "block";
    document.querySelector("#encrypted-text").style.display = "block";
    document.querySelector("#encrypted-label").textContent =
      "Decrypted Text";
    document.querySelector("#encrypted-text").value = decoded;
  }
}

Conclusion

Hope you had fun learning our customized encoder and decoder, very soon we also look at how to encode text using in-built APIs.