1 /*
2 * Copyright (C) 2012 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 <stdint.h>
18 #include <string.h>
19 #include <sys/types.h>
20 #include <unistd.h>
21
22 #include <keystore/keystore.h>
23
24 /**
25 * When a key is being migrated from a software keymaster implementation
26 * to a hardware keymaster implementation, the first 4 bytes of the key_blob
27 * given to the hardware implementation will be equal to SOFT_KEY_MAGIC.
28 * The hardware implementation should import these PKCS#8 format keys which
29 * are encoded like this:
30 *
31 * 4-byte SOFT_KEY_MAGIC
32 *
33 * 4-byte 32-bit integer big endian for public_key_length. This may be zero
34 * length which indicates the public key should be derived from the
35 * private key.
36 *
37 * public_key_length bytes of public key (may be empty)
38 *
39 * 4-byte 32-bit integer big endian for private_key_length
40 *
41 * private_key_length bytes of private key
42 */
43 static const uint8_t SOFT_KEY_MAGIC[] = { 'P', 'K', '#', '8' };
44
get_softkey_header_size()45 size_t get_softkey_header_size() {
46 return sizeof(SOFT_KEY_MAGIC);
47 }
48
add_softkey_header(uint8_t * key_blob,size_t key_blob_length)49 uint8_t* add_softkey_header(uint8_t* key_blob, size_t key_blob_length) {
50 if (key_blob_length < sizeof(SOFT_KEY_MAGIC)) {
51 return nullptr;
52 }
53
54 memcpy(key_blob, SOFT_KEY_MAGIC, sizeof(SOFT_KEY_MAGIC));
55
56 return key_blob + sizeof(SOFT_KEY_MAGIC);
57 }
58
is_softkey(const uint8_t * key_blob,const size_t key_blob_length)59 bool is_softkey(const uint8_t* key_blob, const size_t key_blob_length) {
60 if (key_blob_length < sizeof(SOFT_KEY_MAGIC)) {
61 return false;
62 }
63
64 return !memcmp(key_blob, SOFT_KEY_MAGIC, sizeof(SOFT_KEY_MAGIC));
65 }
66