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 crate::error::Error;
  8use crate::helpers::Base64;
  9use base64;
 10use minidom::IntoAttributeValue;
 11use std::str::FromStr;
 12
 13/// List of the algorithms we support, or Unknown.
 14#[allow(non_camel_case_types)]
 15#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 16pub enum Algo {
 17    /// The Secure Hash Algorithm 1, with known vulnerabilities, do not use it.
 18    ///
 19    /// See https://tools.ietf.org/html/rfc3174
 20    Sha_1,
 21
 22    /// The Secure Hash Algorithm 2, in its 256-bit version.
 23    ///
 24    /// See https://tools.ietf.org/html/rfc6234
 25    Sha_256,
 26
 27    /// The Secure Hash Algorithm 2, in its 512-bit version.
 28    ///
 29    /// See https://tools.ietf.org/html/rfc6234
 30    Sha_512,
 31
 32    /// The Secure Hash Algorithm 3, based on Keccak, in its 256-bit version.
 33    ///
 34    /// See https://keccak.team/files/Keccak-submission-3.pdf
 35    Sha3_256,
 36
 37    /// The Secure Hash Algorithm 3, based on Keccak, in its 512-bit version.
 38    ///
 39    /// See https://keccak.team/files/Keccak-submission-3.pdf
 40    Sha3_512,
 41
 42    /// The BLAKE2 hash algorithm, for a 256-bit output.
 43    ///
 44    /// See https://tools.ietf.org/html/rfc7693
 45    Blake2b_256,
 46
 47    /// The BLAKE2 hash algorithm, for a 512-bit output.
 48    ///
 49    /// See https://tools.ietf.org/html/rfc7693
 50    Blake2b_512,
 51
 52    /// An unknown hash not in this list, you can probably reject it.
 53    Unknown(String),
 54}
 55
 56impl FromStr for Algo {
 57    type Err = Error;
 58
 59    fn from_str(s: &str) -> Result<Algo, Error> {
 60        Ok(match s {
 61            "" => return Err(Error::ParseError("'algo' argument can’t be empty.")),
 62
 63            "sha-1" => Algo::Sha_1,
 64            "sha-256" => Algo::Sha_256,
 65            "sha-512" => Algo::Sha_512,
 66            "sha3-256" => Algo::Sha3_256,
 67            "sha3-512" => Algo::Sha3_512,
 68            "blake2b-256" => Algo::Blake2b_256,
 69            "blake2b-512" => Algo::Blake2b_512,
 70            value => Algo::Unknown(value.to_owned()),
 71        })
 72    }
 73}
 74
 75impl From<Algo> for String {
 76    fn from(algo: Algo) -> String {
 77        String::from(match algo {
 78            Algo::Sha_1 => "sha-1",
 79            Algo::Sha_256 => "sha-256",
 80            Algo::Sha_512 => "sha-512",
 81            Algo::Sha3_256 => "sha3-256",
 82            Algo::Sha3_512 => "sha3-512",
 83            Algo::Blake2b_256 => "blake2b-256",
 84            Algo::Blake2b_512 => "blake2b-512",
 85            Algo::Unknown(text) => return text,
 86        })
 87    }
 88}
 89
 90impl IntoAttributeValue for Algo {
 91    fn into_attribute_value(self) -> Option<String> {
 92        Some(String::from(self))
 93    }
 94}
 95
 96generate_element!(
 97    /// This element represents a hash of some data, defined by the hash
 98    /// algorithm used and the computed value.
 99    #[derive(PartialEq)]
100    Hash, "hash", HASHES,
101    attributes: [
102        /// The algorithm used to create this hash.
103        algo: Algo = "algo" => required
104    ],
105    text: (
106        /// The hash value, as a vector of bytes.
107        hash: Base64<Vec<u8>>
108    )
109);
110
111impl Hash {
112    /// Creates a [Hash] element with the given algo and data.
113    pub fn new(algo: Algo, hash: Vec<u8>) -> Hash {
114        Hash { algo, hash }
115    }
116
117    /// Like [new](#method.new) but takes base64-encoded data before decoding
118    /// it.
119    pub fn from_base64(algo: Algo, hash: &str) -> Result<Hash, Error> {
120        Ok(Hash::new(algo, base64::decode(hash)?))
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use minidom::Element;
128    use try_from::TryFrom;
129
130    #[cfg(target_pointer_width = "32")]
131    #[test]
132    fn test_size() {
133        assert_size!(Algo, 16);
134        assert_size!(Hash, 28);
135    }
136
137    #[cfg(target_pointer_width = "64")]
138    #[test]
139    fn test_size() {
140        assert_size!(Algo, 32);
141        assert_size!(Hash, 56);
142    }
143
144    #[test]
145    fn test_simple() {
146        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
147        let hash = Hash::try_from(elem).unwrap();
148        assert_eq!(hash.algo, Algo::Sha_256);
149        assert_eq!(
150            hash.hash,
151            base64::decode("2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=").unwrap()
152        );
153    }
154
155    #[test]
156    fn test_unknown() {
157        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>"
158            .parse()
159            .unwrap();
160        let error = Hash::try_from(elem).unwrap_err();
161        let message = match error {
162            Error::ParseError(string) => string,
163            _ => panic!(),
164        };
165        assert_eq!(message, "This is not a hash element.");
166    }
167
168    #[test]
169    fn test_invalid_child() {
170        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2'><coucou/></hash>"
171            .parse()
172            .unwrap();
173        let error = Hash::try_from(elem).unwrap_err();
174        let message = match error {
175            Error::ParseError(string) => string,
176            _ => panic!(),
177        };
178        assert_eq!(message, "Unknown child in hash element.");
179    }
180}