How to Rotate a Cipher in JavaScript
In encryption, a "cipher" is a code through which a text or message is passed. The cipher takes the letters of the text, and substitutes other letters based on whatever rules the cipher follows. For example, a cipher that replaces each letter in a message with the third letter down the alphabet would replace every letter "A" with the letter "D," the letter "B" with the letter "E," all the way down to "Z," which would wrap around to the letter "C." Using this method, you can create a simple JavaScript cipher which you can rotate to use different alphabet offsets.
Instructions
-
-
1
Create a JavaScript function to encode a message. This function will receive the message to encode and the number of letters to shift. It will call a cipher function which will create the appropriate cipher, and return an encoded message.
function encode(message, cipher_shift){
var 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"];
var coder = cipher(alphabet, 3);
var new_message = encode(message, alphabet, coder);
return new_message;
} -
2
Create a JavaScript function that creates a cipher. You will use an array containing each letter of the alphabet and another array containing the cipher shifted code. You will also use an integer to determine how many characters to shift. The shift is arbitrary; there can be any number of rotations in the cipher array:
function cipher(letters, shift){
var i = 0;
var cipher = new Array(26);for (i; i < 26; i++){
var index = 0;
if ((i + shift) > 25){
index = (i + shift) % 26;
}else {
index = i + shift;
}cipher[i] = letters[index];
}return cipher;
} -
-
3
Create another function, which will take a piece of text to encode, the cipher, and the alphabet array. This function will use the cipher array to encode and return an encoded message:
function encode(message, letters, code){
var i = 0;
var coded_message;for (i; i < message.length; i ++){
var index = letters.indexOf(message[i]); //finds location of letter in alphabet array
coded_message[i] = code[index]; //replaces letter with letter in cipher array
}return coded_message;
}
-
1