简体   繁体   中英

Pack/unpack and BSON encode/decode dat

We have an iOS app that sends data in an encoded format. In PHP the following code will decode it properly.

bson_decode(pack("H*", $hex_string));

In Python, the following code will create a valid encoded object that the PHP code can then decode ( data is a dict in this).

from bson import BSON
def encode(data):
    return str(BSON.encode(data)).encode('hex')

The following Python code will decode a string that was encoded by the above Python code:

from bson import BSON
def parse(str):
    hexed = str.decode('hex')
    return BSON.decode(BSON(hexed))

In theory that should decoded data sent from the app as well. But it throws the following exceptions:

bson.errors.InvalidBSON: bad eoo

It looks like the Objective C code that encodes the data in the app adds some extra padding. If I remove the last characters from the app encoded string it works. Is there anything I can do to account for this? Changing the app code is NOT possible. Even if it were there are millions of device running the old code which I need to support so I still need to have a fix for this.

According the BSON specification , BSON documents must be terminated with a NULL byte ( \\x00 ). Have you checked if the byte string you are trying to decode is NULL terminated? If not, you may need to append a NULL byte at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM