氧化钠定义PublicKey
为:
new_type! {
/// `PublicKey` for signatures
public PublicKey(PUBLICKEYBYTES);
}
pub struct $name(pub [u8; $bytes]);
因此,PublicKey
定义为 32 字节的简单包装器。
当我定义自己的 32 字节 ( MyPubKey
) 包装器时,它的 bincode 序列化为 32 字节。
当我对 serialise 进行 bincode 时PublicKey
,它是 40 个字节 - 32 个字节以u64
包含长度的 little-endian 为前缀。
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
extern crate sodiumoxide;
use sodiumoxide::crypto::{sign, box_};
use bincode::{serialize, deserialize, Infinite};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
pub struct MyPubKey(pub [u8; 32]);
fn main() {
let (pk, sk) = sign::gen_keypair();
let arr: [u8; 32] = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31];
let mpk = MyPubKey(arr);
let encoded_pk: Vec<u8> = serialize(&pk, Infinite).unwrap();
let encoded_arr: Vec<u8> = serialize(&arr, Infinite).unwrap();
let encoded_mpk: Vec<u8> = serialize(&mpk, Infinite).unwrap();
println!("encoded_pk len:{:?} {:?}", encoded_pk.len(), encoded_pk);
println!("encoded_arr len:{:?} {:?}", encoded_arr.len(), encoded_arr);
println!("encoded_mpk len:{:?} {:?}", encoded_mpk.len(), encoded_mpk);
}
结果:
encoded_pk len:40 [32, 0, 0, 0, 0, 0, 0, 0, 7, 199, 134, 217, 109, 46, 34, 155, 89, 232, 171, 185, 199, 190, 253, 88, 15, 202, 58, 211, 198, 49, 46, 225, 213, 233, 114, 253, 61, 182, 123, 181]
encoded_arr len:32 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
encoded_mpk len:32 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
PublicKey
用氧化钠的new_type!
宏创建的类型和类型之间有什么区别MyPublicKey
?
如何从 a 中获取 32 个字节,PublicKey
以便有效地序列化它们?