blob: f6c62c75cb727e6d73ed15b00d0fe42c9c534265 [file] [log] [blame]
Thomas Fossati5ebf4832024-08-26 09:30:05 +00001#!/usr/bin/env python3
2# -----------------------------------------------------------------------------
3# Copyright (c) 2024, Linaro Limited. All rights reserved.
4#
5# SPDX-License-Identifier: BSD-3-Clause
6#
7# -----------------------------------------------------------------------------
8
9"""
10Convert a PEM key into an equivalent COSE_Key, and optionally compute the CCA hash-lock claims
11
12Examples:
13 ./pem2cose.py -h
14 ./pem2cose.py ../tests/data/cca_realm.pem cca_realm.cbor
15 ./pem2cose.py --hash-alg sha-256 ../tests/data/cca_realm.pem - > hashlock-claims.yaml
16
17"""
18import argparse
19
20from iatverifier.util import read_keyfile
21from iatverifier.attest_token_verifier import AttestationTokenVerifier
22from hashlib import sha256, sha384, sha512
23from base64 import b64encode
24
25hash_algorithms = {
26 'sha-256': sha256,
27 'sha-384': sha384,
28 'sha-512': sha512,
29}
30
31if __name__ == '__main__':
32 parser = argparse.ArgumentParser(
33 description='convert a PEM key into an equivalent COSE_Key; optionally compute the CCA hash-lock claims')
34
35 parser.add_argument('pemfile', type=str, help='input PEM file')
36 parser.add_argument(
37 'cosefile', type=str, help='output COSE_Key file (pass "-" to write to stdout)')
38 parser.add_argument('--hash-alg', type=str, help='compute the hash lock using the specified algorithm',
39 choices=hash_algorithms.keys())
40
41 args = parser.parse_args()
42
43 cose_key = read_keyfile(
44 args.pemfile, AttestationTokenVerifier.SIGN_METHOD_SIGN1).encode()
45
46 if args.cosefile == '-':
47 b64_cose_key = b64encode(cose_key).decode()
48 print(f'cca_realm_pub_key: !!binary {b64_cose_key}')
49 else:
50 with open(args.cosefile, 'wb') as f:
51 f.write(cose_key)
52
53 if args.hash_alg is not None:
54 h = hash_algorithms[args.hash_alg]()
55 h.update(cose_key)
56 b64_hash_lock = b64encode(h.digest()).decode()
57 print(f'cca_platform_challenge: !!binary {b64_hash_lock}')
58 print(f'cca_realm_pub_key_hash_algo_id: {args.hash_alg}')