caesars Cipher Algorithm
The Caesar Cipher Algorithm, also known as Caesar's Shift, is one of the earliest and simplest methods used for encryption and decryption of messages. Named after the Roman emperor Julius Caesar, who was known to have used it for secure communication with his military generals, this algorithm is a type of substitution cipher where each letter in the plaintext message is replaced by a letter with a fixed number of positions down the alphabet. For example, if the shift value is 3, the letter 'A' would be replaced by 'D', 'B' would become 'E', and so on. The same shift value is then used to decrypt the message and retrieve the original plaintext.
Despite its simplicity, the Caesar Cipher Algorithm was effective during ancient times, largely due to the widespread illiteracy and lack of knowledge about encryption techniques. However, in modern times, this algorithm is easily breakable and not considered secure for any serious communication. It is often used as a beginner's introduction to the world of cryptography due to its simplicity and ease of understanding. Although not practically secure, the Caesar Cipher provides a foundation for learning more advanced encryption techniques and serves as a stepping stone into the complex world of cryptography.
/**
* Caesar's Cipher - also known as the ROT13 Cipher is when
* a letter is replaced by the one that is 13 spaces away
* from it in the alphabet. If the letter is in the first half
* of the alphabet we add 13, if it's in the latter half we
* subtract 13 from the character code value.
*/
/**
* Decrypt a ROT13 cipher
* @param {String} str - string to be decrypted
* @return {String} decrypted string
*/
function rot13 (str) {
const response = []
const strLength = str.length
for (let i = 0; i < strLength; i++) {
const char = str.charCodeAt(i)
if (char < 65 || (char > 90 && char < 97) || char > 122) {
response.push(str.charAt(i))
} else if ((char > 77 && char <= 90) || (char > 109 && char <= 122)) {
response.push(String.fromCharCode(str.charCodeAt(i) - 13))
} else {
response.push(String.fromCharCode(str.charCodeAt(i) + 13))
}
}
return response.join('')
}
// Caesars Cipher Example
const encryptedString = 'Uryyb Jbeyq'
const decryptedString = rot13(encryptedString)
console.log(decryptedString) // Hello World