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    #[derive(PartialEq)]
101    Hash, "hash", HASHES,
102    attributes: [
103        /// The algorithm used to create this hash.
104        algo: Required<Algo> = "algo"
105    ],
106    text: (
107        /// The hash value, as a vector of bytes.
108        hash: Base64<Vec<u8>>
109    )
110);
111
112impl Hash {
113    /// Creates a [Hash] element with the given algo and data.
114    pub fn new(algo: Algo, hash: Vec<u8>) -> Hash {
115        Hash { algo, hash }
116    }
117
118    /// Like [new](#method.new) but takes base64-encoded data before decoding
119    /// it.
120    pub fn from_base64(algo: Algo, hash: &str) -> Result<Hash, Error> {
121        Ok(Hash::new(algo, base64::decode(hash)?))
122    }
123
124    /// Like [new](#method.new) but takes hex-encoded data before decoding it.
125    pub fn from_hex(algo: Algo, hex: &str) -> Result<Hash, ParseIntError> {
126        let mut bytes = vec![];
127        for i in 0..hex.len() / 2 {
128            let byte = u8::from_str_radix(&hex[2 * i..2 * i + 2], 16)?;
129            bytes.push(byte);
130        }
131        Ok(Hash::new(algo, bytes))
132    }
133
134    /// Formats this hash into base64.
135    pub fn to_base64(&self) -> String {
136        base64::encode(&self.hash[..])
137    }
138
139    /// Formats this hash into hexadecimal.
140    pub fn to_hex(&self) -> String {
141        let mut bytes = vec![];
142        for byte in self.hash.iter() {
143            bytes.push(format!("{:02x}", byte));
144        }
145        bytes.join("")
146    }
147
148    /// Formats this hash into colon-separated hexadecimal.
149    pub fn to_colon_hex(&self) -> String {
150        let mut bytes = vec![];
151        for byte in self.hash.iter() {
152            bytes.push(format!("{:02x}", byte));
153        }
154        bytes.join(":")
155    }
156}
157
158/// Helper for parsing and serialising a SHA-1 attribute.
159#[derive(Debug, Clone, PartialEq)]
160pub struct Sha1HexAttribute(Hash);
161
162impl FromStr for Sha1HexAttribute {
163    type Err = ParseIntError;
164
165    fn from_str(hex: &str) -> Result<Self, Self::Err> {
166        let hash = Hash::from_hex(Algo::Sha_1, hex)?;
167        Ok(Sha1HexAttribute(hash))
168    }
169}
170
171impl IntoAttributeValue for Sha1HexAttribute {
172    fn into_attribute_value(self) -> Option<String> {
173        Some(self.to_hex())
174    }
175}
176
177impl DerefMut for Sha1HexAttribute {
178    fn deref_mut(&mut self) -> &mut Self::Target {
179        &mut self.0
180    }
181}
182
183impl Deref for Sha1HexAttribute {
184    type Target = Hash;
185
186    fn deref(&self) -> &Self::Target {
187        &self.0
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::Element;
195    use std::convert::TryFrom;
196
197    #[cfg(target_pointer_width = "32")]
198    #[test]
199    fn test_size() {
200        assert_size!(Algo, 16);
201        assert_size!(Hash, 28);
202    }
203
204    #[cfg(target_pointer_width = "64")]
205    #[test]
206    fn test_size() {
207        assert_size!(Algo, 32);
208        assert_size!(Hash, 56);
209    }
210
211    #[test]
212    fn test_simple() {
213        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
214        let hash = Hash::try_from(elem).unwrap();
215        assert_eq!(hash.algo, Algo::Sha_256);
216        assert_eq!(
217            hash.hash,
218            base64::decode("2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=").unwrap()
219        );
220    }
221
222    #[test]
223    fn value_serialisation() {
224        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=</hash>".parse().unwrap();
225        let hash = Hash::try_from(elem).unwrap();
226        assert_eq!(hash.to_base64(), "2XarmwTlNxDAMkvymloX3S5+VbylNrJt/l5QyPa+YoU=");
227        assert_eq!(hash.to_hex(), "d976ab9b04e53710c0324bf29a5a17dd2e7e55bca536b26dfe5e50c8f6be6285");
228        assert_eq!(hash.to_colon_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");
229    }
230
231    #[test]
232    fn test_unknown() {
233        let elem: Element = "<replace xmlns='urn:xmpp:message-correct:0'/>"
234            .parse()
235            .unwrap();
236        let error = Hash::try_from(elem).unwrap_err();
237        let message = match error {
238            Error::ParseError(string) => string,
239            _ => panic!(),
240        };
241        assert_eq!(message, "This is not a hash element.");
242    }
243
244    #[test]
245    fn test_invalid_child() {
246        let elem: Element = "<hash xmlns='urn:xmpp:hashes:2'><coucou/></hash>"
247            .parse()
248            .unwrap();
249        let error = Hash::try_from(elem).unwrap_err();
250        let message = match error {
251            Error::ParseError(string) => string,
252            _ => panic!(),
253        };
254        assert_eq!(message, "Unknown child in hash element.");
255    }
256}