54
54
from cryptography .hazmat .primitives import serialization
55
55
from cryptography .hazmat .primitives .asymmetric import rsa
56
56
from cryptography .hazmat .bindings .openssl .binding import Binding
57
+ from cryptography .hazmat .primitives .serialization import pkcs7
58
+
57
59
58
60
except ImportError :
59
61
ex = exception_info ()
@@ -116,7 +118,6 @@ def sign_tra(tra, cert=CERT, privatekey=PRIVATEKEY, passphrase=""):
116
118
_lib = Binding .lib
117
119
_ffi = Binding .ffi
118
120
# Crear un buffer desde el texto
119
- bio_in = _lib .BIO_new_mem_buf (tra , len (tra ))
120
121
121
122
# Leer privatekey y cert
122
123
if not privatekey .startswith (b"-----BEGIN RSA PRIVATE KEY-----" ):
@@ -136,42 +137,28 @@ def sign_tra(tra, cert=CERT, privatekey=PRIVATEKEY, passphrase=""):
136
137
cert = open (cert ).read ()
137
138
if isinstance (cert , str ):
138
139
cert = cert .encode ("utf-8" )
139
- cert = x509 .load_pem_x509_certificate (cert , default_backend () )
140
+ cert = x509 .load_pem_x509_certificate (cert )
140
141
141
- try :
142
- # Firmar el texto (tra) usando cryptography (openssl bindings para python)
143
- p7 = _lib .PKCS7_sign (
144
- cert ._x509 , private_key ._evp_pkey , _ffi .NULL , bio_in , 0
145
- )
146
- finally :
147
- # Liberar memoria asignada
148
- _lib .BIO_free (bio_in )
149
- # Se crea un buffer nuevo porque la firma lo consume
150
- bio_in = _lib .BIO_new_mem_buf (tra , len (tra ))
151
- try :
152
- # Crear buffer de salida
153
- bio_out = _lib .BIO_new (_lib .BIO_s_mem ())
154
- try :
155
- # Instanciar un SMIME
156
- _lib .SMIME_write_PKCS7 (bio_out , p7 , bio_in , 0 )
157
-
158
- # Tomar datos para la salida
159
- result_buffer = _ffi .new ("char**" )
160
- buffer_length = _lib .BIO_get_mem_data (bio_out , result_buffer )
161
- output = _ffi .buffer (result_buffer [0 ], buffer_length )[:]
162
- finally :
163
- _lib .BIO_free (bio_out )
164
- finally :
165
- _lib .BIO_free (bio_in )
142
+
143
+ p7 = pkcs7 .PKCS7SignatureBuilder ().set_data (
144
+ tra
145
+ ).add_signer (
146
+ cert , private_key , hashes .SHA256 ()
147
+ ).sign (
148
+ serialization .Encoding .SMIME , [pkcs7 .PKCS7Options .DetachedSignature ]
149
+ )
166
150
167
151
# Generar p7 en formato mail y recortar headers
168
- msg = email .message_from_string (output .decode ("utf8" ))
152
+ msg = email .message_from_string (p7 .decode ("utf8" ))
169
153
for part in msg .walk ():
170
154
filename = part .get_filename ()
171
- if filename == "smime.p7m " :
155
+ if filename == "smime.p7s " :
172
156
# Es la parte firmada?
173
157
# Devolver CMS
174
158
return part .get_payload (decode = False )
159
+ finally :
160
+ raise RuntimeError ("Part not found" )
161
+
175
162
else :
176
163
# Firmar el texto (tra) usando OPENSSL directamente
177
164
try :
@@ -642,4 +629,4 @@ def main():
642
629
print ("Expiro?" , wsaa .Expirado ())
643
630
644
631
if __name__ == "__main__" :
645
- main ()
632
+ main ()
0 commit comments