1#![forbid(unsafe_code)]
29#![forbid(non_ascii_idents)]
30#![deny(missing_docs)]
31#![allow(clippy::complexity, clippy::style, clippy::pedantic)]
32
33use yasna::Tag;
34use yasna::models::ObjectIdentifier;
35#[cfg(feature = "pem")]
36use pem::Pem;
37use std::convert::TryInto;
38use ring::digest;
39use ring::signature::{EcdsaKeyPair, Ed25519KeyPair, RsaKeyPair, RsaEncoding};
40use ring::rand::SystemRandom;
41use ring::signature::KeyPair as RingKeyPair;
42use ring::signature::{self, EcdsaSigningAlgorithm, EdDSAParameters};
43use yasna::DERWriter;
44use yasna::models::{GeneralizedTime, UTCTime};
45use yasna::tags::{TAG_BMPSTRING, TAG_TELETEXSTRING, TAG_UNIVERSALSTRING};
46use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time};
47use std::collections::HashMap;
48use std::fmt;
49use std::convert::TryFrom;
50use std::error::Error;
51use std::net::IpAddr;
52use std::str::FromStr;
53use std::hash::{Hash, Hasher};
54
55pub struct Certificate {
57 params :CertificateParams,
58 key_pair :KeyPair,
59}
60
61
62pub fn generate_simple_self_signed(subject_alt_names :impl Into<Vec<String>>) -> Result<Certificate, RcgenError> {
87 Certificate::from_params(CertificateParams::new(subject_alt_names))
88}
89
90const OID_PKCS_9_AT_EXTENSION_REQUEST :&[u64] = &[1, 2, 840, 113549, 1, 9, 14];
97
98const OID_COUNTRY_NAME :&[u64] = &[2, 5, 4, 6];
100const OID_LOCALITY_NAME :&[u64] = &[2, 5, 4, 7];
102const OID_STATE_OR_PROVINCE_NAME :&[u64] = &[2, 5, 4, 8];
104const OID_ORG_NAME :&[u64] = &[2, 5, 4, 10];
106const OID_ORG_UNIT_NAME :&[u64] = &[2, 5, 4, 11];
108const OID_COMMON_NAME :&[u64] = &[2, 5, 4, 3];
110
111const OID_EC_PUBLIC_KEY :&[u64] = &[1, 2, 840, 10045, 2, 1];
113const OID_EC_SECP_256_R1 :&[u64] = &[1, 2, 840, 10045, 3, 1, 7];
114const OID_EC_SECP_384_R1 :&[u64] = &[1, 3, 132, 0, 34];
115
116const OID_RSA_ENCRYPTION :&[u64] = &[1, 2, 840, 113549, 1, 1, 1];
118
119const OID_RSASSA_PSS :&[u64] = &[1, 2, 840, 113549, 1, 1, 10];
121
122const OID_KEY_USAGE :&[u64] = &[2, 5, 29, 15];
124
125const OID_SUBJECT_ALT_NAME :&[u64] = &[2, 5, 29, 17];
128
129const OID_BASIC_CONSTRAINTS :&[u64] = &[2, 5, 29, 19];
131
132const OID_SUBJECT_KEY_IDENTIFIER :&[u64] = &[2, 5, 29, 14];
134
135const OID_AUTHORITY_KEY_IDENTIFIER :&[u64] = &[2, 5, 29, 35];
137
138const OID_EXT_KEY_USAGE :&[u64] = &[2, 5, 29, 37];
141
142const OID_NAME_CONSTRAINTS :&[u64] = &[2, 5, 29, 30];
145
146const OID_PE_ACME :&[u64] = &[1, 3, 6, 1, 5, 5, 7, 1, 31];
149
150#[derive(Debug, PartialEq, Eq, Hash, Clone)]
151#[allow(missing_docs)]
152#[non_exhaustive]
153pub enum SanType {
155 Rfc822Name(String),
157 DnsName(String),
158 URI(String),
159 IpAddress(IpAddr),
160}
161
162impl SanType {
163 #[cfg(feature = "x509-parser")]
164 fn try_from_general(name :&x509_parser::extensions::GeneralName<'_>) -> Result<Self, RcgenError> {
165 Ok(match name {
166 x509_parser::extensions::GeneralName::RFC822Name(name) => {
167 SanType::Rfc822Name((*name).into())
168 }
169 x509_parser::extensions::GeneralName::DNSName(name) => {
170 SanType::DnsName((*name).into())
171 }
172 x509_parser::extensions::GeneralName::URI(name) => {
173 SanType::URI((*name).into())
174 }
175 _ => return Err(RcgenError::InvalidNameType),
176 })
177 }
178
179 fn tag(&self) -> u64 {
180 const TAG_RFC822_NAME :u64 = 1;
183 const TAG_DNS_NAME :u64 = 2;
184 const TAG_URI :u64 = 6;
185 const TAG_IP_ADDRESS :u64 = 7;
186
187 match self {
188 SanType::Rfc822Name(_name) => TAG_RFC822_NAME,
189 SanType::DnsName(_name) => TAG_DNS_NAME,
190 SanType::URI(_name) => TAG_URI,
191 SanType::IpAddress(_addr) => TAG_IP_ADDRESS,
192 }
193 }
194}
195
196#[derive(Debug, PartialEq, Eq, Clone)]
197#[allow(missing_docs)]
198#[non_exhaustive]
199pub enum GeneralSubtree {
205 Rfc822Name(String),
207 DnsName(String),
208 DirectoryName(DistinguishedName),
209 IpAddress(CidrSubnet),
210}
211
212impl GeneralSubtree {
213 fn tag(&self) -> u64 {
214 const TAG_RFC822_NAME :u64 = 1;
217 const TAG_DNS_NAME :u64 = 2;
218 const TAG_DIRECTORY_NAME :u64 = 4;
219 const TAG_IP_ADDRESS :u64 = 7;
220
221 match self {
222 GeneralSubtree::Rfc822Name(_name) => TAG_RFC822_NAME,
223 GeneralSubtree::DnsName(_name) => TAG_DNS_NAME,
224 GeneralSubtree::DirectoryName(_name) => TAG_DIRECTORY_NAME,
225 GeneralSubtree::IpAddress(_addr) => TAG_IP_ADDRESS,
226 }
227 }
228}
229
230#[derive(Debug, PartialEq, Eq, Hash, Clone)]
231#[allow(missing_docs)]
232pub enum CidrSubnet {
241 V4([u8; 4], [u8; 4]),
242 V6([u8; 16], [u8; 16]),
243}
244
245macro_rules! mask {
246 ($t:ty, $d:expr) => {{
247 let v = <$t>::max_value();
248 let v = v.checked_shr($d as u32).unwrap_or(0);
249 (!v).to_be_bytes()
250 }};
251}
252
253impl CidrSubnet {
254 pub fn from_str(s :&str) -> Result<Self, ()> {
265 let mut iter = s.split('/');
266 if let (Some(addr_s), Some(prefix_s)) = (iter.next(), iter.next()) {
267 let addr = IpAddr::from_str(addr_s).map_err(|_| ())?;
268 let prefix = u8::from_str(prefix_s).map_err(|_| ())?;
269 Ok(Self::from_addr_prefix(addr, prefix))
270 } else {
271 Err(())
272 }
273 }
274 pub fn from_addr_prefix(addr :IpAddr, prefix :u8) -> Self {
288 match addr {
289 IpAddr::V4(addr) => {
290 Self::from_v4_prefix(addr.octets(), prefix)
291 },
292 IpAddr::V6(addr) => {
293 Self::from_v6_prefix(addr.octets(), prefix)
294 },
295 }
296 }
297 pub fn from_v4_prefix(addr :[u8; 4], prefix :u8) -> Self {
300 CidrSubnet::V4(addr, mask!(u32, prefix))
301 }
302 pub fn from_v6_prefix(addr :[u8; 16], prefix :u8) -> Self {
305 CidrSubnet::V6(addr, mask!(u128, prefix))
306 }
307 fn to_bytes(&self) -> Vec<u8> {
308 let mut res = Vec::new();
309 match self {
310 CidrSubnet::V4(addr, mask) => {
311 res.extend_from_slice(addr);
312 res.extend_from_slice(mask);
313 },
314 CidrSubnet::V6(addr, mask) => {
315 res.extend_from_slice(addr);
316 res.extend_from_slice(mask);
317 },
318 }
319 res
320 }
321}
322
323#[derive(Debug, PartialEq, Eq, Hash, Clone)]
324#[non_exhaustive]
325pub enum DnType {
327 CountryName,
329 LocalityName,
331 StateOrProvinceName,
333 OrganizationName,
335 OrganizationalUnitName,
337 CommonName,
339 CustomDnType(Vec<u64>),
341}
342
343impl DnType {
344 fn to_oid(&self) -> ObjectIdentifier {
345 let sl = match self {
346 DnType::CountryName => OID_COUNTRY_NAME,
347 DnType::LocalityName => OID_LOCALITY_NAME,
348 DnType::StateOrProvinceName => OID_STATE_OR_PROVINCE_NAME,
349 DnType::OrganizationName => OID_ORG_NAME,
350 DnType::OrganizationalUnitName => OID_ORG_UNIT_NAME,
351 DnType::CommonName => OID_COMMON_NAME,
352 DnType::CustomDnType(ref oid) => oid.as_slice(),
353 };
354 ObjectIdentifier::from_slice(sl)
355 }
356
357 pub fn from_oid(slice :&[u64]) -> Self {
359 match slice {
360 OID_COUNTRY_NAME => DnType::CountryName,
361 OID_LOCALITY_NAME => DnType::LocalityName,
362 OID_STATE_OR_PROVINCE_NAME => DnType::StateOrProvinceName,
363 OID_ORG_NAME => DnType::OrganizationName,
364 OID_ORG_UNIT_NAME => DnType::OrganizationalUnitName,
365 OID_COMMON_NAME => DnType::CommonName,
366 oid => DnType::CustomDnType(oid.into())
367 }
368 }
369}
370
371#[derive(Debug, PartialEq, Eq, Hash, Clone)]
373#[non_exhaustive]
374pub enum DnValue {
375 TeletexString(Vec<u8>),
377 PrintableString(String),
379 UniversalString(Vec<u8>),
381 Utf8String(String),
383 BmpString(Vec<u8>),
385}
386
387impl<T> From<T> for DnValue
388where
389 T :Into<String>
390{
391 fn from(t :T) -> Self {
392 DnValue::Utf8String(t.into())
393 }
394}
395
396#[derive(Debug, PartialEq, Eq, Clone)]
397pub struct DistinguishedName {
408 entries :HashMap<DnType, DnValue>,
409 order :Vec<DnType>,
410}
411
412impl DistinguishedName {
413 pub fn new() -> Self {
415 Self {
416 entries : HashMap::new(),
417 order : Vec::new(),
418 }
419 }
420 pub fn get(&self, ty :&DnType) -> Option<&DnValue> {
422 self.entries.get(ty)
423 }
424 pub fn remove(&mut self, ty :DnType) -> bool {
430 let removed = self.entries.remove(&ty).is_some();
431 if removed {
432 self.order.retain(|ty_o| &ty != ty_o);
433 }
434 removed
435 }
436 pub fn push(&mut self, ty :DnType, s :impl Into<DnValue>) {
447 if !self.entries.contains_key(&ty) {
448 self.order.push(ty.clone());
449 }
450 self.entries.insert(ty, s.into());
451 }
452 pub fn iter(&self) -> DistinguishedNameIterator<'_> {
454 DistinguishedNameIterator {
455 distinguished_name :self,
456 iter :self.order.iter()
457 }
458 }
459
460 #[cfg(feature = "x509-parser")]
461 fn from_name(name :&x509_parser::x509::X509Name) -> Result<Self, RcgenError> {
462 use x509_parser::der_parser::asn1_rs::Tag;
463
464 let mut dn = DistinguishedName::new();
465 for rdn in name.iter() {
466 let mut rdn_iter = rdn.iter();
467 let dn_opt = rdn_iter.next();
468 let attr = if let Some(dn) = dn_opt {
469 if rdn_iter.next().is_some() {
470 return Err(RcgenError::CouldNotParseCertificate);
472 } else {
473 dn
474 }
475 } else {
476 panic!("x509-parser distinguished name set is empty");
477 };
478
479 let attr_type_oid = attr.attr_type().iter()
480 .ok_or(RcgenError::CouldNotParseCertificate)?;
481 let dn_type = DnType::from_oid(&attr_type_oid.collect::<Vec<_>>());
482 let data = attr.attr_value().data;
483 let dn_value = match attr.attr_value().header.tag() {
484 Tag::T61String => DnValue::TeletexString(data.into()),
485 Tag::PrintableString => {
486 let data = std::str::from_utf8(data)
487 .map_err(|_| RcgenError::CouldNotParseCertificate)?;
488 DnValue::PrintableString(data.to_owned())
489 },
490 Tag::UniversalString => DnValue::UniversalString(data.into()),
491 Tag::Utf8String => {
492 let data = std::str::from_utf8(data)
493 .map_err(|_| RcgenError::CouldNotParseCertificate)?;
494 DnValue::Utf8String(data.to_owned())
495 },
496 Tag::BmpString => DnValue::BmpString(data.into()),
497 _ => return Err(RcgenError::CouldNotParseCertificate),
498 };
499
500 dn.push(dn_type, dn_value);
501 }
502 Ok(dn)
503 }
504}
505
506pub struct DistinguishedNameIterator<'a> {
510 distinguished_name :&'a DistinguishedName,
511 iter :std::slice::Iter<'a, DnType>,
512}
513
514impl <'a> Iterator for DistinguishedNameIterator<'a> {
515 type Item = (&'a DnType, &'a DnValue);
516
517 fn next(&mut self) -> Option<Self::Item> {
518 self.iter.next()
519 .and_then(|ty| {
520 self.distinguished_name.entries.get(ty).map(|v| (ty, v))
521 })
522 }
523}
524
525
526#[derive(Debug, PartialEq, Eq, Hash)]
528pub struct PublicKey {
529 raw: Vec<u8>,
530 alg: &'static SignatureAlgorithm,
531}
532
533impl PublicKeyData for PublicKey {
534 fn alg(&self) -> &SignatureAlgorithm {
535 self.alg
536 }
537
538 fn raw_bytes(&self) -> &[u8] {
539 &self.raw
540 }
541}
542
543#[allow(missing_docs)]
545pub struct CertificateSigningRequest {
546 pub params :CertificateParams,
547 pub public_key :PublicKey,
548}
549
550impl CertificateSigningRequest {
551 #[cfg(all(feature = "pem", feature = "x509-parser"))]
555 pub fn from_pem(pem_str :&str) -> Result<Self, RcgenError> {
556 let csr = pem::parse(pem_str)
557 .or(Err(RcgenError::CouldNotParseCertificationRequest))?;
558 Self::from_der(&csr.contents)
559 }
560
561 #[cfg(feature = "x509-parser")]
566 pub fn from_der(csr :&[u8]) -> Result<Self, RcgenError> {
567 use x509_parser::prelude::FromDer;
568 let csr = x509_parser::certification_request::X509CertificationRequest::from_der(csr)
569 .map_err(|_| RcgenError::CouldNotParseCertificationRequest)?.1;
570 csr.verify_signature().map_err(|_| RcgenError::RingUnspecified)?;
571 let alg_oid = csr.signature_algorithm.algorithm.iter()
572 .ok_or(RcgenError::CouldNotParseCertificationRequest)?
573 .collect::<Vec<_>>();
574 let alg = SignatureAlgorithm::from_oid(&alg_oid)?;
575
576 let info = &csr.certification_request_info;
577 let mut params = CertificateParams::default();
578 params.alg = alg;
579 params.distinguished_name = DistinguishedName::from_name(&info.subject)?;
580 let raw = info.subject_pki.subject_public_key.data.to_vec();
581
582 if let Some(extensions) = csr.requested_extensions() {
583 for ext in extensions {
584 match ext {
585 x509_parser::extensions::ParsedExtension::SubjectAlternativeName(san) => {
586 for name in &san.general_names {
587 params.subject_alt_names.push(SanType::try_from_general(name)?);
588 }
589 }
590 _ => return Err(RcgenError::UnsupportedExtension),
591 }
592 }
593 }
594
595 Ok(Self {
602 params,
603 public_key: PublicKey { alg, raw },
604 })
605 }
606 pub fn serialize_der_with_signer(&self, ca :&Certificate) -> Result<Vec<u8>, RcgenError> {
608 self.params.serialize_der_with_signer(&self.public_key, ca)
609 }
610 #[cfg(feature = "pem")]
614 pub fn serialize_pem_with_signer(&self, ca :&Certificate) -> Result<String, RcgenError> {
615 let p = Pem {
616 tag : "CERTIFICATE".to_string(),
617 contents : self.params.serialize_der_with_signer(&self.public_key, ca)?,
618 };
619 Ok(pem::encode(&p))
620 }
621}
622
623#[allow(missing_docs)]
625#[non_exhaustive]
626pub struct CertificateParams {
627 pub alg :&'static SignatureAlgorithm,
628 pub not_before :OffsetDateTime,
629 pub not_after :OffsetDateTime,
630 pub serial_number :Option<u64>,
631 pub subject_alt_names :Vec<SanType>,
632 pub distinguished_name :DistinguishedName,
633 pub is_ca :IsCa,
634 pub key_usages :Vec<KeyUsagePurpose>,
635 pub extended_key_usages :Vec<ExtendedKeyUsagePurpose>,
636 pub name_constraints :Option<NameConstraints>,
637 pub custom_extensions :Vec<CustomExtension>,
638 pub key_pair :Option<KeyPair>,
640 pub use_authority_key_identifier_extension :bool,
642 pub key_identifier_method :KeyIdMethod,
646}
647
648impl Default for CertificateParams {
649 fn default() -> Self {
650 let not_before = date_time_ymd(1975, 01, 01);
652 let not_after = date_time_ymd(4096, 01, 01);
653 let mut distinguished_name = DistinguishedName::new();
654 distinguished_name.push(DnType::CommonName, "rcgen self signed cert");
655 CertificateParams {
656 alg : &PKCS_ECDSA_P256_SHA256,
657 not_before,
658 not_after,
659 serial_number : None,
660 subject_alt_names : Vec::new(),
661 distinguished_name,
662 is_ca : IsCa::NoCa,
663 key_usages : Vec::new(),
664 extended_key_usages : Vec::new(),
665 name_constraints : None,
666 custom_extensions : Vec::new(),
667 key_pair : None,
668 use_authority_key_identifier_extension : false,
669 key_identifier_method : KeyIdMethod::Sha256,
670 }
671 }
672}
673
674impl CertificateParams {
675 #[cfg(all(feature = "pem", feature = "x509-parser"))]
681 pub fn from_ca_cert_pem(pem_str :&str, key_pair :KeyPair) -> Result<Self, RcgenError> {
682 let certificate = pem::parse(pem_str)
683 .or(Err(RcgenError::CouldNotParseCertificate))?;
684 Self::from_ca_cert_der(&certificate.contents, key_pair)
685 }
686
687 #[cfg(feature = "x509-parser")]
703 pub fn from_ca_cert_der(ca_cert :&[u8], key_pair :KeyPair) -> Result<Self, RcgenError> {
704 let (_remainder, x509) = x509_parser::parse_x509_certificate(ca_cert)
705 .or(Err(RcgenError::CouldNotParseCertificate))?;
706
707 let alg_oid = x509.signature_algorithm.algorithm.iter()
708 .ok_or(RcgenError::CouldNotParseCertificate)?;
709 let alg = SignatureAlgorithm::from_oid(&alg_oid.collect::<Vec<_>>())?;
710
711 let dn = DistinguishedName::from_name(&x509.tbs_certificate.subject)?;
712 Ok(
713 CertificateParams {
714 alg,
715 distinguished_name : dn,
716 key_pair : Some(key_pair),
717 .. Default::default()
718 }
719 )
720 }
721 fn write_subject_alt_names(&self, writer :DERWriter) {
722 Self::write_extension(writer, OID_SUBJECT_ALT_NAME, false, |writer| {
723 writer.write_sequence(|writer| {
724 for san in self.subject_alt_names.iter() {
725 writer.next().write_tagged_implicit(Tag::context(san.tag()), |writer| {
726 match san {
727 SanType::Rfc822Name(name) |
728 SanType::DnsName(name) |
729 SanType::URI(name) => writer.write_ia5_string(name),
730 SanType::IpAddress(IpAddr::V4(addr)) => writer.write_bytes(&addr.octets()),
731 SanType::IpAddress(IpAddr::V6(addr)) => writer.write_bytes(&addr.octets()),
732 }
733 });
734 }
735 });
736 });
737 }
738 fn write_request<K: PublicKeyData>(&self, pub_key: &K, writer :DERWriter) {
739 writer.write_sequence(|writer| {
740 writer.next().write_u8(0);
742 writer.next().write_sequence(|writer| {
744 for (ty, content) in self.distinguished_name.iter() {
745 writer.next().write_set(|writer| {
746 writer.next().write_sequence(|writer| {
747 writer.next().write_oid(&ty.to_oid());
748 match content {
749 DnValue::TeletexString(s) => writer.next().write_tagged_implicit(TAG_TELETEXSTRING, |writer| {
750 writer.write_bytes(s)
751 }),
752 DnValue::PrintableString(s) => writer.next().write_printable_string(s),
753 DnValue::UniversalString(s) => writer.next().write_tagged_implicit(TAG_UNIVERSALSTRING, |writer| {
754 writer.write_bytes(s)
755 }),
756 DnValue::Utf8String(s) => writer.next().write_utf8_string(s),
757 DnValue::BmpString(s) => writer.next().write_tagged_implicit(TAG_BMPSTRING, |writer| {
758 writer.write_bytes(s)
759 }),
760 }
761 });
762 });
763 }
764 });
765 pub_key.serialize_public_key_der(writer.next());
767 writer.next().write_tagged(Tag::context(0), |writer| {
770 if !self.subject_alt_names.is_empty() {
771 writer.write_sequence(|writer| {
772 let oid = ObjectIdentifier::from_slice(OID_PKCS_9_AT_EXTENSION_REQUEST);
773 writer.next().write_oid(&oid);
774 writer.next().write_set(|writer| {
775 writer.next().write_sequence(|writer| {
776 self.write_subject_alt_names(writer.next());
778 });
779 });
780 });
781 }
782 });
783
784 });
785 }
786 fn write_cert<K: PublicKeyData>(&self, writer :DERWriter, pub_key: &K, ca :&Certificate) -> Result<(), RcgenError> {
787 writer.write_sequence(|writer| {
788 writer.next().write_tagged(Tag::context(0), |writer| {
790 writer.write_u8(2);
791 });
792 let serial = self.serial_number.unwrap_or_else(|| {
794 let hash = digest::digest(&digest::SHA256, pub_key.raw_bytes());
795 let bytes: [u8; 8] = hash.as_ref()[0..8].try_into().unwrap();
796 u64::from_le_bytes(bytes)
797 });
798 writer.next().write_u64(serial);
799 ca.params.alg.write_alg_ident(writer.next());
801 write_distinguished_name(writer.next(), &ca.params.distinguished_name);
803 writer.next().write_sequence(|writer| {
805 write_dt_utc_or_generalized(writer.next(), self.not_before);
807 write_dt_utc_or_generalized(writer.next(), self.not_after);
809 Ok::<(), RcgenError>(())
810 })?;
811 write_distinguished_name(writer.next(), &self.distinguished_name);
813 pub_key.serialize_public_key_der(writer.next());
815 let not_self_signed = ca.key_pair.public_key_raw() != pub_key.raw_bytes();
817 let should_write_exts = (not_self_signed && self.use_authority_key_identifier_extension) ||
818 !self.subject_alt_names.is_empty() ||
819 !self.extended_key_usages.is_empty() ||
820 self.name_constraints.iter().any(|c| !c.is_empty()) ||
821 matches!(self.is_ca, IsCa::ExplicitNoCa) ||
822 matches!(self.is_ca, IsCa::Ca(_)) ||
823 !self.custom_extensions.is_empty();
824 if should_write_exts {
825 writer.next().write_tagged(Tag::context(3), |writer| {
826 writer.write_sequence(|writer| {
827 if not_self_signed && self.use_authority_key_identifier_extension {
828 Self::write_extension(writer.next(), OID_AUTHORITY_KEY_IDENTIFIER, false, |writer| {
836 writer.write_sequence(|writer| {
837 writer.next().write_tagged_implicit(Tag::context(0), |writer| {
838 writer.write_bytes(ca.get_key_identifier().as_ref())
839 })
840 });
841 });
842 }
843 if !self.subject_alt_names.is_empty() {
845 self.write_subject_alt_names(writer.next());
846 }
847
848 if !self.key_usages.is_empty() {
850 writer.next().write_sequence(|writer| {
851
852 let oid = ObjectIdentifier::from_slice(OID_KEY_USAGE);
853 writer.next().write_oid(&oid);
854 writer.next().write_bool(true);
855
856 let mut bits :u16 = 0;
857
858 for entry in self.key_usages.iter() {
859 let index = match entry {
861 KeyUsagePurpose::DigitalSignature => 0,
862 KeyUsagePurpose::ContentCommitment => 1,
863 KeyUsagePurpose::KeyEncipherment => 2,
864 KeyUsagePurpose::DataEncipherment => 3,
865 KeyUsagePurpose::KeyAgreement => 4,
866 KeyUsagePurpose::KeyCertSign => 5,
867 KeyUsagePurpose::CrlSign => 6,
868 KeyUsagePurpose::EncipherOnly => 7,
869 KeyUsagePurpose::DecipherOnly => 8,
870 };
871
872 bits |= 1 << index;
873 }
874
875 let msb = 16 - bits.leading_zeros();
877 let nb = if msb <= 8 {
878 1
879 } else {
880 2
881 };
882
883 let bits = bits.reverse_bits().to_be_bytes();
884
885 let bits = &bits[..nb];
887
888 let der = yasna::construct_der(|writer| {
889 writer.write_bitvec_bytes(&bits, msb as usize)
890 });
891
892 writer.next().write_bytes(&der);
894
895 });
896 }
897
898 if !self.extended_key_usages.is_empty() {
900 Self::write_extension(writer.next(), OID_EXT_KEY_USAGE, false, |writer| {
901 writer.write_sequence(|writer| {
902 for usage in self.extended_key_usages.iter() {
903 let oid = ObjectIdentifier::from_slice(usage.oid());
904 writer.next().write_oid(&oid);
905 }
906 });
907 });
908 }
909 if let Some(name_constraints) = &self.name_constraints {
910 if !name_constraints.is_empty() {
912 Self::write_extension(writer.next(), OID_NAME_CONSTRAINTS, true, |writer| {
913 writer.write_sequence(|writer| {
914 if !name_constraints.permitted_subtrees.is_empty() {
915 write_general_subtrees(writer.next(), 0, &name_constraints.permitted_subtrees);
916 }
917 if !name_constraints.excluded_subtrees.is_empty() {
918 write_general_subtrees(writer.next(), 1, &name_constraints.excluded_subtrees);
919 }
920 });
921 });
922 }
923 }
924 match self.is_ca {
925 IsCa::Ca(ref constraint) => {
926 Self::write_extension(writer.next(), OID_SUBJECT_KEY_IDENTIFIER, false, |writer| {
928 let key_identifier = self.key_identifier(pub_key);
929 writer.write_bytes(key_identifier.as_ref());
930 });
931 Self::write_extension(writer.next(), OID_BASIC_CONSTRAINTS, true, |writer| {
933 writer.write_sequence(|writer| {
934 writer.next().write_bool(true); if let BasicConstraints::Constrained(path_len_constraint) = constraint {
936 writer.next().write_u8(*path_len_constraint);
937 }
938 });
939 });
940 }
941 IsCa::ExplicitNoCa => {
942 Self::write_extension(writer.next(), OID_SUBJECT_KEY_IDENTIFIER, false, |writer| {
944 let key_identifier = self.key_identifier(pub_key);
945 writer.write_bytes(key_identifier.as_ref());
946 });
947 Self::write_extension(writer.next(), OID_BASIC_CONSTRAINTS, true, |writer| {
949 writer.write_sequence(|writer| {
950 writer.next().write_bool(false); });
952 });
953 }
954 IsCa::NoCa => {}
955 }
956
957 for ext in &self.custom_extensions {
959 writer.next().write_sequence(|writer| {
960 let oid = ObjectIdentifier::from_slice(&ext.oid);
961 writer.next().write_oid(&oid);
962 if ext.critical {
966 writer.next().write_bool(true);
967 }
968 writer.next().write_bytes(&ext.content);
969 });
970 }
971 });
972 });
973 }
974 Ok(())
975 })
976 }
977 fn write_extension(writer :DERWriter, extension_oid :&[u64], is_critical :bool, value_serializer :impl FnOnce(DERWriter)) {
979 writer.write_sequence(|writer| {
990 let oid = ObjectIdentifier::from_slice(extension_oid);
991 writer.next().write_oid(&oid);
992 if is_critical {
993 writer.next().write_bool(true);
994 }
995 let bytes = yasna::construct_der(value_serializer);
996 writer.next().write_bytes(&bytes);
997 })
998 }
999 fn key_identifier<K: PublicKeyData>(&self, pub_key: &K) -> Vec<u8> {
1002 let digest_method = match self.key_identifier_method {
1004 KeyIdMethod::Sha256 => &digest::SHA256,
1005 KeyIdMethod::Sha384 => &digest::SHA384,
1006 KeyIdMethod::Sha512 => &digest::SHA512,
1007 };
1008 let digest = digest::digest(digest_method, pub_key.raw_bytes());
1009 let truncated_digest = &digest.as_ref()[0..20];
1010 truncated_digest.to_vec()
1011 }
1012 fn serialize_der_with_signer<K: PublicKeyData>(&self, pub_key: &K, ca :&Certificate) -> Result<Vec<u8>, RcgenError> {
1013 yasna::try_construct_der(|writer| {
1014 writer.write_sequence(|writer| {
1015
1016 let tbs_cert_list_serialized = yasna::try_construct_der(|writer| {
1017 self.write_cert(writer, pub_key, ca)?;
1018 Ok::<(), RcgenError>(())
1019 })?;
1020 writer.next().write_der(&tbs_cert_list_serialized);
1022
1023 ca.params.alg.write_alg_ident(writer.next());
1025
1026 ca.key_pair.sign(&tbs_cert_list_serialized, writer.next())?;
1028
1029 Ok(())
1030 })
1031 })
1032 }
1033}
1034
1035#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1037pub enum IsCa {
1038 NoCa,
1040 ExplicitNoCa,
1042 Ca(BasicConstraints),
1044}
1045
1046#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1051pub enum BasicConstraints {
1052 Unconstrained,
1054 Constrained(u8),
1056}
1057
1058impl CertificateParams {
1059 pub fn new(subject_alt_names :impl Into<Vec<String>>) -> Self {
1061 let subject_alt_names = subject_alt_names.into()
1062 .into_iter()
1063 .map(|s| SanType::DnsName(s))
1064 .collect::<Vec<_>>();
1065 CertificateParams {
1066 subject_alt_names,
1067 .. Default::default()
1068 }
1069 }
1070}
1071
1072#[derive(Debug, PartialEq, Eq, Clone)]
1075pub struct NameConstraints {
1076 pub permitted_subtrees :Vec<GeneralSubtree>,
1079 pub excluded_subtrees :Vec<GeneralSubtree>,
1084}
1085
1086impl NameConstraints {
1087 fn is_empty(&self) -> bool {
1088 self.permitted_subtrees.is_empty() && self.excluded_subtrees.is_empty()
1089 }
1090}
1091
1092#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1094pub enum KeyUsagePurpose {
1095 DigitalSignature,
1097 ContentCommitment,
1099 KeyEncipherment,
1101 DataEncipherment,
1103 KeyAgreement,
1105 KeyCertSign,
1107 CrlSign,
1109 EncipherOnly,
1111 DecipherOnly,
1113}
1114
1115#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1116pub enum ExtendedKeyUsagePurpose {
1118 Any,
1120 ServerAuth,
1122 ClientAuth,
1124 CodeSigning,
1126 EmailProtection,
1128 TimeStamping,
1130 OcspSigning,
1132}
1133
1134impl ExtendedKeyUsagePurpose {
1135 fn oid(&self) -> &'static [u64] {
1136 use ExtendedKeyUsagePurpose::*;
1137 match self {
1138 Any => &[2, 5, 29, 37],
1140 ServerAuth => &[1, 3, 6, 1, 5, 5, 7, 3, 1],
1142 ClientAuth => &[1, 3, 6, 1, 5, 5, 7, 3, 2],
1143 CodeSigning => &[1, 3, 6, 1, 5, 5, 7, 3, 3],
1144 EmailProtection => &[1, 3, 6, 1, 5, 5, 7, 3, 4],
1145 TimeStamping => &[1, 3, 6, 1, 5, 5, 7, 3, 8],
1146 OcspSigning => &[1, 3, 6, 1, 5, 5, 7, 3, 9],
1147 }
1148 }
1149}
1150
1151#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1154pub struct CustomExtension {
1155 oid :Vec<u64>,
1156 critical :bool,
1157
1158 content :Vec<u8>,
1160}
1161
1162impl CustomExtension {
1163 pub fn new_acme_identifier(sha_digest :&[u8]) -> Self {
1168 assert_eq!(sha_digest.len(), 32, "wrong size of sha_digest");
1169 let content = yasna::construct_der(|writer| {
1170 writer.write_bytes(sha_digest);
1171 });
1172 Self {
1173 oid : OID_PE_ACME.to_owned(),
1174 critical : true,
1175 content,
1176 }
1177 }
1178 pub fn from_oid_content(oid :&[u64], content :Vec<u8>) -> Self {
1180 Self {
1181 oid : oid.to_owned(),
1182 critical : false,
1183 content,
1184 }
1185 }
1186 pub fn set_criticality(&mut self, criticality :bool) {
1188 self.critical = criticality;
1189 }
1190 pub fn criticality(&self) -> bool {
1192 self.critical
1193 }
1194 pub fn content(&self) -> &[u8] {
1196 &self.content
1197 }
1198 pub fn oid_components(&self) -> impl Iterator<Item = u64> + '_ {
1200 self.oid.iter().copied()
1201 }
1202}
1203
1204#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1209#[non_exhaustive]
1210pub enum KeyIdMethod {
1211 Sha256,
1213 Sha384,
1215 Sha512,
1217}
1218
1219pub fn date_time_ymd(year :i32, month :u8, day :u8) -> OffsetDateTime {
1228 let month = Month::try_from(month).expect("out-of-range month");
1229 let primitive_dt = PrimitiveDateTime::new(
1230 Date::from_calendar_date(year, month, day).expect("invalid or out-of-range date"),
1231 Time::MIDNIGHT
1232 );
1233 primitive_dt.assume_utc()
1234}
1235
1236fn dt_strip_nanos(dt :OffsetDateTime) -> OffsetDateTime {
1237 let time = Time::from_hms(dt.hour(), dt.minute(), dt.second())
1245 .expect("invalid or out-of-range time");
1246 dt.replace_time(time)
1247}
1248
1249fn dt_to_generalized(dt :OffsetDateTime) -> GeneralizedTime {
1250 let date_time = dt_strip_nanos(dt);
1251 GeneralizedTime::from_datetime(date_time)
1252}
1253
1254fn write_dt_utc_or_generalized(writer :DERWriter, dt :OffsetDateTime) {
1255 if (1950..2050).contains(&dt.year()) {
1262 let date_time = dt_strip_nanos(dt);
1263 let ut = UTCTime::from_datetime(date_time);
1264 writer.write_utctime(&ut);
1265 } else {
1266 let gt = dt_to_generalized(dt);
1267 writer.write_generalized_time(>);
1268 }
1269}
1270
1271fn write_distinguished_name(writer :DERWriter, dn :&DistinguishedName) {
1272 writer.write_sequence(|writer| {
1273 for (ty, content) in dn.iter() {
1274 writer.next().write_set(|writer| {
1275 writer.next().write_sequence(|writer| {
1276 writer.next().write_oid(&ty.to_oid());
1277 match content {
1278 DnValue::TeletexString(s) => writer.next().write_tagged_implicit(TAG_TELETEXSTRING, |writer| {
1279 writer.write_bytes(s)
1280 }),
1281 DnValue::PrintableString(s) => writer.next().write_printable_string(s),
1282 DnValue::UniversalString(s) => writer.next().write_tagged_implicit(TAG_UNIVERSALSTRING, |writer| {
1283 writer.write_bytes(s)
1284 }),
1285 DnValue::Utf8String(s) => writer.next().write_utf8_string(s),
1286 DnValue::BmpString(s) => writer.next().write_tagged_implicit(TAG_BMPSTRING, |writer| {
1287 writer.write_bytes(s)
1288 }),
1289 }
1290 });
1291 });
1292 }
1293 });
1294}
1295
1296fn write_general_subtrees(writer :DERWriter, tag :u64, general_subtrees :&[GeneralSubtree]) {
1297 writer.write_tagged_implicit(Tag::context(tag), |writer| {
1298 writer.write_sequence(|writer| {
1299 for subtree in general_subtrees.iter() {
1300 writer.next().write_sequence(|writer| {
1301 writer.next().write_tagged_implicit(Tag::context(subtree.tag()), |writer| {
1302 match subtree {
1303 GeneralSubtree::Rfc822Name(name) |
1304 GeneralSubtree::DnsName(name) => writer.write_ia5_string(name),
1305 GeneralSubtree::DirectoryName(name) => write_distinguished_name(writer, name),
1306 GeneralSubtree::IpAddress(subnet) => writer.write_bytes(&subnet.to_bytes()),
1307 }
1308 });
1309 });
1311 }
1312 });
1313 });
1314}
1315
1316impl Certificate {
1317 pub fn from_params(mut params :CertificateParams) -> Result<Self, RcgenError> {
1319 let key_pair = if let Some(key_pair) = params.key_pair.take() {
1320 if !key_pair.is_compatible(¶ms.alg) {
1321 return Err(RcgenError::CertificateKeyPairMismatch);
1322 }
1323 key_pair
1324 } else {
1325 KeyPair::generate(¶ms.alg)?
1326 };
1327
1328 Ok(Certificate {
1329 params,
1330 key_pair,
1331 })
1332 }
1333 pub fn get_key_identifier(&self) -> Vec<u8> {
1336 self.params.key_identifier(&self.key_pair)
1337 }
1338 pub fn serialize_der(&self) -> Result<Vec<u8>, RcgenError> {
1340 self.serialize_der_with_signer(&self)
1341 }
1342 pub fn serialize_der_with_signer(&self, ca :&Certificate) -> Result<Vec<u8>, RcgenError> {
1344 self.params.serialize_der_with_signer(&self.key_pair, ca)
1345 }
1346 pub fn serialize_request_der(&self) -> Result<Vec<u8>, RcgenError> {
1348 yasna::try_construct_der(|writer| {
1349 writer.write_sequence(|writer| {
1350 let cert_data = yasna::construct_der(|writer| {
1351 self.params.write_request(&self.key_pair, writer);
1352 });
1353 writer.next().write_der(&cert_data);
1354
1355 self.params.alg.write_alg_ident(writer.next());
1357
1358 self.key_pair.sign(&cert_data, writer.next())?;
1360
1361 Ok(())
1362 })
1363 })
1364 }
1365 pub fn get_key_pair(&self) -> &KeyPair {
1367 &self.key_pair
1368 }
1369 #[cfg(feature = "pem")]
1373 pub fn serialize_pem(&self) -> Result<String, RcgenError> {
1374 let p = Pem {
1375 tag : "CERTIFICATE".to_string(),
1376 contents : self.serialize_der()?,
1377 };
1378 Ok(pem::encode(&p))
1379 }
1380 #[cfg(feature = "pem")]
1384 pub fn serialize_pem_with_signer(&self, ca :&Certificate) -> Result<String, RcgenError> {
1385 let p = Pem {
1386 tag : "CERTIFICATE".to_string(),
1387 contents : self.serialize_der_with_signer(ca)?,
1388 };
1389 Ok(pem::encode(&p))
1390 }
1391 #[cfg(feature = "pem")]
1395 pub fn serialize_request_pem(&self) -> Result<String, RcgenError> {
1396 let p = Pem {
1397 tag : "CERTIFICATE REQUEST".to_string(),
1398 contents : self.serialize_request_der()?,
1399 };
1400 Ok(pem::encode(&p))
1401 }
1402 pub fn serialize_private_key_der(&self) -> Vec<u8> {
1406 self.key_pair.serialize_der()
1407 }
1408 #[cfg(feature = "pem")]
1414 pub fn serialize_private_key_pem(&self) -> String {
1415 self.key_pair.serialize_pem()
1416 }
1417}
1418
1419enum SignAlgo {
1420 EcDsa(&'static EcdsaSigningAlgorithm),
1421 EdDsa(&'static EdDSAParameters),
1422 Rsa(),
1423}
1424
1425#[allow(clippy::large_enum_variant)]
1427enum KeyPairKind {
1428 Ec(EcdsaKeyPair),
1430 Ed(Ed25519KeyPair),
1432 Rsa(RsaKeyPair, &'static dyn RsaEncoding),
1434 Remote(Box<dyn RemoteKeyPair + Send + Sync>),
1436}
1437
1438impl fmt::Debug for KeyPairKind {
1439 fn fmt(&self, f :&mut fmt::Formatter) -> fmt::Result {
1440 match self {
1441 Self::Ec(key_pair) => write!(f, "{:?}", key_pair),
1442 Self::Ed(key_pair) => write!(f, "{:?}", key_pair),
1443 Self::Rsa(key_pair, _) => write!(f, "{:?}", key_pair),
1444 Self::Remote(_) => write!(f, "Box<dyn RemotePrivateKey>"),
1445 }
1446 }
1447}
1448
1449#[derive(Debug)]
1457pub struct KeyPair {
1458 kind :KeyPairKind,
1459 alg :&'static SignatureAlgorithm,
1460 serialized_der :Vec<u8>,
1461}
1462
1463impl KeyPair {
1464 pub fn from_der(der :&[u8]) -> Result<Self, RcgenError> {
1468 Ok(der.try_into()?)
1469 }
1470 #[cfg(feature = "pem")]
1474 pub fn from_pem(pem_str :&str) -> Result<Self, RcgenError> {
1475 let private_key = pem::parse(pem_str)?;
1476 let private_key_der :&[_] = &private_key.contents;
1477 Ok(private_key_der.try_into()?)
1478 }
1479
1480 pub fn from_remote(key_pair :Box<dyn RemoteKeyPair + Send + Sync>) -> Result<Self, RcgenError> {
1482 Ok(Self {
1483 alg : key_pair.algorithm(),
1484 kind : KeyPairKind::Remote(key_pair),
1485 serialized_der : Vec::new(),
1486 })
1487 }
1488
1489
1490 #[cfg(feature = "pem")]
1497 pub fn from_pem_and_sign_algo(pem_str :&str, alg :&'static SignatureAlgorithm) -> Result<Self, RcgenError> {
1498 let private_key = pem::parse(pem_str)?;
1499 let private_key_der :&[_] = &private_key.contents;
1500 Ok(Self::from_der_and_sign_algo(private_key_der, alg)?)
1501 }
1502
1503 pub fn from_der_and_sign_algo(pkcs8 :&[u8], alg :&'static SignatureAlgorithm) -> Result<Self, RcgenError> {
1513 let pkcs8_vec = pkcs8.to_vec();
1514
1515 let kind = if alg == &PKCS_ED25519 {
1516 KeyPairKind::Ed(Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8)?)
1517 } else if alg == &PKCS_ECDSA_P256_SHA256 {
1518 KeyPairKind::Ec(EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8)?)
1519 } else if alg == &PKCS_ECDSA_P384_SHA384 {
1520 KeyPairKind::Ec(EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P384_SHA384_ASN1_SIGNING, pkcs8)?)
1521 } else if alg == &PKCS_RSA_SHA256 {
1522 let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
1523 KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA256)
1524 } else if alg == &PKCS_RSA_SHA384 {
1525 let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
1526 KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA384)
1527 } else if alg == &PKCS_RSA_SHA512 {
1528 let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
1529 KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA512)
1530 } else if alg == &PKCS_RSA_PSS_SHA256 {
1531 let rsakp = RsaKeyPair::from_pkcs8(pkcs8)?;
1532 KeyPairKind::Rsa(rsakp, &signature::RSA_PSS_SHA256)
1533 } else {
1534 panic!("Unknown SignatureAlgorithm specified!");
1535 };
1536
1537 Ok(KeyPair {
1538 kind,
1539 alg,
1540 serialized_der : pkcs8_vec,
1541 })
1542 }
1543
1544 fn from_raw(pkcs8: &[u8]) -> Result<(KeyPairKind, &'static SignatureAlgorithm), RcgenError> {
1545 let (kind, alg) = if let Ok(edkp) = Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8) {
1546 (KeyPairKind::Ed(edkp), &PKCS_ED25519)
1547 } else if let Ok(eckp) = EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8) {
1548 (KeyPairKind::Ec(eckp), &PKCS_ECDSA_P256_SHA256)
1549 } else if let Ok(eckp) = EcdsaKeyPair::from_pkcs8(&signature::ECDSA_P384_SHA384_ASN1_SIGNING, pkcs8) {
1550 (KeyPairKind::Ec(eckp), &PKCS_ECDSA_P384_SHA384)
1551 } else if let Ok(rsakp) = RsaKeyPair::from_pkcs8(pkcs8) {
1552 (KeyPairKind::Rsa(rsakp, &signature::RSA_PKCS1_SHA256), &PKCS_RSA_SHA256)
1553 } else {
1554 return Err(RcgenError::CouldNotParseKeyPair);
1555 };
1556 Ok((kind, alg))
1557 }
1558}
1559
1560pub trait RemoteKeyPair {
1565 fn public_key(&self) -> &[u8];
1567
1568 fn sign(&self, msg :&[u8]) -> Result<Vec<u8>, RcgenError>;
1570
1571 fn algorithm(&self) -> &'static SignatureAlgorithm;
1573}
1574
1575#[derive(Debug, PartialEq, Eq)]
1576#[non_exhaustive]
1577pub enum RcgenError {
1579 CouldNotParseCertificate,
1581 CouldNotParseCertificationRequest,
1583 CouldNotParseKeyPair,
1585 #[cfg(feature = "x509-parser")]
1586 InvalidNameType,
1588 KeyGenerationUnavailable,
1591 #[cfg(feature = "x509-parser")]
1592 UnsupportedExtension,
1594 UnsupportedSignatureAlgorithm,
1596 RingUnspecified,
1598 RingKeyRejected(&'static str),
1600 CertificateKeyPairMismatch,
1603 Time,
1605 #[cfg(feature = "pem")]
1606 PemError(pem::PemError),
1610 RemoteKeyError,
1612}
1613
1614impl fmt::Display for RcgenError {
1615 fn fmt(&self, f :&mut fmt::Formatter) -> fmt::Result {
1616 use self::RcgenError::*;
1617 match self {
1618 CouldNotParseCertificate => write!(f, "Could not parse certificate")?,
1619 CouldNotParseCertificationRequest => write!(f, "Could not parse certificate signing \
1620 request")?,
1621 CouldNotParseKeyPair => write!(f, "Could not parse key pair")?,
1622 #[cfg(feature = "x509-parser")]
1623 InvalidNameType => write!(f, "Invalid subject alternative name type")?,
1624 KeyGenerationUnavailable => write!(f, "There is no support for generating \
1625 keys for the given algorithm")?,
1626 UnsupportedSignatureAlgorithm => write!(f, "The requested signature algorithm \
1627 is not supported")?,
1628 #[cfg(feature = "x509-parser")]
1629 UnsupportedExtension => write!(f, "Unsupported extension requested in CSR")?,
1630 RingUnspecified => write!(f, "Unspecified ring error")?,
1631 RingKeyRejected(e) => write!(f, "Key rejected by ring: {}", e)?,
1632 CertificateKeyPairMismatch => write!(f, "The provided certificate's signature \
1633 algorithm is incompatible with the given key pair")?,
1634
1635 Time => write!(f, "Time error")?,
1636 RemoteKeyError => write!(f, "Remote key error")?,
1637 #[cfg(feature = "pem")]
1638 PemError(e) => write!(f, "PEM error: {}", e)?,
1639 };
1640 Ok(())
1641 }
1642}
1643
1644impl Error for RcgenError {}
1645
1646impl From<ring::error::Unspecified> for RcgenError {
1647 fn from(_unspecified :ring::error::Unspecified) -> Self {
1648 RcgenError::RingUnspecified
1649 }
1650}
1651
1652impl From<ring::error::KeyRejected> for RcgenError {
1653 fn from(err :ring::error::KeyRejected) -> Self {
1654 RcgenError::RingKeyRejected(err.description_())
1655 }
1656}
1657
1658#[cfg(feature = "pem")]
1659impl From<pem::PemError> for RcgenError {
1660 fn from(e :pem::PemError) -> Self {
1661 RcgenError::PemError(e)
1662 }
1663}
1664
1665impl TryFrom<&[u8]> for KeyPair {
1666 type Error = RcgenError;
1667
1668 fn try_from(pkcs8: &[u8]) -> Result<KeyPair, RcgenError> {
1669 let (kind, alg) = KeyPair::from_raw(pkcs8)?;
1670 Ok(KeyPair {
1671 kind,
1672 alg,
1673 serialized_der: pkcs8.to_vec(),
1674 })
1675 }
1676}
1677
1678impl TryFrom<Vec<u8>> for KeyPair {
1679 type Error = RcgenError;
1680
1681 fn try_from(pkcs8: Vec<u8>) -> Result<KeyPair, RcgenError> {
1682 let (kind, alg) = KeyPair::from_raw(pkcs8.as_slice())?;
1683 Ok(KeyPair {
1684 kind,
1685 alg,
1686 serialized_der: pkcs8,
1687 })
1688 }
1689}
1690
1691impl KeyPair {
1692 pub fn generate(alg :&'static SignatureAlgorithm) -> Result<Self, RcgenError> {
1694 let system_random = SystemRandom::new();
1695 match alg.sign_alg {
1696 SignAlgo::EcDsa(sign_alg) => {
1697 let key_pair_doc = EcdsaKeyPair::generate_pkcs8(sign_alg, &system_random)?;
1698 let key_pair_serialized = key_pair_doc.as_ref().to_vec();
1699
1700 let key_pair = EcdsaKeyPair::from_pkcs8(&sign_alg, &&key_pair_doc.as_ref()).unwrap();
1701 Ok(KeyPair {
1702 kind : KeyPairKind::Ec(key_pair),
1703 alg,
1704 serialized_der : key_pair_serialized,
1705 })
1706 },
1707 SignAlgo::EdDsa(_sign_alg) => {
1708 let key_pair_doc = Ed25519KeyPair::generate_pkcs8(&system_random)?;
1709 let key_pair_serialized = key_pair_doc.as_ref().to_vec();
1710
1711 let key_pair = Ed25519KeyPair::from_pkcs8(&&key_pair_doc.as_ref()).unwrap();
1712 Ok(KeyPair {
1713 kind : KeyPairKind::Ed(key_pair),
1714 alg,
1715 serialized_der : key_pair_serialized,
1716 })
1717 },
1718 SignAlgo::Rsa() => Err(RcgenError::KeyGenerationUnavailable),
1722 }
1723 }
1724 pub fn public_key_raw(&self) -> &[u8] {
1730 self.raw_bytes()
1731 }
1732 pub fn is_compatible(&self, signature_algorithm :&SignatureAlgorithm) -> bool {
1734 self.alg == signature_algorithm
1735 }
1736 pub fn compatible_algs(&self)
1739 -> impl Iterator<Item=&'static SignatureAlgorithm> {
1740 std::iter::once(self.alg)
1741 }
1742 fn sign(&self, msg :&[u8], writer :DERWriter) -> Result<(), RcgenError> {
1743 match &self.kind {
1744 KeyPairKind::Ec(kp) => {
1745 let system_random = SystemRandom::new();
1746 let signature = kp.sign(&system_random, msg)?;
1747 let sig = &signature.as_ref();
1748 writer.write_bitvec_bytes(&sig, &sig.len() * 8);
1749 },
1750 KeyPairKind::Ed(kp) => {
1751 let signature = kp.sign(msg);
1752 let sig = &signature.as_ref();
1753 writer.write_bitvec_bytes(&sig, &sig.len() * 8);
1754 },
1755 KeyPairKind::Rsa(kp, padding_alg) => {
1756 let system_random = SystemRandom::new();
1757 let mut signature = vec![0; kp.public_modulus_len()];
1758 kp.sign(*padding_alg, &system_random,
1759 msg, &mut signature)?;
1760 let sig = &signature.as_ref();
1761 writer.write_bitvec_bytes(&sig, &sig.len() * 8);
1762 },
1763 KeyPairKind::Remote(kp) => {
1764 let signature = kp.sign(msg)?;
1765 writer.write_bitvec_bytes(&signature, &signature.len() * 8);
1766 },
1767 }
1768 Ok(())
1769 }
1770 pub fn public_key_der(&self) -> Vec<u8> {
1776 yasna::construct_der(|writer| self.serialize_public_key_der(writer))
1777 }
1778 #[cfg(feature = "pem")]
1784 pub fn public_key_pem(&self) -> String {
1785 let p = Pem {
1786 tag : "PUBLIC KEY".to_string(),
1787 contents : self.public_key_der(),
1788 };
1789 pem::encode(&p)
1790 }
1791 pub fn serialize_der(&self) -> Vec<u8> {
1795 if let KeyPairKind::Remote(_) = self.kind {
1796 panic!("Serializing a remote key pair is not supported")
1797 }
1798
1799 self.serialized_der.clone()
1800 }
1801
1802 pub fn serialized_der(&self) -> &[u8] {
1807 if let KeyPairKind::Remote(_) = self.kind {
1808 panic!("Serializing a remote key pair is not supported")
1809 }
1810
1811 &self.serialized_der
1812 }
1813
1814 #[cfg(feature = "pem")]
1818 pub fn serialize_pem(&self) -> String {
1819 let p = Pem {
1820 tag : "PRIVATE KEY".to_string(),
1821 contents : self.serialize_der(),
1822 };
1823 pem::encode(&p)
1824 }
1825}
1826
1827impl PublicKeyData for KeyPair {
1828 fn alg(&self) -> &SignatureAlgorithm {
1829 self.alg
1830 }
1831 fn raw_bytes(&self) -> &[u8] {
1832 match &self.kind {
1833 KeyPairKind::Ec(kp) => kp.public_key().as_ref(),
1834 KeyPairKind::Ed(kp) => kp.public_key().as_ref(),
1835 KeyPairKind::Rsa(kp, _) => kp.public_key().as_ref(),
1836 KeyPairKind::Remote(kp) => kp.public_key(),
1837 }
1838 }
1839}
1840
1841trait PublicKeyData {
1842 fn alg(&self) -> &SignatureAlgorithm;
1843 fn raw_bytes(&self) -> &[u8];
1844 fn serialize_public_key_der(&self, writer :DERWriter) {
1845 writer.write_sequence(|writer| {
1846 self.alg().write_oids_sign_alg(writer.next());
1847 let pk = self.raw_bytes();
1848 writer.next().write_bitvec_bytes(&pk, pk.len() * 8);
1849 })
1850 }
1851}
1852
1853#[derive(PartialEq, Eq)]
1854enum SignatureAlgorithmParams {
1855 None,
1857 Null,
1859 RsaPss {
1861 hash_algorithm :&'static [u64],
1862 salt_length :u64,
1863 },
1864}
1865
1866pub struct SignatureAlgorithm {
1868 oids_sign_alg :&'static [&'static [u64]],
1869 sign_alg :SignAlgo,
1870 oid_components :&'static [u64],
1871 params :SignatureAlgorithmParams,
1872}
1873
1874impl fmt::Debug for SignatureAlgorithm {
1875 fn fmt(&self, f :&mut fmt::Formatter) -> fmt::Result {
1876 if self == &PKCS_RSA_SHA256 {
1877 write!(f, "PKCS_RSA_SHA256")
1878 } else if self == &PKCS_RSA_SHA384 {
1879 write!(f, "PKCS_RSA_SHA384")
1880 } else if self == &PKCS_RSA_SHA512 {
1881 write!(f, "PKCS_RSA_SHA512")
1882 } else if self == &PKCS_RSA_PSS_SHA256 {
1883 write!(f, "PKCS_RSA_PSS_SHA256")
1884 } else if self == &PKCS_ECDSA_P256_SHA256 {
1885 write!(f, "PKCS_ECDSA_P256_SHA256")
1886 } else if self == &PKCS_ECDSA_P384_SHA384 {
1887 write!(f, "PKCS_ECDSA_P384_SHA384")
1888 } else if self == &PKCS_ED25519 {
1889 write!(f, "PKCS_ED25519")
1890 } else {
1891 write!(f, "Unknown")
1892 }
1893 }
1894}
1895
1896impl PartialEq for SignatureAlgorithm {
1897 fn eq(&self, other :&Self) -> bool {
1898 (self.oids_sign_alg, self.oid_components) == (other.oids_sign_alg, other.oid_components)
1899 }
1900}
1901
1902impl Eq for SignatureAlgorithm {}
1903
1904impl Hash for SignatureAlgorithm {
1906 fn hash<H: Hasher>(&self, state: &mut H) {
1907 self.oids_sign_alg.hash(state);
1909 }
1910}
1911
1912impl SignatureAlgorithm {
1913 fn iter() -> std::slice::Iter<'static, &'static SignatureAlgorithm> {
1914 static ALGORITHMS :&[&SignatureAlgorithm] = &[
1915 &PKCS_RSA_SHA256,
1916 &PKCS_RSA_SHA384,
1917 &PKCS_RSA_SHA512,
1918 &PKCS_ECDSA_P256_SHA256,
1920 &PKCS_ECDSA_P384_SHA384,
1921 &PKCS_ED25519
1922 ];
1923 ALGORITHMS.iter()
1924 }
1925
1926 pub fn from_oid(oid :&[u64]) -> Result<&'static SignatureAlgorithm, RcgenError> {
1928 for algo in Self::iter() {
1929 if algo.oid_components == oid {
1930 return Ok(algo);
1931 }
1932 }
1933 Err(RcgenError::UnsupportedSignatureAlgorithm)
1934 }
1935}
1936
1937
1938pub static PKCS_RSA_SHA256 :SignatureAlgorithm = SignatureAlgorithm {
1940 oids_sign_alg :&[&OID_RSA_ENCRYPTION],
1941 sign_alg :SignAlgo::Rsa(),
1942 oid_components : &[1, 2, 840, 113549, 1, 1, 11],
1944 params : SignatureAlgorithmParams::Null,
1945};
1946
1947pub static PKCS_RSA_SHA384 :SignatureAlgorithm = SignatureAlgorithm {
1949 oids_sign_alg :&[&OID_RSA_ENCRYPTION],
1950 sign_alg :SignAlgo::Rsa(),
1951 oid_components : &[1, 2, 840, 113549, 1, 1, 12],
1953 params : SignatureAlgorithmParams::Null,
1954};
1955
1956pub static PKCS_RSA_SHA512 :SignatureAlgorithm = SignatureAlgorithm {
1958 oids_sign_alg :&[&OID_RSA_ENCRYPTION],
1959 sign_alg :SignAlgo::Rsa(),
1960 oid_components : &[1, 2, 840, 113549, 1, 1, 13],
1962 params : SignatureAlgorithmParams::Null,
1963};
1964
1965static PKCS_RSA_PSS_SHA256 :SignatureAlgorithm = SignatureAlgorithm {
1972 oids_sign_alg :&[&OID_RSASSA_PSS],
1975 sign_alg :SignAlgo::Rsa(),
1976 oid_components : &OID_RSASSA_PSS,params : SignatureAlgorithmParams::RsaPss {
1979 hash_algorithm : &[2, 16, 840, 1, 101, 3, 4, 2, 1],
1981 salt_length : 20,
1982 },
1983};
1984
1985pub static PKCS_ECDSA_P256_SHA256 :SignatureAlgorithm = SignatureAlgorithm {
1987 oids_sign_alg :&[&OID_EC_PUBLIC_KEY, &OID_EC_SECP_256_R1],
1988 sign_alg :SignAlgo::EcDsa(&signature::ECDSA_P256_SHA256_ASN1_SIGNING),
1989 oid_components : &[1, 2, 840, 10045, 4, 3, 2],
1991 params : SignatureAlgorithmParams::None,
1992};
1993
1994pub static PKCS_ECDSA_P384_SHA384 :SignatureAlgorithm = SignatureAlgorithm {
1996 oids_sign_alg :&[&OID_EC_PUBLIC_KEY, &OID_EC_SECP_384_R1],
1997 sign_alg :SignAlgo::EcDsa(&signature::ECDSA_P384_SHA384_ASN1_SIGNING),
1998 oid_components : &[1, 2, 840, 10045, 4, 3, 3],
2000 params : SignatureAlgorithmParams::None,
2001};
2002
2003pub static PKCS_ED25519 :SignatureAlgorithm = SignatureAlgorithm {
2007 oids_sign_alg :&[&[1, 3, 101, 112]],
2009 sign_alg :SignAlgo::EdDsa(&signature::ED25519),
2010 oid_components : &[1, 3, 101, 112],
2012 params : SignatureAlgorithmParams::None,
2013};
2014
2015impl SignatureAlgorithm {
2017 fn alg_ident_oid(&self) -> ObjectIdentifier {
2018 ObjectIdentifier::from_slice(self.oid_components)
2019 }
2020 fn write_params(&self, writer :&mut yasna::DERWriterSeq) {
2021 match self.params {
2022 SignatureAlgorithmParams::None => (),
2023 SignatureAlgorithmParams::Null => {
2024 writer.next().write_null();
2025 },
2026 SignatureAlgorithmParams::RsaPss {
2027 hash_algorithm, salt_length,
2028 } => {
2029 writer.next().write_sequence(|writer| {
2030 let oid = ObjectIdentifier::from_slice(hash_algorithm);
2033 writer.next().write_tagged(Tag::context(0), |writer| {
2035 writer.write_sequence(|writer| {
2036 writer.next().write_oid(&oid);
2037 });
2038 });
2039 writer.next().write_tagged(Tag::context(1), |writer| {
2041 writer.write_sequence(|writer| {
2042 const ID_MGF1 :&[u64] = &[1, 2, 840, 113549, 1, 1, 8];
2044 let oid = ObjectIdentifier::from_slice(ID_MGF1);
2045 writer.next().write_oid(&oid);
2046 writer.next().write_sequence(|writer| {
2047 let oid = ObjectIdentifier::from_slice(hash_algorithm);
2048 writer.next().write_oid(&oid);
2049 writer.next().write_null();
2050 });
2051 });
2052 });
2053 writer.next().write_tagged(Tag::context(2), |writer| {
2055 writer.write_u64(salt_length);
2056 });
2057 })
2059 },
2060 }
2061 }
2062 fn write_alg_ident(&self, writer :DERWriter) {
2064 writer.write_sequence(|writer| {
2065 writer.next().write_oid(&self.alg_ident_oid());
2066 self.write_params(writer);
2067 });
2068 }
2069 fn write_oids_sign_alg(&self, writer :DERWriter) {
2071 writer.write_sequence(|writer| {
2072 for oid in self.oids_sign_alg {
2073 let oid = ObjectIdentifier::from_slice(oid);
2074 writer.next().write_oid(&oid);
2075 }
2076 self.write_params(writer);
2077 });
2078 }
2079}
2080
2081#[cfg(feature = "zeroize")]
2082impl zeroize::Zeroize for KeyPair {
2083 fn zeroize(&mut self) {
2084 self.serialized_der.zeroize();
2085 }
2086}
2087
2088#[cfg(feature = "zeroize")]
2089impl zeroize::Zeroize for Certificate {
2090 fn zeroize(&mut self) {
2091 self.params.zeroize();
2092 self.key_pair.zeroize();
2093 }
2094}
2095
2096#[cfg(feature = "zeroize")]
2097impl zeroize::Zeroize for CertificateSigningRequest {
2098 fn zeroize(&mut self) {
2099 self.params.zeroize();
2100 }
2101}
2102
2103#[cfg(feature = "zeroize")]
2104impl zeroize::Zeroize for CertificateParams {
2105 fn zeroize(&mut self) {
2106 self.key_pair.zeroize();
2107 }
2108}
2109
2110#[cfg(test)]
2111mod tests {
2112 use super::*;
2113
2114 use std::panic::catch_unwind;
2115
2116 fn get_times() -> [OffsetDateTime; 2] {
2117 let dt_nanos = {
2118 let date = Date::from_calendar_date(2020, Month::December, 3).unwrap();
2119 let time = Time::from_hms_nano(0, 0, 1, 444).unwrap();
2120 PrimitiveDateTime::new(date, time).assume_utc()
2121 };
2122 let dt_zero = {
2123 let date = Date::from_calendar_date(2020, Month::December, 3).unwrap();
2124 let time = Time::from_hms_nano(0, 0, 1, 0).unwrap();
2125 PrimitiveDateTime::new(date, time).assume_utc()
2126 };
2127 [dt_nanos, dt_zero]
2129 }
2130
2131 #[test]
2132 fn test_dt_utc_strip_nanos() {
2133 let times = get_times();
2134
2135 let res = catch_unwind(|| UTCTime::from_datetime(times[0]));
2137 assert!(res.is_err());
2138
2139 for dt in times {
2141 let date_time = dt_strip_nanos(dt);
2142 assert_eq!(date_time.time().nanosecond(), 0);
2143 let _ut = UTCTime::from_datetime(date_time);
2144 }
2145 }
2146
2147 #[test]
2148 fn test_dt_to_generalized() {
2149 let times = get_times();
2150
2151 for dt in times {
2152 let _gt = dt_to_generalized(dt);
2153 }
2154 }
2155
2156 #[test]
2157 fn test_with_key_usages() {
2158 let mut params: CertificateParams = Default::default();
2159
2160 params.key_usages = vec![
2162 KeyUsagePurpose::DigitalSignature,
2163 KeyUsagePurpose::KeyEncipherment,
2164 KeyUsagePurpose::ContentCommitment,
2165 ];
2166
2167 params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
2169
2170 let cert = Certificate::from_params(params).unwrap();
2172
2173 let der = cert.serialize_der().unwrap();
2175
2176 let (_rem, cert) = x509_parser::parse_x509_certificate(&der).unwrap();
2178
2179 let key_usage_oid_str= "2.5.29.15";
2181
2182 let mut found = false;
2184
2185 for ext in cert.extensions() {
2186 if key_usage_oid_str == ext.oid.to_id_string() {
2187 match ext.parsed_extension() {
2188 x509_parser::extensions::ParsedExtension::KeyUsage(usage) =>{
2189 assert!(usage.flags == 7);
2190 found = true;
2191 }
2192 _ => {}
2193 }
2194 }
2195 }
2196
2197 assert!(found);
2198 }
2199
2200 #[test]
2201 fn test_with_key_usages_decipheronly_only() {
2202 let mut params: CertificateParams = Default::default();
2203
2204 params.key_usages = vec![KeyUsagePurpose::DecipherOnly];
2206
2207 params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
2209
2210 let cert = Certificate::from_params(params).unwrap();
2212
2213 let der = cert.serialize_der().unwrap();
2215
2216 let (_rem, cert) = x509_parser::parse_x509_certificate(&der).unwrap();
2218
2219 let key_usage_oid_str= "2.5.29.15";
2221
2222 let mut found = false;
2224
2225 for ext in cert.extensions() {
2226 if key_usage_oid_str == ext.oid.to_id_string() {
2227 match ext.parsed_extension() {
2228 x509_parser::extensions::ParsedExtension::KeyUsage(usage) =>{
2229 assert!(usage.flags == 256);
2230 found = true;
2231 }
2232 _ => {}
2233 }
2234 }
2235 }
2236
2237 assert!(found);
2238 }
2239
2240 #[test]
2241 fn signature_algos_different() {
2242 for (i, alg_i) in SignatureAlgorithm::iter().enumerate() {
2246 for (j, alg_j) in SignatureAlgorithm::iter().enumerate() {
2247 assert_eq!(alg_i == alg_j, i == j,
2248 "Algorighm relationship mismatch for algorithm index pair {} and {}", i, j);
2249 }
2250 }
2251 }
2252}