-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaesarCipher.js
More file actions
66 lines (59 loc) · 2.04 KB
/
caesarCipher.js
File metadata and controls
66 lines (59 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Caesar Cipher - Encryption and Decryption
*
* The Caesar Cipher is a simple substitution cipher where each letter in the plaintext
* is shifted a fixed number of places down or up the alphabet.
*
* Example: With a shift of 3, 'A' becomes 'D', 'B' becomes 'E', etc.
*/
/**
* Encrypts a message using Caesar Cipher
* @param {string} message - The text to encrypt
* @param {number} shift - The number of positions to shift (1-25)
* @returns {string} - The encrypted text
*/
function encrypt(message, shift) {
let encrypted = '';
// Normalize shift to 0-25 range
shift = shift % 26;
for (let i = 0; i < message.length; i++) {
const char = message[i];
// Check if character is uppercase letter
if (char >= 'A' && char <= 'Z') {
// Get position in alphabet (0-25)
const position = char.charCodeAt(0) - 'A'.charCodeAt(0);
// Apply shift and wrap around using modulo
const newPosition = (position + shift) % 26;
// Convert back to character
encrypted += String.fromCharCode(newPosition + 'A'.charCodeAt(0));
}
// Check if character is lowercase letter
else if (char >= 'a' && char <= 'z') {
// Get position in alphabet (0-25)
const position = char.charCodeAt(0) - 'a'.charCodeAt(0);
// Apply shift and wrap around using modulo
const newPosition = (position + shift) % 26;
// Convert back to character
encrypted += String.fromCharCode(newPosition + 'a'.charCodeAt(0));
}
// Non-alphabetic characters remain unchanged
else {
encrypted += char;
}
}
return encrypted;
}
/**
* Decrypts a Caesar Cipher message
* @param {string} encrypted - The encrypted text
* @param {number} shift - The shift value used for encryption
* @returns {string} - The decrypted text
*/
function decrypt(encrypted, shift) {
// Decryption is just encryption with negative shift
return encrypt(encrypted, -shift);
}
// Export for use in other modules
if (typeof module !== 'undefined' && module.exports) {
module.exports = { encrypt, decrypt };
}