Exercism v3 launches on Sept 1st 2021. Learn more! 🚀🚀🚀
Avatar of rootulp

rootulp's solution

to Simple Cipher in the TypeScript Track

Published at Nov 05 2018 · 0 comments
Test suite


This exercise has changed since this solution was written.

Implement a simple shift cipher like Caesar and a more secure substitution cipher.

Step 1

"If he had anything confidential to say, he wrote it in cipher, that is, by so changing the order of the letters of the alphabet, that not a word could be made out. If anyone wishes to decipher these, and get at their meaning, he must substitute the fourth letter of the alphabet, namely D, for A, and so with the others." —Suetonius, Life of Julius Caesar

Ciphers are very straight-forward algorithms that allow us to render text less readable while still allowing easy deciphering. They are vulnerable to many forms of cryptoanalysis, but we are lucky that generally our little sisters are not cryptoanalysts.

The Caesar Cipher was used for some messages from Julius Caesar that were sent afield. Now Caesar knew that the cipher wasn't very good, but he had one ally in that respect: almost nobody could read well. So even being a couple letters off was sufficient so that people couldn't recognize the few words that they did know.

Your task is to create a simple shift cipher like the Caesar Cipher. This image is a great example of the Caesar Cipher:

Caesar Cipher

For example:

Giving "iamapandabear" as input to the encode function returns the cipher "ldpdsdqgdehdu". Obscure enough to keep our message secret in transit.

When "ldpdsdqgdehdu" is put into the decode function it would return the original "iamapandabear" letting your friend read your original message.

Step 2

Shift ciphers are no fun though when your kid sister figures it out. Try amending the code to allow us to specify a key and use that for the shift distance. This is called a substitution cipher.

Here's an example:

Given the key "aaaaaaaaaaaaaaaaaa", encoding the string "iamapandabear" would return the original "iamapandabear".

Given the key "ddddddddddddddddd", encoding our string "iamapandabear" would return the obscured "ldpdsdqgdehdu"

In the example above, we've set a = 0 for the key value. So when the plaintext is added to the key, we end up with the same message coming out. So "aaaa" is not an ideal key. But if we set the key to "dddd", we would get the same thing as the Caesar Cipher.

Step 3

The weakest link in any cipher is the human being. Let's make your substitution cipher a little more fault tolerant by providing a source of randomness and ensuring that the key contains only lowercase letters.

If someone doesn't submit a key at all, generate a truly random key of at least 100 characters in length.

If the key submitted is not composed only of lowercase letters, your solution should handle the error in a language-appropriate way.


Shift ciphers work by making the text slightly odd, but are vulnerable to frequency analysis. Substitution ciphers help that, but are still very vulnerable when the key is short or if spaces are preserved. Later on you'll see one solution to this problem in the exercise "crypto-square".

If you want to go farther in this field, the questions begin to be about how we can exchange keys in a secure way. Take a look at Diffie-Hellman on Wikipedia for one of the first implementations of this scheme.


Go through the setup instructions for TypeScript to install the necessary dependencies:



Install assignment dependencies:

$ yarn install

Making the test suite pass

Execute the tests with:

$ yarn test


Substitution Cipher at Wikipedia http://en.wikipedia.org/wiki/Substitution_cipher

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.


import SimpleCipher from './simple-cipher'

describe('Random key generation', () => {
    xit('generates keys at random', () => {
        // Strictly speaking, this is difficult to test with 100% certainty.
        // But, if you have a generator that generates 100-character-long
        // strings of lowercase letters at random, the odds of two consecutively
        // generated keys being identical are astronomically low.
        expect(new SimpleCipher().key).not.toEqual(new SimpleCipher().key)

describe('Random key cipher', () => {
    const simpleCipher = new SimpleCipher()

    it('has a key made of letters', () => {

    xit('has a key that is at least 100 characters long', () => {

    // Here we take advantage of the fact that plaintext of "aaa..."
    // outputs the key. This is a critical problem with shift ciphers, some
    // characters will always output the key verbatim.
    xit('can encode', () => {
        expect(simpleCipher.encode('aaaaaaaaaa')).toEqual(simpleCipher.key.substr(0, 10))

    xit('can decode', () => {
        expect(simpleCipher.decode(simpleCipher.key.substr(0, 10))).toEqual('aaaaaaaaaa')

    xit('is reversible', () => {
        const plaintext = 'abcdefghij'

describe('Incorrect key cipher', () => {
    xit('throws an error with an all caps key', () => {
        expect(() => {
            new SimpleCipher('ABCDEF')
        }).toThrowError('Bad key')

    xit('throws an error with a numeric key', () => {
        expect(() => {
            new SimpleCipher('12345')
        }).toThrow('Bad key')

    xit('throws an error with an empty key', () => {
        expect(() => {
            new SimpleCipher('')
        }).toThrow('Bad key')

describe('Substitution cipher', () => {
    const key = 'abcdefghij'
    const simpleCipher = new SimpleCipher(key)

    xit('keeps the submitted key', () => {

    xit('can encode', () => {

    xit('can decode', () => {

    xit('is reversible', () => {

    xit(': double shift encode', () => {
        expect(new SimpleCipher('iamapandabear').encode('iamapandabear'))

    xit('can wrap on encode', () => {

    xit('can wrap on decode', () => {

    xit('can handle messages longer than the key', () => {
        expect(new SimpleCipher('abc').encode('iamapandabear'))
class SimpleCipher {
    public key: string
    static readonly alphabet = "abcdefghijklmnopqrstuvwxyz"

    constructor(inputKey?: string) {
        if (inputKey === undefined) {
            this.key = Key.generate()
        } else if (Key.isValid(inputKey)) {
            this.key = inputKey
        } else {
            throw "Bad key"
    public encode = (data: string): string => {
        return data.split("").map(this.encodeCharacter).join("")

    public decode = (encodedData: string): string => {
        return encodedData.split("").map(this.decodeCharacter).join("")

    private encodeCharacter = (character: string, index: number): string => {
        const shiftDistance = this.getShiftDistance(index)
        const encryptedValue = this.valueOf(character) + shiftDistance
        return this.convertValueToCharacter(encryptedValue)

    private decodeCharacter = (character: string, index: number): string => {
        const shiftDistance = this.getShiftDistance(index)
        const decryptedValue = this.valueOf(character) - shiftDistance
        return this.convertValueToCharacter(decryptedValue)

    private getShiftDistance = (index: number): number => {
        const encryptionCharacter = this.getEncryptionCharacter(index)
        return this.valueOf(encryptionCharacter)

    private getEncryptionCharacter = (index: number): string => {
        return this.key[index % this.key.length]

    private convertValueToCharacter = (value: number): string => {
        return SimpleCipher.alphabet[mod(value,  SimpleCipher.alphabet.length)]

    private valueOf = (character: string): number => {
        return SimpleCipher.alphabet.indexOf(character)

class Key {
    static readonly alphabet = "abcdefghijklmnopqrstuvwxyz"

    static isValid(inputKey: string): boolean {
        return Key.containsOnlyLowercaseCharacters(inputKey) && Key.isNotEmpty(inputKey)

    static generate(): string {
        const KEY_LENGTH: number = 100
        return Key.generateRandomString(KEY_LENGTH)

    static generateRandomString(length: number): string {
        return [...Array(length)].map(this.generateRandomCharacter).join("")

    static generateRandomCharacter(): string  {
        return Key.alphabet.charAt(Math.floor(Math.random() * Key.alphabet.length))

    static containsOnlyLowercaseCharacters(inputKey: string): boolean {
        return inputKey.split("").every(Key.isLowercaseLetter)

    static isLowercaseLetter(character: string): boolean {
        return Key.alphabet.includes(character)

    static isNotEmpty(inputKey: string): boolean {
        return inputKey !== ""

// % in JavaScript is the remainder operator (rather than modulo)
// See: https://stackoverflow.com/questions/4467539/javascript-modulo-gives-a-negative-result-for-negative-numbers
function mod(n: number, m: number) {
    return ((n % m) + m) % m

export default SimpleCipher

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?