fork(6) download
  1. # Part I: Keyed Caesar
  2. # Example usage:
  3. # encrypt('Hello cipher world!',[1,19,6,4])
  4. # decrypt('MMRIYUIYCPJLRCSLYQBRV',[7,24,3])
  5. # Note the these functions are not strictly inverses of each other,
  6. # as the decryption function does not restore spaces or punctuation.
  7.  
  8. import re
  9.  
  10. def encrypt(text, key):
  11. # Turn text to uppercase
  12. text = text.upper()
  13. # Remove spaces and punctuation
  14. text = re.sub(r'[^A-Z]','',text)
  15. # Turn text into numbers, A=0, ...Z=25
  16. numbers = []
  17. for letter in text:
  18. numbers.append(ord(letter) - 65)
  19. # Apply the key:
  20. # For the nth letter of the plaintext, apply the nth key (modulo the key length)
  21. # And hence shift the number that many places
  22. encnum = []
  23. for (pos, num) in enumerate(numbers):
  24. shift = key[pos % len(key)]
  25. encnum.append((num + shift) % 26)
  26. # Turn the numbers back into letters
  27. enc = []
  28. for num in encnum:
  29. enc.append(chr(num + 65))
  30.  
  31. return ''.join(enc)
  32.  
  33. def decrypt(enc, key):
  34. # Turn encrypted text into numbers, A=0, ...Z=25
  35. encnum = []
  36. for letter in enc:
  37. encnum.append(ord(letter) - 65)
  38. # Apply the key in reverse:
  39. # For the nth letter of the plaintext, apply the nth key (modulo the key length)
  40. # And hence shift the number that many places in the negative direction
  41. numbers = []
  42. for (pos, num) in enumerate(encnum):
  43. shift = key[pos % len(key)]
  44. numbers.append((num - shift + 26) % 26)
  45. # Turn the numbers back into letters
  46. text = []
  47. for num in numbers:
  48. text.append(chr(num + 65))
  49.  
  50. return ''.join(text)
Success #stdin #stdout 0.04s 9440KB
stdin
Standard input is empty
stdout
Standard output is empty