Skip to content

Instantly share code, notes, and snippets.

@nenodias
Created March 28, 2017 00:39
Show Gist options
  • Select an option

  • Save nenodias/f3161fb3d5bee7e4b0ee9f0e049ad2e1 to your computer and use it in GitHub Desktop.

Select an option

Save nenodias/f3161fb3d5bee7e4b0ee9f0e049ad2e1 to your computer and use it in GitHub Desktop.
Criptografia com PyCrypto (linux)
"""Modulo para Criptografar Arquivo."""
# -*- coding:utf-8 -*-
import base64
import zlib
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
def gerar_chaves(bits=2048):
"""GenerateRSA.
Generate an RSA keypair with an exponent of 65537 in PEM format
param: bits The key length in bits
Return private key and public key
"""
new_key = RSA.generate(bits, e=65537)
public_key = new_key.publickey().exportKey("PEM")
private_key = new_key.exportKey("PEM")
return private_key, public_key
def criptografar(plaintext, public_key):
"""Função que criptografa usando uma chave pública."""
# chunk_size = 256 # Exemplo antigo
chunk_size = 214
print('Comprimindo: %d bytes' % (len(plaintext)))
plaintext = zlib.compress(plaintext)
print('Criptografando %d bytes' % (len(plaintext)))
rsakey = RSA.importKey(public_key)
rsakey = PKCS1_OAEP.new(rsakey)
encrypted = b""
offset = 0
while offset < len(plaintext):
chunk = plaintext[offset:offset+chunk_size]
if len(chunk) % chunk_size != 0:
chunk += b" " * (chunk_size - len(chunk))
encrypted += rsakey.encrypt(chunk)
offset += chunk_size
encrypted = base64.b64encode(encrypted)
print('Base64 criptografado: %d' % len(encrypted))
return encrypted
def descriptografar(cripto_text, private):
"""Método para Descriptografar."""
rsakey = RSA.importKey(private)
rsakey = PKCS1_OAEP.new(rsakey)
chunk_size = 256
offset = 0
descripto = b''
encrytado = base64.b64decode(cripto_text)
while offset < len(encrytado):
descripto += rsakey.decrypt(encrytado[offset:offset+chunk_size])
offset += chunk_size
# agora descompactar as paradas
plaintext = zlib.decompress(descripto)
return plaintext
if __name__ == '__main__':
# Chaves
privada, publica = gerar_chaves()
# arquivo = b'Exemplo dois'
# arquivo = 'Horácio Dias'.encode('utf-8')
caminho = input('digite o caminho do arquivo:')
with open(caminho, 'rb') as f:
arquivo = f.read()
arquivo_criptografado = criptografar(arquivo, publica)
print(arquivo_criptografado)
print(descriptografar(arquivo_criptografado, privada))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment