ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

# el-camo's solution

## to Simple Cipher in the JavaScript Track

Published at Oct 19 2020 · 0 comments
Instructions
Test suite
Solution

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 cryptanalysis, but we are lucky that generally our little sisters are not cryptanalysts.

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:

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 alphanumeric characters in length.

## Extensions

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.

## Setup

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

https://exercism.io/tracks/javascript/installation

## Requirements

Please `cd` into exercise directory before running all below commands.

Install assignment dependencies:

``````\$ npm install
``````

## Making the test suite pass

Execute the tests with:

``````\$ npm test
``````

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by changing `xtest` to `test`.

## Submitting Solutions

Once you have a solution ready, you can submit it using:

``````exercism submit simple-cipher.js
``````

## Submitting Incomplete Solutions

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

## Exercise Source Credits

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

### simple-cipher.spec.js

``````/* eslint-disable no-new */
import { Cipher } from './simple-cipher';

describe('Random key cipher', () => {
const cipher = new Cipher();

test('can encode', () => {
// 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.
expect(cipher.encode('aaaaaaaaaa')).toEqual(cipher.key.substr(0, 10));
});

xtest('can decode', () => {
expect(cipher.decode(cipher.key.substr(0, 10))).toEqual('aaaaaaaaaa');
});

xtest('is reversible', () => {
// I.e., if you apply decode in a encoded result, you must see
// the same plaintext encode parameter as a result of the decode method
const plaintext = 'abcdefghij';
expect(cipher.decode(cipher.encode(plaintext))).toEqual(plaintext);
});

xtest('key is made only of lowercase letters', () => {
expect(cipher.key).toMatch(/^[a-z]+\$/);
});
});

describe('Substitution cipher', () => {
const key = 'abcdefghij';
const cipher = new Cipher(key);

xtest('can encode', () => {
expect(cipher.encode('aaaaaaaaaa')).toEqual('abcdefghij');
});

xtest('can decode', () => {
expect(cipher.decode('abcdefghij')).toEqual('aaaaaaaaaa');
});

xtest('is reversible', () => {
// I.e., if you apply decode in a encoded result, you must see
// the same plaintext encode parameter as a result of the decode method
expect(cipher.decode(cipher.encode('abcdefghij'))).toEqual('abcdefghij');
});

xtest('can double shift encode', () => {
expect(new Cipher('iamapandabear').encode('iamapandabear'))
.toEqual('qayaeaagaciai');
});

xtest('can wrap on encode', () => {
expect(cipher.encode('zzzzzzzzzz')).toEqual('zabcdefghi');
});

xtest('can wrap on decode', () => {
expect(cipher.decode('zabcdefghi')).toEqual('zzzzzzzzzz');
});

xtest('can encode messages longer than the key', () => {
expect(new Cipher('abc').encode('iamapandabear'))
.toEqual('iboaqcnecbfcr');
});

xtest('can decode messages longer than the key', () => {
expect(new Cipher('abc').decode('iboaqcnecbfcr'))
.toEqual('iamapandabear');
});
});``````
``````//
// This is only a SKELETON file for the 'Simple Cipher' exercise. It's been provided as a
// convenience to get you started writing code faster.
//

export class Cipher {
constructor(key = "aaaaaaaaaa") {
this._key = key;
}

newCode(str, i, encode) {
const oldCode = str.charCodeAt(0);
const keyCode = this._key.charCodeAt(i) - 97;
let newCode = encode ? oldCode + keyCode : oldCode - keyCode;

if (newCode > 122) newCode -= 26;
if (newCode < 97) newCode += 26;

const newChar = String.fromCharCode( newCode );

return newChar;
}

encode(str) {
return str.split('')
.map((x, i) => this.newCode(x,i % this._key.length, true))
.join('');
}

decode(str) {
return str.split('')
.map( (x, i) => this.newCode(x, i % this._key.length, false) )
.join('');
}

get key() {
return this._key;
}

}``````
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}