{"id":309,"date":"2018-03-07T20:52:49","date_gmt":"2018-03-07T20:52:49","guid":{"rendered":"http:\/\/loop.cs.mtu.edu\/?p=309"},"modified":"2023-11-06T17:29:18","modified_gmt":"2023-11-06T17:29:18","slug":"traditional-caesar-cipher","status":"publish","type":"post","link":"https:\/\/loop.cs.mtu.edu\/index.php\/2018\/03\/07\/traditional-caesar-cipher\/","title":{"rendered":"Traditional Caesar Cipher"},"content":{"rendered":"<p><span style=\"font-weight: 400;\">Julius Caesar was worried. \u00a0He needed to get a letter back to Cicero, the consul of Rome, but it had to travel through enemy territory. \u00a0His solution? \u00a0Shift every letter to the third letter after it, wrapping around so that A became D and Y became B.\u00a0 Here we&#8217;ll implement his idea in a computer program.<\/span><!--more--><\/p>\n<p><span style=\"font-weight: 400;\">To have fun with the traditional Caesar Cipher, we need to be able to read in and print out files. \u00a0We\u2019ll do this using a Scanner and PrintWriter for standard IO, with the methods readFile() and printFile().\u00a0 To learn more about file I\/O, click <a href=\"http:\/\/loop.cs.mtu.edu\/index.php\/2018\/03\/07\/files-that-make-you-smile\/\"><span style=\"color: blue;\">here.<\/span><\/a><\/span><\/p>\n<h2><strong>Shift Cipher &#8211; Encode or Decode<\/strong><\/h2>\n<p><span style=\"font-weight: 400;\">The shift cipher is the real workhorse of the Caesar Cipher. \u00a0It takes a string, converts it to a character array, and does the encryption.<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"eclipse\">public String shiftCipher(String input, int shift) {\r\n  String coded = \"\";\r\n  char [] message = input.toCharArray();\r\n  for (int i = 0; i &lt; message.length; i++) {\r\n    char letter = message[i];\r\n    letter = (char) cipherUppercase(letter, shift);\r\n    letter = (char) cipherLowercase(letter, shift);\r\n    message[i] = letter;\r\n  }\r\n  for (int i = 0; i &lt; message.length; i++) {\r\n    coded += message[i];\r\n  }\r\n  return coded;\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p><span style=\"font-weight: 400;\">We make an empty string to hold the return value of the encrypted\/decrypted message. \u00a0Then we convert the input to a character array. \u00a0In the loop, we visit each element of the array and store it as an int &#8211; this is allowed for any ASCII character.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Dive deep: \u00a0Learn more about <a href=\"http:\/\/loop.cs.mtu.edu\/index.php\/2018\/03\/04\/ascii-fun\/\"><span style=\"color: blue;\">ASCII characters here!<\/span><\/a><\/span><\/p>\n<p><span style=\"font-weight: 400;\">Then we call helper methods to perform the shift. \u00a0Calling both cipherUppercase() and cipherLowercase() is fine here because at most one of them will actually modify the value of letter. \u00a0We convert the integer value returned from these helper methods back into a character by casting. \u00a0After the letter is modified (if needed), it is stored back in the array. \u00a0Then we loop through the array again, adding its values to the string <\/span><i><span style=\"font-weight: 400;\">coded<\/span><\/i><span style=\"font-weight: 400;\"> which we then return.<\/span><\/p>\n<h2><strong>Cipher Uppercase<\/strong><\/h2>\n<p><span style=\"font-weight: 400;\">This helper method checks if the character is uppercase, performs a cipher if it is, and just returns the value unchanged if it isn\u2019t.<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"eclipse\">private int cipherUppercase(char letter, int shift) {\r\n  final int a = 65; \/\/ ASCII value for 'A'\r\n  final int z = 90; \/\/ ASCII value for 'Z'\r\n  int coded = letter;\r\n  if ((a &lt;= letter) &amp;&amp; (letter &lt;= z)) {\r\n      \/\/ Get the value of the letter on a scale of 0 to 25\r\n      int azLetter = letter - a; \r\n      int newLetter = azLetter + shift; \/\/ Add the shift\r\n      int remainder = newLetter % 26; \/\/ Get the remainder\r\n      coded = a + remainder; \/\/ Return to ASCII scale\r\n  }\r\n  return coded;\r\n}<\/pre>\n<p><span style=\"font-weight: 400;\">The first thing we notice in this method is the \u201cfinal\u201d before the first two ints. This \u201cfinal\u201d means we cannot modify these variables by giving them another value, so the value given when they are declared is their final value. \u00a0Both final ints are storing ASCII values, so we don\u2019t want to modify them. \u00a0Usually, we do want our variables to be modifiable, so we rarely use final.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">We assign <\/span><i><span style=\"font-weight: 400;\">letter <\/span><\/i><span style=\"font-weight: 400;\">to another variable before entering the if-statement. \u00a0This lets us modify the value comfortably and avoids changing a parameter variable. \u00a0Then we subtract <\/span><i><span style=\"font-weight: 400;\">a<\/span><\/i><span style=\"font-weight: 400;\"> from the letter and add the shift. \u00a0We get the remainder by using the modulus operator which we represent with the percent sign. \u00a0Then we add the remainder to <\/span><i><span style=\"font-weight: 400;\">a<\/span><\/i><span style=\"font-weight: 400;\">, and store this in the <\/span><i><span style=\"font-weight: 400;\">coded<\/span><\/i><span style=\"font-weight: 400;\"> variable. \u00a0These steps work whether the sum (<\/span><i><span style=\"font-weight: 400;\">letter<\/span><\/i><span style=\"font-weight: 400;\"> + <\/span><i><span style=\"font-weight: 400;\">shift<\/span><\/i><span style=\"font-weight: 400;\">) is a letter or a non-letter because the remainder for a letter is the same as the remainder for that value plus 26. \u00a0Finally we return the coded value of the letter.<\/span><\/p>\n<h2><strong>Cipher Lowercase<\/strong><\/h2>\n<p><span style=\"font-weight: 400;\">It\u2019s pretty much the same as CipherUppercase(), except the values for a and z are changed to match the lowercase ASCII characters:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"eclipse\">private int cipherLowercase(char letter, int shift) {\r\n  final int a = 97; \/\/ ASCII value for 'a'\r\n  final int z = 122; \/\/ ASCII value for 'z'\r\n  int coded = letter;\r\n  if ((a &lt;= letter) &amp;&amp; (letter &lt;= z)) {\r\n      \/\/ Get the value of the letter on a scale of 0 to 25\r\n      int azLetter = letter - a; \r\n      int newLetter = azLetter + shift; \/\/ Add the shift\r\n      int remainder = newLetter % 26; \/\/ Get the remainder\r\n      coded = a + remainder; \/\/ Return to ASCII scale\r\n  }\r\n  return coded;\r\n}<\/pre>\n<h2><strong>Main &#8211; Let\u2019s watch it run<\/strong><\/h2>\n<p><span style=\"font-weight: 400;\">This is a pretty standard main method. \u00a0<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"eclipse\">public static void main(String[] args) {\r\n  TraditionalCaesarCipher self = new TraditionalCaesarCipher();\r\n  String original = self.readFile(\"TradCaesarCipherABC1Orig.txt\");\r\n  String encrypted = self.shiftCipher(original, 3);\r\n  self.printFile(encrypted, \"TradCaesarCipherABC1Coded.txt\");\r\n}<\/pre>\n<p><span style=\"font-weight: 400;\">We create an instance of our current class and call it <\/span><i><span style=\"font-weight: 400;\">self<\/span><\/i><span style=\"font-weight: 400;\">. \u00a0Then we read in the original file, perform the cipher, and print out the results to the console and the new file.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">One sample run is shown below:<\/span><\/p>\n<figure id=\"attachment_313\" aria-describedby=\"caption-attachment-313\" style=\"width: 559px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-313 size-full\" src=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TradCaesarCipherEx1.jpg\" alt=\"\" width=\"559\" height=\"237\" srcset=\"https:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TradCaesarCipherEx1.jpg 559w, https:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TradCaesarCipherEx1-300x127.jpg 300w\" sizes=\"auto, (max-width: 559px) 100vw, 559px\" \/><figcaption id=\"caption-attachment-313\" class=\"wp-caption-text\">Original<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<figure id=\"attachment_314\" aria-describedby=\"caption-attachment-314\" style=\"width: 767px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-314 size-full\" src=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TradCaesarCipherEx1c.jpg\" alt=\"\" width=\"767\" height=\"334\" srcset=\"https:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TradCaesarCipherEx1c.jpg 767w, https:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TradCaesarCipherEx1c-300x131.jpg 300w\" sizes=\"auto, (max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px\" \/><figcaption id=\"caption-attachment-314\" class=\"wp-caption-text\">Output<\/figcaption><\/figure>\n<p>&nbsp;<\/p>\n<p>You can try making your own files, as well as downloading the files below to run with it:<\/p>\n<p><a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TraditionalCaesarCipher.txt\"><span style=\"color: blue;\"><span style=\"color: #008000;\">TraditionalCaesarCipher.txt<\/span><\/span><\/a><\/p>\n<p><a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TraditionalCaesarCipher.java\"><span style=\"color: blue;\"><span style=\"color: #ff6600;\">TraditionalCaesarCipher.java<\/span><\/span><\/a><\/p>\n<p><a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TradCaesarCipher1Coded.txt\"><span style=\"color: blue;\">TradCaesarCipher1Coded<\/span><\/a><\/p>\n<p><a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TradCaesarCipher1Orig.txt\"><span style=\"color: blue;\">TradCaesarCipher1Orig<\/span><\/a><\/p>\n<p><a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TradCaesarCipherABC1Coded.txt\"><span style=\"color: blue;\">TradCaesarCipherABC1Coded<\/span><\/a><\/p>\n<p><a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/TradCaesarCipherABC1Orig.txt\"><span style=\"color: blue;\">TradCaesarCipherABC1Orig<\/span><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Julius Caesar was worried. \u00a0He needed to get a letter back to Cicero, the consul of Rome, but it had to travel through enemy territory. \u00a0His solution? \u00a0Shift every letter to the third letter after it, wrapping around so that A became D and Y became B.\u00a0 Here we&#8217;ll implement his idea in a computer &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/loop.cs.mtu.edu\/index.php\/2018\/03\/07\/traditional-caesar-cipher\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Traditional Caesar Cipher&#8221;<\/span><\/a><\/p>\n","protected":false},"author":4,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[10,31],"tags":[27,21,26,18,25,24,11],"class_list":["post-309","post","type-post","status-publish","format-standard","hentry","category-intermediate","category-java","tag-arrays","tag-ascii","tag-caesar-cipher","tag-cryptography","tag-cs1121","tag-intermediate","tag-loops"],"_links":{"self":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts\/309","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/comments?post=309"}],"version-history":[{"count":12,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts\/309\/revisions"}],"predecessor-version":[{"id":361,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts\/309\/revisions\/361"}],"wp:attachment":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/media?parent=309"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/categories?post=309"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/tags?post=309"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}