fork(2) download
  1. # Part II: Hardened Keyed Caesar
  2. # Example usage:
  3. # encrypt('Ciphers are hard!',[1,2,3,4],3);
  4. # decrypt('GQBXULQCTKROFV',[1,2,3,4],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, inc):
  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. # Add the incerement times the position (starting at 1)
  26. shift += ((pos + 1) * inc) % 26
  27. encnum.append((num + shift) % 26)
  28. # Turn the numbers back into letters
  29. enc = []
  30. for num in encnum:
  31. enc.append(chr(num + 65))
  32.  
  33. return ''.join(enc)
  34.  
  35. def decrypt(enc, key, inc):
  36. # Turn encrypted text into numbers, A=0, ...Z=25
  37. encnum = []
  38. for letter in enc:
  39. encnum.append(ord(letter) - 65)
  40. # Apply the key in reverse:
  41. # For the nth letter of the plaintext, apply the nth key (modulo the key length)
  42. # And hence shift the number that many places in the negative direction
  43. numbers = []
  44. for (pos, num) in enumerate(encnum):
  45. shift = key[pos % len(key)]
  46. # Add the incerement times the position (starting at 1)
  47. shift += ((pos + 1) * inc) % 26
  48. numbers.append((num - shift + 52) % 26)
  49. # Turn the numbers back into letters
  50. text = []
  51. for num in numbers:
  52. text.append(chr(num + 65))
  53.  
  54. return ''.join(text)
Success #stdin #stdout 0.09s 10088KB
stdin
Standard input is empty
stdout
Standard output is empty