1/*
2 * Measure performance of SHA using raw CommonCrypto digests.
3 * Use hashTime to measure performance thru the CSP.
4 */
5
6#include <stdlib.h>
7#include <stdio.h>
8#include <strings.h>
9#include <CommonCrypto/CommonDigest.h>
10#include "cputime.h"
11#include "common.h"
12
13static void usage(char **argv)
14{
15	printf("Usage: %s bytecount [q(uiet)]\n", argv[0]);
16	exit(1);
17}
18
19#define BUFSIZE		(8 * 1024)
20
21int main(int argc, char **argv)
22{
23	bool quiet = false;
24	unsigned byteCount;
25
26	if(argc < 2) {
27		usage(argv);
28	}
29	byteCount = atoi(argv[1]);
30	for(int arg=2; arg<argc; arg++) {
31		switch(argv[arg][0]) {
32			case 'q':
33				quiet = true;
34				break;
35			default:
36				usage(argv);
37		}
38	}
39
40	unsigned char *text = (unsigned char *)malloc(BUFSIZE);
41	appGetRandomBytes(text, BUFSIZE);
42
43	unsigned	toMove = byteCount;
44	unsigned	thisMove;
45	CPUTime		startTime;
46	double		timeSpentMs;
47
48	if(!quiet) {
49		printf("...testing SHA1\n");
50	}
51
52	CC_SHA1_CTX ctx1;
53	unsigned char dig1[CC_SHA1_DIGEST_LENGTH];
54
55	CC_SHA1_Init(&ctx1);
56
57	/* start critical timing loop */
58	startTime = CPUTimeRead();
59	do {
60		if(toMove > BUFSIZE) {
61			thisMove = BUFSIZE;
62		}
63		else {
64			thisMove = toMove;
65		}
66		toMove -= thisMove;
67		CC_SHA1_Update(&ctx1, text, thisMove);
68	} while(toMove);
69	CC_SHA1_Final(dig1, &ctx1);
70	timeSpentMs = CPUTimeDeltaMs(startTime, CPUTimeRead());
71	printf("SHA1: Digest %u bytes : %.2f ms\n", byteCount, timeSpentMs);
72
73	/* SHA256 */
74	if(!quiet) {
75		printf("...testing SHA256\n");
76	}
77
78	CC_SHA256_CTX ctx256;
79	unsigned char dig256[CC_SHA256_DIGEST_LENGTH];
80	toMove = byteCount;
81	CC_SHA256_Init(&ctx256);
82
83	/* start critical timing loop */
84	startTime = CPUTimeRead();
85	do {
86		if(toMove > BUFSIZE) {
87			thisMove = BUFSIZE;
88		}
89		else {
90			thisMove = toMove;
91		}
92		toMove -= thisMove;
93		CC_SHA256_Update(&ctx256, text, thisMove);
94	} while(toMove);
95	CC_SHA256_Final(dig256, &ctx256);
96	timeSpentMs = CPUTimeDeltaMs(startTime, CPUTimeRead());
97	printf("SHA256: Digest %u bytes : %.2f ms\n", byteCount, timeSpentMs);
98
99	/* SHA256 */
100	if(!quiet) {
101		printf("...testing SHA512\n");
102	}
103
104	CC_SHA512_CTX ctx512;
105	unsigned char dig512[CC_SHA512_DIGEST_LENGTH];
106	toMove = byteCount;
107	CC_SHA512_Init(&ctx512);
108
109	/* start critical timing loop */
110	startTime = CPUTimeRead();
111	do {
112		if(toMove > BUFSIZE) {
113			thisMove = BUFSIZE;
114		}
115		else {
116			thisMove = toMove;
117		}
118		toMove -= thisMove;
119		CC_SHA512_Update(&ctx512, text, thisMove);
120	} while(toMove);
121	CC_SHA512_Final(dig512, &ctx512);
122	timeSpentMs = CPUTimeDeltaMs(startTime, CPUTimeRead());
123	printf("SHA512: Digest %u bytes : %.2f ms\n", byteCount, timeSpentMs);
124
125	return 0;
126}
127