xref: /aosp_15_r20/external/vboot_reference/host/lib/crypto.c (revision 8617a60d3594060b7ecbd21bc622a7c14f3cf2bc)
1 /* Copyright 2020 The ChromiumOS Authors
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  */
5 
6 #include <stdlib.h>
7 #include <strings.h>
8 
9 #include "vboot_host.h"
10 
lookup_helper(const char * str,const char * table[],size_t size,unsigned int * out)11 static int lookup_helper(const char *str, const char *table[], size_t size,
12 			 unsigned int *out)
13 {
14 	unsigned int algo;
15 	char *e;
16 
17 	/* try string first */
18 	for (algo = 0; algo < size; algo++)
19 		if (table[algo] && !strcasecmp(table[algo], str))
20 			goto found;
21 
22 	/* fine, try number */
23 	algo = strtoul(str, &e, 0);
24 	if (!*str || (e && *e))
25 		/* that's not a number */
26 		return false;
27 	if (algo >= size || !table[algo])
28 		/* that's not a valid algorithm */
29 		return false;
30 
31  found:
32 	*out = algo;
33 	return true;
34 }
35 
vb2_lookup_sig_alg(const char * str,enum vb2_signature_algorithm * sig_alg)36 bool vb2_lookup_sig_alg(const char *str, enum vb2_signature_algorithm *sig_alg)
37 {
38 	return lookup_helper(str, vb2_sig_names, VB2_SIG_ALG_COUNT, sig_alg);
39 }
40 
vb2_lookup_hash_alg(const char * str,enum vb2_hash_algorithm * hash_alg)41 bool vb2_lookup_hash_alg(const char *str, enum vb2_hash_algorithm *hash_alg)
42 {
43 	return lookup_helper(str, vb2_hash_names, VB2_HASH_ALG_COUNT, hash_alg);
44 }
45