Skip to content

Commit

Permalink
chore: Move SigningAlg into c2pa-crypto (#682)
Browse files Browse the repository at this point in the history
  • Loading branch information
scouten-adobe authored Nov 16, 2024
1 parent 756a3a9 commit fffdd64
Show file tree
Hide file tree
Showing 35 changed files with 136 additions and 93 deletions.
5 changes: 5 additions & 0 deletions internal/crypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ exclude = ["tests/fixtures"]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]

[features]
json_schema = ["dep:schemars"]

[dependencies]
base64 = "0.22.1"
bcder = "0.7.3"
Expand All @@ -33,6 +36,8 @@ hex = "0.4.3"
rasn = "0.18.0"
rasn-ocsp = "0.18.0"
rasn-pkix = "0.18.0"
schemars = { version = "0.8.21", optional = true }
serde = { version = "1.0.197", features = ["derive"] }
sha1 = "0.10.6"
thiserror = "1.0.61"
x509-certificate = "0.21.0"
Expand Down
3 changes: 3 additions & 0 deletions internal/crypto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,8 @@ pub(crate) mod internal;
pub mod ocsp;
pub mod validation_codes;

mod signing_alg;
pub use signing_alg::{SigningAlg, UnknownAlgorithmError};

#[cfg(test)]
pub(crate) mod tests;
55 changes: 7 additions & 48 deletions sdk/src/signing_alg.rs → internal/crypto/src/signing_alg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
// specific language governing permissions and limitations under
// each license.

#![deny(missing_docs)]

use std::{fmt, str::FromStr};

#[cfg(feature = "json_schema")]
Expand All @@ -21,11 +19,13 @@ use serde::{Deserialize, Serialize};

/// Describes the digital signature algorithms allowed by the C2PA spec.
///
/// Per <https://c2pa.org/specifications/specifications/1.0/specs/C2PA_Specification.html#_digital_signatures>:
/// Per [§13.2, “Digital Signatures”]:
///
/// > All digital signatures applied as per the technical requirements of this
/// > specification shall be generated using one of the digital signature
/// > algorithms and key types listed as described in this section.
///
/// > All digital signatures that are stored in a C2PA Manifest shall
/// > be generated using one of the digital signature algorithms and
/// > key types listed as described in this section.
/// [§13.2, “Digital Signatures”]: https://c2pa.org/specifications/specifications/2.1/specs/C2PA_Specification.html#_digital_signatures
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "json_schema", derive(JsonSchema))]
pub enum SigningAlg {
Expand Down Expand Up @@ -92,7 +92,7 @@ impl fmt::Display for SigningAlg {
///
/// The string must be one of "es256", "es384", "es512", "ps256", "ps384",
/// "ps512", or "ed25519".
pub struct UnknownAlgorithmError(String);
pub struct UnknownAlgorithmError(pub String);

impl fmt::Display for UnknownAlgorithmError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
Expand All @@ -101,44 +101,3 @@ impl fmt::Display for UnknownAlgorithmError {
}

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

#[cfg(test)]
mod tests {
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]

use super::*;

#[test]
fn alg_from_str() {
assert_eq!("es256".parse(), Ok(SigningAlg::Es256));
assert_eq!("es384".parse(), Ok(SigningAlg::Es384));
assert_eq!("es512".parse(), Ok(SigningAlg::Es512));
assert_eq!("ps256".parse(), Ok(SigningAlg::Ps256));
assert_eq!("ps384".parse(), Ok(SigningAlg::Ps384));
assert_eq!("ps512".parse(), Ok(SigningAlg::Ps512));
assert_eq!("ed25519".parse(), Ok(SigningAlg::Ed25519));

let r: Result<SigningAlg, UnknownAlgorithmError> = "bogus".parse();
assert_eq!(r, Err(UnknownAlgorithmError("bogus".to_string())));
}

#[test]
fn signing_alg_impl_display() {
assert_eq!(format!("{}", SigningAlg::Es256), "es256");
assert_eq!(format!("{}", SigningAlg::Es384), "es384");
assert_eq!(format!("{}", SigningAlg::Es512), "es512");
assert_eq!(format!("{}", SigningAlg::Ps256), "ps256");
assert_eq!(format!("{}", SigningAlg::Ps384), "ps384");
assert_eq!(format!("{}", SigningAlg::Ps512), "ps512");
assert_eq!(format!("{}", SigningAlg::Ed25519), "ed25519");
}

#[test]
fn err_impl_display() {
assert_eq!(
format!("{}", UnknownAlgorithmError("bogus".to_owned())),
"UnknownAlgorithmError(bogus)"
);
}
}
1 change: 1 addition & 0 deletions internal/crypto/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ mod base64;
mod hash;
mod internal;
mod ocsp;
mod signing_alg;
47 changes: 47 additions & 0 deletions internal/crypto/src/tests/signing_alg.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// Copyright 2022 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

use crate::signing_alg::{SigningAlg, UnknownAlgorithmError};

#[test]
fn alg_from_str() {
assert_eq!("es256".parse(), Ok(SigningAlg::Es256));
assert_eq!("es384".parse(), Ok(SigningAlg::Es384));
assert_eq!("es512".parse(), Ok(SigningAlg::Es512));
assert_eq!("ps256".parse(), Ok(SigningAlg::Ps256));
assert_eq!("ps384".parse(), Ok(SigningAlg::Ps384));
assert_eq!("ps512".parse(), Ok(SigningAlg::Ps512));
assert_eq!("ed25519".parse(), Ok(SigningAlg::Ed25519));

let r: Result<SigningAlg, UnknownAlgorithmError> = "bogus".parse();
assert_eq!(r, Err(UnknownAlgorithmError("bogus".to_string())));
}

#[test]
fn signing_alg_impl_display() {
assert_eq!(format!("{}", SigningAlg::Es256), "es256");
assert_eq!(format!("{}", SigningAlg::Es384), "es384");
assert_eq!(format!("{}", SigningAlg::Es512), "es512");
assert_eq!(format!("{}", SigningAlg::Ps256), "ps256");
assert_eq!(format!("{}", SigningAlg::Ps384), "ps384");
assert_eq!(format!("{}", SigningAlg::Ps512), "ps512");
assert_eq!(format!("{}", SigningAlg::Ed25519), "ed25519");
}

#[test]
fn err_impl_display() {
assert_eq!(
format!("{}", UnknownAlgorithmError("bogus".to_owned())),
"UnknownAlgorithmError(bogus)"
);
}
3 changes: 2 additions & 1 deletion sdk/examples/client/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ use std::path::PathBuf;
use anyhow::Result;
use c2pa::{
assertions::{c2pa_action, labels, Action, Actions, CreativeWork, Exif, SchemaDotOrgPerson},
create_signer, Builder, ClaimGeneratorInfo, Ingredient, Reader, Relationship, SigningAlg,
create_signer, Builder, ClaimGeneratorInfo, Ingredient, Reader, Relationship,
};
use c2pa_crypto::SigningAlg;

const GENERATOR: &str = "test_app/0.1";
const INDENT_SPACE: usize = 2;
Expand Down
4 changes: 3 additions & 1 deletion sdk/examples/data_hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ use c2pa::{
c2pa_action, labels::*, Action, Actions, CreativeWork, DataHash, Exif, SchemaDotOrgPerson,
},
create_signer, hash_stream_by_alg, Builder, ClaimGeneratorInfo, HashRange, Ingredient, Reader,
Relationship, Result, SigningAlg,
Relationship, Result,
};
#[cfg(not(target_arch = "wasm32"))]
use c2pa_crypto::SigningAlg;

fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
println!("DataHash demo");
Expand Down
3 changes: 2 additions & 1 deletion sdk/examples/v2api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
use std::io::{Cursor, Seek};

use anyhow::Result;
use c2pa::{settings::load_settings_from_str, Builder, CallbackSigner, Reader, SigningAlg};
use c2pa::{settings::load_settings_from_str, Builder, CallbackSigner, Reader};
use c2pa_crypto::SigningAlg;
use serde_json::json;

const TEST_IMAGE: &[u8] = include_bytes!("../tests/fixtures/CA.jpg");
Expand Down
4 changes: 3 additions & 1 deletion sdk/src/callback_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@
//! The `callback_signer` module provides a way to obtain a [`Signer`] or [`AsyncSigner`]
//! using a callback and public signing certificates.

use c2pa_crypto::SigningAlg;

use crate::{
error::{Error, Result},
AsyncSigner, Signer, SigningAlg,
AsyncSigner, Signer,
};

/// Defines a callback function interface for a [`CallbackSigner`].
Expand Down
7 changes: 4 additions & 3 deletions sdk/src/cose_sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use std::io::Cursor;

use async_generic::async_generic;
use c2pa_crypto::SigningAlg;
use c2pa_status_tracker::OneShotStatusTracker;
use ciborium::value::Value;
use coset::{
Expand All @@ -35,7 +36,7 @@ use crate::{
},
trust_handler::TrustHandlerConfig,
utils::sig_utils::{der_to_p1363, parse_ec_der_sig},
AsyncSigner, Error, Result, Signer, SigningAlg,
AsyncSigner, Error, Result, Signer,
};

/// Generate a COSE signature for a block of bytes which must be a valid C2PA
Expand Down Expand Up @@ -412,8 +413,8 @@ mod tests {
Ok(b"totally bogus signature".to_vec())
}

fn alg(&self) -> crate::SigningAlg {
crate::SigningAlg::Ps256
fn alg(&self) -> c2pa_crypto::SigningAlg {
c2pa_crypto::SigningAlg::Ps256
}

fn certs(&self) -> crate::error::Result<Vec<Vec<u8>>> {
Expand Down
3 changes: 1 addition & 2 deletions sdk/src/cose_validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use std::io::Cursor;

use asn1_rs::{Any, Class, Header, Tag};
use async_generic::async_generic;
use c2pa_crypto::{asn1::rfc3161::TstInfo, ocsp::OcspResponse};
use c2pa_crypto::{asn1::rfc3161::TstInfo, ocsp::OcspResponse, SigningAlg};
use c2pa_status_tracker::{log_item, StatusTracker};
use ciborium::value::Value;
use conv::*;
Expand All @@ -42,7 +42,6 @@ use crate::{
utils::sig_utils::parse_ec_der_sig,
validation_status,
validator::ValidationInfo,
SigningAlg,
};
#[cfg(target_arch = "wasm32")]
use crate::{
Expand Down
4 changes: 3 additions & 1 deletion sdk/src/create_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@
#[cfg(feature = "file_io")]
use std::path::Path;

use c2pa_crypto::SigningAlg;

use crate::{
error::Result,
openssl::{EcSigner, EdSigner, RsaSigner},
signer::ConfigurableSigner,
Signer, SigningAlg,
Signer,
};

/// Creates a [`Signer`] instance using signing certificate and private key
Expand Down
3 changes: 1 addition & 2 deletions sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ pub use assertions::Relationship;
pub use asset_io::{CAIRead, CAIReadWrite};
#[cfg(feature = "unstable_api")]
pub use builder::{Builder, ManifestDefinition};
pub use c2pa_crypto::SigningAlg;
pub use callback_signer::{CallbackFunc, CallbackSigner};
pub use claim_generator_info::ClaimGeneratorInfo;
pub use dynamic_assertion::DynamicAssertion;
Expand All @@ -137,7 +138,6 @@ pub use manifest_store_report::ManifestStoreReport;
pub use reader::Reader;
pub use resource_store::{ResourceRef, ResourceStore};
pub use signer::{AsyncSigner, RemoteSigner, Signer};
pub use signing_alg::SigningAlg;
pub use utils::mime::format_from_path;

// Internal modules
Expand Down Expand Up @@ -171,7 +171,6 @@ pub(crate) mod reader;
pub(crate) mod resource_store;
pub(crate) mod salt;
pub(crate) mod signer;
pub(crate) mod signing_alg;
pub(crate) mod store;
pub(crate) mod time_stamp;
pub(crate) mod trust_handler;
Expand Down
3 changes: 2 additions & 1 deletion sdk/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use std::{borrow::Cow, collections::HashMap, io::Cursor, slice::Iter};
use std::{fs::create_dir_all, path::Path};

use async_generic::async_generic;
use c2pa_crypto::SigningAlg;
use log::{debug, error};
#[cfg(feature = "json_schema")]
use schemars::JsonSchema;
Expand All @@ -40,7 +41,7 @@ use crate::{
salt::DefaultSalt,
store::Store,
AsyncSigner, ClaimGeneratorInfo, HashRange, ManifestAssertionKind, ManifestPatchCallback,
RemoteSigner, Signer, SigningAlg,
RemoteSigner, Signer,
};

/// A Manifest represents all the information in a c2pa manifest
Expand Down
3 changes: 2 additions & 1 deletion sdk/src/openssl/ec_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
// specific language governing permissions and limitations under
// each license.

use c2pa_crypto::SigningAlg;
use openssl::{
ec::EcKey,
hash::MessageDigest,
Expand All @@ -23,7 +24,7 @@ use crate::{
error::{Error, Result},
signer::ConfigurableSigner,
utils::sig_utils::der_to_p1363,
Signer, SigningAlg,
Signer,
};

/// Implements `Signer` trait using OpenSSL's implementation of
Expand Down
3 changes: 2 additions & 1 deletion sdk/src/openssl/ec_validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
// specific language governing permissions and limitations under
// each license.

use c2pa_crypto::SigningAlg;
use openssl::{ec::EcKey, hash::MessageDigest, pkey::PKey};

use crate::{validator::CoseValidator, Error, Result, SigningAlg};
use crate::{validator::CoseValidator, Error, Result};

pub struct EcValidator {
alg: SigningAlg,
Expand Down
3 changes: 2 additions & 1 deletion sdk/src/openssl/ed_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@
// specific language governing permissions and limitations under
// each license.

use c2pa_crypto::SigningAlg;
use openssl::{
pkey::{PKey, Private},
x509::X509,
};

use super::check_chain_order;
use crate::{signer::ConfigurableSigner, Error, Result, Signer, SigningAlg};
use crate::{signer::ConfigurableSigner, Error, Result, Signer};

/// Implements `Signer` trait using OpenSSL's implementation of
/// Edwards Curve encryption.
Expand Down
3 changes: 2 additions & 1 deletion sdk/src/openssl/ed_validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
// specific language governing permissions and limitations under
// each license.

use c2pa_crypto::SigningAlg;
use openssl::pkey::PKey;

use crate::{validator::CoseValidator, Error, Result, SigningAlg};
use crate::{validator::CoseValidator, Error, Result};

pub struct EdValidator {
_alg: SigningAlg,
Expand Down
4 changes: 3 additions & 1 deletion sdk/src/openssl/openssl_trust_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,10 +300,12 @@ pub mod tests {
#![allow(clippy::panic)]
#![allow(clippy::unwrap_used)]

use c2pa_crypto::SigningAlg;

use super::*;
use crate::{
openssl::temp_signer::{self},
Signer, SigningAlg,
Signer,
};

#[test]
Expand Down
4 changes: 2 additions & 2 deletions sdk/src/openssl/rsa_signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

use std::cell::Cell;

use c2pa_crypto::ocsp::OcspResponse;
use c2pa_crypto::{ocsp::OcspResponse, SigningAlg};
use openssl::{
hash::MessageDigest,
pkey::{PKey, Private},
Expand All @@ -22,7 +22,7 @@ use openssl::{
};

use super::check_chain_order;
use crate::{signer::ConfigurableSigner, Error, Result, Signer, SigningAlg};
use crate::{signer::ConfigurableSigner, Error, Result, Signer};

/// Implements `Signer` trait using OpenSSL's implementation of
/// SHA256 + RSA encryption.
Expand Down
Loading

0 comments on commit fffdd64

Please sign in to comment.