• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2011 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 <fcntl.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15 
16 #include "cryptolib.h"
17 #include "file_keys.h"
18 #include "host_common.h"
19 #include "signature_digest.h"
20 
BufferFromFile(const char * input_file,uint64_t * len)21 uint8_t* BufferFromFile(const char* input_file, uint64_t* len) {
22   int fd;
23   struct stat stat_fd;
24   uint8_t* buf = NULL;
25 
26   if ((fd = open(input_file, O_RDONLY)) == -1) {
27     VBDEBUG(("Couldn't open file %s\n", input_file));
28     return NULL;
29   }
30 
31   if (-1 == fstat(fd, &stat_fd)) {
32     VBDEBUG(("Couldn't stat file %s\n", input_file));
33     return NULL;
34   }
35   *len = stat_fd.st_size;
36 
37   buf = (uint8_t*)malloc(*len);
38   if (!buf) {
39     VbExError("Couldn't allocate %ld bytes for file %s\n", *len, input_file);
40     return NULL;
41   }
42 
43   if (*len != read(fd, buf, *len)) {
44     VBDEBUG(("Couldn't read file %s into a buffer\n", input_file));
45     return NULL;
46   }
47 
48   close(fd);
49   return buf;
50 }
51 
RSAPublicKeyFromFile(const char * input_file)52 RSAPublicKey* RSAPublicKeyFromFile(const char* input_file) {
53   uint64_t len;
54   RSAPublicKey* key = NULL;
55   uint8_t* buf = BufferFromFile(input_file, &len);
56   if (buf)
57     key = RSAPublicKeyFromBuf(buf, len);
58   free(buf);
59   return key;
60 }
61 
DigestFile(char * input_file,int sig_algorithm)62 uint8_t* DigestFile(char* input_file, int sig_algorithm) {
63   int input_fd, len;
64   uint8_t data[SHA1_BLOCK_SIZE];
65   uint8_t* digest = NULL;
66   DigestContext ctx;
67 
68   if( (input_fd = open(input_file, O_RDONLY)) == -1 ) {
69     VBDEBUG(("Couldn't open %s\n", input_file));
70     return NULL;
71   }
72   DigestInit(&ctx, sig_algorithm);
73   while ( (len = read(input_fd, data, SHA1_BLOCK_SIZE)) ==
74           SHA1_BLOCK_SIZE)
75     DigestUpdate(&ctx, data, len);
76   if (len != -1)
77     DigestUpdate(&ctx, data, len);
78   digest = DigestFinal(&ctx);
79   close(input_fd);
80   return digest;
81 }
82