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: 3.0 kB

HITS: 639

  1. # -*- coding: utf-8 -*-
  2. from random import shuffle
  3. """ Classe com metodos basicos para cifras classicas """
  4. class Cipher(object):
  5. """ Classe base para as cifras classicas """
  6. plain_alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  7. plain_alphanum = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  8. def format_str(self, text):
  9. '''Retorna text sem espacos e em maiusculas'''
  10. return text.replace(' ', '').upper()
  11. def shift_alphabet(self, alphabet, shift):
  12. '''Retorna alphabet com deslocamento de valor shift'''
  13. return alphabet[shift:] + alphabet[:shift]
  14. def create_square(self, alphabet = [], key = '', alphanum = False, replace = ['J', 'I'], sequence = False):
  15. """ Retorna um alfabeto numa matriz de num x num
  16. Por padrao, retorna uma matriz formada pelo alfabeto ABCDEFGHIKLMNOPQRSTUVWXYZ
  17. Se key, retorna um square com key iniciando o square
  18. alphanum square com letras e numeros
  19. replace letras a serem trocadas, so funciona se for usado somente o alfabeto
  20. sequence se True continua a preencher o square a partir do ultimo caracter da key
  21. """
  22. square = []
  23. if alphabet:
  24. if alphanum:
  25. replace = ['', '']
  26. # num = 5
  27. alfabeto = alphabet
  28. elif alphanum:
  29. # num = 6
  30. alfabeto = self.plain_alphanum
  31. replace = ['', '']
  32. else:
  33. # num = 5
  34. alfabeto = self.plain_alphabet
  35. alfabeto = self.create_alphabet(key.upper(), alfabeto, replace, sequence)##
  36. num = 5 + len(alfabeto) % 5
  37. for idx in range(0, len(alfabeto), num):
  38. square.append(alfabeto[idx:idx + num])
  39. return square
  40. def create_alphabet(self, key = '', alfabeto = plain_alphabet, replace = ['', ''], sequence = False):
  41. """ Retorna um alfabeto com key como chave e no inicio do alfabeto """
  42. if key:
  43. key = self.key_repeated(key)
  44. if replace[0] in key:
  45. key = key.replace(replace[0], replace[1])
  46. if sequence:
  47. idx = alfabeto.index(key[-1])
  48. alfabeto = self.shift_alphabet(alfabeto, idx)
  49. cipher = alfabeto.replace(replace[0], '')
  50. for ch_key in key:
  51. if ch_key in cipher:
  52. cipher = cipher.replace(ch_key, '')
  53. return key + cipher
  54. def random_alphabet(self, alphanum=False):
  55. """ Retorna um alfabeto aleatório """
  56. if alphanum:
  57. alfabeto = list(self.create_alphabet(alfabeto=self.plain_alphanum))
  58. else:
  59. alfabeto = list(self.create_alphabet())
  60. shuffle(alfabeto)
  61. return ''.join(alfabeto)
  62. def key_repeated(self, key):
  63. ''' Remove caracteres repetidos da senha key '''
  64. temp = ''
  65. for ch in key.upper():
  66. if ch not in temp:
  67. temp += ch
  68. return temp

comments powered by Disqus