Advertisement
diegomrodrigues

Criptografia - Cifra de César em Python

Mar 21st, 2018
359
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.96 KB | None | 0 0
  1. '''
  2. Criptografia - Cifra de César em Python
  3.  
  4. Artigo no LinkedIn:
  5. https://www.linkedin.com/pulse/criptografia-cifra-de-césar-em-python-diego-mendes-rodrigues/
  6.  
  7. Curso de Python 3:
  8. https://produto.mercadolivre.com.br/MLB-991504015-curso-de-python-3-_JM
  9.  
  10. Diego Mendes Rodrigues
  11. '''
  12.  
  13. class Cesar:
  14.     def __init__(self):
  15.         self.__letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  16.  
  17.     def encrypt(self, texto_plano, key = 3):
  18.         '''(Cesar, str, int) -> str
  19.        Retorna o texto_plano cifrado com a cifra de Cesar,
  20.        utlizando a chave key, cujo padrao e 3.
  21.        '''
  22.         cipher_text = ''
  23.         texto_plano = texto_plano.upper()
  24.         for ch in texto_plano:
  25.             if ch in self.__letters:
  26.                 idx = self.__letters.find(ch) + key
  27.                 if idx >= 26:
  28.                     idx -= 26
  29.                 cipher_text += self.__letters[idx]
  30.             else:
  31.                 cipher_text += ch
  32.         return cipher_text
  33.  
  34.     def decrypt(self, texto_cifrado,  key = 3):
  35.         ''' (Cesar, str, int) -> str
  36.        Retorna em texto plano o texto_cifrado decifrado com a
  37.        cifra de Cesar, utilizando a chave key, cujo padrao e 3.
  38.        '''
  39.         plain_text = ''
  40.         texto_cifrado = texto_cifrado.upper()
  41.         for ch in texto_cifrado:
  42.             if ch in self.__letters:
  43.                 idx = self.__letters.find(ch) - key
  44.                 plain_text += self.__letters[idx]
  45.             else:
  46.                 plain_text += ch
  47.         return plain_text.lower()
  48.  
  49. # Usando a chave de César = 3
  50. print('Chave de César = 3')
  51. criptografado = Cesar().encrypt('teste de texto com a cifra de Cesar')
  52. print(criptografado)
  53. decriptado = Cesar().decrypt(criptografado)
  54. print(decriptado)
  55.  
  56. # Usando a chave de César = 17
  57. print('\nChave de César = 17')
  58. criptografado = Cesar().encrypt('teste de texto com a cifra de Cesar', 17)
  59. print(criptografado)
  60. decriptado = Cesar().decrypt(criptografado, 17)
  61. print(decriptado)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement