]> git.saurik.com Git - apple/security.git/blob - Security/sec/SecurityTool/digest_calc.c
Security-57031.40.6.tar.gz
[apple/security.git] / Security / sec / SecurityTool / 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/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 2; /* Return 2 triggers 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 2; /* Return 2 triggers usage message. */
68
69 ccdigest_di_decl(di, ctx);
70 ccdigest_init(di, ctx);
71
72 digest = malloc(di->output_size);
73 require_quiet(digest, exit);
74
75 for (i = 2; i < (unsigned int)argc; ++i)
76 {
77 printf("%s(%s)= ", argv[1], argv[i]);
78 if ((fd = inspect_file_and_size(argv[i], NULL)) == -1)
79 {
80 printf("error reading file\n");
81 continue;
82 }
83 totalBytes = 0;
84 while((nr = pread(fd, data, sizeof(data), totalBytes)) > 0){
85 ccdigest_update(di, ctx, nr, data);
86 totalBytes += nr;
87 }
88
89 ccdigest_final(di, ctx, digest);
90
91 for (j = 0; j < di->output_size; j++)
92 printf("%02x", digest[j]);
93 printf("\n");
94 }
95 result = 0;
96
97 exit:
98 if (digest)
99 free(digest);
100
101 return result;
102 }