Home >Web Front-end >JS Tutorial >How to Build a Cipher Machine with JavaScript

How to Build a Cipher Machine with JavaScript

Joseph Gordon-Levitt
Joseph Gordon-LevittOriginal
2025-02-14 09:34:11501browse

This tutorial shows you how to build a Caesar cipher machine using JavaScript. The Caesar cipher shifts each letter in a message a certain number of places.

How to Build a Cipher Machine with JavaScript

We'll create an HTML page with a form to input the message and shift value, and a div to display the encrypted result.

The JavaScript code includes:

  • An alphabet array.
  • DOM manipulation to access form elements.
  • An event handler for the submit button.
  • An encrypt function applying the Caesar cipher, handling non-alphabet characters and case sensitivity.

Here's an example of the finished code. Experiment with creating secret messages!

First, create caesar.html:

<code class="language-html"><!DOCTYPE html>


  <meta charset="utf-8">
  <title>Caesar Cipher</title>


  <h1>Caesar Cipher</h1>
  <form>
    <label>Plaintext:</label>
    <textarea name="plaintext">Top Secret</textarea><br>
    <label>Shift:</label>
    <input type="number" name="shift" value="5" min="1" max="26">
    <input type="submit" value="encrypt">
  </form>
  <h2>Output</h2>
  <div id="output"></div>
  

</code>

This HTML creates a simple form. The shift input defaults to 5, but you can adjust it.

Next, create main.js in the same folder:

<code class="language-javascript">const alphabet = [
  'A','B','C','D','E','F',
  'G','H','I','J','K','L',
  'M','N','O','P','Q','R',
  'S','T','U','V','W','X',
  'Y','Z'
];

const form = document.forms[0];
const output = document.getElementById('output');

form.addEventListener ('submit',event => {
  event.preventDefault();
  output.innerHTML = [...form.plaintext.value].map(char => encrypt(char)).join('');
});

function encrypt(char) {
  const shift = Number(form.shift.value);
  if (alphabet.includes(char.toUpperCase())) {
    const position = alphabet.indexOf(char.toUpperCase());
    const newPosition = (position + shift)%26;
    return alphabet[newPosition];
  } else {
    return char;
  }
}</code>

This JavaScript code defines the alphabet, gets form elements, adds an event listener to handle form submission, and includes the encrypt function which performs the Caesar cipher. The encrypt function handles uppercase letters; lowercase letters are handled implicitly by the includes and indexOf methods.

How to Build a Cipher Machine with JavaScript

This completes the Caesar cipher machine. Remember that this is a simple cipher and not suitable for secure communication.

Frequently Asked Questions (FAQs) (Summarized for brevity)

  • Caesar Cipher: A substitution cipher shifting letters a fixed number of places.
  • JavaScript Implementation: Create a function iterating through the string, shifting letter positions, and handling non-alphabetic characters and case.
  • Non-alphabet Characters: Check if a character is a letter before shifting; otherwise, keep it unchanged.
  • Case Sensitivity: Convert the input to uppercase or lowercase before processing, or handle cases individually.
  • Decryption: Shift characters in the opposite direction using the known shift value. If unknown, try all possible shifts.
  • Optimization: Pre-calculate shifted values or use a StringBuilder for faster string manipulation.
  • Security: Not secure; use modern algorithms like AES for secure encryption.
  • Extending to Other Ciphers: Abstract the shifting logic into a separate function, replaceable with other cipher implementations.
  • Testing: Encrypt known plaintext with a known shift value and check the output. Use a testing framework for automated tests.
  • Special Characters: Create a custom alphabet including all desired characters.

The above is the detailed content of How to Build a Cipher Machine with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn