Exposez _hashlib.pyd internes pour evp_md_ctx?
-
28-10-2019 - |
Question
Quelqu'un sait comment exposer Python 2.x _hashlib.pyd internes à l'aide de ctypes? J'ai particulièrement besoin d'extraire la structure EVP_MD_CTX pour la sérialisation des objets de hachage Python.
La solution
Le mappage des structures C à partir des fichiers d'en-tête (OpenSSL / EVP.h et _hashopensssl.c dans votre cas) est simple, mais n'est pas toujours portable sur différentes versions. Voici pour mon environnement:
from ctypes import *
PyObject_HEAD = [
('ob_refcnt', c_size_t),
('ob_type', c_void_p),
]
class EVP_MD(Structure):
_fields_ = [
('type', c_int),
('pkey_type', c_int),
('md_size', c_int),
('flags', c_ulong),
('init', c_void_p),
('update', c_void_p),
('final', c_void_p),
('copy', c_void_p),
('cleanup', c_void_p),
('sign', c_void_p),
('verify', c_void_p),
('required_pkey_type', c_int*5),
('block_size', c_int),
('ctx_size', c_int),
]
class EVP_MD_CTX(Structure):
_fields_ = [
('digest', POINTER(EVP_MD)),
('engine', c_void_p),
('flags', c_ulong),
('md_data', POINTER(c_char)),
]
class EVPobject(Structure):
_fields_ = PyObject_HEAD + [
('name', py_object),
('ctx', EVP_MD_CTX),
]
Vous trouverez ci-dessous un exemple sur la façon de l'utiliser pour Enregistrer et restaurer l'état de l'objet de hachage:
import hashlib
hash = hashlib.md5('test')
print hash.hexdigest()
c_evp_obj = cast(c_void_p(id(hash)), POINTER(EVPobject)).contents
ctx = c_evp_obj.ctx
digest = ctx.digest.contents
state = ctx.md_data[:digest.ctx_size]
hash2 = hashlib.md5()
c_evp_obj = cast(c_void_p(id(hash2)), POINTER(EVPobject)).contents
ctx = c_evp_obj.ctx
digest = ctx.digest.contents
memmove(ctx.md_data, state, digest.ctx_size)
print hash2.hexdigest()
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow