Skip to content

Caesar Cipher JS

A small npm library for the Caesar cipher in JavaScript and TypeScript, with no dependencies. The panel below runs the real thing.

Terminal
npm install caesar-cipher-js
JavaScript
import { encrypt, decrypt } from "caesar-cipher-js"; console.log(encrypt("Hello World!", 3));// Khoor Zruog!console.log(decrypt("Khoor Zruog!", 3));// Hello World!
advertisement

Installation

The package is on npm under the MIT license, and the source and tests are on GitHub. Use whichever package manager you prefer:

Terminal
npm install caesar-cipher-jsyarn add caesar-cipher-jspnpm add caesar-cipher-js

It needs Node.js 20 or newer and ships as ES modules and CommonJS. In the browser, use it through a bundler: this site’s tools load it with Vite. The ES module build is about 3.5 KB gzipped.

Quick start

Import the function you need. By default, the library keeps upper and lower case and leaves everything outside the alphabet alone.

JavaScript
import { encrypt, decrypt } from "caesar-cipher-js"; console.log(encrypt("Hello World!", 3));// Khoor Zruog!console.log(decrypt("Khoor Zruog!", 3));// Hello World!
CommonJS
const { encrypt } = require("caesar-cipher-js"); console.log(encrypt("Hello World!", 3));// Khoor Zruog!

Functions

These are the ones you will use most. A negative shift works too, and so does one larger than the alphabet.

NameWhat it does
encrypt(text, shift, options?)Returns the encrypted text.
decrypt(text, shift, options?)Returns the decrypted text.
bruteforce(text, options?)Tries every shift and returns an array of { shift, text, score? }. Options: alphabet, maxResults, scoreFunction.
getScoreFunction(language)Returns a scoring function for a language.
mapDiacritics(text, language)Replaces accented letters with basic ones.
new CaesarCipher(options?)The same features as an object with saved settings.

Options

encrypt, decrypt and the CaesarCipher constructor all take the same options:

OptionWhat it does
alphabetThe alphabet to shift within. Default: a to z.
caseStrategymaintain (default), upper or lower.
preserveCaseDefault true. With false, the result is lower case.
preserveNonAlphaDefault true. With false, everything outside the alphabet is removed.
preserveSpacesDefault true. With false, spaces are removed.
preserveSpecialCharsDefault true. With false, punctuation and digits are removed.
diacriticsLanguageSet to french to map accented letters before shifting.
JavaScript
import { encrypt } from "caesar-cipher-js"; console.log(encrypt("Hello, World! 123", 3, { caseStrategy: "upper" }));// KHOOR, ZRUOG! 123console.log(encrypt("Hello, World! 123", 3, { preserveSpaces: false }));// Khoor,Zruog!123console.log(encrypt("Hello, World! 123", 3, { preserveNonAlpha: false }));// KhoorZruog

Other alphabets

The library exports alphabets for English, Polish, German, Spanish and French, plus ALPHABET_ALPHANUMERIC_LOWER with digits, as in this example. You can also pass any string of your own.

JavaScript
import { encrypt, ALPHABET_ALPHANUMERIC_LOWER } from "caesar-cipher-js"; console.log(encrypt("Room 101", 3, { alphabet: ALPHABET_ALPHANUMERIC_LOWER }));// Urrp 434

Breaking a cipher with bruteforce

bruteforce returns one result per shift, starting from shift 0. To get the most likely answer first, pass a scoreFunction. getScoreFunction has ready scoring for english, polish, german, spanish and french.

JavaScript
import { bruteforce, getScoreFunction } from "caesar-cipher-js"; const results = bruteforce("Wkh txlfn eurzq ira mxpsv ryhu wkh odcb grj", {    scoreFunction: getScoreFunction("english"),    maxResults: 2,}); for (const { shift, text } of results) {    console.log(shift, text);}// 3 The quick brown fox jumps over the lazy dog// 9 Nby kocwe vliqh zir dogjm ipyl nby futs xia

The score only compares results with each other, so check the text yourself, especially when the message is short.

The CaesarCipher class

The class remembers its settings, which is handy when you use the same options many times. It also has setters such as setAlphabet, and reset() to return to the defaults.

JavaScript
import { CaesarCipher, ALPHABET_ALPHANUMERIC_LOWER } from "caesar-cipher-js"; const cipher = new CaesarCipher({ alphabet: ALPHABET_ALPHANUMERIC_LOWER });const secret = cipher.encrypt("Room 101", 3); console.log(secret);// Urrp 434console.log(cipher.decrypt(secret, 3));// Room 101

Accented letters

Accented letters outside the alphabet normally stay as they are. For French, diacriticsLanguage first turns é into e and ç into c, so that they get shifted too. French is the only language with this mapping so far.

JavaScript
import { encrypt, mapDiacritics } from "caesar-cipher-js"; console.log(mapDiacritics("Déjà vu à Noël", "french"));// Deja vu a Noelconsole.log(encrypt("Déjà vu à Noël", 3, { diacriticsLanguage: "french" }));// Ghmd yx d Qrho

TypeScript

The package includes its types, so there is nothing else to install. It exports EncryptOptions, DecryptOptions, BruteforceResult and more.

TypeScript
import { encrypt, type EncryptOptions } from "caesar-cipher-js"; const options: EncryptOptions = { caseStrategy: "upper" };const result: string = encrypt("Hello", 3, options); console.log(result);// KHOOR

Library, API or your own code?

Choose the library for a JavaScript or TypeScript project: it runs locally, with no requests or limits. For other languages, or if you need ROT13 or Vigenère, use the REST API. If you’re learning, write the cipher yourself by following the JavaScript tutorial.

Frequently asked questions

Is the library free?

Yes. It is under the MIT license, so you can use it in personal and commercial projects.

Can I use this to protect real data?

No. The Caesar cipher breaks in seconds, as bruteforce shows. Use the library for learning, puzzles and games. For real data, use modern encryption such as the Web Crypto API.

Is it used in production?

Yes. The Caesar cipher tool on this site runs on it, including the solver.

Keep going