xref: /aosp_15_r20/external/vboot_reference/utility/pad_digest_utility.c (revision 8617a60d3594060b7ecbd21bc622a7c14f3cf2bc)
1 /* Copyright 2011 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 
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 
11 #include "2common.h"
12 #include "2sha.h"
13 #include "2sysincludes.h"
14 #include "host_common.h"
15 #include "host_signature21.h"
16 #include "signature_digest.h"
17 
usage(char * argv[])18 static void usage(char* argv[]) {
19 	fprintf(stderr,
20 		"Usage: %s <alg_id> <digest_file>\n"
21 		"\n"
22 		"Generate a padded hash suitable for generating PKCS#1.5 "
23 		"signatures.\n",
24 		basename(argv[0]));
25 }
26 
main(int argc,char * argv[])27 int main(int argc, char* argv[])
28 {
29 	int algorithm = -1;
30 	int error_code = -1;
31 	uint8_t* digest = NULL;
32 	uint8_t* padded_digest = NULL;
33 	uint32_t len;
34 
35 	if (argc != 3) {
36 		usage(argv);
37 		goto cleanup;
38 	}
39 	algorithm = atoi(argv[1]);
40 	if (algorithm < 0 || algorithm >= VB2_ALG_COUNT) {
41 		fprintf(stderr, "Invalid Algorithm!\n");
42 		goto cleanup;
43 	}
44 
45 	enum vb2_hash_algorithm hash_alg = vb2_crypto_to_hash(algorithm);
46 	uint32_t digest_size = vb2_digest_size(hash_alg);
47 	uint32_t digestinfo_size = 0;
48 	const uint8_t* digestinfo = NULL;
49 	if (VB2_SUCCESS != vb2_digest_info(hash_alg, &digestinfo,
50 					   &digestinfo_size)) {
51 		fprintf(stderr, "SignatureBuf(): Couldn't get digest info\n");
52 		goto cleanup;
53 	}
54 	uint32_t padded_digest_len = digest_size + digestinfo_size;
55 
56 	if (VB2_SUCCESS != vb2_read_file(argv[2], &digest, &len)) {
57 		fprintf(stderr, "Could not read file: %s\n", argv[2]);
58 		goto cleanup;
59 	}
60 
61 	padded_digest = PrependDigestInfo(hash_alg, digest);
62 	if (padded_digest &&
63 	   fwrite(padded_digest, padded_digest_len, 1, stdout) == 1)
64 		error_code = 0;
65 
66 cleanup:
67 	free(padded_digest);
68 	free(digest);
69 	return error_code;
70 }
71