Caesar Cipher Encrypt and Decrypt in JavaScript

Caesar Cipher Encrypt and Decrypt in JavaScript
Code Snippet:Caesars Cipher
Author: Aleksandar Sandro Cvetković
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 844
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to encrypt and decrypt text using the Caesar cipher mechanism. It works by shifting characters in a given text to provide a simple form of encryption. It’s helpful for securing sensitive messages and learning about basic cryptography.

You can use this code to enhance the security of sensitive messages by encrypting them using the Caesar cipher technique. It’s beneficial for creating simple encryption tools or educational projects.

How to Create Caesar Cipher Encrypt And Decrypt Feature Using JavaScript

1. First of all, load the Google Fonts by adding the following CDN link into the head tag of your HTML document. (Optional)

<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Archivo+Black|Muli:400,800,900&amp;display=swap'>

2. Create an HTML file and include the necessary HTML elements. Make sure to have input fields for the text you want to encrypt or decrypt and specify the shift value.

<div id="container">
      <h1>Caesars Cipher</h1>
      <h3>
        One of the simplest and most widely known ciphers is a
        <span>Caesar cipher</span>, also known as a <span>shift cipher</span>.
        In a shift cipher the meanings of the letters are shifted by some set
        amount. A common modern use is the <span>ROT13 cipher</span>, where the
        values of the letters are <span>shifted by 13 places</span>. Thus 'A' ↔
        'N', 'B' ↔ 'O' and so on.
      </h3>
      <div class="panel">
        <label>Message:</label>
        <input id="inputText" type="text" placeholder="Type something..." />
        <label>Shift:</label>
        <div class="row">
          <select name="shifts" id="shift">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
            <option value="11">11</option>
            <option value="12">12</option>
            <option value="13" selected>13</option>
            <option value="14">14</option>
            <option value="15">15</option>
            <option value="16">16</option>
            <option value="17">17</option>
            <option value="18">18</option>
            <option value="19">19</option>
            <option value="20">20</option>
            <option value="21">21</option>
            <option value="22">22</option>
            <option value="23">23</option>
            <option value="24">24</option>
            <option value="25">25</option>
          </select>
          <button class="btn" id="clipboard">
            <i class="far fa-clipboard"></i>
          </button>
        </div>
        <button onclick="caesarShift(inputText.value, shift.value)">
          Encrypt
        </button>
        <button onclick="decrypt(inputText.value)">
          Decrypt
        </button>
      </div>
    </div>

3. Now, add the following CSS code to your project to style the encryption and decryption interface. You can modify the CSS code to match your web/app project’s theme.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: "Muli", sans-serif;
  color: #fff;
}

#container {
  background-image: linear-gradient(60deg, #29323c 0%, #485563 100%);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

#container h3 span {
  color: #fff;
}

h1 {
  color: white; /* Fallback */
  /*Photo by Freepik on Freepik - https://www.freepik.com/free-vector/abstract-futuristic-wallpaper_6413324.htm*/
  background: url(https://image.freepik.com/free-vector/abstract-futuristic-wallpaper_23-2148398113.jpg)
    repeat;
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-transform: uppercase;
  letter-spacing: 5px;
  font-family: "Archivo Black", "Arial Black", sans-serif;
  font-size: 8vw;
}

h3 {
  color: lightsteelblue;
  letter-spacing: 1px;
  text-align: center;
  margin: 0px 0px 20px;
  padding: 0px 50px;
}

.row {
  display: flex;
  flex-direction: row;
}

.panel {
  background-image: linear-gradient(#141e30, #243b55);
  border-radius: 15px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
  padding: 30px;
  margin: 15px;
}

.panel input,
.panel button {
  border: none;
  border-radius: 3px;
  display: block;
  font-size: 16px;
  padding: 8px 10px;
  margin: 15px 0;
  width: 100%;
}

.panel select {
  border: none;
  border-radius: 3px;
  font-size: 16px;
  padding: 8px 10px;
  margin: 15px 0;
  width: 100%;
}

.panel .btn {
  font-size: 16px;
  padding: 8px 12px;
  margin-left: 15px;
  width: 100%;
}

.panel button {
  background-image: linear-gradient(to bottom right, #141e30, #243b55);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #fff;
  cursor: pointer;
}

@media (max-width: 600px) {
  h3 {
    font-size: 14px;
    margin: 15px 0px 0px;
  }
}

4. Load the Font Awesome Icons Kit by adding the following scripts before closing the body tag:

<script src='https://kit.fontawesome.com/7a230f0a67.js'></script>

5. Finally, copy and paste the following JavaScript code into a <script> tag at the end of your HTML file. This code includes three essential functions:

  • caesarShift(text, shift): This function performs the Caesar cipher encryption or decryption.
  • decrypt(isDecrypt): This function reads the input text and shift value, allowing you to decrypt or encrypt the text.
  • copyToClipboard(): A function that enables you to copy the encrypted text to the clipboard.
function decrypt(isDecrypt) {
  var shiftText = document.getElementById("shift").value;
  var shift = parseInt(shiftText, 10);
  if (isDecrypt) shift = (26 - shift) % 26;
  var textElem = document.getElementById("inputText");
  textElem.value = caesarShift(textElem.value, shift);
}

function caesarShift(text, shift) {
  var shift = parseInt(shift, 10);
  var result = "";

  for (var i = 0; i < text.length; i++) {
    var c = text.charCodeAt(i);

    if (65 <= c && c <= 90)
      result += String.fromCharCode(((c - 65 + shift) % 26) + 65);
    // Uppercase
    else if (97 <= c && c <= 122)
      result += String.fromCharCode(((c - 97 + shift) % 26) + 97);
    // Lowercase
    else result += text.charAt(i);
  }
  var textElem = document.getElementById("inputText");
  textElem.value = result;
  return result;
}

document.getElementById("clipboard").addEventListener("click", copyToClipboard);

function copyToClipboard() {
  let textArea = document.createElement("textarea");
  const emptyResultField = inputText.value;

  if (!emptyResultField) {
    return;
  }
  textArea.value = inputText.value;
  document.body.appendChild(textArea);
  textArea.select();
  document.execCommand("Copy");
  textArea.remove();

  alert("Caesaris codice copied to clipboard!");
}

That’s all! hopefully, you have successfully created Caesar Cipher Encrypt and Decrypt functionality in JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X