Skip to content

Commit

Permalink
Use built in cryptography pkcs7 signature.
Browse files Browse the repository at this point in the history
Signed-off-by: Robert Stewart <rbstewart@protonmail.com>
  • Loading branch information
salticus committed Apr 25, 2023
1 parent e08c9d1 commit 0a5992b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 31 deletions.
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ httplib2==0.20.4; python_version > '3'
pysimplesoap==1.08.14; python_version <= '2.7'
git+https://github.com/pysimplesoap/pysimplesoap.git@py311#pysimplesoap; python_version > '3'
cryptography==3.3.2; python_version <= '2.7'
cryptography==3.4.7; python_version > '3'
cryptography==39.0.2; python_version > '3'
fpdf>=1.7.2
dbf>=0.88.019
Pillow>=2.0.0
Expand Down
47 changes: 17 additions & 30 deletions wsaa.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.bindings.openssl.binding import Binding
from cryptography.hazmat.primitives.serialization import pkcs7


except ImportError:
ex = exception_info()
Expand Down Expand Up @@ -116,7 +118,6 @@ def sign_tra(tra, cert=CERT, privatekey=PRIVATEKEY, passphrase=""):
_lib = Binding.lib
_ffi = Binding.ffi
# Crear un buffer desde el texto
bio_in = _lib.BIO_new_mem_buf(tra, len(tra))

# Leer privatekey y cert
if not privatekey.startswith(b"-----BEGIN RSA PRIVATE KEY-----"):
Expand All @@ -136,42 +137,28 @@ def sign_tra(tra, cert=CERT, privatekey=PRIVATEKEY, passphrase=""):
cert = open(cert).read()
if isinstance(cert, str):
cert = cert.encode("utf-8")
cert = x509.load_pem_x509_certificate(cert, default_backend())
cert = x509.load_pem_x509_certificate(cert)

try:
# Firmar el texto (tra) usando cryptography (openssl bindings para python)
p7 = _lib.PKCS7_sign(
cert._x509, private_key._evp_pkey, _ffi.NULL, bio_in, 0
)
finally:
# Liberar memoria asignada
_lib.BIO_free(bio_in)
# Se crea un buffer nuevo porque la firma lo consume
bio_in = _lib.BIO_new_mem_buf(tra, len(tra))
try:
# Crear buffer de salida
bio_out = _lib.BIO_new(_lib.BIO_s_mem())
try:
# Instanciar un SMIME
_lib.SMIME_write_PKCS7(bio_out, p7, bio_in, 0)

# Tomar datos para la salida
result_buffer = _ffi.new("char**")
buffer_length = _lib.BIO_get_mem_data(bio_out, result_buffer)
output = _ffi.buffer(result_buffer[0], buffer_length)[:]
finally:
_lib.BIO_free(bio_out)
finally:
_lib.BIO_free(bio_in)

p7 = pkcs7.PKCS7SignatureBuilder().set_data(
tra
).add_signer(
cert, private_key, hashes.SHA256()
).sign(
serialization.Encoding.SMIME, [pkcs7.PKCS7Options.DetachedSignature]
)

# Generar p7 en formato mail y recortar headers
msg = email.message_from_string(output.decode("utf8"))
msg = email.message_from_string(p7.decode("utf8"))
for part in msg.walk():
filename = part.get_filename()
if filename == "smime.p7m":
if filename == "smime.p7s":
# Es la parte firmada?
# Devolver CMS
return part.get_payload(decode=False)
else:
raise RuntimeError("Part not found")

else:
# Firmar el texto (tra) usando OPENSSL directamente
try:
Expand Down Expand Up @@ -642,4 +629,4 @@ def main():
print("Expiro?", wsaa.Expirado())

if __name__=="__main__":
main()
main()

0 comments on commit 0a5992b

Please sign in to comment.