· 6 years ago · Feb 27, 2019, 02:02 PM
1/*
2 * Write a program that asks the user for an encrypted message
3 * and Caesar cipher key, and decrypts the message.
4 *
5 * Use the function caesarEncrypt! What key value do you need to
6 * pass this function to decrypt your message?
7 *
8 */
9
10
11var ALPHABET = "abcdefghijklmnopqrstuvwxyz";
12
13function start(){
14 var originalMessage = readLine("Enter the message you would like to encrypt: ");
15 originalMessage = originalMessage.toLowerCase();
16
17 var secretKey = readInt("Enter the number you'd like to shift each character by: ");
18
19 var encryptedMessage = caesarEncrypt(originalMessage, secretKey);
20 println("");
21 println("Encrypted message: " + encryptedMessage);
22
23 println("");
24 println("Decrypting message...");
25 println("");
26
27 // You will need to write caesarDecrypt below
28 var decrypted = caesarDecrypt(encryptedMessage, secretKey);
29 println("Done:");
30
31 println(decrypted);
32}
33
34
35function caesarDecrypt(encryptedMessage, key){
36 // Write a function that returns the decrypted message
37 // Hint--use the caesarEncrypt method!
38 // Decrypting is the same process as encrypting,
39 // the key just needs to shift the letters back instead of forward
40var decryptedResult = "";
41
42 for(var i = 0; i < encryptedMessage.length; i++){
43 // Get the character in the original message
44 var originalCharacter = encryptedMessage.charAt(i);
45
46 // If it's an alphabetical character, we'll compute the new
47 // shifted character and add it to the decrypted result
48 var alphabeticIndex = ALPHABET.indexOf(originalCharacter);
49 if(alphabeticIndex >= 0){
50 // Compute new index
51 var newIndex = alphabeticIndex + key + ALPHABET.length;
52 newIndex = newIndex % ALPHABET.length;
53
54 // Get the new character
55 var newCharacter = ALPHABET.charAt(newIndex);
56
57 // Add the new shifted character to the encrypted result
58 decryptedResult += newCharacter
59 }
60
61 // Otherwise we'll keep the original character
62 else{
63 decryptedResult += originalCharacter;
64 }
65 }
66
67 return decryptedResult;
68}
69
70function caesarEncrypt(message, key){
71 var encryptedResult = "";
72
73 for(var i = 0; i < message.length; i++){
74 // Get the character in the original message
75 var originalCharacter = message.charAt(i);
76
77 // If it's an alphabetical character, we'll compute the new
78 // shifted character and add it to the encrypted result
79 var alphabeticIndex = ALPHABET.indexOf(originalCharacter);
80 if(alphabeticIndex >= 0){
81 // Compute new index
82 var newIndex = alphabeticIndex + key + ALPHABET.length;
83 newIndex = newIndex % ALPHABET.length;
84
85 // Get the new character
86 var newCharacter = ALPHABET.charAt(newIndex);
87
88 // Add the new shifted character to the encrypted result
89 encryptedResult += newCharacter
90 }
91
92 // Otherwise we'll keep the original character
93 else{
94 encryptedResult += originalCharacter;
95 }
96 }
97
98 return encryptedResult;
99}