hashes.rs

  1// Copyright (c) 2017 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
  2//
  3// This Source Code Form is subject to the terms of the Mozilla Public
  4// License, v. 2.0. If a copy of the MPL was not distributed with this
  5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6
  7use try_from::TryFrom;
  8use std::str::FromStr;
  9
 10use minidom::{Element, IntoAttributeValue};
 11
 12use error::Error;
 13
 14use ns;
 15
 16use base64;
 17
 18#[allow(non_camel_case_types)]
 19#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 20pub enum Algo {
 21    Sha_1,
 22    Sha_256,
 23    Sha_512,
 24    Sha3_256,
 25    Sha3_512,
 26    Blake2b_256,
 27    Blake2b_512,
 28    Unknown(String),
 29}
 30
 31impl FromStr for Algo {
 32    type Err = Error;
 33
 34    fn from_str(s: &str) -> Result<Algo, Error> {
 35        Ok(match s {
 36            "" => return Err(Error::ParseError("'algo' argument can’t be empty.")),
 37
 38            "sha-1" => Algo::Sha_1,
 39            "sha-256" => Algo::Sha_256,
 40            "sha-512" => Algo::Sha_512,
 41            "sha3-256" => Algo::Sha3_256,
 42            "sha3-512" => Algo::Sha3_512,
 43            "blake2b-256" => Algo::Blake2b_256,
 44            "blake2b-512" => Algo::Blake2b_512,
 45            value => Algo::Unknown(value.to_owned()),
 46        })
 47    }
 48}
 49
 50impl From<Algo> for String {
 51    fn from(algo: Algo) -> String {
 52        String::from(match algo {
 53            Algo::Sha_1 => "sha-1",
 54            Algo::Sha_256 => "sha-256",
 55            Algo::Sha_512 => "sha-512",
 56            Algo::Sha3_256 => "sha3-256",
 57            Algo::Sha3_512 => "sha3-512",
 58            Algo::Blake2b_256 => "blake2b-256",
 59            Algo::Blake2b_512 => "blake2b-512",
 60            Algo::Unknown(text) => return text,
 61        })
 62    }
 63}
 64
 65impl IntoAttributeValue for Algo {
 66    fn into_attribute_value(self) -> Option<String> {
 67        Some(String::from(self))
 68    }
 69}
 70
 71#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 72pub struct Hash {
 73    pub algo: Algo,
 74    pub hash: Vec<u8>,
 75}
 76
 77impl TryFrom<Element> for Hash {
 78    type Err = Error;
 79
 80    fn try_from(elem: Element) -> Result<Hash, Error> {
 81        if !elem.is("hash", ns::HASHES) {
 82            return Err(Error::ParseError("This is not a hash element."));
 83        }
 84        for _ in elem.children() {
 85            return Err(Error::ParseError("Unknown child in hash element."));
 86        }
 87        let algo = get_attr!(elem, "algo", required);
 88        let hash = match elem.text().as_ref() {
 89            "" => return Err(Error::ParseError("Hash element shouldn’t be empty.")),
 90            text => base64::decode(text)?,
 91        };
 92        Ok(Hash {
 93            algo: algo,
 94            hash: hash,
 95        })
 96    }
 97}
 98
 99impl From<Hash> for Element {
100    fn from(hash: Hash) -> Element {
101        Element::builder("hash")
102                .ns(ns::HASHES)
103                .attr("algo", hash.algo)
104                .append(base64::encode(&hash.hash))
105                .build()
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112
113    #[test]
114    fn test_simple() {
115        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
116        let hash = Hash::try_from(elem).unwrap();
117        assert_eq!(hash.algo, Algo::Sha_256);
118        assert_eq!(hash.hash, base64::decode("2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=").unwrap());
119    }
120
121    #[test]
122    fn test_unknown() {
123        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>".parse().unwrap();
124        let error = Hash::try_from(elem).unwrap_err();
125        let message = match error {
126            Error::ParseError(string) => string,
127            _ => panic!(),
128        };
129        assert_eq!(message, "This is not a hash element.");
130    }
131
132    #[test]
133    fn test_invalid_child() {
134        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2'><coucou/></hash>".parse().unwrap();
135        let error = Hash::try_from(elem).unwrap_err();
136        let message = match error {
137            Error::ParseError(string) => string,
138            _ => panic!(),
139        };
140        assert_eq!(message, "Unknown child in hash element.");
141    }
142}