56
56
from cryptography .hazmat .bindings .openssl .binding import Binding
57
57
from cryptography .hazmat .primitives .serialization import pkcs7
58
58
59
-
60
59
except ImportError :
61
60
ex = exception_info ()
62
61
warnings .warn ("No es posible importar cryptography (OpenSSL)" )
@@ -115,9 +114,6 @@ def sign_tra(tra, cert=CERT, privatekey=PRIVATEKEY, passphrase=""):
115
114
tra = tra .encode ("utf8" )
116
115
117
116
if Binding :
118
- _lib = Binding .lib
119
- _ffi = Binding .ffi
120
- # Crear un buffer desde el texto
121
117
122
118
# Leer privatekey y cert
123
119
if not privatekey .startswith (b"-----BEGIN RSA PRIVATE KEY-----" ):
@@ -139,20 +135,53 @@ def sign_tra(tra, cert=CERT, privatekey=PRIVATEKEY, passphrase=""):
139
135
cert = cert .encode ("utf-8" )
140
136
cert = x509 .load_pem_x509_certificate (cert )
141
137
138
+ if sys .version_info .major == 2 :
139
+ _lib = Binding .lib
140
+ _ffi = Binding .ffi
141
+ # Crear un buffer desde el texto
142
+ # Se crea un buffer nuevo porque la firma lo consume
143
+ bio_in = _lib .BIO_new_mem_buf (tra , len (tra ))
144
+
145
+ try :
146
+ # Firmar el texto (tra) usando cryptography (openssl bindings para python)
147
+ p7 = _lib .PKCS7_sign (
148
+ cert ._x509 , private_key ._evp_pkey , _ffi .NULL , bio_in , 0
149
+ )
150
+ finally :
151
+ # Liberar memoria asignada
152
+ _lib .BIO_free (bio_in )
153
+ # Se crea un buffer nuevo porque la firma lo consume
154
+ bio_in = _lib .BIO_new_mem_buf (tra , len (tra ))
155
+ try :
156
+ # Crear buffer de salida
157
+ bio_out = _lib .BIO_new (_lib .BIO_s_mem ())
158
+ try :
159
+ # Instanciar un SMIME
160
+ _lib .SMIME_write_PKCS7 (bio_out , p7 , bio_in , 0 )
161
+
162
+ # Tomar datos para la salida
163
+ result_buffer = _ffi .new ("char**" )
164
+ buffer_length = _lib .BIO_get_mem_data (bio_out , result_buffer )
165
+ p7 = _ffi .buffer (result_buffer [0 ], buffer_length )[:]
166
+ finally :
167
+ _lib .BIO_free (bio_out )
168
+ finally :
169
+ _lib .BIO_free (bio_in )
142
170
143
- p7 = pkcs7 .PKCS7SignatureBuilder ().set_data (
171
+ else :
172
+ p7 = pkcs7 .PKCS7SignatureBuilder ().set_data (
144
173
tra
145
- ).add_signer (
146
- cert , private_key , hashes .SHA256 ()
147
- ).sign (
148
- serialization .Encoding .SMIME , [pkcs7 .PKCS7Options .Binary ]
149
- )
174
+ ).add_signer (
175
+ cert , private_key , hashes .SHA256 ()
176
+ ).sign (
177
+ serialization .Encoding .SMIME , [pkcs7 .PKCS7Options .Binary ]
178
+ )
150
179
151
180
# Generar p7 en formato mail y recortar headers
152
181
msg = email .message_from_string (p7 .decode ("utf8" ))
153
182
for part in msg .walk ():
154
183
filename = part .get_filename ()
155
- if filename == "smime.p7s" :
184
+ if filename and filename . startswith ( "smime.p7" ) :
156
185
# Es la parte firmada?
157
186
# Devolver CMS
158
187
return part .get_payload (decode = False )
0 commit comments