📅  最后修改于: 2023-12-03 15:14:05.317000             🧑  作者: Mango
In this article, we will explore the Caesar Cipher encryption technique implemented in JavaScript. The Caesar Cipher, also known as the Shift Cipher, is one of the simplest encryption methods where each letter in the plaintext message is shifted a certain number of positions down the alphabet.
Below is the JavaScript code for implementing the Caesar Cipher:
/**
* Encrypts a message using the Caesar Cipher technique
* @param {string} message - The plaintext message to be encrypted
* @param {number} shift - The number of positions each letter should be shifted
* @returns {string} - The encrypted ciphertext
*/
function caesarCipher(message, shift) {
let result = "";
for (let i = 0; i < message.length; i++) {
let char = message[i];
if (char.match(/[a-z]/i)) {
let code = message.charCodeAt(i);
if (code >= 65 && code <= 90) {
char = String.fromCharCode(((code - 65 + shift) % 26) + 65);
} else if (code >= 97 && code <= 122) {
char = String.fromCharCode(((code - 97 + shift) % 26) + 97);
}
}
result += char;
}
return result;
}
// Example usage
const plaintext = "Hello, World!";
const shift = 3;
const ciphertext = caesarCipher(plaintext, shift);
console.log(ciphertext); // Output: Khoor, Zruog!
The caesarCipher
function takes two parameters: message
(the plaintext message) and shift
(the number of positions each letter should be shifted). It initializes an empty string result
to store the encrypted message.
The function uses a for
loop to iterate over each character in the message
. If the character is a letter, it checks whether it is uppercase or lowercase using the regular expression /[a-z]/i
.
If the character is uppercase, it calculates its ASCII code by using the charCodeAt
method. Then it applies the shift using modular arithmetic to handle wrapping around the alphabet, and converts the modified code back to a character using String.fromCharCode
.
The same process is repeated for lowercase characters. Non-alphabetic characters are left unchanged.
Finally, the encrypted character is appended to the result
string. After iterating through all the characters in the message
, the function returns the encrypted ciphertext.
The Caesar Cipher is a simple and easy-to-understand encryption technique. Although it is relatively weak in terms of security, it provides a good starting point for beginners to understand encryption concepts. The implementation in JavaScript showcased in this article can be used as a foundation to build more complex encryption algorithms.