brndnmtthws / dryoc

Don't Roll Your Own Crypto: pure-Rust, hard to misuse cryptography library
https://docs.rs/dryoc
MIT License
267 stars 14 forks source link

How to convert the Vec<u8> to StackByteArray<32_usize>? #5

Closed rikonaka closed 2 years ago

rikonaka commented 2 years ago

Hi guys, my program need a key exchange function, and I see the dryoc doc here.

let client_session_keys =
    Session::new_client_with_defaults(&client_keypair, &server_keypair.public_key)
        .expect("compute client failed");

But I only have a public key from tcp or udp like [u8], so how can I convert the [u8] to StackByteArray<32_usize> then I can use it in Session::new_client_with_defaults ?

brndnmtthws commented 2 years ago

You can convert it using try_from() with a slice, as noted here: https://docs.rs/dryoc/latest/dryoc/types/struct.StackByteArray.html#impl-TryFrom%3C%26%27a%20%5Bu8%5D%3E-for-StackByteArray%3CLENGTH%3E

Essentially a byte array has a fixed length, whereas Vec is variable length, so converting a vec into a byte array might fail which is why you can't use .into() or From.

For example, try something like this: https://gist.github.com/brndnmtthws/e0cfdf30316036a9d44cb2223d57cc19

If you happen to be using serde, you can just serialize/deserialize the stackbytearray directly instead and save yourself some typing.