spki-0.7.2/.cargo_vcs_info.json0000644000000001420000000000100120050ustar { "git": { "sha1": "ade4dc30e6cb4fb1ce33eb6f5a43abc39d7f2e9d" }, "path_in_vcs": "spki" }spki-0.7.2/CHANGELOG.md000064400000000000000000000104711046102023000124140ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## 0.7.2 (2023-05-04) ### Added - `AlgorithmIdentifierWithOid` trait ([#986]) - `SignatureBitStringEncoding` trait ([#1047]) ### Changed - Bump `hex-literal` to v0.4.1 ([#999]) [#986]: https://github.com/RustCrypto/formats/pull/986 [#999]: https://github.com/RustCrypto/formats/pull/999 [#1047]: https://github.com/RustCrypto/formats/pull/1047 ## 0.7.1 (2023-04-04) ### Added - `AssociatedAlgorithmIdentifier` trait ([#962], [#966]) - `DynAssociatedAlgorithmIdentifier` trait ([#962]) - `SignatureAlgorithmIdentifier` trait ([#967]) - `DynSignatureAlgorithmIdentifier` trait ([#967]) ### Changed - Bump `der` dependency to v0.7.2 ([#979]) [#962]: https://github.com/RustCrypto/formats/pull/962 [#966]: https://github.com/RustCrypto/formats/pull/966 [#967]: https://github.com/RustCrypto/formats/pull/967 [#979]: https://github.com/RustCrypto/formats/pull/979 ## 0.7.0 (2023-02-26) ### Changed - Make `AlgorithmIdentifier` generic around `Params` ([#769]) - Use blanket impls for `Decode*` traits ([#785]) - Make `SubjectPublicKeyInfo` own the public key ([#790]) - Rename `to_owned` method ([#835]) - Bump `der` dependency to v0.7 ([#899]) [#769]: https://github.com/RustCrypto/formats/pull/769 [#785]: https://github.com/RustCrypto/formats/pull/785 [#790]: https://github.com/RustCrypto/formats/pull/790 [#835]: https://github.com/RustCrypto/formats/pull/835 [#899]: https://github.com/RustCrypto/formats/pull/899 ## 0.6.0 (2022-05-08) ### Added - `AlgorithmIdentifier::oids()` helper function ([#443]) - Impl `PartialOrd` for `AlgorithmIdentifier` ([#476]) - Impl `DecodeValue` for `AlgorithmIdentifier` ([#449]) - Impl `ValueOrd` for `SubjectPublicKeyInfo` ([#522]) ### Changed - Replace `PublicKeyDocument` with `der` crate's `Document` type ([#571]) - Streaming fingerprint builder ([#616]) - Bump `der` crate dependency to v0.6 ([#653]) ### Removed - `PublicKeyDocument` ([#571]) [#443]: https://github.com/RustCrypto/formats/pull/443 [#449]: https://github.com/RustCrypto/formats/pull/449 [#476]: https://github.com/RustCrypto/formats/pull/476 [#522]: https://github.com/RustCrypto/formats/pull/522 [#571]: https://github.com/RustCrypto/formats/pull/571 [#616]: https://github.com/RustCrypto/formats/pull/616 [#653]: https://github.com/RustCrypto/formats/pull/653 ## 0.5.4 (2022-01-05) ### Added - `Error::KeyMalformed` variant ([#318]) [#318]: https://github.com/RustCrypto/formats/pull/318 ## 0.5.3 (2021-12-19) ### Added - Impl `ValueOrd` for `AlgorithmIdentifier` ([#289]) [#289]: https://github.com/RustCrypto/formats/pull/289 ## 0.5.2 (2021-11-17) ### Changed - Relax `base64ct` version requirement to `^1` ([#239]) [#239]: https://github.com/RustCrypto/formats/pull/239 ## 0.5.1 (2021-11-17) ### Changed - Replace `from_spki` with `TryFrom` ([#231]) [#231]: https://github.com/RustCrypto/formats/pull/231 ## 0.5.0 (2021-11-15) [YANKED] ### Added - SPKI fingerprint support ([#36]) - `PublicKeyDocument` type originally from `pkcs8` crate ([#118]) - `Error` type ([#143]) ### Changed - Rename `From/ToPublicKey` => `DecodePublicKey`/`EncodePublicKey` ([#119]) - Use `der::Document` to impl `PublicKeyDocument` ([#134]) - Rust 2021 edition upgrade; MSRV 1.56 ([#136]) - Bump `der` dependency to v0.5 ([#222]) [#36]: https://github.com/RustCrypto/formats/pull/36 [#118]: https://github.com/RustCrypto/formats/pull/118 [#119]: https://github.com/RustCrypto/formats/pull/119 [#134]: https://github.com/RustCrypto/formats/pull/134 [#136]: https://github.com/RustCrypto/formats/pull/136 [#143]: https://github.com/RustCrypto/formats/pull/143 [#222]: https://github.com/RustCrypto/formats/pull/222 ## 0.4.1 (2021-09-14) ### Changed - Moved to `formats` repo ([#2]) [#2]: https://github.com/RustCrypto/formats/pull/2 ## 0.4.0 (2021-06-07) ### Added - `AlgorithmIdentifier::assert_oids` ### Changed - Bump `der` to v0.4 ## 0.3.0 (2021-03-22) ### Changed - Bump `der` to v0.3 ### Removed - `AlgorithmParameters` enum ## 0.2.1 (2021-02-22) ### Added - Impl `Choice` for `AlgorithmParameters` ## 0.2.0 (2021-02-18) ### Changed - Return `Result` from `AlgorithmIdentifier::params_*` ## 0.1.0 (2021-02-16) - Initial release spki-0.7.2/Cargo.toml0000644000000032710000000000100100110ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.65" name = "spki" version = "0.7.2" authors = ["RustCrypto Developers"] description = """ X.509 Subject Public Key Info (RFC5280) describing public keys as well as their associated AlgorithmIdentifiers (i.e. OIDs) """ readme = "README.md" keywords = [ "crypto", "x509", ] categories = [ "cryptography", "data-structures", "encoding", "no-std", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/RustCrypto/formats/tree/master/spki" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [dependencies.arbitrary] version = "1.2" features = ["derive"] optional = true [dependencies.base64ct] version = "1" optional = true default-features = false [dependencies.der] version = "0.7.2" features = ["oid"] [dependencies.sha2] version = "0.10" optional = true default-features = false [dev-dependencies.hex-literal] version = "0.4" [dev-dependencies.tempfile] version = "3" [features] alloc = [ "base64ct?/alloc", "der/alloc", ] arbitrary = [ "std", "dep:arbitrary", "der/arbitrary", ] base64 = ["dep:base64ct"] fingerprint = ["sha2"] pem = [ "alloc", "der/pem", ] std = [ "der/std", "alloc", ] spki-0.7.2/Cargo.toml.orig000064400000000000000000000021621046102023000134700ustar 00000000000000[package] name = "spki" version = "0.7.2" description = """ X.509 Subject Public Key Info (RFC5280) describing public keys as well as their associated AlgorithmIdentifiers (i.e. OIDs) """ authors = ["RustCrypto Developers"] license = "Apache-2.0 OR MIT" repository = "https://github.com/RustCrypto/formats/tree/master/spki" categories = ["cryptography", "data-structures", "encoding", "no-std"] keywords = ["crypto", "x509"] readme = "README.md" edition = "2021" rust-version = "1.65" [dependencies] der = { version = "0.7.2", features = ["oid"] } # Optional dependencies arbitrary = { version = "1.2", features = ["derive"], optional = true } base64ct = { version = "1", optional = true, default-features = false } sha2 = { version = "0.10", optional = true, default-features = false } [dev-dependencies] hex-literal = "0.4" tempfile = "3" [features] alloc = ["base64ct?/alloc", "der/alloc"] std = ["der/std", "alloc"] arbitrary = ["std", "dep:arbitrary", "der/arbitrary"] base64 = ["dep:base64ct"] fingerprint = ["sha2"] pem = ["alloc", "der/pem"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] spki-0.7.2/LICENSE-APACHE000064400000000000000000000251411046102023000125270ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. spki-0.7.2/LICENSE-MIT000064400000000000000000000020721046102023000122350ustar 00000000000000Copyright (c) 2021-2023 The RustCrypto Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. spki-0.7.2/README.md000064400000000000000000000035441046102023000120650ustar 00000000000000# [RustCrypto]: X.509 Subject Public Key Info (SPKI) [![crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] [![Build Status][build-image]][build-link] ![Apache2/MIT licensed][license-image] ![Rust Version][rustc-image] [![Project Chat][chat-image]][chat-link] [X.509] Subject Public Key Info types describing public keys as well as their associated AlgorithmIdentifiers (i.e. OIDs). Specified in [RFC 5280 § 4.1]. [Documentation][docs-link] ## Minimum Supported Rust Version This crate requires **Rust 1.65** at a minimum. We may change the MSRV in the future, but it will be accompanied by a minor version bump. ## License Licensed under either of: * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) * [MIT license](http://opensource.org/licenses/MIT) 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. [//]: # (badges) [crate-image]: https://buildstats.info/crate/spki [crate-link]: https://crates.io/crates/spki [docs-image]: https://docs.rs/spki/badge.svg [docs-link]: https://docs.rs/spki/ [build-image]: https://github.com/RustCrypto/formats/actions/workflows/spki.yml/badge.svg [build-link]: https://github.com/RustCrypto/formats/actions/workflows/spki.yml [license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg [rustc-image]: https://img.shields.io/badge/rustc-1.65+-blue.svg [chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg [chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/300570-formats [//]: # (links) [RustCrypto]: https://github.com/rustcrypto [X.509]: https://en.wikipedia.org/wiki/X.509 [RFC 5280 § 4.1]: https://tools.ietf.org/html/rfc5280#section-4.1 spki-0.7.2/src/algorithm.rs000064400000000000000000000134171046102023000137310ustar 00000000000000//! X.509 `AlgorithmIdentifier` use crate::{Error, Result}; use core::cmp::Ordering; use der::{ asn1::{AnyRef, Choice, ObjectIdentifier}, Decode, DecodeValue, DerOrd, Encode, EncodeValue, Header, Length, Reader, Sequence, ValueOrd, Writer, }; #[cfg(feature = "alloc")] use der::asn1::Any; /// X.509 `AlgorithmIdentifier` as defined in [RFC 5280 Section 4.1.1.2]. /// /// ```text /// AlgorithmIdentifier ::= SEQUENCE { /// algorithm OBJECT IDENTIFIER, /// parameters ANY DEFINED BY algorithm OPTIONAL } /// ``` /// /// [RFC 5280 Section 4.1.1.2]: https://tools.ietf.org/html/rfc5280#section-4.1.1.2 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)] pub struct AlgorithmIdentifier { /// Algorithm OID, i.e. the `algorithm` field in the `AlgorithmIdentifier` /// ASN.1 schema. pub oid: ObjectIdentifier, /// Algorithm `parameters`. pub parameters: Option, } impl<'a, Params> DecodeValue<'a> for AlgorithmIdentifier where Params: Choice<'a>, { fn decode_value>(reader: &mut R, header: Header) -> der::Result { reader.read_nested(header.length, |reader| { Ok(Self { oid: reader.decode()?, parameters: reader.decode()?, }) }) } } impl EncodeValue for AlgorithmIdentifier where Params: Encode, { fn value_len(&self) -> der::Result { self.oid.encoded_len()? + self.parameters.encoded_len()? } fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> { self.oid.encode(writer)?; self.parameters.encode(writer)?; Ok(()) } } impl<'a, Params> Sequence<'a> for AlgorithmIdentifier where Params: Choice<'a> + Encode {} impl<'a, Params> TryFrom<&'a [u8]> for AlgorithmIdentifier where Params: Choice<'a> + Encode, { type Error = Error; fn try_from(bytes: &'a [u8]) -> Result { Ok(Self::from_der(bytes)?) } } impl ValueOrd for AlgorithmIdentifier where Params: DerOrd, { fn value_cmp(&self, other: &Self) -> der::Result { match self.oid.der_cmp(&other.oid)? { Ordering::Equal => self.parameters.der_cmp(&other.parameters), other => Ok(other), } } } /// `AlgorithmIdentifier` reference which has `AnyRef` parameters. pub type AlgorithmIdentifierRef<'a> = AlgorithmIdentifier>; /// `AlgorithmIdentifier` with `ObjectIdentifier` parameters. pub type AlgorithmIdentifierWithOid = AlgorithmIdentifier; /// `AlgorithmIdentifier` reference which has `Any` parameters. #[cfg(feature = "alloc")] pub type AlgorithmIdentifierOwned = AlgorithmIdentifier; impl AlgorithmIdentifier { /// Assert the `algorithm` OID is an expected value. pub fn assert_algorithm_oid(&self, expected_oid: ObjectIdentifier) -> Result { if self.oid == expected_oid { Ok(expected_oid) } else { Err(Error::OidUnknown { oid: expected_oid }) } } } impl<'a> AlgorithmIdentifierRef<'a> { /// Assert `parameters` is an OID and has the expected value. pub fn assert_parameters_oid( &self, expected_oid: ObjectIdentifier, ) -> Result { let actual_oid = self.parameters_oid()?; if actual_oid == expected_oid { Ok(actual_oid) } else { Err(Error::OidUnknown { oid: expected_oid }) } } /// Assert the values of the `algorithm` and `parameters` OIDs. pub fn assert_oids( &self, algorithm: ObjectIdentifier, parameters: ObjectIdentifier, ) -> Result<()> { self.assert_algorithm_oid(algorithm)?; self.assert_parameters_oid(parameters)?; Ok(()) } /// Get the `parameters` field as an [`AnyRef`]. /// /// Returns an error if `parameters` are `None`. pub fn parameters_any(&self) -> Result> { self.parameters.ok_or(Error::AlgorithmParametersMissing) } /// Get the `parameters` field as an [`ObjectIdentifier`]. /// /// Returns an error if it is absent or not an OID. pub fn parameters_oid(&self) -> Result { Ok(ObjectIdentifier::try_from(self.parameters_any()?)?) } /// Convert to a pair of [`ObjectIdentifier`]s. /// /// This method is helpful for decomposing in match statements. Note in /// particular that `NULL` parameters are treated the same as missing /// parameters. /// /// Returns an error if parameters are present but not an OID. pub fn oids(&self) -> der::Result<(ObjectIdentifier, Option)> { Ok(( self.oid, match self.parameters { None => None, Some(p) => match p { AnyRef::NULL => None, _ => Some(p.decode_as::()?), }, }, )) } } #[cfg(feature = "alloc")] mod allocating { use super::*; use der::referenced::*; impl<'a> RefToOwned<'a> for AlgorithmIdentifierRef<'a> { type Owned = AlgorithmIdentifierOwned; fn ref_to_owned(&self) -> Self::Owned { AlgorithmIdentifier { oid: self.oid, parameters: self.parameters.ref_to_owned(), } } } impl OwnedToRef for AlgorithmIdentifierOwned { type Borrowed<'a> = AlgorithmIdentifierRef<'a>; fn owned_to_ref(&self) -> Self::Borrowed<'_> { AlgorithmIdentifier { oid: self.oid, parameters: self.parameters.owned_to_ref(), } } } } spki-0.7.2/src/error.rs000064400000000000000000000035351046102023000130740ustar 00000000000000//! Error types use core::fmt; use der::asn1::ObjectIdentifier; /// Result type with `spki` crate's [`Error`] type. pub type Result = core::result::Result; #[cfg(feature = "pem")] use der::pem; /// Error type #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[non_exhaustive] pub enum Error { /// Algorithm parameters are missing. AlgorithmParametersMissing, /// ASN.1 DER-related errors. Asn1(der::Error), /// Malformed cryptographic key contained in a SPKI document. /// /// This is intended for relaying errors related to the raw data contained /// in [`SubjectPublicKeyInfo::subject_public_key`][`crate::SubjectPublicKeyInfo::subject_public_key`]. KeyMalformed, /// Unknown algorithm OID. OidUnknown { /// Unrecognized OID value found in e.g. a SPKI `AlgorithmIdentifier`. oid: ObjectIdentifier, }, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::AlgorithmParametersMissing => { f.write_str("AlgorithmIdentifier parameters missing") } Error::Asn1(err) => write!(f, "ASN.1 error: {}", err), Error::KeyMalformed => f.write_str("SPKI cryptographic key data malformed"), Error::OidUnknown { oid } => { write!(f, "unknown/unsupported algorithm OID: {}", oid) } } } } impl From for Error { fn from(err: der::Error) -> Error { if let der::ErrorKind::OidUnknown { oid } = err.kind() { Error::OidUnknown { oid } } else { Error::Asn1(err) } } } #[cfg(feature = "pem")] impl From for Error { fn from(err: pem::Error) -> Error { der::Error::from(err).into() } } #[cfg(feature = "std")] impl std::error::Error for Error {} spki-0.7.2/src/fingerprint.rs000064400000000000000000000021411046102023000142620ustar 00000000000000//! SPKI fingerprint support. use der::Writer; use sha2::{Digest, Sha256}; /// Size of a SHA-256 SPKI fingerprint in bytes. pub(crate) const SIZE: usize = 32; /// Raw bytes of a SPKI fingerprint i.e. SHA-256 digest of /// `SubjectPublicKeyInfo`'s DER encoding. /// /// See [RFC7469 § 2.1.1] for more information. /// /// [RFC7469 § 2.1.1]: https://datatracker.ietf.org/doc/html/rfc7469#section-2.1.1 pub type FingerprintBytes = [u8; SIZE]; /// Writer newtype which accepts DER being serialized on-the-fly and computes a /// hash of the contents. #[derive(Clone, Default)] pub(crate) struct Builder { /// In-progress digest being computed from streaming DER. digest: Sha256, } impl Builder { /// Create a new fingerprint builder. pub fn new() -> Self { Self::default() } /// Finish computing a fingerprint, returning the computed digest. pub fn finish(self) -> FingerprintBytes { self.digest.finalize().into() } } impl Writer for Builder { fn write(&mut self, der_bytes: &[u8]) -> der::Result<()> { self.digest.update(der_bytes); Ok(()) } } spki-0.7.2/src/lib.rs000064400000000000000000000037111046102023000125050ustar 00000000000000#![no_std] #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![doc = include_str!("../README.md")] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg" )] #![forbid(unsafe_code)] #![warn( clippy::mod_module_files, clippy::unwrap_used, missing_docs, rust_2018_idioms, unused_lifetimes, unused_qualifications )] //! # Usage //! The following example demonstrates how to use an OID as the `parameters` //! of an [`AlgorithmIdentifier`]. //! //! Borrow the [`ObjectIdentifier`] first then use [`der::AnyRef::from`] or `.into()`: //! //! ``` //! use spki::{AlgorithmIdentifier, ObjectIdentifier}; //! //! let alg_oid = "1.2.840.10045.2.1".parse::().unwrap(); //! let params_oid = "1.2.840.10045.3.1.7".parse::().unwrap(); //! //! let alg_id = AlgorithmIdentifier { //! oid: alg_oid, //! parameters: Some(params_oid) //! }; //! ``` #[cfg(feature = "alloc")] #[allow(unused_extern_crates)] extern crate alloc; #[cfg(feature = "std")] extern crate std; mod algorithm; mod error; mod spki; mod traits; #[cfg(feature = "fingerprint")] mod fingerprint; pub use crate::{ algorithm::{AlgorithmIdentifier, AlgorithmIdentifierRef, AlgorithmIdentifierWithOid}, error::{Error, Result}, spki::{SubjectPublicKeyInfo, SubjectPublicKeyInfoRef}, traits::{AssociatedAlgorithmIdentifier, DecodePublicKey, SignatureAlgorithmIdentifier}, }; pub use der::{self, asn1::ObjectIdentifier}; #[cfg(feature = "alloc")] pub use { crate::{ algorithm::AlgorithmIdentifierOwned, spki::SubjectPublicKeyInfoOwned, traits::{ DynAssociatedAlgorithmIdentifier, DynSignatureAlgorithmIdentifier, EncodePublicKey, SignatureBitStringEncoding, }, }, der::Document, }; #[cfg(feature = "fingerprint")] pub use crate::fingerprint::FingerprintBytes; spki-0.7.2/src/spki.rs000064400000000000000000000144241046102023000127100ustar 00000000000000//! X.509 `SubjectPublicKeyInfo` use crate::{AlgorithmIdentifier, Error, Result}; use core::cmp::Ordering; use der::{ asn1::{AnyRef, BitStringRef}, Choice, Decode, DecodeValue, DerOrd, Encode, EncodeValue, FixedTag, Header, Length, Reader, Sequence, ValueOrd, Writer, }; #[cfg(feature = "alloc")] use der::{ asn1::{Any, BitString}, Document, }; #[cfg(feature = "fingerprint")] use crate::{fingerprint, FingerprintBytes}; #[cfg(feature = "pem")] use der::pem::PemLabel; /// [`SubjectPublicKeyInfo`] with [`AnyRef`] algorithm parameters, and [`BitStringRef`] params. pub type SubjectPublicKeyInfoRef<'a> = SubjectPublicKeyInfo, BitStringRef<'a>>; /// [`SubjectPublicKeyInfo`] with [`Any`] algorithm parameters, and [`BitString`] params. #[cfg(feature = "alloc")] pub type SubjectPublicKeyInfoOwned = SubjectPublicKeyInfo; /// X.509 `SubjectPublicKeyInfo` (SPKI) as defined in [RFC 5280 § 4.1.2.7]. /// /// ASN.1 structure containing an [`AlgorithmIdentifier`] and public key /// data in an algorithm specific format. /// /// ```text /// SubjectPublicKeyInfo ::= SEQUENCE { /// algorithm AlgorithmIdentifier, /// subjectPublicKey BIT STRING } /// ``` /// /// [RFC 5280 § 4.1.2.7]: https://tools.ietf.org/html/rfc5280#section-4.1.2.7 #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] #[derive(Clone, Debug, Eq, PartialEq)] pub struct SubjectPublicKeyInfo { /// X.509 [`AlgorithmIdentifier`] for the public key type pub algorithm: AlgorithmIdentifier, /// Public key data pub subject_public_key: Key, } impl<'a, Params, Key> SubjectPublicKeyInfo where Params: Choice<'a> + Encode, // TODO: replace FixedTag with FixedTag once // https://github.com/rust-lang/rust/issues/92827 is fixed Key: Decode<'a> + Encode + FixedTag, { /// Calculate the SHA-256 fingerprint of this [`SubjectPublicKeyInfo`] and /// encode it as a Base64 string. /// /// See [RFC7469 § 2.1.1] for more information. /// /// [RFC7469 § 2.1.1]: https://datatracker.ietf.org/doc/html/rfc7469#section-2.1.1 #[cfg(all(feature = "fingerprint", feature = "alloc", feature = "base64"))] pub fn fingerprint_base64(&self) -> Result { use base64ct::{Base64, Encoding}; Ok(Base64::encode_string(&self.fingerprint_bytes()?)) } /// Calculate the SHA-256 fingerprint of this [`SubjectPublicKeyInfo`] as /// a raw byte array. /// /// See [RFC7469 § 2.1.1] for more information. /// /// [RFC7469 § 2.1.1]: https://datatracker.ietf.org/doc/html/rfc7469#section-2.1.1 #[cfg(feature = "fingerprint")] pub fn fingerprint_bytes(&self) -> Result { let mut builder = fingerprint::Builder::new(); self.encode(&mut builder)?; Ok(builder.finish()) } } impl<'a: 'k, 'k, Params, Key: 'k> DecodeValue<'a> for SubjectPublicKeyInfo where Params: Choice<'a> + Encode, Key: Decode<'a>, { fn decode_value>(reader: &mut R, header: Header) -> der::Result { reader.read_nested(header.length, |reader| { Ok(Self { algorithm: reader.decode()?, subject_public_key: Key::decode(reader)?, }) }) } } impl<'a, Params, Key> EncodeValue for SubjectPublicKeyInfo where Params: Choice<'a> + Encode, Key: Encode, { fn value_len(&self) -> der::Result { self.algorithm.encoded_len()? + self.subject_public_key.encoded_len()? } fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> { self.algorithm.encode(writer)?; self.subject_public_key.encode(writer)?; Ok(()) } } impl<'a, Params, Key> Sequence<'a> for SubjectPublicKeyInfo where Params: Choice<'a> + Encode, Key: Decode<'a> + Encode + FixedTag, { } impl<'a, Params, Key> TryFrom<&'a [u8]> for SubjectPublicKeyInfo where Params: Choice<'a> + Encode, Key: Decode<'a> + Encode + FixedTag, { type Error = Error; fn try_from(bytes: &'a [u8]) -> Result { Ok(Self::from_der(bytes)?) } } impl<'a, Params, Key> ValueOrd for SubjectPublicKeyInfo where Params: Choice<'a> + DerOrd + Encode, Key: ValueOrd, { fn value_cmp(&self, other: &Self) -> der::Result { match self.algorithm.der_cmp(&other.algorithm)? { Ordering::Equal => self.subject_public_key.value_cmp(&other.subject_public_key), other => Ok(other), } } } #[cfg(feature = "alloc")] impl<'a: 'k, 'k, Params, Key: 'k> TryFrom> for Document where Params: Choice<'a> + Encode, Key: Decode<'a> + Encode + FixedTag, BitStringRef<'a>: From<&'k Key>, { type Error = Error; fn try_from(spki: SubjectPublicKeyInfo) -> Result { Self::try_from(&spki) } } #[cfg(feature = "alloc")] impl<'a: 'k, 'k, Params, Key: 'k> TryFrom<&SubjectPublicKeyInfo> for Document where Params: Choice<'a> + Encode, Key: Decode<'a> + Encode + FixedTag, BitStringRef<'a>: From<&'k Key>, { type Error = Error; fn try_from(spki: &SubjectPublicKeyInfo) -> Result { Ok(Self::encode_msg(spki)?) } } #[cfg(feature = "pem")] impl PemLabel for SubjectPublicKeyInfo { const PEM_LABEL: &'static str = "PUBLIC KEY"; } #[cfg(feature = "alloc")] mod allocating { use super::*; use der::referenced::*; impl<'a> RefToOwned<'a> for SubjectPublicKeyInfoRef<'a> { type Owned = SubjectPublicKeyInfoOwned; fn ref_to_owned(&self) -> Self::Owned { SubjectPublicKeyInfo { algorithm: self.algorithm.ref_to_owned(), subject_public_key: self.subject_public_key.ref_to_owned(), } } } impl OwnedToRef for SubjectPublicKeyInfoOwned { type Borrowed<'a> = SubjectPublicKeyInfoRef<'a>; fn owned_to_ref(&self) -> Self::Borrowed<'_> { SubjectPublicKeyInfo { algorithm: self.algorithm.owned_to_ref(), subject_public_key: self.subject_public_key.owned_to_ref(), } } } } spki-0.7.2/src/traits.rs000064400000000000000000000137551046102023000132560ustar 00000000000000//! Traits for encoding/decoding SPKI public keys. use crate::{AlgorithmIdentifier, Error, Result, SubjectPublicKeyInfoRef}; use der::{EncodeValue, Tagged}; #[cfg(feature = "alloc")] use { crate::AlgorithmIdentifierOwned, der::{asn1::BitString, Any, Document}, }; #[cfg(feature = "pem")] use { alloc::string::String, der::pem::{LineEnding, PemLabel}, }; #[cfg(feature = "std")] use std::path::Path; #[cfg(doc)] use crate::SubjectPublicKeyInfo; /// Parse a public key object from an encoded SPKI document. pub trait DecodePublicKey: Sized { /// Deserialize object from ASN.1 DER-encoded [`SubjectPublicKeyInfo`] /// (binary format). fn from_public_key_der(bytes: &[u8]) -> Result; /// Deserialize PEM-encoded [`SubjectPublicKeyInfo`]. /// /// Keys in this format begin with the following delimiter: /// /// ```text /// -----BEGIN PUBLIC KEY----- /// ``` #[cfg(feature = "pem")] fn from_public_key_pem(s: &str) -> Result { let (label, doc) = Document::from_pem(s)?; SubjectPublicKeyInfoRef::validate_pem_label(label)?; Self::from_public_key_der(doc.as_bytes()) } /// Load public key object from an ASN.1 DER-encoded file on the local /// filesystem (binary format). #[cfg(feature = "std")] fn read_public_key_der_file(path: impl AsRef) -> Result { let doc = Document::read_der_file(path)?; Self::from_public_key_der(doc.as_bytes()) } /// Load public key object from a PEM-encoded file on the local filesystem. #[cfg(all(feature = "pem", feature = "std"))] fn read_public_key_pem_file(path: impl AsRef) -> Result { let (label, doc) = Document::read_pem_file(path)?; SubjectPublicKeyInfoRef::validate_pem_label(&label)?; Self::from_public_key_der(doc.as_bytes()) } } impl DecodePublicKey for T where T: for<'a> TryFrom, Error = Error>, { fn from_public_key_der(bytes: &[u8]) -> Result { Self::try_from(SubjectPublicKeyInfoRef::try_from(bytes)?) } } /// Serialize a public key object to a SPKI-encoded document. #[cfg(feature = "alloc")] pub trait EncodePublicKey { /// Serialize a [`Document`] containing a SPKI-encoded public key. fn to_public_key_der(&self) -> Result; /// Serialize this public key as PEM-encoded SPKI with the given [`LineEnding`]. #[cfg(feature = "pem")] fn to_public_key_pem(&self, line_ending: LineEnding) -> Result { let doc = self.to_public_key_der()?; Ok(doc.to_pem(SubjectPublicKeyInfoRef::PEM_LABEL, line_ending)?) } /// Write ASN.1 DER-encoded public key to the given path #[cfg(feature = "std")] fn write_public_key_der_file(&self, path: impl AsRef) -> Result<()> { Ok(self.to_public_key_der()?.write_der_file(path)?) } /// Write ASN.1 DER-encoded public key to the given path #[cfg(all(feature = "pem", feature = "std"))] fn write_public_key_pem_file( &self, path: impl AsRef, line_ending: LineEnding, ) -> Result<()> { let doc = self.to_public_key_der()?; Ok(doc.write_pem_file(path, SubjectPublicKeyInfoRef::PEM_LABEL, line_ending)?) } } /// Returns `AlgorithmIdentifier` associated with the structure. /// /// This is useful for e.g. keys for digital signature algorithms. pub trait AssociatedAlgorithmIdentifier { /// Algorithm parameters. type Params: Tagged + EncodeValue; /// `AlgorithmIdentifier` for this structure. const ALGORITHM_IDENTIFIER: AlgorithmIdentifier; } /// Returns `AlgorithmIdentifier` associated with the structure. /// /// This is useful for e.g. keys for digital signature algorithms. #[cfg(feature = "alloc")] pub trait DynAssociatedAlgorithmIdentifier { /// `AlgorithmIdentifier` for this structure. fn algorithm_identifier(&self) -> Result; } #[cfg(feature = "alloc")] impl DynAssociatedAlgorithmIdentifier for T where T: AssociatedAlgorithmIdentifier, { fn algorithm_identifier(&self) -> Result { Ok(AlgorithmIdentifierOwned { oid: T::ALGORITHM_IDENTIFIER.oid, parameters: T::ALGORITHM_IDENTIFIER .parameters .as_ref() .map(Any::encode_from) .transpose()?, }) } } /// Returns `AlgorithmIdentifier` associated with the signature system. /// /// Unlike AssociatedAlgorithmIdentifier this is intended to be implemented for public and/or /// private keys. pub trait SignatureAlgorithmIdentifier { /// Algorithm parameters. type Params: Tagged + EncodeValue; /// `AlgorithmIdentifier` for the corresponding singature system. const SIGNATURE_ALGORITHM_IDENTIFIER: AlgorithmIdentifier; } /// Returns `AlgorithmIdentifier` associated with the signature system. /// /// Unlike AssociatedAlgorithmIdentifier this is intended to be implemented for public and/or /// private keys. #[cfg(feature = "alloc")] pub trait DynSignatureAlgorithmIdentifier { /// `AlgorithmIdentifier` for the corresponding singature system. fn signature_algorithm_identifier(&self) -> Result; } #[cfg(feature = "alloc")] impl DynSignatureAlgorithmIdentifier for T where T: SignatureAlgorithmIdentifier, { fn signature_algorithm_identifier(&self) -> Result { Ok(AlgorithmIdentifierOwned { oid: T::SIGNATURE_ALGORITHM_IDENTIFIER.oid, parameters: T::SIGNATURE_ALGORITHM_IDENTIFIER .parameters .as_ref() .map(Any::encode_from) .transpose()?, }) } } /// Returns the `BitString` encoding of the signature. /// /// X.509 and CSR structures require signatures to be BitString encoded. #[cfg(feature = "alloc")] pub trait SignatureBitStringEncoding { /// `BitString` encoding for this signature. fn to_bitstring(&self) -> der::Result; } spki-0.7.2/tests/examples/ed25519-pub.der000064400000000000000000000000541046102023000160350ustar 000000000000000*0+ep!M)?):^{&{UPS spki-0.7.2/tests/examples/ed25519-pub.pem000064400000000000000000000001611046102023000160430ustar 00000000000000-----BEGIN PUBLIC KEY----- MCowBQYDK2VwAyEATSkWfz8ZEqb3rfopOgUaFcBexnuPFyZ7HFVQ3OhTvQ0= -----END PUBLIC KEY----- spki-0.7.2/tests/examples/p256-pub.der000064400000000000000000000001331046102023000155310ustar 000000000000000Y0*H=*H=B_/,؝7K&$R-79āD0M~jЏ_+RDp)spki-0.7.2/tests/examples/p256-pub.pem000064400000000000000000000002621046102023000155430ustar 00000000000000-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHKz/tV8vLO/YnYnrN0smgRUkUoAt 7qCZFgaBN9g5z3/EgaREkjBNfvZqwRe+/oOo0I8VXytS+fYY3URwKQSODw== -----END PUBLIC KEY----- spki-0.7.2/tests/examples/rsa2048-pub.der000064400000000000000000000004461046102023000161470ustar 000000000000000"0  *H 0 ,Q_>BCp&3H3cGOo6:])9 K9AOG8,v=Syr~ _'^|KOYp("ܼʻ|CɂrEX2&mt:큒шLG9fܗǬE = |W_SOWN0ǻțxRUϰ'ȟN<򈎓2A֕ܐN> _pX%?^)\m8Pa☗[/spki-0.7.2/tests/examples/rsa2048-pub.pem000064400000000000000000000007031046102023000161520ustar 00000000000000-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtsQsUV8QpqrygsY+2+JC Q6Fw8/omM71IM2N/R8pPbzbgOl0p78MZGsgPOQ2HSznjD0FPzsH8oO2B5Uftws04 LHb2HJAYlz25+lN5cqfHAfa3fgmC38FfwBkn7l582UtPWZ/wcBOnyCgb3yLcvJrX yrt8QxHJgvWO23ITrUVYszImbXQ67YGS0YhMrbixRzmo2tpm3JcIBtnHrEUMsT0N fFdfsZhTT8YbxBvA8FdODgEwx7u/vf3J9qbi4+Kv8cvqyJuleIRSjVXPsIMnoejI n04APPKIjpMyQdnWlby7rNyQtE4+CV+jcFjqJbE/Xilcvqxt6DirjFCvYeKYl1uH LwIDAQAB -----END PUBLIC KEY----- spki-0.7.2/tests/spki.rs000064400000000000000000000136071046102023000132650ustar 00000000000000//! `SubjectPublicKeyInfo` tests. use der::asn1::ObjectIdentifier; use hex_literal::hex; use spki::SubjectPublicKeyInfoRef; #[cfg(feature = "alloc")] use der::Encode; #[cfg(feature = "pem")] use der::{pem::LineEnding, EncodePem}; /// Elliptic Curve (P-256) `SubjectPublicKeyInfo` encoded as ASN.1 DER const EC_P256_DER_EXAMPLE: &[u8] = include_bytes!("examples/p256-pub.der"); /// Ed25519 `SubjectPublicKeyInfo` encoded as ASN.1 DER #[cfg(any(feature = "alloc", feature = "fingerprint"))] const ED25519_DER_EXAMPLE: &[u8] = include_bytes!("examples/ed25519-pub.der"); /// RSA-2048 `SubjectPublicKeyInfo` encoded as ASN.1 DER const RSA_2048_DER_EXAMPLE: &[u8] = include_bytes!("examples/rsa2048-pub.der"); /// Elliptic Curve (P-256) public key encoded as PEM #[cfg(feature = "pem")] const EC_P256_PEM_EXAMPLE: &str = include_str!("examples/p256-pub.pem"); /// Ed25519 public key encoded as PEM #[cfg(feature = "pem")] const ED25519_PEM_EXAMPLE: &str = include_str!("examples/ed25519-pub.pem"); /// RSA-2048 PKCS#8 public key encoded as PEM #[cfg(feature = "pem")] const RSA_2048_PEM_EXAMPLE: &str = include_str!("examples/rsa2048-pub.pem"); /// The SPKI fingerprint for `ED25519_SPKI_FINGERPRINT` as a Base64 string /// /// Generated using `cat ed25519-pub.der | openssl dgst -binary -sha256 | base64` #[cfg(all(feature = "alloc", feature = "base64", feature = "fingerprint"))] const ED25519_SPKI_FINGERPRINT_BASE64: &str = "Vd1MdLDkhTTi9OFzzs61DfjyenrCqomRzHrpFOAwvO0="; /// The SPKI fingerprint for `ED25519_SPKI_FINGERPRINT` as straight hash bytes /// /// Generated using `cat ed25519-pub.der | openssl dgst -sha256` #[cfg(all(feature = "fingerprint"))] const ED25519_SPKI_FINGERPRINT: &[u8] = &hex!("55dd4c74b0e48534e2f4e173ceceb50df8f27a7ac2aa8991cc7ae914e030bced"); #[test] fn decode_ec_p256_der() { let spki = SubjectPublicKeyInfoRef::try_from(EC_P256_DER_EXAMPLE).unwrap(); assert_eq!(spki.algorithm.oid, "1.2.840.10045.2.1".parse().unwrap()); assert_eq!( spki.algorithm .parameters .unwrap() .decode_as::() .unwrap(), "1.2.840.10045.3.1.7".parse().unwrap() ); assert_eq!(spki.subject_public_key.raw_bytes(), &hex!("041CACFFB55F2F2CEFD89D89EB374B2681152452802DEEA09916068137D839CF7FC481A44492304D7EF66AC117BEFE83A8D08F155F2B52F9F618DD447029048E0F")[..]); } #[test] #[cfg(feature = "fingerprint")] fn decode_ed25519_and_fingerprint_spki() { // Repeat the decode test from the pkcs8 crate let spki = SubjectPublicKeyInfoRef::try_from(ED25519_DER_EXAMPLE).unwrap(); assert_eq!(spki.algorithm.oid, "1.3.101.112".parse().unwrap()); assert_eq!(spki.algorithm.parameters, None); assert_eq!( spki.subject_public_key.raw_bytes(), &hex!("4D29167F3F1912A6F7ADFA293A051A15C05EC67B8F17267B1C5550DCE853BD0D")[..] ); // Check the fingerprint assert_eq!( spki.fingerprint_bytes().unwrap().as_slice(), ED25519_SPKI_FINGERPRINT ); } #[test] #[cfg(all(feature = "alloc", feature = "base64", feature = "fingerprint"))] fn decode_ed25519_and_fingerprint_base64() { // Repeat the decode test from the pkcs8 crate let spki = SubjectPublicKeyInfoRef::try_from(ED25519_DER_EXAMPLE).unwrap(); assert_eq!(spki.algorithm.oid, "1.3.101.112".parse().unwrap()); assert_eq!(spki.algorithm.parameters, None); assert_eq!( spki.subject_public_key.raw_bytes(), &hex!("4D29167F3F1912A6F7ADFA293A051A15C05EC67B8F17267B1C5550DCE853BD0D")[..] ); // Check the fingerprint assert_eq!( spki.fingerprint_base64().unwrap(), ED25519_SPKI_FINGERPRINT_BASE64 ); } #[test] fn decode_rsa_2048_der() { let spki = SubjectPublicKeyInfoRef::try_from(RSA_2048_DER_EXAMPLE).unwrap(); assert_eq!(spki.algorithm.oid, "1.2.840.113549.1.1.1".parse().unwrap()); assert!(spki.algorithm.parameters.unwrap().is_null()); assert_eq!(spki.subject_public_key.raw_bytes(), &hex!("3082010A0282010100B6C42C515F10A6AAF282C63EDBE24243A170F3FA2633BD4833637F47CA4F6F36E03A5D29EFC3191AC80F390D874B39E30F414FCEC1FCA0ED81E547EDC2CD382C76F61C9018973DB9FA537972A7C701F6B77E0982DFC15FC01927EE5E7CD94B4F599FF07013A7C8281BDF22DCBC9AD7CABB7C4311C982F58EDB7213AD4558B332266D743AED8192D1884CADB8B14739A8DADA66DC970806D9C7AC450CB13D0D7C575FB198534FC61BC41BC0F0574E0E0130C7BBBFBDFDC9F6A6E2E3E2AFF1CBEAC89BA57884528D55CFB08327A1E8C89F4E003CF2888E933241D9D695BCBBACDC90B44E3E095FA37058EA25B13F5E295CBEAC6DE838AB8C50AF61E298975B872F0203010001")[..]); } #[test] #[cfg(feature = "alloc")] fn encode_ec_p256_der() { let pk = SubjectPublicKeyInfoRef::try_from(EC_P256_DER_EXAMPLE).unwrap(); let pk_encoded = pk.to_der().unwrap(); assert_eq!(EC_P256_DER_EXAMPLE, pk_encoded.as_slice()); } #[test] #[cfg(feature = "alloc")] fn encode_ed25519_der() { let pk = SubjectPublicKeyInfoRef::try_from(ED25519_DER_EXAMPLE).unwrap(); let pk_encoded = pk.to_der().unwrap(); assert_eq!(ED25519_DER_EXAMPLE, pk_encoded.as_slice()); } #[test] #[cfg(feature = "alloc")] fn encode_rsa_2048_der() { let pk = SubjectPublicKeyInfoRef::try_from(RSA_2048_DER_EXAMPLE).unwrap(); let pk_encoded = pk.to_der().unwrap(); assert_eq!(RSA_2048_DER_EXAMPLE, pk_encoded.as_slice()); } #[test] #[cfg(feature = "pem")] fn encode_ec_p256_pem() { let pk = SubjectPublicKeyInfoRef::try_from(EC_P256_DER_EXAMPLE).unwrap(); let pk_encoded = pk.to_pem(LineEnding::LF).unwrap(); assert_eq!(EC_P256_PEM_EXAMPLE, pk_encoded); } #[test] #[cfg(feature = "pem")] fn encode_ed25519_pem() { let pk = SubjectPublicKeyInfoRef::try_from(ED25519_DER_EXAMPLE).unwrap(); let pk_encoded = pk.to_pem(LineEnding::LF).unwrap(); assert_eq!(ED25519_PEM_EXAMPLE, pk_encoded); } #[test] #[cfg(feature = "pem")] fn encode_rsa_2048_pem() { let pk = SubjectPublicKeyInfoRef::try_from(RSA_2048_DER_EXAMPLE).unwrap(); let pk_encoded = pk.to_pem(LineEnding::LF).unwrap(); assert_eq!(RSA_2048_PEM_EXAMPLE, pk_encoded); } spki-0.7.2/tests/traits.rs000064400000000000000000000053271046102023000136250ustar 00000000000000//! Tests for SPKI encoding/decoding traits. #![cfg(any(feature = "pem", feature = "std"))] use der::{Decode, Encode}; use spki::{DecodePublicKey, Document, EncodePublicKey, Error, Result, SubjectPublicKeyInfoRef}; #[cfg(feature = "pem")] use spki::der::pem::LineEnding; #[cfg(feature = "std")] use tempfile::tempdir; #[cfg(all(feature = "pem", feature = "std"))] use std::fs; /// Ed25519 `SubjectPublicKeyInfo` encoded as ASN.1 DER const ED25519_DER_EXAMPLE: &[u8] = include_bytes!("examples/ed25519-pub.der"); /// Ed25519 public key encoded as PEM #[cfg(feature = "pem")] const ED25519_PEM_EXAMPLE: &str = include_str!("examples/ed25519-pub.pem"); /// Mock key type for testing trait impls against. pub struct MockKey(Vec); impl AsRef<[u8]> for MockKey { fn as_ref(&self) -> &[u8] { self.0.as_ref() } } impl EncodePublicKey for MockKey { fn to_public_key_der(&self) -> Result { Ok(Document::from_der(self.as_ref())?) } } impl TryFrom> for MockKey { type Error = Error; fn try_from(spki: SubjectPublicKeyInfoRef<'_>) -> Result { Ok(MockKey(spki.to_der()?)) } } #[cfg(feature = "pem")] #[test] fn from_public_key_pem() { let key = MockKey::from_public_key_pem(ED25519_PEM_EXAMPLE).unwrap(); assert_eq!(key.as_ref(), ED25519_DER_EXAMPLE); } #[cfg(feature = "std")] #[test] fn read_public_key_der_file() { let key = MockKey::read_public_key_der_file("tests/examples/ed25519-pub.der").unwrap(); assert_eq!(key.as_ref(), ED25519_DER_EXAMPLE); } #[cfg(all(feature = "pem", feature = "std"))] #[test] fn read_public_key_pem_file() { let key = MockKey::read_public_key_pem_file("tests/examples/ed25519-pub.pem").unwrap(); assert_eq!(key.as_ref(), ED25519_DER_EXAMPLE); } #[cfg(feature = "pem")] #[test] fn to_public_key_pem() { let pem = MockKey(ED25519_DER_EXAMPLE.to_vec()) .to_public_key_pem(LineEnding::LF) .unwrap(); assert_eq!(pem, ED25519_PEM_EXAMPLE); } #[cfg(feature = "std")] #[test] fn write_public_key_der_file() { let dir = tempdir().unwrap(); let path = dir.path().join("example.der"); MockKey(ED25519_DER_EXAMPLE.to_vec()) .write_public_key_der_file(&path) .unwrap(); let key = MockKey::read_public_key_der_file(&path).unwrap(); assert_eq!(key.as_ref(), ED25519_DER_EXAMPLE); } #[cfg(all(feature = "pem", feature = "std"))] #[test] fn write_public_key_pem_file() { let dir = tempdir().unwrap(); let path = dir.path().join("example.pem"); MockKey(ED25519_DER_EXAMPLE.to_vec()) .write_public_key_pem_file(&path, LineEnding::LF) .unwrap(); let pem = fs::read_to_string(path).unwrap(); assert_eq!(&pem, ED25519_PEM_EXAMPLE); }