Skip to content

Serializing SecretKey to bytes #104

@iancoleman

Description

@iancoleman

Converting a SecretKey to json gives [u64; 4]

let sk = SecretKey::random();
let skj = serde_json::to_string(&SerdeSecret(&sk)).unwrap();
println!("{:?}", skj);
// "[13835017372499487413,8530528684116874606,14604090506237340830,7436755248230544869]"

Javascript will happily but incorrectly parse this (javascript uses f64 for all numbers):

sk = JSON.parse("[13835017372499487413,8530528684116874606,14604090506237340830,7436755248230544869]");
console.log(sk);
// [ 13835017372499487000, 8530528684116874000, 14604090506237342000, 7436755248230544000 ]

Being able to convert to bytes would be handy in these sorts of cases, maybe to_bytes and from_bytes method?

Here's a SecretKey method that works for converting to bytes:

/// Reveals the prime field as bytes
pub fn to_bytes(&self) -> Vec<u8> {
    use ff::PrimeField;
    let mut bytes = Vec::<u8>::new();
    self.0.into_repr().0.iter().for_each(|n| bytes.extend(&n.to_le_bytes()));
    bytes.reverse();
    bytes
}

But I'm not sure if this logic is best to be in the SecretKey impl or if it's something that should be added to serde_impl.rs, since it depends on how much the library wants to insulate the secret key and how it would achieve that.

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