pub struct CapturedX509Certificate { /* private fields */ }
Expand description
Implementations§
source§impl CapturedX509Certificate
impl CapturedX509Certificate
sourcepub fn from_der(data: impl Into<Vec<u8>>) -> Result<Self, Error>
pub fn from_der(data: impl Into<Vec<u8>>) -> Result<Self, Error>
Construct an instance from DER encoded data.
A copy of this data will be stored in the instance and is guaranteed to be immutable for the lifetime of the instance. The original constructing data can be retrieved later.
Examples found in repository?
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
pub fn from_pem(data: impl AsRef<[u8]>) -> Result<Self, Error> {
let data = pem::parse(data.as_ref()).map_err(Error::PemDecode)?;
Self::from_der(data.contents)
}
/// Construct instances by parsing PEM with potentially multiple records.
///
/// By default, we only look for `--------- BEGIN CERTIFICATE --------`
/// entries and silently ignore unknown ones. If you would like to specify
/// an alternate set of tags (this is the value after the `BEGIN`) to search,
/// call [Self::from_pem_multiple_tags].
pub fn from_pem_multiple(data: impl AsRef<[u8]>) -> Result<Vec<Self>, Error> {
Self::from_pem_multiple_tags(data, &["CERTIFICATE"])
}
/// Construct instances by parsing PEM armored DER encoded certificates with specific PEM tags.
///
/// This is like [Self::from_pem_multiple] except you control the filter for
/// which `BEGIN <tag>` values are filtered through to the DER parser.
pub fn from_pem_multiple_tags(
data: impl AsRef<[u8]>,
tags: &[&str],
) -> Result<Vec<Self>, Error> {
let pem = pem::parse_many(data.as_ref()).map_err(Error::PemDecode)?;
pem.into_iter()
.filter(|pem| tags.contains(&pem.tag.as_str()))
.map(|pem| Self::from_der(pem.contents))
.collect::<Result<_, _>>()
}
/// Obtain the DER data that was used to construct this instance.
///
/// The data is guaranteed to not have been modified since the instance
/// was constructed.
pub fn constructed_data(&self) -> &[u8] {
match &self.original {
OriginalData::Ber(data) => data,
OriginalData::Der(data) => data,
}
}
/// Encode the original contents of this certificate to PEM.
pub fn encode_pem(&self) -> String {
pem::encode(&pem::Pem {
tag: "CERTIFICATE".to_string(),
contents: self.constructed_data().to_vec(),
})
}
/// Verify that another certificate, `other`, signed this certificate.
///
/// If this is a self-signed certificate, you can pass `self` as the 2nd
/// argument.
///
/// This function isn't exposed on [X509Certificate] because the exact
/// bytes constituting the certificate's internals need to be consulted
/// to verify signatures. And since this type tracks the underlying
/// bytes, we are guaranteed to have a pristine copy.
pub fn verify_signed_by_certificate(
&self,
other: impl AsRef<X509Certificate>,
) -> Result<(), Error> {
let public_key = other
.as_ref()
.0
.tbs_certificate
.subject_public_key_info
.subject_public_key
.octet_bytes();
self.verify_signed_by_public_key(public_key)
}
/// Verify a signature over signed data purportedly signed by this certificate.
///
/// This is a wrapper to [Self::verify_signed_data_with_algorithm()] that will derive
/// the verification algorithm from the public key type type and the signature algorithm
/// indicated in this certificate. Typically these align. However, it is possible for
/// a signature to be produced with a different digest algorithm from that indicated
/// in this certificate.
pub fn verify_signed_data(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
) -> Result<(), Error> {
let key_algorithm = KeyAlgorithm::try_from(self.key_algorithm_oid())?;
let signature_algorithm = SignatureAlgorithm::try_from(self.signature_algorithm_oid())?;
let verify_algorithm = signature_algorithm.resolve_verification_algorithm(key_algorithm)?;
self.verify_signed_data_with_algorithm(signed_data, signature, verify_algorithm)
}
/// Verify a signature over signed data using an explicit verification algorithm.
///
/// This is like [Self::verify_signed_data()] except the verification algorithm to use
/// is passed in instead of derived from the default algorithm for the signing key's
/// type.
pub fn verify_signed_data_with_algorithm(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
verify_algorithm: &'static dyn ringsig::VerificationAlgorithm,
) -> Result<(), Error> {
let public_key = ringsig::UnparsedPublicKey::new(verify_algorithm, self.public_key_data());
public_key
.verify(signed_data.as_ref(), signature.as_ref())
.map_err(|_| Error::CertificateSignatureVerificationFailed)
}
/// Verifies that this certificate was cryptographically signed using raw public key data from a signing key.
///
/// This function does the low-level work of extracting the signature and
/// verification details from the current certificate and figuring out
/// the correct combination of cryptography settings to apply to perform
/// signature verification.
///
/// In many cases, an X.509 certificate is signed by another certificate. And
/// since the public key is embedded in the X.509 certificate, it is easier
/// to go through [Self::verify_signed_by_certificate] instead.
pub fn verify_signed_by_public_key(
&self,
public_key_data: impl AsRef<[u8]>,
) -> Result<(), Error> {
// Always verify against the original content, as the inner
// certificate could be mutated via the mutable wrapper of this
// type.
let this_cert = match &self.original {
OriginalData::Ber(data) => X509Certificate::from_ber(data),
OriginalData::Der(data) => X509Certificate::from_der(data),
}
.expect("certificate re-parse should never fail");
let signed_data = this_cert
.0
.tbs_certificate
.raw_data
.as_ref()
.expect("original certificate data should have persisted as part of re-parse");
let signature = this_cert.0.signature.octet_bytes();
let key_algorithm = KeyAlgorithm::try_from(
&this_cert
.0
.tbs_certificate
.subject_public_key_info
.algorithm,
)?;
let signature_algorithm = SignatureAlgorithm::try_from(&this_cert.0.signature_algorithm)?;
let verify_algorithm = signature_algorithm.resolve_verification_algorithm(key_algorithm)?;
let public_key = ringsig::UnparsedPublicKey::new(verify_algorithm, public_key_data);
public_key
.verify(signed_data, &signature)
.map_err(|_| Error::CertificateSignatureVerificationFailed)
}
/// Attempt to find the issuing certificate of this one.
///
/// Given an iterable of certificates, we find the first certificate
/// where we are able to verify that our signature was made by their public
/// key.
///
/// This function can yield false negatives for cases where we don't
/// support the signature algorithm on the incoming certificates.
pub fn find_signing_certificate<'a>(
&self,
mut certs: impl Iterator<Item = &'a Self>,
) -> Option<&'a Self> {
certs.find(|candidate| self.verify_signed_by_certificate(candidate).is_ok())
}
/// Attempt to resolve the signing chain of this certificate.
///
/// Given an iterable of certificates, we recursively resolve the
/// chain of certificates that signed this one until we are no longer able
/// to find any more certificates in the input set.
///
/// Like [Self::find_signing_certificate], this can yield false
/// negatives (read: an incomplete chain) due to run-time failures,
/// such as lack of support for a certificate's signature algorithm.
///
/// As a certificate is encountered, it is removed from the set of
/// future candidates.
///
/// The traversal ends when we get to an identical certificate (its
/// DER data is equivalent) or we couldn't find a certificate in
/// the remaining set that signed the last one.
///
/// Because we need to recursively verify certificates, the incoming
/// iterator is buffered.
pub fn resolve_signing_chain<'a>(
&self,
certs: impl Iterator<Item = &'a Self>,
) -> Vec<&'a Self> {
// The logic here is a bit wonky. As we build up the collection of certificates,
// we want to filter out ourself and remove duplicates. We remove duplicates by
// storing encountered certificates in a HashSet.
#[allow(clippy::mutable_key_type)]
let mut seen = HashSet::new();
let mut remaining = vec![];
for cert in certs {
if cert == self || seen.contains(cert) {
continue;
} else {
remaining.push(cert);
seen.insert(cert);
}
}
drop(seen);
let mut chain = vec![];
let mut last_cert = self;
while let Some(issuer) = last_cert.find_signing_certificate(remaining.iter().copied()) {
chain.push(issuer);
last_cert = issuer;
remaining = remaining
.drain(..)
.filter(|cert| *cert != issuer)
.collect::<Vec<_>>();
}
chain
}
}
impl PartialEq for CapturedX509Certificate {
fn eq(&self, other: &Self) -> bool {
self.constructed_data() == other.constructed_data()
}
}
impl Eq for CapturedX509Certificate {}
impl Hash for CapturedX509Certificate {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(self.constructed_data());
}
}
impl Deref for CapturedX509Certificate {
type Target = X509Certificate;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl AsRef<X509Certificate> for CapturedX509Certificate {
fn as_ref(&self) -> &X509Certificate {
&self.inner
}
}
impl AsRef<rfc5280::Certificate> for CapturedX509Certificate {
fn as_ref(&self) -> &rfc5280::Certificate {
self.inner.as_ref()
}
}
impl TryFrom<&X509Certificate> for CapturedX509Certificate {
type Error = Error;
fn try_from(cert: &X509Certificate) -> Result<Self, Self::Error> {
let mut buffer = Vec::<u8>::new();
cert.encode_der_to(&mut buffer)?;
Self::from_der(buffer)
}
}
impl TryFrom<X509Certificate> for CapturedX509Certificate {
type Error = Error;
fn try_from(cert: X509Certificate) -> Result<Self, Self::Error> {
let mut buffer = Vec::<u8>::new();
cert.encode_der_to(&mut buffer)?;
Self::from_der(buffer)
}
}
impl From<CapturedX509Certificate> for rfc5280::Certificate {
fn from(cert: CapturedX509Certificate) -> Self {
cert.inner.0
}
}
/// Provides a mutable wrapper to an X.509 certificate that was parsed from data.
///
/// This is like [CapturedX509Certificate] except it implements [DerefMut],
/// enabling you to modify the certificate while still being able to access
/// the raw data the certificate is backed by. However, mutations are
/// only performed against the parsed ASN.1 data structure, not the original
/// data it was constructed with.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MutableX509Certificate(CapturedX509Certificate);
impl Deref for MutableX509Certificate {
type Target = X509Certificate;
fn deref(&self) -> &Self::Target {
&self.0.inner
}
}
impl DerefMut for MutableX509Certificate {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0.inner
}
}
impl From<CapturedX509Certificate> for MutableX509Certificate {
fn from(cert: CapturedX509Certificate) -> Self {
Self(cert)
}
}
/// Whether one certificate is a subset of another certificate.
///
/// This returns true iff the two certificates have the same serial number
/// and every `Name` attribute in the first certificate is present in the other.
pub fn certificate_is_subset_of(
a_serial: &Integer,
a_name: &Name,
b_serial: &Integer,
b_name: &Name,
) -> bool {
if a_serial != b_serial {
return false;
}
let Name::RdnSequence(a_sequence) = &a_name;
let Name::RdnSequence(b_sequence) = &b_name;
a_sequence.iter().all(|rdn| b_sequence.contains(rdn))
}
/// X.509 extension to define how a certificate can be used.
///
/// ```asn.1
/// KeyUsage ::= BIT STRING {
/// digitalSignature(0),
/// nonRepudiation(1),
/// keyEncipherment(2),
/// dataEncipherment(3),
/// keyAgreement(4),
/// keyCertSign(5),
/// cRLSign(6)
/// }
/// ```
pub enum KeyUsage {
DigitalSignature,
NonRepudiation,
KeyEncipherment,
DataEncipherment,
KeyAgreement,
KeyCertSign,
CrlSign,
}
impl From<KeyUsage> for u8 {
fn from(ku: KeyUsage) -> Self {
match ku {
KeyUsage::DigitalSignature => 0,
KeyUsage::NonRepudiation => 1,
KeyUsage::KeyEncipherment => 2,
KeyUsage::DataEncipherment => 3,
KeyUsage::KeyAgreement => 4,
KeyUsage::KeyCertSign => 5,
KeyUsage::CrlSign => 6,
}
}
}
/// Interface for constructing new X.509 certificates.
///
/// This holds fields for various certificate metadata and allows you
/// to incrementally derive a new X.509 certificate.
///
/// The certificate is populated with defaults:
///
/// * The serial number is 1.
/// * The time validity is now until 1 hour from now.
/// * There is no issuer. If no attempt is made to define an issuer,
/// the subject will be copied to the issuer field and this will be
/// a self-signed certificate.
///
/// This type can also be used to produce certificate signing requests. In this mode,
/// only the subject value and additional registered attributes are meaningful.
pub struct X509CertificateBuilder {
key_algorithm: KeyAlgorithm,
subject: Name,
issuer: Option<Name>,
extensions: rfc5280::Extensions,
serial_number: i64,
not_before: chrono::DateTime<Utc>,
not_after: chrono::DateTime<Utc>,
csr_attributes: Attributes,
}
impl X509CertificateBuilder {
pub fn new(alg: KeyAlgorithm) -> Self {
let not_before = Utc::now();
let not_after = not_before + Duration::hours(1);
Self {
key_algorithm: alg,
subject: Name::default(),
issuer: None,
extensions: rfc5280::Extensions::default(),
serial_number: 1,
not_before,
not_after,
csr_attributes: Attributes::default(),
}
}
/// Obtain a mutable reference to the subject [Name].
///
/// The type has functions that will allow you to add attributes with ease.
pub fn subject(&mut self) -> &mut Name {
&mut self.subject
}
/// Obtain a mutable reference to the issuer [Name].
///
/// If no issuer has been created yet, an empty one will be created.
pub fn issuer(&mut self) -> &mut Name {
self.issuer.get_or_insert_with(Name::default)
}
/// Set the serial number for the certificate.
pub fn serial_number(&mut self, value: i64) {
self.serial_number = value;
}
/// Obtain the raw certificate extensions.
pub fn extensions(&self) -> &rfc5280::Extensions {
&self.extensions
}
/// Obtain a mutable reference to raw certificate extensions.
pub fn extensions_mut(&mut self) -> &mut rfc5280::Extensions {
&mut self.extensions
}
/// Add an extension to the certificate with its value as pre-encoded DER data.
pub fn add_extension_der_data(&mut self, oid: Oid, critical: bool, data: impl AsRef<[u8]>) {
self.extensions.push(rfc5280::Extension {
id: oid,
critical: Some(critical),
value: OctetString::new(Bytes::copy_from_slice(data.as_ref())),
});
}
/// Set the expiration time in terms of [Duration] since its currently set start time.
pub fn validity_duration(&mut self, duration: Duration) {
self.not_after = self.not_before + duration;
}
/// Add a basic constraint extension that this isn't a CA certificate.
pub fn constraint_not_ca(&mut self) {
self.extensions.push(rfc5280::Extension {
id: Oid(OID_EXTENSION_BASIC_CONSTRAINTS.as_ref().into()),
critical: Some(true),
value: OctetString::new(Bytes::copy_from_slice(&[0x30, 00])),
});
}
/// Add a key usage extension.
pub fn key_usage(&mut self, key_usage: KeyUsage) {
let value: u8 = key_usage.into();
self.extensions.push(rfc5280::Extension {
id: Oid(OID_EXTENSION_KEY_USAGE.as_ref().into()),
critical: Some(true),
// Value is a bit string. We just encode it manually since it is easy.
value: OctetString::new(Bytes::copy_from_slice(&[3, 2, 7, 128 | value])),
});
}
/// Add an [Attribute] to a future certificate signing requests.
///
/// Has no effect on regular certificate creation: only if creating certificate
/// signing requests.
pub fn add_csr_attribute(&mut self, attribute: rfc5652::Attribute) {
self.csr_attributes.push(attribute);
}
/// Create a new certificate given settings, using a randomly generated key pair.
pub fn create_with_random_keypair(
&self,
) -> Result<
(
CapturedX509Certificate,
InMemorySigningKeyPair,
ring::pkcs8::Document,
),
Error,
> {
let (key_pair, document) = InMemorySigningKeyPair::generate_random(self.key_algorithm)?;
let key_pair_signature_algorithm = key_pair.signature_algorithm();
let issuer = if let Some(issuer) = &self.issuer {
issuer
} else {
&self.subject
};
let tbs_certificate = rfc5280::TbsCertificate {
version: Some(rfc5280::Version::V3),
serial_number: self.serial_number.into(),
signature: key_pair_signature_algorithm?.into(),
issuer: issuer.clone(),
validity: rfc5280::Validity {
not_before: Time::from(self.not_before),
not_after: Time::from(self.not_after),
},
subject: self.subject.clone(),
subject_public_key_info: rfc5280::SubjectPublicKeyInfo {
algorithm: key_pair
.key_algorithm()
.expect("InMemorySigningKeyPair always has known key algorithm")
.into(),
subject_public_key: BitString::new(0, key_pair.public_key_data()),
},
issuer_unique_id: None,
subject_unique_id: None,
extensions: if self.extensions.is_empty() {
None
} else {
Some(self.extensions.clone())
},
raw_data: None,
};
// Now encode the TBS certificate so we can sign it with the private key
// and include its signature.
let mut tbs_der = Vec::<u8>::new();
tbs_certificate
.encode_ref()
.write_encoded(Mode::Der, &mut tbs_der)?;
let signature = key_pair.try_sign(&tbs_der)?;
let signature_algorithm = key_pair.signature_algorithm()?;
let cert = rfc5280::Certificate {
tbs_certificate,
signature_algorithm: signature_algorithm.into(),
signature: BitString::new(0, Bytes::copy_from_slice(signature.as_ref())),
};
let cert = X509Certificate::from(cert);
let cert_der = cert.encode_der()?;
let cert = CapturedX509Certificate::from_der(cert_der)?;
Ok((cert, key_pair, document))
}
sourcepub fn from_ber(data: impl Into<Vec<u8>>) -> Result<Self, Error>
pub fn from_ber(data: impl Into<Vec<u8>>) -> Result<Self, Error>
Construct an instance from BER encoded data.
A copy of this data will be stored in the instance and is guaranteed to be immutable for the lifetime of the instance, allowing it to be retrieved later.
sourcepub fn from_pem(data: impl AsRef<[u8]>) -> Result<Self, Error>
pub fn from_pem(data: impl AsRef<[u8]>) -> Result<Self, Error>
Construct an instance by parsing PEM encoded ASN.1 data.
The data is a human readable string likely containing
--------- BEGIN CERTIFICATE ----------
.
sourcepub fn from_pem_multiple(data: impl AsRef<[u8]>) -> Result<Vec<Self>, Error>
pub fn from_pem_multiple(data: impl AsRef<[u8]>) -> Result<Vec<Self>, Error>
Construct instances by parsing PEM with potentially multiple records.
By default, we only look for --------- BEGIN CERTIFICATE --------
entries and silently ignore unknown ones. If you would like to specify
an alternate set of tags (this is the value after the BEGIN
) to search,
call Self::from_pem_multiple_tags.
Construct instances by parsing PEM armored DER encoded certificates with specific PEM tags.
This is like Self::from_pem_multiple except you control the filter for
which BEGIN <tag>
values are filtered through to the DER parser.
sourcepub fn constructed_data(&self) -> &[u8] ⓘ
pub fn constructed_data(&self) -> &[u8] ⓘ
Obtain the DER data that was used to construct this instance.
The data is guaranteed to not have been modified since the instance was constructed.
Examples found in repository?
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
pub fn encode_pem(&self) -> String {
pem::encode(&pem::Pem {
tag: "CERTIFICATE".to_string(),
contents: self.constructed_data().to_vec(),
})
}
/// Verify that another certificate, `other`, signed this certificate.
///
/// If this is a self-signed certificate, you can pass `self` as the 2nd
/// argument.
///
/// This function isn't exposed on [X509Certificate] because the exact
/// bytes constituting the certificate's internals need to be consulted
/// to verify signatures. And since this type tracks the underlying
/// bytes, we are guaranteed to have a pristine copy.
pub fn verify_signed_by_certificate(
&self,
other: impl AsRef<X509Certificate>,
) -> Result<(), Error> {
let public_key = other
.as_ref()
.0
.tbs_certificate
.subject_public_key_info
.subject_public_key
.octet_bytes();
self.verify_signed_by_public_key(public_key)
}
/// Verify a signature over signed data purportedly signed by this certificate.
///
/// This is a wrapper to [Self::verify_signed_data_with_algorithm()] that will derive
/// the verification algorithm from the public key type type and the signature algorithm
/// indicated in this certificate. Typically these align. However, it is possible for
/// a signature to be produced with a different digest algorithm from that indicated
/// in this certificate.
pub fn verify_signed_data(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
) -> Result<(), Error> {
let key_algorithm = KeyAlgorithm::try_from(self.key_algorithm_oid())?;
let signature_algorithm = SignatureAlgorithm::try_from(self.signature_algorithm_oid())?;
let verify_algorithm = signature_algorithm.resolve_verification_algorithm(key_algorithm)?;
self.verify_signed_data_with_algorithm(signed_data, signature, verify_algorithm)
}
/// Verify a signature over signed data using an explicit verification algorithm.
///
/// This is like [Self::verify_signed_data()] except the verification algorithm to use
/// is passed in instead of derived from the default algorithm for the signing key's
/// type.
pub fn verify_signed_data_with_algorithm(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
verify_algorithm: &'static dyn ringsig::VerificationAlgorithm,
) -> Result<(), Error> {
let public_key = ringsig::UnparsedPublicKey::new(verify_algorithm, self.public_key_data());
public_key
.verify(signed_data.as_ref(), signature.as_ref())
.map_err(|_| Error::CertificateSignatureVerificationFailed)
}
/// Verifies that this certificate was cryptographically signed using raw public key data from a signing key.
///
/// This function does the low-level work of extracting the signature and
/// verification details from the current certificate and figuring out
/// the correct combination of cryptography settings to apply to perform
/// signature verification.
///
/// In many cases, an X.509 certificate is signed by another certificate. And
/// since the public key is embedded in the X.509 certificate, it is easier
/// to go through [Self::verify_signed_by_certificate] instead.
pub fn verify_signed_by_public_key(
&self,
public_key_data: impl AsRef<[u8]>,
) -> Result<(), Error> {
// Always verify against the original content, as the inner
// certificate could be mutated via the mutable wrapper of this
// type.
let this_cert = match &self.original {
OriginalData::Ber(data) => X509Certificate::from_ber(data),
OriginalData::Der(data) => X509Certificate::from_der(data),
}
.expect("certificate re-parse should never fail");
let signed_data = this_cert
.0
.tbs_certificate
.raw_data
.as_ref()
.expect("original certificate data should have persisted as part of re-parse");
let signature = this_cert.0.signature.octet_bytes();
let key_algorithm = KeyAlgorithm::try_from(
&this_cert
.0
.tbs_certificate
.subject_public_key_info
.algorithm,
)?;
let signature_algorithm = SignatureAlgorithm::try_from(&this_cert.0.signature_algorithm)?;
let verify_algorithm = signature_algorithm.resolve_verification_algorithm(key_algorithm)?;
let public_key = ringsig::UnparsedPublicKey::new(verify_algorithm, public_key_data);
public_key
.verify(signed_data, &signature)
.map_err(|_| Error::CertificateSignatureVerificationFailed)
}
/// Attempt to find the issuing certificate of this one.
///
/// Given an iterable of certificates, we find the first certificate
/// where we are able to verify that our signature was made by their public
/// key.
///
/// This function can yield false negatives for cases where we don't
/// support the signature algorithm on the incoming certificates.
pub fn find_signing_certificate<'a>(
&self,
mut certs: impl Iterator<Item = &'a Self>,
) -> Option<&'a Self> {
certs.find(|candidate| self.verify_signed_by_certificate(candidate).is_ok())
}
/// Attempt to resolve the signing chain of this certificate.
///
/// Given an iterable of certificates, we recursively resolve the
/// chain of certificates that signed this one until we are no longer able
/// to find any more certificates in the input set.
///
/// Like [Self::find_signing_certificate], this can yield false
/// negatives (read: an incomplete chain) due to run-time failures,
/// such as lack of support for a certificate's signature algorithm.
///
/// As a certificate is encountered, it is removed from the set of
/// future candidates.
///
/// The traversal ends when we get to an identical certificate (its
/// DER data is equivalent) or we couldn't find a certificate in
/// the remaining set that signed the last one.
///
/// Because we need to recursively verify certificates, the incoming
/// iterator is buffered.
pub fn resolve_signing_chain<'a>(
&self,
certs: impl Iterator<Item = &'a Self>,
) -> Vec<&'a Self> {
// The logic here is a bit wonky. As we build up the collection of certificates,
// we want to filter out ourself and remove duplicates. We remove duplicates by
// storing encountered certificates in a HashSet.
#[allow(clippy::mutable_key_type)]
let mut seen = HashSet::new();
let mut remaining = vec![];
for cert in certs {
if cert == self || seen.contains(cert) {
continue;
} else {
remaining.push(cert);
seen.insert(cert);
}
}
drop(seen);
let mut chain = vec![];
let mut last_cert = self;
while let Some(issuer) = last_cert.find_signing_certificate(remaining.iter().copied()) {
chain.push(issuer);
last_cert = issuer;
remaining = remaining
.drain(..)
.filter(|cert| *cert != issuer)
.collect::<Vec<_>>();
}
chain
}
}
impl PartialEq for CapturedX509Certificate {
fn eq(&self, other: &Self) -> bool {
self.constructed_data() == other.constructed_data()
}
}
impl Eq for CapturedX509Certificate {}
impl Hash for CapturedX509Certificate {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(self.constructed_data());
}
sourcepub fn encode_pem(&self) -> String
pub fn encode_pem(&self) -> String
Encode the original contents of this certificate to PEM.
sourcepub fn verify_signed_by_certificate(
&self,
other: impl AsRef<X509Certificate>
) -> Result<(), Error>
pub fn verify_signed_by_certificate(
&self,
other: impl AsRef<X509Certificate>
) -> Result<(), Error>
Verify that another certificate, other
, signed this certificate.
If this is a self-signed certificate, you can pass self
as the 2nd
argument.
This function isn’t exposed on X509Certificate because the exact bytes constituting the certificate’s internals need to be consulted to verify signatures. And since this type tracks the underlying bytes, we are guaranteed to have a pristine copy.
sourcepub fn verify_signed_data(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>
) -> Result<(), Error>
pub fn verify_signed_data(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>
) -> Result<(), Error>
Verify a signature over signed data purportedly signed by this certificate.
This is a wrapper to Self::verify_signed_data_with_algorithm() that will derive the verification algorithm from the public key type type and the signature algorithm indicated in this certificate. Typically these align. However, it is possible for a signature to be produced with a different digest algorithm from that indicated in this certificate.
sourcepub fn verify_signed_data_with_algorithm(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
verify_algorithm: &'static dyn VerificationAlgorithm
) -> Result<(), Error>
pub fn verify_signed_data_with_algorithm(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
verify_algorithm: &'static dyn VerificationAlgorithm
) -> Result<(), Error>
Verify a signature over signed data using an explicit verification algorithm.
This is like Self::verify_signed_data() except the verification algorithm to use is passed in instead of derived from the default algorithm for the signing key’s type.
sourcepub fn verify_signed_by_public_key(
&self,
public_key_data: impl AsRef<[u8]>
) -> Result<(), Error>
pub fn verify_signed_by_public_key(
&self,
public_key_data: impl AsRef<[u8]>
) -> Result<(), Error>
Verifies that this certificate was cryptographically signed using raw public key data from a signing key.
This function does the low-level work of extracting the signature and verification details from the current certificate and figuring out the correct combination of cryptography settings to apply to perform signature verification.
In many cases, an X.509 certificate is signed by another certificate. And since the public key is embedded in the X.509 certificate, it is easier to go through Self::verify_signed_by_certificate instead.
Examples found in repository?
523 524 525 526 527 528 529 530 531 532 533 534 535 536
pub fn verify_signed_by_certificate(
&self,
other: impl AsRef<X509Certificate>,
) -> Result<(), Error> {
let public_key = other
.as_ref()
.0
.tbs_certificate
.subject_public_key_info
.subject_public_key
.octet_bytes();
self.verify_signed_by_public_key(public_key)
}
sourcepub fn find_signing_certificate<'a>(
&self,
certs: impl Iterator<Item = &'a Self>
) -> Option<&'a Self>
pub fn find_signing_certificate<'a>(
&self,
certs: impl Iterator<Item = &'a Self>
) -> Option<&'a Self>
Attempt to find the issuing certificate of this one.
Given an iterable of certificates, we find the first certificate where we are able to verify that our signature was made by their public key.
This function can yield false negatives for cases where we don’t support the signature algorithm on the incoming certificates.
Examples found in repository?
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
pub fn resolve_signing_chain<'a>(
&self,
certs: impl Iterator<Item = &'a Self>,
) -> Vec<&'a Self> {
// The logic here is a bit wonky. As we build up the collection of certificates,
// we want to filter out ourself and remove duplicates. We remove duplicates by
// storing encountered certificates in a HashSet.
#[allow(clippy::mutable_key_type)]
let mut seen = HashSet::new();
let mut remaining = vec![];
for cert in certs {
if cert == self || seen.contains(cert) {
continue;
} else {
remaining.push(cert);
seen.insert(cert);
}
}
drop(seen);
let mut chain = vec![];
let mut last_cert = self;
while let Some(issuer) = last_cert.find_signing_certificate(remaining.iter().copied()) {
chain.push(issuer);
last_cert = issuer;
remaining = remaining
.drain(..)
.filter(|cert| *cert != issuer)
.collect::<Vec<_>>();
}
chain
}
sourcepub fn resolve_signing_chain<'a>(
&self,
certs: impl Iterator<Item = &'a Self>
) -> Vec<&'a Self> ⓘ
pub fn resolve_signing_chain<'a>(
&self,
certs: impl Iterator<Item = &'a Self>
) -> Vec<&'a Self> ⓘ
Attempt to resolve the signing chain of this certificate.
Given an iterable of certificates, we recursively resolve the chain of certificates that signed this one until we are no longer able to find any more certificates in the input set.
Like Self::find_signing_certificate, this can yield false negatives (read: an incomplete chain) due to run-time failures, such as lack of support for a certificate’s signature algorithm.
As a certificate is encountered, it is removed from the set of future candidates.
The traversal ends when we get to an identical certificate (its DER data is equivalent) or we couldn’t find a certificate in the remaining set that signed the last one.
Because we need to recursively verify certificates, the incoming iterator is buffered.
Methods from Deref<Target = X509Certificate>§
sourcepub fn serial_number_asn1(&self) -> &Integer
pub fn serial_number_asn1(&self) -> &Integer
Obtain the serial number as the ASN.1 Integer type.
sourcepub fn subject_name(&self) -> &Name
pub fn subject_name(&self) -> &Name
Obtain the certificate’s subject, as its ASN.1 Name type.
sourcepub fn subject_common_name(&self) -> Option<String>
pub fn subject_common_name(&self) -> Option<String>
Obtain the Common Name (CN) attribute from the certificate’s subject, if set and decodable.
sourcepub fn issuer_name(&self) -> &Name
pub fn issuer_name(&self) -> &Name
Obtain the certificate’s issuer, as its ASN.1 Name type.
sourcepub fn issuer_common_name(&self) -> Option<String>
pub fn issuer_common_name(&self) -> Option<String>
Obtain the Common Name (CN) attribute from the certificate’s issuer, if set and decodable.
sourcepub fn iter_extensions(&self) -> impl Iterator<Item = &Extension>
pub fn iter_extensions(&self) -> impl Iterator<Item = &Extension>
Iterate over extensions defined in this certificate.
sourcepub fn encode_der_to(&self, fh: &mut impl Write) -> Result<(), Error>
pub fn encode_der_to(&self, fh: &mut impl Write) -> Result<(), Error>
Encode the certificate data structure using DER encoding.
(This is the common ASN.1 encoding format for X.509 certificates.)
This always serializes the internal ASN.1 data structure. If you call this on a wrapper type that has retained a copy of the original data, this may emit different data than that copy.
Examples found in repository?
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
pub fn encode_der(&self) -> Result<Vec<u8>, std::io::Error> {
let mut buffer = Vec::<u8>::new();
self.encode_der_to(&mut buffer)?;
Ok(buffer)
}
/// Obtain the BER encoded representation of this certificate.
pub fn encode_ber(&self) -> Result<Vec<u8>, std::io::Error> {
let mut buffer = Vec::<u8>::new();
self.encode_ber_to(&mut buffer)?;
Ok(buffer)
}
/// Encode the certificate to PEM.
///
/// This will write a human-readable string with `------ BEGIN CERTIFICATE -------`
/// armoring. This is a very common method for encoding certificates.
///
/// The underlying binary data is DER encoded.
pub fn write_pem(&self, fh: &mut impl Write) -> Result<(), std::io::Error> {
let encoded = pem::encode(&pem::Pem {
tag: "CERTIFICATE".to_string(),
contents: self.encode_der()?,
});
fh.write_all(encoded.as_bytes())
}
/// Encode the certificate to a PEM string.
pub fn encode_pem(&self) -> Result<String, std::io::Error> {
Ok(pem::encode(&pem::Pem {
tag: "CERTIFICATE".to_string(),
contents: self.encode_der()?,
}))
}
/// Attempt to resolve a known [KeyAlgorithm] used by the private key associated with this certificate.
///
/// If this crate isn't aware of the OID associated with the key algorithm,
/// `None` is returned.
pub fn key_algorithm(&self) -> Option<KeyAlgorithm> {
KeyAlgorithm::try_from(&self.0.tbs_certificate.subject_public_key_info.algorithm).ok()
}
/// Obtain the OID of the private key's algorithm.
pub fn key_algorithm_oid(&self) -> &Oid {
&self
.0
.tbs_certificate
.subject_public_key_info
.algorithm
.algorithm
}
/// Obtain the [SignatureAlgorithm this certificate will use.
///
/// Returns [None] if we failed to resolve an instance (probably because we don't
/// recognize the algorithm).
pub fn signature_algorithm(&self) -> Option<SignatureAlgorithm> {
SignatureAlgorithm::try_from(&self.0.tbs_certificate.signature.algorithm).ok()
}
/// Obtain the OID of the signature algorithm this certificate will use.
pub fn signature_algorithm_oid(&self) -> &Oid {
&self.0.tbs_certificate.signature.algorithm
}
/// Obtain the [SignatureAlgorithm] used to sign this certificate.
///
/// Returns [None] if we failed to resolve an instance (probably because we
/// don't recognize that algorithm).
pub fn signature_signature_algorithm(&self) -> Option<SignatureAlgorithm> {
SignatureAlgorithm::try_from(&self.0.signature_algorithm).ok()
}
/// Obtain the OID of the signature algorithm used to sign this certificate.
pub fn signature_signature_algorithm_oid(&self) -> &Oid {
&self.0.signature_algorithm.algorithm
}
/// Obtain the raw data constituting this certificate's public key.
///
/// A copy of the data is returned.
pub fn public_key_data(&self) -> Bytes {
self.0
.tbs_certificate
.subject_public_key_info
.subject_public_key
.octet_bytes()
}
/// Attempt to parse the public key data as [RsaPublicKey] parameters.
///
/// Note that the raw integer value for modulus has a leading 0 byte. So its
/// raw length will be 1 greater than key length. e.g. an RSA 2048 key will
/// have `value.modulus.as_slice().len() == 257` instead of `256`.
pub fn rsa_public_key_data(&self) -> Result<RsaPublicKey, Error> {
let der = self.public_key_data();
Ok(Constructed::decode(
der.as_ref(),
Mode::Der,
RsaPublicKey::take_from,
)?)
}
/// Compare 2 instances, sorting them so the issuer comes before the issued.
///
/// This function examines the [Self::issuer_name] and [Self::subject_name]
/// fields of 2 certificates, attempting to sort them so the issuing
/// certificate comes before the issued certificate.
///
/// This function performs a strict compare of the ASN.1 [Name] data.
/// The assumption here is that the issuing certificate's subject [Name]
/// is identical to the issued's issuer [Name]. This assumption is often
/// true. But it likely isn't always true, so this function may not produce
/// reliable results.
pub fn compare_issuer(&self, other: &Self) -> Ordering {
// Self signed certificate has no ordering.
if self.0.tbs_certificate.subject == self.0.tbs_certificate.issuer {
Ordering::Equal
// We were issued by the other certificate. The issuer comes first.
} else if self.0.tbs_certificate.issuer == other.0.tbs_certificate.subject {
Ordering::Greater
} else if self.0.tbs_certificate.subject == other.0.tbs_certificate.issuer {
// We issued the other certificate. We come first.
Ordering::Less
} else {
Ordering::Equal
}
}
/// Whether the subject [Name] is also the issuer's [Name].
///
/// This might be a way of determining if a certificate is self-signed.
/// But there can likely be false negatives due to differences in ASN.1
/// encoding of the underlying data. So we don't claim this is a test for
/// being self-signed.
pub fn subject_is_issuer(&self) -> bool {
self.0.tbs_certificate.subject == self.0.tbs_certificate.issuer
}
/// Obtain the fingerprint for this certificate given a digest algorithm.
pub fn fingerprint(
&self,
algorithm: DigestAlgorithm,
) -> Result<ring::digest::Digest, std::io::Error> {
let raw = self.encode_der()?;
let mut h = algorithm.digester();
h.update(&raw);
Ok(h.finish())
}
/// Obtain the SHA-1 fingerprint of this certificate.
pub fn sha1_fingerprint(&self) -> Result<ring::digest::Digest, std::io::Error> {
self.fingerprint(DigestAlgorithm::Sha1)
}
/// Obtain the SHA-256 fingerprint of this certificate.
pub fn sha256_fingerprint(&self) -> Result<ring::digest::Digest, std::io::Error> {
self.fingerprint(DigestAlgorithm::Sha256)
}
}
impl From<rfc5280::Certificate> for X509Certificate {
fn from(v: rfc5280::Certificate) -> Self {
Self(v)
}
}
impl From<X509Certificate> for rfc5280::Certificate {
fn from(v: X509Certificate) -> Self {
v.0
}
}
impl AsRef<rfc5280::Certificate> for X509Certificate {
fn as_ref(&self) -> &rfc5280::Certificate {
&self.0
}
}
impl AsMut<rfc5280::Certificate> for X509Certificate {
fn as_mut(&mut self) -> &mut rfc5280::Certificate {
&mut self.0
}
}
impl EncodePublicKey for X509Certificate {
fn to_public_key_der(&self) -> spki::Result<Document> {
let mut data = vec![];
self.0
.tbs_certificate
.subject_public_key_info
.encode_ref()
.write_encoded(Mode::Der, &mut data)
.map_err(|_| spki::Error::Asn1(der::Error::new(der::ErrorKind::Failed, 0u8.into())))?;
Document::from_der(&data).map_err(spki::Error::Asn1)
}
}
#[derive(Clone, Eq, PartialEq)]
enum OriginalData {
Ber(Vec<u8>),
Der(Vec<u8>),
}
impl Debug for OriginalData {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"{}({})",
match self {
Self::Ber(_) => "Ber",
Self::Der(_) => "Der",
},
match self {
Self::Ber(data) => hex::encode(data),
Self::Der(data) => hex::encode(data),
}
))
}
}
/// Represents an immutable (read-only) X.509 certificate that was parsed from data.
///
/// This type implements [Deref] but not [DerefMut], so only functions
/// taking a non-mutable instance are usable.
///
/// A copy of the certificate's raw backing data is stored, facilitating
/// subsequent access.
#[derive(Clone, Debug)]
pub struct CapturedX509Certificate {
original: OriginalData,
inner: X509Certificate,
}
impl CapturedX509Certificate {
/// Construct an instance from DER encoded data.
///
/// A copy of this data will be stored in the instance and is guaranteed
/// to be immutable for the lifetime of the instance. The original constructing
/// data can be retrieved later.
pub fn from_der(data: impl Into<Vec<u8>>) -> Result<Self, Error> {
let der_data = data.into();
let inner = X509Certificate::from_der(&der_data)?;
Ok(Self {
original: OriginalData::Der(der_data),
inner,
})
}
/// Construct an instance from BER encoded data.
///
/// A copy of this data will be stored in the instance and is guaranteed
/// to be immutable for the lifetime of the instance, allowing it to
/// be retrieved later.
pub fn from_ber(data: impl Into<Vec<u8>>) -> Result<Self, Error> {
let data = data.into();
let inner = X509Certificate::from_ber(&data)?;
Ok(Self {
original: OriginalData::Ber(data),
inner,
})
}
/// Construct an instance by parsing PEM encoded ASN.1 data.
///
/// The data is a human readable string likely containing
/// `--------- BEGIN CERTIFICATE ----------`.
pub fn from_pem(data: impl AsRef<[u8]>) -> Result<Self, Error> {
let data = pem::parse(data.as_ref()).map_err(Error::PemDecode)?;
Self::from_der(data.contents)
}
/// Construct instances by parsing PEM with potentially multiple records.
///
/// By default, we only look for `--------- BEGIN CERTIFICATE --------`
/// entries and silently ignore unknown ones. If you would like to specify
/// an alternate set of tags (this is the value after the `BEGIN`) to search,
/// call [Self::from_pem_multiple_tags].
pub fn from_pem_multiple(data: impl AsRef<[u8]>) -> Result<Vec<Self>, Error> {
Self::from_pem_multiple_tags(data, &["CERTIFICATE"])
}
/// Construct instances by parsing PEM armored DER encoded certificates with specific PEM tags.
///
/// This is like [Self::from_pem_multiple] except you control the filter for
/// which `BEGIN <tag>` values are filtered through to the DER parser.
pub fn from_pem_multiple_tags(
data: impl AsRef<[u8]>,
tags: &[&str],
) -> Result<Vec<Self>, Error> {
let pem = pem::parse_many(data.as_ref()).map_err(Error::PemDecode)?;
pem.into_iter()
.filter(|pem| tags.contains(&pem.tag.as_str()))
.map(|pem| Self::from_der(pem.contents))
.collect::<Result<_, _>>()
}
/// Obtain the DER data that was used to construct this instance.
///
/// The data is guaranteed to not have been modified since the instance
/// was constructed.
pub fn constructed_data(&self) -> &[u8] {
match &self.original {
OriginalData::Ber(data) => data,
OriginalData::Der(data) => data,
}
}
/// Encode the original contents of this certificate to PEM.
pub fn encode_pem(&self) -> String {
pem::encode(&pem::Pem {
tag: "CERTIFICATE".to_string(),
contents: self.constructed_data().to_vec(),
})
}
/// Verify that another certificate, `other`, signed this certificate.
///
/// If this is a self-signed certificate, you can pass `self` as the 2nd
/// argument.
///
/// This function isn't exposed on [X509Certificate] because the exact
/// bytes constituting the certificate's internals need to be consulted
/// to verify signatures. And since this type tracks the underlying
/// bytes, we are guaranteed to have a pristine copy.
pub fn verify_signed_by_certificate(
&self,
other: impl AsRef<X509Certificate>,
) -> Result<(), Error> {
let public_key = other
.as_ref()
.0
.tbs_certificate
.subject_public_key_info
.subject_public_key
.octet_bytes();
self.verify_signed_by_public_key(public_key)
}
/// Verify a signature over signed data purportedly signed by this certificate.
///
/// This is a wrapper to [Self::verify_signed_data_with_algorithm()] that will derive
/// the verification algorithm from the public key type type and the signature algorithm
/// indicated in this certificate. Typically these align. However, it is possible for
/// a signature to be produced with a different digest algorithm from that indicated
/// in this certificate.
pub fn verify_signed_data(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
) -> Result<(), Error> {
let key_algorithm = KeyAlgorithm::try_from(self.key_algorithm_oid())?;
let signature_algorithm = SignatureAlgorithm::try_from(self.signature_algorithm_oid())?;
let verify_algorithm = signature_algorithm.resolve_verification_algorithm(key_algorithm)?;
self.verify_signed_data_with_algorithm(signed_data, signature, verify_algorithm)
}
/// Verify a signature over signed data using an explicit verification algorithm.
///
/// This is like [Self::verify_signed_data()] except the verification algorithm to use
/// is passed in instead of derived from the default algorithm for the signing key's
/// type.
pub fn verify_signed_data_with_algorithm(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
verify_algorithm: &'static dyn ringsig::VerificationAlgorithm,
) -> Result<(), Error> {
let public_key = ringsig::UnparsedPublicKey::new(verify_algorithm, self.public_key_data());
public_key
.verify(signed_data.as_ref(), signature.as_ref())
.map_err(|_| Error::CertificateSignatureVerificationFailed)
}
/// Verifies that this certificate was cryptographically signed using raw public key data from a signing key.
///
/// This function does the low-level work of extracting the signature and
/// verification details from the current certificate and figuring out
/// the correct combination of cryptography settings to apply to perform
/// signature verification.
///
/// In many cases, an X.509 certificate is signed by another certificate. And
/// since the public key is embedded in the X.509 certificate, it is easier
/// to go through [Self::verify_signed_by_certificate] instead.
pub fn verify_signed_by_public_key(
&self,
public_key_data: impl AsRef<[u8]>,
) -> Result<(), Error> {
// Always verify against the original content, as the inner
// certificate could be mutated via the mutable wrapper of this
// type.
let this_cert = match &self.original {
OriginalData::Ber(data) => X509Certificate::from_ber(data),
OriginalData::Der(data) => X509Certificate::from_der(data),
}
.expect("certificate re-parse should never fail");
let signed_data = this_cert
.0
.tbs_certificate
.raw_data
.as_ref()
.expect("original certificate data should have persisted as part of re-parse");
let signature = this_cert.0.signature.octet_bytes();
let key_algorithm = KeyAlgorithm::try_from(
&this_cert
.0
.tbs_certificate
.subject_public_key_info
.algorithm,
)?;
let signature_algorithm = SignatureAlgorithm::try_from(&this_cert.0.signature_algorithm)?;
let verify_algorithm = signature_algorithm.resolve_verification_algorithm(key_algorithm)?;
let public_key = ringsig::UnparsedPublicKey::new(verify_algorithm, public_key_data);
public_key
.verify(signed_data, &signature)
.map_err(|_| Error::CertificateSignatureVerificationFailed)
}
/// Attempt to find the issuing certificate of this one.
///
/// Given an iterable of certificates, we find the first certificate
/// where we are able to verify that our signature was made by their public
/// key.
///
/// This function can yield false negatives for cases where we don't
/// support the signature algorithm on the incoming certificates.
pub fn find_signing_certificate<'a>(
&self,
mut certs: impl Iterator<Item = &'a Self>,
) -> Option<&'a Self> {
certs.find(|candidate| self.verify_signed_by_certificate(candidate).is_ok())
}
/// Attempt to resolve the signing chain of this certificate.
///
/// Given an iterable of certificates, we recursively resolve the
/// chain of certificates that signed this one until we are no longer able
/// to find any more certificates in the input set.
///
/// Like [Self::find_signing_certificate], this can yield false
/// negatives (read: an incomplete chain) due to run-time failures,
/// such as lack of support for a certificate's signature algorithm.
///
/// As a certificate is encountered, it is removed from the set of
/// future candidates.
///
/// The traversal ends when we get to an identical certificate (its
/// DER data is equivalent) or we couldn't find a certificate in
/// the remaining set that signed the last one.
///
/// Because we need to recursively verify certificates, the incoming
/// iterator is buffered.
pub fn resolve_signing_chain<'a>(
&self,
certs: impl Iterator<Item = &'a Self>,
) -> Vec<&'a Self> {
// The logic here is a bit wonky. As we build up the collection of certificates,
// we want to filter out ourself and remove duplicates. We remove duplicates by
// storing encountered certificates in a HashSet.
#[allow(clippy::mutable_key_type)]
let mut seen = HashSet::new();
let mut remaining = vec![];
for cert in certs {
if cert == self || seen.contains(cert) {
continue;
} else {
remaining.push(cert);
seen.insert(cert);
}
}
drop(seen);
let mut chain = vec![];
let mut last_cert = self;
while let Some(issuer) = last_cert.find_signing_certificate(remaining.iter().copied()) {
chain.push(issuer);
last_cert = issuer;
remaining = remaining
.drain(..)
.filter(|cert| *cert != issuer)
.collect::<Vec<_>>();
}
chain
}
}
impl PartialEq for CapturedX509Certificate {
fn eq(&self, other: &Self) -> bool {
self.constructed_data() == other.constructed_data()
}
}
impl Eq for CapturedX509Certificate {}
impl Hash for CapturedX509Certificate {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(self.constructed_data());
}
}
impl Deref for CapturedX509Certificate {
type Target = X509Certificate;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl AsRef<X509Certificate> for CapturedX509Certificate {
fn as_ref(&self) -> &X509Certificate {
&self.inner
}
}
impl AsRef<rfc5280::Certificate> for CapturedX509Certificate {
fn as_ref(&self) -> &rfc5280::Certificate {
self.inner.as_ref()
}
}
impl TryFrom<&X509Certificate> for CapturedX509Certificate {
type Error = Error;
fn try_from(cert: &X509Certificate) -> Result<Self, Self::Error> {
let mut buffer = Vec::<u8>::new();
cert.encode_der_to(&mut buffer)?;
Self::from_der(buffer)
}
}
impl TryFrom<X509Certificate> for CapturedX509Certificate {
type Error = Error;
fn try_from(cert: X509Certificate) -> Result<Self, Self::Error> {
let mut buffer = Vec::<u8>::new();
cert.encode_der_to(&mut buffer)?;
Self::from_der(buffer)
}
sourcepub fn encode_ber_to(&self, fh: &mut impl Write) -> Result<(), Error>
pub fn encode_ber_to(&self, fh: &mut impl Write) -> Result<(), Error>
Encode the certificate data structure use BER encoding.
sourcepub fn encode_der(&self) -> Result<Vec<u8>, Error>
pub fn encode_der(&self) -> Result<Vec<u8>, Error>
Encode the internal ASN.1 data structures to DER.
Examples found in repository?
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
pub fn write_pem(&self, fh: &mut impl Write) -> Result<(), std::io::Error> {
let encoded = pem::encode(&pem::Pem {
tag: "CERTIFICATE".to_string(),
contents: self.encode_der()?,
});
fh.write_all(encoded.as_bytes())
}
/// Encode the certificate to a PEM string.
pub fn encode_pem(&self) -> Result<String, std::io::Error> {
Ok(pem::encode(&pem::Pem {
tag: "CERTIFICATE".to_string(),
contents: self.encode_der()?,
}))
}
/// Attempt to resolve a known [KeyAlgorithm] used by the private key associated with this certificate.
///
/// If this crate isn't aware of the OID associated with the key algorithm,
/// `None` is returned.
pub fn key_algorithm(&self) -> Option<KeyAlgorithm> {
KeyAlgorithm::try_from(&self.0.tbs_certificate.subject_public_key_info.algorithm).ok()
}
/// Obtain the OID of the private key's algorithm.
pub fn key_algorithm_oid(&self) -> &Oid {
&self
.0
.tbs_certificate
.subject_public_key_info
.algorithm
.algorithm
}
/// Obtain the [SignatureAlgorithm this certificate will use.
///
/// Returns [None] if we failed to resolve an instance (probably because we don't
/// recognize the algorithm).
pub fn signature_algorithm(&self) -> Option<SignatureAlgorithm> {
SignatureAlgorithm::try_from(&self.0.tbs_certificate.signature.algorithm).ok()
}
/// Obtain the OID of the signature algorithm this certificate will use.
pub fn signature_algorithm_oid(&self) -> &Oid {
&self.0.tbs_certificate.signature.algorithm
}
/// Obtain the [SignatureAlgorithm] used to sign this certificate.
///
/// Returns [None] if we failed to resolve an instance (probably because we
/// don't recognize that algorithm).
pub fn signature_signature_algorithm(&self) -> Option<SignatureAlgorithm> {
SignatureAlgorithm::try_from(&self.0.signature_algorithm).ok()
}
/// Obtain the OID of the signature algorithm used to sign this certificate.
pub fn signature_signature_algorithm_oid(&self) -> &Oid {
&self.0.signature_algorithm.algorithm
}
/// Obtain the raw data constituting this certificate's public key.
///
/// A copy of the data is returned.
pub fn public_key_data(&self) -> Bytes {
self.0
.tbs_certificate
.subject_public_key_info
.subject_public_key
.octet_bytes()
}
/// Attempt to parse the public key data as [RsaPublicKey] parameters.
///
/// Note that the raw integer value for modulus has a leading 0 byte. So its
/// raw length will be 1 greater than key length. e.g. an RSA 2048 key will
/// have `value.modulus.as_slice().len() == 257` instead of `256`.
pub fn rsa_public_key_data(&self) -> Result<RsaPublicKey, Error> {
let der = self.public_key_data();
Ok(Constructed::decode(
der.as_ref(),
Mode::Der,
RsaPublicKey::take_from,
)?)
}
/// Compare 2 instances, sorting them so the issuer comes before the issued.
///
/// This function examines the [Self::issuer_name] and [Self::subject_name]
/// fields of 2 certificates, attempting to sort them so the issuing
/// certificate comes before the issued certificate.
///
/// This function performs a strict compare of the ASN.1 [Name] data.
/// The assumption here is that the issuing certificate's subject [Name]
/// is identical to the issued's issuer [Name]. This assumption is often
/// true. But it likely isn't always true, so this function may not produce
/// reliable results.
pub fn compare_issuer(&self, other: &Self) -> Ordering {
// Self signed certificate has no ordering.
if self.0.tbs_certificate.subject == self.0.tbs_certificate.issuer {
Ordering::Equal
// We were issued by the other certificate. The issuer comes first.
} else if self.0.tbs_certificate.issuer == other.0.tbs_certificate.subject {
Ordering::Greater
} else if self.0.tbs_certificate.subject == other.0.tbs_certificate.issuer {
// We issued the other certificate. We come first.
Ordering::Less
} else {
Ordering::Equal
}
}
/// Whether the subject [Name] is also the issuer's [Name].
///
/// This might be a way of determining if a certificate is self-signed.
/// But there can likely be false negatives due to differences in ASN.1
/// encoding of the underlying data. So we don't claim this is a test for
/// being self-signed.
pub fn subject_is_issuer(&self) -> bool {
self.0.tbs_certificate.subject == self.0.tbs_certificate.issuer
}
/// Obtain the fingerprint for this certificate given a digest algorithm.
pub fn fingerprint(
&self,
algorithm: DigestAlgorithm,
) -> Result<ring::digest::Digest, std::io::Error> {
let raw = self.encode_der()?;
let mut h = algorithm.digester();
h.update(&raw);
Ok(h.finish())
}
/// Obtain the SHA-1 fingerprint of this certificate.
pub fn sha1_fingerprint(&self) -> Result<ring::digest::Digest, std::io::Error> {
self.fingerprint(DigestAlgorithm::Sha1)
}
/// Obtain the SHA-256 fingerprint of this certificate.
pub fn sha256_fingerprint(&self) -> Result<ring::digest::Digest, std::io::Error> {
self.fingerprint(DigestAlgorithm::Sha256)
}
}
impl From<rfc5280::Certificate> for X509Certificate {
fn from(v: rfc5280::Certificate) -> Self {
Self(v)
}
}
impl From<X509Certificate> for rfc5280::Certificate {
fn from(v: X509Certificate) -> Self {
v.0
}
}
impl AsRef<rfc5280::Certificate> for X509Certificate {
fn as_ref(&self) -> &rfc5280::Certificate {
&self.0
}
}
impl AsMut<rfc5280::Certificate> for X509Certificate {
fn as_mut(&mut self) -> &mut rfc5280::Certificate {
&mut self.0
}
}
impl EncodePublicKey for X509Certificate {
fn to_public_key_der(&self) -> spki::Result<Document> {
let mut data = vec![];
self.0
.tbs_certificate
.subject_public_key_info
.encode_ref()
.write_encoded(Mode::Der, &mut data)
.map_err(|_| spki::Error::Asn1(der::Error::new(der::ErrorKind::Failed, 0u8.into())))?;
Document::from_der(&data).map_err(spki::Error::Asn1)
}
}
#[derive(Clone, Eq, PartialEq)]
enum OriginalData {
Ber(Vec<u8>),
Der(Vec<u8>),
}
impl Debug for OriginalData {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"{}({})",
match self {
Self::Ber(_) => "Ber",
Self::Der(_) => "Der",
},
match self {
Self::Ber(data) => hex::encode(data),
Self::Der(data) => hex::encode(data),
}
))
}
}
/// Represents an immutable (read-only) X.509 certificate that was parsed from data.
///
/// This type implements [Deref] but not [DerefMut], so only functions
/// taking a non-mutable instance are usable.
///
/// A copy of the certificate's raw backing data is stored, facilitating
/// subsequent access.
#[derive(Clone, Debug)]
pub struct CapturedX509Certificate {
original: OriginalData,
inner: X509Certificate,
}
impl CapturedX509Certificate {
/// Construct an instance from DER encoded data.
///
/// A copy of this data will be stored in the instance and is guaranteed
/// to be immutable for the lifetime of the instance. The original constructing
/// data can be retrieved later.
pub fn from_der(data: impl Into<Vec<u8>>) -> Result<Self, Error> {
let der_data = data.into();
let inner = X509Certificate::from_der(&der_data)?;
Ok(Self {
original: OriginalData::Der(der_data),
inner,
})
}
/// Construct an instance from BER encoded data.
///
/// A copy of this data will be stored in the instance and is guaranteed
/// to be immutable for the lifetime of the instance, allowing it to
/// be retrieved later.
pub fn from_ber(data: impl Into<Vec<u8>>) -> Result<Self, Error> {
let data = data.into();
let inner = X509Certificate::from_ber(&data)?;
Ok(Self {
original: OriginalData::Ber(data),
inner,
})
}
/// Construct an instance by parsing PEM encoded ASN.1 data.
///
/// The data is a human readable string likely containing
/// `--------- BEGIN CERTIFICATE ----------`.
pub fn from_pem(data: impl AsRef<[u8]>) -> Result<Self, Error> {
let data = pem::parse(data.as_ref()).map_err(Error::PemDecode)?;
Self::from_der(data.contents)
}
/// Construct instances by parsing PEM with potentially multiple records.
///
/// By default, we only look for `--------- BEGIN CERTIFICATE --------`
/// entries and silently ignore unknown ones. If you would like to specify
/// an alternate set of tags (this is the value after the `BEGIN`) to search,
/// call [Self::from_pem_multiple_tags].
pub fn from_pem_multiple(data: impl AsRef<[u8]>) -> Result<Vec<Self>, Error> {
Self::from_pem_multiple_tags(data, &["CERTIFICATE"])
}
/// Construct instances by parsing PEM armored DER encoded certificates with specific PEM tags.
///
/// This is like [Self::from_pem_multiple] except you control the filter for
/// which `BEGIN <tag>` values are filtered through to the DER parser.
pub fn from_pem_multiple_tags(
data: impl AsRef<[u8]>,
tags: &[&str],
) -> Result<Vec<Self>, Error> {
let pem = pem::parse_many(data.as_ref()).map_err(Error::PemDecode)?;
pem.into_iter()
.filter(|pem| tags.contains(&pem.tag.as_str()))
.map(|pem| Self::from_der(pem.contents))
.collect::<Result<_, _>>()
}
/// Obtain the DER data that was used to construct this instance.
///
/// The data is guaranteed to not have been modified since the instance
/// was constructed.
pub fn constructed_data(&self) -> &[u8] {
match &self.original {
OriginalData::Ber(data) => data,
OriginalData::Der(data) => data,
}
}
/// Encode the original contents of this certificate to PEM.
pub fn encode_pem(&self) -> String {
pem::encode(&pem::Pem {
tag: "CERTIFICATE".to_string(),
contents: self.constructed_data().to_vec(),
})
}
/// Verify that another certificate, `other`, signed this certificate.
///
/// If this is a self-signed certificate, you can pass `self` as the 2nd
/// argument.
///
/// This function isn't exposed on [X509Certificate] because the exact
/// bytes constituting the certificate's internals need to be consulted
/// to verify signatures. And since this type tracks the underlying
/// bytes, we are guaranteed to have a pristine copy.
pub fn verify_signed_by_certificate(
&self,
other: impl AsRef<X509Certificate>,
) -> Result<(), Error> {
let public_key = other
.as_ref()
.0
.tbs_certificate
.subject_public_key_info
.subject_public_key
.octet_bytes();
self.verify_signed_by_public_key(public_key)
}
/// Verify a signature over signed data purportedly signed by this certificate.
///
/// This is a wrapper to [Self::verify_signed_data_with_algorithm()] that will derive
/// the verification algorithm from the public key type type and the signature algorithm
/// indicated in this certificate. Typically these align. However, it is possible for
/// a signature to be produced with a different digest algorithm from that indicated
/// in this certificate.
pub fn verify_signed_data(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
) -> Result<(), Error> {
let key_algorithm = KeyAlgorithm::try_from(self.key_algorithm_oid())?;
let signature_algorithm = SignatureAlgorithm::try_from(self.signature_algorithm_oid())?;
let verify_algorithm = signature_algorithm.resolve_verification_algorithm(key_algorithm)?;
self.verify_signed_data_with_algorithm(signed_data, signature, verify_algorithm)
}
/// Verify a signature over signed data using an explicit verification algorithm.
///
/// This is like [Self::verify_signed_data()] except the verification algorithm to use
/// is passed in instead of derived from the default algorithm for the signing key's
/// type.
pub fn verify_signed_data_with_algorithm(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
verify_algorithm: &'static dyn ringsig::VerificationAlgorithm,
) -> Result<(), Error> {
let public_key = ringsig::UnparsedPublicKey::new(verify_algorithm, self.public_key_data());
public_key
.verify(signed_data.as_ref(), signature.as_ref())
.map_err(|_| Error::CertificateSignatureVerificationFailed)
}
/// Verifies that this certificate was cryptographically signed using raw public key data from a signing key.
///
/// This function does the low-level work of extracting the signature and
/// verification details from the current certificate and figuring out
/// the correct combination of cryptography settings to apply to perform
/// signature verification.
///
/// In many cases, an X.509 certificate is signed by another certificate. And
/// since the public key is embedded in the X.509 certificate, it is easier
/// to go through [Self::verify_signed_by_certificate] instead.
pub fn verify_signed_by_public_key(
&self,
public_key_data: impl AsRef<[u8]>,
) -> Result<(), Error> {
// Always verify against the original content, as the inner
// certificate could be mutated via the mutable wrapper of this
// type.
let this_cert = match &self.original {
OriginalData::Ber(data) => X509Certificate::from_ber(data),
OriginalData::Der(data) => X509Certificate::from_der(data),
}
.expect("certificate re-parse should never fail");
let signed_data = this_cert
.0
.tbs_certificate
.raw_data
.as_ref()
.expect("original certificate data should have persisted as part of re-parse");
let signature = this_cert.0.signature.octet_bytes();
let key_algorithm = KeyAlgorithm::try_from(
&this_cert
.0
.tbs_certificate
.subject_public_key_info
.algorithm,
)?;
let signature_algorithm = SignatureAlgorithm::try_from(&this_cert.0.signature_algorithm)?;
let verify_algorithm = signature_algorithm.resolve_verification_algorithm(key_algorithm)?;
let public_key = ringsig::UnparsedPublicKey::new(verify_algorithm, public_key_data);
public_key
.verify(signed_data, &signature)
.map_err(|_| Error::CertificateSignatureVerificationFailed)
}
/// Attempt to find the issuing certificate of this one.
///
/// Given an iterable of certificates, we find the first certificate
/// where we are able to verify that our signature was made by their public
/// key.
///
/// This function can yield false negatives for cases where we don't
/// support the signature algorithm on the incoming certificates.
pub fn find_signing_certificate<'a>(
&self,
mut certs: impl Iterator<Item = &'a Self>,
) -> Option<&'a Self> {
certs.find(|candidate| self.verify_signed_by_certificate(candidate).is_ok())
}
/// Attempt to resolve the signing chain of this certificate.
///
/// Given an iterable of certificates, we recursively resolve the
/// chain of certificates that signed this one until we are no longer able
/// to find any more certificates in the input set.
///
/// Like [Self::find_signing_certificate], this can yield false
/// negatives (read: an incomplete chain) due to run-time failures,
/// such as lack of support for a certificate's signature algorithm.
///
/// As a certificate is encountered, it is removed from the set of
/// future candidates.
///
/// The traversal ends when we get to an identical certificate (its
/// DER data is equivalent) or we couldn't find a certificate in
/// the remaining set that signed the last one.
///
/// Because we need to recursively verify certificates, the incoming
/// iterator is buffered.
pub fn resolve_signing_chain<'a>(
&self,
certs: impl Iterator<Item = &'a Self>,
) -> Vec<&'a Self> {
// The logic here is a bit wonky. As we build up the collection of certificates,
// we want to filter out ourself and remove duplicates. We remove duplicates by
// storing encountered certificates in a HashSet.
#[allow(clippy::mutable_key_type)]
let mut seen = HashSet::new();
let mut remaining = vec![];
for cert in certs {
if cert == self || seen.contains(cert) {
continue;
} else {
remaining.push(cert);
seen.insert(cert);
}
}
drop(seen);
let mut chain = vec![];
let mut last_cert = self;
while let Some(issuer) = last_cert.find_signing_certificate(remaining.iter().copied()) {
chain.push(issuer);
last_cert = issuer;
remaining = remaining
.drain(..)
.filter(|cert| *cert != issuer)
.collect::<Vec<_>>();
}
chain
}
}
impl PartialEq for CapturedX509Certificate {
fn eq(&self, other: &Self) -> bool {
self.constructed_data() == other.constructed_data()
}
}
impl Eq for CapturedX509Certificate {}
impl Hash for CapturedX509Certificate {
fn hash<H: Hasher>(&self, state: &mut H) {
state.write(self.constructed_data());
}
}
impl Deref for CapturedX509Certificate {
type Target = X509Certificate;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl AsRef<X509Certificate> for CapturedX509Certificate {
fn as_ref(&self) -> &X509Certificate {
&self.inner
}
}
impl AsRef<rfc5280::Certificate> for CapturedX509Certificate {
fn as_ref(&self) -> &rfc5280::Certificate {
self.inner.as_ref()
}
}
impl TryFrom<&X509Certificate> for CapturedX509Certificate {
type Error = Error;
fn try_from(cert: &X509Certificate) -> Result<Self, Self::Error> {
let mut buffer = Vec::<u8>::new();
cert.encode_der_to(&mut buffer)?;
Self::from_der(buffer)
}
}
impl TryFrom<X509Certificate> for CapturedX509Certificate {
type Error = Error;
fn try_from(cert: X509Certificate) -> Result<Self, Self::Error> {
let mut buffer = Vec::<u8>::new();
cert.encode_der_to(&mut buffer)?;
Self::from_der(buffer)
}
}
impl From<CapturedX509Certificate> for rfc5280::Certificate {
fn from(cert: CapturedX509Certificate) -> Self {
cert.inner.0
}
}
/// Provides a mutable wrapper to an X.509 certificate that was parsed from data.
///
/// This is like [CapturedX509Certificate] except it implements [DerefMut],
/// enabling you to modify the certificate while still being able to access
/// the raw data the certificate is backed by. However, mutations are
/// only performed against the parsed ASN.1 data structure, not the original
/// data it was constructed with.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MutableX509Certificate(CapturedX509Certificate);
impl Deref for MutableX509Certificate {
type Target = X509Certificate;
fn deref(&self) -> &Self::Target {
&self.0.inner
}
}
impl DerefMut for MutableX509Certificate {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0.inner
}
}
impl From<CapturedX509Certificate> for MutableX509Certificate {
fn from(cert: CapturedX509Certificate) -> Self {
Self(cert)
}
}
/// Whether one certificate is a subset of another certificate.
///
/// This returns true iff the two certificates have the same serial number
/// and every `Name` attribute in the first certificate is present in the other.
pub fn certificate_is_subset_of(
a_serial: &Integer,
a_name: &Name,
b_serial: &Integer,
b_name: &Name,
) -> bool {
if a_serial != b_serial {
return false;
}
let Name::RdnSequence(a_sequence) = &a_name;
let Name::RdnSequence(b_sequence) = &b_name;
a_sequence.iter().all(|rdn| b_sequence.contains(rdn))
}
/// X.509 extension to define how a certificate can be used.
///
/// ```asn.1
/// KeyUsage ::= BIT STRING {
/// digitalSignature(0),
/// nonRepudiation(1),
/// keyEncipherment(2),
/// dataEncipherment(3),
/// keyAgreement(4),
/// keyCertSign(5),
/// cRLSign(6)
/// }
/// ```
pub enum KeyUsage {
DigitalSignature,
NonRepudiation,
KeyEncipherment,
DataEncipherment,
KeyAgreement,
KeyCertSign,
CrlSign,
}
impl From<KeyUsage> for u8 {
fn from(ku: KeyUsage) -> Self {
match ku {
KeyUsage::DigitalSignature => 0,
KeyUsage::NonRepudiation => 1,
KeyUsage::KeyEncipherment => 2,
KeyUsage::DataEncipherment => 3,
KeyUsage::KeyAgreement => 4,
KeyUsage::KeyCertSign => 5,
KeyUsage::CrlSign => 6,
}
}
}
/// Interface for constructing new X.509 certificates.
///
/// This holds fields for various certificate metadata and allows you
/// to incrementally derive a new X.509 certificate.
///
/// The certificate is populated with defaults:
///
/// * The serial number is 1.
/// * The time validity is now until 1 hour from now.
/// * There is no issuer. If no attempt is made to define an issuer,
/// the subject will be copied to the issuer field and this will be
/// a self-signed certificate.
///
/// This type can also be used to produce certificate signing requests. In this mode,
/// only the subject value and additional registered attributes are meaningful.
pub struct X509CertificateBuilder {
key_algorithm: KeyAlgorithm,
subject: Name,
issuer: Option<Name>,
extensions: rfc5280::Extensions,
serial_number: i64,
not_before: chrono::DateTime<Utc>,
not_after: chrono::DateTime<Utc>,
csr_attributes: Attributes,
}
impl X509CertificateBuilder {
pub fn new(alg: KeyAlgorithm) -> Self {
let not_before = Utc::now();
let not_after = not_before + Duration::hours(1);
Self {
key_algorithm: alg,
subject: Name::default(),
issuer: None,
extensions: rfc5280::Extensions::default(),
serial_number: 1,
not_before,
not_after,
csr_attributes: Attributes::default(),
}
}
/// Obtain a mutable reference to the subject [Name].
///
/// The type has functions that will allow you to add attributes with ease.
pub fn subject(&mut self) -> &mut Name {
&mut self.subject
}
/// Obtain a mutable reference to the issuer [Name].
///
/// If no issuer has been created yet, an empty one will be created.
pub fn issuer(&mut self) -> &mut Name {
self.issuer.get_or_insert_with(Name::default)
}
/// Set the serial number for the certificate.
pub fn serial_number(&mut self, value: i64) {
self.serial_number = value;
}
/// Obtain the raw certificate extensions.
pub fn extensions(&self) -> &rfc5280::Extensions {
&self.extensions
}
/// Obtain a mutable reference to raw certificate extensions.
pub fn extensions_mut(&mut self) -> &mut rfc5280::Extensions {
&mut self.extensions
}
/// Add an extension to the certificate with its value as pre-encoded DER data.
pub fn add_extension_der_data(&mut self, oid: Oid, critical: bool, data: impl AsRef<[u8]>) {
self.extensions.push(rfc5280::Extension {
id: oid,
critical: Some(critical),
value: OctetString::new(Bytes::copy_from_slice(data.as_ref())),
});
}
/// Set the expiration time in terms of [Duration] since its currently set start time.
pub fn validity_duration(&mut self, duration: Duration) {
self.not_after = self.not_before + duration;
}
/// Add a basic constraint extension that this isn't a CA certificate.
pub fn constraint_not_ca(&mut self) {
self.extensions.push(rfc5280::Extension {
id: Oid(OID_EXTENSION_BASIC_CONSTRAINTS.as_ref().into()),
critical: Some(true),
value: OctetString::new(Bytes::copy_from_slice(&[0x30, 00])),
});
}
/// Add a key usage extension.
pub fn key_usage(&mut self, key_usage: KeyUsage) {
let value: u8 = key_usage.into();
self.extensions.push(rfc5280::Extension {
id: Oid(OID_EXTENSION_KEY_USAGE.as_ref().into()),
critical: Some(true),
// Value is a bit string. We just encode it manually since it is easy.
value: OctetString::new(Bytes::copy_from_slice(&[3, 2, 7, 128 | value])),
});
}
/// Add an [Attribute] to a future certificate signing requests.
///
/// Has no effect on regular certificate creation: only if creating certificate
/// signing requests.
pub fn add_csr_attribute(&mut self, attribute: rfc5652::Attribute) {
self.csr_attributes.push(attribute);
}
/// Create a new certificate given settings, using a randomly generated key pair.
pub fn create_with_random_keypair(
&self,
) -> Result<
(
CapturedX509Certificate,
InMemorySigningKeyPair,
ring::pkcs8::Document,
),
Error,
> {
let (key_pair, document) = InMemorySigningKeyPair::generate_random(self.key_algorithm)?;
let key_pair_signature_algorithm = key_pair.signature_algorithm();
let issuer = if let Some(issuer) = &self.issuer {
issuer
} else {
&self.subject
};
let tbs_certificate = rfc5280::TbsCertificate {
version: Some(rfc5280::Version::V3),
serial_number: self.serial_number.into(),
signature: key_pair_signature_algorithm?.into(),
issuer: issuer.clone(),
validity: rfc5280::Validity {
not_before: Time::from(self.not_before),
not_after: Time::from(self.not_after),
},
subject: self.subject.clone(),
subject_public_key_info: rfc5280::SubjectPublicKeyInfo {
algorithm: key_pair
.key_algorithm()
.expect("InMemorySigningKeyPair always has known key algorithm")
.into(),
subject_public_key: BitString::new(0, key_pair.public_key_data()),
},
issuer_unique_id: None,
subject_unique_id: None,
extensions: if self.extensions.is_empty() {
None
} else {
Some(self.extensions.clone())
},
raw_data: None,
};
// Now encode the TBS certificate so we can sign it with the private key
// and include its signature.
let mut tbs_der = Vec::<u8>::new();
tbs_certificate
.encode_ref()
.write_encoded(Mode::Der, &mut tbs_der)?;
let signature = key_pair.try_sign(&tbs_der)?;
let signature_algorithm = key_pair.signature_algorithm()?;
let cert = rfc5280::Certificate {
tbs_certificate,
signature_algorithm: signature_algorithm.into(),
signature: BitString::new(0, Bytes::copy_from_slice(signature.as_ref())),
};
let cert = X509Certificate::from(cert);
let cert_der = cert.encode_der()?;
let cert = CapturedX509Certificate::from_der(cert_der)?;
Ok((cert, key_pair, document))
}
sourcepub fn encode_ber(&self) -> Result<Vec<u8>, Error>
pub fn encode_ber(&self) -> Result<Vec<u8>, Error>
Obtain the BER encoded representation of this certificate.
sourcepub fn write_pem(&self, fh: &mut impl Write) -> Result<(), Error>
pub fn write_pem(&self, fh: &mut impl Write) -> Result<(), Error>
Encode the certificate to PEM.
This will write a human-readable string with ------ BEGIN CERTIFICATE -------
armoring. This is a very common method for encoding certificates.
The underlying binary data is DER encoded.
sourcepub fn encode_pem(&self) -> Result<String, Error>
pub fn encode_pem(&self) -> Result<String, Error>
Encode the certificate to a PEM string.
sourcepub fn key_algorithm(&self) -> Option<KeyAlgorithm>
pub fn key_algorithm(&self) -> Option<KeyAlgorithm>
Attempt to resolve a known KeyAlgorithm used by the private key associated with this certificate.
If this crate isn’t aware of the OID associated with the key algorithm,
None
is returned.
sourcepub fn key_algorithm_oid(&self) -> &Oid
pub fn key_algorithm_oid(&self) -> &Oid
Obtain the OID of the private key’s algorithm.
sourcepub fn signature_algorithm(&self) -> Option<SignatureAlgorithm>
pub fn signature_algorithm(&self) -> Option<SignatureAlgorithm>
Obtain the [SignatureAlgorithm this certificate will use.
Returns None if we failed to resolve an instance (probably because we don’t recognize the algorithm).
sourcepub fn signature_algorithm_oid(&self) -> &Oid
pub fn signature_algorithm_oid(&self) -> &Oid
Obtain the OID of the signature algorithm this certificate will use.
sourcepub fn signature_signature_algorithm(&self) -> Option<SignatureAlgorithm>
pub fn signature_signature_algorithm(&self) -> Option<SignatureAlgorithm>
Obtain the SignatureAlgorithm used to sign this certificate.
Returns None if we failed to resolve an instance (probably because we don’t recognize that algorithm).
sourcepub fn signature_signature_algorithm_oid(&self) -> &Oid
pub fn signature_signature_algorithm_oid(&self) -> &Oid
Obtain the OID of the signature algorithm used to sign this certificate.
sourcepub fn public_key_data(&self) -> Bytes
pub fn public_key_data(&self) -> Bytes
Obtain the raw data constituting this certificate’s public key.
A copy of the data is returned.
Examples found in repository?
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
pub fn rsa_public_key_data(&self) -> Result<RsaPublicKey, Error> {
let der = self.public_key_data();
Ok(Constructed::decode(
der.as_ref(),
Mode::Der,
RsaPublicKey::take_from,
)?)
}
/// Compare 2 instances, sorting them so the issuer comes before the issued.
///
/// This function examines the [Self::issuer_name] and [Self::subject_name]
/// fields of 2 certificates, attempting to sort them so the issuing
/// certificate comes before the issued certificate.
///
/// This function performs a strict compare of the ASN.1 [Name] data.
/// The assumption here is that the issuing certificate's subject [Name]
/// is identical to the issued's issuer [Name]. This assumption is often
/// true. But it likely isn't always true, so this function may not produce
/// reliable results.
pub fn compare_issuer(&self, other: &Self) -> Ordering {
// Self signed certificate has no ordering.
if self.0.tbs_certificate.subject == self.0.tbs_certificate.issuer {
Ordering::Equal
// We were issued by the other certificate. The issuer comes first.
} else if self.0.tbs_certificate.issuer == other.0.tbs_certificate.subject {
Ordering::Greater
} else if self.0.tbs_certificate.subject == other.0.tbs_certificate.issuer {
// We issued the other certificate. We come first.
Ordering::Less
} else {
Ordering::Equal
}
}
/// Whether the subject [Name] is also the issuer's [Name].
///
/// This might be a way of determining if a certificate is self-signed.
/// But there can likely be false negatives due to differences in ASN.1
/// encoding of the underlying data. So we don't claim this is a test for
/// being self-signed.
pub fn subject_is_issuer(&self) -> bool {
self.0.tbs_certificate.subject == self.0.tbs_certificate.issuer
}
/// Obtain the fingerprint for this certificate given a digest algorithm.
pub fn fingerprint(
&self,
algorithm: DigestAlgorithm,
) -> Result<ring::digest::Digest, std::io::Error> {
let raw = self.encode_der()?;
let mut h = algorithm.digester();
h.update(&raw);
Ok(h.finish())
}
/// Obtain the SHA-1 fingerprint of this certificate.
pub fn sha1_fingerprint(&self) -> Result<ring::digest::Digest, std::io::Error> {
self.fingerprint(DigestAlgorithm::Sha1)
}
/// Obtain the SHA-256 fingerprint of this certificate.
pub fn sha256_fingerprint(&self) -> Result<ring::digest::Digest, std::io::Error> {
self.fingerprint(DigestAlgorithm::Sha256)
}
}
impl From<rfc5280::Certificate> for X509Certificate {
fn from(v: rfc5280::Certificate) -> Self {
Self(v)
}
}
impl From<X509Certificate> for rfc5280::Certificate {
fn from(v: X509Certificate) -> Self {
v.0
}
}
impl AsRef<rfc5280::Certificate> for X509Certificate {
fn as_ref(&self) -> &rfc5280::Certificate {
&self.0
}
}
impl AsMut<rfc5280::Certificate> for X509Certificate {
fn as_mut(&mut self) -> &mut rfc5280::Certificate {
&mut self.0
}
}
impl EncodePublicKey for X509Certificate {
fn to_public_key_der(&self) -> spki::Result<Document> {
let mut data = vec![];
self.0
.tbs_certificate
.subject_public_key_info
.encode_ref()
.write_encoded(Mode::Der, &mut data)
.map_err(|_| spki::Error::Asn1(der::Error::new(der::ErrorKind::Failed, 0u8.into())))?;
Document::from_der(&data).map_err(spki::Error::Asn1)
}
}
#[derive(Clone, Eq, PartialEq)]
enum OriginalData {
Ber(Vec<u8>),
Der(Vec<u8>),
}
impl Debug for OriginalData {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"{}({})",
match self {
Self::Ber(_) => "Ber",
Self::Der(_) => "Der",
},
match self {
Self::Ber(data) => hex::encode(data),
Self::Der(data) => hex::encode(data),
}
))
}
}
/// Represents an immutable (read-only) X.509 certificate that was parsed from data.
///
/// This type implements [Deref] but not [DerefMut], so only functions
/// taking a non-mutable instance are usable.
///
/// A copy of the certificate's raw backing data is stored, facilitating
/// subsequent access.
#[derive(Clone, Debug)]
pub struct CapturedX509Certificate {
original: OriginalData,
inner: X509Certificate,
}
impl CapturedX509Certificate {
/// Construct an instance from DER encoded data.
///
/// A copy of this data will be stored in the instance and is guaranteed
/// to be immutable for the lifetime of the instance. The original constructing
/// data can be retrieved later.
pub fn from_der(data: impl Into<Vec<u8>>) -> Result<Self, Error> {
let der_data = data.into();
let inner = X509Certificate::from_der(&der_data)?;
Ok(Self {
original: OriginalData::Der(der_data),
inner,
})
}
/// Construct an instance from BER encoded data.
///
/// A copy of this data will be stored in the instance and is guaranteed
/// to be immutable for the lifetime of the instance, allowing it to
/// be retrieved later.
pub fn from_ber(data: impl Into<Vec<u8>>) -> Result<Self, Error> {
let data = data.into();
let inner = X509Certificate::from_ber(&data)?;
Ok(Self {
original: OriginalData::Ber(data),
inner,
})
}
/// Construct an instance by parsing PEM encoded ASN.1 data.
///
/// The data is a human readable string likely containing
/// `--------- BEGIN CERTIFICATE ----------`.
pub fn from_pem(data: impl AsRef<[u8]>) -> Result<Self, Error> {
let data = pem::parse(data.as_ref()).map_err(Error::PemDecode)?;
Self::from_der(data.contents)
}
/// Construct instances by parsing PEM with potentially multiple records.
///
/// By default, we only look for `--------- BEGIN CERTIFICATE --------`
/// entries and silently ignore unknown ones. If you would like to specify
/// an alternate set of tags (this is the value after the `BEGIN`) to search,
/// call [Self::from_pem_multiple_tags].
pub fn from_pem_multiple(data: impl AsRef<[u8]>) -> Result<Vec<Self>, Error> {
Self::from_pem_multiple_tags(data, &["CERTIFICATE"])
}
/// Construct instances by parsing PEM armored DER encoded certificates with specific PEM tags.
///
/// This is like [Self::from_pem_multiple] except you control the filter for
/// which `BEGIN <tag>` values are filtered through to the DER parser.
pub fn from_pem_multiple_tags(
data: impl AsRef<[u8]>,
tags: &[&str],
) -> Result<Vec<Self>, Error> {
let pem = pem::parse_many(data.as_ref()).map_err(Error::PemDecode)?;
pem.into_iter()
.filter(|pem| tags.contains(&pem.tag.as_str()))
.map(|pem| Self::from_der(pem.contents))
.collect::<Result<_, _>>()
}
/// Obtain the DER data that was used to construct this instance.
///
/// The data is guaranteed to not have been modified since the instance
/// was constructed.
pub fn constructed_data(&self) -> &[u8] {
match &self.original {
OriginalData::Ber(data) => data,
OriginalData::Der(data) => data,
}
}
/// Encode the original contents of this certificate to PEM.
pub fn encode_pem(&self) -> String {
pem::encode(&pem::Pem {
tag: "CERTIFICATE".to_string(),
contents: self.constructed_data().to_vec(),
})
}
/// Verify that another certificate, `other`, signed this certificate.
///
/// If this is a self-signed certificate, you can pass `self` as the 2nd
/// argument.
///
/// This function isn't exposed on [X509Certificate] because the exact
/// bytes constituting the certificate's internals need to be consulted
/// to verify signatures. And since this type tracks the underlying
/// bytes, we are guaranteed to have a pristine copy.
pub fn verify_signed_by_certificate(
&self,
other: impl AsRef<X509Certificate>,
) -> Result<(), Error> {
let public_key = other
.as_ref()
.0
.tbs_certificate
.subject_public_key_info
.subject_public_key
.octet_bytes();
self.verify_signed_by_public_key(public_key)
}
/// Verify a signature over signed data purportedly signed by this certificate.
///
/// This is a wrapper to [Self::verify_signed_data_with_algorithm()] that will derive
/// the verification algorithm from the public key type type and the signature algorithm
/// indicated in this certificate. Typically these align. However, it is possible for
/// a signature to be produced with a different digest algorithm from that indicated
/// in this certificate.
pub fn verify_signed_data(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
) -> Result<(), Error> {
let key_algorithm = KeyAlgorithm::try_from(self.key_algorithm_oid())?;
let signature_algorithm = SignatureAlgorithm::try_from(self.signature_algorithm_oid())?;
let verify_algorithm = signature_algorithm.resolve_verification_algorithm(key_algorithm)?;
self.verify_signed_data_with_algorithm(signed_data, signature, verify_algorithm)
}
/// Verify a signature over signed data using an explicit verification algorithm.
///
/// This is like [Self::verify_signed_data()] except the verification algorithm to use
/// is passed in instead of derived from the default algorithm for the signing key's
/// type.
pub fn verify_signed_data_with_algorithm(
&self,
signed_data: impl AsRef<[u8]>,
signature: impl AsRef<[u8]>,
verify_algorithm: &'static dyn ringsig::VerificationAlgorithm,
) -> Result<(), Error> {
let public_key = ringsig::UnparsedPublicKey::new(verify_algorithm, self.public_key_data());
public_key
.verify(signed_data.as_ref(), signature.as_ref())
.map_err(|_| Error::CertificateSignatureVerificationFailed)
}
sourcepub fn rsa_public_key_data(&self) -> Result<RsaPublicKey, Error>
pub fn rsa_public_key_data(&self) -> Result<RsaPublicKey, Error>
Attempt to parse the public key data as RsaPublicKey parameters.
Note that the raw integer value for modulus has a leading 0 byte. So its
raw length will be 1 greater than key length. e.g. an RSA 2048 key will
have value.modulus.as_slice().len() == 257
instead of 256
.
sourcepub fn compare_issuer(&self, other: &Self) -> Ordering
pub fn compare_issuer(&self, other: &Self) -> Ordering
Compare 2 instances, sorting them so the issuer comes before the issued.
This function examines the Self::issuer_name and Self::subject_name fields of 2 certificates, attempting to sort them so the issuing certificate comes before the issued certificate.
This function performs a strict compare of the ASN.1 Name data. The assumption here is that the issuing certificate’s subject Name is identical to the issued’s issuer Name. This assumption is often true. But it likely isn’t always true, so this function may not produce reliable results.
sourcepub fn subject_is_issuer(&self) -> bool
pub fn subject_is_issuer(&self) -> bool
sourcepub fn fingerprint(&self, algorithm: DigestAlgorithm) -> Result<Digest, Error>
pub fn fingerprint(&self, algorithm: DigestAlgorithm) -> Result<Digest, Error>
Obtain the fingerprint for this certificate given a digest algorithm.
sourcepub fn sha1_fingerprint(&self) -> Result<Digest, Error>
pub fn sha1_fingerprint(&self) -> Result<Digest, Error>
Obtain the SHA-1 fingerprint of this certificate.
sourcepub fn sha256_fingerprint(&self) -> Result<Digest, Error>
pub fn sha256_fingerprint(&self) -> Result<Digest, Error>
Obtain the SHA-256 fingerprint of this certificate.
Trait Implementations§
source§impl AsRef<Certificate> for CapturedX509Certificate
impl AsRef<Certificate> for CapturedX509Certificate
source§fn as_ref(&self) -> &Certificate
fn as_ref(&self) -> &Certificate
source§impl AsRef<X509Certificate> for CapturedX509Certificate
impl AsRef<X509Certificate> for CapturedX509Certificate
source§fn as_ref(&self) -> &X509Certificate
fn as_ref(&self) -> &X509Certificate
source§impl Clone for CapturedX509Certificate
impl Clone for CapturedX509Certificate
source§fn clone(&self) -> CapturedX509Certificate
fn clone(&self) -> CapturedX509Certificate
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more