[go: up one dir, main page]

Crate der

Crate der 

Source
Expand description

§RustCrypto: ASN.1 DER

Crate Docs Build Status Apache2/MIT licensed Rust Version Project Chat

Pure Rust embedded-friendly implementation of the Distinguished Encoding Rules (DER) for Abstract Syntax Notation One (ASN.1) as described in ITU X.690.

Documentation

§About

This crate provides a no_std-friendly implementation of a subset of ASN.1 DER necessary for decoding/encoding the following cryptography-related formats implemented as crates maintained by the RustCrypto project:

  • cms: Cryptographic Message Syntax
  • pkcs1: RSA Cryptography Specifications
  • pkcs5: Password-Based Cryptography Specification
  • pkcs8: Private-Key Information Syntax Specification
  • pkcs12: Personal Information Exchange Syntax
  • sec1: Elliptic Curve Cryptography
  • spki: X.509 Subject Public Key Info
  • x509-cert: Public Key Infrastructure Certificate
  • x509-ocsp: Online Certificate Status Protocol

The core implementation avoids any heap usage (with convenience methods that allocate gated under the off-by-default alloc feature).

The DER decoder in this crate performs checks to ensure that the input document is in canonical form, and will return errors if non-canonical productions are encountered. There is currently no way to disable these checks.

§Features

  • Rich support for ASN.1 types used by PKCS/PKIX documents
  • Performs DER canonicalization checks at decoding time
  • no_std friendly: supports “heapless” usage
  • Optionally supports alloc and std if desired
  • No hard dependencies! Self-contained implementation with optional integrations with the following crates, all of which are no_std friendly:
    • const-oid: const-friendly OID implementation
    • pem-rfc7468: PKCS/PKIX-flavored PEM library with constant-time decoder/encoders
    • time crate: date/time library

§Minimum Supported Rust Version (MSRV) Policy

MSRV increases are not considered breaking changes and can happen in patch releases.

The crate MSRV accounts for all supported targets and crate feature combinations, excluding explicitly unstable features.

§License

Licensed under either of:

at your option.

§Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

§Usage

§Decode and Encode traits

The Decode and Encode traits provide the decoding/encoding API respectively, and are designed to work in conjunction with concrete ASN.1 types, including all types which impl the Sequence trait.

The traits are impl’d for the following Rust core types:

The following ASN.1 types provided by this crate also impl these traits:

Context specific fields can be modeled using these generic types:

§Example

The following example implements X.509’s AlgorithmIdentifier message type as defined in RFC 5280 Section 4.1.1.2.

The ASN.1 schema for this message type is as follows:

AlgorithmIdentifier  ::=  SEQUENCE  {
     algorithm               OBJECT IDENTIFIER,
     parameters              ANY DEFINED BY algorithm OPTIONAL  }

Structured ASN.1 messages are typically encoded as a SEQUENCE, which this crate maps to a Rust struct using the Sequence trait. This trait is bounded on the Decode trait and provides a blanket impl of the Encode trait, so any type which impls Sequence can be used for both decoding and encoding.

The following code example shows how to define a struct which maps to the above schema, as well as impl the Sequence trait for that struct:

// Note: the following example does not require the `std` feature at all.
// It does leverage the `alloc` feature, but also provides instructions for
// "heapless" usage when the `alloc` feature is disabled.
use der::{
    asn1::{AnyRef, ObjectIdentifier},
    Decode, DecodeValue, Encode, EncodeValue, Header, Length,
    Reader, Sequence, SliceReader, Writer
};

/// X.509 `AlgorithmIdentifier`.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct AlgorithmIdentifier<'a> {
    /// This field contains an ASN.1 `OBJECT IDENTIFIER`, a.k.a. OID.
    pub algorithm: ObjectIdentifier,

    /// This field is `OPTIONAL` and contains the ASN.1 `ANY` type, which
    /// in this example allows arbitrary algorithm-defined parameters.
    pub parameters: Option<AnyRef<'a>>
}

impl<'a> DecodeValue<'a> for AlgorithmIdentifier<'a> {
    type Error = der::Error;

    fn decode_value<R: Reader<'a>>(reader: &mut R, _header: Header) -> der::Result<Self> {
       // The `der::Decode::decode` method can be used to decode any
       // type which impls the `Decode` trait, which is impl'd for
       // all of the ASN.1 built-in types in the `der` crate.
       let algorithm = reader.decode()?;

       // This field contains an ASN.1 `OPTIONAL` type. The `der` crate
       // maps this directly to Rust's `Option` type and provides
       // impls of the `Decode` and `Encode` traits for `Option`.
       let parameters = reader.decode()?;

       // The value returned from this `decode_value` will be
       // returned from the `AlgorithmIdentifier::decode` call, unchanged.
       // Note that the entire sequence body *MUST* be consumed
       // or an error will be returned.
       Ok(Self { algorithm, parameters })
    }
}

impl<'a> EncodeValue for AlgorithmIdentifier<'a> {
    fn value_len(&self) -> der::Result<Length> {
        // Length of the Value part in Tag-Length-Value structure
        // is calculated for every TLV header in the tree.
        // Therefore, in this example `AlgorithmIdentifier::value_len`
        // will be called once, originating from `Encode::to_der()`.
        self.algorithm.encoded_len()? + self.parameters.encoded_len()?
    }

    fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
        self.algorithm.encode(writer)?;
        self.parameters.encode(writer)?;
        Ok(())
    }
}

impl<'a> Sequence<'a> for AlgorithmIdentifier<'a> {}

// Example parameters value: OID for the NIST P-256 elliptic curve.
let parameters = "1.2.840.10045.3.1.7".parse::<ObjectIdentifier>().unwrap();

// We need to convert `parameters` into an `Any<'a>` type, which wraps a
// `&'a [u8]` byte slice.
//
// To do that, we need owned DER-encoded data so that we can have
// `AnyRef` borrow a reference to it, so we have to serialize the OID.
//
// When the `alloc` feature of this crate is enabled, any type that impls
// the `Encode` trait including all ASN.1 built-in types and any type
// which impls `Sequence` can be serialized by calling `Encode::to_der()`.
//
// If you would prefer to avoid allocations, you can create a byte array
// as backing storage instead, pass that to `der::SliceWriter::new`, and then
// encode the `parameters` value using `writer.encode(parameters)`.
let der_encoded_parameters = parameters.to_der().unwrap();

let algorithm_identifier = AlgorithmIdentifier {
    // OID for `id-ecPublicKey`, if you're curious
    algorithm: "1.2.840.10045.2.1".parse().unwrap(),

    // `AnyRef<'a>` impls `TryFrom<&'a [u8]>`, which parses the provided
    // slice as an ASN.1 DER-encoded message.
    parameters: Some(der_encoded_parameters.as_slice().try_into().unwrap())
};

// Serialize the `AlgorithmIdentifier` created above as ASN.1 DER,
// allocating a `Vec<u8>` for storage.
//
// As mentioned earlier, if you don't have the `alloc` feature enabled you
// can create a fix-sized array instead, then call `SliceWriter::new` with a
// reference to it, then encode the message using
// `writer.encode(algorithm_identifier)`, then finally `writer.finish()`
// to obtain a byte slice containing the encoded message.
let der_encoded_algorithm_identifier = algorithm_identifier.to_der().unwrap();

// Deserialize the `AlgorithmIdentifier` bytes we just serialized from ASN.1 DER
// using `der::Decode::from_der`.
let decoded_algorithm_identifier = AlgorithmIdentifier::from_der(
    &der_encoded_algorithm_identifier
).unwrap();

// Ensure the original `AlgorithmIdentifier` is the same as the one we just
// decoded from ASN.1 DER.
assert_eq!(algorithm_identifier, decoded_algorithm_identifier);

§Custom derive support

When the derive feature of this crate is enabled, the following custom derive macros are available:

§Derive Sequence for struct

The following is a code example of how to use the Sequence custom derive:

use der::{asn1::{AnyRef, ObjectIdentifier}, Encode, Decode, Sequence};

/// X.509 `AlgorithmIdentifier` (same as above)
#[derive(Copy, Clone, Debug, Eq, PartialEq, Sequence)] // NOTE: added `Sequence`
pub struct AlgorithmIdentifier<'a> {
    /// This field contains an ASN.1 `OBJECT IDENTIFIER`, a.k.a. OID.
    pub algorithm: ObjectIdentifier,

    /// This field is `OPTIONAL` and contains the ASN.1 `ANY` type, which
    /// in this example allows arbitrary algorithm-defined parameters.
    pub parameters: Option<AnyRef<'a>>
}

// Example parameters value: OID for the NIST P-256 elliptic curve.
let parameters_oid = "1.2.840.10045.3.1.7".parse::<ObjectIdentifier>().unwrap();

let algorithm_identifier = AlgorithmIdentifier {
    // OID for `id-ecPublicKey`, if you're curious
    algorithm: "1.2.840.10045.2.1".parse().unwrap(),

    // `Any<'a>` impls `From<&'a ObjectIdentifier>`, allowing OID constants to
    // be directly converted to an `AnyRef` type for this use case.
    parameters: Some(AnyRef::from(&parameters_oid))
};

// Encode
let der_encoded_algorithm_identifier = algorithm_identifier.to_der().unwrap();

// Decode
let decoded_algorithm_identifier = AlgorithmIdentifier::from_der(
    &der_encoded_algorithm_identifier
).unwrap();

assert_eq!(algorithm_identifier, decoded_algorithm_identifier);

For fields which don’t directly impl Decode and Encode, you can add annotations to convert to an intermediate ASN.1 type first, so long as that type impls TryFrom and Into for the ASN.1 type.

For example, structs containing &'a [u8] fields may want them encoded as either a BIT STRING or OCTET STRING. By using the #[asn1(type = "BIT STRING")] annotation it’s possible to select which ASN.1 type should be used.

Building off the above example:

/// X.509 `SubjectPublicKeyInfo` (SPKI)
#[derive(Copy, Clone, Debug, Eq, PartialEq, Sequence)]
pub struct SubjectPublicKeyInfo<'a> {
    /// X.509 `AlgorithmIdentifier`
    pub algorithm: AlgorithmIdentifier<'a>,

    /// Public key data
    pub subject_public_key: BitStringRef<'a>,
}

§Owned vs Borrowed

This crate exposes owned and borrowed objects for representing the same structure.

RefToOwned and OwnedToRef are provided to convert objects from one to the other.

§See also

For more information about ASN.1 DER we recommend the following guides:

Re-exports§

pub use crate::asn1::AnyRef;
pub use crate::asn1::Choice;
pub use crate::asn1::Sequence;
pub use crate::asn1::Any;alloc
pub use flagset;flagset
pub use const_oid as oid;oid
pub use pem_rfc7468 as pem;pem
pub use time;time
pub use zeroize;zeroize

Modules§

asn1
Module containing all of the various ASN.1 built-in types supported by this library.
referenced
A module for working with referenced data.

Structs§

DateTime
Date-and-time type shared by multiple ASN.1 types (e.g. GeneralizedTime, UTCTime).
Documentalloc
ASN.1 DER-encoded document.
EncodeRef
Reference encoder: wrapper type which impls Encode for any reference to a type which impls the same.
EncodeValueRef
Reference value encoder: wrapper type which impls EncodeValue and Tagged for any reference type which impls the same.
Error
Error type.
Header
ASN.1 DER headers: tag + length component of TLV-encoded values
Length
ASN.1-encoded length.
PemReaderpem
Reader type which decodes PEM on-the-fly.
PemWriterpem
Writer type which outputs PEM-encoded data.
SecretDocumentalloc and zeroize
Secret Document type.
SliceReader
Reader which consumes an input byte slice.
SliceWriter
Writer which encodes DER into a mutable output byte slice.
TagNumber
ASN.1 tag numbers (i.e. lower 5 bits of a Tag).

Enums§

Class
Class of an ASN.1 tag.
EncodingRules
ASN.1 encoding rules.
ErrorKind
Error type.
Tag
ASN.1 tags.
TagMode
Tagging modes: EXPLICIT versus IMPLICIT.

Traits§

AllowedLenBitString
Trait on automatically derived by BitString macro. Used for checking if binary data fits into defined struct.
Decode
Decode trait parses a complete TLV (Tag-Length-Value) structure.
DecodeOwned
Marker trait for data structures that can be decoded from DER without borrowing any data from the decoder.
DecodePempem
PEM decoding trait.
DecodeValue
DecodeValue trait parses the value part of a Tag-Length-Value object, sans the Tag and Length.
DerOrd
DER ordering trait.
Encode
Encode trait produces a complete TLV (Tag-Length-Value) structure.
EncodePempem
PEM encoding trait.
EncodeValue
Encode the value part of a Tag-Length-Value encoded field, sans the Tag and Length.
FixedTag
Types which have a constant ASN.1 Tag.
IsConstructed
Types which have a constant ASN.1 constructed bit.
Reader
Reader trait which reads DER-encoded input.
Tagged
Types which have an ASN.1 Tag.
ValueOrd
DER value ordering trait.
Writer
Writer trait which outputs encoded DER.

Type Aliases§

Result
Result type.

Derive Macros§

BitStringderive
Derive the BitString on a struct with bool fields.
Choicederive
Derive the Choice trait on an enum.
DecodeValuederive
Derive the DecodeValue trait on a struct.
EncodeValuederive
Derive the EncodeValue trait on a struct.
Enumeratedderive
Derive decoders and encoders for ASN.1 Enumerated types on a C-like enum type.
Sequencederive
Derive the DecodeValue, EncodeValue, Sequence traits on a struct.
ValueOrdderive
Derive the ValueOrd trait on a struct.