Skip to content

der: Reader and Writer traits #525

@tarcieri

Description

@tarcieri

In the ssh-key crate I've used a similar (but simplified) trait structure inspired by the der crate. It also has Decode/Encode traits, but additionally provides traits for Reader/Writer:

These traits are impl'd for types like pem_rfc7468::{Decoder, Encoder}, allowing it to decode from/encode to PEM directly without an intermediate step where data is first decoded from/encoded to a Vec<u8>. This makes it possible to use PEM encoding in heapless environments, which currently isn't possible with the der crate.

PEM decoding is a bit tricky: since the original buffer can't be referenced (since it's encoded as Base64) decoding only works for fully owned types, which happens to be what the ssh-key provides. We don't currently have a way of bounding on such types (though that's trivial to add).

If we were to add this, type signatures would change as follows:

  • fn decode(decoder: &mut Decoder<'a>) -> Result<T> => fn decode(decoder: &mut impl Reader<'a>) -> Result<T>
  • fn encode(&self, encoder: &mut Encoder<'_>) -> Result<()> => fn encode(&self, encoder: &mut impl Writer) -> Result<()>

We'd also need to come up with new names for the current struct Decoder / struct Encoder, possibly something like SliceDecoder and SliceEncoder.

The encoder trait could also be impl'd for sha2::Sha256 which would allow on-the-fly computation of key fingerprints:

https://github.com/RustCrypto/formats/blob/d42432a3/ssh-key/src/encoder.rs#L107-L113

Presently the spki crate first encodes SubjectPublicKeyInfo to an intermediate buffer before computing a digest of that buffer:

https://github.com/RustCrypto/formats/blob/d42432a3/spki/src/spki.rs#L40-L43

Instead the DER serialization could be computed on the fly and input directly to Sha256 with no intermediate buffer as in the ssh-key crate:

https://github.com/RustCrypto/formats/blob/d42432a3/ssh-key/src/fingerprint.rs#L125-L127

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