blob: bcba749a4bb92c1d629959db629a3138d5d07453 [file] [log] [blame]
Gaurav Shah431b9882010-02-12 15:54:37 -08001/* Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
4 *
5 * Utility functions for file and key handling.
6 */
7
8#include "file_keys.h"
9
10#include <fcntl.h>
11#include <stdio.h>
12#include <stdlib.h>
13#include <string.h>
14#include <sys/stat.h>
15#include <sys/types.h>
16#include <unistd.h>
17
Gaurav Shah08df9b82010-02-23 16:16:23 -080018#include "padding.h"
Gaurav Shah431b9882010-02-12 15:54:37 -080019#include "rsa_utility.h"
20#include "utility.h"
21
22uint8_t* BufferFromFile(char* input_file, int* len) {
23 int fd;
24 struct stat stat_fd;
25 uint8_t* buf = NULL;
26
27 if ((fd = open(input_file, O_RDONLY)) == -1) {
28 fprintf(stderr, "Couldn't open file.\n");
29 return NULL;
30 }
31
32 if (-1 == fstat(fd, &stat_fd)) {
33 fprintf(stderr, "Couldn't stat key file\n");
34 return NULL;
35 }
36 *len = stat_fd.st_size;
37
38 /* Read entire key binary blob into a buffer. */
39 buf = (uint8_t*) Malloc(*len);
40 if (!buf)
41 return NULL;
42
43 if (*len != read(fd, buf, *len)) {
44 fprintf(stderr, "Couldn't read key into a buffer.\n");
45 return NULL;
46 }
47
48 close(fd);
49 return buf;
50}
51
52RSAPublicKey* RSAPublicKeyFromFile(char* input_file) {
53 int len;
54 uint8_t* buf = BufferFromFile(input_file, &len);
55 RSAPublicKey* key = RSAPublicKeyFromBuf(buf, len);
56 Free(buf);
57 return key;
58}
Gaurav Shah08df9b82010-02-23 16:16:23 -080059
60uint8_t* SignatureFile(char* input_file, char* key_file, int algorithm) {
61 char* sign_utility = "./sign_data.sh";
62 char* cmd; /* Command line to invoke. */
63 int cmd_len;
64 FILE* cmd_out; /* File descriptor to command output. */
65 uint8_t* signature = NULL;
66 int signature_size = siglen_map[algorithm] * sizeof(uint32_t);
67
68 /* Build command line:
69 * sign_data.sh <algorithm> <key file> <input file>
70 */
71 cmd_len = (strlen(sign_utility) + 1 + /* +1 for space. */
72 2 + 1 + /* For [algorithm]. */
73 strlen(key_file) + 1 + /* +1 for space. */
74 strlen(input_file) +
75 1); /* For the trailing '\0'. */
76 cmd = (char*) Malloc(cmd_len);
77 snprintf(cmd, cmd_len, "%s %d %s %s", sign_utility, algorithm, key_file,
78 input_file);
79 cmd_out = popen(cmd, "r");
80 Free(cmd);
81 if (!cmd_out) {
82 fprintf(stderr, "Couldn't execute: %s\n", cmd);
83 return NULL;
84 }
85
86 signature = (uint8_t*) Malloc(signature_size);
87 if (fread(signature, signature_size, 1, cmd_out) != 1) {
88 fprintf(stderr, "Couldn't read signature.\n");
89 pclose(cmd_out);
90 Free(signature);
91 return NULL;
92 }
93
94 pclose(cmd_out);
95 return signature;
96}