fork download
  1. <?php
  2.  
  3. # Part II: Hardened Keyed Caesar
  4. # Example usage:
  5. # encrypt('Ciphers are hard!',array(1,2,3,4),3);
  6. # decrypt('GQBXULQCTKROFV',array(1,2,3,4),3);
  7. # Note the these functions are not strictly inverses of each other,
  8. # as the decryption function does not restore spaces or punctuation.
  9.  
  10. function encrypt($text, $key, $inc) {
  11. # Turn text to uppercase
  12. $text = strtoupper($text);
  13. # Remove spaces and punctuation
  14. $text = preg_replace('/[^A-Z]/','',$text);
  15. # Turn text into an array
  16. $text = str_split($text);
  17. # Turn text into numbers, A=0, ...Z=25
  18. $numbers = array();
  19. foreach($text as $letter) {
  20. $numbers[] = ord($letter) - 65;
  21. }
  22. # Apply the key:
  23. # For the nth letter of the plaintext, apply the nth key (modulo the key length)
  24. # And hence shift the number that many places
  25. $encnum = array();
  26. foreach($numbers as $pos => $num) {
  27. $shift = $key[$pos % count($key)];
  28. # Add the incerement times the position (starting at 1)
  29. $shift += (($pos + 1) * $inc) % 26;
  30. $encnum[] = ($num + $shift) % 26;
  31. }
  32. # Turn the numbers back into letters
  33. $enc = array();
  34. foreach($encnum as $num) {
  35. $enc[] = chr($num + 65);
  36. }
  37.  
  38. return implode('', $enc);
  39. }
  40.  
  41. function decrypt($enc, $key, $inc) {
  42. # Turn encrypted text into an array
  43. $enc = str_split($enc);
  44. # Turn encrypted text into numbers, A=0, ...Z=25
  45. $encnum = array();
  46. foreach($enc as $letter) {
  47. $encnum[] = ord($letter) - 65;
  48. }
  49. # Apply the key in reverse:
  50. # For the nth letter of the plaintext, apply the nth key (modulo the key length)
  51. # And hence shift the number that many places in the negative direction
  52. $numbers = array();
  53. foreach($encnum as $pos => $num) {
  54. $shift = $key[$pos % count($key)];
  55. # Add the incerement times the position (starting at 1)
  56. $shift += (($pos + 1) * $inc) % 26;
  57. $numbers[] = (($num - $shift)+52) % 26;
  58. }
  59. # Turn the numbers back into letters
  60. $text = array();
  61. foreach($numbers as $num) {
  62. $text[] = chr($num + 65);
  63. }
  64.  
  65. return implode('', $text);
  66. }
Success #stdin #stdout 0.01s 20520KB
stdin
Standard input is empty
stdout
Standard output is empty