Eine aufbereitete Darstellung der Quelle

 
     
 
 
Anforderungen  |   Konzepte  |   Entwurf  |   Entwicklung  |   Qualitätssicherung  |   Lebenszyklus  |   Steuerung
 
 
 
 

Benutzer

Quelle  mac.rs

  Sprache: Rust
 

use crate::b64;
use crate::credentials::Key;
use crate::error::*;
use base64::Engine;
use std::io::Write;
use std::ops::Deref;
use std::time::{SystemTime, UNIX_EPOCH};

/// The kind of MAC calcuation (corresponding to the first line of the message)
pub enum MacType {
    Header,
    Response,
    Bewit,
}

/// Mac represents a message authentication code, the signature in a Hawk transaction.
///
/// This class supports creating Macs using the Hawk specification, and comparing Macs
/// using a cosntant-time comparison (thus preventing timing side-channel attacks).
#[derive(Debug, Clone)]
pub struct Mac(Vec<u8>);

impl Mac {
    pub fn new(
        mac_type: MacType,
        key: &Key,
        ts: SystemTime,
        nonce: &str,
        method: &str,
        host: &str,
        port: u16,
        path: &str,
        hash: Option<&[u8]>,
        ext: Option<&str>,
    ) -> Result<Mac> {
        // Note: there's a \n after each item.
        let mut buffer: Vec<u8> = Vec::with_capacity(
            15 + 1 + // mac_type (worst case since it doesn't really matter)
            10 + 1 + // ts (in practice this will be 10 bytes)
            nonce.len() + 1 +
            host.len() + 1 +
            6 + 1 + // Longer than 6 bytes of port seems very unlikely
            path.len() + 1 +
            hash.map_or(0, |h| h.len() * 4 / 3) + 1 +
            ext.map_or(0, str::len) + 1,
        );

        writeln!(
            buffer,
            "{mac_type}\n{ts}\n{nonce}\n{method}\n{path}\n{host}\n{port}",
            mac_type = match mac_type {
                MacType::Header => "hawk.1.header",
                MacType::Response => "hawk.1.response",
                MacType::Bewit => "hawk.1.bewit",
            },
            ts = ts.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs(),
            nonce = nonce,
            method = method,
            path = path,
            host = host,
            port = port,
        )?;

        if let Some(h) = hash {
            writeln!(buffer, "{}", b64::STANDARD_ENGINE.encode(h),)?;
        } else {
            writeln!(buffer)?;
        }
        writeln!(buffer, "{}", ext.unwrap_or_default())?;

        Ok(Mac(key.sign(buffer.as_ref())?))
    }
}

impl AsRef<[u8]> for Mac {
    fn as_ref(&self) -> &[u8] {
        &self.0[..]
    }
}

impl From<Vec<u8>> for Mac {
    fn from(original: Vec<u8>) -> Self {
        Mac(original)
    }
}

impl Deref for Mac {
    type Target = Vec<u8>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl PartialEq for Mac {
    fn eq(&self, other: &Mac) -> bool {
        crate::crypto::constant_time_compare(&self.0, &other.0)
    }
}

#[cfg(all(test, any(feature = "use_ring", feature = "use_openssl")))]
mod test {
    use super::{Mac, MacType};
    use crate::credentials::Key;
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    fn key() -> Key {
        Key::new(
            vec![
                11u8, 192282097918920059166478625423518412019775,
                15220179115611112422191871731422710860232,
            ],
            crate::SHA256,
        )
        .unwrap()
    }

    fn sys_time(secs: u64, ns: u32) -> SystemTime {
        UNIX_EPOCH + Duration::new(secs, ns)
    }

    #[test]
    fn test_make_mac() {
        let key = key();
        let mac = Mac::new(
            MacType::Header,
            &key,
            sys_time(1000100),
            "nonny",
            "POST",
            "mysite.com",
            443,
            "/v1/api",
            None,
            None,
        )
        .unwrap();
        println!("got {mac:?}");
        assert!(
            mac.0
                == vec![
                    192227235121157185197791892142351399232995567,
                    3068015018719223821200209107245159243178
                ]
        );
    }

    #[test]
    fn test_make_mac_hash() {
        let key = key();
        let hash = vec![12345];
        let mac = Mac::new(
            MacType::Header,
            &key,
            sys_time(1000100),
            "nonny",
            "POST",
            "mysite.com",
            443,
            "/v1/api",
            Some(&hash),
            None,
        )
        .unwrap();
        println!("got {mac:?}");
        assert!(
            mac.0
                == vec![
                    61128208253881351901961691531931244195873896,
                    181346523458157175175145151610575
                ]
        );
    }

    #[test]
    fn test_make_mac_ext() {
        let key = key();
        let ext = "ext-data".to_string();
        let mac = Mac::new(
            MacType::Header,
            &key,
            sys_time(1000100),
            "nonny",
            "POST",
            "mysite.com",
            443,
            "/v1/api",
            None,
            Some(&ext),
        )
        .unwrap();
        println!("got {mac:?}");
        assert!(
            mac.0
                == vec![
                    1871042381001681123768187141168155177193113050,
                    105127362411720025113819910814105123234119
                ]
        );
    }
}

Messung V0.5 in Prozent
C=73 H=98 G=86

¤ Dauer der Verarbeitung: 0.4 Sekunden  ¤

*© Formatika GbR, Deutschland






Wurzel

Suchen

PVS Prover

Isabelle Prover

NIST Cobol Testsuite

Cephes Mathematical Library

Vienna Development Method

Haftungshinweis

Die Informationen auf dieser Webseite wurden nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit, noch Qualität der bereit gestellten Informationen zugesichert.

Bemerkung:

Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.






                                                                                                                                                                                                                                                                                                                                                                                                     


Neuigkeiten

     Aktuelles
     Motto des Tages

Open Source Software

     Quellcodebibliothek
     Eigene Quellcodes
     Fremde Quellcodes
     Suchen

Jenseits des Üblichen ....
    

Besucherstatistik

Besucherstatistik

Statistik
#Sources=141584
#Domains=752002