crypto/mac.rs
1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7/*!
8 * The mac module defines the Message Authentication Code (Mac) trait.
9 */
10
11use util::fixed_time_eq;
12
13/**
14 * The Mac trait defines methods for a Message Authentication function.
15 */
16pub trait Mac {
17 /**
18 * Process input data.
19 *
20 * # Arguments
21 * * data - The input data to process.
22 *
23 */
24 fn input(&mut self, data: &[u8]);
25
26 /**
27 * Reset the Mac state to begin processing another input stream.
28 */
29 fn reset(&mut self);
30
31 /**
32 * Obtain the result of a Mac computation as a MacResult.
33 */
34 fn result(&mut self) -> MacResult;
35
36 /**
37 * Obtain the result of a Mac computation as [u8]. This method should be used very carefully
38 * since incorrect use of the Mac code could result in permitting a timing attack which defeats
39 * the security provided by a Mac function.
40 */
41 fn raw_result(&mut self, output: &mut [u8]);
42
43 /**
44 * Get the size of the Mac code, in bytes.
45 */
46 fn output_bytes(&self) -> usize;
47}
48
49/**
50 * A MacResult wraps a Mac code and provides a safe Eq implementation that runs in fixed time.
51 */
52pub struct MacResult {
53 code: Vec<u8>
54}
55
56impl MacResult {
57 /**
58 * Create a new MacResult.
59 */
60 pub fn new(code: &[u8]) -> MacResult {
61 MacResult {
62 code: code.to_vec()
63 }
64 }
65
66 /**
67 * Create a new MacResult taking ownership of the specified code value.
68 */
69 pub fn new_from_owned(code: Vec<u8>) -> MacResult {
70 MacResult {
71 code: code
72 }
73 }
74
75 /**
76 * Get the code value. Be very careful using this method, since incorrect use of the code value
77 * may permit timing attacks which defeat the security provided by the Mac function.
78 */
79 pub fn code<'s>(&'s self) -> &'s [u8] {
80 &self.code[..]
81 }
82}
83
84impl PartialEq for MacResult {
85 fn eq(&self, x: &MacResult) -> bool {
86 let lhs = self.code();
87 let rhs = x.code();
88 fixed_time_eq(lhs, rhs)
89 }
90}
91
92impl Eq for MacResult { }