1 /* 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 22 namespace keymaster { 23 24 // Only HMAC-SHA256 is supported. 25 class HmacSha256 { 26 public: HmacSha256()27 HmacSha256(){}; 28 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: 54 UniquePtr<uint8_t[]> key_; 55 size_t key_len_; 56 }; 57 58 } // namespace keymaster 59 60 #endif // SYSTEM_KEYMASTER_HMAC_H_ 61