Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. <script type="text/javascript">
  2. function Encrypt(){
  3. plaintext = document.getElementById("p").value.toLowerCase().replace(/[^a-z]/g, "");
  4. k = document.getElementById("k").value.toLowerCase().replace(/[^0-9 ]/g, "");
  5. keys = k.split(" ");
  6. // do some error checking
  7. if(plaintext.length < 1){ alert("please enter some plaintext (letters and numbers only)"); return; }
  8. if(plaintext.length % 2 == 1){ plaintext = plaintext + "x"; }
  9. if(keys.length != 4){ alert("key should consist of 4 integers"); return; }
  10. for(i=0;i<4;i++) keys[i] = keys[i]%26;
  11. ciphertext="";
  12. for(i=0; i<plaintext.length; i+=2){
  13. ciphertext += String.fromCharCode((keys[0]*(plaintext.charCodeAt(i)-97) + keys[1]*(plaintext.charCodeAt(i+1)-97))%26 + 97);
  14. ciphertext += String.fromCharCode((keys[2]*(plaintext.charCodeAt(i)-97) + keys[3]*(plaintext.charCodeAt(i+1)-97))%26 + 97);
  15. }
  16. document.getElementById("c").value = ciphertext;
  17. }
  18. function Decrypt(){
  19. ciphertext = document.getElementById("c").value.toLowerCase().replace(/[^a-z]/g, "");
  20. k = document.getElementById("k").value.toLowerCase().replace(/[^0-9 ]/g, "");
  21. keys = k.split(" ");
  22. // do some error checking
  23. if(ciphertext.length < 1){ alert("please enter some ciphertext (letters only, numbers should be spelled)"); return; }
  24. if(ciphertext.length % 2 == 1){ alert("ciphertext is not divisible by 2 (wrong algorithm?)"); return; }
  25. if(keys.length != 4){ alert("key should consist of 4 integers"); return; }
  26. for(i=0;i<4;i++) keys[i] = keys[i]%26;
  27. // calc inv matrix
  28. det = keys[0]*keys[3] - keys[1]*keys[2];
  29. det = ((det%26)+26)%26;
  30. di=0;
  31. for(i=0;i<26;i++){ if((det*i)%26 == 1) di = i; }
  32. if(di == 0){alert("could not invert, try different key"); return; }
  33. ikeys = new Array(4);
  34. ikeys[0] = (di*keys[3])%26; ikeys[1] = (-1*di*keys[1])%26;
  35. ikeys[2] = (-1*di*keys[2])%26; ikeys[3] = di*keys[0];
  36. for(i=0;i<4;i++){ if(ikeys[i] < 0) ikeys[i] += 26; }
  37. plaintext="";
  38. for(i=0; i<ciphertext.length; i+=2){
  39. plaintext += String.fromCharCode((ikeys[0]*(ciphertext.charCodeAt(i)-97) + ikeys[1]*(ciphertext.charCodeAt(i+1)-97))%26 + 97);
  40. plaintext += String.fromCharCode((ikeys[2]*(ciphertext.charCodeAt(i)-97) + ikeys[3]*(ciphertext.charCodeAt(i+1)-97))%26 + 97);
  41. }
  42. document.getElementById("p").value = plaintext;
  43. }
  44. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement