blob: eb9e2caab0ae8fdef4f614f14c8360b9b9eaa39a [file] [log] [blame]
Shawn Willden8ba2a042015-05-18 08:35:28 -06001/*
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#include "auth_encrypted_key_blob.h"
18
19#include <keymaster/android_keymaster_utils.h>
20#include <keymaster/authorization_set.h>
21#include <keymaster/logger.h>
22
23#include "ocb_utils.h"
24
25namespace keymaster {
26
27const uint32_t CURRENT_BLOB_VERSION = 0;
28
29keymaster_error_t SerializeAuthEncryptedBlob(const KeymasterKeyBlob& encrypted_key_material,
30 const AuthorizationSet& hw_enforced,
31 const AuthorizationSet& sw_enforced,
32
33 const Buffer& nonce, const Buffer& tag,
34 KeymasterKeyBlob* key_blob) {
35 size_t size = 1 /* version byte */ + nonce.SerializedSize() +
36 encrypted_key_material.SerializedSize() + tag.SerializedSize() +
37 hw_enforced.SerializedSize() + sw_enforced.SerializedSize();
38
39 if (!key_blob->Reset(size))
40 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
41
42 uint8_t* buf = key_blob->writable_data();
43 const uint8_t* end = key_blob->key_material + key_blob->key_material_size;
44
45 *buf++ = CURRENT_BLOB_VERSION;
46 buf = nonce.Serialize(buf, end);
47 buf = encrypted_key_material.Serialize(buf, end);
48 buf = tag.Serialize(buf, end);
49 buf = hw_enforced.Serialize(buf, end);
50 buf = sw_enforced.Serialize(buf, end);
51 if (buf != key_blob->key_material + key_blob->key_material_size)
52 return KM_ERROR_UNKNOWN_ERROR;
53
54 return KM_ERROR_OK;
55}
56
57keymaster_error_t DeserializeAuthEncryptedBlob(const KeymasterKeyBlob& key_blob,
58 KeymasterKeyBlob* encrypted_key_material,
59 AuthorizationSet* hw_enforced,
60 AuthorizationSet* sw_enforced, Buffer* nonce,
61 Buffer* tag) {
62 const uint8_t* tmp = key_blob.key_material;
63 const uint8_t** buf_ptr = &tmp;
64 const uint8_t* end = tmp + key_blob.key_material_size;
65
66 uint8_t version = *(*buf_ptr)++;
67 if (version != CURRENT_BLOB_VERSION || //
68 !nonce->Deserialize(buf_ptr, end) || nonce->available_read() != OCB_NONCE_LENGTH ||
69 !encrypted_key_material->Deserialize(buf_ptr, end) || //
70 !tag->Deserialize(buf_ptr, end) || tag->available_read() != OCB_TAG_LENGTH ||
71 !hw_enforced->Deserialize(buf_ptr, end) || //
72 !sw_enforced->Deserialize(buf_ptr, end))
73 return KM_ERROR_INVALID_KEY_BLOB;
74 return KM_ERROR_OK;
75}
76
77} // namespace keymaster