crypto/
digest.rs

1// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11use std::iter::repeat;
12
13/**
14 * The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
15 * family of digest functions.
16 */
17pub trait Digest {
18    /**
19     * Provide message data.
20     *
21     * # Arguments
22     *
23     * * input - A vector of message data
24     */
25    fn input(&mut self, input: &[u8]);
26
27    /**
28     * Retrieve the digest result. This method may be called multiple times.
29     *
30     * # Arguments
31     *
32     * * out - the vector to hold the result. Must be large enough to contain output_bits().
33     */
34    fn result(&mut self, out: &mut [u8]);
35
36    /**
37     * Reset the digest. This method must be called after result() and before supplying more
38     * data.
39     */
40    fn reset(&mut self);
41
42    /**
43     * Get the output size in bits.
44     */
45    fn output_bits(&self) -> usize;
46
47    /**
48     * Get the output size in bytes.
49     */
50    fn output_bytes(&self) -> usize {
51        (self.output_bits() + 7) / 8
52    }
53
54    /**
55     * Get the block size in bytes.
56     */
57    fn block_size(&self) -> usize;
58
59    /**
60     * Convenience function that feeds a string into a digest.
61     *
62     * # Arguments
63     *
64     * * `input` The string to feed into the digest
65     */
66    fn input_str(&mut self, input: &str) {
67        self.input(input.as_bytes());
68    }
69
70    /**
71     * Convenience function that retrieves the result of a digest as a
72     * String in hexadecimal format.
73     */
74    fn result_str(&mut self) -> String {
75        use serialize::hex::ToHex;
76
77        let mut buf: Vec<u8> = repeat(0).take((self.output_bits()+7)/8).collect();
78        self.result(&mut buf);
79        buf[..].to_hex()
80    }
81}