JavaScript

Caesar Cipher in Javascript

In this tutorial, we are going to see how to use the Caesar cipher to encrypt a message. Caesar’s cipher, also known as Shift Cipher, is one of the oldest and simplest forms of message encryption. This is a type of substitution cipher in which each letter of the original message is replaced by a letter corresponding to a number of letters shifted up or down in the alphabet.
 

Example :
text = ABCD, Key = 10

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

Right shift by 10, A is replaced by K
Right shift by 10, B is replaced by L
Right shift by 10, C is replaced by M
Right shift by 10, D is replaced by N

Output:

KLMN

 
[st_adsense]  

JavaScript implementation
function cesar(str, amount) {
	
	if (amount < 0)
		return cesar(str, amount + 26);
	
	// variable to store the result
	var res = '';
	// iterate over the string
	for (var i = 0; i < str.length; i++) {
		// Get the character that we are going to add
		var c = str[i];
		// Check if it's a letter
		if (c.match(/[a-z]/i)) {
			// Get the letter's code
			var code = str.charCodeAt(i);
			// Capital letters
			if ((code >= 65) && (code <= 90))
				c = String.fromCharCode(((code - 65 + amount) % 26) + 65);
			// Lowercase letters
			else if ((code >= 97) && (code <= 122))
				c = String.fromCharCode(((code - 97 + amount) % 26) + 97);
		}
		// Add the character
		res += c;
	}
	// Result
	return res;
};

console.log(cesar("ABCD", 10))

Output:

KLMN
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *