willyb321

caesar cipher

Jun 9th, 2016
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 2.04 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3.  
  4. <body>
  5.     <form action="#" method="get" onsubmit="return false;" _lpchecked="1">
  6.         <label for="text">Text:</label>
  7.         <textarea id="text" cols="50" rows="10">THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.</textarea>
  8.         <br>
  9.         <label for="shift">Shift:</label>
  10.         <input type="text" id="shift" value="13" />
  11.         <br>
  12.         <input type="button" value="Encrypt" onclick="doCrypt(false);" />
  13.         <input type="button" value="Decrypt" onclick="doCrypt(true);" />
  14.     </form>
  15.     <script>
  16.     function doCrypt(isDecrypt) { // this func figures out the shift value, and also the text
  17.         var shift = parseInt(document.getElementById("shift").value); // find how many chars to shift by.
  18.         //var shift = shiftText, 10; // parsing the number from the text, is now done by the prev line
  19.         if (shift < 0 || shift >= 26) { //make sure shift from 0-26
  20.             alert("Shift is out of range");
  21.             return; //break the function
  22.         }
  23.         if (isDecrypt) // if its already decrypted
  24.             shift = (26 - shift) % 26; // figure out what the shift was.
  25.         var textElem = document.getElementById("text"); // figure out what the text actually is.
  26.         textElem.value = caesarShift(textElem.value, shift); // un-decrypt it.
  27.     }
  28.  
  29.     function caesarShift(text, shift) {
  30.         var result = ""; // used to display the en/de crypted text
  31.         for (var i = 0; i < text.length; i++) { // a for loop to make sure that the text is fully changed.
  32.            var c = text.charCodeAt(i); // used to determine what the character is according to the computer
  33.            if (c >= 65 && c <= 90) result += String.fromCharCode((c - 65 + shift) % 26 + 65); // Uppercase
  34.             else if (c >= 97 && c <= 122) result += String.fromCharCode((c - 97 + shift) % 26 + 97); // Lowercase
  35.             else result += text.charAt(i); // Copy
  36.         }
  37.         return result; // display the result in the text box that text was entered into
  38.     }
  39.     </script>
  40. </body>
  41.  
  42. </html>
Advertisement
Add Comment
Please, Sign In to add comment