/*-
 * Scram-rs - a SCRAM authentification authorization library
 * 
 * Copyright (C) 2021  Aleksandr Morozov
 * Copyright (C) 2025 Aleksandr Morozov
 * 
 * The syslog-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *
 *   2. The MIT License (MIT)
 *                     
 *   3. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */


#[cfg(feature = "std")]
use std::num::NonZeroU32;
#[cfg(not(feature = "std"))]
use core::num::NonZeroU32;

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
#[cfg(not(feature = "std"))]
use alloc::vec;

use hmac::{Hmac, Mac, KeyInit};
use pbkdf2::pbkdf2;
use sha3::{Sha3_512, Digest};

use crate::ScramCommon;
use crate::{ScramHashing, ScramOps};

use super::scram_error::{ScramResult, ScramErrorCode};
use super::scram_error_map;

/// A `ScramProvider` which provides SCRAM-SHA3-512 and SCRAM-SHA3-512-PLUS 
/// See https://datatracker.ietf.org/doc/html/draft-melnikov-scram-sha3-512#name-scram-sha3-512-and-scram-sh
/// based on the PBKDF2, Sha3, Hmac
#[derive(Debug)]
pub struct ScramSha3_512RustNative;

impl ScramOps for ScramSha3_512RustNative {}

impl ScramHashing for ScramSha3_512RustNative 
{
    const MIN_ITERS: NonZeroU32 = ScramCommon::SCRAM_DEFAULT_SALT3_ITER;

    fn hash(data: &[u8]) -> Vec<u8> 
    {
        let hash =  Sha3_512::digest(data);

        return Vec::from(hash.as_slice());
    }

    fn hmac(data: &[u8], key: &[u8]) -> ScramResult<Vec<u8>> 
    {
        use crate::ScramServerError;

        let mut mac = 
            Hmac::<Sha3_512>::new_from_slice(key)
                .map_err(|e| 
                    scram_error_map!(ScramErrorCode::ExternalError, ScramServerError::OtherError, 
                        "hmac() Hmac::<Sha512> err, {}", e)
                )?;

        mac.update(data);
        
        let result = mac.finalize();
        let ret = Vec::from(result.into_bytes().as_slice());

        return Ok(ret);
    }

    fn derive(password: &[u8], salt: &[u8], iterations: NonZeroU32) -> ScramResult<Vec<u8>> 
    {
        use crate::ScramServerError;

        let mut salted = vec![0; Sha3_512::output_size()]; //64
        pbkdf2::<Hmac<Sha3_512>>(password, salt, iterations.get(), &mut salted)
            .map_err(|e| 
                scram_error_map!(ScramErrorCode::ExternalError, ScramServerError::OtherError,
                    "pbkdf2 Hmac::<Sha1> err, {}", e)
            )?;

        return Ok(salted);
    }
}


// At the moment SHA3 is not available in the ring crate 
/*
#[cfg(feature = "use_aws_lc")]
pub mod sha3_512_aec_ls_based
{
    #[cfg(feature = "std")]
    use std::num::NonZeroU32;
    #[cfg(not(feature = "std"))]
    use core::num::NonZeroU32;

    #[cfg(not(feature = "std"))]
    use alloc::vec::Vec;
    #[cfg(not(feature = "std"))]
    use alloc::vec;

    use aws_lc_rs::{digest, pbkdf2, hmac};

    use crate::{ScramCommon, ScramHashing, ScramOps, ScramResult};

    /// A `ScramProvider` which provides SCRAM-SHA-256 and SCRAM-SHA-256-PLUS
    /// based on the Ring. 
    #[derive(Debug)]
    pub struct ScramSha3_512AwsLc;

    impl ScramOps for ScramSha3_512AwsLc {}

    impl ScramHashing for ScramSha3_512AwsLc 
    {
        const MIN_ITERS: NonZeroU32 = ScramCommon::SCRAM_DEFAULT_SALT3_ITER;
        
        fn hash(data: &[u8]) -> Vec<u8> 
        {
            let hash = digest::digest(&digest::SHA3_512, data);

            return Vec::from(hash.as_ref());
        }

        fn hmac(data: &[u8], key: &[u8]) -> ScramResult<Vec<u8>> 
        {
            let s_key = hmac::Key::new(hmac::HMAC_SHA512, key);
            let mut mac = hmac::Context::with_key(&s_key);

            mac.update(data);

            let ret: Vec<u8> = mac.sign().as_ref().into();

            return Ok(ret);
        }

        fn derive(password: &[u8], salt: &[u8], iterations: NonZeroU32) -> ScramResult<Vec<u8>> 
        {
            let mut salted = vec![0; digest::SHA3_512.output_len];

            pbkdf2::derive(pbkdf2::PBKDF2_HMAC_SHA512, iterations.into(), salt, password, &mut salted);

            return Ok(salted);
        }

    }
}

#[cfg(feature = "use_aws_lc")]
pub use self::sha3_512_aec_ls_based::ScramSha3_512AwsLc;
*/


// At the moment SHA3 is not available in the ring crate 
// see https://github.com/briansmith/ring/issues/59
/*#[cfg(feature = "use_ring")]
pub mod sha3_512_ring_based
{
    #[cfg(feature = "std")]
    use std::num::NonZeroU32;
    #[cfg(not(feature = "std"))]
    use core::num::NonZeroU32;

    #[cfg(not(feature = "std"))]
    use alloc::vec::Vec;
    #[cfg(not(feature = "std"))]
    use alloc::vec;

    use ring::{digest as ring_digest, hmac as ring_hmac, pbkdf2 as ring_pbkdf2};

    use crate::{ScramHashing, ScramOps, ScramResult};

    /// A `ScramProvider` which provides SCRAM-SHA-256 and SCRAM-SHA-256-PLUS
    /// based on the Ring. 
    pub struct ScramSha512Ring;

    impl ScramOps for ScramSha512Ring {}

    impl ScramHashing for ScramSha512Ring 
    {
        fn hash(data: &[u8]) -> Vec<u8> 
        {
            let hash = ring_digest::digest(&ring_digest::S, data);

            return Vec::from(hash.as_ref());
        }

        fn hmac(data: &[u8], key: &[u8]) -> ScramResult<Vec<u8>> 
        {
            let s_key = ring_hmac::Key::new(ring_hmac::HMAC_SHA512, key);
            let mut mac = ring_hmac::Context::with_key(&s_key);

            mac.update(data);

            let ret: Vec<u8> = mac.sign().as_ref().into();

            return Ok(ret);
        }

        fn derive(password: &[u8], salt: &[u8], iterations: NonZeroU32) -> ScramResult<Vec<u8>> 
        {
            let mut salted = vec![0; ring_digest::SHA512_OUTPUT_LEN];

            ring_pbkdf2::derive(ring_pbkdf2::PBKDF2_HMAC_SHA512, iterations.into(), salt, password, &mut salted);

            return Ok(salted);
        }

    }
}

#[cfg(feature = "use_ring")]
pub use self::sha512_ring_based::*;*/
