Skip to content

Commit

Permalink
Merge pull request #301 from felps-dev/master
Browse files Browse the repository at this point in the history
Atualiza criptografia A1 para utilizar Cryptography no Lugar de OpenSSL
  • Loading branch information
juniortada authored Oct 31, 2023
2 parents 3a902f6 + 8286c8b commit 9b1ff41
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 25 deletions.
62 changes: 39 additions & 23 deletions pynfe/entidades/certificado.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
# -*- coding: utf-8 -*-

from .base import Entidade
from OpenSSL import crypto
import tempfile
import os
import tempfile

from cryptography.hazmat.primitives.serialization import (
Encoding,
NoEncryption,
PrivateFormat,
pkcs12,
)

from .base import Entidade


class Certificado(Entidade):
Expand Down Expand Up @@ -49,43 +56,52 @@ def separar_arquivo(self, senha, caminho=False):
"Falha ao abrir arquivo do certificado digital A1. Causa desconhecida."
) from exc

if not isinstance(senha, bytes):
senha = str.encode(senha)

# Carrega o arquivo .pfx, erro pode ocorrer se a senha estiver errada ou formato invalido.
try:
pkcs12 = crypto.load_pkcs12(cert_conteudo, senha)
except crypto.Error as exc:
raise Exception(
"Falha ao carregar certificado digital A1. Verifique a senha do"
" certificado."
) from exc
except Exception as exc:
raise Exception(
"Falha ao carregar certificado digital A1. Causa desconhecida."
) from exc
(
chave,
cert,
) = pkcs12.load_key_and_certificates(
cert_conteudo, senha
)[:2]
except Exception as e:
if "invalid password" in str(e).lower():
raise Exception(
"Falha ao carregar certificado digital A1. Verifique a senha do"
" certificado."
) from e
else:
raise Exception(
"Falha ao carregar certificado digital A1. Causa desconhecida."
) from e

if caminho:
cert = crypto.dump_certificate(
crypto.FILETYPE_PEM, pkcs12.get_certificate()
)
chave = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())
# cria arquivos temporarios
with tempfile.NamedTemporaryFile(delete=False) as arqcert:
arqcert.write(cert)
arqcert.write(cert.public_bytes(Encoding.PEM))
with tempfile.NamedTemporaryFile(delete=False) as arqchave:
arqchave.write(chave)
arqchave.write(
chave.private_bytes(
Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()
)
)
self.arquivos_temp.append(arqchave.name)
self.arquivos_temp.append(arqcert.name)
return arqchave.name, arqcert.name
else:
# Certificado
cert = crypto.dump_certificate(
crypto.FILETYPE_PEM, pkcs12.get_certificate()
).decode("utf-8")
cert = cert.public_bytes(Encoding.PEM).decode("utf-8")
cert = cert.replace("\n", "")
cert = cert.replace("-----BEGIN CERTIFICATE-----", "")
cert = cert.replace("-----END CERTIFICATE-----", "")

# Chave, string decodificada da chave privada
chave = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())
chave = chave.private_bytes(
Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()
)

return chave, cert

Expand Down
3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
# Dependencias basicas
pyopenssl>=23.0.0
requests
lxml
signxml

cryptography
# Opcional para NFS-e
#-r requirements-nfse.txt

0 comments on commit 9b1ff41

Please sign in to comment.