Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:40
Show Gist options
  • Save rfprod/ee323908ce0d7fda59575598b29f4493 to your computer and use it in GitHub Desktop.
Save rfprod/ee323908ce0d7fda59575598b29f4493 to your computer and use it in GitHub Desktop.
Keyword Cipher
function keywordCipher(abc, keyword) {
this.keywordDictionary = abc;
for (let i in keyword) {
this.keywordDictionary = this.keywordDictionary.replace(keyword[i], '');
}
for (let i = 0, counter = 0, max = keyword.length; i < max; i++) {
if (this.keywordDictionary.indexOf(keyword[i]) === -1) {
this.keywordDictionary = this.keywordDictionary.slice(0, counter) + keyword[i] + this.keywordDictionary.slice(counter, this.keywordDictionary.length);
counter++;
}
}
this.encode = (str) => {
let output = '';
for (let i in str) {
const index = abc.indexOf(str[i]);
output += (index !== -1) ? this.keywordDictionary[index] : str[i];
}
return output;
}
this.decode = (str) => {
let output = '';
for (let i in str) {
const index = this.keywordDictionary.indexOf(str[i]);
output += (index !== -1) ? abc[index] : str[i];
}
return output;
}
}
const alphabet = "abcdefghijklmnopqrstuvwxyz";
const key = "keyword";
let keywordCipher = new keywordCipher(alphabet, key);
cipher.encode("abc"); // "key"
cipher.encode("xyz"); // "vxz"
cipher.decode("key"), // "abc"
cipher.decode("vxz"), // "xyz"

Keyword Cipher

Methods encode(str)/decode(str) of the keywordCipher instance encode / decode input string based on previously provided alphabet and key.

Class keywordCipher operates as follows:

  1. on instantiation second alphabet is generated based on provided alphabet and keyword
  2. to form a second alphabet:

2.1 all characters present in keyword are removed from provided alphabet

2.2 keyword is added to the beginning on the provided alphabet with removed characters; duplicate characters in keyword are ignored 3. calling encode(str)/decode(str) alters string in the following way:

3.1 find an index of each character of the string in provided alphabet and replaces it with a character at the found index in generated alphabet for encode, and vice versa for decode

3.2 if character in the string is not present in respective alphabet the character remains unchanged diring encode/decode

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment