Cryptography-related format encoders/decoders: PKCS, PKIX

Related tags

Cryptography formats
Overview

RustCrypto: Formats Project Chat MSRV dependency status

Cryptography-related format encoders/decoders: PKCS, PKIX.

Crates

Name crates.io Docs Description
base64ct crates.io Documentation Constant-time encoder and decoder of several Base64 variants
const‑oid crates.io Documentation Const-friendly implementation of the ISO/IEC Object Identifier (OID) standard as defined in ITU X.660
der crates.io Documentation Decoder and encoder of the Distinguished Encoding Rules (DER) for Abstract Syntax Notation One (ASN.1) as described in ITU X.690
pem‑rfc7468 crates.io Documentation Strict PEM encoding for PKIX/PKCS/CMS objects
pkcs1 crates.io Documentation Implementation of PKCS#1: RSA Cryptography Specifications Version 2.2 (RFC 8017)
pkcs5 crates.io Documentation Implementation of PKCS#5: Password-Based Cryptography Specification Version 2.1 (RFC 8018)
pkcs8 crates.io Documentation Implementation of PKCS#8(v2): Private-Key Information Syntax Specification (RFC 5208) and asymmetric key packages (RFC 5958)
sec1 crates.io Documentation SEC1: Elliptic Curve Cryptography encoding formats
spki crates.io Documentation X.509 Subject Public Key Info (RFC 5280 Section 4.1) describing public keys as well as their associated AlgorithmIdentifiers (i.e. OIDs)
x509 crates.io Documentation Implementation of the X.509 Public Key Infrastructure Certificate format as described in RFC 5280

License

All crates 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.

Comments
  • der: support for CHOICE types with context-specific subtypes that have the same underlying type

    der: support for CHOICE types with context-specific subtypes that have the same underlying type

    Before going too deep into this, I'm trying to implement a Subject Alternative Names struct, RFC section link here: https://datatracker.ietf.org/doc/html/rfc2459#section-4.2.1.7

    General Name here is a CHOICE, with 9 context-specific implicit tags. Several of these tags have the same underlying type.

    I'm trying to implement the Encodable/Decodable/Choice traits on my GeneralName enum. I can't use the Choice derive macro because:

    • It doesn't include Ia5String as a possible type (my main interest)
    • Even if it did, the Choice derive macro does not allow for multiple enum variants of the same intermediate subtype

    Having dug into the expanded macro, I think I understand why, so I figured I could implement the traits on my own, but I'm running into trouble implementing TryFrom<Any<'a>>. Code snippet:

        fn try_from(any: Any<'a>) -> Result<Self, Self::Error> {
            match any.tag() {
                der::Tag::Ia5String => any
                    .ia5_string()
                    .ok()
                    .and_then(|val| val.try_into().ok())
                    .ok_or_else(|| der::Tag::Ia5String.value_error()),
                actual => Err(der::ErrorKind::UnexpectedTag {
                    expected: None,
                    actual,
                }
                .into()),
            }
        }
    

    Should the tag requested here be an Ia5String, or do I need to manually interpret the tag? I also don't understand how to interpret implicit context-specific tags, and the ContextSpecific struct seems to set the constructed bit even though, in the X509 certificates I've parsed, none of them do (the tag for each SAN goes 0x82 <len> <value>, where as the ContextSpecific struct always serializes to 0xA2.

    opened by ajpauwels 36
  • Allow for data before PEM (RFC 7468) encapsulation boundary

    Allow for data before PEM (RFC 7468) encapsulation boundary

    opened by dwhjames 36
  • Adds SignedData type to `pkcs7`

    Adds SignedData type to `pkcs7`

    • Adds SignedData type to ContentInfo
    • Two examples + test cases (Apple MDM Signature and SCEP Request from Apple device) originally BER encoded but reencoded in DER
    • Requires x509-cert now for some types

    Missing

    • Some types (like AttributeCertificateV2) I haven't encountered
    • More asserts in the new tests. Currently only tests if e_content ambiguity in PKCS#7 vs CMS standard was handled
    • ValueOrd implementation.. what makes sense?
    opened by smndtrl 19
  • der: support for the `REAL` type

    der: support for the `REAL` type

    Hi there,

    I'm seriously considering using your library to encode lots of f64 data (cf. https://github.com/anise-toolkit , and specifically this flatbuffer example: https://github.com/anise-toolkit/specs/blob/1-draft-0-0-1/ephemeris.fbs ).

    I'm brand new to ASN.1, so please excuse novice questions. According to a copy of some specs I found here, https://www.oss.com/asn1/resources/books-whitepapers-pubs/larmouth-asn1-book.pdf, section 2.4 (page 83) talks about a REAL type. The ASN.1 playground also uses that type in their default example: https://asn1.io/asn1playground/ .

    However, I don't see it in the docs as one of the supported type (https://docs.rs/der/latest/der/asn1/index.html).

    Is the REAL type not supported in DER encoding? Or has it not yet been implemented in this library because it isn't needed for the crypto algorithms?

    Thanks

    opened by ChristopherRabotin 17
  • Add a PKCS#10 (certification requests) implementation

    Add a PKCS#10 (certification requests) implementation

    The following are outstanding issues and/or discussion points.

    • [x] https://github.com/RustCrypto/formats/issues/322

    • [ ] https://github.com/RustCrypto/formats/issues/321

    • [ ] I'm not sure about structure naming. I've chosen CertReq. But I think the style of the repo might be the longer CertificationRequest. But this gets pretty long for CertificationRequestDocument. Also, *Info seems to be shortened by this project. So some guidance on the naming would be helpful.

    • [ ] I'm only testing this with RSA keys. However, I'm just re-using spki::SubjectPublicKeyInfo. So I think this might be okay.

    • [ ] pkcs10::CertReq is incredibly similar to x509::Certificate. These two could be genericized and then they could share an implementation of signature validation. However, I don't know the right crate to put them in. This could also be a future enhancement.

    opened by npmccallum 12
  • der: Compilation error when combined with `worker` and `rsa` crate for WASM target

    der: Compilation error when combined with `worker` and `rsa` crate for WASM target

    Reproducing DER crate compilation failure

    See this repo https://github.com/mishazharov/der-repro for a small test case to show the error

    Versions

    $ rustc --version
    rustc 1.56.0 (09c42c458 2021-10-18)
    
    $ cargo --version
    cargo 1.56.0 (4ed5d137b 2021-10-04)
    

    Platform

    Kernel: 5.11.0-38-generic Distro: #42~20.04.1-Ubuntu Arch: x86_64

    Steps to reproduce

    Run wasm-pack build --no-typescript --release.

    Error shown

       Compiling der v0.4.4
    error[E0277]: can't compare `usize` with `()`
       --> /home/misha/.cargo/registry/src/github.com-1ecc6299db9ec823/der-0.4.4/src/encoder.rs:151:43
        |
    151 |         if nested_encoder.finish()?.len() == length.try_into()? {
        |                                           ^^ no implementation for `usize == ()`
        |
        = help: the trait `PartialEq<()>` is not implemented for `usize`
    
    error[E0277]: the trait bound `(): From<Length>` is not satisfied
       --> /home/misha/.cargo/registry/src/github.com-1ecc6299db9ec823/der-0.4.4/src/encoder.rs:151:53
        |
    151 |         if nested_encoder.finish()?.len() == length.try_into()? {
        |                                                     ^^^^^^^^ the trait `From<Length>` is not implemented for `()`
        |
        = note: required because of the requirements on the impl of `Into<()>` for `Length`
    note: required because of the requirements on the impl of `TryFrom<Length>` for `()`
       --> /home/misha/.cargo/registry/src/github.com-1ecc6299db9ec823/der-0.4.4/src/asn1/null.rs:46:6
        |
    46  | impl TryFrom<Any<'_>> for () {
        |      ^^^^^^^^^^^^^^^^     ^^
        = note: required because of the requirements on the impl of `TryInto<()>` for `Length`
    
    For more information about this error, try `rustc --explain E0277`.
    error: could not compile `der` due to 2 previous errors
    Error: Compiling your crate to WebAssembly failed
    Caused by: failed to execute `cargo build`: exited with exit status: 101
      full command: "cargo" "build" "--lib" "--release" "--target" "wasm32-unknown-unknown"
    

    Proposed fix

    I did some basic testing and found that patching the encoder with the following line appeared to resolve it on v0.4.4, but I didn't get the chance to test it on master. In https://github.com/RustCrypto/formats/blob/master/der/src/encoder.rs#L159

            Header::new(Tag::Sequence, length).and_then(|header| header.encode(self))?;
    
            let mut nested_encoder = Encoder::new(self.reserve(length)?);
            f(&mut nested_encoder)?;
    
    +       let len: usize = length.try_into()?;
    +       if nested_encoder.finish()?.len() == len {
    -       if nested_encoder.finish()?.len() == length.try_into()? {
                Ok(())
            } else {
                self.error(ErrorKind::Length { tag: Tag::Sequence })
            }
    

    I wanted to get some thoughts before opening a PR though because this seems like a bandaid fix. Am happy to open a PR though if the maintainers think this is worth fixing and the fix is acceptable!

    Edit: Going to open one anyway because it's easy

    opened by mishazharov 12
  • tls-codec

    tls-codec

    Moving code from https://github.com/openmls/tls-codec/

    I'm sure there are a couple things in here we want to touch. Some things I noticed

    • [x] There's currently only an MIT license. We have to add Apache
    • [ ] We should agree on a badge style
    • [x] I added CI, let's see if that's working. I also added Windows and macOS targets.
    • [x] Are there binaries or why do we have a Cargo.lock?
    • [x] There are no-std CI targets. tls-codec wasn't written with no-std in mind so far.

    I'm sure there's more. Let me know what you think @tarcieri

    opened by franziskuskiefer 12
  • der: Any vs AnyRef: issues with generating AlgorithmIdentifier's parameters on the fly

    der: Any vs AnyRef: issues with generating AlgorithmIdentifier's parameters on the fly

    I tried writing a function that returns complete AlgorithmIdentifier for the RSASSA-PSS algorithm. However my attempts to write a sensible one have failed up to now, as it's not possible to embed an owned value into the parameters field (AnyRef). I ended up declaring static byte array with the PSS parameters in DER encoding, but it is not really intuitive.

    opened by lumag 11
  • chore(deps): bump rstest from 0.12.0 to 0.14.0

    chore(deps): bump rstest from 0.12.0 to 0.14.0

    Bumps rstest from 0.12.0 to 0.14.0.

    Release notes

    Sourced from rstest's releases.

    0.14.0

    Feature gate async-timeout

    0.13.0

    Timeout

    Introduce #[timeout] attribute

    Changelog

    Sourced from rstest's changelog.

    [0.14.0] 2022/06/19

    Changed

    • Feature gated async timeout via async-timeout feature [see #148]

    Fixed

    • Removed async-std build dependency [see #148]

    [0.13.0] 2022/05/15

    Add

    • #[timeout(duration)] test implementation for both sync and async tests (See #136)

    Changed

    • Split rstest in separated crates for macro and libs (See #32)
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 11
  • spki: make `AlgorithmIdentifier` generic around `Params`

    spki: make `AlgorithmIdentifier` generic around `Params`

    NOTE: breaking change.

    Previously AlgorithmIdentifier::parameters were always AnyRef. This commit changes them to a generic parameter Params.

    An alias AlgorithmIdentifierRef provides a type identical to the original with AnyRef as its parameters, which is used in all of the other crates in this repo.

    cc @baloo @lumag

    opened by tarcieri 10
  • Derive `tls_codec` traits for enumerations with data

    Derive `tls_codec` traits for enumerations with data

    This PR adds the ability to derive the tls_codec traits for enumerations with data. It also adds an attribute to specify what the discriminant should be. The tls_codec_derive crate documentation provides more details. Thank you.

    opened by stephaneyfx 10
  • WIP: add test for mixed DER/BER encoding CMS

    WIP: add test for mixed DER/BER encoding CMS

    As requested in #813 a test for mixed encoding CMS.

    @tarcieri I didn't find my original BER file from the Apple MDM Signature so I just checked the example at https://lapo.it/asn1js/# and it's very similar in that it starts with an indefinite length tag, uses multiple along the way and also uses constructed undefined length OctetStrings.

    Both the DER/BER file have the same e_content. Currently the DER encoded file is used in the test and works fine.

    opened by smndtrl 0
  • x509-cert: another parse failure on publicly known cert

    x509-cert: another parse failure on publicly known cert

    Like #821, although probably a different cause: d3eefbcbbcf49867838626e23bb59ca01e305db7 in the Windows CTL fails to parse with:

    ASN.1 DER message is too long at DER byte 60
    

    The offending cert, as PEM:

    -----BEGIN CERTIFICATE-----
    MIIDcTCCAlmgAwIBAgIVAOYJ/nrqAGiM4CS07SAbH+9StETRMA0GCSqGSIb3DQEB
    BQUAMFAxCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9LcmFqb3dhIEl6YmEgUm96bGlj
    emVuaW93YSBTLkEuMRcwFQYDVQQDDA5TWkFGSVIgUk9PVCBDQTAeFw0xMTEyMDYx
    MTEwNTdaFw0zMTEyMDYxMTEwNTdaMFAxCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9L
    cmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRcwFQYDVQQDDA5TWkFGSVIg
    Uk9PVCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKxHL49ZMTml
    6g3wpYwrvQKkvc0Kc6oJ5sxfgmp1qZfluwbv88BdocHSiXlY8NzrVYzuWBp7J/9K
    ULMAoWoTIzOQ6C9TNm4YbA9A1jdX1wYNL5Akylf8W5L/I4BXhT9KnlI6x+a7BVAm
    nr/Ttl+utT/Asms2fRfEsF2vZPMxH4UFqOAhFjxTkmJWf2Cu4nvRQJHcttB+cEAo
    ag/hERt/+tzo4URz6x6r19toYmxx4FjjBkUhWQw1X21re//Hof2+0YgiwYT84zLb
    eqDqCOMOXxvH480yGDkh/QoazWX3U75HQExT/iJlwnu7I1V6HXztKIwCBjsxffbH
    3jOshCJtywcCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC
    AQYwHQYDVR0OBBYEFFOSo33/gnbwM9TrkmdHYTMbaDsqMA0GCSqGSIb3DQEBBQUA
    A4IBAQA5UFWd5EL/pBviIMm1zD2JLUCpp0mJG7JkwznIOzawhGmFFaxGoxAhQBEg
    haP+E0KR66oAwVC6xe32QUVSHfWqWndzbODzLB8yj7WAR0cDM45ZngSBPBuFE3Wu
    GLJX9g100ETfIX+4YBR/4NR/uvTnpnd9ete7Whl0ZfY94yuu4xQqB5QFv+P7IXXV
    lTOjkjuGXEcyQAjQzbFaT9vIABSbeCXWBbjvOXukJy6WgAiclzGNSYprre8Ryydd
    fmjW9HIGwsIO03EldivvqEYL1Hv1w/Pur+6FUEOaL68PEIUovfgwIB2BAw+vZDuw
    cH0mX548PojGyg434cDjkSXa3mHF
    -----END CERTIFICATE-----
    

    Happy to debug this again, just making the issue for visibility.

    opened by woodruffw 4
  • added `impl AsRef<[u8]> for SecretDocument`

    added `impl AsRef<[u8]> for SecretDocument`

    Hey, I'm using std::fs::write and its signature looks like that: (it has AsRef generic) image

    and I think I found one hole in your API:

    error[E0277]: the trait bound `SecretDocument: AsRef<[u8]>` is not satisfied
       --> keypair/build.rs:25:55
        |
    25  |     fs::write(keys_dir.join("private_key_pkcs1.der"), private_key_der)?;
        |     ---------                                         ^^^^^^^^^^^^^^^ the trait `AsRef<[u8]>` is not implemented for `SecretDocument`
        |     |
        |     required by a bound introduced by this call
    

    Now the developer needs to manually call .as_bytes() for SecretDocument, but Document already has impl AsRef<[u8]> for Document image1

    opened by StackOverflowExcept1on 7
  • DER: adding a field which is already DER encoded?

    DER: adding a field which is already DER encoded?

    Suppose I have a struct:

    
    use der::Sequence;
    
    #[derive(Sequence)]
    struct MyThing {
       things: Vec<u8>,
       already_encoded: Vec<u8>,
    }
    

    How could I add bytes to MyThing.already_encoded that is a Vec that's from some other der::Encode.to_vec()? That is, I have something else already der-encoded (let's say der(thing)), and don't want to have an additional wrapper of der encoded vec of vec of bytes (let's say der(der(thing))).

    opened by rjzak 1
  • pkcs7, der: mixed BER/DER encoding with undefined length

    pkcs7, der: mixed BER/DER encoding with undefined length

    Hi,

    while looking into the pkcs7 crate for a CMS usecase around the Apple world I discovered that their detached signatures use the BER indefinite length encoding for some of the SEQUENCE which of course is not supported by the der crate.

    Has there been any thoughts/discussions around if that's something the formats repo should address or if that is out of scope (for now) and left to other crates.

    I started with adding the signed-data content to pkcs7 validating against a DER encoded signature and discovered the problem afterwards with the ones Apple generates :( Link to example

    Simon

    opened by smndtrl 5
  • x509-cert: move to all owned types?

    x509-cert: move to all owned types?

    The x509-cert crate currently has a hard dependency on alloc, but several types still have a lifetime which borrows from the input, which precludes one-pass decoding from PEM (where Base64 is decoded directly into owned types) and makes writing things like certificate builders harder.

    We could potentially move entirely to types which own their backing data, eliminating lifetimes from all types. We could still potentially have a corresponding set of borrowed e.g. Ref types (see https://github.com/RustCrypto/formats/issues/689), but using owned types would make usage more convenient at the cost of losing zero-copy decoding from DER bytes.

    opened by tarcieri 7
Owner
Rust Crypto
Cryptographic algorithms written in pure Rust
Rust Crypto
Traits - Collection of cryptography-related traits

RustCrypto: Traits Collection of traits which describe functionality of cryptographic primitives. Crates Name Algorithm Crates.io Docs MSRV aead Authe

Rust Crypto 401 Dec 27, 2022
A general solution for commonly used crypt in rust, collection of cryptography-related traits and algorithms.

Crypto-rs A general solution for commonly used crypt in rust, collection of cryptography-related traits and algorithms. This is a Rust implementation

houseme 4 Nov 28, 2022
convert CHAIN format to PAF format

convert CHAIN format to PAF format

Andrea Guarracino 9 May 24, 2022
Example implementation for Biscuit tokens cryptography

example implementation for Biscuit token cryptography To aid in the implementation of Biscuit tokens in various languages, this repository contains an

Clever Cloud 6 May 25, 2021
Mundane is a Rust cryptography library backed by BoringSSL that is difficult to misuse, ergonomic, and performant (in that order).

Mundane Mundane is a Rust cryptography library backed by BoringSSL that is difficult to misuse, ergonomic, and performant (in that order). Issues and

Google 1.1k Jan 3, 2023
Manage secret values in-repo via public key cryptography

amber Manage secret values in-repo via public key cryptography. See the announcement blog post for more motivation. Amber provides the ability to secu

FP Complete 82 Nov 10, 2022
Implementation of the Web Cryptography specification in Rust.

[wip] webcrypto Implementation of the Web Cryptography specification in Rust. This crate hopes to ease interoperability between WASM and native target

Divy Srivastava 5 Mar 7, 2022
Cryptography-oriented big integer library with constant-time, stack-allocated (no_std-friendly) implementations of modern formulas

RustCrypto: Cryptographic Big Integers Pure Rust implementation of a big integer library which has been designed from the ground-up for use in cryptog

Rust Crypto 88 Dec 31, 2022
Pairing cryptography library in Rust

bn This is a pairing cryptography library written in pure Rust. It makes use of the Barreto-Naehrig (BN) curve construction from [BCTV2015] to provide

Electric Coin Company Prototypes and Experiments 139 Dec 15, 2022
Pairing cryptography library in Rust

bn This is a pairing cryptography library written in pure Rust. It makes use of the Barreto-Naehrig (BN) curve construction from [BCTV2015] to provide

Parity Technologies 23 Apr 22, 2022
BLS12-381 cryptography using Apache Milagro

BLS12-381 Aggregate Signatures in Rust using Apache Milagro WARNING: This library is a work in progress and has not been audited. Do NOT consider the

Sigma Prime 21 Apr 4, 2022
Ursa - Hyperledger Ursa is a shared cryptography library

HYPERLEDGER URSA Introduction Features Libursa Libzmix Dependencies Building from source Contributing Introduction Ursa was created because people in

Hyperledger 307 Dec 20, 2022
Collect libraries and packages about cryptography in Rust.

Awesome Cryptography Rust Collect libraries and packages about cryptography in Rust. Collection Library Symmetric Public-key / Asymmetric One-way Hash

Rust Cryptography Community 282 Dec 25, 2022
A down-to-the-metal ongoing cryptography challenge designed by Radical Semiconductor.

woodpecker ?? [NOTE: scoreboard will now be updated weekends, starting the weekend of 12/10/2022--sorry for delays! I'll also be merging in pull reque

Radical Semiconductor 16 Dec 15, 2022
Elliptic curve cryptography on Soroban.

Elliptic Curve Cryptography on Soroban Contract examples and reusable primitives. Groth 16 verifier. This crate provides a SorobanGroth16Verifier obje

Xycloo Labs 5 Feb 10, 2023
HD wallet BIP-32 related key derivation utilities.

HDWallet Docs HD wallet(BIP-32) key derivation utilities. This crate is build upon secp256k1 crate, this crate only provides BIP-32 related features,

jjy 23 Nov 27, 2022
Prototype: ORAM and related for Intel SGX enclaves

mc-oblivious Traits and implementations for Oblivious RAM inside of Intel SGX enclaves. The scope of this repository is: Traits for fast constant-time

MobileCoin 37 Nov 23, 2022
A tool to identify related SSL keys, CSRs, and certificates.

⛓ sslchains A tool to identify related SSL keys, CSRs, and certificates. Usage Default Display Mode Run with any number of path arguments to define th

Gary Locke 1 Apr 2, 2022
Library with support for de/serialization, parsing and executing on data-structures and network messages related to Bitcoin

Rust Bitcoin Library with support for de/serialization, parsing and executing on data-structures and network messages related to Bitcoin. Heads up for

Rust Bitcoin Community 1.3k Dec 29, 2022