Cifra de Substituição Simples em Python


SUBMITTED BY: Guest

DATE: Dec. 3, 2013, 12:22 a.m.

FORMAT: Python

SIZE: 1.4 kB

HITS: 1827

  1. class SimpleSubstitution:
  2. def __init__(self):
  3. self.p_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  4. self.decrypting = False
  5. def cipher_alphabet(self, password):
  6. ''' (str) -> str
  7. Retorna um alfabeto cifrado iniciado com
  8. o texto da palavra chave password
  9. '''
  10. c_alphabet = []
  11. password = password.upper()
  12. for ch in password:
  13. if ch not in c_alphabet:
  14. c_alphabet.append(ch)
  15. idx = self.p_alphabet.find(ch)
  16. p_alphabet = self.p_alphabet[idx:] + self.p_alphabet[:idx]
  17. for ch in p_alphabet:
  18. if ch not in c_alphabet:
  19. c_alphabet.append(ch)
  20. return ''.join(c_alphabet)
  21. def encrypt(self, plaintext, password):
  22. '''(str, str) -> str
  23. Retorna o texto plano cifrado com a cifra de
  24. substituicao com a palavra chave password
  25. '''
  26. txt = ''
  27. p_alphabet = self.p_alphabet
  28. text = plaintext.replace(' ', '').upper()
  29. cipher = self.cipher_alphabet(password)
  30. if self.decrypting:
  31. p_alphabet, cipher = cipher, p_alphabet
  32. self.decrypting = False
  33. for ch in text:
  34. txt += cipher[p_alphabet.find(ch)]
  35. return txt
  36. def decrypt(self, ciphertext, password):
  37. '''(str, str) -> str
  38. Retorna o texto cifrado decifrado com a cifra de
  39. substituicao com a palavra chave password
  40. '''
  41. self.decrypting = True
  42. return self.encrypt(ciphertext, password)

comments powered by Disqus