cipher.py


SUBMITTED BY: siriarah

DATE: Dec. 10, 2019, 3:01 p.m.

UPDATED: Feb. 19, 2022, 7:01 p.m.

FORMAT: Python 3

SIZE: 2.1 kB

HITS: 812

  1. # -*- coding: utf-8 -*-
  2. """ Classe com metodos basicos para cifras classicas """
  3. class Cipher(object):
  4. """ Classe base para as cifras classicas """
  5. plain_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  6. plain_alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  7. def format_str(self, text):
  8. '''Retorna text sem espacos e em maiusculas'''
  9. return text.replace(' ', '').upper()
  10. def shift_alphabet(self, alphabet, shift):
  11. '''Retorna alphabet com deslocamento de valor shift'''
  12. return alphabet[shift:] + alphabet[:shift]
  13. def create_square(self, key = '', alphanum = False, replace = ['J', 'I'], sequence = False):
  14. """Retorna um alfabeto numa matriz de num x num
  15. Por padrao, retorna uma matriz formada pelo alfabeto ABCDEFGHIKLMNOPQRSTUVWXYZ
  16. """
  17. square = []
  18. if alphanum:
  19. num = 6
  20. alfabeto = self.plain_alphanum
  21. replace = ['', '']
  22. else:
  23. num = 5
  24. alfabeto = self.plain_alphabet
  25. alfabeto = self.create_alphabet(key, alfabeto, replace, sequence)
  26. for idx in range(0, len(alfabeto), num):
  27. square.append(alfabeto[idx:idx + num])
  28. return square
  29. def create_alphabet(self, key = '', alfabeto = plain_alphabet, replace = ['', ''], sequence = False):
  30. '''Retorna um alfabeto com key como chave e no inicio do alfabeto'''
  31. if key:
  32. key = key.upper()
  33. temp = ''
  34. for ch in key:
  35. if ch not in temp:
  36. temp += ch
  37. key = temp
  38. if replace[0] in key:
  39. key = key.replace(replace[0], replace[1])
  40. if sequence:
  41. idx = alfabeto.index(key[-1])
  42. alfabeto = self.shift_alphabet(alfabeto, idx)
  43. cipher = alfabeto.replace(replace[0], '')
  44. for ch_key in key:
  45. if ch_key in cipher:
  46. cipher = cipher.replace(ch_key, '')
  47. return key + cipher

comments powered by Disqus