della_porta.py


SUBMITTED BY: siriarah

DATE: Nov. 19, 2019, 9:29 p.m.

FORMAT: Python 3

SIZE: 2.1 kB

HITS: 591

  1. # -*- coding: utf-8 -*-
  2. from cipher import Cipher
  3. class DellaPorta(Cipher):
  4. ''' Cifra criptografica de Giambattista della Porta '''
  5. def __init__(self):
  6. '''
  7. keys - chaves para determinar o deslocamento da cifra
  8. plain - alfabeto fixo
  9. cipher - alfabeto a ser deslocado
  10. '''
  11. self.keys = {
  12. 'A': 0, 'B': 0, 'C': 1, 'D': 1, 'E': 2, 'F': 2,
  13. 'G': 3, 'H': 3, 'I': 4, 'J': 4, 'K': 5, 'L': 5,
  14. 'M': 6, 'N': 6, 'O': 7, 'P': 7, 'Q': 8, 'R': 8,
  15. 'S': 9, 'T': 9, 'U': 10, 'V': 10, 'W': 11,
  16. 'X': 11, 'Y': 12, 'Z': 12
  17. }
  18. self.plain = 'ABCDEFGHIJKLM'
  19. self.cipher = 'NOPQRSTUVWXYZ'
  20. def shift(self, key):
  21. ''' Desloca o alfabeto '''
  22. shift = self.keys[key]
  23. return self.cipher[shift:] + self.cipher[:shift]
  24. def repeat_password(self, password, length):
  25. ''' Repete a password ate o tamanho do texto plano '''
  26. new_pass = password * int((length/len(password)))
  27. length -= len(new_pass)
  28. if length:
  29. new_pass += password[:length]
  30. return new_pass
  31. def encrypt(self, plaintext, password):
  32. ''' Retorna o texto cifrado '''
  33. ciphertext = ''
  34. plaintext = self.format_str(plaintext)
  35. plainalphabet = self.plain
  36. password = self.format_str(
  37. self.repeat_password(password, len(plaintext))
  38. )
  39. for idx in range(len(plaintext)):
  40. char = plaintext[idx]
  41. cipheralphabet = self.shift(password[idx])
  42. if char in plainalphabet:
  43. idchar = plainalphabet.find(char)
  44. ciphertext += cipheralphabet[idchar]
  45. elif char in cipheralphabet:
  46. idchar = cipheralphabet.find(char)
  47. ciphertext += plainalphabet[idchar]
  48. return ciphertext
  49. def decrypt(self, ciphertext, password):
  50. ''' Retorna o texto decifrado '''
  51. return self.encrypt(ciphertext, password)

comments powered by Disqus