· 6 years ago · Feb 11, 2019, 06:18 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
40
41}
42
43function caesarEncrypt(message, key){
44 var encryptedResult = "";
45
46 for(var i = 0; i < message.length; i++){
47 // Get the character in the original message
48 var originalCharacter = message.charAt(i);
49
50 // If it's an alphabetical character, we'll compute the new
51 // shifted character and add it to the encrypted result
52 var alphabeticIndex = ALPHABET.indexOf(originalCharacter);
53 if(alphabeticIndex >= 0){
54 // Compute new index
55 var newIndex = alphabeticIndex + key + ALPHABET.length;
56 newIndex = newIndex % ALPHABET.length;
57
58 // Get the new character
59 var newCharacter = ALPHABET.charAt(newIndex);
60
61 // Add the new shifted character to the encrypted result
62 encryptedResult += newCharacter
63 }
64
65 // Otherwise we'll keep the original character
66 else{
67 encryptedResult += originalCharacter;
68 }
69 }
70
71 return encryptedResult;
72}