(index<- ) ./libextra/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
11 use std::vec;
12
13
14 /**
15 * The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
16 * family of digest functions.
17 */
18 pub trait Digest {
19 /**
20 * Provide message data.
21 *
22 * # Arguments
23 *
24 * * input - A vector of message data
25 */
26 fn input(&mut self, input: &[u8]);
27
28 /**
29 * Retrieve the digest result. This method may be called multiple times.
30 *
31 * # Arguments
32 *
33 * * out - the vector to hold the result. Must be large enough to contain output_bits().
34 */
35 fn result(&mut self, out: &mut [u8]);
36
37 /**
38 * Reset the digest. This method must be called after result() and before supplying more
39 * data.
40 */
41 fn reset(&mut self);
42
43 /**
44 * Get the output size in bits.
45 */
46 fn output_bits(&self) -> uint;
47
48 /**
49 * Convenience function that feeds a string into a digest.
50 *
51 * # Arguments
52 *
53 * * `input` The string to feed into the digest
54 */
55 fn input_str(&mut self, input: &str) {
56 self.input(input.as_bytes());
57 }
58
59 /**
60 * Convenience function that retrieves the result of a digest as a
61 * ~str in hexadecimal format.
62 */
63 fn result_str(&mut self) -> ~str {
64 let mut buf = vec::from_elem((self.output_bits()+7)/8, 0u8);
65 self.result(buf);
66 return to_hex(buf);
67 }
68 }
69
70 fn to_hex(rr: &[u8]) -> ~str {
71 let mut s = ~"";
72 for b in rr.iter() {
73 let hex = (*b as uint).to_str_radix(16u);
74 if hex.len() == 1 {
75 s.push_char('0');
76 }
77 s.push_str(hex);
78 }
79 return s;
80 }