· 7 years ago · Sep 12, 2018, 01:08 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
30 println("Done:");
31
32 println(decrypted);
33}
34
35
36function caesarDecrypt(encryptedMessage, key){
37 // Write a function that returns the decrypted message
38 // Hint--use the caesarEncrypt method!
39 // Decrypting is the same process as encrypting,
40 // the key just needs to shift the letters back instead of forward
41
42}
43
44function caesarEncrypt(message, key){
45 var encryptedResult = "";
46
47 for(var i = 0; i < message.length; i++){
48 // Get the character in the original message
49 var originalCharacter = message.charAt(i);
50
51 // If it's an alphabetical character, we'll compute the new
52 // shifted character and add it to the encrypted result
53 var alphabeticIndex = ALPHABET.indexOf(originalCharacter);
54 if(alphabeticIndex >= 0){
55 // Compute new index
56 var newIndex = alphabeticIndex + key + ALPHABET.length;
57 newIndex = newIndex % ALPHABET.length;
58
59 // Get the new character
60 var newCharacter = ALPHABET.charAt(newIndex);
61
62 // Add the new shifted character to the encrypted result
63 encryptedResult += newCharacter
64 }
65
66 // Otherwise we'll keep the original character
67 else{
68 encryptedResult += originalCharacter;
69 }
70 }
71
72 return encryptedResult;
73}