c2pa_raw_crypto 0.1.1

Raw cryptographic signing and validation primitives for C2PA
Documentation
// 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 openssl::{pkey::PKey, sign::Verifier};

use crate::{RawSignatureValidationError, RawSignatureValidator, openssl::OpenSslMutex};

/// Validates raw signatures with the Ed25519 signature algorithm.
pub(crate) struct Ed25519Validator {}

impl RawSignatureValidator for Ed25519Validator {
    fn validate(
        &self,
        sig: &[u8],
        data: &[u8],
        public_key: &[u8],
    ) -> Result<(), RawSignatureValidationError> {
        let _openssl = OpenSslMutex::acquire()?;

        let public_key = PKey::public_key_from_der(public_key)?;

        if Verifier::new_without_digest(&public_key)?.verify_oneshot(sig, data)? {
            Ok(())
        } else {
            Err(RawSignatureValidationError::SignatureMismatch)
        }
    }
}

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

    use super::*;

    const SAMPLE_DATA: &[u8] = b"some sample content to sign";

    #[test]
    fn unparseable_public_key_is_crypto_error() {
        let sig = include_bytes!("../../../tests/fixtures/raw_signature/ed25519.raw_sig");

        let err = Ed25519Validator {}
            .validate(sig, SAMPLE_DATA, &[0x00, 0x01, 0x02])
            .unwrap_err();

        assert!(matches!(
            err,
            RawSignatureValidationError::CryptoLibraryError(_)
        ));
    }
}