Advertisement
BumbleguppysRevenant

Simple Substitution Cypher

Feb 11th, 2012
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function substitutionCipher()
  2. {
  3.     var str = prompt("Enter a string to encrypt","").toUpperCase().replace(/[^A-Z]*/g,'');
  4.     var pwd = prompt("Enter you Little Orphan Annie secret password","").toUpperCase().replace(/[^A-Z]*/g,'');
  5.     var endecrypted = '';
  6.     var alphabet = cypherbet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  7.     var charBox = '';
  8.     var i = len = 0;
  9.     var encryptFlag = confirm('To encrypt, click OK. To decrypt click CANCEL.');
  10.    
  11.     /* strip duplicate letters from the password */
  12.     for(i = 0, len = pwd.length; i < len; i++)
  13.     {
  14.         if(!charBox || charBox.indexOf(pwd.charAt(i)) < 0 )
  15.         {
  16.             charBox += pwd.charAt(i);
  17.             cypherbet = cypherbet.replace(pwd.charAt(i),'');  /*remove the password character from the cyphered alphabet for now*/
  18.         }
  19.     }
  20.     pwd = charBox;   /*replace the password with the result of stripping redundant characters from the password*/
  21.    
  22.  
  23.    
  24.     /*prepend the password to the cyphered alphabet*/
  25.     cypherbet = pwd + cypherbet;
  26.    
  27.    
  28.     for(i = 0, len = str.length; i < len; i++)
  29.     {
  30.         if(encryptFlag)
  31.         {
  32.             if(endecrypted && i % 5 == 0)
  33.             {
  34.                 endecrypted += ' ';
  35.             }
  36.             endecrypted += cypherbet.charAt(alphabet.indexOf(str.charAt(i)));
  37.         }else{
  38.             endecrypted += alphabet.charAt(cypherbet.indexOf(str.charAt(i)));
  39.         }
  40.     }
  41.  
  42.     alert(endecrypted);
  43. }
  44.  
  45. substitutionCipher();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement