Caesar encryption of string using JavaScript
Caesar encryption of string is basically shifting of characters by some amount. Let me put it this way, if you’ve a string “abc” and you want it to be shifted by amount 4. i.e. “efg”. This is called Caesar encryption.
Here in this example, we are going to use concept of ASCII code. Every letter in alphabet has some decimal value assigned i.e. “a” = 97, “b” = 98 …”z” = 122 or “A” = 65, “B” = 66…”Z” = 90.
The trick liesĀ when you’ve to encrypt trailing letters like x,y,z. If your shift amount is 3 and string is “xyz” then encrypted string should be “abc”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function CaesarEncryption (plainString, shiftAmount) { var cipheredtext = ""; for(var i = 0; i < plainString.length; i++) { var plainCharacter = plainString.charCodeAt(i); if(plainCharacter >= 97 && plainCharacter <= 122) { cipheredtext += String.fromCharCode((plainCharacter-97 + shiftAmount)%26 + 97 ); } else if(plainCharacter >= 65 && plainCharacter <= 90) { cipheredtext += String.fromCharCode((plainCharacter-65 + shiftAmount)%26 + 65 ); } else { cipheredtext += String.fromCharCode(plainCharacter); } } return cipheredtext; } |
Output:
1 2 3 4 5 6 |
// We want to encrypt the string "Iambeingencrypted" by Shift amount 3 console.log(CaesarEncryption("Iambeingencryted",3)) //Here is how encrypted string looks like Ldpehlqjhqfubswhg |