· 8 years ago · Nov 16, 2017, 04:22 PM
1/*
2 * This program encrypts alphabetical messages using a
3 * Caesar cipher.
4 *
5 * Given a secret key k, this algorithm simply shifts each alphabetical
6 * character in the message up by k characters. If the shift pushes
7 * a character past 'z', it wraps back around to the beginning and
8 * becomes 'a'.
9 *
10 * For example, "abcz" encrypted with a key of 1 would become "bcda"
11 */
12
13var SECRET_KEY = 8;
14var ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
15
16function start()
17{
18 var originalMessage = readLine("Enter your message that you want to encrypt: ");
19 originalMessage = originalMessage.toUpperCase();
20
21 println("Encrypting with a Caesar Cipher...");
22 var encrypted = caesarEncrypt(originalMessage, SECRET_KEY);
23 println("Done:");
24
25 println(encrypted);
26}
27
28function caesarEncrypt(message, key)
29{
30 var encryptedResult = "";
31
32 for(var i = 0; i < message.length; i++)
33 {
34 // Get the character in the original message
35 var originalCharacter = message.charAt(i);
36
37 // If it's an alphabetical character, we'll compute the new
38 // shifted character and add it to the encrypted result
39 var alphabeticIndex = ALPHABET.indexOf(originalCharacter);
40 if(alphabeticIndex >= 0)
41 {
42 // Compute new index
43 var newIndex = alphabeticIndex + key;
44 newIndex = newIndex % ALPHABET.length;
45
46 // Get the new character
47 var newCharacter = ALPHABET.charAt(newIndex);
48
49 // Add the new shifted character to the encrypted result
50 encryptedResult += newCharacter
51 }
52
53 // Otherwise we'll keep the original character
54 else
55 {
56 encryptedResult += originalCharacter;
57 }
58 }
59
60 return encryptedResult;
61}