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 minidom::IntoAttributeValue;
 10use std::num::ParseIntError;
 11use std::ops::{Deref, DerefMut};
 12use std::str::FromStr;
 13
 14/// List of the algorithms we support, or Unknown.
 15#[allow(non_camel_case_types)]
 16#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 17pub enum Algo {
 18    /// The Secure Hash Algorithm 1, with known vulnerabilities, do not use it.
 19    ///
 20    /// See https://tools.ietf.org/html/rfc3174
 21    Sha_1,
 22
 23    /// The Secure Hash Algorithm 2, in its 256-bit version.
 24    ///
 25    /// See https://tools.ietf.org/html/rfc6234
 26    Sha_256,
 27
 28    /// The Secure Hash Algorithm 2, in its 512-bit version.
 29    ///
 30    /// See https://tools.ietf.org/html/rfc6234
 31    Sha_512,
 32
 33    /// The Secure Hash Algorithm 3, based on Keccak, in its 256-bit version.
 34    ///
 35    /// See https://keccak.team/files/Keccak-submission-3.pdf
 36    Sha3_256,
 37
 38    /// The Secure Hash Algorithm 3, based on Keccak, in its 512-bit version.
 39    ///
 40    /// See https://keccak.team/files/Keccak-submission-3.pdf
 41    Sha3_512,
 42
 43    /// The BLAKE2 hash algorithm, for a 256-bit output.
 44    ///
 45    /// See https://tools.ietf.org/html/rfc7693
 46    Blake2b_256,
 47
 48    /// The BLAKE2 hash algorithm, for a 512-bit output.
 49    ///
 50    /// See https://tools.ietf.org/html/rfc7693
 51    Blake2b_512,
 52
 53    /// An unknown hash not in this list, you can probably reject it.
 54    Unknown(String),
 55}
 56
 57impl FromStr for Algo {
 58    type Err = Error;
 59
 60    fn from_str(s: &str) -> Result<Algo, Error> {
 61        Ok(match s {
 62            "" => return Err(Error::ParseError("'algo' argument can’t be empty.")),
 63
 64            "sha-1" => Algo::Sha_1,
 65            "sha-256" => Algo::Sha_256,
 66            "sha-512" => Algo::Sha_512,
 67            "sha3-256" => Algo::Sha3_256,
 68            "sha3-512" => Algo::Sha3_512,
 69            "blake2b-256" => Algo::Blake2b_256,
 70            "blake2b-512" => Algo::Blake2b_512,
 71            value => Algo::Unknown(value.to_owned()),
 72        })
 73    }
 74}
 75
 76impl From<Algo> for String {
 77    fn from(algo: Algo) -> String {
 78        String::from(match algo {
 79            Algo::Sha_1 => "sha-1",
 80            Algo::Sha_256 => "sha-256",
 81            Algo::Sha_512 => "sha-512",
 82            Algo::Sha3_256 => "sha3-256",
 83            Algo::Sha3_512 => "sha3-512",
 84            Algo::Blake2b_256 => "blake2b-256",
 85            Algo::Blake2b_512 => "blake2b-512",
 86            Algo::Unknown(text) => return text,
 87        })
 88    }
 89}
 90
 91impl IntoAttributeValue for Algo {
 92    fn into_attribute_value(self) -> Option<String> {
 93        Some(String::from(self))
 94    }
 95}
 96
 97generate_element!(
 98    /// This element represents a hash of some data, defined by the hash
 99    /// algorithm used and the computed value.
100    Hash, "hash", HASHES,
101    attributes: [
102        /// The algorithm used to create this hash.
103        algo: Required<Algo> = "algo"
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    /// Like [new](#method.new) but takes hex-encoded data before decoding it.
124    pub fn from_hex(algo: Algo, hex: &str) -> Result<Hash, ParseIntError> {
125        let mut bytes = vec![];
126        for i in 0..hex.len() / 2 {
127            let byte = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)?;
128            bytes.push(byte);
129        }
130        Ok(Hash::new(algo, bytes))
131    }
132
133    /// Like [new](#method.new) but takes hex-encoded data before decoding it.
134    pub fn from_colon_separated_hex(algo: Algo, hex: &str) -> Result<Hash, ParseIntError> {
135        let mut bytes = vec![];
136        for i in 0..(1 + hex.len()) / 3 {
137            let byte = u8::from_str_radix(&hex[3 * i..3 * i + 2], 16)?;
138            if 3 * i + 2 < hex.len() {
139                assert_eq!(&hex[3 * i + 2..3 * i + 3], ":");
140            }
141            bytes.push(byte);
142        }
143        Ok(Hash::new(algo, bytes))
144    }
145
146    /// Formats this hash into base64.
147    pub fn to_base64(&self) -> String {
148        base64::encode(&self.hash[..])
149    }
150
151    /// Formats this hash into hexadecimal.
152    pub fn to_hex(&self) -> String {
153        self.hash
154            .iter()
155            .map(|byte| format!("{:02x}", byte))
156            .collect::<Vec<_>>()
157            .join("")
158    }
159
160    /// Formats this hash into colon-separated hexadecimal.
161    pub fn to_colon_separated_hex(&self) -> String {
162        self.hash
163            .iter()
164            .map(|byte| format!("{:02x}", byte))
165            .collect::<Vec<_>>()
166            .join(":")
167    }
168}
169
170/// Helper for parsing and serialising a SHA-1 attribute.
171#[derive(Debug, Clone, PartialEq)]
172pub struct Sha1HexAttribute(Hash);
173
174impl FromStr for Sha1HexAttribute {
175    type Err = ParseIntError;
176
177    fn from_str(hex: &str) -> Result<Self, Self::Err> {
178        let hash = Hash::from_hex(Algo::Sha_1, hex)?;
179        Ok(Sha1HexAttribute(hash))
180    }
181}
182
183impl IntoAttributeValue for Sha1HexAttribute {
184    fn into_attribute_value(self) -> Option<String> {
185        Some(self.to_hex())
186    }
187}
188
189impl DerefMut for Sha1HexAttribute {
190    fn deref_mut(&mut self) -> &mut Self::Target {
191        &mut self.0
192    }
193}
194
195impl Deref for Sha1HexAttribute {
196    type Target = Hash;
197
198    fn deref(&self) -> &Self::Target {
199        &self.0
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use crate::Element;
207    use std::convert::TryFrom;
208
209    #[cfg(target_pointer_width = "32")]
210    #[test]
211    fn test_size() {
212        assert_size!(Algo, 16);
213        assert_size!(Hash, 28);
214    }
215
216    #[cfg(target_pointer_width = "64")]
217    #[test]
218    fn test_size() {
219        assert_size!(Algo, 32);
220        assert_size!(Hash, 56);
221    }
222
223    #[test]
224    fn test_simple() {
225        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
226        let hash = Hash::try_from(elem).unwrap();
227        assert_eq!(hash.algo, Algo::Sha_256);
228        assert_eq!(
229            hash.hash,
230            base64::decode("2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=").unwrap()
231        );
232    }
233
234    #[test]
235    fn value_serialisation() {
236        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
237        let hash = Hash::try_from(elem).unwrap();
238        assert_eq!(
239            hash.to_base64(),
240            "2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU="
241        );
242        assert_eq!(
243            hash.to_hex(),
244            "d976ab9b04e53710c0324bf29a5a17dd2e7e55bca536b26dfe5e50c8f6be6285"
245        );
246        assert_eq!(hash.to_colon_separated_hex(), "d9:76:ab:9b:04:e5:37:10:c0:32:4b:f2:9a:5a:17:dd:2e:7e:55:bc:a5:36:b2:6d:fe:5e:50:c8:f6:be:62:85");
247    }
248
249    #[test]
250    fn test_unknown() {
251        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>"
252            .parse()
253            .unwrap();
254        let error = Hash::try_from(elem).unwrap_err();
255        let message = match error {
256            Error::ParseError(string) => string,
257            _ => panic!(),
258        };
259        assert_eq!(message, "This is not a hash element.");
260    }
261
262    #[test]
263    fn test_invalid_child() {
264        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2'><coucou/></hash>"
265            .parse()
266            .unwrap();
267        let error = Hash::try_from(elem).unwrap_err();
268        let message = match error {
269            Error::ParseError(string) => string,
270            _ => panic!(),
271        };
272        assert_eq!(message, "Unknown child in hash element.");
273    }
274}