Skip to content

Commit

Permalink
Rename Error type
Browse files Browse the repository at this point in the history
  • Loading branch information
thomaseizinger authored and est31 committed Oct 3, 2023
1 parent 471943b commit ae5deed
Show file tree
Hide file tree
Showing 9 changed files with 111 additions and 111 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@

# Changes

## Unreleased

- Rename `RcGenError` to `Error` to avoid stuttering when used fully-qualified via `rcgen::`.

## Release 0.11.3 - October 1, 2023

- Fix for import errors building without the optional `pem` feature.
Expand Down
20 changes: 9 additions & 11 deletions src/crl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ use crate::{
write_distinguished_name, write_dt_utc_or_generalized, write_x509_authority_key_identifier,
write_x509_extension,
};
use crate::{
Certificate, KeyIdMethod, KeyUsagePurpose, RcgenError, SerialNumber, SignatureAlgorithm,
};
use crate::{Certificate, Error, KeyIdMethod, KeyUsagePurpose, SerialNumber, SignatureAlgorithm};

/// A certificate revocation list (CRL)
///
Expand Down Expand Up @@ -54,9 +52,9 @@ pub struct CertificateRevocationList {

impl CertificateRevocationList {
/// Generates a new certificate revocation list (CRL) from the given parameters.
pub fn from_params(params: CertificateRevocationListParams) -> Result<Self, RcgenError> {
pub fn from_params(params: CertificateRevocationListParams) -> Result<Self, Error> {
if params.next_update.le(&params.this_update) {
return Err(RcgenError::InvalidCrlNextUpdate);
return Err(Error::InvalidCrlNextUpdate);
}
Ok(Self { params })
}
Expand All @@ -66,18 +64,18 @@ impl CertificateRevocationList {
}
/// Serializes the certificate revocation list (CRL) in binary DER format, signed with
/// the issuing certificate authority's key.
pub fn serialize_der_with_signer(&self, ca: &Certificate) -> Result<Vec<u8>, RcgenError> {
pub fn serialize_der_with_signer(&self, ca: &Certificate) -> Result<Vec<u8>, Error> {
if !ca.params.key_usages.is_empty()
&& !ca.params.key_usages.contains(&KeyUsagePurpose::CrlSign)
{
return Err(RcgenError::IssuerNotCrlSigner);
return Err(Error::IssuerNotCrlSigner);
}
self.params.serialize_der_with_signer(ca)
}
/// Serializes the certificate revocation list (CRL) in ASCII PEM format, signed with
/// the issuing certificate authority's key.
#[cfg(feature = "pem")]
pub fn serialize_pem_with_signer(&self, ca: &Certificate) -> Result<String, RcgenError> {
pub fn serialize_pem_with_signer(&self, ca: &Certificate) -> Result<String, Error> {
let contents = self.serialize_der_with_signer(ca)?;
let p = Pem::new("X509 CRL", contents);
Ok(pem::encode_config(&p, ENCODE_CONFIG))
Expand Down Expand Up @@ -174,13 +172,13 @@ pub struct CertificateRevocationListParams {
}

impl CertificateRevocationListParams {
fn serialize_der_with_signer(&self, ca: &Certificate) -> Result<Vec<u8>, RcgenError> {
fn serialize_der_with_signer(&self, ca: &Certificate) -> Result<Vec<u8>, Error> {
yasna::try_construct_der(|writer| {
// https://www.rfc-editor.org/rfc/rfc5280#section-5.1
writer.write_sequence(|writer| {
let tbs_cert_list_serialized = yasna::try_construct_der(|writer| {
self.write_crl(writer, ca)?;
Ok::<(), RcgenError>(())
Ok::<(), Error>(())
})?;

// Write tbsCertList
Expand All @@ -196,7 +194,7 @@ impl CertificateRevocationListParams {
})
})
}
fn write_crl(&self, writer: DERWriter, ca: &Certificate) -> Result<(), RcgenError> {
fn write_crl(&self, writer: DERWriter, ca: &Certificate) -> Result<(), Error> {
writer.write_sequence(|writer| {
// Write CRL version.
// RFC 5280 §5.1.2.1:
Expand Down
21 changes: 10 additions & 11 deletions src/csr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::{DistinguishedName, SanType};
use pem::Pem;
use std::hash::Hash;

use crate::{Certificate, CertificateParams, PublicKeyData, RcgenError, SignatureAlgorithm};
use crate::{Certificate, CertificateParams, Error, PublicKeyData, SignatureAlgorithm};

/// A public key, extracted from a CSR
#[derive(Debug, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -36,8 +36,8 @@ impl CertificateSigningRequest {
///
/// See [`from_der`](Self::from_der) for more details.
#[cfg(all(feature = "pem", feature = "x509-parser"))]
pub fn from_pem(pem_str: &str) -> Result<Self, RcgenError> {
let csr = pem::parse(pem_str).or(Err(RcgenError::CouldNotParseCertificationRequest))?;
pub fn from_pem(pem_str: &str) -> Result<Self, Error> {
let csr = pem::parse(pem_str).or(Err(Error::CouldNotParseCertificationRequest))?;
Self::from_der(csr.contents())
}

Expand All @@ -46,18 +46,17 @@ impl CertificateSigningRequest {
/// Currently, this only supports the `Subject Alternative Name` extension.
/// On encountering other extensions, this function will return an error.
#[cfg(feature = "x509-parser")]
pub fn from_der(csr: &[u8]) -> Result<Self, RcgenError> {
pub fn from_der(csr: &[u8]) -> Result<Self, Error> {
use x509_parser::prelude::FromDer;
let csr = x509_parser::certification_request::X509CertificationRequest::from_der(csr)
.map_err(|_| RcgenError::CouldNotParseCertificationRequest)?
.map_err(|_| Error::CouldNotParseCertificationRequest)?
.1;
csr.verify_signature()
.map_err(|_| RcgenError::RingUnspecified)?;
csr.verify_signature().map_err(|_| Error::RingUnspecified)?;
let alg_oid = csr
.signature_algorithm
.algorithm
.iter()
.ok_or(RcgenError::CouldNotParseCertificationRequest)?
.ok_or(Error::CouldNotParseCertificationRequest)?
.collect::<Vec<_>>();
let alg = SignatureAlgorithm::from_oid(&alg_oid)?;

Expand All @@ -77,7 +76,7 @@ impl CertificateSigningRequest {
.push(SanType::try_from_general(name)?);
}
},
_ => return Err(RcgenError::UnsupportedExtension),
_ => return Err(Error::UnsupportedExtension),
}
}
}
Expand All @@ -94,12 +93,12 @@ impl CertificateSigningRequest {
})
}
/// Serializes the requested certificate, signed with another certificate's key, in binary DER format
pub fn serialize_der_with_signer(&self, ca: &Certificate) -> Result<Vec<u8>, RcgenError> {
pub fn serialize_der_with_signer(&self, ca: &Certificate) -> Result<Vec<u8>, Error> {
self.params.serialize_der_with_signer(&self.public_key, ca)
}
/// Serializes the requested certificate, signed with another certificate's key, to the ASCII PEM format
#[cfg(feature = "pem")]
pub fn serialize_pem_with_signer(&self, ca: &Certificate) -> Result<String, RcgenError> {
pub fn serialize_pem_with_signer(&self, ca: &Certificate) -> Result<String, Error> {
let contents = self
.params
.serialize_der_with_signer(&self.public_key, ca)?;
Expand Down
21 changes: 10 additions & 11 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use std::error::Error;
use std::fmt;

#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
/// The error type of the rcgen crate
pub enum RcgenError {
pub enum Error {
/// The given certificate couldn't be parsed
CouldNotParseCertificate,
/// The given certificate signing request couldn't be parsed
Expand Down Expand Up @@ -46,9 +45,9 @@ pub enum RcgenError {
IssuerNotCrlSigner,
}

impl fmt::Display for RcgenError {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::RcgenError::*;
use self::Error::*;
match self {
CouldNotParseCertificate => write!(f, "Could not parse certificate")?,
CouldNotParseCertificationRequest => write!(
Expand Down Expand Up @@ -97,23 +96,23 @@ impl fmt::Display for RcgenError {
}
}

impl Error for RcgenError {}
impl std::error::Error for Error {}

impl From<ring::error::Unspecified> for RcgenError {
impl From<ring::error::Unspecified> for Error {
fn from(_unspecified: ring::error::Unspecified) -> Self {
RcgenError::RingUnspecified
Error::RingUnspecified
}
}

impl From<ring::error::KeyRejected> for RcgenError {
impl From<ring::error::KeyRejected> for Error {
fn from(err: ring::error::KeyRejected) -> Self {
RcgenError::RingKeyRejected(err.description_())
Error::RingKeyRejected(err.description_())
}
}

#[cfg(feature = "pem")]
impl From<pem::PemError> for RcgenError {
impl From<pem::PemError> for Error {
fn from(e: pem::PemError) -> Self {
RcgenError::PemError(e)
Error::PemError(e)
}
}
32 changes: 16 additions & 16 deletions src/key_pair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::sign_algo::algo::*;
use crate::sign_algo::SignAlgo;
#[cfg(feature = "pem")]
use crate::ENCODE_CONFIG;
use crate::{RcgenError, SignatureAlgorithm};
use crate::{Error, SignatureAlgorithm};

/// A key pair vairant
#[allow(clippy::large_enum_variant)]
Expand Down Expand Up @@ -55,7 +55,7 @@ impl KeyPair {
/// Parses the key pair from the DER format
///
/// Equivalent to using the [`TryFrom`] implementation.
pub fn from_der(der: &[u8]) -> Result<Self, RcgenError> {
pub fn from_der(der: &[u8]) -> Result<Self, Error> {
Ok(der.try_into()?)
}
/// Returns the key pair's signature algorithm
Expand All @@ -64,14 +64,14 @@ impl KeyPair {
}
/// Parses the key pair from the ASCII PEM format
#[cfg(feature = "pem")]
pub fn from_pem(pem_str: &str) -> Result<Self, RcgenError> {
pub fn from_pem(pem_str: &str) -> Result<Self, Error> {
let private_key = pem::parse(pem_str)?;
let private_key_der: &[_] = private_key.contents();
Ok(private_key_der.try_into()?)
}

/// Obtains the key pair from a raw public key and a remote private key
pub fn from_remote(key_pair: Box<dyn RemoteKeyPair + Send + Sync>) -> Result<Self, RcgenError> {
pub fn from_remote(key_pair: Box<dyn RemoteKeyPair + Send + Sync>) -> Result<Self, Error> {
Ok(Self {
alg: key_pair.algorithm(),
kind: KeyPairKind::Remote(key_pair),
Expand All @@ -87,7 +87,7 @@ impl KeyPair {
pub fn from_pem_and_sign_algo(
pem_str: &str,
alg: &'static SignatureAlgorithm,
) -> Result<Self, RcgenError> {
) -> Result<Self, Error> {
let private_key = pem::parse(pem_str)?;
let private_key_der: &[_] = private_key.contents();
Ok(Self::from_der_and_sign_algo(private_key_der, alg)?)
Expand All @@ -105,7 +105,7 @@ impl KeyPair {
pub fn from_der_and_sign_algo(
pkcs8: &[u8],
alg: &'static SignatureAlgorithm,
) -> Result<Self, RcgenError> {
) -> Result<Self, Error> {
let pkcs8_vec = pkcs8.to_vec();

let kind = if alg == &PKCS_ED25519 {
Expand Down Expand Up @@ -145,7 +145,7 @@ impl KeyPair {

pub(crate) fn from_raw(
pkcs8: &[u8],
) -> Result<(KeyPairKind, &'static SignatureAlgorithm), RcgenError> {
) -> Result<(KeyPairKind, &'static SignatureAlgorithm), Error> {
let (kind, alg) = if let Ok(edkp) = Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8) {
(KeyPairKind::Ed(edkp), &PKCS_ED25519)
} else if let Ok(eckp) =
Expand All @@ -162,7 +162,7 @@ impl KeyPair {
&PKCS_RSA_SHA256,
)
} else {
return Err(RcgenError::CouldNotParseKeyPair);
return Err(Error::CouldNotParseKeyPair);
};
Ok((kind, alg))
}
Expand All @@ -177,16 +177,16 @@ pub trait RemoteKeyPair {
fn public_key(&self) -> &[u8];

/// Signs `msg` using the selected algorithm
fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, RcgenError>;
fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, Error>;

/// Reveals the algorithm to be used when calling `sign()`
fn algorithm(&self) -> &'static SignatureAlgorithm;
}

impl TryFrom<&[u8]> for KeyPair {
type Error = RcgenError;
type Error = Error;

fn try_from(pkcs8: &[u8]) -> Result<KeyPair, RcgenError> {
fn try_from(pkcs8: &[u8]) -> Result<KeyPair, Error> {
let (kind, alg) = KeyPair::from_raw(pkcs8)?;
Ok(KeyPair {
kind,
Expand All @@ -197,9 +197,9 @@ impl TryFrom<&[u8]> for KeyPair {
}

impl TryFrom<Vec<u8>> for KeyPair {
type Error = RcgenError;
type Error = Error;

fn try_from(pkcs8: Vec<u8>) -> Result<KeyPair, RcgenError> {
fn try_from(pkcs8: Vec<u8>) -> Result<KeyPair, Error> {
let (kind, alg) = KeyPair::from_raw(pkcs8.as_slice())?;
Ok(KeyPair {
kind,
Expand All @@ -211,7 +211,7 @@ impl TryFrom<Vec<u8>> for KeyPair {

impl KeyPair {
/// Generate a new random key pair for the specified signature algorithm
pub fn generate(alg: &'static SignatureAlgorithm) -> Result<Self, RcgenError> {
pub fn generate(alg: &'static SignatureAlgorithm) -> Result<Self, Error> {
let system_random = SystemRandom::new();
match alg.sign_alg {
SignAlgo::EcDsa(sign_alg) => {
Expand Down Expand Up @@ -240,7 +240,7 @@ impl KeyPair {
// Ring doesn't have RSA key generation yet:
// https://github.com/briansmith/ring/issues/219
// https://github.com/briansmith/ring/pull/733
SignAlgo::Rsa() => Err(RcgenError::KeyGenerationUnavailable),
SignAlgo::Rsa() => Err(Error::KeyGenerationUnavailable),
}
}
/// Get the raw public key of this key pair
Expand All @@ -260,7 +260,7 @@ impl KeyPair {
pub fn compatible_algs(&self) -> impl Iterator<Item = &'static SignatureAlgorithm> {
std::iter::once(self.alg)
}
pub(crate) fn sign(&self, msg: &[u8], writer: DERWriter) -> Result<(), RcgenError> {
pub(crate) fn sign(&self, msg: &[u8], writer: DERWriter) -> Result<(), Error> {
match &self.kind {
KeyPairKind::Ec(kp) => {
let system_random = SystemRandom::new();
Expand Down
Loading

0 comments on commit ae5deed

Please sign in to comment.