Skip to content

How do I decode binary data? #89

@Svedrin

Description

@Svedrin

Hi,

I'm implementing an auth mechanism based on bson and sodiumoxide, and I'm having trouble decoding the challenge. Sodiumoxide treats plaintexts as a &[u8], so I'd like to use a binary string instead of a Unicode string for the challenge, but I can't seem to get bson to decode it correctly.

Code

With a "standard" string, everything works fine:

#[derive(Serialize, Deserialize, Debug)]
pub struct AuthChallenge {
    pub challenge: String,
}

// [...]

    let challenge: AuthChallenge = bson::from_bson(
        bson::Bson::Document(
            bson::decode_document(
                &mut Cursor::new(&message.payload[..])
            ).chain_err(|| "Could not decode bson")?
        )
    ).expect("Decoding failed");
    info!("Challenge: {:?}", challenge.challenge);

This yields:

2018-03-08T08:22:04+01:00 - INFO - Received message ReqAuthentication (payload: [53, 0, 0, 0, 2, 99, 104, 97, 108, 108, 101, 110, 103, 101, 0, 33, 0, 0, 0, 49, 56, 55, 54, 50, 98, 57, 56, 98, 55, 99, 51, 52, 99, 50, 53, 98, 102, 57, 100, 99, 51, 49, 53, 52, 101, 52, 97, 53, 99, 97, 51, 0, 0])
2018-03-08T08:22:04+01:00 - INFO - Challenge: "18762b98b7c34c25bf9dc3154e4a5ca3"

However, if I changeString to Vec<u8> in the struct and change the server side to send a binary string (5) instead of a standard string (2), I get this:

2018-03-08T08:28:12+01:00 - INFO - Received message ReqAuthentication (payload: [53, 0, 0, 0, 5, 99, 104, 97, 108, 108, 101, 110, 103, 101, 0, 32, 0, 0, 0, 0, 54, 55, 98, 54, 100, 53, 50, 99, 50, 101, 48, 51, 52, 52, 56, 49, 98, 52, 57, 101, 102, 51, 56, 56, 101, 100, 100, 54, 51, 98, 50, 102, 0])
thread 'main' panicked at 'Decoding failed: InvalidType("a sequence")', /checkout/src/libcore/result.rs:906:4

I'm also having trouble encoding the signature, because to_bson would always complain that there are no unsigned types in bson, so I ended up doing the encoding manually:

    bson::Bson::Binary(
        bson::spec::BinarySubtype::Generic,
        Vec::from(&signature[..])
    )

Am I doing it wrong, or does bson not currently support binary strings correctly? Can I help in fixing it somehow?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions