blob: ebd5b70741e2f91def6c3da41c313757de39b42d [file] [log] [blame]
Thai Duong7689ed62015-03-20 16:50:18 -07001/*
2 * Copyright 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef SYSTEM_KEYMASTER_HMAC_H_
18#define SYSTEM_KEYMASTER_HMAC_H_
19
20#include <keymaster/serializable.h>
21
22namespace keymaster {
23
Thai Duong7689ed62015-03-20 16:50:18 -070024// Only HMAC-SHA256 is supported.
25class HmacSha256 {
26 public:
Thai Duong60eebdc2015-03-25 17:20:24 -070027 HmacSha256(){};
Thai Duong7689ed62015-03-20 16:50:18 -070028
29 // DigestLength returns the length, in bytes, of the resulting digest.
30 size_t DigestLength() const;
31
32 // Initializes this instance using |key|. Call Init only once. It returns
33 // false on the second of later calls.
34 bool Init(const uint8_t* key, size_t key_length);
35 bool Init(const Buffer& key);
36
37 // Sign calculates the HMAC of |data| with the key supplied to the Init
38 // method. At most |digest_len| bytes of the resulting digest are written
39 // to |digest|.
40 bool Sign(const Buffer& data, uint8_t* digest, size_t digest_len) const;
41 bool Sign(const uint8_t* data, size_t data_len, uint8_t* digest, size_t digest_len) const;
42
43 // Verify returns true if |digest| is a valid HMAC of |data| using the key
44 // supplied to Init. |digest| must be exactly |DigestLength()| bytes long.
45 // Use of this method is strongly recommended over using Sign() with a manual
46 // comparison (such as memcmp), as such comparisons may result in
47 // side-channel disclosures, such as timing, that undermine the cryptographic
48 // integrity.
49 bool Verify(const Buffer& data, const Buffer& digest) const;
50 bool Verify(const uint8_t* data, size_t data_len, const uint8_t* digest,
51 size_t digest_len) const;
52
53 private:
Thai Duong60eebdc2015-03-25 17:20:24 -070054 UniquePtr<uint8_t[]> key_;
55 size_t key_len_;
Thai Duong7689ed62015-03-20 16:50:18 -070056};
57
58} // namespace keymaster
59
60#endif // SYSTEM_KEYMASTER_HMAC_H_