Data corruption: Where's the bug‽

匆匆过客 提交于 2019-12-05 04:50:28

Oy, I hate to do this (answer my own question), but I found the answer: It is a quirk of Cython which I am going to have to look into (I don't know if it is an intended quirk, or if it is a bug).

The problem comes with the memcpy line. I cast the second parameter to <const_void*>, which matches the Cython definition in the pxd file, but apparently that makes Cython compile the code differently than using <char*>, the latter forcing Cython to pass a pointer to the actual bytes instead of (I guess?) a pointer to the Python object/variable itself.

So, instead of this:

cdef char* buffer = <char*>malloc(in_len)
memcpy(buffer, <const_void *>in_bin, in_len)
success = cmc.mcrypt_generic(self._mcStream, <void*>buffer, in_len)

It needs to be this:

cdef char* buffer = <char*>malloc(in_len)
memcpy(buffer, <char *>in_bin, in_len)
success = cmc.mcrypt_generic(self._mcStream, <void*>buffer, in_len)

What a strange quirk. I would honestly expect any cast to point to the same location, but it seems that the cast can affect behavior as well.

I've encountered results similar to this when something funny happened with a combination of using the wrong Initialization Vector (i.e. using a different IV for encryption than for decryption) and the Ciphermode choice. As a sanity check, try switching from CBC to ECB.

Another possibility is that one of your variables is being randomized (with a new time-based seed) when it shouldn't be. In that case, you can cause data corruption to happen more often by putting a delay between the encryption and decryption step.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!