fork(5) download
  1. <?php
  2.  
  3. # Part I: Keyed Caesar
  4. # Example usage:
  5. # encrypt('Hello cipher world!',array(1,19,6,4));
  6. # decrypt('MMRIYUIYCPJLRCSLYQBRV',array(7,24,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) {
  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. $encnum[] = ($num + $shift) % 26;
  29. }
  30. # Turn the numbers back into letters
  31. $enc = array();
  32. foreach($encnum as $num) {
  33. $enc[] = chr($num + 65);
  34. }
  35.  
  36. return implode('', $enc);
  37. }
  38.  
  39. function decrypt($enc, $key) {
  40. # Turn encrypted text into an array
  41. $enc = str_split($enc);
  42. # Turn encrypted text into numbers, A=0, ...Z=25
  43. $encnum = array();
  44. foreach($enc as $letter) {
  45. $encnum[] = ord($letter) - 65;
  46. }
  47. # Apply the key in reverse:
  48. # For the nth letter of the plaintext, apply the nth key (modulo the key length)
  49. # And hence shift the number that many places in the negative direction
  50. $numbers = array();
  51. foreach($encnum as $pos => $num) {
  52. $shift = $key[$pos % count($key)];
  53. $numbers[] = (($num - $shift)+26) % 26;
  54. }
  55. # Turn the numbers back into letters
  56. $text = array();
  57. foreach($numbers as $num) {
  58. $text[] = chr($num + 65);
  59. }
  60.  
  61. return implode('', $text);
  62. }
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
Standard output is empty