Cifra ou disco de Alberti em Python


SUBMITTED BY: Guest

DATE: April 23, 2014, 3:50 p.m.

FORMAT: Python

SIZE: 2.6 kB

HITS: 1467

  1. class Alberti:
  2. def shift(self, shift):
  3. ''' (int) -> None
  4. Desloca o disco movel a quantidade de elementos em shift.
  5. '''
  6. shift = -shift
  7. self.movable_disk = self.movable_disk[shift:] + self.movable_disk[:shift]
  8. def set_fixed_disk(self, plain_alphabet):
  9. ''' (str) -> None
  10. Configura o alfabeto do disco fixo com o texto de plain_alphabet.
  11. '''
  12. self.fixed_disk = plain_alphabet.upper()
  13. def set_movable_disk(self, cipher_alphabet):
  14. ''' (str) -> None
  15. Configura o alfabeto do disco movel com o texto de cipher_alphabet.
  16. '''
  17. self.movable_disk = cipher_alphabet.lower()
  18. def set_keys(self, fixed_key, movable_key):
  19. ''' (char, charstr) -> None
  20. Configura as chaves do disco fixo e do disco movel;
  21. Desloca o disco movel de acordo com as chaves.
  22. '''
  23. self.set_fixed_key(fixed_key)
  24. self.set_movable_key(movable_key)
  25. fixed_id = self.fixed_disk.find(self.fixed_key)
  26. movable_id = self.movable_disk.find(self.movable_key)
  27. shift = fixed_id - movable_id
  28. self.shift(shift)
  29. def encrypt(self, plaintext, shift = 0, decrypt = False):
  30. ''' (str, [int], [bool]) -> str
  31. Cifra o plaintext com a cifra de Alberti.
  32. '''
  33. ciphertext = ''
  34. for ch in plaintext:
  35. if ch.isupper():
  36. #letra maiuscula
  37. self.set_keys(ch, self.movable_key)
  38. elif ch.isdigit():
  39. #numero
  40. movable_key = self.movable_disk[self.fixed_disk.find(ch)]
  41. self.set_keys(self.fixed_key, movable_key)
  42. else:
  43. #letra minuscula
  44. if decrypt:
  45. #decifrando
  46. i = self.movable_disk.find(ch)
  47. ch = self.fixed_disk[i].lower()
  48. else:
  49. #cifrando
  50. i = self.fixed_disk.find(ch.upper())
  51. ch = self.movable_disk[i]
  52. if shift:
  53. #deslocamento
  54. self.shift(shift)
  55. ciphertext += ch
  56. return ciphertext
  57. def decrypt(self, ciphertext, shift = 0):
  58. ''' (str, [int]) -> str
  59. Decifra utilizando a cifra de Alberti.
  60. '''
  61. #return self.encrypt(ciphertext, shift, True)
  62. text = ''
  63. plaintext = self.encrypt(ciphertext, shift, True)
  64. for ch in plaintext:
  65. if ch.islower():
  66. text += ch
  67. return text
  68. def set_fixed_key(self, fixed_key):
  69. ''' (char) -> None
  70. Configura a chave do disco fixo.
  71. '''
  72. self.fixed_key = fixed_key.upper()
  73. def set_movable_key(self, movable_key):
  74. ''' (char) -> None
  75. Configura a chave do disco movel.
  76. '''
  77. self.movable_key = movable_key.lower()

comments powered by Disqus