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