1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include <stddef.h>
16 #include <stdint.h>
17 #include <string.h>
18
19 #include "dice/cbor_writer.h"
20 #include "dice/ops/trait/cose.h"
21
22 #if DICE_PUBLIC_KEY_SIZE != 32
23 #error "Only Ed25519 is supported; 32 bytes needed to store the public key."
24 #endif
25 #if DICE_SIGNATURE_SIZE != 64
26 #error "Only Ed25519 is supported; 64 bytes needed to store the signature."
27 #endif
28
DiceCoseEncodePublicKey(void * context_not_used,const uint8_t public_key[DICE_PUBLIC_KEY_SIZE],size_t buffer_size,uint8_t * buffer,size_t * encoded_size)29 DiceResult DiceCoseEncodePublicKey(
30 void* context_not_used, const uint8_t public_key[DICE_PUBLIC_KEY_SIZE],
31 size_t buffer_size, uint8_t* buffer, size_t* encoded_size) {
32 (void)context_not_used;
33
34 // Constants per RFC 8152.
35 const int64_t kCoseKeyKtyLabel = 1;
36 const int64_t kCoseKeyAlgLabel = 3;
37 const int64_t kCoseKeyOpsLabel = 4;
38 const int64_t kCoseOkpCrvLabel = -1;
39 const int64_t kCoseOkpXLabel = -2;
40 const int64_t kCoseKeyTypeOkp = 1;
41 const int64_t kCoseAlgEdDSA = DICE_COSE_KEY_ALG_VALUE;
42 const int64_t kCoseKeyOpsVerify = 2;
43 const int64_t kCoseCrvEd25519 = 6;
44
45 struct CborOut out;
46 CborOutInit(buffer, buffer_size, &out);
47 CborWriteMap(/*num_pairs=*/5, &out);
48 // Add the key type.
49 CborWriteInt(kCoseKeyKtyLabel, &out);
50 CborWriteInt(kCoseKeyTypeOkp, &out);
51 // Add the algorithm.
52 CborWriteInt(kCoseKeyAlgLabel, &out);
53 CborWriteInt(kCoseAlgEdDSA, &out);
54 // Add the KeyOps.
55 CborWriteInt(kCoseKeyOpsLabel, &out);
56 CborWriteArray(/*num_elements=*/1, &out);
57 CborWriteInt(kCoseKeyOpsVerify, &out);
58 // Add the curve.
59 CborWriteInt(kCoseOkpCrvLabel, &out);
60 CborWriteInt(kCoseCrvEd25519, &out);
61 // Add the public key.
62 CborWriteInt(kCoseOkpXLabel, &out);
63 CborWriteBstr(/*data_size=*/DICE_PUBLIC_KEY_SIZE, public_key, &out);
64
65 *encoded_size = CborOutSize(&out);
66 if (CborOutOverflowed(&out)) {
67 return kDiceResultBufferTooSmall;
68 }
69 return kDiceResultOk;
70 }
71