]> git.saurik.com Git - apple/security.git/blob - SecurityTool/sharedTool/digest_calc.c
Security-59306.11.20.tar.gz
[apple/security.git] / SecurityTool / sharedTool / digest_calc.c
1 /*
2 * Copyright (c) 2011,2013-2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24
25 #include "builtin_commands.h"
26
27 #include <stdlib.h>
28 #include <strings.h>
29 #include <unistd.h>
30
31 #include "SecurityTool/sharedTool/readline.h"
32
33 #include <corecrypto/ccsha1.h>
34 #include <corecrypto/ccsha2.h>
35
36 #include <AssertMacros.h>
37
38 extern int command_digest(int argc, char * const *argv)
39 {
40 int result = 1, fd;
41 const struct ccdigest_info *di;
42 unsigned char *digest = NULL;
43 unsigned long i,j;
44 size_t nr = 0, totalBytes = 0;
45 char data [getpagesize()];
46
47 if (argc < 3)
48 return SHOW_USAGE_MESSAGE;
49
50 if (strcasecmp("sha1", argv[1]) == 0)
51 {
52 //printf("Calculating sha1\n");
53 di = ccsha1_di();
54 }
55 else if (strcasecmp("sha256", argv[1]) == 0)
56 {
57 //printf("Calculating sha256\n");
58 di = ccsha256_di();
59 }
60 else if (strcasecmp("sha512", argv[1]) == 0)
61 {
62 //printf("Calculating sha256\n");
63 di = ccsha512_di();
64
65 }
66 else
67 return SHOW_USAGE_MESSAGE;
68
69 ccdigest_di_decl(di, ctx);
70
71 digest = malloc(di->output_size);
72 require_quiet(digest, exit);
73
74 for (i = 2; i < (unsigned int)argc; ++i)
75 {
76 printf("%s(%s)= ", argv[1], argv[i]);
77 if ((fd = inspect_file_and_size(argv[i], NULL)) == -1)
78 {
79 printf("error reading file\n");
80 continue;
81 }
82
83 ccdigest_init(di, ctx);
84
85 totalBytes = 0;
86 while((nr = pread(fd, data, sizeof(data), totalBytes)) > 0){
87 ccdigest_update(di, ctx, nr, data);
88 totalBytes += nr;
89 }
90
91 ccdigest_final(di, ctx, digest);
92
93 for (j = 0; j < di->output_size; j++)
94 printf("%02x", digest[j]);
95 printf("\n");
96 }
97 result = 0;
98
99 exit:
100 if (digest)
101 free(digest);
102
103 return result;
104 }