本文介绍了公开_hashlib.pyd内部用于EVP_MD_CTX吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何使用ctypes公开python 2.x _hashlib.pyd内部吗?我特别需要提取EVP_MD_CTX结构以对python HASH对象进行序列化.

Anyone know how to expose python 2.x _hashlib.pyd internals using ctypes? I especially need to extract the EVP_MD_CTX struct for serialization of python HASH objects.

推荐答案

从头文件(在您的情况下为openssl/evp.h和_hashopenssl.c)映射C结构很简单,但并不总是可以在不同版本之间移植.这是针对我的环境的:

Mapping C structures from header files (openssl/evp.h and _hashopenssl.c in your case) is straightforward, but is not always portable across different versions. Here it is for my environment:

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),
    ]

以下是有关如何使用它来保存和恢复其状态的示例.哈希对象:

Below is an example on how to use it to save and restore state of hash object:

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()

这篇关于公开_hashlib.pyd内部用于EVP_MD_CTX吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 05:36