CommonCrypto for GNUstep
Check-in [46f9f7687d]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Update CommonCrypto from Apple's source code dump for Mac OS 10.8 (Mountain Lion, r60026)
Timelines: family | ancestors | Apple | r60026
Files: files | file ages | folders
SHA1: 46f9f7687d6de22bc98b71507ad6e88317003936
User & Date: thebeing 2012-08-11 11:27:40
Context
2012-08-11
11:27
Update CommonCrypto from Apple's source code dump for Mac OS 10.8 (Mountain Lion, r60026) Leaf check-in: 46f9f7687d user: thebeing tags: Apple, r60026
2012-03-08
13:39
Update CommonCrypto source to r55010 (from Mac OS X 10.7.3) check-in: 101e407fb2 user: thebeing tags: Apple, r55010
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Added CCRegression/CommonCrypto/CCCryptorTestFuncs.c.











































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
/*
 *  CCCryptorTestFuncs.c
 *  CCRegressions
 *
 *
 */


#include <stdio.h>
#include "CCCryptorTestFuncs.h"
#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"


CCCryptorStatus
CCCryptWithMode(CCOperation op, CCMode mode, CCAlgorithm alg, CCPadding padding, const void *iv, 
				const void *key, size_t keyLength, const void *tweak, size_t tweakLength,
                int numRounds, CCModeOptions options,
                const void *dataIn, size_t dataInLength, 
                void *dataOut, size_t dataOutAvailable, size_t *dataOutMoved)
#ifdef CRYPTORWITHMODE
{
    CCCryptorRef cref;
	CCCryptorStatus retval;
    size_t moved;

   	if((retval = CCCryptorCreateWithMode(op, mode, alg, padding, iv, key, keyLength, tweak, tweakLength, numRounds, options, &cref)) != kCCSuccess) {
    	return retval;
    }
    
    if((retval = CCCryptorUpdate(cref, dataIn, dataInLength, dataOut, dataOutAvailable, &moved)) != kCCSuccess) {
    	return retval;
    }
    
    dataOut += moved;
    dataOutAvailable -= moved;
    *dataOutMoved = moved;
    
    if((retval = CCCryptorFinal(cref, dataOut, dataOutAvailable, &moved)) != kCCSuccess) {
    	return retval;
    }
    
    *dataOutMoved += moved;

	CCCryptorRelease(cref);
    
    return kCCSuccess;
}
#else
{
    return kCCSuccess;
}
#endif



CCCryptorStatus 
CCMultiCrypt(CCOperation op, CCAlgorithm alg, CCOptions options, const void *key, size_t keyLength, const void *iv, const void *dataIn, size_t dataInLength,
	void *dataOut, size_t dataOutAvailable, size_t *dataOutMoved)
{
	CCCryptorRef cref;
    CCCryptorStatus retval;
    size_t p1, p2;
    size_t newmoved;
    size_t finalSize;
    
    retval = CCCryptorCreate(op, alg, options, key, keyLength, iv, &cref);
    if(retval != kCCSuccess) {
    	diag("Cryptor Create Failed\n");
    	return retval;
    }
    p1 = ( dataInLength / 16 ) * 16 - 1;
    if(p1 > 16) p1 = dataInLength;
    p2 = dataInLength - p1;
    // diag("Processing length %d  in two parts %d and %d\n", (int) dataInLength, (int) p1, (int) p2);
    
    *dataOutMoved = 0;
    
    if(p1) {
    	retval = CCCryptorUpdate(cref, dataIn, p1, dataOut, dataOutAvailable, dataOutMoved);
        if(retval) {
        	diag("P1 - Tried to move %d - failed retval = %d\n", (int) p1, (int) retval);
            return retval;
        }
        dataIn += p1;
        dataOut += *dataOutMoved;
        dataOutAvailable -= *dataOutMoved;        
    }
    if(p2) {
        
    	retval = CCCryptorUpdate(cref, dataIn, p2, dataOut, dataOutAvailable, &newmoved);
        if(retval) {
        	diag("P2 - Tried to move %d - failed\n", (int) p2);
            return retval;
        }
        dataIn += p2;
        dataOut += newmoved;        
        dataOutAvailable -= newmoved;
        *dataOutMoved += newmoved;
    }
    
    /* We've had reports that Final fails on some platforms if it's only cipher blocksize.  */
    switch(alg) {
    case kCCAlgorithmDES: /* fallthrough */
    case kCCAlgorithm3DES: finalSize = kCCBlockSizeDES; break;
    case kCCAlgorithmAES128: finalSize = kCCBlockSizeAES128; break;
    case kCCAlgorithmCAST: finalSize = kCCBlockSizeCAST; break;
    case kCCAlgorithmRC2: finalSize = kCCBlockSizeRC2; break;
    default: finalSize = dataOutAvailable;
    }
    
    retval = CCCryptorFinal(cref, dataOut, finalSize, &newmoved);
    if(retval) {
        diag("Final - failed %d\n", (int) retval);
        return retval;
    }
    retval = CCCryptorRelease(cref);
    if(retval) {
        diag("Final - release failed %d\n", (int) retval);
        return retval;
    }
    *dataOutMoved += newmoved;
    return kCCSuccess;
    
    
}

CCCryptorStatus 
CCMultiCryptWithMode(CCOperation op, CCMode mode, CCAlgorithm alg, CCPadding padding, const void *iv, 
	const void *key, size_t keyLength, const void *tweak, size_t tweakLength,
	int numRounds, CCModeOptions options,
    const void *dataIn, size_t dataInLength,
	void *dataOut, size_t dataOutAvailable, size_t *dataOutMoved)
#ifdef CRYPTORWITHMODE
{
	CCCryptorRef cref;
    CCCryptorStatus retval;
    size_t p1, p2;
    size_t newmoved;
    
   	if((retval = CCCryptorCreateWithMode(op, mode, alg, padding, iv, key, keyLength, tweak, tweakLength, numRounds, options, &cref)) != kCCSuccess) {
    	return retval;
    }
    p1 = ( dataInLength / 16 ) * 16 - 1;
    if(p1 > 16) p1 = dataInLength;
    p2 = dataInLength - p1;
    // diag("Processing length %d  in two parts %d and %d\n", (int) dataInLength, (int) p1, (int) p2);
    
    *dataOutMoved = 0;
    
    if(p1) {
    	retval = CCCryptorUpdate(cref, dataIn, p1, dataOut, dataOutAvailable, dataOutMoved);
        if(retval) {
        	diag("P1 - Tried to move %d - failed retval = %d\n", (int) p1, (int) retval);
            return retval;
        }
        dataIn += p1;
        dataOut += *dataOutMoved;
        dataOutAvailable -= *dataOutMoved;        
    }
    if(p2) {
        
    	retval = CCCryptorUpdate(cref, dataIn, p2, dataOut, dataOutAvailable, &newmoved);
        if(retval) {
        	diag("P2 - Tried to move %d - failed\n", (int) p2);
            return retval;
        }
        dataIn += p2;
        dataOut += newmoved;        
        dataOutAvailable -= newmoved;
        *dataOutMoved += newmoved;
    }
    retval = CCCryptorFinal(cref, dataOut, dataOutAvailable, &newmoved);
    if(retval) {
        diag("Final - failed %d\n", (int) retval);
        return retval;
    }
    retval = CCCryptorRelease(cref);
    if(retval) {
        diag("Final - release failed %d\n", (int) retval);
        return retval;
    }
    *dataOutMoved += newmoved;
    return kCCSuccess;
}
#else
{
    return kCCSuccess;
}
#endif


static byteBuffer
ccConditionalTextBuffer(char *inputText)
{
	byteBuffer ret;
    
    if(inputText) ret = hexStringToBytes(inputText);
    else {
    	ret = hexStringToBytes("");
        ret->bytes = NULL;
    }
    return ret;
}

int
CCCryptTestCase(char *keyStr, char *ivStr, CCAlgorithm alg, CCOptions options, char *cipherText, char *plainText)
{
    byteBuffer key, iv;
    byteBuffer pt, ct;
    
    
	CCCryptorStatus retval;
    char cipherDataOut[4096];
    char plainDataOut[4096];
    size_t dataOutMoved;
    byteBuffer bb;
            
    key = hexStringToBytes(keyStr);        
    pt = ccConditionalTextBuffer(plainText);
    ct = ccConditionalTextBuffer(cipherText);
    iv = ccConditionalTextBuffer(ivStr);
    
        
    if((retval = CCCrypt(kCCEncrypt, alg, options, key->bytes, key->len, iv->bytes, pt->bytes, pt->len, cipherDataOut, 4096, &dataOutMoved)) != kCCSuccess) {
    	diag("Encrypt Failed %d\n", retval);
        return 1;
    }
    
    bb = bytesToBytes(cipherDataOut, dataOutMoved);    	

    // If ct isn't defined we're gathering data - print the ciphertext result
    if(!ct->bytes) {
    	diag("Input Length %d Result: %s\n", (int) pt->len, bytesToHexString(bb));
    } else {
        if (!bytesAreEqual(ct, bb)) {
            diag("FAIL Encrypt Output %s\nEncrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(ct));
        	return 1;
        }
    }
    
    free(bb);
    
    if((retval = CCCrypt(kCCDecrypt, alg, options, key->bytes, key->len, iv->bytes, cipherDataOut, dataOutMoved, plainDataOut, 4096, &dataOutMoved)) != kCCSuccess) {
    	diag("Decrypt Failed\n");
        return 1;
    }
    
    bb = bytesToBytes(plainDataOut, dataOutMoved);
    
	if (!bytesAreEqual(pt, bb)) {
        diag("FAIL Decrypt Output %s\nDecrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(pt));
        return 1;
    }
    
    // if(ct->bytes && iv->bytes) diag("PASS Test for length %d\n", (int) pt->len);
    // if(ct && (iv->bytes == NULL)) diag("PASS NULL IV Test for length %d\n", (int) pt->len);

    free(pt);
    free(ct);
    free(key);
    free(iv);
	return 0;
}




int
CCMultiCryptTestCase(char *keyStr, char *ivStr, CCAlgorithm alg, CCOptions options, char *cipherText, char *plainText)
{
    byteBuffer key, iv;
    byteBuffer pt, ct;
    
    
	CCCryptorStatus retval;
    char cipherDataOut[4096];
    char plainDataOut[4096];
    size_t dataOutMoved;
    byteBuffer bb;
            
    key = hexStringToBytes(keyStr);        
    pt = ccConditionalTextBuffer(plainText);
    ct = ccConditionalTextBuffer(cipherText);
    iv = ccConditionalTextBuffer(ivStr);
    
        
    if((retval = CCMultiCrypt(kCCEncrypt, alg, options, key->bytes, key->len, iv->bytes, pt->bytes, pt->len, cipherDataOut, 4096, &dataOutMoved)) != kCCSuccess) {
    	diag("Encrypt Failed\n");
        return 1;
    }
    
    bb = bytesToBytes(cipherDataOut, dataOutMoved);    	

    // If ct isn't defined we're gathering data - print the ciphertext result
    if(!ct->bytes) {
    	diag("Input Length %d Result: %s\n", (int) pt->len, bytesToHexString(bb));
    } else {
        if (!bytesAreEqual(ct, bb)) {
            diag("FAIL Encrypt Output %s\nEncrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(ct));
        	return 1;
        }
    }
    
    free(bb);
    
    if((retval = CCMultiCrypt(kCCDecrypt, alg, options, key->bytes, key->len, iv->bytes, cipherDataOut, dataOutMoved, plainDataOut, 4096, &dataOutMoved)) != kCCSuccess) {
    	diag("Decrypt Failed\n");
        return 1;
    }
    
    bb = bytesToBytes(plainDataOut, dataOutMoved);
    
	if (!bytesAreEqual(pt, bb)) {
        diag("FAIL Decrypt Output %s\nDecrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(pt));
        return 1;
    }
    
    // if(ct && iv->bytes) diag("PASS Test for length %d\n", (int) pt->len);
    // if(ct && (iv->bytes == NULL)) diag("PASS NULL IV Test for length %d\n", (int) pt->len);

    free(pt);
    free(ct);
    free(key);
    free(iv);
	return 0;
}




int
CCModeTestCase(char *keyStr, char *ivStr, CCMode mode, CCAlgorithm alg, CCPadding padding, char *cipherText, char *plainText)
#ifdef CRYPTORWITHMODE
{
    byteBuffer key, iv;
    byteBuffer pt, ct;
    
	CCCryptorStatus retval;
    char cipherDataOut[4096];
    char plainDataOut[4096];
    size_t dataOutMoved;
    byteBuffer bb;
            
    key = hexStringToBytes(keyStr);        
    pt = ccConditionalTextBuffer(plainText);
    ct = ccConditionalTextBuffer(cipherText);
    iv = ccConditionalTextBuffer(ivStr);
    
   	if((retval = CCCryptWithMode(kCCEncrypt, mode, alg, padding, iv->bytes, key->bytes, key->len, NULL, 0, 0, 0,  pt->bytes, pt->len, 
            cipherDataOut, 4096, &dataOutMoved)) != kCCSuccess) {
    	diag("Encrypt Failed\n");
        return 1;
    }
    
    bb = bytesToBytes(cipherDataOut, dataOutMoved);    	

    // If ct isn't defined we're gathering data - print the ciphertext result
    if(!ct->bytes) {
    	diag("Input Length %d Result: %s\n", (int) pt->len, bytesToHexString(bb));
    } else {
        if (!bytesAreEqual(ct, bb)) {
            diag("FAIL\nEncrypt Output %s\nEncrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(ct));
        	return 1;
        }
    }
    
    free(bb);
    
   	if((retval = CCCryptWithMode(kCCDecrypt, mode, alg, padding, iv->bytes, key->bytes, key->len, NULL, 0, 0, 0,  cipherDataOut, dataOutMoved, 
        plainDataOut, 4096, &dataOutMoved)) != kCCSuccess) {
    	diag("Decrypt Failed\n");
        return 1;
    }
    
    bb = bytesToBytes(plainDataOut, dataOutMoved);
    
	if (!bytesAreEqual(pt, bb)) {
        diag("FAIL Decrypt Output %s\nDecrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(pt));
        return 1;
    }
    
    // if(ct->bytes && iv->bytes) diag("PASS Test for length %d\n", (int) pt->len);
    // if(ct->bytes && (iv->bytes == NULL)) diag("PASS NULL IV Test for length %d\n", (int) pt->len);

    free(pt);
    free(ct);
    free(key);
    free(iv);
	return 0;
}
#else
{
    return 0;
}
#endif




int
CCMultiModeTestCase(char *keyStr, char *ivStr, CCMode mode, CCAlgorithm alg, CCPadding padding, char *cipherText, char *plainText)
#ifdef CRYPTORWITHMODE
{
    byteBuffer key, iv;
    byteBuffer pt, ct;    
	CCCryptorStatus retval;
    char cipherDataOut[4096];
    char plainDataOut[4096];
    size_t dataOutMoved;
    byteBuffer bb;
            
    key = hexStringToBytes(keyStr);        
    pt = ccConditionalTextBuffer(plainText);
    ct = ccConditionalTextBuffer(cipherText);
    iv = ccConditionalTextBuffer(ivStr);
    
   	if((retval = CCMultiCryptWithMode(kCCEncrypt, mode, alg, padding, iv->bytes,key->bytes, key->len, NULL, 0,0, 0, pt->bytes, pt->len, 
            cipherDataOut, 4096, &dataOutMoved)) != kCCSuccess) {
    	diag("Encrypt Failed\n");
        return 1;
    }
    
    bb = bytesToBytes(cipherDataOut, dataOutMoved);    	

    // If ct isn't defined we're gathering data - print the ciphertext result
    if(!ct->bytes) {
    	diag("Input Length %d Result: %s\n", (int) pt->len, bytesToHexString(bb));
    } else {
        if (!bytesAreEqual(ct, bb)) {
            diag("FAIL\nEncrypt Output %s\nEncrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(ct));
        	return 1;
        }
    }
    
    free(bb);
    
   	if((retval = CCMultiCryptWithMode(kCCEncrypt, mode, alg, padding, iv->bytes, key->bytes, key->len, NULL, 0, 0, 0, 
        cipherDataOut, dataOutMoved, plainDataOut, 4096, &dataOutMoved)) != kCCSuccess) {
    	diag("Decrypt Failed\n");
        return 1;
    }
    
    bb = bytesToBytes(plainDataOut, dataOutMoved);
    
	if (!bytesAreEqual(pt, bb)) {
        diag("FAIL Decrypt Output %s\nDecrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(pt));
        return 1;
    }
    
    // if(ct && iv->bytes) diag("PASS Test for length %d\n", (int) pt->len);
    // if(ct && (iv->bytes == NULL)) diag("PASS NULL IV Test for length %d\n", (int) pt->len);

    free(pt);
    free(ct);
    free(key);
    free(iv);
	return 0;
}
#else
{
    return kCCSuccess;
}
#endif

#ifdef CCSYMGCM

static CCCryptorStatus 
CCCryptorGCMDiscreet(
	CCOperation 	op,				/* kCCEncrypt, kCCDecrypt */
	CCAlgorithm		alg,
	const void 		*key,			/* raw key material */
	size_t 			keyLength,	
	const void 		*iv,
	size_t 			ivLen,
	const void 		*aData,
	size_t 			aDataLen,
	const void 		*dataIn,
	size_t 			dataInLength,
  	void 			*dataOut,
	const void 		*tag,
	size_t 			*tagLength)
{
    CCCryptorStatus retval;
    CCCryptorRef    cref;
    
    retval = CCCryptorCreateWithMode(op, kCCModeGCM, alg, ccNoPadding, NULL, key, keyLength, NULL, 0, 0, 0, &cref);
    if(retval != kCCSuccess) return retval;
    
    retval = CCCryptorGCMAddIV(cref, iv, ivLen);
    if(retval != kCCSuccess) {
        printf("Failed to add IV\n");
        goto out;
    }
    
    retval = CCCryptorGCMaddAAD(cref, aData, aDataLen);
    if(retval != kCCSuccess) {
        printf("Failed to add ADD\n");
        goto out;
    }


    if(kCCEncrypt == op) {
        retval = CCCryptorGCMEncrypt(cref, dataIn, dataInLength, dataOut);
        if(retval != kCCSuccess) {
            printf("Failed to Encrypt\n");
            goto out;
        }
    } else {
        retval = CCCryptorGCMDecrypt(cref, dataIn, dataInLength, dataOut);
        if(retval != kCCSuccess) {
            printf("Failed to Decrypt\n");
            goto out;
        }
    }


    retval = CCCryptorGCMFinal(cref, tag, tagLength);
    if(retval != kCCSuccess) {
        printf("Failed to Finalize and get tag\n");
        goto out;
    }
    retval = CCCryptorGCMReset(cref);
    if(retval != kCCSuccess) {
        printf("Failed to Reset\n");
    }
    
    
out:

    CCCryptorRelease(cref);
    return retval;
}


int
CCCryptorGCMTestCase(char *keyStr, char *ivStr, char *aDataStr, char *tagStr, CCAlgorithm alg, char *cipherText, char *plainText)
{
    byteBuffer key, iv;
    byteBuffer pt, ct;
    byteBuffer adata, tag;
    byteBuffer bb;
    
    
	CCCryptorStatus retval;
    char cipherDataOut[4096];
    char plainDataOut[4096];
    char tagDataOut[4096];
    size_t tagDataOutlen;
    size_t  dataLen;
    

    key = hexStringToBytes(keyStr);        
    adata = ccConditionalTextBuffer(aDataStr);        
    tag = hexStringToBytes(tagStr);        
    pt = ccConditionalTextBuffer(plainText);
    ct = ccConditionalTextBuffer(cipherText);
    iv = ccConditionalTextBuffer(ivStr);
    
    dataLen = pt->len;
    
    tagDataOutlen = tag->len;
    memset(tagDataOut, 0, 16);
    if((retval = CCCryptorGCM(kCCEncrypt, alg, key->bytes, key->len, iv->bytes, iv->len, adata->bytes, adata->len, pt->bytes, dataLen, cipherDataOut, tagDataOut, &tagDataOutlen)) != kCCSuccess) {
    	diag("Encrypt Failed\n");
        return 1;
    }
        
    bb = bytesToBytes(cipherDataOut, dataLen);    	

    // If ct isn't defined we're gathering data - print the ciphertext result
    if(!ct->bytes) {
    	diag("Input Length %d Result: %s\n", (int) dataLen, bytesToHexString(bb));
    } else {
        if (!bytesAreEqual(ct, bb)) {
            diag("FAIL Encrypt Output %s\nEncrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(ct));
        	return 1;
        }
    }
    
    free(bb);
#if NEVER    
    bb = bytesToBytes(tagDataOut, tagDataOutlen);
    if (!bytesAreEqual(tag, bb)) {
        diag("FAIL Tag on plaintext is wrong\n       got %s\n  expected %s\n", bytesToHexString(bb), bytesToHexString(tag));
        return 1;
    }
#endif
    
    tagDataOutlen = tag->len;
    memset(tagDataOut, 0, 16);
    if((retval = CCCryptorGCM(kCCDecrypt, alg, key->bytes, key->len, iv->bytes, iv->len, adata->bytes, adata->len, cipherDataOut, dataLen, plainDataOut, tagDataOut, &tagDataOutlen)) != kCCSuccess) {
    	diag("Decrypt Failed\n");
        return 1;
    }
    
    bb = bytesToBytes(plainDataOut, dataLen);
    
	if (!bytesAreEqual(pt, bb)) {
        diag("FAIL Decrypt Output %s\nDecrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(pt));
        return 1;
    }
    
    free(bb);
    
    bb = bytesToBytes(tagDataOut, tagDataOutlen);
    if (!bytesAreEqual(tag, bb)) {
        diag("FAIL Tag on ciphertext is wrong\n       got %s\n  expected %s\n", bytesToHexString(bb), bytesToHexString(tag));
        return 1;
    }
    
    free(bb);
    free(pt);
    free(ct);
    free(key);
    free(iv);
    // diag("Pass One-Shot GCM Test\n");
	return 0;
}

int
CCCryptorGCMDiscreetTestCase(char *keyStr, char *ivStr, char *aDataStr, char *tagStr, CCAlgorithm alg, char *cipherText, char *plainText)
{
    byteBuffer key, iv;
    byteBuffer pt, ct;
    byteBuffer adata, tag;
    byteBuffer bb;
    
    
	CCCryptorStatus retval;
    char cipherDataOut[4096];
    char plainDataOut[4096];
    char tagDataOut[4096];
    size_t tagDataOutlen;
    size_t  dataLen;
    

    key = hexStringToBytes(keyStr);        
    adata = ccConditionalTextBuffer(aDataStr);        
    tag = hexStringToBytes(tagStr);        
    pt = ccConditionalTextBuffer(plainText);
    ct = ccConditionalTextBuffer(cipherText);
    iv = ccConditionalTextBuffer(ivStr);
    
    dataLen = pt->len;
    
    tagDataOutlen = tag->len;
    memset(tagDataOut, 0, 4096);
    if((retval = CCCryptorGCMDiscreet(kCCEncrypt, alg, key->bytes, key->len, iv->bytes, iv->len, adata->bytes, adata->len, pt->bytes, dataLen, cipherDataOut, tagDataOut, &tagDataOutlen)) != kCCSuccess) {
    	diag("Encrypt Failed\n");
        return 1;
    }
        
    bb = bytesToBytes(cipherDataOut, dataLen);    	

    // If ct isn't defined we're gathering data - print the ciphertext result
    if(!ct->bytes) {
    	diag("Input Length %d Result: %s\n", (int) dataLen, bytesToHexString(bb));
    } else {
        if (!bytesAreEqual(ct, bb)) {
            diag("FAIL Encrypt Output %s\nEncrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(ct));
        	return 1;
        }
    }
    
    free(bb);

#ifdef NEVER
    bb = bytesToBytes(tagDataOut, tagDataOutlen);
    if (!bytesAreEqual(tag, bb)) {
        diag("FAIL Tag on plaintext is wrong\n       got %s\n  expected %s\n", bytesToHexString(bb), bytesToHexString(tag));
        return 1;
    }
#endif
    
    tagDataOutlen = tag->len;
    memset(tagDataOut, 0, 4096);
    if((retval = CCCryptorGCMDiscreet(kCCDecrypt, alg, key->bytes, key->len, iv->bytes, iv->len, adata->bytes, adata->len, cipherDataOut, dataLen, plainDataOut, tagDataOut, &tagDataOutlen)) != kCCSuccess) {
    	diag("Decrypt Failed\n");
        return 1;
    }
    
    bb = bytesToBytes(plainDataOut, dataLen);
    
	if (!bytesAreEqual(pt, bb)) {
        diag("FAIL Decrypt Output %s\nDecrypt Expect %s\n", bytesToHexString(bb), bytesToHexString(pt));
        return 1;
    }
    
    free(bb);
    
    bb = bytesToBytes(tagDataOut, tagDataOutlen);
    if (!bytesAreEqual(tag, bb)) {
        diag("FAIL Tag on ciphertext is wrong\n       got %s\n  expected %s\n", bytesToHexString(bb), bytesToHexString(tag));
        return 1;
    }
    
    free(bb);
    free(pt);
    free(ct);
    free(key);
    free(iv);
    // diag("Pass Discreet GCM Test\n");

	return 0;
}

#endif

Added CCRegression/CommonCrypto/CCCryptorTestFuncs.h.



























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
 *  CCCryptorTestFuncs.h
 *  CCRegressions
 *
 *
 */

#include "capabilities.h"
#include <CommonCrypto/CommonCryptor.h>
#ifdef CRYPTORWITHMODE
#include <CommonCrypto/CommonCryptorSPI.h>
#else
typedef uint32_t CCMode;
typedef uint32_t CCPadding;
typedef uint32_t CCModeOptions;
#endif

/* This is a CCCrypt with the Updates split into two parts */

CCCryptorStatus 
CCMultiCrypt(CCOperation op, CCAlgorithm alg, CCOptions options, const void *key, size_t keyLength, const void *iv, const void *dataIn, size_t dataInLength,
	void *dataOut, size_t dataOutAvailable, size_t *dataOutMoved);
    
    
/* This is a CCCrypt allowing mode specification */

CCCryptorStatus
CCCryptWithMode(CCOperation op, CCMode mode, CCAlgorithm alg, CCPadding padding, const void *iv, 
				const void *key, size_t keyLength, const void *tweak, size_t tweakLength,
                int numRounds, CCModeOptions options,
                const void *dataIn, size_t dataInLength, 
                void *dataOut, size_t dataOutAvailable, size_t *dataOutMoved);

CCCryptorStatus 
CCMultiCryptWithMode(CCOperation op, CCMode mode, CCAlgorithm alg, CCPadding padding, const void *iv, 
	const void *key, size_t keyLength, const void *tweak, size_t tweakLength,
	int numRounds, CCModeOptions options,
    const void *dataIn, size_t dataInLength,
	void *dataOut, size_t dataOutAvailable, size_t *dataOutMoved);

/* This is a Test Case "doer" using CCCrypt */
int
CCCryptTestCase(char *keyStr, char *ivStr, CCAlgorithm alg, CCOptions options, char *cipherText, char *plainText);

/* This is a Test Case "doer" using CCMultiCrypt */
int
CCMultiCryptTestCase(char *keyStr, char *ivStr, CCAlgorithm alg, CCOptions options, char *cipherText, char *plainText);

/* This is a Test Case "doer" using CCCryptWithMode */
int
CCModeTestCase(char *keyStr, char *ivStr, CCMode mode, CCAlgorithm alg, CCPadding padding, char *cipherText, char *plainText);

/* This is a Test Case "doer" using CCMultiCryptWithMode */
int
CCMultiModeTestCase(char *keyStr, char *ivStr, CCMode mode, CCAlgorithm alg, CCPadding padding, char *cipherText, char *plainText);
/* This is a Test Case "doer" using CCCryptorGCM */
int
CCCryptorGCMTestCase(char *keyStr, char *ivStr, char *aDataStr, char *tagStr, CCAlgorithm alg, char *cipherText, char *plainText);
int
CCCryptorGCMDiscreetTestCase(char *keyStr, char *ivStr, char *aDataStr, char *tagStr, CCAlgorithm alg, char *cipherText, char *plainText);

Added CCRegression/CommonCrypto/CommonBaseEncoding.c.



























































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269

//
//  CNEncoding.c
//  CCRegressions
//
#include <stdio.h>
#include "testbyteBuffer.h"
#include "capabilities.h"
#include "testmore.h"

#if (CNENCODER == 0)
entryPoint(CommonBaseEncoding,"Base XX Encoding")
#else

#include <CommonCrypto/CommonBaseXX.h>

static int kTestTestCount = 358;

#define BUFSIZ 1024

static int
doWithEncoders(CNEncoderRef encoder, CNEncoderRef decoder, char *input, char *expected)
{
    CNStatus retval;
    char outBuf[BUFSIZ], secondBuf[BUFSIZ];
    size_t outLen, outAvailable, secondLen, secondAvailable;
    
    outAvailable = BUFSIZ;
    outLen = 0;
    retval = CNEncoderUpdate(encoder, input, strlen(input), outBuf, &outAvailable);
    
    ok(retval == kCNSuccess, "encoded");
    
    outLen = outAvailable;
    outAvailable = BUFSIZ - outLen;
    
    retval = CNEncoderFinal(encoder, &outBuf[outLen], &outAvailable);
    
    ok(retval == kCNSuccess, "finalized");
    
    outLen += outAvailable;
    
    if(expected) {
        ok(strncmp(expected, outBuf, strlen(expected)) == 0, "output matches");
        if(strncmp(expected, outBuf, strlen(expected))) {
            printf("Encoding %s\n%s\n%s\n", input, expected, outBuf);
        }
    }
    
    retval = CNEncoderRelease(&encoder);
    
    ok(retval == kCNSuccess, "released");
    
    
    secondAvailable = BUFSIZ;
    secondLen = 0;
    retval = CNEncoderUpdate(decoder, outBuf, outLen, secondBuf, &secondAvailable);
    
    ok(retval == kCNSuccess, "encoded");
    
    
    secondLen = secondAvailable;
    secondAvailable = BUFSIZ - secondLen;
    
    retval = CNEncoderFinal(decoder, &secondBuf[secondLen], &secondLen);
    
    ok(retval == kCNSuccess, "finalized");
    
    secondLen += secondAvailable;
    
    ok(strncmp(input, secondBuf, strlen(input)) == 0, "output matches");
    
    retval = CNEncoderRelease(&decoder);
    ok(retval == kCNSuccess, "encoder Released");
    
    return 0;
}


static int
doEncoder(CNEncodings encodingStrat, char *input, char *expected)
{
    CNStatus retval;
    CNEncoderRef encoder, decoder;
        
    retval = CNEncoderCreate(encodingStrat, kCNEncode, &encoder);
        
    ok(retval == kCNSuccess, "got an encoder");
    
    retval = CNEncoderCreate(encodingStrat, kCNDecode, &decoder);
    
    ok(retval == kCNSuccess, "got a decoder");
    

    doWithEncoders(encoder, decoder, input, expected);
    
    return 0;
}


static int
doCustomEncoder(const char *name,
                const uint8_t baseNum,
                const char *charMap,
                const uint8_t padChar, char *input, char *expected)
{
    CNStatus retval;
    CNEncoderRef encoder, decoder;
    
    retval = CNEncoderCreateCustom(name, baseNum, charMap, padChar, kCNEncode, &encoder);
    
    ok(retval == kCNSuccess, "got an encoder");
        
    retval = CNEncoderCreateCustom(name, baseNum, charMap, padChar, kCNDecode, &decoder);
    
    ok(retval == kCNSuccess, "got a decoder");
    
    doWithEncoders(encoder, decoder, input, expected);
    
    return 0;
}

static int
doOneShotStyle(CNEncodings encodingStrat, char *input, char *expected)
{
    CNStatus retval;
    char outBuf[BUFSIZ], secondBuf[BUFSIZ];
    size_t outLen, outAvailable, secondLen, secondAvailable;
    
    outAvailable = BUFSIZ;
    retval = CNEncode(encodingStrat, kCNEncode, input, strlen(input), outBuf, &outAvailable);
    
    outLen = outAvailable;
    
    if(expected) {
        ok(strncmp(expected, outBuf, strlen(expected)) == 0, "output matches");
        if(strncmp(expected, outBuf, strlen(expected))) {
            printf("Encoding %s\n%s\n%s\n", input, expected, outBuf);
        }
    }
        
    
    secondAvailable = BUFSIZ;
    retval = CNEncode(encodingStrat, kCNDecode, outBuf, outLen, secondBuf, &secondAvailable);

    secondLen = secondAvailable;
    
    ok(strncmp(input, secondBuf, strlen(input)) == 0, "output matches");
    if(strncmp(input, secondBuf, strlen(input))) {
        printf("input:  %s\n", input);
        printf("result: %s\n", secondBuf);
    }
    
    return 0;    
}

    

int CommonBaseEncoding(int argc, char *const *argv) {
    int accum = 0;
    
    plan_tests(kTestTestCount);
    
    // diag("Base64\n");
    
	doEncoder(kCNEncodingBase64, "", ""); 
	doEncoder(kCNEncodingBase64, "f", "Zg=="); 
	doEncoder(kCNEncodingBase64, "fo", "Zm8="); 
	doEncoder(kCNEncodingBase64, "foo", "Zm9v"); 
	doEncoder(kCNEncodingBase64, "foob", "Zm9vYg=="); 
	doEncoder(kCNEncodingBase64, "fooba", "Zm9vYmE="); 
	doEncoder(kCNEncodingBase64, "foobar", "Zm9vYmFy"); 
    
    //diag("Base32\n");

	doEncoder(kCNEncodingBase32, "", ""); 
	doEncoder(kCNEncodingBase32, "f", "MY======"); 
	doEncoder(kCNEncodingBase32, "fo", "MZXQ===="); 
	doEncoder(kCNEncodingBase32, "foo", "MZXW6==="); 
	doEncoder(kCNEncodingBase32, "foob", "MZXW6YQ="); 
	doEncoder(kCNEncodingBase32, "fooba", "MZXW6YTB"); 
	doEncoder(kCNEncodingBase32, "foobar", "MZXW6YTBOI======");
    
    //diag("Base32HEX\n");

	doEncoder(kCNEncodingBase32HEX, "", ""); 
	doEncoder(kCNEncodingBase32HEX, "f", "CO======"); 
	doEncoder(kCNEncodingBase32HEX, "fo", "CPNG===="); 
	doEncoder(kCNEncodingBase32HEX, "foo", "CPNMU==="); 
	doEncoder(kCNEncodingBase32HEX, "foob", "CPNMUOG="); 
	doEncoder(kCNEncodingBase32HEX, "fooba", "CPNMUOJ1"); 
	doEncoder(kCNEncodingBase32HEX, "foobar", "CPNMUOJ1E8======"); 
    
    //diag("Base16\n");

	doEncoder(kCNEncodingBase16, "", ""); 
	doEncoder(kCNEncodingBase16, "f", "66"); 
	doEncoder(kCNEncodingBase16, "fo", "666F"); 
	doEncoder(kCNEncodingBase16, "foo", "666F6F"); 
	doEncoder(kCNEncodingBase16, "foob", "666F6F62"); 
	doEncoder(kCNEncodingBase16, "fooba", "666F6F6261"); 
	doEncoder(kCNEncodingBase16, "foobar", "666F6F626172"); 
    
    //diag("Base64 Long\n");
    accum |= doEncoder(kCNEncodingBase64, 
    "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.",
                       "");
<<<<<<< HEAD
    //diag("Custom\n");
=======
    
    diag("Base64 - One-Shot\n");
    
	doOneShotStyle(kCNEncodingBase64, "", ""); 
	doOneShotStyle(kCNEncodingBase64, "f", "Zg=="); 
	doOneShotStyle(kCNEncodingBase64, "fo", "Zm8="); 
	doOneShotStyle(kCNEncodingBase64, "foo", "Zm9v"); 
	doOneShotStyle(kCNEncodingBase64, "foob", "Zm9vYg=="); 
	doOneShotStyle(kCNEncodingBase64, "fooba", "Zm9vYmE="); 
	doOneShotStyle(kCNEncodingBase64, "foobar", "Zm9vYmFy"); 
    
    diag("Base32 - One-Shot\n");
    
	doOneShotStyle(kCNEncodingBase32, "", ""); 
	doOneShotStyle(kCNEncodingBase32, "f", "MY======"); 
	doOneShotStyle(kCNEncodingBase32, "fo", "MZXQ===="); 
	doOneShotStyle(kCNEncodingBase32, "foo", "MZXW6==="); 
	doOneShotStyle(kCNEncodingBase32, "foob", "MZXW6YQ="); 
	doOneShotStyle(kCNEncodingBase32, "fooba", "MZXW6YTB"); 
	doOneShotStyle(kCNEncodingBase32, "foobar", "MZXW6YTBOI======");
    
    diag("Base32HEX - One-Shot\n");
    
	doOneShotStyle(kCNEncodingBase32HEX, "", ""); 
	doOneShotStyle(kCNEncodingBase32HEX, "f", "CO======"); 
	doOneShotStyle(kCNEncodingBase32HEX, "fo", "CPNG===="); 
	doOneShotStyle(kCNEncodingBase32HEX, "foo", "CPNMU==="); 
	doOneShotStyle(kCNEncodingBase32HEX, "foob", "CPNMUOG="); 
	doOneShotStyle(kCNEncodingBase32HEX, "fooba", "CPNMUOJ1"); 
	doOneShotStyle(kCNEncodingBase32HEX, "foobar", "CPNMUOJ1E8======"); 
    
    diag("Base16 - One-Shot\n");
    
	doOneShotStyle(kCNEncodingBase16, "", ""); 
	doOneShotStyle(kCNEncodingBase16, "f", "66"); 
	doOneShotStyle(kCNEncodingBase16, "fo", "666F"); 
	doOneShotStyle(kCNEncodingBase16, "foo", "666F6F"); 
	doOneShotStyle(kCNEncodingBase16, "foob", "666F6F62"); 
	doOneShotStyle(kCNEncodingBase16, "fooba", "666F6F6261"); 
	doOneShotStyle(kCNEncodingBase16, "foobar", "666F6F626172"); 
    
    diag("Base64 Long - One-Shot\n");
    accum |= doOneShotStyle(kCNEncodingBase64, 
                       "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.",
                       "");

    
    
    
    diag("Custom\n");
    accum |= doCustomEncoder("Custom64", 64, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/", '*',
                       "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.",
                       "");
    
    return 0;
}

#endif

Added CCRegression/CommonCrypto/CommonBigDigest.c.





















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <stdio.h>
#include "testbyteBuffer.h"
#include "capabilities.h"
#include "testmore.h"
#include <string.h>
#include <CommonCrypto/CommonDigest.h>

#if (CCBIGDIGEST == 0)
entryPoint(CommonBigDigest,"CommonCrypto CCDigest Large Size test")
#else
#include <CommonCrypto/CommonDigestSPI.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>


static void DigestInChunks(CCDigestAlgorithm algorithm, size_t chunksize, const uint8_t *bytesToDigest, size_t numbytes, uint8_t *outbuf)
{
    CCDigestRef d = CCDigestCreate(algorithm);
    while(numbytes) {
        size_t n = (numbytes < chunksize) ? numbytes: chunksize;
        CCDigestUpdate(d, bytesToDigest, n);
        numbytes -= n; bytesToDigest += n;
    }
    if(CCDigestFinal(d, outbuf)) return;
    CCDigestDestroy(d);
}

/*
 * Compute the digest of a whole file
 */

static int
checksum_file(char *filename, CCDigestAlgorithm algorithm)
{
    struct stat st;
    size_t digestsize = CCDigestGetOutputSize(algorithm);
    uint8_t mdwhole[digestsize];
    uint8_t mdchunk[digestsize];
    size_t blocksz = 0x40000000L; // 1 GB
    off_t filesize;
    u_char *buf;
    int fd; 
    
    fd = open(filename, O_RDONLY);
    if (fd < 0) {
        perror(filename);
        return -1; 
    }   
    if (fstat(fd, &st) < 0) {
        perror(filename);
        (void) close(fd);
        return -1; 
    }   
    
    filesize = st.st_size;
    buf = (u_char *) mmap(NULL, filesize,
                          PROT_READ, MAP_PRIVATE | MAP_NOCACHE, fd, 0); 
    if (buf == (u_char *) -1) {
        perror("mmap");
        close(fd);
        return -1; 
    }   
    (void) madvise(buf, filesize, MADV_SEQUENTIAL);
	printf("File is mapped\n");
    
	/*
	 * First do it in one big chunk
	 */
    
    CCDigest(algorithm, buf, filesize, mdwhole);
    
	/*
	 * Now do it in several 1GB chunks
	 */
    
    DigestInChunks(algorithm, blocksz, buf, filesize, mdchunk);
    
    (void) munmap(buf, filesize);
    (void) close(fd);
    
    int cmpval = memcmp(mdchunk, mdwhole, digestsize);
    ok(cmpval == 0, "Results are the same for both digests");
    
    return 0;
}


static const int kTestTestCount = 1000;

int CommonBigDigest(int argc, char *const *argv)
{
    
	plan_tests(kTestTestCount);
    
    char *testpath = "/Volumes/Data/Users/murf/Downloads/Zin_12A130_AppleInternal_038-2423-191.dmg";
    checksum_file(testpath, kCCDigestSHA1);

    return 0;
}


#endif

Added CCRegression/CommonCrypto/CommonBigNum.c.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478

#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"
#include "CommonRandomSPI.h"




#if (CCBIGNUM == 0)
entryPoint(CommonBigNum,"Big Number Arithmetic")
#else

#include <CommonCrypto/CommonBigNum.h>
static int kTestTestCount = 7;



#define STRESSSIZE 5000

static int testCreateFree()
{
    CCStatus status;
    CCBigNumRef stress[STRESSSIZE];
    for(size_t i=0; i<STRESSSIZE; i++) stress[i] = NULL;
    byteBuffer bb = hexStringToBytes("0102030405060708091011121314151617181920");
    for(int i=0; i<100; i++) {
        for(int j=0; j<100; j++) {
            CCBigNumRef r = CCBigNumCreateRandom(&status, 31, 31, 0);
            ok(status == kCCSuccess, "Created Random Number");
            size_t ri = CCBigNumGetI(&status, r);
            ok(status == kCCSuccess, "translated to int");
            
            ri %= STRESSSIZE;

            if(stress[ri] == NULL) {
                int sel = ri % 3;
                switch(sel) {
                    case 0: /* printf("(%lu) BigNum\n", ri); */ stress[ri] = CCCreateBigNum(&status); break;
                    case 1: /* printf("(%lu) FromHex\n", ri); */ stress[ri] = CCBigNumFromHexString(&status, "0003"); break;
                    case 2: /* printf("(%lu) FromData\n", ri); */ stress[ri] = CCBigNumFromData(&status, bb->bytes, bb->len); break;
                }
                ok(status == kCCSuccess, "BigNum Created");
            } else {
                /* printf("(%lu) Freeing\n", ri); */
                CCBigNumClear(stress[ri]);
                CCBigNumFree(stress[ri]);
                stress[ri] = NULL;
            }
            CCBigNumFree(r);
        }
    }
    return 0;
}

static int testHexString()
{
    CCStatus status;
    char *hexstring = "1002030405060708090021222324252627282920";
    CCBigNumRef num1 = CCBigNumFromHexString(&status, hexstring);
    char *output;
    
    ok(status == 0, "BigNum Created");
    output = CCBigNumToHexString(&status, num1);
    ok(status == 0, "Value retrieved");
    ok(strcmp(output, hexstring) == 0, "strings are equal");
    if(strcmp(output, hexstring)) {
        printf("output: %s\n", output);
        printf("input : %s\n", hexstring);
    }
    free(output);
    CCBigNumFree(num1);

    return 0;

}

static int testData()
{
    CCStatus status;
    char *hexstring = "1002030405060708090021222324252627282920";
    byteBuffer bb = hexStringToBytes(hexstring);
    CCBigNumRef num1 = CCBigNumFromData(&status, bb->bytes, bb->len);
    char *output;
    
    ok(status == 0, "BigNum Created");
    output = CCBigNumToHexString(&status, num1);
    ok(status == 0, "Value retrieved");
    ok(strcmp(output, hexstring) == 0, "strings are equal");
    if(strcmp(output, hexstring)) {
        printf("output: %s\n", output);
        printf("input : %s\n", hexstring);
    }
    free(output);
    
    byteBuffer outbuf = mallocByteBuffer(64);
    outbuf->len = CCBigNumToData(&status, num1, outbuf->bytes);
    ok(status == 0, "Value retrieved 2");
    
    ok(bytesAreEqual(bb, outbuf), "input == output");
    free(bb);
    free(outbuf);
    CCBigNumFree(num1);

    return 0;
    
}

static int testI()
{
    CCStatus status;
    uint32_t I=0x10203040;
    char *hexstring = "10203040";
    byteBuffer bb = hexStringToBytes(hexstring);
    CCBigNumRef num1 = CCCreateBigNum(&status);
    char *output;
    
    ok(status == 0, "BigNum Created");
    status = CCBigNumSetI(num1, I);
    ok(status == 0, "BigNum Set to I");
    output = CCBigNumToHexString(&status, num1);
    ok(status == 0, "Value retrieved");
    ok(strcmp(output, hexstring) == 0, "strings are equal");
    if(strcmp(output, hexstring)) {
        printf("output: %s\n", output);
        printf("input : %s\n", hexstring);
    }
    free(output);
    
    uint32_t outI = CCBigNumGetI(&status, num1);
    ok(status == 0, "Value retrieved 2");
    
    ok(outI == I, "input == output");
    free(bb);
    CCBigNumFree(num1);
    
    return 0;
    
}


static int testCompare()
{
    CCStatus status;
    char *lowstring = "030405060708090021222324252627282920";
    char *midstring = "1002030405060708090021222324252627282920";
    char *histring  = "1002030405060708090f21222324252627282920";
    CCBigNumRef low = CCBigNumFromHexString(&status, lowstring);
    ok(status == 0, "BigNum Created");
    CCBigNumRef mid = CCBigNumFromHexString(&status, midstring);
    ok(status == 0, "BigNum Created");
    CCBigNumRef midsame = CCBigNumFromHexString(&status, midstring);
    ok(status == 0, "BigNum Created");
    CCBigNumRef hi = CCBigNumFromHexString(&status, histring);
    ok(status == 0, "BigNum Created");
    CCBigNumRef iVal = CCCreateBigNum(&status);
    ok(status == 0, "BigNum Created");
    status = CCBigNumSetI(iVal, 67);

    ok(CCBigNumCompare(mid, low) == 1, "mid > low");
    ok(CCBigNumCompare(mid, hi) == -1, "mid < hi");
    ok(CCBigNumCompare(mid, midsame) == 0, "mid == midsame");
    ok(CCBigNumCompareI(iVal, 67) == 0, "iVal equality is correct");
    ok(CCBigNumCompareI(iVal, 66) > 0, "iVal greater is correct");
    ok(CCBigNumCompareI(iVal, 68) < 0, "iVal less than is correct");

    CCBigNumFree(low);
    CCBigNumFree(mid);
    CCBigNumFree(midsame);
    CCBigNumFree(hi);
    CCBigNumFree(iVal);

    return 0;
    
}

static int testBitCount()
{
    CCStatus status;
    char *hexstring = "1002030405060708090021222324252627282920";
    CCBigNumRef num1 = CCBigNumFromHexString(&status, hexstring);
    ok(status == 0, "BigNum Created");
    
    int bits = CCBigNumBitCount(num1);
    ok(bits == 157, "bit count is correct");

    CCBigNumFree(num1);
    return 0;
}

static int testAddSub()
{
    CCStatus status;
    char *hex1 = "1002030405060708090021222324252627282920";
    char *hex2 = "1002030405060708090021222324252627282920";
    char *result = "200406080a0c0e101200424446484a4c4e505240";
    CCBigNumRef num1 = CCBigNumFromHexString(&status, hex1);
    CCBigNumRef num2 = CCBigNumFromHexString(&status, hex2);
    CCBigNumRef output = CCCreateBigNum(&status);
    CCBigNumRef resultExpected = CCBigNumFromHexString(&status, result);
    
    status = CCBigNumAdd(output, num1, num2);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected) == 0, "expected operation result");

    status = CCBigNumSub(output, num1, num2);
    ok(status == 0, "operation completed");
    CCBigNumSetI(resultExpected, 0);
    ok(CCBigNumCompare(output, resultExpected) == 0, "expected operation result");
    
    CCBigNumFree(num1);
    CCBigNumFree(num2);
    CCBigNumFree(output);
    CCBigNumFree(resultExpected);
    return 0;
}

static int testAddSubI()
{
    CCStatus status;
    char *hex1 = "1002030405060708090021222324252627282920";
    char *result = "1002030405060708090021222324252627282921";
    CCBigNumRef num1 = CCBigNumFromHexString(&status, hex1);
    CCBigNumRef output = CCCreateBigNum(&status);
    CCBigNumRef resultExpected = CCBigNumFromHexString(&status, result);
    
    status = CCBigNumAddI(output, num1, 1);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected) == 0, "expected operation result");
    
    status = CCBigNumSubI(output, output, 1);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, num1) == 0, "expected operation result");
    
    CCBigNumFree(num1);
    CCBigNumFree(output);
    CCBigNumFree(resultExpected);
    return 0;
}


static int testShift()
{
    CCStatus status;
    
    // Shift n right by 11
    CCBigNumRef n = CCBigNumFromHexString(&status, "1002030405060708090021222324252627282920");
    CCBigNumRef resultExpected = CCBigNumFromHexString(&status, "200406080a0c0e101200424446484a4c4e505");
    CCBigNumRef output = CCCreateBigNum(&status);
    status = CCBigNumRightShift(output, n, 11);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected) == 0, "expected operation result");

    // Shift n left by 14
    CCBigNumRef resultExpected2 = CCBigNumFromHexString(&status, "40080c1014181c20240084888c9094989ca0a480000");
    status = CCBigNumLeftShift(output, n, 14);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected2) == 0, "expected operation result");

    
    CCBigNumFree(n);
    CCBigNumFree(output);
    CCBigNumFree(resultExpected);
    CCBigNumFree(resultExpected2);
    return 0;
}

static int testModExp()
{
    CCStatus status;
    
    // Shift n right by 11
    CCBigNumRef a = CCBigNumFromHexString(&status, "c968e40c5304364b057425920b18cc358f254ddb0f42f84850d6deec46006b4a692e52b7c3bddead45f77f2c1be1c606521d8a24260429f362d65b57873dbf270e97e210b872e45e97cb4cd87977ad20491e53c48cf0e88da9a61312675a2527c86ac537740c5e4206972f09c0f91fa1c9f14a2cf1be07e82a3b6fd58dc12c3a");
    CCBigNumRef b = CCBigNumFromHexString(&status, "010001");
    CCBigNumRef c = CCBigNumFromHexString(&status, "354c912b09ee7abff5b3d94ed52a9e8dcae582e094daa375c495f970710af73efcc4f9776010511f654c7408a6d5d351ab1d94a0fede757d782b54ddcf6fe8d714870b78b0e67a9754cb03a5cf63bbda1c71791902ea4527fb0cd76437391e5422c704ffb6d6018261171d8cee98adcf0243f1fd520fb3761afe94a2f4d99f94");
    CCBigNumRef resultExpected = CCBigNumFromHexString(&status, "0fb978a4f4fccdb14c7268918b784c4f6d5281c0d6ff43e60e88e97f97f2617608de2488c84eb99a3f467013c860536ec74f4968abeccbc1b026ee5873e40bdd292f8f7416a93df619288b49ba21d3e09aa796cb35a340b1abfda4e3b6cd92df2de64967e6a59f787586929c4d2920da20caeb384594d7f2b7e999dab0d6a1ac");
    CCBigNumRef output = CCCreateBigNum(&status);
    
    status = CCBigNumModExp(output, a, b, c);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected) == 0, "expected operation result");

    CCBigNumFree(a);
    CCBigNumFree(b);
    CCBigNumFree(c);
    CCBigNumFree(output);
    CCBigNumFree(resultExpected);
    return 0;
}

static int testMod()
{
    CCStatus status;
    
    // Shift n right by 11
    CCBigNumRef a = CCBigNumFromHexString(&status, "c968e40c5304364b057425920b18cc358f254ddb0f42f84850d6deec46006b4a692e52b7c3bddead45f77f2c1be1c606521d8a24260429f362d65b57873dbf270e97e210b872e45e97cb4cd87977ad20491e53c48cf0e88da9a61312675a2527c86ac537740c5e4206972f09c0f91fa1c9f14a2cf1be07e82a3b6fd58dc12c3a");
    CCBigNumRef c = CCBigNumFromHexString(&status, "354c912b09ee7abff5b3d94ed52a9e8dcae582e094daa375c495f970710af73efcc4f9776010511f654c7408a6d5d351ab1d94a0fede757d782b54ddcf6fe8d714870b78b0e67a9754cb03a5cf63bbda1c71791902ea4527fb0cd76437391e5422c704ffb6d6018261171d8cee98adcf0243f1fd520fb3761afe94a2f4d99f94");
    CCBigNumRef resultExpected = CCBigNumFromHexString(&status, "2983308b3538c60b245899a58b98f08c2e74c53950b30de70314f29af2df858d72df6651a38ceb4f1612231227604c1150c4cc412968c97afa545cbe18ee04a1d102bfa6a5bf7498996a41e70b4c7991f3c9e87984321915b87f8ce5c1aeca2b6015b6384f8a59bae351d662f52f1634c3257434fb8eed85d93fb1ecaf344d7e");
    CCBigNumRef output = CCCreateBigNum(&status);
    
    status = CCBigNumMod(output, a, c);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected) == 0, "expected operation result");
    
    CCBigNumFree(a);
    CCBigNumFree(c);
    CCBigNumFree(output);
    CCBigNumFree(resultExpected);
    return 0;
}


static int testModI()
{
    CCStatus status;
    
    // Shift n right by 11
    CCBigNumRef a = CCBigNumFromHexString(&status, "c968e40c5304364b057425920b18cc358f254ddb0f42f84850d6deec46006b4a692e52b7c3bddead45f77f2c1be1c606521d8a24260429f362d65b57873dbf270e97e210b872e45e97cb4cd87977ad20491e53c48cf0e88da9a61312675a2527c86ac537740c5e4206972f09c0f91fa1c9f14a2cf1be07e82a3b6fd58dc12c3a");
    uint32_t c=63;
    uint32_t resultExpected = 23;
    uint32_t output;
    
    status = CCBigNumModI(&output, a, c);
    ok(status == 0, "operation completed");
    ok(resultExpected == output, "expected operation result");
    
    CCBigNumFree(a);
    return 0;
}


static int testMul()
{
    CCStatus status;
    
    // Shift n right by 11
    CCBigNumRef a = CCBigNumFromHexString(&status, "c968e40c5304364b057425920b18cc358f254ddb0f42f84850d6deec46006b4a692e52b7c3bddead45f77f2c1be1c606521d8a24260429f362d65b57873dbf270e97e210b872e45e97cb4cd87977ad20491e53c48cf0e88da9a61312675a2527c86ac537740c5e4206972f09c0f91fa1c9f14a2cf1be07e82a3b6fd58dc12c3a");
    CCBigNumRef c = CCBigNumFromHexString(&status, "354c912b09ee7abff5b3d94ed52a9e8dcae582e094daa375c495f970710af73efcc4f9776010511f654c7408a6d5d351ab1d94a0fede757d782b54ddcf6fe8d714870b78b0e67a9754cb03a5cf63bbda1c71791902ea4527fb0cd76437391e5422c704ffb6d6018261171d8cee98adcf0243f1fd520fb3761afe94a2f4d99f94");
    CCBigNumRef resultExpected = CCBigNumFromHexString(&status, "29eef49086721db0707b81175570af0db1517307f313564ff3a07f695514e92f525efea63ab5de4830c06b365f5c21cba747b96c6cb315d5b3dfa6642324e0a30f0a999acd196c1c78b99bff4d53e1e1e5d02b521a964a286279129e9bfbb51738743617a73f896bfd21e7c4c24e8f72a4a995781b0b4fa1b37a2320b935b0c5e130f27a65135ac4b7247db58e7f752550d92e08b177a84d5d0364cd8c74d4e2bb086d1cd9bc4c541e86ecf66940be30b73675a63921f9fd1fdfa6db57bd4b13304ac0ac84d64c262d5802a1363ee1d519f88b8ca0997a77f7ece081042d88814da526c44f1323c7ac5b7eeedccda0e28bc65bc415bba767d34f161ab34f9788");
    CCBigNumRef output = CCCreateBigNum(&status);
    
    status = CCBigNumMul(output, a, c);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected) == 0, "expected operation result");
    
    CCBigNumFree(a);
    CCBigNumFree(c);
    CCBigNumFree(output);
    CCBigNumFree(resultExpected);
    return 0;
}

static int testMulI()
{
    CCStatus status;
    
    // Shift n right by 11
    CCBigNumRef a = CCBigNumFromHexString(&status, "c968e40c5304364b057425920b18cc358f254ddb0f42f84850d6deec46006b4a692e52b7c3bddead45f77f2c1be1c606521d8a24260429f362d65b57873dbf270e97e210b872e45e97cb4cd87977ad20491e53c48cf0e88da9a61312675a2527c86ac537740c5e4206972f09c0f91fa1c9f14a2cf1be07e82a3b6fd58dc12c3a");
    uint32_t c = 63;
    CCBigNumRef resultExpected = CCBigNumFromHexString(&status, "3190d01f086e095c7657953ef0bb1a412e3a2e28e8c17b19cbe4e0dc253a1a674fe2665b392bb9cca437e84bdadc8fbb8e3544fee55b0652e552c07a8a48320a9c9760a21d644633475b07e945e4739af1fe769d5eaf493adcbfdeb1876f2f24ca524688a58f0b323f9f3493667d4ec8d0b261410f7dc3f22264a0858de289e246");
    CCBigNumRef output = CCCreateBigNum(&status);
    
    status = CCBigNumMulI(output, a, c);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected) == 0, "expected operation result");
    
    CCBigNumFree(a);
    CCBigNumFree(output);
    CCBigNumFree(resultExpected);
    return 0;
}

static int testPrime()
{
    CCStatus status;
    
    // Shift n right by 11
    CCBigNumRef a = CCBigNumFromHexString(&status, "09c75b");
    ok(CCBigNumIsPrime(&status, a), "prime number");
    CCBigNumRef b = CCBigNumFromHexString(&status, "09c75c");
    ok(!CCBigNumIsPrime(&status, b), "not prime number");

    return 0;
}


static int testDiv()
{
    CCStatus status;
    
    // Shift n right by 11
    CCBigNumRef a = CCBigNumFromHexString(&status, "c968e40c5304364b057425920b18cc358f254ddb0f42f84850d6deec46006b4a692e52b7c3bddead45f77f2c1be1c606521d8a24260429f362d65b57873dbf270e97e210b872e45e97cb4cd87977ad20491e53c48cf0e88da9a61312675a2527c86ac537740c5e4206972f09c0f91fa1c9f14a2cf1be07e82a3b6fd58dc12c3a");
    CCBigNumRef c = CCBigNumFromHexString(&status, "354c912b09ee7abff5b3d94ed52a9e8dcae582e094daa375c495f970710af73efcc4f9776010511f654c7408a6d5d351ab1d94a0fede757d782b54ddcf6fe8d714870b78b0e67a9754cb03a5cf63bbda1c71791902ea4527fb0cd76437391e5422c704ffb6d6018261171d8cee98adcf0243f1fd520fb3761afe94a2f4d99f94");
    CCBigNumRef resultExpected = CCBigNumFromHexString(&status, "03");
    CCBigNumRef c2 = CCBigNumFromHexString(&status, "43"); // dec 67
    CCBigNumRef resultExpected2 = CCBigNumFromHexString(&status, "30190c6ded9da99f49e63e76ef8ba736d1f1fbaac2b0786cf88f03904dd9e4210da7b80d5121e11dea7fe13c3482557f99574b04cfc3dc2ad6a5d1097089039e578b6f4c9708551a690684fa61c8850b87e8acd70e8d970eb9b5086018ae5ceec10e08e33675949951d00b3ba487e8fc9b35cceffc985d96f6fb16e2c25456f");
    CCBigNumRef output = CCCreateBigNum(&status);
    
    status = CCBigNumDiv(output, NULL, a, c);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected) == 0, "expected operation result");
    
    status = CCBigNumDiv(output, NULL, a, c2);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected2) == 0, "expected operation result");

    CCBigNumFree(a);
    CCBigNumFree(c);
    CCBigNumFree(c2);
    CCBigNumFree(output);
    CCBigNumFree(resultExpected);
    CCBigNumFree(resultExpected2);
    return 0;
}


static int testMulMod()
{
    CCStatus status;
    
    // Shift n right by 11
    CCBigNumRef a = CCBigNumFromHexString(&status, "c968e40c5304364b057425920b18cc358f254ddb0f42f84850d6deec46006b4a692e52b7c3bddead45f77f2c1be1c606521d8a24260429f362d65b57873dbf270e97e210b872e45e97cb4cd87977ad20491e53c48cf0e88da9a61312675a2527c86ac537740c5e4206972f09c0f91fa1c9f14a2cf1be07e82a3b6fd58dc12c3a");
    CCBigNumRef c = CCBigNumFromHexString(&status, "354c912b09ee7abff5b3d94ed52a9e8dcae582e094daa375c495f970710af73efcc4f9776010511f654c7408a6d5d351ab1d94a0fede757d782b54ddcf6fe8d714870b78b0e67a9754cb03a5cf63bbda1c71791902ea4527fb0cd76437391e5422c704ffb6d6018261171d8cee98adcf0243f1fd520fb3761afe94a2f4d99f94");
    CCBigNumRef mod1 = CCBigNumFromHexString(&status, "912b09ee7abff5b3d94ed52a9e8dcae582e094daa375c495f970710af73efcc4f9776010511f654c7408a6d5d351ab1d94a0fede757d782b54ddcf6fe8d714870b78b0e67a9754cb03a5cf63bbda1c71791902ea4527fb0cd76437391e5422c704ffb6d6018261171d8cee98adcf0243f1fd520fb3761afe94a2f4d99f94");
    CCBigNumRef mod2 = CCBigNumFromHexString(&status, "43"); // dec 67
    CCBigNumRef resultExpected1 = CCBigNumFromHexString(&status, "57c1dfcd53105f1f653539172a789fc97067101320d12b93dd400eaad0bbb9d8d9857beeeae28c1ad0614075f1d59bb12556f78d85e4af9d2283fa5d3c192a03a59932dd537d4c1a9d74a8a2d647f266cc4fe9365c5c9b8ac4d5afc960002850243b2175eb09842d1f1cfd59bdd5c2564cb056586d2186aae39583061a88");
    CCBigNumRef resultExpected2 = CCBigNumFromHexString(&status, "3d");
    CCBigNumRef output = CCCreateBigNum(&status);
    
    status = CCBigNumMulMod(output, a, c, mod1);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected1) == 0, "expected operation result");
    
    status = CCBigNumMulMod(output, a, c, mod2);
    ok(status == 0, "operation completed");
    ok(CCBigNumCompare(output, resultExpected2) == 0, "expected operation result");
 
    CCBigNumFree(a);
    CCBigNumFree(c);
    CCBigNumFree(output);
    CCBigNumFree(resultExpected1);
    CCBigNumFree(resultExpected2);
    CCBigNumFree(mod1);
    CCBigNumFree(mod2);
    return 0;
}




int CommonBigNum(int argc, char *const *argv) {

    
	plan_tests(kTestTestCount);

    for(int i=0; i<10; i++) {
        testCreateFree();
        testHexString();
        testData();
        testI();
        testCompare();
        testBitCount();
        testAddSub();
        testAddSubI();
        testShift();
        testMod();
        testModI();
        testModExp();
        testMul();
        testMulI();
        testPrime();
        testDiv();
        testMulMod();
    }

    return 0;
}
#endif /* CCBigNum */

Added CCRegression/CommonCrypto/CommonCMac.c.















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
//  CCCMACtests.c
//  CCRegressions
//

#include <stdio.h>
#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"

#if (CCCMAC == 0)
entryPoint(CommonCMac,"Common CMac")
#else

#include <CommonCrypto/CommonCMACSPI.h>

static int
CMACTest(char *input, char *keystr, char *expected)
{
    byteBuffer mdBuf;
    byteBuffer inputBytes, expectedBytes, keyBytes;
    char *digestName;
    char outbuf[160];
    int retval = 0;
    
    inputBytes = hexStringToBytes(input);
    expectedBytes = hexStringToBytes(expected);
    keyBytes = hexStringToBytes(keystr);
    mdBuf = mallocByteBuffer(CC_CMACAES_DIGEST_LENGTH); digestName = "CMAC-AES"; 
    CCAESCmac(keyBytes->bytes, inputBytes->bytes, inputBytes->len, mdBuf->bytes);
    
	sprintf(outbuf, "Hmac-%s test for %s", digestName, input);
    
    ok(bytesAreEqual(mdBuf, expectedBytes), outbuf);
    
    if(!bytesAreEqual(mdBuf, expectedBytes)) {
        diag("HMAC FAIL: HMAC-%s(\"%s\")\n expected %s\n      got %s\n", digestName, input, expected, bytesToHexString(mdBuf));
        retval = 1;
    } else {
        // diag("HMAC PASS: HMAC-%s(\"%s\")\n", digestName, input);
    }
    
    free(mdBuf);
    free(expectedBytes);
    free(keyBytes);
    free(inputBytes);
    return retval;
}

static int kTestTestCount = 4;

int CommonCMac (int argc, char *const *argv) {
	char *strvalue, *keyvalue;
	plan_tests(kTestTestCount);
    int accum = 0;
    
    strvalue = "";
    keyvalue = "2b7e151628aed2a6abf7158809cf4f3c";
	accum |= CMACTest(strvalue, keyvalue, "bb1d6929e95937287fa37d129b756746");   
    strvalue = "6bc1bee22e409f96e93d7e117393172a";
	accum |= CMACTest(strvalue, keyvalue, "070a16b46b4d4144f79bdd9dd04a287c");   
    strvalue = "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411";
	accum |= CMACTest(strvalue, keyvalue, "dfa66747de9ae63030ca32611497c827");   
    strvalue = "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710";
	accum |= CMACTest(strvalue, keyvalue, "51f0bebf7e3b9d92fc49741779363cfe");  
    
    return accum;
}
#endif


Added CCRegression/CommonCrypto/CommonCryptoCTSPadding.c.

























































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

#include <stdio.h>
#include <stdint.h>
#include <CommonCrypto/CommonCryptor.h>
#include <CommonCrypto/CommonCryptorSPI.h>
#include "CCCryptorTestFuncs.h"
#include "testbyteBuffer.h"
#include "capabilities.h"
#include "testmore.h"

#if (CCPADCTS == 0)
entryPoint(CommonCryptoCTSPadding,"CommonCrypto CTS Padding Testing")

#else

static int kTestTestCount = 9;

int CommonCryptoCTSPadding(int argc, char *const *argv)
{
	char *keyStr;
	char *iv;
	char *plainText;
	char *cipherText;
    CCMode mode;
    CCAlgorithm alg;
    CCPadding padding;
    int retval, accum = 0;
    char *test;
    
	keyStr 	   = "636869636b656e207465726979616b69";
	iv         = "0f0e0d0c0b0a09080706050403020100";
    mode 	   = kCCModeCBC;
    alg		= kCCAlgorithmAES128;
    padding = ccCBCCTS1;
    
	plan_tests(kTestTestCount);
    
    test = "CTS1 Test - Length 64";
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "e22abba9d2a201b18dc2f57e04aba21a16e0ed6358164c59ca64d204f33247ee2dc88b70f6ae0243d2dbcd6822a1058604b1c432a7a71395b36d820e2c3de4ee";
    diag(test);
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, test);
    accum += retval;
    
    test = "CTS1 Test - Length 63";
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "e22abba9d2a201b18dc2f57e04aba21a16e0ed6358164c59ca64d204f33247ee2dc88b70f6ae0243d2dbcd6822a105950b6576660739916d058623d688e27e";
    diag(test);
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, test);
    accum += retval;
    
    test = "CTS1 Test - Length 57";
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "e22abba9d2a201b18dc2f57e04aba21a16e0ed6358164c59ca64d204f33247ee2dc88b70f6ae0243d2db751002ef7a0f9d915d15346571eee7aa";
    diag(test);
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, test);
    accum += retval;
    
    
    padding = ccCBCCTS2;
    
    test = "CTS2 Test - Length 64";
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "e22abba9d2a201b18dc2f57e04aba21a16e0ed6358164c59ca64d204f33247ee2dc88b70f6ae0243d2dbcd6822a1058604b1c432a7a71395b36d820e2c3de4ee";
    diag(test);
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, test);
    accum += retval;
    
    test = "CTS2 Test - Length 63";
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "e22abba9d2a201b18dc2f57e04aba21a16e0ed6358164c59ca64d204f33247ee950b6576660739916d058623d688e27e2dc88b70f6ae0243d2dbcd6822a105";
    diag(test);
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, test);
    accum += retval;
    
    test = "CTS2 Test - Length 57";
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "e22abba9d2a201b18dc2f57e04aba21a16e0ed6358164c59ca64d204f33247ee751002ef7a0f9d915d15346571eee7aa2dc88b70f6ae0243d2db";
    diag(test);
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, test);
    accum += retval;
    
    padding = ccCBCCTS3;
    
    test = "CTS3 Test - Length 64";
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "e22abba9d2a201b18dc2f57e04aba21a16e0ed6358164c59ca64d204f33247ee04b1c432a7a71395b36d820e2c3de4ee2dc88b70f6ae0243d2dbcd6822a10586";
    diag(test);
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, test);
    accum += retval;
    
    test = "CTS3 Test - Length 63";
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "e22abba9d2a201b18dc2f57e04aba21a16e0ed6358164c59ca64d204f33247ee950b6576660739916d058623d688e27e2dc88b70f6ae0243d2dbcd6822a105";
    diag(test);
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, test);
    accum += retval;
    
    test = "CTS3 Test - Length 57";
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "e22abba9d2a201b18dc2f57e04aba21a16e0ed6358164c59ca64d204f33247ee751002ef7a0f9d915d15346571eee7aa2dc88b70f6ae0243d2db";
    diag(test);
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, test);
    accum += retval;
    
    
    return accum != 0;
}
#endif

Added CCRegression/CommonCrypto/CommonCryptoReset.c.

































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//
//  CommonCryptoReset.c
//  CommonCrypto
//
//  Created by Richard Murphy on 2/10/12.
//  Copyright (c) 2012 McKenzie-Murphy. All rights reserved.
//

#include "capabilities.h"
#include <stdio.h>
#include <string.h>
#include <CommonCrypto/CommonCryptor.h>
#include <CommonCrypto/CommonCryptorSPI.h>
#include "CCCryptorTestFuncs.h"
#include "testbyteBuffer.h"
#include "testmore.h"





#if (CCRESET == 0)
entryPoint(CommonCryptoReset,"CommonCrypto Reset Testing")
#else




static int kTestTestCount = 13;

int CommonCryptoReset(int argc, char *const *argv)
{
    CCCryptorRef cref;
	CCCryptorStatus retval;
    size_t moved;
    uint8_t key[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
    uint8_t plain[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
    uint8_t nulliv[16];
    uint8_t cipher1[16], cipher2[16], cipher3[16], cipher4[16], cipher5[16], unused[16];
    
	plan_tests(kTestTestCount);

    bzero(nulliv, 16);
    
   	retval = CCCryptorCreateWithMode(kCCEncrypt, kCCModeCBC, kCCAlgorithmAES128, 
                                     ccNoPadding, NULL, key, 16, NULL, 0, 0, 0, &cref);

    ok(retval == kCCSuccess, "cryptor created");
    
    retval = CCCryptorUpdate(cref, plain, 16, cipher1, 16, &moved);
    
    ok((retval == kCCSuccess && moved == 16), "first update");

    retval = CCCryptorUpdate(cref, plain, 16, cipher2, 16, &moved);
    
    ok((retval == kCCSuccess && moved == 16), "second (chained) update");
    
    ok(memcmp(cipher1, cipher2, 16) != 0, "chained crypts shouldn't be the same even with the same data");
    
    retval = CCCryptorReset(cref, NULL);
    
    ok(retval == kCCSuccess, "cryptor NULL reset");

    retval = CCCryptorUpdate(cref, plain, 16, cipher3, 16, &moved);
    
    ok((retval == kCCSuccess && moved == 16), "third update - NULL Reset");
    
    ok(memcmp(cipher1, cipher3, 16) == 0, "reset crypt should be the same as the start");

    retval = CCCryptorReset(cref, nulliv);
   
    ok(retval == kCCSuccess, "cryptor zero iv reset");

    retval = CCCryptorUpdate(cref, plain, 16, cipher4, 16, &moved);
    
    ok((retval == kCCSuccess && moved == 16), "fourth update - zero iv Reset");
    
    ok(memcmp(cipher1, cipher4, 16) == 0, "reset crypt should be the same as the start");
    
    retval = CCCryptorUpdate(cref, plain, 16, cipher5, 16, &moved);
    
    ok((retval == kCCSuccess && moved == 16), "fifth (chained) update");
    
    ok(memcmp(cipher2, cipher5, 16) == 0, "reset crypt should be the same as the second");

    retval = CCCryptorFinal(cref, unused, 16, &moved);
        
    ok((retval == kCCSuccess && moved == 0), "Final - no work");

	CCCryptorRelease(cref);
    
    return kCCSuccess;

}

#endif

Added CCRegression/CommonCrypto/CommonCryptoSymCBC.c.























































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  CBCTest.c
 *  CommonCrypto
 */

#include <stdio.h>
#include "CCCryptorTestFuncs.h"
#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"

#if (CCSYMCBC == 0)
entryPoint(CommonCryptoSymCBC,"CommonCrypto Symmetric CBC Testing")
#else


static int kTestTestCount = 28;

int CommonCryptoSymCBC(int argc, char *const *argv) {
	char *keyStr;
	char *iv;
	char *plainText;
	char *cipherText;
    CCAlgorithm alg;
    CCOptions options;
	int retval;
    int accum = 0;

	keyStr 	   = "000102030405060708090a0b0c0d0e0f";
	iv         = "0f0e0d0c0b0a09080706050403020100";
    alg		   = kCCAlgorithmAES128;
    options    = kCCOptionPKCS7Padding;
    
	plan_tests(kTestTestCount);
    
    accum = (int) genRandomSize(1,10);
	// 1
	plainText  = "0a";
	cipherText = "a385b047a4108a8748bf96b435738213";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 1 byte CCCrypt");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 1 byte Multiple Updates");
    accum |= retval;

	// 15
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "324a44cf3395b14214861084019f9257";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 15 byte CCCrypt");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 15 byte Multiple Updates");
    accum |= retval;

	// 16
    plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "16d67a52c1e8384f7ed887c2011605346544febcf84574c334f1145d17567047";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 16 byte CCCrypt");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 16 byte Multiple Updates");
    accum |= retval;

	// 17
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "16d67a52c1e8384f7ed887c2011605348b72cecb00bbc00f328af6bb69085b02";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 17 byte CCCrypt");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 17 byte Multiple Updates");
    accum |= retval;

	// 31
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "16d67a52c1e8384f7ed887c2011605347175cf878a75bc1947ae79c6c6835030";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 31 byte CCCrypt");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 31 byte Multiple Updates");
    accum |= retval;

	// 32
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "16d67a52c1e8384f7ed887c20116053486869f3b83f3b3a83531e4169e97b7244a49199daa033fa88f07dd4be52ae78e";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 32 byte CCCrypt");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 32 byte Multiple Updates");
    accum |= retval;

	// 33
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "16d67a52c1e8384f7ed887c20116053486869f3b83f3b3a83531e4169e97b724d0080fb874dd556fa86b314acc4f597b";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 33 byte CCCrypt");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 33 byte Multiple Updates");
    accum |= retval;
    
    iv = NULL;
	// 1
	plainText  = "0a";
	cipherText = "27cae51ac763b250945fd805c937119b";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 1 byte CCCrypt NULL IV");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 1 byte Multiple Updates NULL IV");
    accum |= retval;

	// 15
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "feb9c3a005dcbd1e2630af742e988e81";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 15 byte CCCrypt NULL IV");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 15 byte Multiple Updates NULL IV");
    accum |= retval;

	// 16
    plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "d307b25d3abaf87c0053e8188152992a8b002a94911ee1e157d815a026cfadeb";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 16 byte CCCrypt NULL IV");
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 16 byte Multiple Updates NULL IV");
    accum |= retval;

	// 17
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "d307b25d3abaf87c0053e8188152992ab8fe4130b613e93617b2eda2e0c5c678";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 17 byte CCCrypt NULL IV");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 17 byte Multiple Updates NULL IV");
    accum |= retval;

	// 31
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "d307b25d3abaf87c0053e8188152992a4157ad665141a79481f463357707f759";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 31 byte CCCrypt NULL IV");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 31 byte Multiple Updates NULL IV");
    accum |= retval;

	// 32
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "d307b25d3abaf87c0053e8188152992a923832530aa268661a6c1fa3c69d6a23dc6d5c0d7fa8127cfd601cae71b4c14f";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 32 byte CCCrypt NULL IV");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 32 byte Multiple Updates NULL IV");
    accum |= retval;

	// 33
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "d307b25d3abaf87c0053e8188152992a923832530aa268661a6c1fa3c69d6a2382178b537aa2946f7a4124ee33744edd";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 33 byte CCCrypt NULL IV");
    accum |= retval;
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    ok(retval == 0, "CBC with Padding 33 byte Multiple Updates NULL IV");
    accum |= retval;
    
    return accum != 0;
}
#endif

Added CCRegression/CommonCrypto/CommonCryptoSymCFB.c.











































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

#include <stdio.h>
#include "CCCryptorTestFuncs.h"
#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"

#if (CCSYMCFB == 0)
entryPoint(CommonCryptoSymCFB,"CommonCrypto Symmetric CFB Testing")
#else
static int kTestTestCount = 5;

int CommonCryptoSymCFB(int argc, char *const *argv)
{
	char *keyStr;
	char *iv;
	char *plainText;
	char *cipherText;
    CCMode mode;
    CCAlgorithm alg;
    CCPadding padding;
    int retval, accum = 0;
    
	keyStr 	   = "00000000000000000000000000000000";
    mode 	   = kCCModeCFB;
    alg		= kCCAlgorithmAES128;
    padding = ccNoPadding;
    
	plan_tests(kTestTestCount);
    
	plainText  = "00000000000000000000000000000000";
	iv         = "80000000000000000000000000000000";
	cipherText = "3ad78e726c1ec02b7ebfe92b23d9ec34";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, "CFB Test 1");
    accum += retval;
    
	plainText  = "00000000000000000000000000000000";
	iv         = "c0000000000000000000000000000000";
	cipherText = "aae5939c8efdf2f04e60b9fe7117b2c2";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, "CFB Test 2");
    accum += retval;
    
	plainText  = "00000000000000000000000000000000";
	iv         = "ffffffffffffffffffffffc000000000";
	cipherText = "90684a2ac55fe1ec2b8ebd5622520b73";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, "CFB Test 3");
    accum += retval;
    
	keyStr 	   = "f36f40aeb3e20c19440081919df4ecb9";
	plainText  = "5552ee4fbf25859cdfecf34742d640855c55a00a1c6aa571c322b4ddf561b6e110de0f9dbe6fd42ac687383928fc48f6680ed9332aa6bec2ffdb3e227fbac55f9847d93325bf5071c220c0a3dfeb38f214292d47b4acb7b0a597fe056f21eecb";
	iv         = "cf75d0cae8dbce85e0bc0e58eb4e82c0";
	cipherText = "d579c0e622047e0efef9ddacc94be36450d09366e38ea9e4ed3c2e39923f580fdc436a874e34fb39330f8a8a7bf1f68d8a93644a2b9d1fed260eb6e7c8ac874d616ec02b57d08f043aae552fc52bf11eb4a4ed5918ff81738b3ea3ce244c9cd1";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, "CFB Test 4");
    accum += retval;
    
	keyStr 	   = "02f5f980a3c6af2984c9eed684f5224f";
	plainText  = "cb9056b3c195cef43da2634271f2f34e556868ac41d0ea35bb6854aa8e9fe49a1c1c3685f4027341a773c69dd8530f45934edce5e01c95919703f665759ec26870deb6b6484ebcdf5f9b628aca538a5ea8ed6322b20a982214fac7d57c8234be70dcbf90e40013950c2221506f7ccd623d4de6aae2225cb0db54ad44c8d2a162c3203759f1a0df2c5611e939ee553e18f9774ec696ec4903931992f88416711d";
	iv         = "7844c96a2c65e9c334573b9894d91046";
	cipherText = "227d8e80650e60c1c9e9ab2f8fe8bc24185725f1f1b8e326b73c04501e91995d5a7be17d0c74ce1cd2d5a3d917738dea486fb523297aea2badc6f8766ffdfcc6e8efd640a8d5d1f55d1e4fe4f03bb9f66956eaa9864ee760d1ad3e5faaae6da36476c55d1f25d7c064b9c518ce5b3f42ecdb1c3ef57c7b3fa3ef188218d0d0c417056935bcc76a90ff277f9e698ff9a599ebaa6c2723288c9f0817694e400ce6";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, "CFB Test 5");
    accum += retval;
    
    keyStr 	   = "e0000000000000000000000000000000";
    iv         = NULL;
    plainText  = "00000000000000000000000000000000";
    cipherText = "72a1da770f5d7ac4c9ef94d822affd97";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, "CFB Test NULLIV");
    accum += retval;

    
    return accum != 0;
}
#endif

Added CCRegression/CommonCrypto/CommonCryptoSymCTR.c.





































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

#include <stdio.h>
#include <CommonCrypto/CommonCryptor.h>
#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"

#if (CCSYMCTR == 0)
entryPoint(CommonCryptoSymCTR,"CommonCrypto Symmetric CTR Testing")
#else
static int kTestTestCount = 10;

static CCCryptorStatus doCrypt(char *in, char *out, CCCryptorRef cryptor) {
    byteBuffer inbb = hexStringToBytes(in);
    byteBuffer outbb = hexStringToBytes(out);
    byteBuffer buf = mallocByteBuffer(64);
    CCCryptorStatus retval = CCCryptorUpdate(cryptor, inbb->bytes, inbb->len, buf->bytes, buf->len, &buf->len);
    if(!retval) {
        ok(bytesAreEqual(outbb, buf), "crypt results are equal");
    }
    return retval;
}

int CommonCryptoSymCTR(int argc, char *const *argv)
{
    CCCryptorStatus retval;
    CCCryptorRef cryptor;
    
	plan_tests(kTestTestCount);
    
    byteBuffer key = hexStringToBytes("2b7e151628aed2a6abf7158809cf4f3c");
    byteBuffer counter = hexStringToBytes("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff");
    
    retval = CCCryptorCreateWithMode(kCCEncrypt, kCCModeCTR, kCCAlgorithmAES128, 
                                     ccNoPadding, counter->bytes, key->bytes, key->len, 
                                     NULL, 0, 0, kCCModeOptionCTR_LE, &cryptor);

    
    ok(retval == kCCUnimplemented, "CTR Mode Encrypt unavailable for kCCModeOptionCTR_LE");

    retval = CCCryptorCreateWithMode(kCCEncrypt, kCCModeCTR, kCCAlgorithmAES128, 
                                     ccNoPadding, counter->bytes, key->bytes, key->len, 
                                     NULL, 0, 0, kCCModeOptionCTR_BE, &cryptor);
                                     
    ok(retval == kCCSuccess, "CTR Mode Encrypt");

    retval = doCrypt("6bc1bee22e409f96e93d7e117393172a",
                     "874d6191b620e3261bef6864990db6ce",
                     cryptor);
   
    
    ok(retval == kCCSuccess, "CTR Mode Encrypt");

    retval = doCrypt("ae2d8a571e03ac9c9eb76fac45af8e51",
                     "9806f66b7970fdff8617187bb9fffdff",
                     cryptor);
    
    
    ok(retval == kCCSuccess, "CTR Mode Encrypt");

    retval = doCrypt("30c81c46a35ce411e5fbc1191a0a52ef",
                     "5ae4df3edbd5d35e5b4f09020db03eab",
                     cryptor);
    
    ok(retval == kCCSuccess, "CTR Mode Encrypt");

    retval = doCrypt("f69f2445df4f9b17ad2b417be66c3710",
                     "1e031dda2fbe03d1792170a0f3009cee",
                     cryptor);
    
    ok(retval == kCCSuccess, "CTR Mode Encrypt");
    

    return 0;
}
#endif

Added CCRegression/CommonCrypto/CommonCryptoSymGCM.c.





























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  CCGCMTest.c
 *  CommonCrypto
 */

#include "capabilities.h"
#include <stdio.h>
#include <CommonCrypto/CommonCryptor.h>
#include <CommonCrypto/CommonCryptorSPI.h>
#include "CCCryptorTestFuncs.h"
#include "testbyteBuffer.h"
#include "testmore.h"

#if (CCSYMGCM == 0)
entryPoint(CommonCryptoSymGCM,"CommonCrypto Symmetric GCM Testing")
#else




static int kTestTestCount = 7;

int CommonCryptoSymGCM(int argc, char *const *argv) {
	char *keyStr;
	char *iv;
	char *plainText;
	char *cipherText;
    char *adata;
    char *tag;
    CCAlgorithm alg;
	int retval, accum = 0;

    alg		   = kCCAlgorithmAES128;
    
	plan_tests(kTestTestCount);
    
    /* testcase #1 */

    keyStr =     "00000000000000000000000000000000";
    adata =      "";
    iv =         "000000000000000000000000";
    plainText =  "";
    cipherText = "";
    tag =        "58e2fccefa7e3061367f1d57a4e7455a";

    retval = CCCryptorGCMTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    retval = CCCryptorGCMDiscreetTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    
    ok(retval == 0, "AES-GCM Testcase 1");
    accum += retval;
    
    /* testcase #2 */

    keyStr =     "00000000000000000000000000000000";
    adata =      "";
    iv =         "000000000000000000000000";
    plainText =  "00000000000000000000000000000000";
    cipherText = "0388dace60b6a392f328c2b971b2fe78";
    tag =        "ab6e47d42cec13bdf53a67b21257bddf";

    retval = CCCryptorGCMTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    retval = CCCryptorGCMDiscreetTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    ok(retval == 0, "AES-GCM Testcase 2");
    accum += retval;

    /* testcase #3 */

    keyStr =     "feffe9928665731c6d6a8f9467308308";
    adata =      "";
    iv =         "cafebabefacedbaddecaf888";
    plainText =  "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255";
    cipherText = "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f5985";
    tag =        "4d5c2af327cd64a62cf35abd2ba6fab4";

    retval = CCCryptorGCMTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    retval = CCCryptorGCMDiscreetTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    ok(retval == 0, "AES-GCM Testcase 3");
    accum += retval;

    /* testcase #4 */

    keyStr =     "feffe9928665731c6d6a8f9467308308";
    adata =      "feedfacedeadbeeffeedfacedeadbeefabaddad2";
    iv =         "cafebabefacedbaddecaf888";
    plainText =  "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39";
    cipherText = "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091";
    tag =        "5bc94fbc3221a5db94fae95ae7121a47";

    retval = CCCryptorGCMTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    retval = CCCryptorGCMDiscreetTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    ok(retval == 0, "AES-GCM Testcase 4");
    accum += retval;

    /* testcase #5 */

    keyStr =     "feffe9928665731c6d6a8f9467308308";
    adata =      "feedfacedeadbeeffeedfacedeadbeefabaddad2";
    iv =         "cafebabefacedbad";
    plainText =  "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39";
    cipherText = "61353b4c2806934a777ff51fa22a4755699b2a714fcdc6f83766e5f97b6c742373806900e49f24b22b097544d4896b424989b5e1ebac0f07c23f4598";
    tag =        "3612d2e79e3b0785561be14aaca2fccb";

    retval = CCCryptorGCMTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    retval = CCCryptorGCMDiscreetTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    ok(retval == 0, "AES-GCM Testcase 5");
    accum += retval;

    /* testcase #6 */

    keyStr =     "feffe9928665731c6d6a8f9467308308";
    adata = "feedfacedeadbeeffeedfacedeadbeefabaddad2";
    iv = "9313225df88406e555909c5aff5269aa6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b525416aedbf5a0de6a57a637b39b";
    plainText = "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39";
    cipherText = "8ce24998625615b603a033aca13fb894be9112a5c3a211a8ba262a3cca7e2ca701e4a9a4fba43c90ccdcb281d48c7c6fd62875d2aca417034c34aee5";
    tag = "619cc5aefffe0bfa462af43c1699d050";

    retval = CCCryptorGCMTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    retval = CCCryptorGCMDiscreetTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    ok(retval == 0, "AES-GCM Testcase 6");
    accum += retval;

    /* testcase #46 from BG (catchestheLTCbugofv1.15) */
    keyStr = "00000000000000000000000000000000";
    adata =  "688e1aa984de926dc7b4c47f44";
    iv =     "b72138b5a05ff5070e8cd94183f761d8";
    plainText =  "a2aab3ad8b17acdda288426cd7c429b7ca86b7aca05809c70ce82db25711cb5302eb2743b036f3d750d6cf0dc0acb92950d546db308f93b4ff244afa9dc72bcd758d2c";
    cipherText = "cbc8d2f15481a4cc7dd1e19aaa83de5678483ec359ae7dec2ab8d534e0906f4b4663faff58a8b2d733b845eef7c9b331e9e10eb2612c995feb1ac15a6286cce8b297a8";
    tag =    "8d2d2a9372626f6bee8580276a6366bf";

    retval = CCCryptorGCMTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    retval = CCCryptorGCMDiscreetTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    ok(retval == 0, "AES-GCM Testcase 7");
    accum += retval;

    /* testcase #8 - #1 with NULL IV and AAD */
    
    keyStr =     "00000000000000000000000000000000";
    adata =      "";
    iv =         "";
    plainText =  "";
    cipherText = "";
    tag =        "66e94bd4ef8a2c3b884cfa59ca342b2e";
    
    retval = CCCryptorGCMTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);
    retval = CCCryptorGCMDiscreetTestCase(keyStr, iv, adata, tag, alg, cipherText, plainText);


    return accum != 0;
}
#endif

Added CCRegression/CommonCrypto/CommonCryptoSymOFB.c.











































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

#include <stdio.h>
#include "CCCryptorTestFuncs.h"
#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"

#if (CCSYMOFB == 0)
entryPoint(CommonCryptoSymOFB,"CommonCrypto Symmetric OFB Testing")
#else
static int kTestTestCount = 5;

int CommonCryptoSymOFB(int argc, char *const *argv)
{
	char *keyStr;
	char *iv;
	char *plainText;
	char *cipherText;
    CCMode mode;
    CCAlgorithm alg;
    CCPadding padding;
    int retval, accum = 0;
    
	keyStr 	   = "000102030405060708090a0b0c0d0e0f";
	iv         = "0f0e0d0c0b0a09080706050403020100";
    mode 	   = kCCModeOFB;
    alg		= kCCAlgorithmAES128;
    padding = ccNoPadding;
    
	plan_tests(kTestTestCount);
    
	// 1
	plainText  = "0a";
	cipherText = "2a";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, "OFB Mode single byte");
    accum += retval;
    
	// 15
	plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "2aa3f398be4651e20e15f6d666a493a";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, "OFB Mode 15 byte");
    accum += retval;
    
	// 16
    plainText  = "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a";
	cipherText = "2aa3f398be4651e20e15f6d666a49360a";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, "OFB Mode single byte");
    accum += retval;
    
	// from OFBVarTxt256e KAT test 1
	keyStr 	   = "0000000000000000000000000000000000000000000000000000000000000000";
	iv         = "80000000000000000000000000000000";
    mode 	   = kCCModeOFB;
    alg		= kCCAlgorithmAES128;
    padding = ccNoPadding;
    plainText  = "00000000000000000000000000000000";
	cipherText = "ddc6bf790c15760d8d9aeb6f9a75fd4e";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
	ok(retval == 0, "OFB Mode OFBVarTxt256e KAT test 1");
    accum += retval;
    
	// from OFBVarTxt256e KAT test 13
	keyStr 	   = "0000000000000000000000000000000000000000000000000000000000000000";
	iv         = "fffc0000000000000000000000000000";
    mode 	   = kCCModeOFB;
    alg		= kCCAlgorithmAES128;
    padding = ccNoPadding;
    plainText  = "00000000000000000000000000000000";
	cipherText = "dc8f0e4915fd81ba70a331310882f6da";
    retval = CCModeTestCase(keyStr, iv, mode, alg, padding, cipherText, plainText);
    ok(retval == 0, "OFB Mode OFBVarTxt256e KAT test 13");
    accum += retval;
    
    return accum != 0;
}
#endif

Added CCRegression/CommonCrypto/CommonCryptoSymOffset.c.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  CCSymOffset.c
 *  CommonCrypto
 */

#include <stdio.h>
#include <CommonCrypto/CommonCryptor.h>
#include <CommonCrypto/CommonCryptorSPI.h>
#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"

#if (CCSYMOFFSET == 0)
entryPoint(CommonCryptoSymOffset,"CommonCrypto Symmetric Unaligned Testing")
#else



#define ILIKEEMDISBIG 4096
#define ALITTLEONTHESIDE 5


static int kTestTestCount = ALITTLEONTHESIDE;


int CommonCryptoSymOffset(int argc, char *const *argv) {
    int accum = 0;
    uint8_t iLikeBigBuffs[ILIKEEMDISBIG];
    uint8_t andICannotLie[ILIKEEMDISBIG];
    uint8_t iLikeEmRoundandBig[ILIKEEMDISBIG];
    int i;
    size_t moved;
    CCCryptorStatus retval;
    byteBuffer key = hexStringToBytes("010203040506070809000a0b0c0d0e0f");
    
    plan_tests(kTestTestCount);

    
    for(i=0; i<ALITTLEONTHESIDE; i++) {
        retval = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, 0, key->bytes, key->len, NULL, iLikeBigBuffs+i, ILIKEEMDISBIG-16, andICannotLie+i, ILIKEEMDISBIG, &moved);
        retval = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0, key->bytes, key->len, NULL, andICannotLie+i, moved, iLikeEmRoundandBig+i, ILIKEEMDISBIG, &moved);
        if(moved != (ILIKEEMDISBIG-16))
            retval = 99;
        else if(memcmp(iLikeBigBuffs+i, iLikeEmRoundandBig+i, moved))
            retval = 999;
        ok(retval == 0, "Encrypt/Decrypt Cycle");
        accum += retval;
    }
    
    return accum != 0;
}
#endif

Added CCRegression/CommonCrypto/CommonCryptoSymRC2.c.



















































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  CCRC2KAT.c
 *  CCRegressions
 *
 */

#include <stdio.h>
#include "CCCryptorTestFuncs.h"
#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"

#if (CCSYMRC2 == 0)
entryPoint(CommonCryptoSymRC2,"Common Crypto RC2 Test")
#else


#ifdef WEIRDCASE
static int kTestTestCount = 12;
#else
static int kTestTestCount = 8;
#endif


int CommonCryptoSymRC2(int argc, char *const *argv) {
	char *keyStr;
	char *iv;
	char *plainText;
	char *cipherText;
    CCAlgorithm alg;
    CCOptions options;
	int retval;
    int rkeylen, ekeylenBits;
    char printString[128];

    alg = kCCAlgorithmRC2;
    iv = NULL;
    options = 0;
	plan_tests(kTestTestCount);

    rkeylen = 8;
    ekeylenBits = 63;
    keyStr =    "0000000000000000";
    plainText = "0000000000000000";
    cipherText = "ebb773f993278eff";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) One-Shot", rkeylen, ekeylenBits);
    ok(retval == 0, printString);
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) Multi", rkeylen, ekeylenBits);
    ok(retval == 0, printString);

    rkeylen = 8;
    ekeylenBits = 64;
    keyStr =    "ffffffffffffffff";
    plainText = "ffffffffffffffff";
    cipherText = "278b27e42e2f0d49";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) One-Shot", rkeylen, ekeylenBits);
    ok(retval == 0, printString);
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) Multi", rkeylen, ekeylenBits);
    ok(retval == 0, printString);

    rkeylen = 8;
    ekeylenBits = 64;
    keyStr =    "3000000000000000";
    plainText = "1000000000000001";
    cipherText = "30649edf9be7d2c2";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) One-Shot", rkeylen, ekeylenBits);
    ok(retval == 0, printString);
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) Multi", rkeylen, ekeylenBits);
    ok(retval == 0, printString);

#ifdef WEIRDCASE
    rkeylen = 1;
    ekeylenBits = 64;
    keyStr =    "88";
    plainText = "0000000000000000";
    cipherText = "61a8a244adacccf0";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) One-Shot", rkeylen, ekeylenBits);
    ok(retval == 0, printString);
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) Multi", rkeylen, ekeylenBits);
    ok(retval == 0, printString);

    rkeylen = 7;
    ekeylenBits = 64;
    keyStr = "88bca90e90875a";
    plainText = "0000000000000000";
    cipherText = "6ccf4308974c267f";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) One-Shot", rkeylen, ekeylenBits);
    ok(retval == 0, printString);
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) Multi", rkeylen, ekeylenBits);
    ok(retval == 0, printString);
    
    rkeylen = 16;
    ekeylenBits = 64;
    keyStr = "88bca90e90875a7f0f79c384627bafb2";
    plainText = "0000000000000000";
    cipherText = "1a807d272bbe5db1";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) One-Shot", rkeylen, ekeylenBits);
    ok(retval == 0, printString);
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) Multi", rkeylen, ekeylenBits);
    ok(retval == 0, printString);
#endif

    rkeylen = 16;
    ekeylenBits = 128;
    keyStr = "88bca90e90875a7f0f79c384627bafb2";
    plainText = "0000000000000000";
    cipherText = "2269552ab0f85ca6";
    retval = CCCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) One-Shot", rkeylen, ekeylenBits);
    ok(retval == 0, printString);
    retval = CCMultiCryptTestCase(keyStr, iv, alg, options, cipherText, plainText);
    sprintf(printString, "RC2 %d byte Key (effective %d bits) Multi", rkeylen, ekeylenBits);
    ok(retval == 0, printString);

    
    return 0;
}
#endif

Added CCRegression/CommonCrypto/CommonCryptoSymRegression.c.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
/* Copyright 2006 Apple Computer, Inc.
 *
 * ccSymTest.c - test CommonCrypto symmetric encrypt/decrypt.
 */
#include "testmore.h"
#include "capabilities.h"
#if (CCSYMREGRESSION == 0)
entryPoint(CommonCryptoSymRegression,"CommonCrypto Base Behavior Regression Tests")
#else



#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <CommonCrypto/CommonCryptor.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>

// #include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacErrors.h>

/*
 * Defaults.
 */
#define LOOPS_DEF		500
#define MIN_DATA_SIZE	8
#define MAX_DATA_SIZE	10000						/* bytes */
#define MAX_KEY_SIZE	kCCKeySizeMaxRC4			/* bytes */
#define MAX_BLOCK_SIZE	kCCBlockSizeAES128			/* bytes */
#define LOOP_NOTIFY		250

/*
 * Enumerate algs our own way to allow iteration.
 */
typedef enum {
	ALG_AES_128 = 1,	/* 128 bit block, 128 bit key */
	ALG_AES_192,		/* 128 bit block, 192 bit key */
	ALG_AES_256,		/* 128 bit block, 256 bit key */
	ALG_DES,
	ALG_3DES,
	ALG_CAST,
	ALG_RC4,
	/* these aren't in CommonCrypto (yet?) */
	ALG_RC2,
	ALG_RC5,
	ALG_BFISH,
	ALG_ASC,
	ALG_NULL					/* normally not used */
} SymAlg;
#define ALG_FIRST			ALG_AES_128
#define ALG_LAST			ALG_RC4


#define LOG_SIZE			0
#if		LOG_SIZE
#define logSize(s)	diag s
#else
#define logSize(s)
#endif




static void
appGetRandomBytes(void *keyBytes, size_t keySizeInBytes)
{
	int fd;
    
    if((fd = open("/dev/random", O_RDONLY)) < 0) {
    	diag("Can't open Random\n");
        exit(0);
    }
    if(read(fd, keyBytes, keySizeInBytes) != keySizeInBytes) {
		diag("Can't read Random\n");
        exit(0);
    }
    close(fd);
}

/* min <= return <= max */
static unsigned 
genRand(unsigned min, unsigned max)
{
	unsigned i;
	if(min == max) {
		return min;
	}
	appGetRandomBytes(&i, 4);
	return (min + (i % (max - min + 1)));
}	


static void printCCError(const char *str, CCCryptorStatus crtn)
{
	const char *errStr;
	char unknownStr[200];
	
	switch(crtn) {
		case kCCSuccess: errStr = "kCCSuccess"; break;
		case kCCParamError: errStr = "kCCParamError"; break;
		case kCCBufferTooSmall: errStr = "kCCBufferTooSmall"; break;
		case kCCMemoryFailure: errStr = "kCCMemoryFailure"; break;
		case kCCAlignmentError: errStr = "kCCAlignmentError"; break;
		case kCCDecodeError: errStr = "kCCDecodeError"; break;
		case kCCUnimplemented: errStr = "kCCUnimplemented"; break;
		default:
			sprintf(unknownStr, "Unknown(%ld)\n", (long)crtn);
			errStr = unknownStr;
			break;
	}
	diag("***%s returned %s\n", str, errStr);
}

/* max context size */
#define CC_MAX_CTX_SIZE	kCCContextSizeRC4

/* 
 * We write a marker at end of expected output and at end of caller-allocated 
 * CCCryptorRef, and check at the end to make sure they weren't written 
 */
#define MARKER_LENGTH	8
#define MARKER_BYTE		0x7e

/* 
 * Test harness for CCCryptor with lots of options. 
 */
static CCCryptorStatus doCCCrypt(
	bool forEncrypt,
	CCAlgorithm encrAlg,			
	bool doCbc,
	bool doPadding,
	const void *keyBytes, size_t keyLen,
	const void *iv,
	bool randUpdates,
	bool inPlace,								/* !doPadding only */
	size_t ctxSize,								/* if nonzero, we allocate ctx */
	bool askOutSize,
	const uint8_t *inText, size_t inTextLen,
	uint8_t **outText, size_t *outTextLen)		/* both returned, WE malloc */
{
	CCCryptorRef	cryptor = NULL;
	CCCryptorStatus crtn;
	CCOperation		op = forEncrypt ? kCCEncrypt : kCCDecrypt;
	CCOptions		options = 0;
	uint8_t			*outBuf = NULL;			/* mallocd output buffer */
	uint8_t			*outp;					/* running ptr into outBuf */
	const uint8_t		*inp;					/* running ptr into inText */
	size_t			outLen = 0;					/* bytes remaining in outBuf */
	size_t			toMove;					/* bytes remaining in inText */
	size_t			thisMoveOut;			/* output from CCCryptUpdate()/CCCryptFinal() */
	size_t			outBytes;				/* total bytes actually produced in outBuf */
	char			ctx[CC_MAX_CTX_SIZE];	/* for CCCryptorCreateFromData() */
	uint8_t			*textMarker = NULL;		/* 8 bytes of marker here after expected end of 
											 * output */
	char			*ctxMarker = NULL;		/* ditto for caller-provided context */
	unsigned		dex;
	size_t			askedOutSize;			/* from the lib */
	size_t			thisOutLen;				/* dataOutAvailable we use */
	

	if(0) diag("%s %s %s keylen %d %s %s %s %s %s input length %ld\n", 
    	forEncrypt ? "Encrypting": "Decrypting", 
    	doCbc ? "CBC": "ECB", 
    	doPadding ? "Padding ON": "Padding OFF",
        (int) keyLen,
        iv ? "IV Provided": "No IV Provided",
		randUpdates ? "Random Updates": "Non-Random Updates", 
		inPlace ? "In Place": "Separate Buffers", 
    	ctxSize ? "We Allocate": "CC Allocated", 
    	askOutSize ? "Ask OutSize": "Don't Ask OutSize", 
		inTextLen);
         
	if(ctxSize > CC_MAX_CTX_SIZE) {
		diag("***HEY! Adjust CC_MAX_CTX_SIZE!\n");
		exit(1);
	}
	if(!doCbc) {
		options |= kCCOptionECBMode;
	}
	if(doPadding) {
		options |= kCCOptionPKCS7Padding;
	}
	
	/* just hack this one */
	outLen = inTextLen;
	if(forEncrypt) {
		outLen += MAX_BLOCK_SIZE;
	}
	
	outBuf = (uint8_t *)malloc(outLen + MARKER_LENGTH);
	memset(outBuf, 0xEE, outLen + MARKER_LENGTH);
	
	/* library should not touch this memory */
	textMarker = outBuf + outLen;
	memset(textMarker, MARKER_BYTE, MARKER_LENGTH);
	
	/* subsequent errors to errOut: */

	if(inPlace) {
		memmove(outBuf, inText, inTextLen);
		inp = outBuf;
	}
	else {
		inp = inText;
	}

	if(!randUpdates) {
		/* one shot */
		if(askOutSize) {
			crtn = CCCrypt(op, encrAlg, options,
				keyBytes, keyLen, iv,
				inp, inTextLen,
				outBuf, 0, &askedOutSize);
			if(crtn != kCCBufferTooSmall) {
				diag("***Did not get kCCBufferTooSmall as expected\n");
				diag("   alg %d inTextLen %lu cbc %d padding %d keyLen %lu\n",
					(int)encrAlg, (unsigned long)inTextLen, (int)doCbc, (int)doPadding,
					(unsigned long)keyLen);
				printCCError("CCCrypt", crtn);
				crtn = -1;
				goto errOut;
			}
			outLen = askedOutSize;
		}
		crtn = CCCrypt(op, encrAlg, options,
			keyBytes, keyLen, iv,
			inp, inTextLen,
			outBuf, outLen, &outLen);
		if(crtn) {
			printCCError("CCCrypt", crtn);
			goto errOut;
		}
		*outText = outBuf;
		*outTextLen = outLen;
		goto errOut;
	}
	
	/* random multi updates */
	if(ctxSize) {
		size_t ctxSizeCreated;
		
		if(askOutSize) {
			crtn = CCCryptorCreateFromData(op, encrAlg, options,
				keyBytes, keyLen, iv,
				ctx, 0 /* ctxSize */,
				&cryptor, &askedOutSize);
			if(crtn != kCCBufferTooSmall) {
				diag("***Did not get kCCBufferTooSmall as expected\n");
				printCCError("CCCryptorCreateFromData", crtn);
				crtn = -1;
				goto errOut;
			}
			ctxSize = askedOutSize;
		}
		crtn = CCCryptorCreateFromData(op, encrAlg, options,
			keyBytes, keyLen, iv,
			ctx, ctxSize, &cryptor, &ctxSizeCreated);
		if(crtn) {
			printCCError("CCCryptorCreateFromData", crtn);
			return crtn;
		}
		ctxMarker = ctx + ctxSizeCreated;
		memset(ctxMarker, MARKER_BYTE, MARKER_LENGTH);
	}
	else {
		crtn = CCCryptorCreate(op, encrAlg, options,
			keyBytes, keyLen, iv,
			&cryptor);
		if(crtn) {
			printCCError("CCCryptorCreate", crtn);
			return crtn;
		}
	}
	
	toMove = inTextLen;		/* total to go */
	outp = outBuf;
	outBytes = 0;			/* bytes actually produced in outBuf */
	
	while(toMove) {
		size_t thisMoveIn;			/* input to CCryptUpdate() */
		
		thisMoveIn = (size_t) genRand(1, (unsigned int) toMove);
		logSize(("###ptext segment len %lu\n", (unsigned long)thisMoveIn)); 
		if(askOutSize) {
			thisOutLen = CCCryptorGetOutputLength(cryptor, thisMoveIn, false);
		}
		else {
			thisOutLen = outLen;
		}
		crtn = CCCryptorUpdate(cryptor, inp, thisMoveIn,
			outp, thisOutLen, &thisMoveOut);
		if(crtn) {
			printCCError("CCCryptorUpdate", crtn);
			goto errOut;
		}
		inp			+= thisMoveIn;
		toMove		-= thisMoveIn;
		outp		+= thisMoveOut;
		outLen   	-= thisMoveOut;
		outBytes	+= thisMoveOut;
	}
	
	if(doPadding) {
		/* Final is not needed if padding is disabled */
		if(askOutSize) {
			thisOutLen = CCCryptorGetOutputLength(cryptor, 0, true);
		}
		else {
			thisOutLen = outLen;
		}
		crtn = CCCryptorFinal(cryptor, outp, thisOutLen, &thisMoveOut);
	}
	else {
		thisMoveOut = 0;
		crtn = kCCSuccess;
	}
	
	if(crtn) {
		printCCError("CCCryptorFinal", crtn);
		goto errOut;
	}
	
	outBytes += thisMoveOut;
	*outText = outBuf;
	*outTextLen = outBytes;
	crtn = kCCSuccess;

	for(dex=0; dex<MARKER_LENGTH; dex++) {
		if(textMarker[dex] != MARKER_BYTE) {
			diag("***lib scribbled on our textMarker memory (op=%s)!\n",
				forEncrypt ? "encrypt" : "decrypt");
			crtn = (CCCryptorStatus)-1;
		}
	}
	if(ctxSize) {
		for(dex=0; dex<MARKER_LENGTH; dex++) {
			if(ctxMarker[dex] != MARKER_BYTE) {
				diag("***lib scribbled on our ctxMarker memory (op=%s)!\n",
					forEncrypt ? "encrypt" : "decrypt");
				crtn = (CCCryptorStatus)-1;
			}
		}
	}
	
errOut:
	if(crtn) {
		if(outBuf) {
			free(outBuf);
		}
	}
	if(cryptor) {
		CCCryptorRelease(cryptor);
	}
	return crtn;
}

static int doTest(const uint8_t *ptext,
	size_t ptextLen,
	CCAlgorithm encrAlg,			
	bool doCbc,
	bool doPadding,
	bool nullIV,			/* if CBC, use NULL IV */
	uint32_t keySizeInBytes,
	bool stagedEncr,
	bool stagedDecr,
	bool inPlace,	
	size_t ctxSize,		
	bool askOutSize,
	bool quiet)
{
	uint8_t			keyBytes[MAX_KEY_SIZE];
	uint8_t			iv[MAX_BLOCK_SIZE];
	uint8_t			*ivPtrEncrypt;
	uint8_t			*ivPtrDecrypt;
	uint8_t			*ctext = NULL;		/* mallocd by doCCCrypt */
	size_t			ctextLen = 0;
	uint8_t			*rptext = NULL;		/* mallocd by doCCCrypt */
	size_t			rptextLen;
	CCCryptorStatus	crtn;
	int				rtn = 0;
	
	/* random key */
	appGetRandomBytes(keyBytes, keySizeInBytes);
	
	/* random IV if needed */
	if(doCbc) {
		if(nullIV) {
			memset(iv, 0, MAX_BLOCK_SIZE);
			
			/* flip a coin, give one side NULL, the other size zeroes */
			if(genRand(1,2) == 1) {
				ivPtrEncrypt = NULL;
				ivPtrDecrypt = iv;
			}
			else {
				ivPtrEncrypt = iv;
				ivPtrDecrypt = NULL;
			}
		}
		else {
			appGetRandomBytes(iv, MAX_BLOCK_SIZE);
			ivPtrEncrypt = iv;
			ivPtrDecrypt = iv;
		}
	}	
	else {
		ivPtrEncrypt = NULL;
		ivPtrDecrypt = NULL;
	}

	crtn = doCCCrypt(true, encrAlg, doCbc, doPadding,
		keyBytes, keySizeInBytes, ivPtrEncrypt,
		stagedEncr, inPlace, ctxSize, askOutSize,
		ptext, ptextLen,
		&ctext, &ctextLen);
    
    ok(crtn == 0, "doCCCrypt");
	if(crtn) {
        diag("Test Failure Encrypt encrAlg = %d dodCbc = %d doPadding %d\n", encrAlg, doCbc, doPadding);
	}
	
	logSize(("###ctext len %lu\n", ctextLen)); 
	crtn = doCCCrypt(false, encrAlg, doCbc, doPadding,
		keyBytes, keySizeInBytes, ivPtrDecrypt,
		stagedDecr, inPlace, ctxSize, askOutSize,
		ctext, ctextLen,
		&rptext, &rptextLen);
    ok(crtn == 0, "doCCCrypt");
	if(crtn) {
        diag("Test Failure Encrypt encrAlg = %d dodCbc = %d doPadding %d\n", encrAlg, doCbc, doPadding);
	}

	logSize(("###rptext len %lu\n", rptextLen)); 
	
	/* compare ptext, rptext */
	if(ptextLen != rptextLen) {
		diag("Ptext length mismatch: expect %lu, got %lu\n", ptextLen, rptextLen);
	}
	if(memcmp(ptext, rptext, ptextLen)) {
		diag("***data miscompare\n");
	}
abort:
	if(ctext) {
		free(ctext);
	}
	if(rptext) {
		free(rptext);
	}
	return rtn;
}

static bool isBitSet(unsigned bit, unsigned word) 
{
	if(bit > 31) {
		diag("We don't have that many bits\n");
		exit(1);
	}
	unsigned mask = 1 << bit;
	return (word & mask) ? true : false;
}


static int kTestTestCount = 1;


int CommonCryptoSymRegression(int argc, char *const *argv)
{
	unsigned			loop;
	uint8_t				*ptext;
	size_t				ptextLen;
	bool				stagedEncr = false;
	bool				stagedDecr = false;
	bool				doPadding;
	bool				doCbc = false;
	bool				nullIV;
	const char			*algStr;
	CCAlgorithm			encrAlg;	
	int					i;
	int					currAlg;		// ALG_xxx
	uint32_t				minKeySizeInBytes;
	uint32_t				maxKeySizeInBytes;
	uint32_t				keySizeInBytes = 0;
	int					rtn = 0;
	uint32_t				blockSize;		// for noPadding case
	size_t				ctxSize;		// always set per alg
	size_t				ctxSizeUsed;	// passed to doTest
	bool				askOutSize;		// inquire output size each op
	
	/*
	 * User-spec'd params
	 */
	bool		keySizeSpec = false;		// false: use rand key size
	SymAlg		minAlg = ALG_FIRST;
	SymAlg		maxAlg = ALG_LAST;
	unsigned	loops = LOOPS_DEF;
	bool		verbose = false;
	size_t		minPtextSize = MIN_DATA_SIZE;
	size_t		maxPtextSize = MAX_DATA_SIZE;
	bool		quiet = true;
	unsigned	pauseInterval = 0;
	bool		paddingSpec = false;		// true: user calls doPadding, const
	bool		cbcSpec = false;			// ditto for doCbc
	bool		stagedSpec = false;			// ditto for stagedEncr and stagedDecr
	bool		inPlace = false;			// en/decrypt in place for ECB
	bool		allocCtxSpec = false;		// use allocCtx
	bool		allocCtx = false;			// allocate context ourself

	plan_tests(kTestTestCount);
	

	ptext = (uint8_t *)malloc(maxPtextSize);
	if(ptext == NULL) {
		diag("Insufficient heap space\n");
		exit(1);
	}
	/* ptext length set in test loop */
	
	if(!quiet) diag("Starting ccSymTest; args: ");
	for(i=1; i<argc; i++) {
		if(!quiet) diag("%s ", argv[i]);
	}
	if(!quiet) diag("\n");
	
	if(pauseInterval) {
		fpurge(stdin);
		diag("Top of test; hit CR to proceed: ");
		getchar();
	}

	for(currAlg=minAlg; currAlg<=maxAlg; currAlg++) {
		switch(currAlg) {
			case ALG_DES:
				encrAlg = kCCAlgorithmDES;
				blockSize = kCCBlockSizeDES;
				minKeySizeInBytes = kCCKeySizeDES;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeDES;
				algStr = "DES";
                diag("Running DES Tests");
				break;
			case ALG_3DES:
				encrAlg = kCCAlgorithm3DES;
				blockSize = kCCBlockSize3DES;
				minKeySizeInBytes = kCCKeySize3DES;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSize3DES;
				
				algStr = "3DES";
                diag("Running 3DES Tests");
				break;
			case ALG_AES_128:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES128;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES128";
                diag("Running AES (128 bit key) Tests");
				break;
			case ALG_AES_192:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES192;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES192";
                diag("Running AES (192 bit key) Tests");
				break;
			case ALG_AES_256:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES256;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES256";
                diag("Running AES (256 bit key) Tests");
				break;
			case ALG_CAST:
				encrAlg = kCCAlgorithmCAST;
				blockSize = kCCBlockSizeCAST;
				minKeySizeInBytes = kCCKeySizeMinCAST;
				maxKeySizeInBytes = kCCKeySizeMaxCAST;
				ctxSize = kCCContextSizeCAST;
				algStr = "CAST";
                diag("Running CAST Tests");
				break;
			case ALG_RC4:
				encrAlg = kCCAlgorithmRC4;
				blockSize = 0;
				minKeySizeInBytes = kCCKeySizeMinRC4;
				maxKeySizeInBytes = kCCKeySizeMaxRC4;
				ctxSize = kCCContextSizeRC4;
				algStr = "RC4";
                diag("Running RC4 Tests");
				break;
			default:
				diag("***BRRZAP!\n");
				exit(1);
		}
		if(!quiet || verbose) {
			diag("Testing alg %s\n", algStr);
		}
		for(loop=1; ; loop++) {
			ptextLen = (size_t) genRand((unsigned int) minPtextSize, (unsigned int) maxPtextSize);
			appGetRandomBytes(ptext, ptextLen);
			
			/* per-loop settings */
			if(!keySizeSpec) {
				if(minKeySizeInBytes == maxKeySizeInBytes) {
					keySizeInBytes = minKeySizeInBytes;
				}
				else {
					keySizeInBytes = genRand(minKeySizeInBytes, maxKeySizeInBytes);
				}
			}
			if(blockSize == 0) {
				/* stream cipher */
				doCbc = false;
				doPadding = false;
			}
			else {
				if(!cbcSpec) {
					doCbc = isBitSet(0, loop);
				}
				if(!paddingSpec) {
					doPadding = isBitSet(1, loop);
				}
			}
			if(!doPadding && (blockSize != 0)) {
				/* align plaintext */
				ptextLen = (ptextLen / blockSize) * blockSize;
				if(ptextLen == 0) {
					ptextLen = blockSize;
				}
			}
			if(!stagedSpec) {
				stagedEncr = isBitSet(2, loop);
				stagedDecr = isBitSet(3, loop);
			}
			if(doCbc) {
				nullIV = isBitSet(4, loop);
			}
			else {
				nullIV = false;
			}
			inPlace = isBitSet(5, loop);
			if(allocCtxSpec) {
				ctxSizeUsed = allocCtx ? ctxSize : 0;
			}
			else if(isBitSet(6, loop)) {
				ctxSizeUsed = ctxSize;
			}
			else {
				ctxSizeUsed = 0;
			}
			askOutSize = isBitSet(7, loop);
			if(!quiet) {
			   	if(verbose || ((loop % LOOP_NOTIFY) == 0)) {
					diag("..loop %3d ptextLen %lu keyLen %d cbc=%d padding=%d stagedEncr=%d "
							"stagedDecr=%d\n",
						loop, (unsigned long)ptextLen, (int)keySizeInBytes, 
						(int)doCbc, (int)doPadding,
					 	(int)stagedEncr, (int)stagedDecr);
					diag("           nullIV %d inPlace %d ctxSize %d askOutSize %d\n",
						(int)nullIV, (int)inPlace, (int)ctxSizeUsed, (int)askOutSize);
				}
			}
			
			if(doTest(ptext, ptextLen,
					encrAlg, doCbc, doPadding, nullIV,
					keySizeInBytes,
					stagedEncr,	stagedDecr, inPlace, ctxSizeUsed, askOutSize,
					quiet)) {
				rtn = 1;
				break;
			}
			if(pauseInterval && ((loop % pauseInterval) == 0)) {
				char c;
				fpurge(stdin);
				diag("Hit CR to proceed, q to abort: ");
				c = getchar();
				if(c == 'q') {
					goto testDone;
				}
			}
			if(loops && (loop == loops)) {
				break;
			}
		}	/* main loop */
		if(rtn) {
			break;
		}
		
	}	/* for algs */
	
testDone:

    ok(rtn == 0, "ccSymTest");

	if(pauseInterval) {
		fpurge(stdin);
		diag("ModuleDetach/Unload complete; hit CR to exit: ");
		getchar();
	}
	if((rtn == 0) && !quiet) {
		diag("%s test complete\n", argv[0]);
	}
	free(ptext);
	return rtn;
}
#endif

Added CCRegression/CommonCrypto/CommonCryptoSymXTS.c.

more than 10,000 changes

Added CCRegression/CommonCrypto/CommonCryptoSymZeroLength.c.











































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdio.h>
#include <CommonCrypto/CommonCryptor.h>
#include "CCCryptorTestFuncs.h"
#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"

#if (CCSYMZEROLEN == 0)
entryPoint(CommonCryptoSymZeroLength,"CommonCrypto Symmetric Zero-Length Testing")
#else

static int kTestTestCount = 4;


int CommonCryptoSymZeroLength (int argc, char *const *argv) 
{
	char *keyStr;
	char *iv;
	char *plainText;
	char *cipherText;
    int retval, accum = 0;

	plan_tests(kTestTestCount);

	/* Two Test cases - "" and NULL WITH an IV */
        
	keyStr 	   = "000102030405060708090a0b0c0d0e0f";
	iv         = "0f0e0d0c0b0a09080706050403020100";

	// 1
	plainText  = "";
	cipherText = "efddc425a6fa0c5f25e444092eb0f503";
    retval = CCCryptTestCase(keyStr, iv, kCCAlgorithmAES128, kCCOptionPKCS7Padding, cipherText, plainText);
    ok(retval == 0, "CBC Zero Length String, IV defined");
    accum += retval;
    

	// 1
	plainText  = NULL;
	cipherText = "efddc425a6fa0c5f25e444092eb0f503";
    retval = CCCryptTestCase(keyStr, iv, kCCAlgorithmAES128, kCCOptionPKCS7Padding, cipherText, plainText);
    ok(retval == 0, "CBC NULL String, IV defined");
    accum += retval;
    
	/* Two more Test cases - "" and NULL WITH IV=NULL */
        
	keyStr 	   = "000102030405060708090a0b0c0d0e0f";
	iv         = NULL;

	// 1
	plainText  = "";
	cipherText = "954f64f2e4e86e9eee82d20216684899";
    retval = CCCryptTestCase(keyStr, iv, kCCAlgorithmAES128, kCCOptionPKCS7Padding, cipherText, plainText);
    ok(retval == 0, "CBC Zero Length String, IV NULL");
    accum += retval;
    

	// 1
	plainText  = NULL;
	cipherText = "954f64f2e4e86e9eee82d20216684899";
    retval = CCCryptTestCase(keyStr, iv, kCCAlgorithmAES128, kCCOptionPKCS7Padding, cipherText, plainText);
    //retval = 0;
    ok(retval == 0, "CBC NULL String, IV NULL");
    accum += retval;

    return accum != 0;
}
#endif

Added CCRegression/CommonCrypto/CommonCryptoSymmetricWrap.c.







































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
//
//  CommonCryptoSymmetricWrap.c
//  CCRegressions
//
//  Created by Richard Murphy on 1/13/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#include <stdio.h>
#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"

#if (CCSYMWRAP == 0)
entryPoint(CommonSymmetricWrap,"Symmetric Wrap")
#else

#include <CommonCrypto/CommonSymmetricKeywrap.h>


static int
wrapTest(char *kekstr, char *keystr, char *wrapped_keystr)
{
    byteBuffer kek, key, wrapped_key, bb;    
        
    kek = hexStringToBytes(kekstr);
    key = hexStringToBytes(keystr);
    if(wrapped_keystr) wrapped_key = hexStringToBytes(wrapped_keystr);
    else wrapped_key = hexStringToBytes("0x00");
	const uint8_t *iv =  CCrfc3394_iv;
	const size_t ivLen = CCrfc3394_ivLen;
	size_t wrapped_size = CCSymmetricWrappedSize(kCCWRAPAES, key->len);
	uint8_t wrapped[wrapped_size];
    
    // printf("Wrapped Size %lu\n", wrapped_size);

    ok(CCSymmetricKeyWrap(kCCWRAPAES, iv , ivLen, kek->bytes, kek->len, key->bytes, key->len, wrapped, &wrapped_size) == 0, "function is successful");
    if(wrapped_keystr) {
        bb = bytesToBytes(wrapped, wrapped_size);
        if(!strcmp(wrapped_keystr, "")) printByteBuffer(bb, "Result: ");
        ok(bytesAreEqual(bb, wrapped_key), "Equal to expected wrapping");
        // printByteBuffer(bb, "Result: ");
        // printByteBuffer(wrapped_key, "Expected: ");
        free(bb);
    }
        
	size_t unwrapped_size = CCSymmetricUnwrappedSize(kCCWRAPAES, wrapped_size);
	uint8_t unwrapped[unwrapped_size];
    
    ok(CCSymmetricKeyUnwrap(kCCWRAPAES, iv, ivLen, kek->bytes, kek->len, wrapped, wrapped_size, unwrapped, &unwrapped_size) == 0, "function is successful");
    bb = bytesToBytes(unwrapped, unwrapped_size);
    ok(bytesAreEqual(bb, key), "Equal to original key");
    free(bb);
    free(kek);
    free(key);
    free(wrapped_key);

    return 0;
}





static int kTestTestCount = 35;

int
CommonSymmetricWrap(int argc, char *const *argv)
{
    char *kek, *key, *wrapped_key;
    int accum = 0;
	plan_tests(kTestTestCount);
    
    diag("Test 1");
    kek = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
    key = "00112233445566778899aabbccddeeff000102030405060708090a0b0c0d0e0f";
    wrapped_key = "28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21";
    accum |= wrapTest(kek, key, wrapped_key);
    
    diag("Test 2");
    kek = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
    key = "00112233445566778899aabbccddeeff00010203040506070";
    wrapped_key = "a8f9bc1612c68b3ff6e6f4fbe30e71e4769c8b80a32cb8958cd5d17d6b254da1";
    accum |= wrapTest(kek, key, wrapped_key);

    diag("Test 3");
    byteBuffer keybuf = mallocByteBuffer(2048);
    for(int i=0; i<2048; i++) keybuf->bytes[i] = i%256;
    key = bytesToHexString(keybuf);
    accum |= wrapTest(kek, key, NULL);
    
    diag("Test Vectors from RFC 3394");
    diag("4.1 Wrap 128 bits of Key Data with a 128-bit KEK");
    kek = "000102030405060708090A0B0C0D0E0F";
    key = "00112233445566778899AABBCCDDEEFF";
    wrapped_key = "1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5";
    accum |= wrapTest(kek, key, wrapped_key);

    diag("4.2 Wrap 128 bits of Key Data with a 192-bit KEK");
    kek = "000102030405060708090A0B0C0D0E0F1011121314151617";
    key = "00112233445566778899AABBCCDDEEFF";
    wrapped_key = "96778B25AE6CA435F92B5B97C050AED2468AB8A17AD84E5D";
    accum |= wrapTest(kek, key, wrapped_key);

    diag("4.3 Wrap 128 bits of Key Data with a 256-bit KEK");
    kek = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";
    key = "00112233445566778899AABBCCDDEEFF";
    wrapped_key = "64E8C3F9CE0F5BA263E9777905818A2A93C8191E7D6E8AE7";
    accum |= wrapTest(kek, key, wrapped_key);

    diag("4.4 Wrap 192 bits of Key Data with a 192-bit KEK");
    kek = "000102030405060708090A0B0C0D0E0F1011121314151617";
    key = "00112233445566778899AABBCCDDEEFF0001020304050607";
    wrapped_key = "031D33264E15D33268F24EC260743EDCE1C6C7DDEE725A936BA814915C6762D2";
    accum |= wrapTest(kek, key, wrapped_key);

    diag("4.5 Wrap 192 bits of Key Data with a 256-bit KEK");
    kek = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";
    key = "00112233445566778899AABBCCDDEEFF0001020304050607";
    wrapped_key = "A8F9BC1612C68B3FF6E6F4FBE30E71E4769C8B80A32CB8958CD5D17D6B254DA1";
    accum |= wrapTest(kek, key, wrapped_key);

    diag("4.6 Wrap 256 bits of Key Data with a 256-bit KEK");
    kek = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F";
    key = "00112233445566778899AABBCCDDEEFF000102030405060708090A0B0C0D0E0F";
    wrapped_key = "28C9F404C4B810F4CBCCB35CFB87F8263F5786E2D80ED326CBC7F0E71A99F43BFB988B9B7A02DD21";
    accum |= wrapTest(kek, key, wrapped_key);
    
    return 0;
}
#endif

Added CCRegression/CommonCrypto/CommonDHtest.c.

























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <Availability.h>
#include "capabilities.h"
#include "testmore.h"
#include "testbyteBuffer.h"

#if (CCDH == 0)
entryPoint(CommonDH,"Diffie-Hellman Key Agreement")
#else

#include "CommonDH.h"
static int kTestTestCount = 2;

int CommonDH(int argc, char *const *argv) {
    CCDHRef dh1, dh2;

    plan_tests(kTestTestCount);
    
    
    dh1 = CCDHCreate(kCCDHRFC2409Group2);
    ok(dh1 == NULL, "kCCDHRFC2409Group2 isn't implemented in corecrypto");

    dh1 = CCDHCreate(kCCDHRFC3526Group5);
    ok(dh1 != NULL, "got a DH ref");
    
    dh2 = CCDHCreate(kCCDHRFC3526Group5);
    ok(dh2 != NULL, "got a DH ref");
    
    diag("CCDHRefs Created\n");

    uint8_t pubkey1[4096], pubkey2[4096];
    size_t len1 = 4096, len2 = 4096;
    int ret1 = CCDHGenerateKey(dh1, pubkey1, &len1);
    int ret2 = CCDHGenerateKey(dh2, pubkey2, &len2);

    ok(ret1 != -1 && ret2 != -1, "pubkeys generated");

    diag("Pubkeys Created\n");
    
    uint8_t sharedkey1[4096], sharedkey2[4096];
    size_t slen1 = 4096, slen2 = 4096;

    int sret1 = CCDHComputeKey(sharedkey1, &slen1, pubkey2, len2, dh1);
    int sret2 = CCDHComputeKey(sharedkey2, &slen2, pubkey1, len1, dh2);
    
    ok(sret1 != -1 && sret2 != -1, "shared keys generated");

    ok(slen1 == slen2, "shared key lengths are equal");
    
    ok(memcmp(sharedkey1, sharedkey2, slen1) == 0, "shared keys are equal");
    
    
    
    CCDHRelease(dh1);
    ok(1, "Didn't crash");


    return 0;
}

#endif

Added CCRegression/CommonCrypto/CommonDigest.c.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#include <stdio.h>
#include "testbyteBuffer.h"
#include "capabilities.h"
#include "testmore.h"
#include <string.h>

#define COMMON_DIGEST_FOR_RFC_1321
#include <CommonCrypto/CommonCryptor.h>
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>

#ifdef CCDIGEST
#include <CommonCrypto/CommonDigestSPI.h>
#endif

#ifdef CCKEYDERIVATION
#include <CommonCrypto/CommonKeyDerivation.h>
#endif

static char *digestName(CCDigestAlgorithm digestSelector) {
    switch(digestSelector) {
        default: return "None";
        case  kCCDigestMD2: return "MD2";
        case  kCCDigestMD4: return "MD4";
        case  kCCDigestMD5: return "MD5";
        case  kCCDigestRMD128: return "RMD128";
        case  kCCDigestRMD160: return "RMD160";
        case  kCCDigestRMD256: return "RMD256";
        case  kCCDigestRMD320: return "RMD320";
        case  kCCDigestSHA1: return "SHA1";
        case  kCCDigestSHA224: return "SHA224";
        case  kCCDigestSHA256: return "SHA256";
        case  kCCDigestSHA384: return "SHA384";
        case  kCCDigestSHA512: return "SHA512";
        case  kCCDigestSkein128: return "Skein128";
        case  kCCDigestSkein160: return "Skein160";
        case  kCCDigestSkein224: return "Skein224";
        case  kCCDigestSkein256: return "Skein256";
        case  kCCDigestSkein384: return "Skein384";
        case  kCCDigestSkein512: return "Skein512";
    }
}

static size_t nullstrlen(const char *s) {
    if(!s) return 0;
    return strlen(s);
}

#define MAX_DIGEST_SIZE CC_SHA512_DIGEST_LENGTH

#if (CCKEYDERIVATION == 1)
static int
PBKDF2Test(char *password, uint8_t *salt, size_t saltlen, int rounds, CCDigestAlgorithm PRF, int dklen, char *expected)
{
    byteBuffer derivedKey;
    byteBuffer expectedBytes;
    char outbuf[80];
    int retval = 0;
    
    if(expected) expectedBytes = hexStringToBytes(expected);
    derivedKey = mallocByteBuffer(dklen);
    switch(PRF) {
        case 0: CCKeyDerivationPBKDF(kCCPBKDF2, password, strlen(password), (uint8_t *) salt, saltlen, 0, rounds, derivedKey->bytes, derivedKey->len); break;
        case kCCDigestSHA1: CCKeyDerivationPBKDF(kCCPBKDF2, password, strlen(password), salt, saltlen, kCCPRFHmacAlgSHA1, rounds, derivedKey->bytes, derivedKey->len); break;
        case kCCDigestSHA224: CCKeyDerivationPBKDF(kCCPBKDF2, password, strlen(password), salt, saltlen, kCCPRFHmacAlgSHA224, rounds, derivedKey->bytes, derivedKey->len); break;
        case kCCDigestSHA256: CCKeyDerivationPBKDF(kCCPBKDF2, password, strlen(password), salt, saltlen, kCCPRFHmacAlgSHA256, rounds, derivedKey->bytes, derivedKey->len); break;
        case kCCDigestSHA384: CCKeyDerivationPBKDF(kCCPBKDF2, password, strlen(password), salt, saltlen, kCCPRFHmacAlgSHA384, rounds, derivedKey->bytes, derivedKey->len); break;
        case kCCDigestSHA512: CCKeyDerivationPBKDF(kCCPBKDF2, password, strlen(password), salt, saltlen, kCCPRFHmacAlgSHA512, rounds, derivedKey->bytes, derivedKey->len); break;
        default: return 1;
    }
	sprintf(outbuf, "PBKDF2-HMAC-%s test for %s", digestName(PRF), password);
    
    if(expected) {
        ok(bytesAreEqual(derivedKey, expectedBytes), outbuf);
        
        if(!bytesAreEqual(derivedKey, expectedBytes)) {
            diag("KEYDERIVE FAIL: PBKDF2-HMAC-%s(\"%s\")\n expected %s\n      got %s\n", digestName(PRF), password, expected, bytesToHexString(derivedKey));
            retval = 1;
        } else {
            //printf("KEYDERIVE PASS: PBKDF2-HMAC-%s(\"%s\")\n", digestName(PRF), password);
        }
        free(expectedBytes);
    }
    free(derivedKey);
    return retval;
}
#endif

static byteBuffer mallocDigestBuffer(CCDigestAlgorithm digestSelector) {
    size_t len;
    switch(digestSelector) {
        default: len = CCDigestGetOutputSize(digestSelector); break;
        case kCCDigestMD2: len = CC_MD2_DIGEST_LENGTH; break;
        case kCCDigestMD4: len = CC_MD4_DIGEST_LENGTH; break;
        case kCCDigestMD5: len = CC_MD5_DIGEST_LENGTH; break;
        case kCCDigestSHA1: len = CC_SHA1_DIGEST_LENGTH; break;
        case kCCDigestSHA224: len = CC_SHA224_DIGEST_LENGTH; break;
        case kCCDigestSHA256: len = CC_SHA256_DIGEST_LENGTH; break;
        case kCCDigestSHA384: len = CC_SHA384_DIGEST_LENGTH; break;
        case kCCDigestSHA512: len = CC_SHA512_DIGEST_LENGTH; break;
    }
    return mallocByteBuffer(len);
}

static void
OneShotHmac(CCHmacAlgorithm hmacAlg, uint8_t *key, size_t keylen, const char *data, size_t datalen, uint8_t *output)
{
    CCHmacContext ctx;
    
    CCHmacInit(&ctx, hmacAlg, key, keylen);
    CCHmacUpdate(&ctx, data, datalen);
    CCHmacFinal(&ctx, output);    
}

static int
HMACTest(const char *input, char *keystr, CCDigestAlgorithm digestSelector, char *expected)
{
    CCHmacAlgorithm hmacAlg;
    size_t inputLen = nullstrlen(input);
    char outbuf[80];
    int retval = 0;
    
    byteBuffer expectedBytes = hexStringToBytes(expected);
    byteBuffer keyBytes = hexStringToBytes(keystr);
    byteBuffer mdBuf = mallocDigestBuffer(digestSelector);
    switch(digestSelector) {
        case kCCDigestMD5: hmacAlg = kCCHmacAlgMD5; break;
        case kCCDigestSHA1: hmacAlg = kCCHmacAlgSHA1; break;
        case kCCDigestSHA224: hmacAlg = kCCHmacAlgSHA224; break;
        case kCCDigestSHA256: hmacAlg = kCCHmacAlgSHA256; break;
        case kCCDigestSHA384: hmacAlg = kCCHmacAlgSHA384; break;
        case kCCDigestSHA512: hmacAlg = kCCHmacAlgSHA512; break;
        default: return 1;
    }
    CCHmac(hmacAlg, keyBytes->bytes, keyBytes->len, input, inputLen, mdBuf->bytes);
    sprintf(outbuf, "Hmac-%s test for %s", digestName(digestSelector), input);
    ok(bytesAreEqual(mdBuf, expectedBytes), outbuf);
    if(!bytesAreEqual(mdBuf, expectedBytes)) {
        diag("HMAC FAIL: HMAC-%s(\"%s\")\n expected %s\n      got %s\n", digestName(digestSelector), input, expected, bytesToHexString(mdBuf));
        retval = 1;
    } else {
        // printf("HMAC PASS: HMAC-%s(\"%s\")\n", digestName(digestSelector), input);
    }
    OneShotHmac(hmacAlg, keyBytes->bytes, keyBytes->len, input, inputLen, mdBuf->bytes);
    sprintf(outbuf, "Hmac-%s test for %s", digestName(digestSelector), input);
    ok(bytesAreEqual(mdBuf, expectedBytes), outbuf);
    if(!bytesAreEqual(mdBuf, expectedBytes)) {
        diag("HMAC FAIL: HMAC-%s(\"%s\")\n expected %s\n      got %s\n", digestName(digestSelector), input, expected, bytesToHexString(mdBuf));
        retval = 1;
    } else {
        //printf("HMAC PASS: HMAC-%s(\"%s\")\n", digestName(digestSelector), input);
    }
    free(mdBuf);
    free(expectedBytes);
    free(keyBytes);
	return retval;
}

#if (CCDIGEST == 1)

static void OneShotDigest(CCDigestAlgorithm algorithm, const uint8_t *bytesToDigest, size_t numbytes, uint8_t *outbuf)
{
    CCDigestRef d;
    *outbuf = 0;
    if((d = CCDigestCreate(algorithm)) == NULL) return;
    
    size_t fromAlg = CCDigestGetOutputSize(algorithm);
    size_t fromRef = CCDigestGetOutputSizeFromRef(d);
    size_t fromOldRoutine = CCDigestOutputSize(d);
    
    ok(fromAlg == fromRef, "Size is the same from ref or alg");
    ok(fromAlg == fromOldRoutine, "Size is the same from ref or alg");
    if(CCDigestUpdate(d, bytesToDigest, numbytes)) return;
    if(CCDigestFinal(d, outbuf)) return;
    
    uint8_t dupBuf[fromRef];
    CCDigestReset(d);
    if(CCDigestUpdate(d, bytesToDigest, numbytes)) return;
    if(CCDigestFinal(d, dupBuf)) return;
    ok(memcmp(outbuf, dupBuf, fromRef) == 0, "result should be the same from recycled context");

    CCDigestDestroy(d);

}


static int
newHashTest(char *input, CCDigestAlgorithm digestSelector, char *expected)
{
    size_t inputLen = nullstrlen(input);
    char outbuf[4096];
    int retval = 0;
    
    byteBuffer expectedBytes = hexStringToBytes(expected);
    byteBuffer mdBuf = mallocByteBuffer(CCDigestGetOutputSize(digestSelector));

    CCDigest(digestSelector, (const uint8_t *) input, inputLen, mdBuf->bytes);
    sprintf(outbuf, "new interface %s test for %s", digestName(digestSelector), input);
    ok(bytesAreEqual(mdBuf, expectedBytes), outbuf);
    if(!bytesAreEqual(mdBuf, expectedBytes)) {
        diag("Digestor FAIL: %s(\"%s\")\nexpected %s\ngot      %s\n", digestName(digestSelector), input, expected, bytesToHexString(mdBuf));
        retval = 1;
    } else {
        // printf("Digestor PASS: %s(\"%s\")\n", digestName(digestSelector), input);
    }

    printf("Digest is %s\n", digestName(digestSelector));
    OneShotDigest(digestSelector, (const uint8_t *) input, inputLen, mdBuf->bytes);
    sprintf(outbuf, "composite interface %s test for %s", digestName(digestSelector), input);
    ok(bytesAreEqual(mdBuf, expectedBytes), outbuf);
    if(!bytesAreEqual(mdBuf, expectedBytes)) {
        diag("Digestor FAIL: %s(\"%s\")\nexpected %s\ngot      %s\n", digestName(digestSelector), input, expected, bytesToHexString(mdBuf));
        retval = 1;
    } else {
        // printf("Digestor PASS: %s(\"%s\")\n", digestName(digestSelector), input);
    }
 
    free(mdBuf);
    free(expectedBytes);
	return retval;
}

static int
unHashTest(CCDigestAlgorithm digestSelector)
{
    char *buf[128];
    int retval;
    CCDigestRef retref;
    
    retval = CCDigest(digestSelector, (const uint8_t *) buf, 128, (uint8_t *) buf);
    ok(retval == kCCUnimplemented, "Unsupported Digest returns kCCUnimplemented");
    retref = CCDigestCreate(digestSelector);
    ok(retref == NULL, "Unsupported Digest returns NULL");
    return 0;
}
#endif

#define CC_SHA224_CTX CC_SHA256_CTX
#define CC_SHA384_CTX CC_SHA512_CTX
#define OLD_ALL_IN_ONE_HASH(name,input,len,out) \
{ \
    CC_##name##_CTX ctx; \
    ok(CC_##name##_Init(&ctx) == 1, "Old Hash init should result in 1\n"); \
    ok(CC_##name##_Update(&ctx, input, len) == 1, "Old Hash update should result in 1\n"); \
    ok(CC_##name##_Final(out, &ctx) == 1, "Old Hash final should result in 1\n"); \
} \
break


static int
hashTest(char *input, CCDigestAlgorithm digestSelector, char *expected)
{
    CC_LONG inputLen = (CC_LONG) nullstrlen(input);
    char outbuf[4096];
    int retval = 0;
    byteBuffer mdBuf = mallocDigestBuffer(digestSelector);
    byteBuffer expectedBytes = hexStringToBytes(expected);
    
    switch(digestSelector) {
        case kCCDigestMD2:		CC_MD2(input, inputLen, mdBuf->bytes); break;
        case kCCDigestMD4:		CC_MD4(input, inputLen, mdBuf->bytes); break;
        case kCCDigestMD5:		CC_MD5(input, inputLen, mdBuf->bytes); break;
        case kCCDigestSHA1:	CC_SHA1(input, inputLen, mdBuf->bytes); break;
        case kCCDigestSHA224:	CC_SHA224(input, inputLen, mdBuf->bytes); break;
        case kCCDigestSHA256:	CC_SHA256(input, inputLen, mdBuf->bytes); break;
        case kCCDigestSHA384:	CC_SHA384(input, inputLen, mdBuf->bytes); break;
        case kCCDigestSHA512:	CC_SHA512(input, inputLen, mdBuf->bytes); break;
        default: return 1;
    }
    sprintf(outbuf, "Legacy %s test for %s", digestName(digestSelector), input);
    ok(bytesAreEqual(mdBuf, expectedBytes), outbuf);

    if(!bytesAreEqual(mdBuf, expectedBytes)) {
        diag("Legacy FAIL: %s(\"%s\") expected %s got %s\n", digestName(digestSelector), input, expected, bytesToHexString(mdBuf));
        retval = 1;
    } else {
        // printf("Legacy PASS: %s(\"%s\")\n", digestName(digestSelector), input);
    }
    
    switch(digestSelector) {
        case kCCDigestMD2:		OLD_ALL_IN_ONE_HASH(MD2, input, inputLen, mdBuf->bytes);
        case kCCDigestMD4:		OLD_ALL_IN_ONE_HASH(MD4, input, inputLen, mdBuf->bytes);
        case kCCDigestMD5:		OLD_ALL_IN_ONE_HASH(MD5, input, inputLen, mdBuf->bytes);
        case kCCDigestSHA1:	OLD_ALL_IN_ONE_HASH(SHA1, input, inputLen, mdBuf->bytes);
        case kCCDigestSHA224:	OLD_ALL_IN_ONE_HASH(SHA224, input, inputLen, mdBuf->bytes);
        case kCCDigestSHA256:	OLD_ALL_IN_ONE_HASH(SHA256, input, inputLen, mdBuf->bytes);
        case kCCDigestSHA384:	OLD_ALL_IN_ONE_HASH(SHA384, input, inputLen, mdBuf->bytes);
        case kCCDigestSHA512:	OLD_ALL_IN_ONE_HASH(SHA512, input, inputLen, mdBuf->bytes);
        default: return 1;
    }
    sprintf(outbuf, "Legacy %s test for %s", digestName(digestSelector), input);
    ok(bytesAreEqual(mdBuf, expectedBytes), outbuf);
    
    if(!bytesAreEqual(mdBuf, expectedBytes)) {
        diag("Legacy FAIL: %s(\"%s\") expected %s got %s\n", digestName(digestSelector), input, expected, bytesToHexString(mdBuf));
        retval = 1;
    } else {
        // printf("Legacy PASS: %s(\"%s\")\n", digestName(digestSelector), input);
    }

   free(mdBuf);
   free(expectedBytes);
   return retval;
}

static int
rfc1321Test(char *input, char *expected)
{
    CC_LONG inputLen = (CC_LONG) nullstrlen(input);
    char outbuf[80];
    int retval = 0;
    MD5_CTX ctx;
    byteBuffer expectedBytes = hexStringToBytes(expected);
    byteBuffer mdBuf = mallocByteBuffer(CC_MD5_DIGEST_LENGTH); 
    
    MD5Init(&ctx);
    MD5Update(&ctx, input, inputLen);
    MD5Final(mdBuf->bytes, &ctx);
    
    sprintf(outbuf, "Legacy MD5-1321 test for %s", input);
    
    ok(bytesAreEqual(mdBuf, expectedBytes), outbuf);
    
    if(!bytesAreEqual(mdBuf, expectedBytes)) {
        diag("Legacy FAIL: MD5-1321(\"%s\") expected %s got %s\n", input, expected, bytesToHexString(mdBuf));
        retval = 1;
    } else {
        // printf("Legacy PASS: MD5-1321(\"%s\")\n", input);
    }
    free(mdBuf);
    free(expectedBytes);
    return retval;
}


static int kTestTestCount = 250;

int CommonDigest(int argc, char *const *argv) {
	char *strvalue, *keyvalue;
	plan_tests(kTestTestCount);
    int accum = 0;
    
	/* strvalue of NULL and strvalue of "" must end up the same */
    strvalue = NULL;
    accum |= hashTest(strvalue, kCCDigestMD2, "8350e5a3e24c153df2275c9f80692773");
    accum |= hashTest(strvalue, kCCDigestMD4, "31d6cfe0d16ae931b73c59d7e0c089c0");
    accum |= hashTest(strvalue, kCCDigestMD5, "d41d8cd98f00b204e9800998ecf8427e");
    accum |= hashTest(strvalue, kCCDigestSHA1, "da39a3ee5e6b4b0d3255bfef95601890afd80709");
    accum |= hashTest(strvalue, kCCDigestSHA224, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f");
    accum |= hashTest(strvalue, kCCDigestSHA256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
    accum |= hashTest(strvalue, kCCDigestSHA384, "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b");
    accum |= hashTest(strvalue, kCCDigestSHA512, "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
#if (CCDIGEST == 1)
    accum |= newHashTest(strvalue, kCCDigestMD2, "8350e5a3e24c153df2275c9f80692773");
    accum |= newHashTest(strvalue, kCCDigestMD4, "31d6cfe0d16ae931b73c59d7e0c089c0");
    accum |= newHashTest(strvalue, kCCDigestMD5, "d41d8cd98f00b204e9800998ecf8427e");
    accum |= newHashTest(strvalue, kCCDigestSHA1, "da39a3ee5e6b4b0d3255bfef95601890afd80709");
    accum |= newHashTest(strvalue, kCCDigestSHA224, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f");
    accum |= newHashTest(strvalue, kCCDigestSHA256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
    accum |= newHashTest(strvalue, kCCDigestSHA384, "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b");
    accum |= newHashTest(strvalue, kCCDigestSHA512, "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
    accum |= newHashTest(strvalue, kCCDigestRMD128, "cdf26213a150dc3ecb610f18f6b38b46");
    accum |= newHashTest(strvalue, kCCDigestRMD160, "9c1185a5c5e9fc54612808977ee8f548b2258d31");
    accum |= newHashTest(strvalue, kCCDigestRMD256, "02ba4c4e5f8ecd1877fc52d64d30e37a2d9774fb1e5d026380ae0168e3c5522d");
    accum |= newHashTest(strvalue, kCCDigestRMD320, "22d65d5661536cdc75c1fdf5c6de7b41b9f27325ebc61e8557177d705a0ec880151c3a32a00899b8");
#else
    diag("No Testing of the new Digest Interfaces\n");
#endif

    strvalue = "";
    accum |= hashTest(strvalue, kCCDigestMD2, "8350e5a3e24c153df2275c9f80692773");
    accum |= hashTest(strvalue, kCCDigestMD4, "31d6cfe0d16ae931b73c59d7e0c089c0");
    accum |= hashTest(strvalue, kCCDigestMD5, "d41d8cd98f00b204e9800998ecf8427e");
    accum |= hashTest(strvalue, kCCDigestSHA1, "da39a3ee5e6b4b0d3255bfef95601890afd80709");
    accum |= hashTest(strvalue, kCCDigestSHA224, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f");
    accum |= hashTest(strvalue, kCCDigestSHA256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
    accum |= hashTest(strvalue, kCCDigestSHA384, "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b");
    accum |= hashTest(strvalue, kCCDigestSHA512, "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
#if (CCDIGEST == 1)
    accum |= newHashTest(strvalue, kCCDigestMD2, "8350e5a3e24c153df2275c9f80692773");
    accum |= newHashTest(strvalue, kCCDigestMD4, "31d6cfe0d16ae931b73c59d7e0c089c0");
    accum |= newHashTest(strvalue, kCCDigestMD5, "d41d8cd98f00b204e9800998ecf8427e");
    accum |= newHashTest(strvalue, kCCDigestSHA1, "da39a3ee5e6b4b0d3255bfef95601890afd80709");
    accum |= newHashTest(strvalue, kCCDigestSHA224, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f");
    accum |= newHashTest(strvalue, kCCDigestSHA256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
    accum |= newHashTest(strvalue, kCCDigestSHA384, "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b");
    accum |= newHashTest(strvalue, kCCDigestSHA512, "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
    accum |= newHashTest(strvalue, kCCDigestRMD128, "cdf26213a150dc3ecb610f18f6b38b46");
    accum |= newHashTest(strvalue, kCCDigestRMD160, "9c1185a5c5e9fc54612808977ee8f548b2258d31");
    accum |= newHashTest(strvalue, kCCDigestRMD256, "02ba4c4e5f8ecd1877fc52d64d30e37a2d9774fb1e5d026380ae0168e3c5522d");
    accum |= newHashTest(strvalue, kCCDigestRMD320, "22d65d5661536cdc75c1fdf5c6de7b41b9f27325ebc61e8557177d705a0ec880151c3a32a00899b8");
#if defined(TESTSKEIN)

    accum |= newHashTest(strvalue, kCCDigestSkein128, "030085a5c5e9fc54612808977ee8f548");
    accum |= newHashTest(strvalue, kCCDigestSkein160, "030085a5c5e9fc54612808977ee8f548b2258d31");
    accum |= newHashTest(strvalue, kCCDigestSkein224, "030085a5c5e9fc54612808977ee8f548b2258d31009b934ca495991b");
    accum |= newHashTest(strvalue, kCCDigestSkein256, "0900d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
    accum |= newHashTest(strvalue, kCCDigestSkein384, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
    accum |= newHashTest(strvalue, kCCDigestSkein512, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
#else
    accum |= unHashTest(kCCDigestSkein128);
    accum |= unHashTest(kCCDigestSkein160);
    accum |= unHashTest(kCCDigestSkein224);
    accum |= unHashTest(kCCDigestSkein256);
    accum |= unHashTest(kCCDigestSkein384);
    accum |= unHashTest(kCCDigestSkein512);
#endif
#else
    diag("No Testing of the new Digest Interfaces\n");
#endif

    strvalue = "Test vector from febooti.com";
    accum |= hashTest(strvalue, kCCDigestMD2, "db128d6e0d20a1192a6bd1fade401150");
    accum |= hashTest(strvalue, kCCDigestMD4, "6578f2664bc56e0b5b3f85ed26ecc67b");
    accum |= hashTest(strvalue, kCCDigestMD5, "500ab6613c6db7fbd30c62f5ff573d0f");
    accum |= hashTest(strvalue, kCCDigestSHA1, "a7631795f6d59cd6d14ebd0058a6394a4b93d868");
    accum |= hashTest(strvalue, kCCDigestSHA224, "3628b402254caa96827e3c79c0a559e4558da8ee2b65f1496578137d");
    accum |= hashTest(strvalue, kCCDigestSHA256, "077b18fe29036ada4890bdec192186e10678597a67880290521df70df4bac9ab");
    accum |= hashTest(strvalue, kCCDigestSHA384, "388bb2d487de48740f45fcb44152b0b665428c49def1aaf7c7f09a40c10aff1cd7c3fe3325193c4dd35d4eaa032f49b0");
    accum |= hashTest(strvalue, kCCDigestSHA512, "09fb898bc97319a243a63f6971747f8e102481fb8d5346c55cb44855adc2e0e98f304e552b0db1d4eeba8a5c8779f6a3010f0e1a2beb5b9547a13b6edca11e8a");
    accum |= rfc1321Test(strvalue, "500ab6613c6db7fbd30c62f5ff573d0f");


#if (CCDIGEST == 1)
    accum |= newHashTest(strvalue, kCCDigestMD2, "db128d6e0d20a1192a6bd1fade401150");
    accum |= newHashTest(strvalue, kCCDigestMD4, "6578f2664bc56e0b5b3f85ed26ecc67b");
    accum |= newHashTest(strvalue, kCCDigestMD5, "500ab6613c6db7fbd30c62f5ff573d0f");
    accum |= newHashTest(strvalue, kCCDigestSHA1, "a7631795f6d59cd6d14ebd0058a6394a4b93d868");
    accum |= newHashTest(strvalue, kCCDigestSHA224, "3628b402254caa96827e3c79c0a559e4558da8ee2b65f1496578137d");
    accum |= newHashTest(strvalue, kCCDigestSHA256, "077b18fe29036ada4890bdec192186e10678597a67880290521df70df4bac9ab");
    accum |= newHashTest(strvalue, kCCDigestSHA384, "388bb2d487de48740f45fcb44152b0b665428c49def1aaf7c7f09a40c10aff1cd7c3fe3325193c4dd35d4eaa032f49b0");
    accum |= newHashTest(strvalue, kCCDigestSHA512, "09fb898bc97319a243a63f6971747f8e102481fb8d5346c55cb44855adc2e0e98f304e552b0db1d4eeba8a5c8779f6a3010f0e1a2beb5b9547a13b6edca11e8a");
#if defined(TESTSKEIN)
    accum |= newHashTest(strvalue, kCCDigestSkein128, "03000000000000700000000000000070");
    accum |= newHashTest(strvalue, kCCDigestSkein160, "0300000000000070000000000000007000000000");
    accum |= newHashTest(strvalue, kCCDigestSkein224, "030000000000007000000000000000700000000000000070ca030210");
    accum |= newHashTest(strvalue, kCCDigestSkein256, "0000000000000000000000000000000000000000000000000000000000000000");
    accum |= newHashTest(strvalue, kCCDigestSkein384, "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
    accum |= newHashTest(strvalue, kCCDigestSkein512, "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
#endif

#else
    diag("No Testing of the new Digest Interfaces\n");
#endif

	// Test Case 1 http://www.faqs.org/rfcs/rfc4231.html
    strvalue = "Hi There";
    keyvalue = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b";
	accum |= HMACTest(strvalue, keyvalue, kCCDigestSHA224, "896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22");   
	accum |= HMACTest(strvalue, keyvalue, kCCDigestSHA256, "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7");   
	accum |= HMACTest(strvalue, keyvalue, kCCDigestSHA384, "afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6");   
	accum |= HMACTest(strvalue, keyvalue, kCCDigestSHA512, "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854");
    // Test Vector from http://www.faqs.org/rfcs/rfc2104.html
    keyvalue = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b";
    accum |= HMACTest(strvalue, keyvalue, kCCDigestMD5, "9294727a3638bb1c13f48ef8158bfc9d");   
    
#if (CCKEYDERIVATION == 1)
    // Test Case PBKDF2 - HMACSHA1 http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-00
    accum |= PBKDF2Test("password", (uint8_t *) "salt", 4, 1, kCCDigestSHA1, 20, "0c60c80f961f0e71f3a9b524af6012062fe037a6");
    accum |= PBKDF2Test("password", (uint8_t *) "salt", 4, 2, kCCDigestSHA1, 20, "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957");
    accum |= PBKDF2Test("password", (uint8_t *) "salt", 4, 4096, kCCDigestSHA1, 20, "4b007901b765489abead49d926f721d065a429c1");
    
    // This crashes
    accum |= PBKDF2Test("password", (uint8_t *) "salt", 4, 1, 0, 20, NULL);
#else
    diag("No Key Derivation Support Testing\n");
#endif
    
    // Test from <rdar://problem/11285435> CC_SHA512_Init(),CC_SHA512_Update(),CC_SHA512_Final() gives wrong digest
    strvalue = "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu";
    accum |= hashTest(strvalue, kCCDigestSHA512, "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909");
    accum |= newHashTest(strvalue, kCCDigestSHA512, "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909");

    return accum;

}

Added CCRegression/CommonCrypto/CommonEC.c.





































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <Availability.h>
#include "capabilities.h"
#include "testmore.h"
#include "testbyteBuffer.h"

#if (CCEC == 0)
entryPoint(CommonEC,"Elliptic Curve Cryptography")
#else

#include <CommonCrypto/CommonECCryptor.h>

static int kTestTestCount = 18;

int CommonEC(int argc, char *const *argv) {
	CCCryptorStatus retval;
    size_t keysize;
    CCECCryptorRef publicKey, privateKey;
    CCECCryptorRef publicKey2;
    // byteBuffer keydata, dekeydata;
    byteBuffer hash;
    char encryptedKey[8192];
    size_t encryptedKeyLen = 8192;
    // char decryptedKey[8192];
    // size_t decryptedKeyLen = 8192;
    char signature[8192];
    size_t signatureLen = 8192;
    char importexport[8192];
    size_t importexportLen = 8192;
    uint32_t valid;
    int accum = 0;
    int debug = 0;
    
	plan_tests(kTestTestCount);
    
    keysize = 256;
    
    retval = CCECCryptorGeneratePair(keysize, &publicKey, &privateKey);
    if(debug) printf("Keys Generated\n");
    ok(retval == 0, "Generate an EC Key Pair");
	accum |= retval;

#ifdef ECDH
    keydata = hexStringToBytes("000102030405060708090a0b0c0d0e0f");
    
    retval = CCECCryptorWrapKey(publicKey, keydata->bytes, keydata->len, encryptedKey, &encryptedKeyLen, kCCDigestSHA1);
    
    ok(retval == 0, "Wrap Key Data with EC Encryption - ccPKCS1Padding");
    accum |= retval;
    
    retval = CCECCryptorUnwrapKey(privateKey, encryptedKey, encryptedKeyLen,
                        decryptedKey, &decryptedKeyLen);
    
    ok(retval == 0, "Unwrap Key Data with EC Encryption - ccPKCS1Padding");
    accum |= retval;

	dekeydata = bytesToBytes(decryptedKey, decryptedKeyLen);
    
	ok(bytesAreEqual(dekeydata, keydata), "Round Trip CCECCryptorWrapKey/CCECCryptorUnwrapKey");
    accum |= retval;
#endif

    
    hash = hexStringToBytes("000102030405060708090a0b0c0d0e0f");

    retval = CCECCryptorSignHash(privateKey, 
                     hash->bytes, hash->len,
                     signature, &signatureLen);
                     
    ok(retval == 0, "EC Signing");
    valid = 0;
    accum |= retval;
    if(debug) printf("Signing Complete\n");
    
    retval = CCECCryptorVerifyHash(publicKey,
                       hash->bytes, hash->len, 
                       signature, signatureLen, &valid);
    ok(retval == 0, "EC Verifying");
    accum |= retval;
	ok(valid, "EC Validity");
    accum |= retval;
    if(debug) printf("Verify Complete\n");
   
    // Mess with the sig - see what happens
    signature[signatureLen-3] += 3;
    retval = CCECCryptorVerifyHash(publicKey,
                                   hash->bytes, hash->len, 
                                   signature, signatureLen, &valid);
    ok(retval == 0, "EC Verifying");
    accum |= retval;
	ok(!valid, "EC Invalid Signature");
    accum |= retval;
    
    if(debug) printf("Verify2 Complete\n");
    
    encryptedKeyLen = 8192;
	retval = CCECCryptorExportPublicKey(publicKey, importexport, &importexportLen);
    
    ok(retval == 0, "EC Export Public Key");
    accum |= retval;

    retval = CCECCryptorImportPublicKey(importexport, importexportLen, &publicKey2);
    
    ok(retval == 0, "EC Import Public Key");
    accum |= retval;
                          
	encryptedKeyLen = 8192;
    retval = CCECCryptorComputeSharedSecret(privateKey, publicKey, encryptedKey, &encryptedKeyLen);

    ok(retval == 0, "EC Shared Secret");
    accum |= retval;

    return accum;
}
#endif /* CCEC */

Added CCRegression/CommonCrypto/CommonHMacClone.c.











































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
/* 
 * ccHmacClone - test CommonCrypto's clone context for HMAC.  
 *
 * Written 3/30/2006 by Doug Mitchell. 
 */

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <string.h>
#include <CommonCrypto/CommonHMAC.h>
#include "testmore.h"
#include "testbyteBuffer.h"
#include "capabilities.h"

#if (CCHMACCLONE == 0)
entryPoint(CommonHMacClone,"Common HMac Cloning")
#else

/*
 * Defaults.
 */
#define LOOPS_DEF		200

#define MIN_DATA_SIZE	8
#define MAX_DATA_SIZE	10000			/* bytes */
#define MIN_KEY_SIZE	1
#define MAX_KEY_SIZE	256				/* bytes */
#define LOOP_NOTIFY		20

/*
 * Enumerate algs our own way to allow iteration.
 */
typedef enum {
	ALG_MD5 = 1,
	ALG_SHA1,
	ALG_SHA224,
	ALG_SHA256,
	ALG_SHA384,
	ALG_SHA512,
} HmacAlg;
#define ALG_FIRST			ALG_MD5
#define ALG_LAST			ALG_SHA512

#define LOG_SIZE			0
#if		LOG_SIZE
#define logSize(s)	diag(s)
#else
#define logSize(s)
#endif

/* 
 * Given an initialized CCHmacContext, feed it some data and get the result.
 */
static void hmacRun(
	CCHmacContext *ctx,
	bool randomUpdates,
	const unsigned char *ptext,
	size_t ptextLen,
	void *dataOut)
{
	while(ptextLen) {
		size_t thisMoveIn;			/* input to CCryptUpdate() */
		
		if(randomUpdates) {
			thisMoveIn = genRandomSize(1, ptextLen);
		}
		else {
			thisMoveIn = ptextLen;
		}
		logSize(("###ptext segment (1) len %lu\n", (unsigned long)thisMoveIn)); 
		CCHmacUpdate(ctx, ptext, thisMoveIn);
		ptext	 += thisMoveIn;
		ptextLen -= thisMoveIn;
	}
	CCHmacFinal(ctx, dataOut);
}


#define MAX_HMAC_SIZE	CC_SHA512_DIGEST_LENGTH

static int doHMacCloneTest(const uint8_t *ptext,
	size_t ptextLen,
	CCHmacAlgorithm hmacAlg,			
	uint32_t keySizeInBytes,
	bool stagedOrig,
	bool stagedClone,
	bool quiet,
	bool verbose)
{
	uint8_t			*keyBytes;
	uint8_t			hmacOrig[MAX_HMAC_SIZE];
	uint8_t			hmacClone[MAX_HMAC_SIZE];
	int				rtn = 1;
	CCHmacContext	ctxOrig;
	CCHmacContext	ctxClone;
	unsigned		die;		/* 0..3 indicates when to clone */
	unsigned		loopNum = 0;
	size_t			hmacLen;
	bool			didClone = false;
	
	switch(hmacAlg) {
		case kCCHmacAlgSHA1:
            if(verbose) diag("hmac-sha1\n");
			hmacLen = CC_SHA1_DIGEST_LENGTH;
			break;
		case kCCHmacAlgMD5:
            if(verbose) diag("hmac-md5\n");
			hmacLen = CC_MD5_DIGEST_LENGTH;
			break;
		case kCCHmacAlgSHA224:
            if(verbose) diag("hmac-sha224\n");
			hmacLen = CC_SHA224_DIGEST_LENGTH;
			break;
		case kCCHmacAlgSHA256:
            if(verbose) diag("hmac-sha256\n");
			hmacLen = CC_SHA256_DIGEST_LENGTH;
			break;
		case kCCHmacAlgSHA384:
            if(verbose) diag("hmac-sha384\n");
			hmacLen = CC_SHA384_DIGEST_LENGTH;
			break;
		case kCCHmacAlgSHA512:
            if(verbose) diag("hmac-sha512\n");
			hmacLen = CC_SHA512_DIGEST_LENGTH;
			break;
		default:
			if(verbose) diag("***BRRRZAP!\n");
			return 0;
	}
	
	/* random key */
    byteBuffer keyBuffer = genRandomByteBuffer(keySizeInBytes, keySizeInBytes);
    keyBytes = keyBuffer->bytes;
	
	/* cook up first context */
	CCHmacInit(&ctxOrig, hmacAlg, keyBytes, keySizeInBytes);
	
	/* roll the dice */
	die = (unsigned) genRandomSize(0, 3);
	
	/* 
	 * In this loop we do updates to the ctxOrig up until we
	 * clone it, then we use hmacRun to finish both of them.
	 */
	while(ptextLen) {
		if((die == loopNum) || !stagedOrig) {
			/* make the clone now */
			if(verbose) {
				diag("   ...cloning at loop %u\n", loopNum);
			}
			ctxClone = ctxOrig;
			didClone = true;
            if(memcmp(&ctxClone, &ctxOrig, CC_HMAC_CONTEXT_SIZE * sizeof(uint32_t))) {
                if(verbose) diag("*** context miscompare\n");
            } else {
                if(verbose) diag("*** context clone worked\n");
            }
			
			/* do all of the clone's updates and final here */
			hmacRun(&ctxClone, stagedClone, ptext, ptextLen, hmacClone);
			
			/* now do all remaining updates and final for original */
			hmacRun(&ctxOrig, stagedOrig, ptext, ptextLen, hmacOrig);
			
			/* we're all done, time to check the HMAC values */
			break;
		}	/* making clone */
		
		/* feed some data into cryptorOrig */
		size_t thisMove;
		if(stagedOrig) {
			thisMove = genRandomSize(1, ptextLen);
		}
		else {
			thisMove = ptextLen;
		}
		logSize(("###ptext segment (2) len %lu\n", (unsigned long)thisMove)); 
		CCHmacUpdate(&ctxOrig, ptext, thisMove);
		ptext += thisMove;
		ptextLen -= thisMove;
		loopNum++;
	}
		
	/* 
	 * It's possible to get here without cloning or doing any finals,
	 * if we ran thru multiple updates and finished ptextLen for cryptorOrig
	 * before we hit the cloning spot.
	 */
	if(!didClone) {
		if(verbose) {
			diag("...ctxOrig finished before we cloned; skipping test\n");
		}
		return 1;
	}
	if(memcmp(hmacOrig, hmacClone, hmacLen)) {
		diag("***data miscompare\n");
		rtn = 0;
	} else {
        if(verbose) diag("*** clone worked\n");
        rtn = 1;
    }
    if(keyBuffer) free(keyBuffer);
    
	return rtn;
}

static bool isBitSet(unsigned bit, unsigned word) 
{
	if(bit > 31) {
		diag("We don't have that many bits\n");
		return -1;
	}
	unsigned mask = 1 << bit;
	return (word & mask) ? true : false;
}


static int kTestTestCount = 1200;


int CommonHMacClone(int argc, char *const *argv)
{
	unsigned			loop;
	uint8_t				*ptext;
	size_t				ptextLen;
	bool				stagedOrig;
	bool				stagedClone;
	const char			*algStr;
	CCHmacAlgorithm		hmacAlg;	
	int					currAlg;		// ALG_xxx
	uint32_t				keySizeInBytes;
	int					rtn = 0;
	
	/*
	 * User-spec'd params
	 */
	bool		keySizeSpec = false;		// false: use rand key size
	HmacAlg		minAlg = ALG_FIRST;
	HmacAlg		maxAlg = ALG_LAST;
	unsigned	loops = LOOPS_DEF;
	bool		verbose = false;
	size_t		minPtextSize = MIN_DATA_SIZE;
	size_t		maxPtextSize = MAX_DATA_SIZE;
	bool		quiet = true;
	bool		stagedSpec = false;		// true means caller fixed stagedOrig and stagedClone
	
	/* ptext length set in test loop */
	plan_tests(kTestTestCount);
	
	for(currAlg=minAlg; currAlg<=maxAlg; currAlg++) {
		/* when zero, set size randomly or per user setting */
		switch(currAlg) {
			case ALG_MD5:
				hmacAlg = kCCHmacAlgMD5;
				algStr = "HMACMD5";
				break;
			case ALG_SHA1:
				hmacAlg = kCCHmacAlgSHA1;
				algStr = "HMACSHA1";
				break;
			case ALG_SHA224:
				hmacAlg = kCCHmacAlgSHA224;
				algStr = "HMACSHA224";
				break;
			case ALG_SHA256:
				hmacAlg = kCCHmacAlgSHA256;
				algStr = "HMACSHA256";
				break;
			case ALG_SHA384:
				hmacAlg = kCCHmacAlgSHA384;
				algStr = "HMACSHA384";
				break;
			case ALG_SHA512:
				hmacAlg = kCCHmacAlgSHA512;
				algStr = "HMACSHA512";
				break;
			default:
				diag("***BRRZAP!\n");
				return -1;
		}
		if(verbose) {
			diag("Testing alg %s\n", algStr);
		}
		for(loop=0; loop < loops; loop++) {
            byteBuffer bb =  genRandomByteBuffer(minPtextSize, maxPtextSize);
            ptextLen = bb->len; ptext = bb->bytes;
			if(!keySizeSpec) {
				keySizeInBytes = (uint32_t)genRandomSize(MIN_KEY_SIZE, MAX_KEY_SIZE);
			}
			
			/* per-loop settings */
			if(!stagedSpec) {
				stagedOrig = isBitSet(1, loop);
				stagedClone = isBitSet(2, loop);
			}
			
			if(!quiet) {
			   	if(verbose || ((loop % LOOP_NOTIFY) == 0)) {
					diag("..loop %d ptextLen %4lu keySize %3lu stagedOrig=%d "
						"stagedClone=%d\n", 
						loop, (unsigned long)ptextLen, (unsigned long)keySizeInBytes,
						(int)stagedOrig, (int)stagedClone);
				}
			}
			
			ok(doHMacCloneTest(ptext, ptextLen, hmacAlg, keySizeInBytes, stagedOrig, stagedClone, quiet, verbose), "HMacClone Test");
			if(loops && (loop == loops)) {
				break;
			}
            free(bb);
		}	/* main loop */
		
	}	/* for algs */
	
testDone:
	if((rtn != 0) && verbose) {
		diag("%s test complete\n", argv[0]);
	}
	return rtn;
}

#endif

Added CCRegression/CommonCrypto/CommonRSA.c.





































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402

#include "testbyteBuffer.h"
#include "testmore.h"
#include "capabilities.h"

#if (CCRSA == 0)
entryPoint(CommonRSA,"RSA Cryptography")
#else

#include <CommonCrypto/CommonRSACryptor.h>
static int kTestTestCount = 18;

static bool
RSAVerifyTest(byteBuffer modulus, byteBuffer exponent, byteBuffer message, byteBuffer signature, CCDigestAlgorithm digestSelector, int verbose, CCAsymetricPadding padding)
{
    CCRSACryptorRef CAVPubKey;
	CCCryptorStatus retval;
    byteBuffer digestValue = mallocByteBuffer(1024);
    byteBuffer decodedSignature = mallocByteBuffer(1024);

    retval = CCRSACryptorCreateFromData(ccRSAKeyPublic, modulus->bytes, modulus->len, exponent->bytes, exponent->len,
                                        NULL, 0, NULL, 0, &CAVPubKey);

    ok(retval == 0, "Build a CAVS test public key using CCRSACryptorCreateFromData");

    CCDigest(digestSelector, message->bytes, message->len, digestValue->bytes);
    digestValue->len = CCDigestGetOutputSize(digestSelector);

    if(verbose) {
        retval = CCRSACryptorCrypt(CAVPubKey, signature->bytes, 128, decodedSignature->bytes, &decodedSignature->len);
        printf("retval = %d\n", retval);
        printf("Decoded Signature %s\n", bytesToHexString(decodedSignature));
        printf("Digest of message %s\n\n\n", bytesToHexString(digestValue));
    }
    // ccOAEPPadding  ccPKCS1Padding ccX931Padding
    retval = CCRSACryptorVerify(CAVPubKey, padding, digestValue->bytes, digestValue->len, digestSelector, 0, signature->bytes, signature->len);
    printf("CCRSACryptorVerify returned %d\n", retval);
    free(digestValue);
    free(decodedSignature);
    return retval == kCCSuccess;
}


static void 
RSAX931BuildTest(uint32_t e, 
                 char *xp1str, char *xp2str, char *xpstr, 
                 char *xq1str, char *xq2str, char *xqstr,
                 char *pstr, char *qstr, char *mstr, char *dstr,
                 CCRSACryptorRef *retpublicKey, CCRSACryptorRef *retprivateKey)
{
    byteBuffer xp1, xp2, xp, xq1, xq2, xq, p, q, m, d;
    int verbose = 1;
    CCRSACryptorRef publicKey, privateKey;

    xp1 = hexStringToBytes(xp1str);
    xp2 = hexStringToBytes(xp2str);
    xp = hexStringToBytes(xpstr);
    xq1 = hexStringToBytes(xq1str);
    xq2 = hexStringToBytes(xq2str);
    xq = hexStringToBytes(xqstr);
    p = hexStringToBytes(pstr);
    q = hexStringToBytes(qstr);
    m = hexStringToBytes(mstr);
    d = hexStringToBytes(dstr);
    
    uint8_t modulus[1024], exponent[1024], pval[1024], qval[1024];
    size_t modulusLength, exponentLength, pLength, qLength;
    
    modulusLength = exponentLength = pLength = qLength = 1024;

    CCRSACryptorCreatePairFromData(e, 
                                   xp1->bytes, xp1->len, xp2->bytes, xp2->len, xp->bytes, xp->len, 
                                   xq1->bytes, xq1->len, xq2->bytes, xq2->len, xq->bytes, xq->len,
                                   &publicKey, &privateKey,
                                   pval, &pLength, qval, &qLength, modulus, &modulusLength, exponent, &exponentLength);
    /*
    retval = CCRSAGetKeyComponents(privateKey, modulus, &modulusLength, exponent, &exponentLength,
                                   pval, &pLength, qval, &qLength);
    ok(retval == 0, "got private key components");
     */
    
    byteBuffer retP = bytesToBytes(pval, pLength);
    byteBuffer retQ = bytesToBytes(qval, qLength);
    byteBuffer retD = bytesToBytes(exponent, exponentLength);
    byteBuffer retM = bytesToBytes(modulus, modulusLength);
    
    if(bytesAreEqual(retP, q) && bytesAreEqual(retQ, p)) {
        byteBuffer tmp = p;
        p = q;
        q = tmp;
        printf("Swapped P and Q\n");
    }
    
    ok(bytesAreEqual(retP, p), "p is built correctly");
    ok(bytesAreEqual(retQ, q), "q is built correctly");
    ok(bytesAreEqual(retD, d), "n is built correctly");
    ok(bytesAreEqual(retM, m), "d is built correctly");
    
    if(verbose) {
        if(!bytesAreEqual(retP, p)) printf("P\nreturned: %s\nexpected: %s\n\n", bytesToHexString(retP), bytesToHexString(p));
        else printf("P is correct\n");
        if(!bytesAreEqual(retQ, q)) printf("Q\nreturned: %s\nexpected: %s\n\n", bytesToHexString(retQ), bytesToHexString(q));
        else printf("Q is correct\n");
        if(!bytesAreEqual(retD, d)) printf("D\nreturned: %s\nexpected: %s\n\n", bytesToHexString(retD), bytesToHexString(d));
        else printf("D is correct\n");
        if(!bytesAreEqual(retM, m)) printf("M\nreturned: %s\nexpected: %s\n\n", bytesToHexString(retM), bytesToHexString(m));
        else printf("M is correct\n");
    }
    *retpublicKey = publicKey;
    *retprivateKey = privateKey;
}

int CommonRSA (int argc, char *const *argv) {
	CCCryptorStatus retval;
    size_t keysize;
    CCRSACryptorRef publicKey, privateKey;
    byteBuffer keydata, dekeydata, hash;
    char encryptedKey[8192];
    size_t encryptedKeyLen = 8192;
    char decryptedKey[8192];
    size_t decryptedKeyLen = 8192;
    char signature[8192];
    size_t signatureLen = 8192;
    // char importexport[8192];
    // size_t importexportLen = 8192;
    char inputpadded[128], outputpadded[128];
    int accum = 0;
    int debug = 0;
    // int verbose = 1;

    
	plan_tests(kTestTestCount);
    
    keysize = 1024;
    
    if(debug) printf("Keygen\n");
    retval = CCRSACryptorGeneratePair(keysize, 65537, &publicKey, &privateKey);
    
    ok(retval == 0, "Generate an RSA Key Pair");
    accum += retval;
    
    if(debug) printf("Encrypt/Decrypt\n");
    keydata = hexStringToBytes("000102030405060708090a0b0c0d0e0f");
        
    retval = CCRSACryptorEncrypt(publicKey, ccPKCS1Padding, keydata->bytes, keydata->len, encryptedKey, &encryptedKeyLen,
                        "murf", 4, kCCDigestSHA1);
    
    ok(retval == 0, "Wrap Key Data with RSA Encryption - ccPKCS1Padding");
    accum += retval;
    
    retval = CCRSACryptorDecrypt(privateKey, ccPKCS1Padding, encryptedKey, encryptedKeyLen,
                        decryptedKey, &decryptedKeyLen,"murf", 4, kCCDigestSHA1);
    
    ok(retval == 0, "Unwrap Key Data with RSA Encryption - ccPKCS1Padding");
    accum += retval;

	dekeydata = bytesToBytes(decryptedKey, decryptedKeyLen);
    
	ok(bytesAreEqual(dekeydata, keydata), "Round Trip ccPKCS1Padding");
    accum += !bytesAreEqual(dekeydata, keydata);

    if(debug) printf("Encrypt/Decrypt 2\n");
    
    encryptedKeyLen = 8192;
    decryptedKeyLen = 8192;
    
    retval = CCRSACryptorEncrypt(publicKey, ccOAEPPadding, keydata->bytes, keydata->len, encryptedKey, &encryptedKeyLen,
                                 "murf", 4, kCCDigestSHA1);

    ok(retval == 0, "Wrap Key Data with RSA Encryption - ccOAEPPadding");
    accum += retval;
    
    
    retval = CCRSACryptorDecrypt(privateKey, ccOAEPPadding, encryptedKey, encryptedKeyLen,
                                 decryptedKey, &decryptedKeyLen,"murf", 4, kCCDigestSHA1);
    
    ok(retval == 0, "Unwrap Key Data with RSA Encryption - ccOAEPPadding");
    accum += retval;
    
	dekeydata = bytesToBytes(decryptedKey, decryptedKeyLen);
    
	ok(bytesAreEqual(dekeydata, keydata), "Round Trip ccOAEPPadding");
        
    if(debug) printf("Sign/Verify\n");
    hash = hexStringToBytes("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f");

    retval = CCRSACryptorSign(privateKey, ccPKCS1Padding, 
                     hash->bytes, CCDigestGetOutputSize(kCCDigestSHA256),
                     kCCDigestSHA256, 16,
                     signature, &signatureLen);

    ok(retval == 0, "RSA Signing");
    accum += retval;
    
    retval = CCRSACryptorVerify(publicKey, ccPKCS1Padding,
                       hash->bytes, CCDigestGetOutputSize(kCCDigestSHA256), 
                       kCCDigestSHA256, 16,
                       signature, signatureLen);
    ok(retval == 0, "RSA Verifying");
    accum += retval;
    signatureLen = 8192;
    retval = CCRSACryptorSign(privateKey, ccOAEPPadding, 
                              hash->bytes, CCDigestGetOutputSize(kCCDigestSHA1),
                              kCCDigestSHA1, 16,
                              signature, &signatureLen);
    
    ok(retval == 0, "RSA Signing OAEP");
    accum += retval;
    
    retval = CCRSACryptorVerify(publicKey, ccOAEPPadding,
                                hash->bytes, CCDigestGetOutputSize(kCCDigestSHA1), 
                                kCCDigestSHA1, 16,
                                signature, signatureLen);
    ok(retval == 0, "RSA Verifying OAEP");
    accum += retval;

#ifdef NEVER
    memset(signature, 5, 8192);

    retval = CCRSACryptorSign(privateKey, ccX931Padding, 
                              hash->bytes, CCDigestGetOutputSize(kCCDigestSHA1),
                              kCCDigestSHA1, 16,
                              signature, &signatureLen);
    
    //diag("Signature retval = %d\n", retval);
    
    ok(retval == 0, "RSA Signing");
    accum += retval;
    
    retval = CCRSACryptorVerify(publicKey, ccX931Padding,
                                hash->bytes, CCDigestGetOutputSize(kCCDigestSHA1), 
                                kCCDigestSHA1, 16,
                                signature, signatureLen);
    ok(retval == 0, "RSA Verifying");
    accum += retval;

	retval = CCRSACryptorExport(publicKey, importexport, &importexportLen);
    
    ok(retval == 0, "RSA Export Public Key");
    accum += retval;

    retval = CCRSACryptorImport(importexport, importexportLen, &publicKey2);
    
    ok(retval == 0, "RSA Import Public Key");
    accum += retval;
                      
	importexportLen = 8192;
	retval = CCRSACryptorExport(privateKey, importexport, &importexportLen);
    
    ok(retval == 0, "RSA Export Private Key");
    accum += retval;
    
    retval = CCRSACryptorImport(importexport, importexportLen, &privateKey2);
    
    ok(retval == 0, "RSA Import Private Key");
    accum += retval;
#endif

    if(debug) printf("Starting to build key from data\n");
    uint32_t e = 3;
    char *xp1, *xp2, *xp, *xq1, *xq2, *xq, *p, *q, *m, *d;
    xp1 = "1eaa9ade4a0da46dd40824d814";
    xp2 = "17379044dc2c6105423da807f8";
    xp = "fd3f368d01a95944bc1578f8ae58a9b6c17f529da1599a8bcd361df6efede4176924944e30cbe5c2ddea5648019d2086b95c68588380b8725003b047db88f92a";
    xq1 = "1da08feb13d9fba526190d3756";
    xq2 = "10d93d84466d213a3e776c61f6";
    xq = "f67b5f051126a8956171561b62f572090cde4b09b13f73ee28a90bea2bfb4001fe7b16bd51266524684520e77941dddc56b892ae4bd09dd44acc08bf45dd0a58";
    
    
    p = "fd3f368d01a95944bc1578f8ae58a9b6c17f529da1599a8bcd361df6efede4176924944e30d114d4c767d573d1149e005267e6fe36c51d86968cf6f65afcb973";
    q = "f67b5f051126a8956171561b62f572090cde4b09b13f73ee28a90bea2bfb4001fe7b16bd5129f06dc6e1f8b4f739c7eb1eb8dcacca3b41cd484fc0c693367037";
    m = "f3d4c9ca2dca5d4b893919ae7bee0d174d1e7bd2190287f79a7db6f21366108e8b0aa37cc972989ff3730d629620076555884da0e895d4e426449c60e36fad1d0208dd4ade1c45fc90da5e76c9c89fd95d13ce76a97530ee83ea3cfbe96cf28f85c4756797cd0123683194b7b2fcd185c3ea984cb0ef90580f95d57a44b027b5";
    d = "28a376f707a1ba3741898447bf525783e22fbf4daed5c153ef14f3d3033bad6d172c7094cc3dc41aa8932ce5c3b0013b8e4162457c18f8d0b10b6f657b3d478482626149773760b0688ded3b1ebf16044273b2cd3924b068c2572dd9cceb4d13afb0cc64ae4da9facefbf66d271d11ef0dcc4e1af2a7dd80b2c984f4e3bf7fad";

    
    RSAX931BuildTest(e, xp1, xp2, xp, xq1, xq2, xq, p, q, m, d, &publicKey,  &privateKey);

    e = 0x010001;
    xp1 = "155e67ddb99eefb13e4b77a7f0";
    xp2 = "17044df236c14e8ec333e92506";
    xp = "d4f2b30f4f062ad2d05fc742e91bc20ca3ee8a2d126aff592c7de19edb3b884550ddd6f99b0a6b2b785617b46c0995bc112176dbae9a5b7f0bec678e84d6f44c";
    p = "d4f2b30f4f062ad2d05fc742e91bc20ca3ee8a2d126aff592c7de19edb3b884550ddd6f99b13e5dd56ffb2ac1867030f385597e712f65ac8dd1de502857c1a41";
    xq1 = "1e2923b103c935e3788ebd10e4";
    xq2 = "11a2ccec655a8b362b5ec5fcc4";
    xq = "f7c6a68cff2467f300b82591e5123b1d1256546d999a37f4b18fe4896464df6987e7cc80efee3ce4e2f5c7a3cc085bbe33e4d375ed59cbc591f2b3302bd823bc";
    q = "f7c6a68cff2467f300b82591e5123b1d1256546d999a37f4b18fe4896464df6987e7cc80efeeb4c59165f7d1aec9be2b34889dbe221147e7ceefb5c9bd5cb945";
    m = "ce1b6904ec27f4a8f420414860704f4797a202ed16a9a35f63a16511a31675ccb046b02b192ef121b328385922f5faa032113332d42f84c70d4323133e216b0f339ebaf672f6214d0d7c13bea301174485ec44f44fae0e8a7f8d3c81ced5df77723331816158c3added7dc55f1436a7e5f14730be22cf3bebab1b62915c80c85";
    d = "18d16522721b5793169e61ae08eacd291641ac6f8718933313c8a5e66b487393dbb00f5b89334556e4ff5555aa678b2fca07972e2a2db4a3d15d81b639f7852ffe71657918d0280ff1be2f8f5d90b3e68195ab35e5069a3053540958bc6d58489fecf8baab0981f4af7b4db43550bcf01114e5ecdcb18f228db1c617b5d09781";
    RSAX931BuildTest(e, xp1, xp2, xp, xq1, xq2, xq, p, q, m, d, &publicKey,  &privateKey);

#ifdef NEVER
    e = 3;
    xp1 = "1c36bd0874761109bb0575ee16";
    xp2 = "1777c33935db08546dd66b6d96";
    xp = "d040fa5fe5e32eab84bac6cab4c512dae938cbbe4a29f972b78b149b0b5f6a639e29c0830fa13ca140ac83dda18a1ea7b25122d3c39a10effe7afad4a8b4e77ba42c7912399fcd4f1592a3059188bff536788fe6807e0df8e3d1e7350cf5dd69";
    p = "d040fa5fe5e32eab84bac6cab4c512dae938cbbe4a29f972b78b149b0b5f6a639e29c0830fa13ca140ac83dda18a1ea7b25122d3c39a10effe7afad4a8b4e77ba42c791239acf889977037a0efe181d54b93279b7e46a2fdcf674039fb11e89b";
    xq1 = "14c70e475b12870bc6efd3b944";
    xq2 = "1432548a4959eed65b858cd316";
    xq = "e4d222daf062a01a3a9ddfc82a229613403b772ff05fa9fab1fc77de51744af98b65d47bdb2e8f5091af66002550b1d3ca446738450f8f670045f8465a952a8942079c1e048228c86291bb0ae7665146782021262c49143b5ea37ce400240372";
    q = "e4d222daf062a01a3a9ddfc82a229613403b772ff05fa9fab1fc77de51744af98b65d47bdb2e8f5091af66002550b1d3ca446738450f8f670045f8465a952a8942079c1e04937b7eb94b8d322faefd691b6fa2b0ef4a2333ed791afe8ac3ac41";
    m = "ba24d0a5878c01f6ad9140b6271b42309887a6815d5ef1bc3415a381b7b511a42b8d2b8d9df59faa0b69456ff908e24b4ccb835420404ce449c9ce4ca65dc4ae4eb6bb8403b809d530ef4b37e5b211c13a03e2a69afb8c748b90c97d52023ae9a24c1f1f4b3b87685eaa649f54e41b6439e29700543f0747f09658ed392f96ee568a50ad7b5441c88ad37c581526ff296b1c6cc87e352d4f921960b6b630f8f546f1077a7586b839ee07717de84e0a19cd52eceb358ff2c69387b13a83e5335b";
    d = "1f0622c641420053c7983573b12f35b2c4169bc03a3a7d9f5e039b404948d846074231ecefa8eff1ac918b92a9817b0c8ccc95e35ab562260c4c4d0cc664f61d0d1e7496009eac4e32d28c8950f302f589ab507119d49768c1ed76ea3855b47bfcded5a6137e49706fe2f50213aa1313ad67b8adaef390a46bd7ccbdfa0f5042dcd4749d181613a3c9694314626207c7a7c125ca139742296de412449dd1267d6574d30c5e8bb60844e1f21c76ca41cf3bb805c521553218ce71390055029a6b";
    RSAX931BuildTest(e, xp1, xp2, xp, xq1, xq2, xq, p, q, m, d, &publicKey,  &privateKey);

    e = 3;
    xp1 = "1408766e2cb2d47ebfee7ea614";
    xp2 = "16292b77507cffd2f798b7c9f2";
    xp = "f74435451a7ddaa163c8c8ad03dfde97fe066360dfee52e3a9d8f41310fdb484e92e302de0b88c6c698a0b4af99ae001758441bbeb74be9d8047d104a9edb60e9e127c5d0cfd5d170ab84b314f71cbeea22006a2916a1dbc66c5be0357def520fd38445d0815f5ac3099afeb6f2d48666d22da9e3c961949459ce399829719c1";
    p = "f74435451a7ddaa163c8c8ad03dfde97fe066360dfee52e3a9d8f41310fdb484e92e302de0b88c6c698a0b4af99ae001758441bbeb74be9d8047d104a9edb60e9e127c5d0cfd5d170ab84b314f71cbeea22006a2916a1dbc66c5be0357def520fd38445d081fbe68dd24e14f0711cc0351fec8641d8ea7d22c4709f233e6349b";
    xq1 = "161d77eb77c6f257d8f8a3b0ca";
    xq2 = "152f11dfc70b78f0fc6c9137b8";
    xq = "c4d3feeb0e561be3727fd83dedaeaaecba01c798e917dd8bb11a03ce07fcf08f6f006ac6137d021912dffffc1aee981c395366fef05718e38aef69f0abf64f8b2cb9750826b8ec854dab1e1280c403169e3497ee9af08bd6d2b53a0d9c49e034220506f7719041f0cced1cc846b853a090ac42af0f699c2c3174606e02800952";
    q = "c4d3feeb0e561be3727fd83dedaeaaecba01c798e917dd8bb11a03ce07fcf08f6f006ac6137d021912dffffc1aee981c395366fef05718e38aef69f0abf64f8b2cb9750826b8ec854dab1e1280c403169e3497ee9af08bd6d2b53a0d9c49e034220506f771942204f0890fb5e617c580aa98a7482b5457215badc119f23b21c3";
    m = "be1cfc39868d8e9a8239f504482be60c01071cbdab4355b03c10edafe85d9ca10689d86036b6d35829a364a8a2b69f28743e50e5e27ac6b6fe8962809e1c2e0765b2d7508d61bfa538085dfb685595c6965bc5e0855a6dd8807a83e2ee7fc50b5b48f2d232195b672f2c325eb6649dee9758ce76f690107f3b0d10afef427777fb0bac0a41e23717fc54d9194a344d1823bdc18fa364e5373da39a3e41bcc4d88a688a711b56c6387b669d37c4fd7878559b93473869ae8190c46605f03cf25038bf771246fb81a27bc9d44ba67bfce94a3051856511661dbe0803d220809695ad707022c4acd24d40e011eb3752e39568f66cdd2d90369a67295e19dadb0d11";
    d = "1faf7f5eebc2426f15b45380b6b1fbacaad684ca4735e39d5f58279d5164ef702bc1a410091e788eb19b3b717073c53168b50d7ba5bf211e7fc1906ac504b25690f323e2c23af546340164ff3c0e43a1190f4ba56b8f124ec0146b507d154b81e48c28785daee49132875dba73bb6fa7c3e42269291802bfdf2cd81d528b13e90a7de94f042d0ac33102095d0ec64b433c9e43c3a4651e215072c5ba3175aff6085efd3f868589487fd4c2fd72be000f1bcb51c20f6fa3d56b97872d6f0ed21e67a896478336340105e6672bf90bb250ac4f487e0973ca17161781f58763f58ac25ddb77b7297da53dddb02661b18dad920fd4dd7b7233f125336dd79e1ef3c9";
    RSAX931BuildTest(e, xp1, xp2, xp, xq1, xq2, xq, p, q, m, d, &publicKey,  &privateKey);

    e = 3;
    xp1 = "164511563871556a9babc022c8";
    xp2 = "1ae2a7a04f23efe080f48a24b0";
    xp = "db5c4ccf412b17041b6e20b7e0cb45d807ef4da8282428e05e26782fef3251ea2f613d00a134842c6070aa6ebd2c38bb2a28c0f457601b159ae1f5af94dc8c9812f9b4e031ed1f08c64fdb6ffca71c0d3fc93c63596100b2dbce1d6cbf34fae84bccb859397f700114b4bba2e56678360f79c9df784e5f21e995f84fb8622543a48351520012ff80144653efc08ed49e62e17050fa4fc1c98cdd8e40c68f9512e3c687b4cfcc55eb8caeaa3fd44ab8ad00a8389c288eac128c4ee82832e3d0bb";
    p = "db5c4ccf412b17041b6e20b7e0cb45d807ef4da8282428e05e26782fef3251ea2f613d00a134842c6070aa6ebd2c38bb2a28c0f457601b159ae1f5af94dc8c9812f9b4e031ed1f08c64fdb6ffca71c0d3fc93c63596100b2dbce1d6cbf34fae84bccb859397f700114b4bba2e56678360f79c9df784e5f21e995f84fb8622543a48351520012ff80144653efc08ed49e62e17050fa4fc1c98cdd8e40c68f9512e3c687b4d000a836a83d21ea810c683a30e79e5fc8626e78961f076aef2f89ab";
    xq1 = "18ab1ad30607288890b387858a";
    xq2 = "19975a38d9368fa99deda7e986";
    xq = "bd7cc6c56616fb5b41f35d8de2a5c61d1894895dfa46aa95c2de4ea5dfe370eb4543d6670898431d29a9efbbb034347cfaeb8a4c55bcb52dca553dd93ae81fa9ad2bc2b5e6a42c3d3b237648a3907d8a11e6db8b008016064f94168f50fddd791c3d72f729c21e811e68db7ae5400a0f02906462241a33e8faa1c20f48aa12253a80ce75f87a81b37a80079a9ecc42d378ee0e19e913769b738628a14b772673b0fcbf777c55be99f974e1eff5bd8c9d190abff776f246e6614b2f8d81ed812c";
    q = "bd7cc6c56616fb5b41f35d8de2a5c61d1894895dfa46aa95c2de4ea5dfe370eb4543d6670898431d29a9efbbb034347cfaeb8a4c55bcb52dca553dd93ae81fa9ad2bc2b5e6a42c3d3b237648a3907d8a11e6db8b008016064f94168f50fddd791c3d72f729c21e811e68db7ae5400a0f02906462241a33e8faa1c20f48aa12253a80ce75f87a81b37a80079a9ecc42d378ee0e19e913769b738628a14b772673b0fcbf777c640b3b2f869336b823710bb296f32aaba903f90af79239c3d97279";
    m = "a25e0fbcc06a40ac879bba988e78b9df8f88b800077d580b615e3f2f663c9ce631eb0229ee7a4d5166122378bd055f686dd382e63c1564c96127ec191c88d1ba02fcf90f1efcfe29bdfab0fd6413dcb4027512d15c2e337f7111e7acc7679cd1b96581461466ca63af5fbfc0579d322ca02413b75a6dce25c529d6475fafbc5d07504a29039c0f567cbb9dff2938687a6e6d4633f9ae46383536060dc7efb90ff99a6e97449e8f8ad24853f70726953b3f1dc82222f8407f98250f2060777cbd05d0b2ed6abb99d86ac30974df41da16bc1e3abd610df6bcff49a2be932baeedf163911eec026dcbd5937734b47ceb48db97c27bd2a35338f90332b75374ae4404913ae82caf14bba7410c638676a544046aed0b6605562186a4ba6b3695ab25f900899bd03a8f3e68d548b4eadbd9a348a142618954b1b9d73245926d6c57e26454db887c6272280c2d0efff1b856762da7c8be77a0006da3ea589b21ee5efec36574c041d8e506af55de52083225242642cafdcdadfa9663e4424a2bb937d3";
    d = "1b0fad4a2011b5721699f46ec269744fed417400013f8eac903a5fdd3bb4c4d10851d5b1a7bf0ce2e6585b3eca2b8fe6bcf895d10a0390cc3adbfcaeda16cd9f007f7ed7da7f7fb19fa9c82a3b58a4c8ab138322e4b25dea92d85147769144cd9ee6403658bbcc65f28ff54ab944ddb21ab0adf3e467a25ba0dc4e613a9d4a0f81380c5c2b44ad3914c9efaa86debc1467bce108a99d0bb408de5657a1529ed7feef126e8b6fc297230c0dfe813118df352fa15b05d40abfeeb0d7dababe94c9e77e9a8ecb3eebe9823aec87d9f8225aef4465f3dfc5db367a60cf517603a7596a1fbf9e8b08f115b73ecf81b684bfad73c093df30ebc07e434caa87c09d55ab0b674b3858afa1939ba249c7265fd747731f2384d75b5fe6b9e06bbd3110787618290fb73cd42aca08f3f2ee855e393a5e6e835aa77cafc7d329c1dde7655abeeb8d74a015f8d2d36a3bc8939864dfd60da40c63435f76ac1b411af42d5145e95d1b0798a8e8b2ee23edb188228061fa60760993399b16b0cb2246c63ec809f3";
    RSAX931BuildTest(e, xp1, xp2, xp, xq1, xq2, xq, p, q, m, d, &publicKey,  &privateKey);

    
    e = 3;
    xp1 = "1a02a180a22a37d3ab4d5523fe";
    xp2 = "1179fc502dbe82ff9946c00392";
    xp = "d94a30017127e43b0005e99016c2f4efb8e0c91e61805b52478e35fddf3918e7a3a6e68013e5be75fa246981f222f5862ae79fdc67b3f7e849343ef1d0fb13301e314f267f862d33a66bae633a813b8b91518c95bb3dca18c2b6f02c30b0777cd253329cbcf4779d8d437fdff4c60f27738658f163081d08397e1353073f8df24675588ad215e4dc3615a59d2ad9b9815aeecb9a69fa37e036f36f115e909dbb02fd8a96cad3be182947e944e3a281c3cdf1ad35d4fd62c9417dcb0b3c8beffe8e558e6bab154b78ef43117c2808af1255f7c56dadf8e4ebe384f1eca918cae473e32caf7dc2d5250f6fe5ef00f68a997968dce7fbd2066da370a75aad1f7895";
    p = "d94a30017127e43b0005e99016c2f4efb8e0c91e61805b52478e35fddf3918e7a3a6e68013e5be75fa246981f222f5862ae79fdc67b3f7e849343ef1d0fb13301e314f267f862d33a66bae633a813b8b91518c95bb3dca18c2b6f02c30b0777cd253329cbcf4779d8d437fdff4c60f27738658f163081d08397e1353073f8df24675588ad215e4dc3615a59d2ad9b9815aeecb9a69fa37e036f36f115e909dbb02fd8a96cad3be182947e944e3a281c3cdf1ad35d4fd62c9417dcb0b3c8beffe8e558e6bab154b78ef43117c2808af1255f7c56dadf8e4ebe384f1eca918cae473e32caf7dd1126fd14c73ebcce310791625550d6582891713c38ac374993099";
    xq1 = "1fb621dce29cbb6a66cc3bf7d6";
    xq2 = "122325102c2e57c27d462e1e06";
    xq = "facc7f5f089ed9267363bc23c6c7b8f73208a36f61fa8ea8084ff777bc154107068061c4b9ead9788318eab4c3bf05729a4684f845ce9700aa70811530c50440d4ac19e47a47e5e78047e912996a79bbd9416fa10c3720174ccf8f65d32de16b0dd81187f1bee5b992792105f1d0fa191681cd305f3e113617f58b2d4a54c0cfd88db075c956c137e034fa5573fa71d67a8c076ee5e952a53369db3640438ab55e515e75a81861a99303dcc9c6efc7382cec83234742ccacc7b3e9485b002565c7af8351370aae57d26b2f2b93b7e2885429ab172c516593fb5c1b2b43957b273a2c87cf1d368e88c6f65b41815bac0d1cc9e6113d1d06a1f8ebdba6a1097343";
    q = "facc7f5f089ed9267363bc23c6c7b8f73208a36f61fa8ea8084ff777bc154107068061c4b9ead9788318eab4c3bf05729a4684f845ce9700aa70811530c50440d4ac19e47a47e5e78047e912996a79bbd9416fa10c3720174ccf8f65d32de16b0dd81187f1bee5b992792105f1d0fa191681cd305f3e113617f58b2d4a54c0cfd88db075c956c137e034fa5573fa71d67a8c076ee5e952a53369db3640438ab55e515e75a81861a99303dcc9c6efc7382cec83234742ccacc7b3e9485b002565c7af8351370aae57d26b2f2b93b7e2885429ab172c516593fb5c1b2b43957b273a2c87cf1d710fc707b5e6d58b6f3cb377b286466c4da41f592c749ebf97fca3";
    m = "d4e0061c2150cdf177232b89266af9153902cbd434a39cab549d997ed6dadcb4e84bbac6d49658428728a01bd7036bab4b0003f7e6ccf69df1effad985185c4ab0756237e4be92b2f42085d4388a29f461af98649c700d6dad5e0fe352513b578b3bff5f19b144e6304defe1b4fb43b37ecb4ed7c0e97377802d9e79c6d742837b3b71fd101fcf5ead4a114d9419af008a421d8a4c5efd4e6da8cc3c967502bd4cc1bda09e87bf7a1d0badaf0783a6dbef5c98359c59d6bda1cc9bacfaa962c841ddfa3670211e38a68998508ea1a2be519718a168d09cc0d2c1d0f8d56ca1d7199b0c4fc78ddb595f6681e5b1b96309251c0714bf134d46f58419a0273bfaab3328b59d75d8ada5e6e2745e816d17ded27b52f0b5632088ee6bf9675793adc52591abc3eacbf3ae4b59871ac9c94e98708801f534ad0a99791827e91cbacf7afbbd72e162698aeba0380f74462b8dd097fb576a99d70ad2117efee8f6ef51d6afd6fb8ce9b6c234ebf00d24d44ad505305e48af1a8037fed9a2a44235980d395bf69489309d37a04b66f236d223b1af759232ecf9d6556a71cd74c4936fc6d3efe6efb3311eea1574e0cebd657a9d36142f0719b95c98900bd32b9cdb6702ff92a7eefc5ec99c6f12709cb3a118cdaf56284dd195e0633dd689889924c42d3e6579e403bb3ecb08310128c673de301c3bea248f3bd0f63cab3f2545da9f8d6b";
    d = "237aabaf5ae2ccfd93db31ec3111d42e342b21f8b3709a1c8e1a443fce79cf737c0c9f21236e640b1686c559f92b3c9c8c8000a95122291a52fd5479962eba0c72be3b0950ca6dc87e056ba35ec1b1a8baf299661a12ace79ce502a5e30d89e3ec89ffe52ef2e0d1080cfd5048d48b489521e2794ad1933e955cefbef67935c09489e854d8054d3a723702e243599d2ac1b5af970cba7f8d1246ccb4c3be2b1f8ccaf4f01a6bf53f04d7479d2beb4679fd3a195e44b9a3ca45a219f229c6e5cc0afa545e680585097116eeb817c59b1fb843d9703c22c4cacdcaf82978e7704e8444820d4becf9e43a9115a648499081862f5683752de2367e40aef00689ff1c3a83010a2a02fd60bde977c71b5066fea69851107da6b3c26fc24ca84a0b8df91491bb3fda29e49ff7af5dd0adfbe3454739a4dac131bf48163de6a5af29c957017aac4e66c493f81440beaa685ff96c323c0f334dbb057055a96a8e7dd8297d229c9e915f2b3b7a4cb33cb5279df74b710e5b178eb456f56c07d64afb55f513df7dec96c388184208da0db6088d410e9aae8ffb46fdcc7b813d5c6a28c49a65ed1956711fb321b89ec38172747c0e09aee2ce756f84bc2f00703e8c35f9d2448a1b24dfea1c45c50d75ba01fb8eb4ae1cabcf8cc9ee5974fe9c14958958fbddc93c5d40daaa1c22e3ffcd00d9eca5d29d030c3491aacc2bb50d30fb4667bab3";
    RSAX931BuildTest(e, xp1, xp2, xp, xq1, xq2, xq, p, q, m, d, &publicKey,  &privateKey);

#endif
   
    bzero(inputpadded, 128);
    bzero(outputpadded, 128);
    bcopy(keydata->bytes, inputpadded, keydata->len);
    decryptedKeyLen = 128;
    retval = CCRSACryptorCrypt(privateKey, inputpadded, 128, encryptedKey, &encryptedKeyLen);

    ok(retval == 0, "RSA Raw Private Key Crypt");
    accum += retval;

    retval = CCRSACryptorCrypt(publicKey, encryptedKey, encryptedKeyLen, outputpadded, &decryptedKeyLen);

    ok(retval == 0, "RSA Raw Private Key Crypt");
    accum += retval;
    bcopy(outputpadded, decryptedKey, keydata->len);
    
 	dekeydata = bytesToBytes(decryptedKey, keydata->len);
    ok(bytesAreEqual(dekeydata, keydata), "RSA Raw Encrypt/Decrypt Round-Trip");
	if(!bytesAreEqual(dekeydata, keydata)) {
        diag("expected: %s\n", bytesToHexString(keydata));
        diag("     got: %s\n", bytesToHexString(dekeydata));
        diag("len = %d\n", (int) decryptedKeyLen);
    }
    
    
    static const uint8_t		kAirTunesRSAPublicKey[] = 
    {
        0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, 0x00, 0xE7, 0xD7, 0x44, 0xF2, 0xA2, 0xE2, 0x78, 
        0x8B, 0x6C, 0x1F, 0x55, 0xA0, 0x8E, 0xB7, 0x05, 0x44, 0xA8, 0xFA, 0x79, 0x45, 0xAA, 0x8B, 0xE6, 
        0xC6, 0x2C, 0xE5, 0xF5, 0x1C, 0xBD, 0xD4, 0xDC, 0x68, 0x42, 0xFE, 0x3D, 0x10, 0x83, 0xDD, 0x2E, 
        0xDE, 0xC1, 0xBF, 0xD4, 0x25, 0x2D, 0xC0, 0x2E, 0x6F, 0x39, 0x8B, 0xDF, 0x0E, 0x61, 0x48, 0xEA, 
        0x84, 0x85, 0x5E, 0x2E, 0x44, 0x2D, 0xA6, 0xD6, 0x26, 0x64, 0xF6, 0x74, 0xA1, 0xF3, 0x04, 0x92, 
        0x9A, 0xDE, 0x4F, 0x68, 0x93, 0xEF, 0x2D, 0xF6, 0xE7, 0x11, 0xA8, 0xC7, 0x7A, 0x0D, 0x91, 0xC9, 
        0xD9, 0x80, 0x82, 0x2E, 0x50, 0xD1, 0x29, 0x22, 0xAF, 0xEA, 0x40, 0xEA, 0x9F, 0x0E, 0x14, 0xC0, 
        0xF7, 0x69, 0x38, 0xC5, 0xF3, 0x88, 0x2F, 0xC0, 0x32, 0x3D, 0xD9, 0xFE, 0x55, 0x15, 0x5F, 0x51, 
        0xBB, 0x59, 0x21, 0xC2, 0x01, 0x62, 0x9F, 0xD7, 0x33, 0x52, 0xD5, 0xE2, 0xEF, 0xAA, 0xBF, 0x9B, 
        0xA0, 0x48, 0xD7, 0xB8, 0x13, 0xA2, 0xB6, 0x76, 0x7F, 0x6C, 0x3C, 0xCF, 0x1E, 0xB4, 0xCE, 0x67, 
        0x3D, 0x03, 0x7B, 0x0D, 0x2E, 0xA3, 0x0C, 0x5F, 0xFF, 0xEB, 0x06, 0xF8, 0xD0, 0x8A, 0xDD, 0xE4, 
        0x09, 0x57, 0x1A, 0x9C, 0x68, 0x9F, 0xEF, 0x10, 0x72, 0x88, 0x55, 0xDD, 0x8C, 0xFB, 0x9A, 0x8B, 
        0xEF, 0x5C, 0x89, 0x43, 0xEF, 0x3B, 0x5F, 0xAA, 0x15, 0xDD, 0xE6, 0x98, 0xBE, 0xDD, 0xF3, 0x59, 
        0x96, 0x03, 0xEB, 0x3E, 0x6F, 0x61, 0x37, 0x2B, 0xB6, 0x28, 0xF6, 0x55, 0x9F, 0x59, 0x9A, 0x78, 
        0xBF, 0x50, 0x06, 0x87, 0xAA, 0x7F, 0x49, 0x76, 0xC0, 0x56, 0x2D, 0x41, 0x29, 0x56, 0xF8, 0x98, 
        0x9E, 0x18, 0xA6, 0x35, 0x5B, 0xD8, 0x15, 0x97, 0x82, 0x5E, 0x0F, 0xC8, 0x75, 0x34, 0x3E, 0xC7, 
        0x82, 0x11, 0x76, 0x25, 0xCD, 0xBF, 0x98, 0x44, 0x7B, 0x02, 0x03, 0x01, 0x00, 0x01, 0xD4, 0x9D
    };
    
    CCRSACryptorRef		key;
    
    retval = CCRSACryptorImport( kAirTunesRSAPublicKey, sizeof( kAirTunesRSAPublicKey ), &key );

    ok(retval == kCCSuccess, "Imported Airport Key");
    accum += retval;
    
    return accum != 0;
}
#endif /* CCRSA */

Added CCRegression/CommonCrypto/CommonRandom.c.



















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  randomTest
 *  CommonCrypto
 */
#include "testmore.h"
#include "capabilities.h"
#include "testbyteBuffer.h"

#if (CCRANDOM == 0)
entryPoint(CommonRandom,"Random Number Generation")
#else
#include <CommonCrypto/CommonRandomSPI.h>

static const int kTestTestCount = 1000;
static const int bufmax = kTestTestCount + 16;

int CommonRandom(int argc, char *const *argv)
{
    int i;
    uint8_t buf1[bufmax], buf2[bufmax], buf3[bufmax], buf4[bufmax], buf5[bufmax], buf6[bufmax];
    CCRandomRef rngref;
    CCRNGStatus retval;
    
	plan_tests(kTestTestCount *3);
    retval = CCRNGCreate(0, &rngref);
    
    struct ccrng_state *devRandom = ccDevRandomGetRngState();
    struct ccrng_state *drbg = ccDRBGGetRngState();
    for(i=0; i<kTestTestCount; i++) {
        size_t len = i+16;
        CCRandomCopyBytes(kCCRandomDefault, buf1, len);
        CCRandomCopyBytes(kCCRandomDevRandom, buf2, len);
        CCRandomCopyBytes(rngref, buf3, len);
        CCRandomCopyBytes(NULL, buf4, len);
        ccrng_generate(devRandom, len, buf5);
        ccrng_generate(drbg, len, buf6);

        ok(memcmp(buf1, buf2, len), "Buffers aren't the same");
        ok(memcmp(buf3, buf4, len), "Buffers aren't the same");
        ok(memcmp(buf2, buf3, len), "Buffers aren't the same");
        ok(memcmp(buf5, buf6, len), "Buffers aren't the same");
        ok(memcmp(buf5, buf2, len), "Buffers aren't the same");
        ok(memcmp(buf6, buf1, len), "Buffers aren't the same");
    }
    retval = CCRNGRelease(rngref);
        
    return 0;
}
#endif

Added CCRegression/CommonCrypto/CryptorPadFailure.c.



















>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
//
//  CryptorPadFailure.c
//  CCRegressions
//
//  Created by Richard Murphy on 5/11/11.
//  Copyright 2011 McKenzie-Murphy. All rights reserved.
//

#include <stdio.h>

Added CCRegression/README.































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
regression test suite for security components.
by Michael Brouwer


GOALS
=====

The goals of this test setup are  to have something that required
0 configuration and setup and allows developers to quickly write
new standalone test cases.


USAGE
=====

The tests are runnable from the top level Makefile by typing:
    make test
or individually from the command line or with gdb.  Tests will be
built into a directory called build by default or into LOCAL_BUILD_DIR
if you set that in your environment.


DIRECTORY LAYOUT
================

Currently there are subdirectories for a number of different parts
of the security stack.  Each directory contains some of the unit
tests I've managed to find from radar and other places.

The test programs output their results in a format called TAP.  This
is described here:
    http://search.cpan.org/~petdance/Test-Harness-2.46/lib/Test/Harness/TAP.pod
Because of this we can use Perl's Test::Harness to run the tests
and produce some nice looking output without the need to write an
entire test harness.

Tests can be written in C, C++ or Objective-C or perl (using
Test::More in perl).


WRITING TESTS
=============

To add a new test simply copy one of the existing ones and hack away.
Any file with a main() function in it will be built into a test
automatically by the top level Makefile (no configuration required).

To use the testmore C "library" all you need to do is #include
"testmore.h" in your test program.

Then in your main function you must call:

plan_tests(NUMTESTS) where NUMTESTS is the number of test cases you
test program will run.  After that you can start writing tests.
There are a couple of macros to help you get started:

The following are ways to run an actual test case (as in they count
towards the NUMTESTS number above):

ok(EXPR, NAME)
    Evaluate EXPR if it's true the test passes if false it fails.
    The second argument is a descriptive name of the test for debugging
    purposes.

is(EXPR, VALUE, NAME)
    Evaluate EXPR if it's equal to VALUE the test passes otherwise
    it fails.  This is equivalent to ok(EXPR == VALUE, NAME) except
    this produces nicer output in a failure case.
    CAVEAT: Currently EXPR and VALUE must both be type int.

isnt(EXPR, VALUE, NAME)
    Opposite of is() above.
    CAVEAT: Currently EXPR and VALUE must both be type int.

cmp_ok(EXPR, OP, VALUE, NAME)
    Succeeds if EXPR OP VALUE is true.  Produces a diagnostic if not.
    CAVEAT: Currently EXPR and VALUE must both be type int.

ok_status(EXPR, NAME)
    Evaluate EXPR, if it's 0 the test passes otherwise print a
    diagnostic with the name and number of the error returned.

is_status(EXPR, VALUE, NAME)
    Evaluate EXPR, if the error returned equals VALUE the test
    passes, otherwise print a diagnostic with the expected and
    actual error returned.

ok_unix(EXPR, NAME)
    Evaluate EXPR, if it's >= 0 the test passes otherwise print a
    diagnostic with the name and number of the errno.

is_unix(EXPR, VALUE, NAME)
    Evaluate EXPR, if the errno set by it equals VALUE the test
    passes, otherwise print a diagnostic with the expected and
    actual errno.

Finally if you somehow can't express the success or failure of a
test using the macros above you can use pass(NAME) or fail(NAME)
explicitly.  These are equivalent to ok(1, NAME) and ok(0, NAME)
respectively.


LEAKS
=====

If you want to check for leaks in your test you can #include
"testleaks.h" in your program and call:

ok_leaks(NAME)
    Passes if there are no leaks in your program.

is_leaks(VALUE, NAME)
    Passes if there are exactly VALUE leaks in your program.  Useful
    if you are calling code that is known to leak and you can't fix
    it.  But you still want to make sure there are no new leaks in
    your code.


C++
===

For C++ programs you can #include "testcpp.h" which defines these
additional macros:
no_throw(EXPR, NAME)
    Success if EXPR doesn't throw.

does_throw(EXPR, NAME)
    Success if EXPR does throw.

is_throw(EXPR, CLASS, FUNC, VALUE, NAME)
    Success if EXPR throws an exception of type CLASS and CLASS.FUNC == VALUE.
    Example usage:
    is_throw(CssmError::throwMe(42), CssmError, osStatus(), 42, "throwMe(42)");


TODO and SKIP
=============

Sometimes you write a test case that is known to fail (because you
found a bug).  Rather than commenting out that test case you should
put it inside a TODO block.  This will cause the test to run but
the failure will not be reported as an error.  When the test starts
passing (presumably because someone fixed the bug) you can comment
out the TODO block and leave the test in place.

The syntax for doing this looks like so:

    TODO: {
        todo("<rdar://problem/4000000> ER: AAPL target: $4,000,000/share");

        cmp_ok(apple_stock_price(), >=, 4000000, "stock over 4M");
    }

Sometimes you don't want to run a particular test case or set of
test cases because something in the environment is missing or you
are running on a different version of the OS than the test was
designed for.  To achieve this you can use a SKIP block.

The syntax for a SKIP block looks like so:

    SKIP: {
        skip("only runs on Tiger and later", 4, os_version() >= os_tiger);

        ok(tiger_test1(), "test1");
        ok(tiger_test2(), "test2");
        ok(tiger_test3(), "test3");
        ok(tiger_test4(), "test4");
    }

How it works is like so:  If the third argument to skip evaluates
to false it breaks out of the SKIP block and reports N tests as
being skipped (where N is the second argument to skip)  The reason
for the test being skipped is given as the first argument to skip.


Utility Functions
=================

Anyone writing tests can add new utility functions.  Currently there
is a pair called tests_begin and tests_end.  To get them
#include "testenv.h". Calling them doesn't count as running a test
case, unless you wrap them in an ok() macro.  tests_begin creates
a unique dir in /tmp and sets HOME in the environment to that dir.
tests_end cleans up the mess that tests_begin made.

When writing your own utility functions you will probably want to use
the setup("task") macro so that any uses of ok() and other macros
don't count as actual test cases run, but do report errors when they
fail.   Here is an example of how tests_end() does this:

int
tests_end(int result)
{
        setup("tests_end");
        /* Restore previous cwd and remove scratch dir. */
        return (ok_unix(fchdir(current_dir), "fchdir") &&
                ok_unix(close(current_dir), "close") &&
                ok_unix(rmdir_recursive(scratch_dir), "rmdir_recursive"));
}

Setup cases all tests unil the end of the current funtion to not count
against your test cases test count and they output nothing if they
succeed.

There is also a simple utility header called "testcssm.h" which
currently defines cssm_attach and cssm_detach functions for loading
and initializing cssm and loading a module.

Added CCRegression/inc/IPC/Run3.pm.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
package IPC::Run3;

$VERSION = 0.010;

=head1 NAME

IPC::Run3 - Run a subprocess in batch mode (a la system) on Unix, Win32, etc.

=head1 SYNOPSIS

    use IPC::Run3;    ## Exports run3() by default
    use IPC::Run3 (); ## Don't pollute

    run3 \@cmd, \$in, \$out, \$err;
    run3 \@cmd, \@in, \&out, \$err;

=head1 DESCRIPTION

This module allows you to run a subprocess and redirect stdin, stdout,
and/or stderr to files and perl data structures.  It aims to satisfy 99%
of the need for using system()/qx``/open3() with a simple, extremely
Perlish API and none of the bloat and rarely used features of IPC::Run.

Speed (of Perl code; which is often much slower than the kind of
buffered I/O that this module uses to spool input to and output from the
child command), simplicity, and portability are paramount.  Disk space
is not.

Note that passing in \undef explicitly redirects the associated file
descriptor for STDIN, STDOUT, or STDERR from or to the local equivalent
of /dev/null (this does I<not> pass a closed filehandle).  Passing in
"undef" (or not passing a redirection) allows the child to inherit the
corresponding STDIN, STDOUT, or STDERR from the parent.

Because the redirects come last, this allows STDOUT and STDERR to
default to the parent's by just not specifying them; a common use
case.

B<Note>: This means that:

    run3 \@cmd, undef, \$out;   ## Pass on parent's STDIN

B<does not close the child's STDIN>, it passes on the parent's.  Use

    run3 \@cmd, \undef, \$out;  ## Close child's STDIN

for that.  It's not ideal, but it does work.

If the exact same value is passed for $stdout and $stderr, then
the child will write both to the same filehandle.  In general, this
means that

    run3 \@cmd, \undef, "foo.txt", "foo.txt";
    run3 \@cmd, \undef, \$both, \$both;

will DWYM and pass a single file handle to the child for both
STDOUT and STDERR, collecting all into $both.

=head1 DEBUGGING

To enable debugging use the IPCRUN3DEBUG environment variable to
a non-zero integer value:

    $ IPCRUN3DEBUG=1 myapp

.

=head1 PROFILING

To enable profiling, set IPCRUN3PROFILE to a number to enable
emitting profile information to STDERR (1 to get timestamps,
2 to get a summary report at the END of the program,
3 to get mini reports after each run) or to a filename to
emit raw data to a file for later analysis.

=head1 COMPARISON

Here's how it stacks up to existing APIs:

=over

=item compared to system(), qx'', open "...|", open "|...":

=over

=item + redirects more than one file descriptor

=item + returns TRUE on success, FALSE on failure

=item + throws an error if problems occur in the parent process (or the
pre-exec child)

=item + allows a very perlish interface to perl data structures and
subroutines

=item + allows 1 word invocations to avoid the shell easily:

    run3 ["foo"];  ## does not invoke shell

=item - does not return the exit code, leaves it in $?

=back

=item compared to open2(), open3():

=over

=item + No lengthy, error prone polling / select loop needed

=item + Hides OS dependancies

=item + Allows SCALAR, ARRAY, and CODE references to source and sink I/O

=item + I/O parameter order is like open3()  (not like open2()).

=item - Does not allow interaction with the subprocess

=back

=item compared to IPC::Run::run():

=over

=item + Smaller, lower overhead, simpler, more portable

=item + No select() loop portability issues

=item + Does not fall prey to Perl closure leaks

=item - Does not allow interaction with the subprocess (which
IPC::Run::run() allows by redirecting subroutines).

=item - Lacks many features of IPC::Run::run() (filters, pipes,
redirects, pty support).

=back

=back

=cut

@EXPORT = qw( run3 );
%EXPORT_TAGS = ( all => \@EXPORT );
@ISA = qw( Exporter );
use Exporter;

use strict;
use constant debugging => $ENV{IPCRUN3DEBUG} || $ENV{IPCRUNDEBUG} || 0;
use constant profiling => $ENV{IPCRUN3PROFILE} || $ENV{IPCRUNPROFILE} || 0;
use constant is_win32  => 0 <= index $^O, "Win32";

BEGIN {
   if ( is_win32 ) {
      eval "use Win32 qw( GetOSName ); 1" or die $@;
   }
}

#use constant is_win2k => is_win32 && GetOSName() =~ /Win2000/i;
#use constant is_winXP => is_win32 && GetOSName() =~ /WinXP/i;

use Carp qw( croak );
use File::Temp qw( tempfile );
use UNIVERSAL qw( isa );
use POSIX qw( dup dup2 );

## We cache the handles of our temp files in order to
## keep from having to incur the (largish) overhead of File::Temp
my %fh_cache;

my $profiler;

sub _profiler { $profiler } ## test suite access

BEGIN {
    if ( profiling ) {
        eval "use Time::HiRes qw( gettimeofday ); 1" or die $@;
        if ( $ENV{IPCRUN3PROFILE} =~ /\A\d+\z/ ) {
            require IPC::Run3::ProfPP;
            $profiler = IPC::Run3::ProfPP->new(
                Level => $ENV{IPCRUN3PROFILE},
            );
        }
        else {
            my ( $dest, undef, $class ) =
               reverse split /(=)/, $ENV{IPCRUN3PROFILE}, 2;
            $class = "IPC::Run3::ProfLogger"
                unless defined $class && length $class;
            unless ( eval "require $class" ) {
                my $x = $@;
                $class = "IPC::Run3::$class";
                eval "require IPC::Run3::$class" or die $x;
            }
            $profiler = $class->new(
                Destination => $dest,
            );
        }
        $profiler->app_call( [ $0, @ARGV ], scalar gettimeofday() );
    }
}


END {
    $profiler->app_exit( scalar gettimeofday() ) if profiling;
}


sub _spool_data_to_child {
    my ( $type, $source, $binmode_it ) = @_;

    ## If undef (not \undef) passed, they want the child to inherit
    ## the parent's STDIN.
    return undef unless defined $source;
    warn "binmode()ing STDIN\n" if is_win32 && debugging && $binmode_it;

    my $fh;
    if ( ! $type ) {
        local *FH;  ## Do this the backcompat way
        open FH, "<$source" or croak "$!: $source";
        $fh = *FH{IO};
        if ( is_win32 ) {
            binmode ":raw"; ## Remove all layers
            binmode ":crlf" unless $binmode_it;
        }
        warn "run3(): feeding file '$source' to child STDIN\n"
            if debugging >= 2;
    }
    elsif ( $type eq "FH" ) {
        $fh = $source;
        warn "run3(): feeding filehandle '$source' to child STDIN\n"
            if debugging >= 2;
    }
    else {
        $fh = $fh_cache{in} ||= tempfile;
        truncate $fh, 0;
        seek $fh, 0, 0;
        if ( is_win32 ) {
            binmode $fh, ":raw"; ## Remove any previous layers
            binmode $fh, ":crlf" unless $binmode_it;
        }
        my $seekit;
        if ( $type eq "SCALAR" ) {

            ## When the run3()'s caller asks to feed an empty file
            ## to the child's stdin, we want to pass a live file
            ## descriptor to an empty file (like /dev/null) so that
            ## they don't get surprised by invalid fd errors and get
            ## normal EOF behaviors.
            return $fh unless defined $$source;  ## \undef passed

            warn "run3(): feeding SCALAR to child STDIN",
                debugging >= 3
                   ? ( ": '", $$source, "' (", length $$source, " chars)" )
                   : (),
                "\n"
                if debugging >= 2;

            $seekit = length $$source;
            print $fh $$source or die "$! writing to temp file";

        }
        elsif ( $type eq "ARRAY" ) {
            warn "run3(): feeding ARRAY to child STDIN",
                debugging >= 3 ? ( ": '", @$source, "'" ) : (),
                "\n"
            if debugging >= 2;

            print $fh @$source or die "$! writing to temp file";
            $seekit = grep length, @$source;
        }
        elsif ( $type eq "CODE" ) {
            warn "run3(): feeding output of CODE ref '$source' to child STDIN\n"
                if debugging >= 2;
            my $parms = [];  ## TODO: get these from $options
            while (1) {
                my $data = $source->( @$parms );
                last unless defined $data;
                print $fh $data or die "$! writing to temp file";
                $seekit = length $data;
            }
        }

        seek $fh, 0, 0 or croak "$! seeking on temp file for child's stdin"
            if $seekit;
    }

    croak "run3() can't redirect $type to child stdin"
        unless defined $fh;

    return $fh;
}


sub _fh_for_child_output {
    my ( $what, $type, $dest, $binmode_it ) = @_;

    my $fh;
    if ( $type eq "SCALAR" && $dest == \undef ) {
        warn "run3(): redirecting child $what to oblivion\n"
            if debugging >= 2;

        $fh = $fh_cache{nul} ||= do {
            local *FH;
            open FH, ">" . File::Spec->devnull;
            *FH{IO};
        };
    }
    elsif ( !$type ) {
        warn "run3(): feeding child $what to file '$dest'\n"
            if debugging >= 2;

        local *FH;
        open FH, ">$dest" or croak "$!: $dest";
        $fh = *FH{IO};
    }
    else {
        warn "run3(): capturing child $what\n"
            if debugging >= 2;

        $fh = $fh_cache{$what} ||= tempfile;
        seek $fh, 0, 0;
        truncate $fh, 0;
    }

    if ( is_win32 ) {
        warn "binmode()ing $what\n" if debugging && $binmode_it;
        binmode $fh, ":raw";
        binmode $fh, ":crlf" unless $binmode_it;
    }
    return $fh;
}


sub _read_child_output_fh {
    my ( $what, $type, $dest, $fh, $options ) = @_;

    return if $type eq "SCALAR" && $dest == \undef;

    seek $fh, 0, 0 or croak "$! seeking on temp file for child $what";

    if ( $type eq "SCALAR" ) {
        warn "run3(): reading child $what to SCALAR\n"
            if debugging >= 3;

        ## two read()s are used instead of 1 so that the first will be
        ## logged even it reads 0 bytes; the second won't.
        my $count = read $fh, $$dest, 10_000;
        while (1) {
            croak "$! reading child $what from temp file"
                unless defined $count;

            last unless $count;

            warn "run3(): read $count bytes from child $what",
                debugging >= 3 ? ( ": '", substr( $$dest, -$count ), "'" ) : (),
                "\n"
                if debugging >= 2;

            $count = read $fh, $$dest, 10_000, length $$dest;
        }
    }
    elsif ( $type eq "ARRAY" ) {
        @$dest = <$fh>;
        if ( debugging >= 2 ) {
            my $count = 0;
            $count += length for @$dest;
            warn
                "run3(): read ",
                scalar @$dest,
                " records, $count bytes from child $what",
                debugging >= 3 ? ( ": '", @$dest, "'" ) : (),
                "\n";
        }
    }
    elsif ( $type eq "CODE" ) {
        warn "run3(): capturing child $what to CODE ref\n"
            if debugging >= 3;

        local $_;
        while ( <$fh> ) {
            warn
                "run3(): read ",
                length,
                " bytes from child $what",
                debugging >= 3 ? ( ": '", $_, "'" ) : (),
                "\n"
                if debugging >= 2;

            $dest->( $_ );
        }
    }
    else {
        croak "run3() can't redirect child $what to a $type";
    }

#    close $fh;
}


sub _type {
    my ( $redir ) = @_;
    return "FH" if isa $redir, "IO::Handle";
    my $type = ref $redir;
    return $type eq "GLOB" ? "FH" : $type;
}


sub _max_fd {
    my $fd = dup(0);
    POSIX::close $fd;
    return $fd;
}

my $run_call_time;
my $sys_call_time;
my $sys_exit_time;

sub run3 {
    $run_call_time = gettimeofday() if profiling;

    my $options = @_ && ref $_[-1] eq "HASH" ? pop : {};

    my ( $cmd, $stdin, $stdout, $stderr ) = @_;

    print STDERR "run3(): running ", 
       join( " ", map "'$_'", ref $cmd ? @$cmd : $cmd ), 
       "\n"
       if debugging;

    if ( ref $cmd ) {
        croak "run3(): empty command"     unless @$cmd;
        croak "run3(): undefined command" unless defined $cmd->[0];
        croak "run3(): command name ('')" unless length  $cmd->[0];
    }
    else {
        croak "run3(): missing command" unless @_;
        croak "run3(): undefined command" unless defined $cmd;
        croak "run3(): command ('')" unless length  $cmd;
    }

    my $in_type  = _type $stdin;
    my $out_type = _type $stdout;
    my $err_type = _type $stderr;

    ## This routine procedes in stages so that a failure in an early
    ## stage prevents later stages from running, and thus from needing
    ## cleanup.

    my $in_fh  = _spool_data_to_child $in_type, $stdin,
        $options->{binmode_stdin} if defined $stdin;

    my $out_fh = _fh_for_child_output "stdout", $out_type, $stdout,
        $options->{binmode_stdout} if defined $stdout;

    my $tie_err_to_out =
        defined $stderr && defined $stdout && $stderr eq $stdout;

    my $err_fh = $tie_err_to_out
        ? $out_fh
        : _fh_for_child_output "stderr", $err_type, $stderr,
            $options->{binmode_stderr} if defined $stderr;

    ## this should make perl close these on exceptions
    local *STDIN_SAVE;
    local *STDOUT_SAVE;
    local *STDERR_SAVE;

    my $saved_fd0 = dup( 0 ) if defined $in_fh;

#    open STDIN_SAVE,  "<&STDIN"#  or croak "run3(): $! saving STDIN"
#        if defined $in_fh;
    open STDOUT_SAVE, ">&STDOUT" or croak "run3(): $! saving STDOUT"
        if defined $out_fh;
    open STDERR_SAVE, ">&STDERR" or croak "run3(): $! saving STDERR"
        if defined $err_fh;

    my $ok = eval {
        ## The open() call here seems to not force fd 0 in some cases;
        ## I ran in to trouble when using this in VCP, not sure why.
        ## the dup2() seems to work.
        dup2( fileno $in_fh, 0 )
#        open STDIN,  "<&=" . fileno $in_fh
            or croak "run3(): $! redirecting STDIN"
            if defined $in_fh;

#        close $in_fh or croak "$! closing STDIN temp file"
#            if ref $stdin;

        open STDOUT, ">&" . fileno $out_fh
            or croak "run3(): $! redirecting STDOUT"
            if defined $out_fh;

        open STDERR, ">&" . fileno $err_fh
            or croak "run3(): $! redirecting STDERR"
            if defined $err_fh;

        $sys_call_time = gettimeofday() if profiling;

        my $r = ref $cmd
           ? system {$cmd->[0]}
                   is_win32
                       ? map {
                           ## Probably need to offer a win32 escaping
                           ## option, every command may be different.
                           ( my $s = $_ ) =~ s/"/"""/g;
                           $s = qq{"$s"};
                           $s;
                       } @$cmd
                       : @$cmd
           : system $cmd;

        $sys_exit_time = gettimeofday() if profiling;

        unless ( defined $r ) {
            if ( debugging ) {
                my $err_fh = defined $err_fh ? \*STDERR_SAVE : \*STDERR;
                print $err_fh "run3(): system() error $!\n"
            }
            die $!;
        }

        if ( debugging ) {
            my $err_fh = defined $err_fh ? \*STDERR_SAVE : \*STDERR;
            print $err_fh "run3(): \$? is $?\n"
        }
        1;
    };
    my $x = $@;

    my @errs;

    if ( defined $saved_fd0 ) {
        dup2( $saved_fd0, 0 );
        POSIX::close( $saved_fd0 );
    }

#    open STDIN,  "<&STDIN_SAVE"#  or push @errs, "run3(): $! restoring STDIN"
#        if defined $in_fh;
    open STDOUT, ">&STDOUT_SAVE" or push @errs, "run3(): $! restoring STDOUT"
        if defined $out_fh;
    open STDERR, ">&STDERR_SAVE" or push @errs, "run3(): $! restoring STDERR"
        if defined $err_fh;

    croak join ", ", @errs if @errs;

    die $x unless $ok;

    _read_child_output_fh "stdout", $out_type, $stdout, $out_fh, $options
        if defined $out_fh && $out_type && $out_type ne "FH";
    _read_child_output_fh "stderr", $err_type, $stderr, $err_fh, $options
        if defined $err_fh && $err_type && $err_type ne "FH" && !$tie_err_to_out;
    $profiler->run_exit(
       $cmd,
       $run_call_time,
       $sys_call_time,
       $sys_exit_time,
       scalar gettimeofday 
    ) if profiling;

    return 1;
}

my $in_fh;
my $in_fd;
my $out_fh;
my $out_fd;
my $err_fh;
my $err_fd;
        $in_fh = tempfile;
        $in_fd = fileno $in_fh;
        $out_fh = tempfile;
        $out_fd = fileno $out_fh;
        $err_fh = tempfile;
        $err_fd = fileno $err_fh;
    my $saved_fd0 = dup 0;
    my $saved_fd1 = dup 1;
    my $saved_fd2 = dup 2;
    my $r;
    my ( $cmd, $stdin, $stdout, $stderr );

sub _run3 {
    ( $cmd, $stdin, $stdout, $stderr ) = @_;

    truncate $in_fh, 0;
    seek $in_fh, 0, 0;

    print $in_fh $$stdin or die "$! writing to temp file";
    seek $in_fh, 0, 0;

    seek $out_fh, 0, 0;
    truncate $out_fh, 0;

    seek $err_fh, 0, 0;
    truncate $err_fh, 0;

    dup2 $in_fd,  0 or croak "run3(): $! redirecting STDIN";
    dup2 $out_fd, 1 or croak "run3(): $! redirecting STDOUT";
    dup2 $err_fd, 2 or croak "run3(): $! redirecting STDERR";

    $r = 
       system {$cmd->[0]}
               is_win32
                   ? map {
                       ## Probably need to offer a win32 escaping
                       ## option, every command is different.
                       ( my $s = $_ ) =~ s/"/"""/g;
                       $s = q{"$s"} if /[^\w.:\/\\'-]/;
                       $s;
                   } @$cmd
                   : @$cmd;

    die $! unless defined $r;

    dup2 $saved_fd0, 0;
    dup2 $saved_fd1, 1;
    dup2 $saved_fd2, 2;

    seek $out_fh, 0, 0 or croak "$! seeking on temp file for child output";

        my $count = read $out_fh, $$stdout, 10_000;
        while ( $count == 10_000 ) {
            $count = read $out_fh, $$stdout, 10_000, length $$stdout;
        }
        croak "$! reading child output from temp file"
            unless defined $count;

    seek $err_fh, 0, 0 or croak "$! seeking on temp file for child errput";

        $count = read $err_fh, $$stderr, 10_000;
        while ( $count == 10_000 ) {
            $count = read $err_fh, $$stderr, 10_000, length $$stdout;
        }
        croak "$! reading child stderr from temp file"
            unless defined $count;

    return 1;
}

=cut


=head1 TODO

pty support

=head1 LIMITATIONS

Often uses intermediate files (determined by File::Temp, and thus by the
File::Spec defaults and the TMPDIR env. variable) for speed, portability and
simplicity.

=head1 COPYRIGHT

    Copyright 2003, R. Barrie Slaymaker, Jr., All Rights Reserved

=head1 LICENSE

You may use this module under the terms of the BSD, Artistic, or GPL licenses,
any version.

=head1 AUTHOR

Barrie Slaymaker <barries@slaysys.com>

=cut

1;

Added CCRegression/inc/MyHarness.pm.



























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use warnings;
use strict;

package MyStraps;
use base qw( Test::Harness::Straps );
 
sub _command_line {
    my $self = shift;
    my $file = shift;

    $file = qq["$file"] if ($file =~ /\s/) && ($file !~ /^".*"$/);
    my $line = "$file";

    return $line;
}

sub _default_inc {
    return @INC;
}
 
package MyHarness;
use base qw( Test::Harness );

#my $Strap = MyStraps->new();
$Test::Harness::Strap = MyStraps->new();
 
sub strap { return $Test::Harness::Strap }
 
1;

Added CCRegression/main.c.























>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>


#include "testenv.h"

int main (int argc, char * const *argv) {

    printf("WARNING: If running those tests on a device with a passcode, DONT FORGET TO UNLOCK!!!\n");
    tests_begin(argc, argv);
    return 0;
}

Added CCRegression/runscript/security.pl.









































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/perl -w
#
#  Copyright (c) 2006-2007 Apple Inc. All Rights Reserved.
#

my $pid = $$;

END {
    return unless $$ == $pid;
    rm_test($_) for @TOCLEAN;
}

use strict;
use Test::More;
use IPC::Run3;

sub plan_security {
    
    unless (1) {
	plan skip_all => "security not installed";
	exit;
    };
    plan @_;
}

use Carp;
our @TOCLEAN;
END {
    return unless $$ == $pid;
    $SIG{__WARN__} = sub { 1 };
    cleanup_test($_) for @TOCLEAN;
}

our $output = '';

sub build_test {
    my $xd = "/tmp/test-$pid";
    my $security = 'security';
    $ENV{HOME} = $xd;
    push @TOCLEAN, [$xd, $security];
    return ($xd, $security);
}

sub rm_test {
    my ($xd, $security) = @{+shift};
    #rmtree [$xd];
}

sub cleanup_test {
    return unless $ENV{TEST_VERBOSE};
    my ($xd, $security) = @{+shift};
}

sub is_output {
    my ($security, $cmd, $arg, $expected, $test) = @_;
    $output = '';
    run3([$security, $cmd, @$arg], \undef, \$output, \$output);
#    open(STDOUT, ">&STDERR") || die "couldn't dup strerr: $!";
#    open(my $out, '-|', $security, $cmd, @$arg);
#    while (<$out>) { $output .= $_; }

    my $cmp = (grep {ref ($_) eq 'Regexp'} @$expected)
	? \&is_deeply_like : \&is_deeply;
    @_ = ([sort split (/\r?\n/, $output)], [sort @$expected], $test || join(' ', $cmd, @$arg));
    goto &$cmp;
}

1;

Added CCRegression/test/00testtest.c.



































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
 * Copyright (c) 2006-2007 Apple Inc. All Rights Reserved.
 */

#include <stdlib.h>

#include "testmore.h"

int main(int argc, char *const *argv)
{
    int rv = 1;
    plan_tests(6);

    TODO: {
	todo("ok 0 is supposed to fail");

	rv = ok(0, "ok bad");
	if (!rv)
	    diag("ok bad not good today");
    }
    rv &= ok(1, "ok ok");
#if 0
    SKIP: {
	skip("is bad will fail", 1, 0);

	if (!is(0, 4, "is bad"))
	    diag("is bad not good today");
    }
    SKIP: {
	skip("is ok should not be skipped", 1, 1);

        is(3, 3, "is ok");
    }
#endif
    isnt(0, 4, "isnt ok");
    TODO: {
	todo("isnt bad is supposed to fail");

	isnt(3, 3, "isnt bad");
    }
    TODO: {
	todo("cmp_ok bad is supposed to fail");

	cmp_ok(3, &&, 0, "cmp_ok bad");
    }
    cmp_ok(3, &&, 3, "cmp_ok ok");

    return 0;
}

Added CCRegression/test/run_tests.sh.







































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/bin/sh

# run_tests.sh
# Security
#
# Created by Fabrice Gautier on 8/26/10.
# Modified for use with CommonCrypto on 3/10/11
# Copyright 2011 Apple, Inc. All rights reserved.


# Run a command line tool on the sim or the device

CMD=CCRegressions

if [ "${PLATFORM_NAME}" == "iphoneos" ]; then
    INSTALL_DIR=
    SCP_URL=phone:${INSTALL_DIR}
#copy libcommonCrypto.dylib and CCRegressions program to the device, to /tmp
#this will not replace the system CommonCrypto.
#it is assumed that ssh is pre-setup on the device with pubkey authentication
    export RSYNC_PASSWORD=alpine
    echo "run_tests.sh:${LINENO}: note: Copying stuff to device"
    # scp ${CONFIGURATION_BUILD_DIR}/libcommonCrypto.dylib ${SCP_URL}
    scp ${CONFIGURATION_BUILD_DIR}/CCRegressions ${SCP_URL}
    echo "run_tests.sh:${LINENO}: note: Running the test"
    xcrun -sdk "$SDKROOT" PurpleExec --env "DYLD_FRAMEWORK_PATH=${INSTALL_DIR}" --cmd ${INSTALL_DIR}/${CMD}
else
    echo "run_tests.sh:${LINENO}: note: Running test on simulator (${BUILT_PRODUCTS_DIR}/${CMD})"
	export DYLD_ROOT_PATH="${SDKROOT}"
    export DYLD_LIBRARY_PATH="${BUILT_PRODUCTS_DIR}"
    export DYLD_FRAMEWORK_PATH="${BUILT_PRODUCTS_DIR}"
    ${BUILT_PRODUCTS_DIR}/${CMD}
fi


Added CCRegression/test/testcpp.h.







































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
 * Copyright (c) 2005-2007 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 *
 * testcpp.h
 */

#ifndef _TESTCPP_H_
#define _TESTCPP_H_  1

#include "testmore.h"

#ifdef __cplusplus

#define no_throw(THIS, TESTNAME) \
({ \
    bool _this; \
    try { THIS; _this = true; } catch (...) { _this = false; } \
    test_ok(_this, TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
		"#          got: <unknown excepetion>\n" \
		"#     expected: <no throw>\n"); \
})
#define does_throw(THIS, TESTNAME) \
({ \
    bool _this; \
    try { THIS; _this = false; } catch (...) { _this = true; } \
    test_ok(_this, TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
		"#          got: <no throw>\n" \
		"#     expected: <any excepetion>\n"); \
})
#define is_throw(THIS, CLASS, METHOD, VALUE, TESTNAME) \
({ \
    bool _this; \
    try \
	{ \
		THIS; \
		_this = test_ok(false, TESTNAME, test_directive, test_reason, \
			__FILE__, __LINE__, \
			"#          got: <no throw>\n" \
			"#     expected: %s.%s == %s\n", \
			#CLASS, #METHOD, #VALUE); \
	} \
    catch (const CLASS &_exception) \
    { \
		_this = test_ok(_exception.METHOD == (VALUE), TESTNAME, \
			test_directive, test_reason, __FILE__, __LINE__, \
			"#          got: %d\n" \
			"#     expected: %s.%s == %s\n", \
			_exception.METHOD, #CLASS, #METHOD, #VALUE); \
	} \
    catch (...) \
    { \
    	_this = test_ok(false, TESTNAME, test_directive, test_reason, \
			__FILE__, __LINE__, \
			"#          got: <unknown excepetion>\n" \
			"#     expected: %s.%s == %s\n", \
			#CLASS, #METHOD, #VALUE); \
	} \
	_this; \
})
#endif /* __cplusplus */

#endif /* !_TESTCPP_H_ */

Added CCRegression/test/testenv.c.



























































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*
 * Copyright (c) 2005-2007,2009-2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 *
 * testenv.c
 */

#include <fcntl.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdbool.h>

#include "testmore.h"
#include "testenv.h"

#if NO_SERVER
#include <securityd/spi.h>

static int current_dir = -1;
static char scratch_dir[50];
static char *home_var;
static bool keep_scratch_dir = false;

static int
rmdir_recursive(const char *path)
{
	char command_buf[256];
	if (strlen(path) + 10 > sizeof(command_buf) || strchr(path, '\''))
	{
		fprintf(stderr, "# rmdir_recursive: invalid path: %s", path);
		return -1;
	}

	sprintf(command_buf, "rm -rf '%s'", path);
	return system(command_buf);
}
#endif

static int tests_init(void) {
    printf("[TEST] CommonCrypto\n");
#if NO_SERVER
	char preferences_dir[80];
	char library_dir[70];

    securityd_init();

	setup("tests_init");
    
    /* Create scratch dir for tests to run in. */
    sprintf(scratch_dir, "/tmp/tst-%d", getpid());
    if (keep_scratch_dir) {
        printf("running tests with HOME=%s\n", scratch_dir);
    }
    sprintf(library_dir, "%s/Library", scratch_dir);
    sprintf(preferences_dir, "%s/Preferences", library_dir);
    return (ok_unix(mkdir(scratch_dir, 0755), "mkdir") &&
            ok_unix(current_dir = open(".", O_RDONLY), "open") &&
            ok_unix(chdir(scratch_dir), "chdir") &&
            ok_unix(setenv("HOME", scratch_dir, 1), "setenv") &&
            /* @@@ Work around a bug that the prefs code in
             libsecurity_keychain never creates the Library/Preferences
             dir. */
            ok_unix(mkdir(library_dir, 0755), "mkdir") &&
            ok_unix(mkdir(preferences_dir, 0755), "mkdir") &&
            ok(home_var = getenv("HOME"), "getenv"));
    
#else
    return 0;
#endif 
}

static int
tests_end(void)
{
    printf("[SUMMARY]\n"); 
#if NO_SERVER
	setup("tests_end");
	/* Restore previous cwd and remove scratch dir. */
	int ok = ok_unix(fchdir(current_dir), "fchdir");
	if (ok)
		ok = ok_unix(close(current_dir), "close");
	if (ok) {
		if (!keep_scratch_dir) {
			ok = ok_unix(rmdir_recursive(scratch_dir), "rmdir_recursive");
		}
	}
    
	return ok;
#else
    return 0;
#endif
}

static void usage(const char *progname)
{
    fprintf(stderr, "usage: %s [-k][-w][testname [testargs] ...]\n", progname);
    exit(1);
}

static int tests_run_index(int i, int argc, char * const *argv)
{
    int verbose = 0;
    int ch;

    while ((ch = getopt(argc, argv, "v")) != -1)
    {
        switch  (ch)
        {
            case 'v':
                verbose++;
                break;
            default:
                usage(argv[0]);
        }
    }

    fprintf(stderr, "[BEGIN] %s\n", testlist[i].name);
    
    run_one_test(&testlist[i], argc, argv);
    if(testlist[i].failed_tests) {
        fprintf(stderr, "[FAIL] %s\n", testlist[i].name);
    } else {
        fprintf(stderr, "duration: %u ms\n", testlist[i].duration);
        fprintf(stderr, "[PASS] %s\n", testlist[i].name);
    }
    
    return 0;
}

static int tests_named_index(const char *testcase)
{
    int i;

    for (i = 0; testlist[i].name; ++i) {
        if (strcmp(testlist[i].name, testcase) == 0) {
            return i;
        }
    }

    return -1;
}

static int tests_run_all(int argc, char * const *argv)
{
    int curroptind = optind;
    int i;

    for (i = 0; testlist[i].name; ++i) {
        tests_run_index(i, argc, argv);
        optind = curroptind;
    }
    
    return 0;
}

int
tests_begin(int argc, char * const *argv)
{
    const char *testcase = NULL;
    bool initialized = false;
    int testix = -1;
	int ch;

    for (;;) {
        while (!testcase && (ch = getopt(argc, argv, "kw")) != -1)
        {
            switch  (ch)
            {
#ifdef NO_SERVER
            case 'k':
                keep_scratch_dir = true;
                break;
#endif
            case 'w':
                sleep(100);
                break;
            case '?':
            default:
                printf("invalid option %c\n",ch); 
                usage(argv[0]);
            }
        }

        if (optind < argc) {
            testix = tests_named_index(argv[optind]);
            if(testix<0) {
                printf("invalid test %s\n",argv[optind]); 
                usage(argv[0]);
            }
        }

        if (testix < 0) {
            if (!initialized) {
                initialized = true;
                tests_init();
                tests_run_all(argc, argv);
            }
            break;
        } else {
            if (!initialized) {
                tests_init();
                initialized = true;
            }
            optind++;
            tests_run_index(testix, argc, argv);
            testix = -1;
        }
    }
        
    /* Cleanups */
    tests_end();
    
    return 0;
}

Added CCRegression/test/testenv.h.















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
 * Copyright (c) 2005-2007 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 *
 * testenv.h
 */

#ifndef _TESTENV_H_
#define _TESTENV_H_  1

#ifdef __cplusplus
extern "C" {
#endif

int tests_begin(int argc, char * const *argv);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* !_TESTENV_H_ */

Added CCRegression/test/testlist.c.































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* This file contains an array of all test functions, last element is NULL */

#include "testmore.h"
#include "testlist.h"

#define ONE_TEST(x) {#x, x, 0 , 0, 0 },
#define DISABLED_ONE_TEST(x)
struct one_test_s testlist[] = {
#include "testlistInc.h"
    { NULL, NULL, 0, 0, 0}, 
};
#undef ONE_TEST
#undef DISABLED_ONE_TEST


Added CCRegression/test/testlist.h.































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

/* This file contains all the prototypes for all the test functions */
#ifndef __TESTLIST_H__
#define __TESTLIST_H__


#define ONE_TEST(x) int x(int argc, char *const *argv);
#define DISABLED_ONE_TEST(x) ONE_TEST(x)
#include "testlistInc.h"
#undef ONE_TEST
#undef DISABLED_ONE_TEST


#endif /* __TESTLIST_H__ */

Added CCRegression/test/testlistInc.h.



















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* To add a test, just add it here */

ONE_TEST(CommonRandom)
ONE_TEST(CommonEC)
ONE_TEST(CommonRSA)
ONE_TEST(CommonHMacClone)
ONE_TEST(CommonCMac)
ONE_TEST(CommonCryptoSymCBC)
ONE_TEST(CommonCryptoSymOFB)
ONE_TEST(CommonCryptoSymGCM)
ONE_TEST(CommonCryptoSymCTR)
ONE_TEST(CommonCryptoSymXTS)
ONE_TEST(CommonCryptoSymRC2)
ONE_TEST(CommonCryptoSymRegression)
ONE_TEST(CommonCryptoSymOffset)
ONE_TEST(CommonCryptoSymZeroLength)
ONE_TEST(CommonCryptoSymCFB)
ONE_TEST(CommonCryptoCTSPadding)
ONE_TEST(CommonSymmetricWrap)
ONE_TEST(CommonDH)
ONE_TEST(CommonDigest)
ONE_TEST(CommonBaseEncoding)
ONE_TEST(CommonCryptoReset)
ONE_TEST(CommonBigNum)
ONE_TEST(CommonBigDigest)

Added CCRegression/test/testmore.c.



























































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/*
 * Copyright (c) 2005-2007 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 *
 * testmore.c
 */

#include <fcntl.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
// #include <AvailabilityMacros.h>

#include "testmore.h"

static int test_num = 0;
static int test_fails = 0;
static int test_cases = 0;
static const char *test_plan_file;
static int test_plan_line=0;

const char *test_directive = NULL;
const char *test_reason = NULL;

void test_skip(const char *reason, int how_many, int unless)
{
    if (unless)
        return;

    int done;
    for (done = 0; done < how_many; ++done)
        test_ok(1, NULL, "skip", reason, __FILE__, __LINE__, NULL);
}

void test_bail_out(const char *reason, const char *file, unsigned line)
{
    printf("BAIL OUT! (%s at line %u) %s\n", file, line, reason);
    fflush(stdout);
    exit(255);
}

void test_plan_skip_all(const char *reason)
{
    if (test_num > test_cases)
    {
	test_skip(reason, test_cases - test_num, 0);
	exit(test_fails > 255 ? 255 : test_fails);
    }
}

static void test_plan_exit(void)
{
    int status = 0;
    fflush(stdout);

    if (!test_num)
    {
        if (test_cases)
        {
            fprintf(stderr, "%s:%u: warning: No tests run!\n", test_plan_file, test_plan_line);
            status = 255;
        }
        else
        {
            fprintf(stderr, "%s:%u: error: Looks like your test died before it could "
                    "output anything.\n", test_plan_file, test_plan_line);
            status = 255;
        }
    }
    else if (test_num < test_cases)
    {
        fprintf(stderr, "%s:%u: warning: Looks like you planned %d tests but only ran %d.\n",
               test_plan_file, test_plan_line, test_cases, test_num);
        status = test_fails + test_cases - test_num;
    }
    else if (test_num > test_cases)
    {
        fprintf(stderr, "%s:%u: warning: Looks like you planned %d tests but ran %d extra.\n",
               test_plan_file, test_plan_line, test_cases, test_num - test_cases);
        status = test_fails;
    }
    else if (test_fails)
    {
        fprintf(stderr, "%s:%u: error: Looks like you failed %d tests of %d.\n",
               test_plan_file, test_plan_line, test_fails, test_cases);
        status = test_fails;
    }

    fflush(stderr);
    
    /* reset the test plan */
    test_num = 0;
    test_fails = 0;
    test_cases = 0;
}

void test_plan_tests(int count, const char *file, unsigned line)
{
#if 0
    if (atexit(test_plan_exit) < 0)
    {
        fprintf(stderr, "failed to setup atexit handler: %s\n",
                strerror(errno));
        fflush(stderr);
        exit(255);
    }
#endif

	if (test_cases)
    {
        fprintf(stderr,
                "%s:%u: error: You tried to plan twice!\n",
                file, line);
        
        fflush(stderr);
        exit(255);
    }
    else
	{
        if (!count)
        {
            fprintf(stderr, "%s:%u: warning: You said to run 0 tests!  You've got to run "
                    "something.\n", file, line);
            fflush(stderr);
            exit(255);
        }

        test_plan_file=file;
        test_plan_line=line;
        
        test_cases = count;
		fprintf(stderr, "%s:%u: note: 1..%d\n", file, line, test_cases);
		fflush(stdout);
	}
}

int
test_diag(const char *directive, const char *reason,
	const char *file, unsigned line, const char *fmt, ...)
{
	int is_todo = directive && !strcmp(directive, "TODO");
	va_list args;

	va_start(args, fmt);

	if (is_todo)
	{
		fputs("# ", stdout);
		if (fmt)
			vprintf(fmt, args);
		fputs("\n", stdout);
		fflush(stdout);
	}
	else
	{
		fflush(stdout);
		fputs("# ", stderr);
		if (fmt)
			vfprintf(stderr, fmt, args);
		fputs("\n", stderr);
		fflush(stderr);
	}

	va_end(args);

	return 1;
}

int
test_ok(int passed, const char *description, const char *directive,
	const char *reason, const char *file, unsigned line,
	const char *fmt, ...)
{
	int is_todo = !passed && directive && !strcmp(directive, "TODO");
	int is_setup = directive && !is_todo && !strcmp(directive, "SETUP");

	if (is_setup)
	{
		if (!passed)
		{
			fflush(stdout);
			fprintf(stderr, "# SETUP not ok%s%s%s%s\n", 
				   description ? " - " : "",
				   description ? description : "",
				   reason ? " - " : "",
				   reason ? reason : "");
		}
	}
	else
	{
		if (!test_cases)
		{
			atexit(test_plan_exit);
			fprintf(stderr, "You tried to run a test without a plan!  "
					"Gotta have a plan. at %s line %u\n", file, line);
			fflush(stderr);
			exit(255);
		}

		++test_num;
		if (test_num > test_cases || (!passed && !is_todo))
			++test_fails;
/* We dont need to print this unless we want to */
#if 0
		fprintf(stderr, "%s:%u: note: %sok %d%s%s%s%s%s%s\n", file, line, passed ? "" : "not ", test_num,
			   description ? " - " : "",
			   description ? description : "",
			   directive ? " # " : "",
			   directive ? directive : "",
			   reason ? " " : "",
			   reason ? reason : "");
#endif
 }

    if (passed)
		fflush(stdout);
	else
    {
		va_list args;

		va_start(args, fmt);

		if (is_todo)
		{
/* Enable this to output TODO as warning */
#if 0             
			printf("%s:%d: warning: Failed (TODO) test\n", file, line);
			if (fmt)
				vprintf(fmt, args);
#endif
			fflush(stdout);
		}
        else
		{
			fflush(stdout);
			fprintf(stderr, "%s:%d: error: Failed test\n", file, line);
			if (fmt)
				vfprintf(stderr, fmt, args);
			fflush(stderr);
		}

		va_end(args);
    }

    return passed;
}


const char *
sec_errstr(int err)
{
#if 1
	static int bufnum = 0;
    static char buf[2][20];
	bufnum = bufnum ? 0 : 1;
    sprintf(buf[bufnum], "0x%X", err);
    return buf[bufnum];
#else /* !1 */
    if (err >= errSecErrnoBase && err <= errSecErrnoLimit)
        return strerror(err - 100000);

#ifdef MAC_OS_X_VERSION_10_4
    /* AvailabilityMacros.h would only define this if we are on a
       Tiger or later machine. */
    extern const char *cssmErrorString(long);
    return cssmErrorString(err);
#else /* !defined(MAC_OS_X_VERSION_10_4) */
    extern const char *_ZN8Security15cssmErrorStringEl(long);
    return _ZN8Security15cssmErrorStringEl(err);
#endif /* MAC_OS_X_VERSION_10_4 */
#endif /* !1 */
}

/* run one test, described by test, return info in test struct */
int run_one_test(struct one_test_s *test, int argc, char * const *argv)
{
    struct timeval start, stop;
    
    if(test->entry==NULL) {
        printf("%s:%d: error: wtf?\n", __FILE__, __LINE__);
        return -1;
    }
    
    gettimeofday(&start, NULL);
    test->entry(argc, argv);
    gettimeofday(&stop, NULL);
    
    test_plan_exit();
    
    /* this may overflow... */
    test->duration=(unsigned int) (stop.tv_sec-start.tv_sec)*1000+(stop.tv_usec/1000)-(start.tv_usec/1000);
    test->failed_tests=test_fails;
    
    return test_fails;
};

Added CCRegression/test/testmore.h.





































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/*
 * Copyright (c) 2005-2007 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 *
 * testmore.h
 */

#ifndef _TESTMORE_H_
#define _TESTMORE_H_  1

#include <errno.h>
#include <string.h>
#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif

/* This is included here, because its already included by all the test case */
#include "testlist.h"
    
typedef int (*one_test_entry)(int argc, char *const *argv);
    
#define ONE_TEST_ENTRY(x) int x(int argc, char *const *argv)
    
struct one_test_s {
    char *name;            /* test name */
    one_test_entry entry;  /* entry point */
    int sub_tests;         /* number of subtests */
    int failed_tests;      /* number of failed tests*/
    unsigned int duration; /* test duration in msecs */
    /* add more later: timing, etc... */
};

extern struct one_test_s testlist[];
    
int run_one_test(struct one_test_s *test, int argc, char * const *argv);

/* this test harnes rely on shadowing for TODO, SKIP and SETUP blocks */
#pragma GCC diagnostic ignored "-Wshadow"
    
#define ok(THIS, TESTNAME) \
    test_ok(!!(THIS), TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, NULL)
#define is(THIS, THAT, TESTNAME) \
({ \
    __typeof__(THIS) _this = (THIS); \
    __typeof__(THAT) _that = (THAT); \
    test_ok((_this == _that), TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
		"#          got: '%d'\n" \
		"#     expected: '%d'\n", \
		_this, _that); \
})
#define isnt(THIS, THAT, TESTNAME) \
	cmp_ok((THIS), !=, (THAT), (TESTNAME))
#define diag(MSG, ARGS...) \
	test_diag(test_directive, test_reason, __FILE__, __LINE__, MSG, ## ARGS)
#define cmp_ok(THIS, OP, THAT, TESTNAME) \
({ \
	__typeof__(THIS) _this = (THIS); \
	__typeof__(THAT) _that = (THAT); \
	test_ok((_this OP _that), TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
	   "#     '%d'\n" \
	   "#         " #OP "\n" \
	   "#     '%d'\n", \
	   _this, _that); \
})
#define eq_string(THIS, THAT, TESTNAME) \
({ \
	const char *_this = (THIS); \
	const char *_that = (THAT); \
	test_ok(!strcmp(_this, _that), TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
	   "#     '%s'\n" \
	   "#         eq\n" \
	   "#     '%s'\n", \
	   _this, _that); \
})
#define eq_stringn(THIS, THISLEN, THAT, THATLEN, TESTNAME) \
({ \
	__typeof__(THISLEN) _thislen = (THISLEN); \
	__typeof__(THATLEN) _thatlen = (THATLEN); \
	const char *_this = (THIS); \
	const char *_that = (THAT); \
	test_ok(_thislen == _thatlen && !strncmp(_this, _that, _thislen), \
		TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
	   "#     '%.*s'\n" \
	   "#         eq\n" \
	   "#     '%.*s'\n", \
	   (int)_thislen, _this, (int)_thatlen, _that); \
})
#define like(THIS, REGEXP, TESTNAME) like_not_yet_implemented()
#define unlike(THIS, REGEXP, TESTNAME) unlike_not_yet_implemented()
#define is_deeply(STRUCT1, STRUCT2, TESTNAME) is_deeply_not_yet_implemented()
#define TODO switch(0) default
#define SKIP switch(0) default
#define SETUP switch(0) default
#define todo(REASON) const char *test_directive __attribute__((unused)) = "TODO", \
	*test_reason __attribute__((unused)) = (REASON)
#define skip(WHY, HOW_MANY, UNLESS) if (!(UNLESS)) \
    { test_skip((WHY), (HOW_MANY), 0); break; }
#define setup(REASON) const char *test_directive = "SETUP", \
	*test_reason = (REASON)
#define pass(TESTNAME) ok(1, (TESTNAME))
#define fail(TESTNAME) ok(0, (TESTNAME))
#define BAIL_OUT(WHY) test_bail_out(WHY, __FILE__, __LINE__)
#define plan_skip_all(REASON) test_plan_skip_all(REASON)
#define plan_tests(COUNT) test_plan_tests(COUNT, __FILE__, __LINE__)

#define ok_status(THIS, TESTNAME) \
({ \
	OSStatus _this = (THIS); \
	test_ok(!_this, TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
	   "#     status: %s(%ld)\n", \
	   sec_errstr(_this), _this); \
})
#define is_status(THIS, THAT, TESTNAME) \
({ \
    OSStatus _this = (THIS); \
    OSStatus _that = (THAT); \
    test_ok(_this == _that, TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
	   "#          got: %s(%ld)\n" \
	   "#     expected: %s(%ld)\n", \
	   sec_errstr(_this), _this, sec_errstr(_that), _that); \
})
#define ok_unix(THIS, TESTNAME) \
({ \
    int _this = (THIS) < 0 ? errno : 0; \
    test_ok(!_this, TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
	   "#          got: %s(%d)\n", \
	   strerror(_this), _this); \
})
#define is_unix(THIS, THAT, TESTNAME) \
({ \
    int _result = (THIS); \
    int _this = _result < 0 ? errno : 0; \
    int _that = (THAT); \
    _that && _result < 0 \
	? test_ok(_this == _that, TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
		"#          got: %s(%d)\n" \
		"#     expected: %s(%d)\n", \
		strerror(_this), _this, strerror(_that), _that) \
	: test_ok(_this == _that, TESTNAME, test_directive, test_reason, \
		__FILE__, __LINE__, \
		"#            got: %d\n" \
		"# expected errno: %s(%d)\n", \
		_result, strerror(_that), _that); \
})


extern const char *test_directive;
extern const char *test_reason;

void test_bail_out(const char *reason, const char *file, unsigned line);
int test_diag(const char *directive, const char *reason,
	const char *file, unsigned line, const char *fmt, ...);
int test_ok(int passed, const char *description, const char *directive,
	const char *reason, const char *file, unsigned line, const char *fmt, ...);
void test_plan_skip_all(const char *reason);
void test_plan_tests(int count, const char *file, unsigned line);
void test_skip(const char *reason, int how_many, int unless);

const char *sec_errstr(int err);

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* !_TESTMORE_H_ */

Added CCRegression/util/capabilities.h.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//
//  capabilities.h
//  CCRegress
//

#include <Availability.h>

#ifndef __CAPABILITIES_H__
#define __CAPABILITIES_H__

#define entryPoint(testname,supportname) \
int testname(int argc, char *const *argv) { \
char prString[80];\
sprintf(prString, "No %s Support in this release\n", supportname);\
plan_tests(1); \
diag(prString); \
ok(1, prString); \
return 0; \
}


#define _SNOWLEOPARD_ 1060
#define _LION_ 1070
#define _ZIN_ 1080
#define _CAB_ 1090
#define _NMOS_ 1091



#if __MAC_OS_X_VERSION_MAX_ALLOWED < _NMOS_
#define CC_RMD128_DIGEST_LENGTH 16
#define CC_RMD160_DIGEST_LENGTH 20
#define CC_RMD256_DIGEST_LENGTH 32
#define CC_RMD320_DIGEST_LENGTH 40
#endif


#define CRYPTORWITHMODE 1
#define CCDIGEST 1
#define CCRANDOM 1
#define CCKEYDERIVATION 1
#define CCCMAC 1
#define CCRSA 1
#define CCEC 1
#define CCDH 1
#define CCBIGNUM 1
#define CCRESET 1
#define CCSYMREGRESSION 1
#define CCSYMOFFSET 1
#define CCSYMZEROLEN 1
#define CCSYMCBC 1
#define CCSYMOFB 1
#define CCSYMCFB 1
#define CCSYMGCM 1
#define CCSYMXTS 1
#define CCSYMRC2 1
#define CCPADCTS 1
#define CCHMACCLONE 1
#define CCSELFTEST 0
#define CCSYMWRAP 1
#define CNENCODER 0
#define CCBIGDIGEST 0
#define CCSYMCTR 1

#endif /* __CAPABILITIES_H__ */

Added CCRegression/util/testbyteBuffer.c.





































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/*
 *  printByteBuffer.c
 *  byteutils
 *
 *  Created by Richard Murphy on 3/7/10.
 *  Copyright 2010 McKenzie-Murphy. All rights reserved.
 *
 */

#include "testbyteBuffer.h"
#include <CommonCrypto/CommonRandomSPI.h>

void printBytes(uint8_t *buff, size_t len, char *name)
{
	int i;
	printf("Dumping %d bytes from %s\n", (int) len, name);
	for(i=0; i<len; i++) {
		if(i > 0 && !(i%8)) putchar(' ');
		if(i > 0 && !(i%64)) putchar('\n');
		printf("%02x", buff[i]);
	}
	putchar('\n');
}

void printByteBuffer(byteBuffer bb, char *name)
{
    printBytes(bb->bytes, bb->len, name);
}


byteBuffer
mallocByteBuffer(size_t len)
{
	byteBuffer retval;
	if((retval = (byteBuffer) malloc(sizeof(byteBufferStruct) + len + 1)) == NULL) return NULL;
    retval->len = len;
    retval->bytes = (uint8_t *) (retval + 1) ; /* just past the byteBuffer in malloc'ed space */
    return retval;
}

size_t
genRandomSize(size_t minSize, size_t maxSize)
{
    size_t randomInt;
    
    if(minSize == maxSize) return minSize;

    // make theSize > minSize < maxSize;
    while(CCRandomCopyBytes(kCCRandomDefault, &randomInt, sizeof(uint32_t)) == -1) {
        printf("got -1 from CCRandomCopyBytes\n");
    }

    randomInt = (randomInt % (maxSize - minSize)) + minSize;
    return randomInt;
}

byteBuffer
genRandomByteBuffer(size_t minSize, size_t maxSize)
{
	byteBuffer retval;
    size_t randomInt;
    CCCryptorStatus err;
    
    randomInt = genRandomSize(minSize, maxSize);
        
    retval = mallocByteBuffer(randomInt);
    if(retval == NULL) return NULL;
    
    if(retval->len != randomInt) return NULL;
    bzero(retval->bytes, retval->len);
    
    // fill bytes randomly
    while((err = CCRandomCopyBytes(kCCRandomDefault, retval->bytes, retval->len)) != kCCSuccess) {
        printf("got %d from CCRandomCopyBytes\n", err);
    }
    
    return retval;    
}

/* utility function to convert hex character representation to their nibble (4 bit) values */
static uint8_t
nibbleFromChar(char c)
{
	if(c >= '0' && c <= '9') return c - '0';
	if(c >= 'a' && c <= 'f') return c - 'a' + 10;
	if(c >= 'A' && c <= 'F') return c - 'A' + 10;
	return 255;
}

/* Convert a string of characters representing a hex buffer into a series of bytes of that real value */
byteBuffer
hexStringToBytes(char *inhex)
{
	byteBuffer retval;
	uint8_t *p;
	int len, i;
	
	len = (int) strlen(inhex) / 2;
	if((retval = mallocByteBuffer(len)) == NULL) return NULL;
    
	for(i=0, p = (uint8_t *) inhex; i<len; i++) {
        retval->bytes[i] = (nibbleFromChar(*p) << 4) | nibbleFromChar(*(p+1));
        p += 2;
	}
    retval->bytes[len] = 0;
	return retval;
}



byteBuffer
bytesToBytes(void *bytes, size_t len)
{
    byteBuffer retval = mallocByteBuffer(len);
    memcpy(retval->bytes, bytes, len);
    return retval;
}

int
bytesAreEqual(byteBuffer b1, byteBuffer b2)
{
    if(b1->len != b2->len) return 0;
    return (memcmp(b1->bytes, b2->bytes, b1->len) == 0);
}


static char byteMap[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
static int byteMapLen = sizeof(byteMap);

/* Utility function to convert nibbles (4 bit values) into a hex character representation */
static char
nibbleToChar(uint8_t nibble)
{
	if(nibble < byteMapLen) return byteMap[nibble];
	return '*';
}

/* Convert a buffer of binary values into a hex string representation */
char
*bytesToHexString(byteBuffer bb)
{
	char *retval;
	int i;
	
	retval = malloc(bb->len*2 + 1);
	for(i=0; i<bb->len; i++) {
		retval[i*2] = nibbleToChar(bb->bytes[i] >> 4);
		retval[i*2+1] = nibbleToChar(bb->bytes[i] & 0x0f);
	}
    retval[bb->len*2] = 0;
	return retval;
}

char
*bytesToHexStringWithSpaces(byteBuffer bb, int breaks)
{
	char *retval;
	int i, j;
    
    if(breaks == 0) {
        return bytesToHexString(bb);
    }
	
    breaks /= 2;
	retval = malloc(bb->len*2 + 1 + (bb->len*2 / breaks) + 10);
	for(i=0, j=0; i<bb->len; i++, j+=2) {
		retval[j] = nibbleToChar(bb->bytes[i] >> 4);
		retval[j+1] = nibbleToChar(bb->bytes[i] & 0x0f);
        if(((i+1) % breaks) == 0) {
            retval[j+2] = ' ';
            retval[j+3] = 0;
            j++;
        }
	}
	return retval;
}


Added CCRegression/util/testbyteBuffer.h.







































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
 *  printByteBuffer.h
 *  byteutils
 *
 */

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#ifndef _BYTEBUFFER_H_
#define _BYTEBUFFER_H_

typedef struct byte_buf {
    size_t  len;
    uint8_t  *bytes;
} byteBufferStruct, *byteBuffer;

void printByteBuffer(byteBuffer bb, char *name);

void printBytes(uint8_t *buff, size_t len, char *name);

byteBuffer
mallocByteBuffer(size_t len);

byteBuffer
hexStringToBytes(char *inhex);

byteBuffer
hexStringToBytesWithSpaces(char *inhex, int breaks);

char
*bytesToHexStringWithSpaces(byteBuffer bb, int breaks);

byteBuffer
bytesToBytes(void *bytes, size_t len);

int
bytesAreEqual(byteBuffer b1, byteBuffer b2);

char
*bytesToHexString(byteBuffer bytes);

byteBuffer
genRandomByteBuffer(size_t minSize, size_t maxSize);

size_t
genRandomSize(size_t minSize, size_t maxSize);

#endif /* _BYTEBUFFER_H_ */

Changes to CommonCrypto.xcodeproj/project.pbxproj.

28
29
30
31
32
33
34
35
36
37
38
39
40
41











42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102












103
104
105
106
107
108





109
110

111
112
113































































114
115
116
117
118
119
120
121
122
123





124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
				05CE942F0A37850A007C91D6 /* CopyFiles */,
			);
			dependencies = (
			);
			name = "Copy Open Source Docs";
			productName = "Copy Open Source Docs";
		};
		5DC876F710FFB6BC0012A390 /* Unit Test World */ = {
			isa = PBXAggregateTarget;
			buildConfigurationList = 5DC876FB10FFB6DA0012A390 /* Build configuration list for PBXAggregateTarget "Unit Test World" */;
			buildPhases = (
			);
			dependencies = (
				5DC8771110FFB7510012A390 /* PBXTargetDependency */,











				5DAD83D21279F6D500240B9A /* PBXTargetDependency */,
			);
			name = "Unit Test World";
			productName = "Unit Test World";
		};
/* End PBXAggregateTarget section */

/* Begin PBXBuildFile section */
		0511C47E0A37892C0028BFC3 /* CommonCrypto.txt in CopyFiles */ = {isa = PBXBuildFile; fileRef = 05CE942C0A37850A007C91D6 /* CommonCrypto.txt */; };
		0539DC2809D4919D00AB7F89 /* opensslDES.c in Sources */ = {isa = PBXBuildFile; fileRef = 0539DC2609D4919D00AB7F89 /* opensslDES.c */; };
		054BBECE05F6AA7200344873 /* CommonDigest.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBECD05F6AA7200344873 /* CommonDigest.h */; settings = {ATTRIBUTES = (Public, ); }; };
		054BBEDE05F6AA8900344873 /* md2_dgst.c in Sources */ = {isa = PBXBuildFile; fileRef = 054BBED305F6AA8900344873 /* md2_dgst.c */; };
		054BBEDF05F6AA8900344873 /* md4_dgst.c in Sources */ = {isa = PBXBuildFile; fileRef = 054BBED405F6AA8900344873 /* md4_dgst.c */; };
		054BBEE005F6AA8900344873 /* md4_locl.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBED505F6AA8900344873 /* md4_locl.h */; };
		054BBEE105F6AA8900344873 /* md5_dgst.c in Sources */ = {isa = PBXBuildFile; fileRef = 054BBED605F6AA8900344873 /* md5_dgst.c */; };
		054BBEE205F6AA8900344873 /* md5_locl.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBED705F6AA8900344873 /* md5_locl.h */; };
		054BBEE305F6AA8900344873 /* md32_common.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBED805F6AA8900344873 /* md32_common.h */; };
		054BBEE505F6AA8900344873 /* sha_locl.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBEDA05F6AA8900344873 /* sha_locl.h */; };
		054BBEE705F6AA8900344873 /* sha1.c in Sources */ = {isa = PBXBuildFile; fileRef = 054BBEDC05F6AA8900344873 /* sha1.c */; };
		0585FE1909DC9873001762F6 /* c_ecb.c in Sources */ = {isa = PBXBuildFile; fileRef = 0585FE1209DC9873001762F6 /* c_ecb.c */; };
		0585FE1A09DC9873001762F6 /* c_enc.c in Sources */ = {isa = PBXBuildFile; fileRef = 0585FE1309DC9873001762F6 /* c_enc.c */; };
		0585FE1B09DC9873001762F6 /* c_skey.c in Sources */ = {isa = PBXBuildFile; fileRef = 0585FE1409DC9873001762F6 /* c_skey.c */; };
		0585FE1D09DC9873001762F6 /* cast_lcl.h in Headers */ = {isa = PBXBuildFile; fileRef = 0585FE1609DC9873001762F6 /* cast_lcl.h */; };
		0585FE1E09DC9873001762F6 /* cast_s.h in Headers */ = {isa = PBXBuildFile; fileRef = 0585FE1709DC9873001762F6 /* cast_s.h */; };
		0585FE1F09DC9873001762F6 /* ccCast.c in Sources */ = {isa = PBXBuildFile; fileRef = 0585FE1809DC9873001762F6 /* ccCast.c */; };
		05C4414409D49F28002066D1 /* des.h in Headers */ = {isa = PBXBuildFile; fileRef = 05ECA0E409D468E200CFE5CB /* des.h */; };
		05C4414509D49F29002066D1 /* des_enc.c in Sources */ = {isa = PBXBuildFile; fileRef = 05ECA0E509D468E200CFE5CB /* des_enc.c */; };
		05C4414609D49F29002066D1 /* des_locl.h in Headers */ = {isa = PBXBuildFile; fileRef = 05ECA0E609D468E200CFE5CB /* des_locl.h */; };
		05C4416F09D4BACE002066D1 /* e_os2.h in Headers */ = {isa = PBXBuildFile; fileRef = 05C4416E09D4BACE002066D1 /* e_os2.h */; };
		05C4417309D4BB0B002066D1 /* opensslconf.h in Headers */ = {isa = PBXBuildFile; fileRef = 05C4417209D4BB0B002066D1 /* opensslconf.h */; };
		05C70C5509D471C30004B8F4 /* spr.h in Headers */ = {isa = PBXBuildFile; fileRef = 05C70C5309D471C30004B8F4 /* spr.h */; };
		05CE942D0A37850A007C91D6 /* CommonCrypto.plist in CopyFiles */ = {isa = PBXBuildFile; fileRef = 05CE942B0A37850A007C91D6 /* CommonCrypto.plist */; };
		05D8D97D09E411AB00E03504 /* CommonHMAC.h in Headers */ = {isa = PBXBuildFile; fileRef = 05D8D97C09E411AA00E03504 /* CommonHMAC.h */; settings = {ATTRIBUTES = (Public, ); }; };
		05D9F61909D85F4A00AD30A7 /* CommonCryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 05D9F61609D85F4A00AD30A7 /* CommonCryptor.h */; settings = {ATTRIBUTES = (Public, ); }; };
		05E319BD063890C100C4AD24 /* sha2.c in Sources */ = {isa = PBXBuildFile; fileRef = 05E319B7063890C100C4AD24 /* sha2.c */; };
		05E319DD0638913700C4AD24 /* sha2Priv.h in Headers */ = {isa = PBXBuildFile; fileRef = 05E319DC0638913700C4AD24 /* sha2Priv.h */; };
		05ECA0EE09D469A100CFE5CB /* set_key.c in Sources */ = {isa = PBXBuildFile; fileRef = 05ECA0ED09D469A100CFE5CB /* set_key.c */; };
		122ADC45121320D70027F302 /* sha256_nossse3.s in Sources */ = {isa = PBXBuildFile; fileRef = 122ADC43121320D70027F302 /* sha256_nossse3.s */; };
		122ADC46121320D70027F302 /* sha256.s in Sources */ = {isa = PBXBuildFile; fileRef = 122ADC44121320D70027F302 /* sha256.s */; };
		1235BCBF1207FAFC002BC892 /* libcommonCrypto.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 054BBEC605F6A98900344873 /* libcommonCrypto.dylib */; };
		1249340812270E8900F9C9E1 /* cfb8_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340112270E8900F9C9E1 /* cfb8_decrypt.c */; };
		1249340912270E8900F9C9E1 /* cfb8_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340212270E8900F9C9E1 /* cfb8_descriptor.c */; };
		1249340A12270E8900F9C9E1 /* cfb8_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340312270E8900F9C9E1 /* cfb8_done.c */; };
		1249340B12270E8900F9C9E1 /* cfb8_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340412270E8900F9C9E1 /* cfb8_encrypt.c */; };
		1249340C12270E8900F9C9E1 /* cfb8_getiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340512270E8900F9C9E1 /* cfb8_getiv.c */; };
		1249340D12270E8900F9C9E1 /* cfb8_setiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340612270E8900F9C9E1 /* cfb8_setiv.c */; };
		1249340E12270E8900F9C9E1 /* cfb8_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340712270E8900F9C9E1 /* cfb8_start.c */; };
		125B78AF11FF877D008C1AD3 /* aesedpPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 125B78AE11FF877D008C1AD3 /* aesedpPriv.h */; };
		125B795611FF925B008C1AD3 /* libcommonCrypto.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 054BBEBE05F6A97700344873 /* libcommonCrypto.dylib */; };
		125B796711FF92FC008C1AD3 /* crypto.c in Sources */ = {isa = PBXBuildFile; fileRef = 125B796011FF92FC008C1AD3 /* crypto.c */; };
		125B796811FF92FC008C1AD3 /* hexString.c in Sources */ = {isa = PBXBuildFile; fileRef = 125B796111FF92FC008C1AD3 /* hexString.c */; };
		125B796911FF92FC008C1AD3 /* printByteBuffer.c in Sources */ = {isa = PBXBuildFile; fileRef = 125B796311FF92FC008C1AD3 /* printByteBuffer.c */; };
		125B796A11FF92FC008C1AD3 /* xtsTestVectors.c in Sources */ = {isa = PBXBuildFile; fileRef = 125B796511FF92FC008C1AD3 /* xtsTestVectors.c */; };
		12B5D56D11FF437500626A60 /* aesxts.c in Sources */ = {isa = PBXBuildFile; fileRef = 48B4B98C11ABA1B4001F1036 /* aesxts.c */; };
		12B5D56E11FF437A00626A60 /* aesxts_asm.s in Sources */ = {isa = PBXBuildFile; fileRef = 48B4B98D11ABA1B4001F1036 /* aesxts_asm.s */; };
		12C3F7E6122AD1B100E09D9E /* SenTestingKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 12C3F7E5122AD1B100E09D9E /* SenTestingKit.framework */; };
		12CC5DDA120373D1001B4FCE /* CBCTest.c in Sources */ = {isa = PBXBuildFile; fileRef = 12CC5DD9120373D1001B4FCE /* CBCTest.c */; };
		12FA0DB011F7962100917A4E /* CommonRandomSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 12FA0DAF11F7962100917A4E /* CommonRandomSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		12FA0DB211F7964700917A4E /* CommonRandom.c in Sources */ = {isa = PBXBuildFile; fileRef = 12FA0DB111F7964700917A4E /* CommonRandom.c */; };
		12FA10CA11F7A01D00917A4E /* libcommonCrypto.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 054BBEBE05F6A97700344873 /* libcommonCrypto.dylib */; };
		48096B2311A5EF900043F67F /* CommonDigest.c in Sources */ = {isa = PBXBuildFile; fileRef = 48096B2211A5EF900043F67F /* CommonDigest.c */; };












		480C9AD712077BCF002EC023 /* byteBuffer.c in Sources */ = {isa = PBXBuildFile; fileRef = 480C9AD512077BCF002EC023 /* byteBuffer.c */; };
		48161AFF11AF011B009A14CE /* AES.s in Sources */ = {isa = PBXBuildFile; fileRef = 48B4B99311ABA1B4001F1036 /* AES.s */; };
		48161B0011AF0123009A14CE /* aes_crypt_hw.s in Sources */ = {isa = PBXBuildFile; fileRef = 48B4B99611ABA1B4001F1036 /* aes_crypt_hw.s */; };
		48161B0111AF0124009A14CE /* aes_key_hw.s in Sources */ = {isa = PBXBuildFile; fileRef = 48B4B99511ABA1B4001F1036 /* aes_key_hw.s */; };
		48161B0211AF0124009A14CE /* aes_modes_asm.s in Sources */ = {isa = PBXBuildFile; fileRef = 48B4B98A11ABA1B4001F1036 /* aes_modes_asm.s */; };
		48161B0311AF0125009A14CE /* aes_modes_hw.s in Sources */ = {isa = PBXBuildFile; fileRef = 48B4B98911ABA1B4001F1036 /* aes_modes_hw.s */; };





		4836A41F11A5C94A00862178 /* rc2.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41811A5C94A00862178 /* rc2.h */; };
		4836A42011A5C94A00862178 /* opensslDES.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41911A5C94A00862178 /* opensslDES.h */; settings = {ATTRIBUTES = (Private, ); }; };

		4836A42111A5C94A00862178 /* CommonCryptoPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41A11A5C94A00862178 /* CommonCryptoPriv.h */; settings = {ATTRIBUTES = (Private, ); }; };
		4836A42211A5C94A00862178 /* ccRC2.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41B11A5C94A00862178 /* ccRC2.h */; };
		4836A42311A5C94A00862178 /* ccCast.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41C11A5C94A00862178 /* ccCast.h */; settings = {ATTRIBUTES = (Private, ); }; };































































		4836A42411A5C94A00862178 /* cast.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41D11A5C94A00862178 /* cast.h */; settings = {ATTRIBUTES = (Private, ); }; };
		4836A43211A5CB4700862178 /* CommonCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42B11A5CB4700862178 /* CommonCryptor.c */; };
		4836A43311A5CB4700862178 /* CommonCryptorPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A42C11A5CB4700862178 /* CommonCryptorPriv.h */; settings = {ATTRIBUTES = (); }; };
		4836A43411A5CB4700862178 /* CommonDigestPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A42D11A5CB4700862178 /* CommonDigestPriv.h */; };
		4836A43511A5CB4700862178 /* CommonHMAC.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42E11A5CB4700862178 /* CommonHMAC.c */; };
		4836A43611A5CB4700862178 /* CommonKeyDerivation.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42F11A5CB4700862178 /* CommonKeyDerivation.c */; };
		4836A43711A5CB4700862178 /* CommonKeyDerivationPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A43011A5CB4700862178 /* CommonKeyDerivationPriv.h */; };
		4836A43811A5CB4700862178 /* CommonSymmetricKeywrap.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A43111A5CB4700862178 /* CommonSymmetricKeywrap.c */; };
		4846CA5611A5C8B800E7DA82 /* CommonCryptorSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 4846CA5411A5C8B800E7DA82 /* CommonCryptorSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		4846CA5711A5C8B800E7DA82 /* CommonDigestSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 4846CA5511A5C8B800E7DA82 /* CommonDigestSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };





		4854F9C21116307500CAFA18 /* CommonKeyDerivation.h in Headers */ = {isa = PBXBuildFile; fileRef = 4854F9C01116307500CAFA18 /* CommonKeyDerivation.h */; settings = {ATTRIBUTES = (Public, ); }; };
		4854F9C31116307500CAFA18 /* CommonSymmetricKeywrap.h in Headers */ = {isa = PBXBuildFile; fileRef = 4854F9C11116307500CAFA18 /* CommonSymmetricKeywrap.h */; settings = {ATTRIBUTES = (Public, ); }; };
		485A566C11AE4BB2003DDC41 /* aesedp.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F34A11A4E47B00B5DDB3 /* aesedp.c */; };
		485A566D11AE4BB4003DDC41 /* aesedp.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F34B11A4E47B00B5DDB3 /* aesedp.h */; };
		4862F09811BDA1D300946BBE /* skein_ltc.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F09411BDA1D300946BBE /* skein_ltc.h */; };
		4862F09911BDA1D300946BBE /* skein_ltc.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F09511BDA1D300946BBE /* skein_ltc.c */; };
		4862F0AB11BDA27200946BBE /* skein.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F09E11BDA27200946BBE /* skein.h */; };
		4862F0AC11BDA27200946BBE /* skein.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F09F11BDA27200946BBE /* skein.c */; };
		4862F0AD11BDA27200946BBE /* skein_port.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A011BDA27200946BBE /* skein_port.h */; };
		4862F0AE11BDA27200946BBE /* skein_iv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A111BDA27200946BBE /* skein_iv.h */; };
		4862F0AF11BDA27200946BBE /* skein_dropin.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A211BDA27200946BBE /* skein_dropin.h */; };
		4862F0B011BDA27200946BBE /* skein_dropin.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F0A311BDA27200946BBE /* skein_dropin.c */; };
		4862F0B111BDA27200946BBE /* skein_debug.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A411BDA27200946BBE /* skein_debug.h */; };
		4862F0B211BDA27200946BBE /* skein_debug.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F0A511BDA27200946BBE /* skein_debug.c */; };
		4862F0B311BDA27200946BBE /* skein_block.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F0A611BDA27200946BBE /* skein_block.c */; };
		4862F0B411BDA27200946BBE /* SHA3api_ref.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A711BDA27200946BBE /* SHA3api_ref.h */; };
		4862F0B511BDA27200946BBE /* SHA3api_ref.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F0A811BDA27200946BBE /* SHA3api_ref.c */; };
		4862F0B611BDA27200946BBE /* brg_types.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A911BDA27200946BBE /* brg_types.h */; };
		4862F0B711BDA27200946BBE /* brg_endian.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0AA11BDA27200946BBE /* brg_endian.h */; };
		4873F40211A4E47B00B5DDB3 /* cast5.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35311A4E47B00B5DDB3 /* cast5.c */; };
		4873F40311A4E47B00B5DDB3 /* des.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35411A4E47B00B5DDB3 /* des.c */; };
		4873F40411A4E47B00B5DDB3 /* rc2.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35511A4E47B00B5DDB3 /* rc2.c */; };
		4873F40511A4E47B00B5DDB3 /* rc4.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F35711A4E47B00B5DDB3 /* rc4.h */; settings = {ATTRIBUTES = (Private, ); }; };
		4873F40611A4E47B00B5DDB3 /* rc4_enc.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35811A4E47B00B5DDB3 /* rc4_enc.c */; };
		4873F40711A4E47B00B5DDB3 /* rc4_skey.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35911A4E47B00B5DDB3 /* rc4_skey.c */; };
		4873F40811A4E47B00B5DDB3 /* rc5.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35A11A4E47B00B5DDB3 /* rc5.c */; };
		4873F40911A4E47B00B5DDB3 /* hash_file.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35D11A4E47B00B5DDB3 /* hash_file.c */; };
		4873F40A11A4E47B00B5DDB3 /* hash_filehandle.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35E11A4E47B00B5DDB3 /* hash_filehandle.c */; };
		4873F40B11A4E47B00B5DDB3 /* hash_memory.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35F11A4E47B00B5DDB3 /* hash_memory.c */; };
		4873F40C11A4E47B00B5DDB3 /* hash_memory_multi.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36011A4E47B00B5DDB3 /* hash_memory_multi.c */; };
		4873F40D11A4E47B00B5DDB3 /* md2.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36111A4E47B00B5DDB3 /* md2.c */; };
		4873F40E11A4E47B00B5DDB3 /* md4.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36211A4E47B00B5DDB3 /* md4.c */; };
		4873F40F11A4E47B00B5DDB3 /* md5.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36311A4E47B00B5DDB3 /* md5.c */; };
		4873F41011A4E47B00B5DDB3 /* rmd128.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36411A4E47B00B5DDB3 /* rmd128.c */; };
		4873F41111A4E47B00B5DDB3 /* rmd160.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36511A4E47B00B5DDB3 /* rmd160.c */; };
		4873F41211A4E47B00B5DDB3 /* rmd256.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36611A4E47B00B5DDB3 /* rmd256.c */; };
		4873F41311A4E47B00B5DDB3 /* rmd320.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36711A4E47B00B5DDB3 /* rmd320.c */; };
		4873F41411A4E47B00B5DDB3 /* sha1.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36811A4E47B00B5DDB3 /* sha1.c */; };
		4873F41611A4E47B00B5DDB3 /* sha256.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36B11A4E47B00B5DDB3 /* sha256.c */; };
		4873F41811A4E47B00B5DDB3 /* sha512.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36D11A4E47B00B5DDB3 /* sha512.c */; };
		4873F41911A4E47B00B5DDB3 /* tomcrypt.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F36F11A4E47B00B5DDB3 /* tomcrypt.h */; };
		4873F41A11A4E47B00B5DDB3 /* tomcrypt_argchk.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37011A4E47B00B5DDB3 /* tomcrypt_argchk.h */; };
		4873F41B11A4E47B00B5DDB3 /* tomcrypt_cfg.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37111A4E47B00B5DDB3 /* tomcrypt_cfg.h */; };
		4873F41C11A4E47B00B5DDB3 /* tomcrypt_cipher.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37211A4E47B00B5DDB3 /* tomcrypt_cipher.h */; };
		4873F41D11A4E47B00B5DDB3 /* tomcrypt_custom.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37311A4E47B00B5DDB3 /* tomcrypt_custom.h */; };
		4873F41E11A4E47B00B5DDB3 /* tomcrypt_hash.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37411A4E47B00B5DDB3 /* tomcrypt_hash.h */; };
		4873F41F11A4E47B00B5DDB3 /* tomcrypt_mac.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37511A4E47B00B5DDB3 /* tomcrypt_mac.h */; };
		4873F42011A4E47B00B5DDB3 /* tomcrypt_macros.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37611A4E47B00B5DDB3 /* tomcrypt_macros.h */; };
		4873F42111A4E47B00B5DDB3 /* tomcrypt_math.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37711A4E47B00B5DDB3 /* tomcrypt_math.h */; };
		4873F42211A4E47B00B5DDB3 /* tomcrypt_misc.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37811A4E47B00B5DDB3 /* tomcrypt_misc.h */; };
		4873F42311A4E47B00B5DDB3 /* tomcrypt_mode.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37911A4E47B00B5DDB3 /* tomcrypt_mode.h */; };
		4873F42411A4E47B00B5DDB3 /* tomcrypt_pk.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37A11A4E47B00B5DDB3 /* tomcrypt_pk.h */; };
		4873F42511A4E47B00B5DDB3 /* tomcrypt_pkcs.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37B11A4E47B00B5DDB3 /* tomcrypt_pkcs.h */; };
		4873F42611A4E47B00B5DDB3 /* tomcrypt_prng.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37C11A4E47B00B5DDB3 /* tomcrypt_prng.h */; };
		4873F42A11A4E47B00B5DDB3 /* crypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38311A4E47B00B5DDB3 /* crypt.c */; };
		4873F42B11A4E47B00B5DDB3 /* crypt_argchk.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38411A4E47B00B5DDB3 /* crypt_argchk.c */; };
		4873F42C11A4E47B00B5DDB3 /* crypt_cipher_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38511A4E47B00B5DDB3 /* crypt_cipher_descriptor.c */; };
		4873F42D11A4E47B00B5DDB3 /* crypt_cipher_is_valid.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38611A4E47B00B5DDB3 /* crypt_cipher_is_valid.c */; };
		4873F42E11A4E47B00B5DDB3 /* crypt_find_cipher.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38711A4E47B00B5DDB3 /* crypt_find_cipher.c */; };
		4873F42F11A4E47B00B5DDB3 /* crypt_find_cipher_any.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38811A4E47B00B5DDB3 /* crypt_find_cipher_any.c */; };
		4873F43011A4E47B00B5DDB3 /* crypt_find_cipher_id.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38911A4E47B00B5DDB3 /* crypt_find_cipher_id.c */; };
		4873F43111A4E47B00B5DDB3 /* crypt_find_hash.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38A11A4E47B00B5DDB3 /* crypt_find_hash.c */; };
		4873F43211A4E47B00B5DDB3 /* crypt_find_hash_any.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38B11A4E47B00B5DDB3 /* crypt_find_hash_any.c */; };
		4873F43311A4E47B00B5DDB3 /* crypt_find_hash_id.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38C11A4E47B00B5DDB3 /* crypt_find_hash_id.c */; };
		4873F43411A4E47B00B5DDB3 /* crypt_find_hash_oid.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38D11A4E47B00B5DDB3 /* crypt_find_hash_oid.c */; };
		4873F43511A4E47B00B5DDB3 /* crypt_find_prng.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38E11A4E47B00B5DDB3 /* crypt_find_prng.c */; };
		4873F43711A4E47B00B5DDB3 /* crypt_hash_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39011A4E47B00B5DDB3 /* crypt_hash_descriptor.c */; };
		4873F43811A4E47B00B5DDB3 /* crypt_hash_is_valid.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39111A4E47B00B5DDB3 /* crypt_hash_is_valid.c */; };
		4873F43911A4E47B00B5DDB3 /* crypt_ltc_mp_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39211A4E47B00B5DDB3 /* crypt_ltc_mp_descriptor.c */; };
		4873F43A11A4E47B00B5DDB3 /* crypt_mode_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39311A4E47B00B5DDB3 /* crypt_mode_descriptor.c */; };
		4873F43D11A4E47B00B5DDB3 /* crypt_register_cipher.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39611A4E47B00B5DDB3 /* crypt_register_cipher.c */; };
		4873F43E11A4E47B00B5DDB3 /* crypt_register_hash.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39711A4E47B00B5DDB3 /* crypt_register_hash.c */; };
		4873F44011A4E47B00B5DDB3 /* crypt_unregister_cipher.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39911A4E47B00B5DDB3 /* crypt_unregister_cipher.c */; };
		4873F44111A4E47B00B5DDB3 /* crypt_unregister_hash.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39A11A4E47B00B5DDB3 /* crypt_unregister_hash.c */; };
		4873F44311A4E47B00B5DDB3 /* error_to_string.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39C11A4E47B00B5DDB3 /* error_to_string.c */; };
		4873F44611A4E47B00B5DDB3 /* zeromem.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A011A4E47B00B5DDB3 /* zeromem.c */; };
		4873F44711A4E47B00B5DDB3 /* cbc_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A311A4E47B00B5DDB3 /* cbc_decrypt.c */; };
		4873F44811A4E47B00B5DDB3 /* cbc_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A411A4E47B00B5DDB3 /* cbc_descriptor.c */; };
		4873F44911A4E47B00B5DDB3 /* cbc_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A511A4E47B00B5DDB3 /* cbc_done.c */; };
		4873F44A11A4E47B00B5DDB3 /* cbc_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A611A4E47B00B5DDB3 /* cbc_encrypt.c */; };
		4873F44B11A4E47B00B5DDB3 /* cbc_getiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A711A4E47B00B5DDB3 /* cbc_getiv.c */; };
		4873F44C11A4E47B00B5DDB3 /* cbc_setiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A811A4E47B00B5DDB3 /* cbc_setiv.c */; };
		4873F44D11A4E47B00B5DDB3 /* cbc_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A911A4E47B00B5DDB3 /* cbc_start.c */; };
		4873F44E11A4E47B00B5DDB3 /* cfb_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3AB11A4E47B00B5DDB3 /* cfb_decrypt.c */; };
		4873F44F11A4E47B00B5DDB3 /* cfb_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3AC11A4E47B00B5DDB3 /* cfb_descriptor.c */; };
		4873F45011A4E47B00B5DDB3 /* cfb_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3AD11A4E47B00B5DDB3 /* cfb_done.c */; };
		4873F45111A4E47B00B5DDB3 /* cfb_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3AE11A4E47B00B5DDB3 /* cfb_encrypt.c */; };
		4873F45211A4E47B00B5DDB3 /* cfb_getiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3AF11A4E47B00B5DDB3 /* cfb_getiv.c */; };
		4873F45311A4E47B00B5DDB3 /* cfb_setiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B011A4E47B00B5DDB3 /* cfb_setiv.c */; };
		4873F45411A4E47B00B5DDB3 /* cfb_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B111A4E47B00B5DDB3 /* cfb_start.c */; };
		4873F45511A4E47B00B5DDB3 /* ctr_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B311A4E47B00B5DDB3 /* ctr_decrypt.c */; };
		4873F45611A4E47B00B5DDB3 /* ctr_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B411A4E47B00B5DDB3 /* ctr_descriptor.c */; };
		4873F45711A4E47B00B5DDB3 /* ctr_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B511A4E47B00B5DDB3 /* ctr_done.c */; };
		4873F45811A4E47B00B5DDB3 /* ctr_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B611A4E47B00B5DDB3 /* ctr_encrypt.c */; };
		4873F45911A4E47B00B5DDB3 /* ctr_getiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B711A4E47B00B5DDB3 /* ctr_getiv.c */; };
		4873F45A11A4E47B00B5DDB3 /* ctr_setiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B811A4E47B00B5DDB3 /* ctr_setiv.c */; };
		4873F45B11A4E47B00B5DDB3 /* ctr_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B911A4E47B00B5DDB3 /* ctr_start.c */; };
		4873F45C11A4E47B00B5DDB3 /* ctr_test.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3BA11A4E47B00B5DDB3 /* ctr_test.c */; };
		4873F45D11A4E47B00B5DDB3 /* ecb_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3BC11A4E47B00B5DDB3 /* ecb_decrypt.c */; };
		4873F45E11A4E47B00B5DDB3 /* ecb_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3BD11A4E47B00B5DDB3 /* ecb_descriptor.c */; };
		4873F45F11A4E47B00B5DDB3 /* ecb_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3BE11A4E47B00B5DDB3 /* ecb_done.c */; };
		4873F46011A4E47B00B5DDB3 /* ecb_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3BF11A4E47B00B5DDB3 /* ecb_encrypt.c */; };
		4873F46111A4E47B00B5DDB3 /* ecb_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3C011A4E47B00B5DDB3 /* ecb_start.c */; };
		4873F47311A4E47B00B5DDB3 /* ofb_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3D511A4E47B00B5DDB3 /* ofb_decrypt.c */; };
		4873F47411A4E47B00B5DDB3 /* ofb_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3D611A4E47B00B5DDB3 /* ofb_descriptor.c */; };
		4873F47511A4E47B00B5DDB3 /* ofb_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3D711A4E47B00B5DDB3 /* ofb_done.c */; };
		4873F47611A4E47B00B5DDB3 /* ofb_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3D811A4E47B00B5DDB3 /* ofb_encrypt.c */; };
		4873F47711A4E47B00B5DDB3 /* ofb_getiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3D911A4E47B00B5DDB3 /* ofb_getiv.c */; };
		4873F47811A4E47B00B5DDB3 /* ofb_setiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3DA11A4E47B00B5DDB3 /* ofb_setiv.c */; };
		4873F47911A4E47B00B5DDB3 /* ofb_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3DB11A4E47B00B5DDB3 /* ofb_start.c */; };
		4873F47A11A4E47B00B5DDB3 /* rc4_stream.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3DC11A4E47B00B5DDB3 /* rc4_stream.c */; };
		4873F47B11A4E47B00B5DDB3 /* unimplemented.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3DD11A4E47B00B5DDB3 /* unimplemented.c */; };
		4873F47C11A4E47B00B5DDB3 /* xts_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3DF11A4E47B00B5DDB3 /* xts_decrypt.c */; };
		4873F47D11A4E47B00B5DDB3 /* xts_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E011A4E47B00B5DDB3 /* xts_descriptor.c */; };
		4873F47E11A4E47B00B5DDB3 /* xts_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E111A4E47B00B5DDB3 /* xts_done.c */; };
		4873F47F11A4E47B00B5DDB3 /* xts_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E211A4E47B00B5DDB3 /* xts_encrypt.c */; };
		4873F48011A4E47B00B5DDB3 /* xts_init.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E311A4E47B00B5DDB3 /* xts_init.c */; };
		4873F48111A4E47B00B5DDB3 /* xts_mult_x.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E411A4E47B00B5DDB3 /* xts_mult_x.c */; };
		4873F48211A4E47B00B5DDB3 /* xts_test.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E511A4E47B00B5DDB3 /* xts_test.c */; };
		4873F48311A4E47B00B5DDB3 /* ansi923pad.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E811A4E47B00B5DDB3 /* ansi923pad.c */; };
		4873F48411A4E47B00B5DDB3 /* ansi923pad.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F3E911A4E47B00B5DDB3 /* ansi923pad.h */; };
		4873F48511A4E47B00B5DDB3 /* iso10126pad.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3EB11A4E47B00B5DDB3 /* iso10126pad.c */; };
		4873F48611A4E47B00B5DDB3 /* iso10126pad.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F3EC11A4E47B00B5DDB3 /* iso10126pad.h */; };
		4873F48711A4E47B00B5DDB3 /* nopad.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3EE11A4E47B00B5DDB3 /* nopad.c */; };
		4873F48811A4E47B00B5DDB3 /* nopad.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F3EF11A4E47B00B5DDB3 /* nopad.h */; };
		4873F48911A4E47B00B5DDB3 /* pkcs7pad.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3F111A4E47B00B5DDB3 /* pkcs7pad.c */; };
		4873F48A11A4E47B00B5DDB3 /* pkcs7pad.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F3F211A4E47B00B5DDB3 /* pkcs7pad.h */; };
		489D982E11A4E8C20004DB89 /* ccdebug.c in Sources */ = {isa = PBXBuildFile; fileRef = 489D982C11A4E8C20004DB89 /* ccdebug.c */; };
		489D982F11A4E8C20004DB89 /* ccdebug.h in Headers */ = {isa = PBXBuildFile; fileRef = 489D982D11A4E8C20004DB89 /* ccdebug.h */; };
		48D5636811A652D7008EBBBF /* aesopt.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D5636611A652D7008EBBBF /* aesopt.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48D5636911A652D7008EBBBF /* aes.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D5636711A652D7008EBBBF /* aes.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48D5637111A652EB008EBBBF /* aescrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D5636B11A652EB008EBBBF /* aescrypt.c */; };
		48D5637211A652EB008EBBBF /* aeskey.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D5636C11A652EB008EBBBF /* aeskey.c */; };
		48D5637311A652EB008EBBBF /* aestab.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D5636D11A652EB008EBBBF /* aestab.c */; };
		48D5637411A652EB008EBBBF /* aestab.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D5636E11A652EB008EBBBF /* aestab.h */; };
		48D5637511A652EB008EBBBF /* ccNewGladman.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D5636F11A652EB008EBBBF /* ccNewGladman.c */; };
		48D5638611A65316008EBBBF /* AES.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D5637711A65316008EBBBF /* AES.c */; };
		48D5638711A65316008EBBBF /* AESAssembly.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D5637811A65316008EBBBF /* AESAssembly.h */; };
		48D5638911A65316008EBBBF /* AES.s in Sources */ = {isa = PBXBuildFile; fileRef = 48D5637B11A65316008EBBBF /* AES.s */; };
		48D5638B11A65316008EBBBF /* DecryptCBC.s in Sources */ = {isa = PBXBuildFile; fileRef = 48D5637D11A65316008EBBBF /* DecryptCBC.s */; };
		48D5638C11A65316008EBBBF /* EncryptCBC.s in Sources */ = {isa = PBXBuildFile; fileRef = 48D5637E11A65316008EBBBF /* EncryptCBC.s */; };
		48F7B00112F248C900E70774 /* CCCalibratePBKDF.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 48F7AFFF12F2488500E70774 /* CCCalibratePBKDF.3cc */; };
		48F7B00212F248C900E70774 /* CCCommonKeyDerivation.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 48F7B00012F2488500E70774 /* CCCommonKeyDerivation.3cc */; };
		48F7B00812F248E600E70774 /* CCKeyDerivationPBKDF.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 48F7B00312F248E600E70774 /* CCKeyDerivationPBKDF.3cc */; };
		48F7B00912F248E600E70774 /* CCSymmetricKeyUnwrap.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 48F7B00412F248E600E70774 /* CCSymmetricKeyUnwrap.3cc */; };
		48F7B00A12F248E600E70774 /* CCSymmetricKeyWrap.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 48F7B00512F248E600E70774 /* CCSymmetricKeyWrap.3cc */; };
		48F7B00B12F248E700E70774 /* CCSymmetricUnwrappedSize.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 48F7B00612F248E600E70774 /* CCSymmetricUnwrappedSize.3cc */; };
		48F7B00C12F248E700E70774 /* CCSymmetricWrappedSize.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 48F7B00712F248E600E70774 /* CCSymmetricWrappedSize.3cc */; };
		48F7F29912B2EF6000AF4587 /* CommonDigest.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBECD05F6AA7200344873 /* CommonDigest.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48F7F29A12B2EF6000AF4587 /* md4_locl.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBED505F6AA8900344873 /* md4_locl.h */; };
		48F7F29B12B2EF6000AF4587 /* md5_locl.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBED705F6AA8900344873 /* md5_locl.h */; };
		48F7F29C12B2EF6000AF4587 /* md32_common.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBED805F6AA8900344873 /* md32_common.h */; };
		48F7F29D12B2EF6000AF4587 /* sha_locl.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBEDA05F6AA8900344873 /* sha_locl.h */; };
		48F7F29E12B2EF6000AF4587 /* sha2Priv.h in Headers */ = {isa = PBXBuildFile; fileRef = 05E319DC0638913700C4AD24 /* sha2Priv.h */; };
		48F7F29F12B2EF6000AF4587 /* spr.h in Headers */ = {isa = PBXBuildFile; fileRef = 05C70C5309D471C30004B8F4 /* spr.h */; };
		48F7F2A012B2EF6000AF4587 /* des.h in Headers */ = {isa = PBXBuildFile; fileRef = 05ECA0E409D468E200CFE5CB /* des.h */; };
		48F7F2A112B2EF6000AF4587 /* des_locl.h in Headers */ = {isa = PBXBuildFile; fileRef = 05ECA0E609D468E200CFE5CB /* des_locl.h */; };
		48F7F2A212B2EF6000AF4587 /* e_os2.h in Headers */ = {isa = PBXBuildFile; fileRef = 05C4416E09D4BACE002066D1 /* e_os2.h */; };
		48F7F2A312B2EF6000AF4587 /* opensslconf.h in Headers */ = {isa = PBXBuildFile; fileRef = 05C4417209D4BB0B002066D1 /* opensslconf.h */; };
		48F7F2A412B2EF6000AF4587 /* CommonCryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 05D9F61609D85F4A00AD30A7 /* CommonCryptor.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48F7F2A512B2EF6000AF4587 /* cast_lcl.h in Headers */ = {isa = PBXBuildFile; fileRef = 0585FE1609DC9873001762F6 /* cast_lcl.h */; };
		48F7F2A612B2EF6000AF4587 /* cast_s.h in Headers */ = {isa = PBXBuildFile; fileRef = 0585FE1709DC9873001762F6 /* cast_s.h */; };
		48F7F2A712B2EF6000AF4587 /* CommonHMAC.h in Headers */ = {isa = PBXBuildFile; fileRef = 05D8D97C09E411AA00E03504 /* CommonHMAC.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48F7F2A812B2EF6000AF4587 /* CommonKeyDerivation.h in Headers */ = {isa = PBXBuildFile; fileRef = 4854F9C01116307500CAFA18 /* CommonKeyDerivation.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48F7F2A912B2EF6000AF4587 /* CommonSymmetricKeywrap.h in Headers */ = {isa = PBXBuildFile; fileRef = 4854F9C11116307500CAFA18 /* CommonSymmetricKeywrap.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48F7F2AA12B2EF6000AF4587 /* rc4.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F35711A4E47B00B5DDB3 /* rc4.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48F7F2AB12B2EF6000AF4587 /* tomcrypt.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F36F11A4E47B00B5DDB3 /* tomcrypt.h */; };
		48F7F2AC12B2EF6000AF4587 /* tomcrypt_argchk.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37011A4E47B00B5DDB3 /* tomcrypt_argchk.h */; };
		48F7F2AD12B2EF6000AF4587 /* tomcrypt_cfg.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37111A4E47B00B5DDB3 /* tomcrypt_cfg.h */; };
		48F7F2AE12B2EF6000AF4587 /* tomcrypt_cipher.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37211A4E47B00B5DDB3 /* tomcrypt_cipher.h */; };
		48F7F2AF12B2EF6000AF4587 /* tomcrypt_custom.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37311A4E47B00B5DDB3 /* tomcrypt_custom.h */; };
		48F7F2B012B2EF6000AF4587 /* tomcrypt_hash.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37411A4E47B00B5DDB3 /* tomcrypt_hash.h */; };
		48F7F2B112B2EF6000AF4587 /* tomcrypt_mac.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37511A4E47B00B5DDB3 /* tomcrypt_mac.h */; };
		48F7F2B212B2EF6000AF4587 /* tomcrypt_macros.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37611A4E47B00B5DDB3 /* tomcrypt_macros.h */; };
		48F7F2B312B2EF6000AF4587 /* tomcrypt_math.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37711A4E47B00B5DDB3 /* tomcrypt_math.h */; };
		48F7F2B412B2EF6000AF4587 /* tomcrypt_misc.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37811A4E47B00B5DDB3 /* tomcrypt_misc.h */; };
		48F7F2B512B2EF6000AF4587 /* tomcrypt_mode.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37911A4E47B00B5DDB3 /* tomcrypt_mode.h */; };
		48F7F2B612B2EF6000AF4587 /* tomcrypt_pk.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37A11A4E47B00B5DDB3 /* tomcrypt_pk.h */; };
		48F7F2B712B2EF6000AF4587 /* tomcrypt_pkcs.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37B11A4E47B00B5DDB3 /* tomcrypt_pkcs.h */; };
		48F7F2B812B2EF6000AF4587 /* tomcrypt_prng.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F37C11A4E47B00B5DDB3 /* tomcrypt_prng.h */; };
		48F7F2B912B2EF6000AF4587 /* ansi923pad.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F3E911A4E47B00B5DDB3 /* ansi923pad.h */; };
		48F7F2BA12B2EF6000AF4587 /* iso10126pad.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F3EC11A4E47B00B5DDB3 /* iso10126pad.h */; };
		48F7F2BB12B2EF6000AF4587 /* nopad.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F3EF11A4E47B00B5DDB3 /* nopad.h */; };
		48F7F2BC12B2EF6000AF4587 /* pkcs7pad.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873F3F211A4E47B00B5DDB3 /* pkcs7pad.h */; };
		48F7F2BD12B2EF6000AF4587 /* ccdebug.h in Headers */ = {isa = PBXBuildFile; fileRef = 489D982D11A4E8C20004DB89 /* ccdebug.h */; };
		48F7F2BE12B2EF6000AF4587 /* CommonCryptorSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 4846CA5411A5C8B800E7DA82 /* CommonCryptorSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48F7F2BF12B2EF6000AF4587 /* CommonDigestSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 4846CA5511A5C8B800E7DA82 /* CommonDigestSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48F7F2C012B2EF6000AF4587 /* rc2.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41811A5C94A00862178 /* rc2.h */; };
		48F7F2C112B2EF6000AF4587 /* opensslDES.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41911A5C94A00862178 /* opensslDES.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48F7F2C212B2EF6000AF4587 /* CommonCryptoPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41A11A5C94A00862178 /* CommonCryptoPriv.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48F7F2C312B2EF6000AF4587 /* ccRC2.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41B11A5C94A00862178 /* ccRC2.h */; };
		48F7F2C412B2EF6000AF4587 /* ccCast.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41C11A5C94A00862178 /* ccCast.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48F7F2C512B2EF6000AF4587 /* cast.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41D11A5C94A00862178 /* cast.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48F7F2C612B2EF6000AF4587 /* CommonCryptorPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A42C11A5CB4700862178 /* CommonCryptorPriv.h */; settings = {ATTRIBUTES = (); }; };
		48F7F2C712B2EF6000AF4587 /* CommonDigestPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A42D11A5CB4700862178 /* CommonDigestPriv.h */; };
		48F7F2C812B2EF6000AF4587 /* CommonKeyDerivationPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A43011A5CB4700862178 /* CommonKeyDerivationPriv.h */; };
		48F7F2C912B2EF6000AF4587 /* aesopt.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D5636611A652D7008EBBBF /* aesopt.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48F7F2CA12B2EF6000AF4587 /* aes.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D5636711A652D7008EBBBF /* aes.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48F7F2CB12B2EF6000AF4587 /* aestab.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D5636E11A652EB008EBBBF /* aestab.h */; };
		48F7F2CC12B2EF6000AF4587 /* AESAssembly.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D5637811A65316008EBBBF /* AESAssembly.h */; };
		48F7F2CE12B2EF6000AF4587 /* skein_ltc.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F09411BDA1D300946BBE /* skein_ltc.h */; };
		48F7F2CF12B2EF6000AF4587 /* skein.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F09E11BDA27200946BBE /* skein.h */; };
		48F7F2D012B2EF6000AF4587 /* skein_port.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A011BDA27200946BBE /* skein_port.h */; };
		48F7F2D112B2EF6000AF4587 /* skein_iv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A111BDA27200946BBE /* skein_iv.h */; };
		48F7F2D212B2EF6000AF4587 /* skein_dropin.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A211BDA27200946BBE /* skein_dropin.h */; };
		48F7F2D312B2EF6000AF4587 /* skein_debug.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A411BDA27200946BBE /* skein_debug.h */; };
		48F7F2D412B2EF6000AF4587 /* SHA3api_ref.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A711BDA27200946BBE /* SHA3api_ref.h */; };
		48F7F2D512B2EF6000AF4587 /* brg_types.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0A911BDA27200946BBE /* brg_types.h */; };
		48F7F2D612B2EF6000AF4587 /* brg_endian.h in Headers */ = {isa = PBXBuildFile; fileRef = 4862F0AA11BDA27200946BBE /* brg_endian.h */; };
		48F7F2D712B2EF6000AF4587 /* CommonRandomSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 12FA0DAF11F7962100917A4E /* CommonRandomSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48F7F2DC12B2EF6000AF4587 /* md2_dgst.c in Sources */ = {isa = PBXBuildFile; fileRef = 054BBED305F6AA8900344873 /* md2_dgst.c */; };
		48F7F2DD12B2EF6000AF4587 /* md4_dgst.c in Sources */ = {isa = PBXBuildFile; fileRef = 054BBED405F6AA8900344873 /* md4_dgst.c */; };
		48F7F2DE12B2EF6000AF4587 /* md5_dgst.c in Sources */ = {isa = PBXBuildFile; fileRef = 054BBED605F6AA8900344873 /* md5_dgst.c */; };
		48F7F2DF12B2EF6000AF4587 /* sha1.c in Sources */ = {isa = PBXBuildFile; fileRef = 054BBEDC05F6AA8900344873 /* sha1.c */; };
		48F7F2E012B2EF6000AF4587 /* sha2.c in Sources */ = {isa = PBXBuildFile; fileRef = 05E319B7063890C100C4AD24 /* sha2.c */; };
		48F7F2E112B2EF6000AF4587 /* set_key.c in Sources */ = {isa = PBXBuildFile; fileRef = 05ECA0ED09D469A100CFE5CB /* set_key.c */; };
		48F7F2E212B2EF6000AF4587 /* opensslDES.c in Sources */ = {isa = PBXBuildFile; fileRef = 0539DC2609D4919D00AB7F89 /* opensslDES.c */; };
		48F7F2E312B2EF6000AF4587 /* des_enc.c in Sources */ = {isa = PBXBuildFile; fileRef = 05ECA0E509D468E200CFE5CB /* des_enc.c */; };
		48F7F2E412B2EF6000AF4587 /* c_ecb.c in Sources */ = {isa = PBXBuildFile; fileRef = 0585FE1209DC9873001762F6 /* c_ecb.c */; };
		48F7F2E512B2EF6000AF4587 /* c_enc.c in Sources */ = {isa = PBXBuildFile; fileRef = 0585FE1309DC9873001762F6 /* c_enc.c */; };
		48F7F2E612B2EF6000AF4587 /* c_skey.c in Sources */ = {isa = PBXBuildFile; fileRef = 0585FE1409DC9873001762F6 /* c_skey.c */; };
		48F7F2E712B2EF6000AF4587 /* ccCast.c in Sources */ = {isa = PBXBuildFile; fileRef = 0585FE1809DC9873001762F6 /* ccCast.c */; };
		48F7F2E812B2EF6000AF4587 /* ccRC2.c in Sources */ = {isa = PBXBuildFile; fileRef = 795CA3FD0D34431400BAE6A2 /* ccRC2.c */; };
		48F7F2E912B2EF6000AF4587 /* rc2.c in Sources */ = {isa = PBXBuildFile; fileRef = 795CA3FE0D34431400BAE6A2 /* rc2.c */; };
		48F7F2EA12B2EF6000AF4587 /* cast5.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35311A4E47B00B5DDB3 /* cast5.c */; };
		48F7F2EB12B2EF6000AF4587 /* des.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35411A4E47B00B5DDB3 /* des.c */; };
		48F7F2EC12B2EF6000AF4587 /* rc2.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35511A4E47B00B5DDB3 /* rc2.c */; };
		48F7F2ED12B2EF6000AF4587 /* rc4_enc.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35811A4E47B00B5DDB3 /* rc4_enc.c */; };
		48F7F2EE12B2EF6000AF4587 /* rc4_skey.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35911A4E47B00B5DDB3 /* rc4_skey.c */; };
		48F7F2EF12B2EF6000AF4587 /* rc5.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35A11A4E47B00B5DDB3 /* rc5.c */; };
		48F7F2F012B2EF6000AF4587 /* hash_file.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35D11A4E47B00B5DDB3 /* hash_file.c */; };
		48F7F2F112B2EF6000AF4587 /* hash_filehandle.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35E11A4E47B00B5DDB3 /* hash_filehandle.c */; };
		48F7F2F212B2EF6000AF4587 /* hash_memory.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F35F11A4E47B00B5DDB3 /* hash_memory.c */; };
		48F7F2F312B2EF6000AF4587 /* hash_memory_multi.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36011A4E47B00B5DDB3 /* hash_memory_multi.c */; };
		48F7F2F412B2EF6000AF4587 /* md2.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36111A4E47B00B5DDB3 /* md2.c */; };
		48F7F2F512B2EF6000AF4587 /* md4.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36211A4E47B00B5DDB3 /* md4.c */; };
		48F7F2F612B2EF6000AF4587 /* md5.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36311A4E47B00B5DDB3 /* md5.c */; };
		48F7F2F712B2EF6000AF4587 /* rmd128.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36411A4E47B00B5DDB3 /* rmd128.c */; };
		48F7F2F812B2EF6000AF4587 /* rmd160.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36511A4E47B00B5DDB3 /* rmd160.c */; };
		48F7F2F912B2EF6000AF4587 /* rmd256.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36611A4E47B00B5DDB3 /* rmd256.c */; };
		48F7F2FA12B2EF6000AF4587 /* rmd320.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36711A4E47B00B5DDB3 /* rmd320.c */; };
		48F7F2FB12B2EF6000AF4587 /* sha1.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36811A4E47B00B5DDB3 /* sha1.c */; };
		48F7F2FC12B2EF6000AF4587 /* sha256.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36B11A4E47B00B5DDB3 /* sha256.c */; };
		48F7F2FD12B2EF6000AF4587 /* sha512.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F36D11A4E47B00B5DDB3 /* sha512.c */; };
		48F7F2FE12B2EF6000AF4587 /* crypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38311A4E47B00B5DDB3 /* crypt.c */; };
		48F7F2FF12B2EF6000AF4587 /* crypt_argchk.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38411A4E47B00B5DDB3 /* crypt_argchk.c */; };
		48F7F30012B2EF6000AF4587 /* crypt_cipher_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38511A4E47B00B5DDB3 /* crypt_cipher_descriptor.c */; };
		48F7F30112B2EF6000AF4587 /* crypt_cipher_is_valid.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38611A4E47B00B5DDB3 /* crypt_cipher_is_valid.c */; };
		48F7F30212B2EF6000AF4587 /* crypt_find_cipher.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38711A4E47B00B5DDB3 /* crypt_find_cipher.c */; };
		48F7F30312B2EF6000AF4587 /* crypt_find_cipher_any.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38811A4E47B00B5DDB3 /* crypt_find_cipher_any.c */; };
		48F7F30412B2EF6000AF4587 /* crypt_find_cipher_id.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38911A4E47B00B5DDB3 /* crypt_find_cipher_id.c */; };
		48F7F30512B2EF6000AF4587 /* crypt_find_hash.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38A11A4E47B00B5DDB3 /* crypt_find_hash.c */; };
		48F7F30612B2EF6000AF4587 /* crypt_find_hash_any.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38B11A4E47B00B5DDB3 /* crypt_find_hash_any.c */; };
		48F7F30712B2EF6000AF4587 /* crypt_find_hash_id.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38C11A4E47B00B5DDB3 /* crypt_find_hash_id.c */; };
		48F7F30812B2EF6000AF4587 /* crypt_find_hash_oid.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38D11A4E47B00B5DDB3 /* crypt_find_hash_oid.c */; };
		48F7F30912B2EF6000AF4587 /* crypt_find_prng.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F38E11A4E47B00B5DDB3 /* crypt_find_prng.c */; };
		48F7F30A12B2EF6000AF4587 /* crypt_hash_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39011A4E47B00B5DDB3 /* crypt_hash_descriptor.c */; };
		48F7F30B12B2EF6000AF4587 /* crypt_hash_is_valid.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39111A4E47B00B5DDB3 /* crypt_hash_is_valid.c */; };
		48F7F30C12B2EF6000AF4587 /* crypt_ltc_mp_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39211A4E47B00B5DDB3 /* crypt_ltc_mp_descriptor.c */; };
		48F7F30D12B2EF6000AF4587 /* crypt_mode_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39311A4E47B00B5DDB3 /* crypt_mode_descriptor.c */; };
		48F7F30E12B2EF6000AF4587 /* crypt_register_cipher.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39611A4E47B00B5DDB3 /* crypt_register_cipher.c */; };
		48F7F30F12B2EF6000AF4587 /* crypt_register_hash.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39711A4E47B00B5DDB3 /* crypt_register_hash.c */; };
		48F7F31012B2EF6000AF4587 /* crypt_unregister_cipher.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39911A4E47B00B5DDB3 /* crypt_unregister_cipher.c */; };
		48F7F31112B2EF6000AF4587 /* crypt_unregister_hash.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39A11A4E47B00B5DDB3 /* crypt_unregister_hash.c */; };
		48F7F31212B2EF6000AF4587 /* error_to_string.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F39C11A4E47B00B5DDB3 /* error_to_string.c */; };
		48F7F31312B2EF6000AF4587 /* zeromem.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A011A4E47B00B5DDB3 /* zeromem.c */; };
		48F7F31412B2EF6000AF4587 /* cbc_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A311A4E47B00B5DDB3 /* cbc_decrypt.c */; };
		48F7F31512B2EF6000AF4587 /* cbc_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A411A4E47B00B5DDB3 /* cbc_descriptor.c */; };
		48F7F31612B2EF6000AF4587 /* cbc_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A511A4E47B00B5DDB3 /* cbc_done.c */; };
		48F7F31712B2EF6000AF4587 /* cbc_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A611A4E47B00B5DDB3 /* cbc_encrypt.c */; };
		48F7F31812B2EF6000AF4587 /* cbc_getiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A711A4E47B00B5DDB3 /* cbc_getiv.c */; };
		48F7F31912B2EF6000AF4587 /* cbc_setiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A811A4E47B00B5DDB3 /* cbc_setiv.c */; };
		48F7F31A12B2EF6000AF4587 /* cbc_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3A911A4E47B00B5DDB3 /* cbc_start.c */; };
		48F7F31B12B2EF6000AF4587 /* cfb_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3AB11A4E47B00B5DDB3 /* cfb_decrypt.c */; };
		48F7F31C12B2EF6000AF4587 /* cfb_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3AC11A4E47B00B5DDB3 /* cfb_descriptor.c */; };
		48F7F31D12B2EF6000AF4587 /* cfb_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3AD11A4E47B00B5DDB3 /* cfb_done.c */; };
		48F7F31E12B2EF6000AF4587 /* cfb_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3AE11A4E47B00B5DDB3 /* cfb_encrypt.c */; };
		48F7F31F12B2EF6000AF4587 /* cfb_getiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3AF11A4E47B00B5DDB3 /* cfb_getiv.c */; };
		48F7F32012B2EF6000AF4587 /* cfb_setiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B011A4E47B00B5DDB3 /* cfb_setiv.c */; };
		48F7F32112B2EF6000AF4587 /* cfb_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B111A4E47B00B5DDB3 /* cfb_start.c */; };
		48F7F32212B2EF6000AF4587 /* ctr_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B311A4E47B00B5DDB3 /* ctr_decrypt.c */; };
		48F7F32312B2EF6000AF4587 /* ctr_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B411A4E47B00B5DDB3 /* ctr_descriptor.c */; };
		48F7F32412B2EF6000AF4587 /* ctr_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B511A4E47B00B5DDB3 /* ctr_done.c */; };
		48F7F32512B2EF6000AF4587 /* ctr_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B611A4E47B00B5DDB3 /* ctr_encrypt.c */; };
		48F7F32612B2EF6000AF4587 /* ctr_getiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B711A4E47B00B5DDB3 /* ctr_getiv.c */; };
		48F7F32712B2EF6000AF4587 /* ctr_setiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B811A4E47B00B5DDB3 /* ctr_setiv.c */; };
		48F7F32812B2EF6000AF4587 /* ctr_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3B911A4E47B00B5DDB3 /* ctr_start.c */; };
		48F7F32912B2EF6000AF4587 /* ctr_test.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3BA11A4E47B00B5DDB3 /* ctr_test.c */; };
		48F7F32A12B2EF6000AF4587 /* ecb_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3BC11A4E47B00B5DDB3 /* ecb_decrypt.c */; };
		48F7F32B12B2EF6000AF4587 /* ecb_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3BD11A4E47B00B5DDB3 /* ecb_descriptor.c */; };
		48F7F32C12B2EF6000AF4587 /* ecb_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3BE11A4E47B00B5DDB3 /* ecb_done.c */; };
		48F7F32D12B2EF6000AF4587 /* ecb_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3BF11A4E47B00B5DDB3 /* ecb_encrypt.c */; };
		48F7F32E12B2EF6000AF4587 /* ecb_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3C011A4E47B00B5DDB3 /* ecb_start.c */; };
		48F7F32F12B2EF6000AF4587 /* ofb_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3D511A4E47B00B5DDB3 /* ofb_decrypt.c */; };
		48F7F33012B2EF6000AF4587 /* ofb_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3D611A4E47B00B5DDB3 /* ofb_descriptor.c */; };
		48F7F33112B2EF6000AF4587 /* ofb_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3D711A4E47B00B5DDB3 /* ofb_done.c */; };
		48F7F33212B2EF6000AF4587 /* ofb_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3D811A4E47B00B5DDB3 /* ofb_encrypt.c */; };
		48F7F33312B2EF6000AF4587 /* ofb_getiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3D911A4E47B00B5DDB3 /* ofb_getiv.c */; };
		48F7F33412B2EF6000AF4587 /* ofb_setiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3DA11A4E47B00B5DDB3 /* ofb_setiv.c */; };
		48F7F33512B2EF6000AF4587 /* ofb_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3DB11A4E47B00B5DDB3 /* ofb_start.c */; };
		48F7F33612B2EF6000AF4587 /* rc4_stream.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3DC11A4E47B00B5DDB3 /* rc4_stream.c */; };
		48F7F33712B2EF6000AF4587 /* unimplemented.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3DD11A4E47B00B5DDB3 /* unimplemented.c */; };
		48F7F33812B2EF6000AF4587 /* xts_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3DF11A4E47B00B5DDB3 /* xts_decrypt.c */; };
		48F7F33912B2EF6000AF4587 /* xts_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E011A4E47B00B5DDB3 /* xts_descriptor.c */; };
		48F7F33A12B2EF6000AF4587 /* xts_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E111A4E47B00B5DDB3 /* xts_done.c */; };
		48F7F33B12B2EF6000AF4587 /* xts_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E211A4E47B00B5DDB3 /* xts_encrypt.c */; };
		48F7F33C12B2EF6000AF4587 /* xts_init.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E311A4E47B00B5DDB3 /* xts_init.c */; };
		48F7F33D12B2EF6000AF4587 /* xts_mult_x.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E411A4E47B00B5DDB3 /* xts_mult_x.c */; };
		48F7F33E12B2EF6000AF4587 /* xts_test.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E511A4E47B00B5DDB3 /* xts_test.c */; };
		48F7F33F12B2EF6000AF4587 /* ansi923pad.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3E811A4E47B00B5DDB3 /* ansi923pad.c */; };
		48F7F34012B2EF6000AF4587 /* iso10126pad.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3EB11A4E47B00B5DDB3 /* iso10126pad.c */; };
		48F7F34112B2EF6000AF4587 /* nopad.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3EE11A4E47B00B5DDB3 /* nopad.c */; };
		48F7F34212B2EF6000AF4587 /* pkcs7pad.c in Sources */ = {isa = PBXBuildFile; fileRef = 4873F3F111A4E47B00B5DDB3 /* pkcs7pad.c */; };
		48F7F34312B2EF6000AF4587 /* ccdebug.c in Sources */ = {isa = PBXBuildFile; fileRef = 489D982C11A4E8C20004DB89 /* ccdebug.c */; };
		48F7F34412B2EF6000AF4587 /* CommonCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42B11A5CB4700862178 /* CommonCryptor.c */; };
		48F7F34512B2EF6000AF4587 /* CommonHMAC.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42E11A5CB4700862178 /* CommonHMAC.c */; };
		48F7F34612B2EF6000AF4587 /* CommonKeyDerivation.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42F11A5CB4700862178 /* CommonKeyDerivation.c */; };
		48F7F34712B2EF6000AF4587 /* CommonSymmetricKeywrap.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A43111A5CB4700862178 /* CommonSymmetricKeywrap.c */; };
		48F7F34812B2EF6000AF4587 /* CommonDigest.c in Sources */ = {isa = PBXBuildFile; fileRef = 48096B2211A5EF900043F67F /* CommonDigest.c */; };
		48F7F34912B2EF6000AF4587 /* aescrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D5636B11A652EB008EBBBF /* aescrypt.c */; };
		48F7F34A12B2EF6000AF4587 /* aeskey.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D5636C11A652EB008EBBBF /* aeskey.c */; };
		48F7F34B12B2EF6000AF4587 /* aestab.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D5636D11A652EB008EBBBF /* aestab.c */; };
		48F7F34C12B2EF6000AF4587 /* ccNewGladman.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D5636F11A652EB008EBBBF /* ccNewGladman.c */; };
		48F7F34D12B2EF6000AF4587 /* AES.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D5637711A65316008EBBBF /* AES.c */; };
		48F7F34E12B2EF6000AF4587 /* AES.s in Sources */ = {isa = PBXBuildFile; fileRef = 48D5637B11A65316008EBBBF /* AES.s */; };
		48F7F34F12B2EF6000AF4587 /* DecryptCBC.s in Sources */ = {isa = PBXBuildFile; fileRef = 48D5637D11A65316008EBBBF /* DecryptCBC.s */; };
		48F7F35012B2EF6000AF4587 /* EncryptCBC.s in Sources */ = {isa = PBXBuildFile; fileRef = 48D5637E11A65316008EBBBF /* EncryptCBC.s */; };
		48F7F35712B2EF6000AF4587 /* skein_ltc.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F09511BDA1D300946BBE /* skein_ltc.c */; };
		48F7F35812B2EF6000AF4587 /* skein.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F09F11BDA27200946BBE /* skein.c */; };
		48F7F35912B2EF6000AF4587 /* skein_dropin.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F0A311BDA27200946BBE /* skein_dropin.c */; };
		48F7F35A12B2EF6000AF4587 /* skein_debug.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F0A511BDA27200946BBE /* skein_debug.c */; };
		48F7F35B12B2EF6000AF4587 /* skein_block.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F0A611BDA27200946BBE /* skein_block.c */; };
		48F7F35C12B2EF6000AF4587 /* SHA3api_ref.c in Sources */ = {isa = PBXBuildFile; fileRef = 4862F0A811BDA27200946BBE /* SHA3api_ref.c */; };
		48F7F35D12B2EF6000AF4587 /* CommonRandom.c in Sources */ = {isa = PBXBuildFile; fileRef = 12FA0DB111F7964700917A4E /* CommonRandom.c */; };
		48F7F36212B2EF6000AF4587 /* cfb8_decrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340112270E8900F9C9E1 /* cfb8_decrypt.c */; };
		48F7F36312B2EF6000AF4587 /* cfb8_descriptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340212270E8900F9C9E1 /* cfb8_descriptor.c */; };
		48F7F36412B2EF6000AF4587 /* cfb8_done.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340312270E8900F9C9E1 /* cfb8_done.c */; };
		48F7F36512B2EF6000AF4587 /* cfb8_encrypt.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340412270E8900F9C9E1 /* cfb8_encrypt.c */; };
		48F7F36612B2EF6000AF4587 /* cfb8_getiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340512270E8900F9C9E1 /* cfb8_getiv.c */; };
		48F7F36712B2EF6000AF4587 /* cfb8_setiv.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340612270E8900F9C9E1 /* cfb8_setiv.c */; };
		48F7F36812B2EF6000AF4587 /* cfb8_start.c in Sources */ = {isa = PBXBuildFile; fileRef = 1249340712270E8900F9C9E1 /* cfb8_start.c */; };
		48F7F37A12B2F05A00AF4587 /* aes.c in Sources */ = {isa = PBXBuildFile; fileRef = 48F7F37712B2F05A00AF4587 /* aes.c */; };
		48F7F37B12B2F05A00AF4587 /* aes_tab.c in Sources */ = {isa = PBXBuildFile; fileRef = 48F7F37812B2F05A00AF4587 /* aes_tab.c */; };
		48F7F37C12B2F05A00AF4587 /* ltc_aes.h in Headers */ = {isa = PBXBuildFile; fileRef = 48F7F37912B2F05A00AF4587 /* ltc_aes.h */; };
		5302E41F1343E367003037FA /* CommonCMAC.c in Sources */ = {isa = PBXBuildFile; fileRef = 53B9FDE81343DD0600CA1154 /* CommonCMAC.c */; };
		5302E4201343E3CE003037FA /* CommonCMACSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 53B9FDED1343DDB700CA1154 /* CommonCMACSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		5D113BE01106452100B412A2 /* CommonCryptoUnitTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5D113BD61106452100B412A2 /* CommonCryptoUnitTests.mm */; };
		5DAD82CF1279DF2B00240B9A /* DigestTest.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5D113BD81106452100B412A2 /* DigestTest.mm */; };
		5DAD82D01279DF2B00240B9A /* EncryptionTest.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5D113BDA1106452100B412A2 /* EncryptionTest.mm */; };
		5DAD82D11279DF2B00240B9A /* HMACTest.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5D113BDC1106452100B412A2 /* HMACTest.mm */; };
		5DAD82D21279DF2B00240B9A /* RandomNumberService.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5D113BDE1106452100B412A2 /* RandomNumberService.mm */; };
		5DAD82D31279DF2B00240B9A /* PBKDFTest.mm in Sources */ = {isa = PBXBuildFile; fileRef = 4882005C111AAD7A00798F94 /* PBKDFTest.mm */; };
		5DAD82D41279DF2B00240B9A /* SymmetricWrapTest.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5D57A808111B5DDE008CA573 /* SymmetricWrapTest.mm */; };
		5DAD82E11279DF7A00240B9A /* libCommonCryptoUnitTest.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DAD82CC1279DEF900240B9A /* libCommonCryptoUnitTest.a */; };
		5DAD839F1279F22C00240B9A /* libCommonCryptoUnitTest.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DAD82CC1279DEF900240B9A /* libCommonCryptoUnitTest.a */; };
		5DAD83A11279F26700240B9A /* System.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4857A13011BDA737001F5A9A /* System.framework */; };
		5DAD83A31279F29300240B9A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DAD83A21279F29300240B9A /* Foundation.framework */; };
		5DAD83A61279F29800240B9A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DAD83A21279F29300240B9A /* Foundation.framework */; };
		5DAD83AF1279F4C400240B9A /* main.mm in Sources */ = {isa = PBXBuildFile; fileRef = 5DAD83A71279F2B200240B9A /* main.mm */; };
		795CA41E0D34459D00BAE6A2 /* ccRC2.c in Sources */ = {isa = PBXBuildFile; fileRef = 795CA3FD0D34431400BAE6A2 /* ccRC2.c */; };
		795CA41F0D34459D00BAE6A2 /* rc2.c in Sources */ = {isa = PBXBuildFile; fileRef = 795CA3FE0D34431400BAE6A2 /* rc2.c */; };
		AAAF0B9E0DC7A3DA0044DA03 /* sha1edpBigEndian.s in Sources */ = {isa = PBXBuildFile; fileRef = AAB5CBCD0DC6AB6D0019E0E6 /* sha1edpBigEndian.s */; };
		AAAF0B9F0DC7A3DA0044DA03 /* sha1edpLittleEndian.s in Sources */ = {isa = PBXBuildFile; fileRef = AAB5CBCE0DC6AB6D0019E0E6 /* sha1edpLittleEndian.s */; };
		D6658D950BD8178400D18063 /* CC_crypto.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 05DF6D1109CF2D7200D9A3E8 /* CC_crypto.3cc */; };
		D6658D960BD8178400D18063 /* CC_MD2.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5B60BC6D67000878B42 /* CC_MD2.3cc */; };
		D6658D970BD8178400D18063 /* CC_MD2_Final.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5B70BC6D67000878B42 /* CC_MD2_Final.3cc */; };
		D6658D980BD8178400D18063 /* CC_MD2_Init.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5B80BC6D67000878B42 /* CC_MD2_Init.3cc */; };
		D6658D990BD8178400D18063 /* CC_MD2_Update.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5B90BC6D67000878B42 /* CC_MD2_Update.3cc */; };
		D6658D9A0BD8178400D18063 /* CC_MD4.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5BA0BC6D67000878B42 /* CC_MD4.3cc */; };
		D6658D9B0BD8178400D18063 /* CC_MD4_Final.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5BB0BC6D67000878B42 /* CC_MD4_Final.3cc */; };







|

|



|
>
>
>
>
>
>
>
>
>
>
>
|

|
|





<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|
<

>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
>
>
>
>
>
|
|
>
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|

|



<



>
>
>
>
>


<
|
<
|
|
|
<
|
<
|
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
|
<
|
<
|


<
<
|
|
|
|
<
|
|
|
|
|
<
<
<
<
<
<
<
<
|
|
<
<
<
<
<
<
<
<
<
|
|
<
<
<
<
|
|
|
<
<
<
|
<
<
<
|
|
|
<
<
<
|
|
|
<
<
|
<
<
|
<
<
<
<
<
<
<
|
<
|
|
|
|
<
<
<
<
<
<
<
<
<
|
|
<
<
<
<
<
<
<
<
<
|
|
|
|
|
|
|
<
<
<
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|
<
|
|
|
|
|
|
<
|
|
|
|
|
|
<
|
|
|
|
<
<
|
<
|
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|
|
<
<
|
|
|
|
|
<
<
<
|
|
|
<
|
|
<
<
<
|
<
<
<
<
|
|
<
|
<
|
<
<
|
|
|
|
|
<
<
<
|
<
|
<
<
<
<
<
<
<
|
|
<
<







28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

62




















63
64
65























66
67

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166

167
168
169
170
171
172
173
174
175
176

177

178
179
180

181

182





183

























































184
185

186
187
188







































189

190

191

192
193
194


195
196
197
198

199
200
201
202
203








204
205









206
207




208
209
210



211



212
213
214



215
216
217


218


219







220

221
222
223
224









225
226









227
228
229
230
231
232
233



234
235
236
237
238
239
240
241
242
243
244




















245
246
247
248

249
250
251
252
253
254

255
256
257
258
259
260

261
262
263
264


265

266











267
268
269
270
271


272
273
274
275
276



277
278
279

280
281



282




283
284

285

286


287
288
289
290
291



292

293







294
295


296
297
298
299
300
301
302
				05CE942F0A37850A007C91D6 /* CopyFiles */,
			);
			dependencies = (
			);
			name = "Copy Open Source Docs";
			productName = "Copy Open Source Docs";
		};
		4C99FCB61326E14F0040AD38 /* commonCryptoMacIOS */ = {
			isa = PBXAggregateTarget;
			buildConfigurationList = 4C99FCB71326E14F0040AD38 /* Build configuration list for PBXAggregateTarget "commonCryptoMacIOS" */;
			buildPhases = (
			);
			dependencies = (
				4C58A28D13281C2100A17BAC /* PBXTargetDependency */,
			);
			name = commonCryptoMacIOS;
			productName = FIPSModeIOS;
		};
		4CA675141332C16C00C45A71 /* CommonCrypto_Sim */ = {
			isa = PBXAggregateTarget;
			buildConfigurationList = 4CA675151332C16C00C45A71 /* Build configuration list for PBXAggregateTarget "CommonCrypto_Sim" */;
			buildPhases = (
				4CA6751A1332C18C00C45A71 /* ShellScript */,
			);
			dependencies = (
				4CA675191332C17900C45A71 /* PBXTargetDependency */,
			);
			name = CommonCrypto_Sim;
			productName = commonCryptoMacIOSSim;
		};
/* End PBXAggregateTarget section */

/* Begin PBXBuildFile section */
		0511C47E0A37892C0028BFC3 /* CommonCrypto.txt in CopyFiles */ = {isa = PBXBuildFile; fileRef = 05CE942C0A37850A007C91D6 /* CommonCrypto.txt */; };

		054BBECE05F6AA7200344873 /* CommonDigest.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBECD05F6AA7200344873 /* CommonDigest.h */; settings = {ATTRIBUTES = (Public, ); }; };




















		05CE942D0A37850A007C91D6 /* CommonCrypto.plist in CopyFiles */ = {isa = PBXBuildFile; fileRef = 05CE942B0A37850A007C91D6 /* CommonCrypto.plist */; };
		05D8D97D09E411AB00E03504 /* CommonHMAC.h in Headers */ = {isa = PBXBuildFile; fileRef = 05D8D97C09E411AA00E03504 /* CommonHMAC.h */; settings = {ATTRIBUTES = (Public, ); }; };
		05D9F61909D85F4A00AD30A7 /* CommonCryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 05D9F61609D85F4A00AD30A7 /* CommonCryptor.h */; settings = {ATTRIBUTES = (Public, ); }; };























		12FA0DB011F7962100917A4E /* CommonRandomSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 12FA0DAF11F7962100917A4E /* CommonRandomSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48067F871362405D005DDEBC /* CommonCryptoAESShoefly.c in Sources */ = {isa = PBXBuildFile; fileRef = 48685586127B641800B88D39 /* CommonCryptoAESShoefly.c */; };

		48096B2311A5EF900043F67F /* CommonDigest.c in Sources */ = {isa = PBXBuildFile; fileRef = 48096B2211A5EF900043F67F /* CommonDigest.c */; };
		48165CD9125AC5D50015A267 /* CommonDigest.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBECD05F6AA7200344873 /* CommonDigest.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48165CDA125AC5D50015A267 /* CommonCryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 05D9F61609D85F4A00AD30A7 /* CommonCryptor.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48165CDB125AC5D50015A267 /* CommonHMAC.h in Headers */ = {isa = PBXBuildFile; fileRef = 05D8D97C09E411AA00E03504 /* CommonHMAC.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48165CDC125AC5D50015A267 /* CommonKeyDerivation.h in Headers */ = {isa = PBXBuildFile; fileRef = 4854F9C01116307500CAFA18 /* CommonKeyDerivation.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48165CDD125AC5D50015A267 /* CommonSymmetricKeywrap.h in Headers */ = {isa = PBXBuildFile; fileRef = 4854F9C11116307500CAFA18 /* CommonSymmetricKeywrap.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48165CF0125AC5D50015A267 /* ccdebug.h in Headers */ = {isa = PBXBuildFile; fileRef = 489D982D11A4E8C20004DB89 /* ccdebug.h */; };
		48165CF1125AC5D50015A267 /* CommonCryptorSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 4846CA5411A5C8B800E7DA82 /* CommonCryptorSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48165CF2125AC5D50015A267 /* CommonDigestSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 4846CA5511A5C8B800E7DA82 /* CommonDigestSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48165CF3125AC5D50015A267 /* CommonCryptoPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41A11A5C94A00862178 /* CommonCryptoPriv.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48165CF4125AC5D50015A267 /* CommonCryptorPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A42C11A5CB4700862178 /* CommonCryptorPriv.h */; settings = {ATTRIBUTES = (); }; };
		48165CF5125AC5D50015A267 /* CommonDigestPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A42D11A5CB4700862178 /* CommonDigestPriv.h */; };
		48165CF7125AC5D50015A267 /* CommonRandomSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 12FA0DAF11F7962100917A4E /* CommonRandomSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48165D78125AC5D50015A267 /* ccdebug.c in Sources */ = {isa = PBXBuildFile; fileRef = 489D982C11A4E8C20004DB89 /* ccdebug.c */; };
		48165D79125AC5D50015A267 /* CommonCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42B11A5CB4700862178 /* CommonCryptor.c */; };
		48165D7A125AC5D50015A267 /* CommonHMAC.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42E11A5CB4700862178 /* CommonHMAC.c */; };
		48165D7B125AC5D50015A267 /* CommonKeyDerivation.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42F11A5CB4700862178 /* CommonKeyDerivation.c */; };
		48165D7C125AC5D50015A267 /* CommonSymmetricKeywrap.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A43111A5CB4700862178 /* CommonSymmetricKeywrap.c */; };
		48165D7D125AC5D50015A267 /* CommonDigest.c in Sources */ = {isa = PBXBuildFile; fileRef = 48096B2211A5EF900043F67F /* CommonDigest.c */; };
		48165DBC125AC5F20015A267 /* CommonDigest.h in Headers */ = {isa = PBXBuildFile; fileRef = 054BBECD05F6AA7200344873 /* CommonDigest.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48165DBD125AC5F20015A267 /* CommonCryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 05D9F61609D85F4A00AD30A7 /* CommonCryptor.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48165DBE125AC5F20015A267 /* CommonHMAC.h in Headers */ = {isa = PBXBuildFile; fileRef = 05D8D97C09E411AA00E03504 /* CommonHMAC.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48165DBF125AC5F20015A267 /* CommonKeyDerivation.h in Headers */ = {isa = PBXBuildFile; fileRef = 4854F9C01116307500CAFA18 /* CommonKeyDerivation.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48165DC0125AC5F20015A267 /* CommonSymmetricKeywrap.h in Headers */ = {isa = PBXBuildFile; fileRef = 4854F9C11116307500CAFA18 /* CommonSymmetricKeywrap.h */; settings = {ATTRIBUTES = (Public, ); }; };
		48165DD3125AC5F20015A267 /* ccdebug.h in Headers */ = {isa = PBXBuildFile; fileRef = 489D982D11A4E8C20004DB89 /* ccdebug.h */; };
		48165DD4125AC5F20015A267 /* CommonCryptorSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 4846CA5411A5C8B800E7DA82 /* CommonCryptorSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48165DD5125AC5F20015A267 /* CommonDigestSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 4846CA5511A5C8B800E7DA82 /* CommonDigestSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48165DD6125AC5F20015A267 /* CommonCryptoPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41A11A5C94A00862178 /* CommonCryptoPriv.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48165DD7125AC5F20015A267 /* CommonCryptorPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A42C11A5CB4700862178 /* CommonCryptorPriv.h */; settings = {ATTRIBUTES = (); }; };
		48165DD8125AC5F20015A267 /* CommonDigestPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A42D11A5CB4700862178 /* CommonDigestPriv.h */; };
		48165DDA125AC5F20015A267 /* CommonRandomSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 12FA0DAF11F7962100917A4E /* CommonRandomSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48165E5B125AC5F20015A267 /* ccdebug.c in Sources */ = {isa = PBXBuildFile; fileRef = 489D982C11A4E8C20004DB89 /* ccdebug.c */; };
		48165E5C125AC5F20015A267 /* CommonCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42B11A5CB4700862178 /* CommonCryptor.c */; };
		48165E5D125AC5F20015A267 /* CommonHMAC.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42E11A5CB4700862178 /* CommonHMAC.c */; };
		48165E5E125AC5F20015A267 /* CommonKeyDerivation.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42F11A5CB4700862178 /* CommonKeyDerivation.c */; };
		48165E5F125AC5F20015A267 /* CommonSymmetricKeywrap.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A43111A5CB4700862178 /* CommonSymmetricKeywrap.c */; };
		48165E60125AC5F20015A267 /* CommonDigest.c in Sources */ = {isa = PBXBuildFile; fileRef = 48096B2211A5EF900043F67F /* CommonDigest.c */; };
		4823B0EA14C1013F008F689F /* CCCryptorTestFuncs.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0AE14C10022008F689F /* CCCryptorTestFuncs.c */; };
		4823B0EC14C1013F008F689F /* CommonBaseEncoding.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B014C10022008F689F /* CommonBaseEncoding.c */; };
		4823B0ED14C1013F008F689F /* CommonBigNum.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B114C10022008F689F /* CommonBigNum.c */; };
		4823B0EE14C1013F008F689F /* CommonCMac.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B214C10022008F689F /* CommonCMac.c */; };
		4823B0EF14C1013F008F689F /* CommonCryptoCTSPadding.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B314C10022008F689F /* CommonCryptoCTSPadding.c */; };
		4823B0F014C1013F008F689F /* CommonCryptoSymCBC.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B414C10022008F689F /* CommonCryptoSymCBC.c */; };
		4823B0F114C1013F008F689F /* CommonCryptoSymGCM.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B514C10022008F689F /* CommonCryptoSymGCM.c */; };
		4823B0F214C1013F008F689F /* CommonCryptoSymmetricWrap.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B614C10022008F689F /* CommonCryptoSymmetricWrap.c */; };
		4823B0F314C1013F008F689F /* CommonCryptoSymOFB.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B714C10022008F689F /* CommonCryptoSymOFB.c */; };
		4823B0F414C1013F008F689F /* CommonCryptoSymOffset.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B814C10022008F689F /* CommonCryptoSymOffset.c */; };
		4823B0F514C1013F008F689F /* CommonCryptoSymRC2.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B914C10022008F689F /* CommonCryptoSymRC2.c */; };
		4823B0F614C1013F008F689F /* CommonCryptoSymRegression.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BA14C10022008F689F /* CommonCryptoSymRegression.c */; };
		4823B0F714C1013F008F689F /* CommonCryptoSymXTS.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BB14C10022008F689F /* CommonCryptoSymXTS.c */; };
		4823B0F814C1013F008F689F /* CommonCryptoSymZeroLength.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BC14C10022008F689F /* CommonCryptoSymZeroLength.c */; };
		4823B0F914C1013F008F689F /* CommonDigest.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BD14C10022008F689F /* CommonDigest.c */; };
		4823B0FA14C1013F008F689F /* CommonEC.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BE14C10022008F689F /* CommonEC.c */; };
		4823B0FB14C1013F008F689F /* CommonHMacClone.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BF14C10022008F689F /* CommonHMacClone.c */; };
		4823B0FC14C1013F008F689F /* CommonRandom.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0C014C10022008F689F /* CommonRandom.c */; };
		4823B0FD14C1013F008F689F /* CommonRSA.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0C114C10022008F689F /* CommonRSA.c */; };
		4823B0FF14C1013F008F689F /* CryptorPadFailure.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0C314C10022008F689F /* CryptorPadFailure.c */; };
		4823B10014C10155008F689F /* main.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0C814C10022008F689F /* main.c */; };
		4823B10214C1016B008F689F /* testenv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0D014C10022008F689F /* testenv.c */; };
		4823B10414C1016B008F689F /* testlist.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0D214C10022008F689F /* testlist.c */; };
		4823B10714C1016B008F689F /* testmore.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0D514C10022008F689F /* testmore.c */; };
		4823B10914C1017C008F689F /* testbyteBuffer.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0D814C10022008F689F /* testbyteBuffer.c */; };
		4825AAF61314CDCD00413A64 /* CommonBigNum.h in Headers */ = {isa = PBXBuildFile; fileRef = 4825AAF31314CDCD00413A64 /* CommonBigNum.h */; settings = {ATTRIBUTES = (Private, ); }; };
		4825AAF71314CDCD00413A64 /* CommonBigNum.h in Headers */ = {isa = PBXBuildFile; fileRef = 4825AAF31314CDCD00413A64 /* CommonBigNum.h */; settings = {ATTRIBUTES = (Private, ); }; };
		4825AAF81314CDCD00413A64 /* CommonBigNum.h in Headers */ = {isa = PBXBuildFile; fileRef = 4825AAF31314CDCD00413A64 /* CommonBigNum.h */; settings = {ATTRIBUTES = (Private, ); }; };
		4834A85314F47A9400438E3D /* libcorecrypto.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 4834A85214F47A9400438E3D /* libcorecrypto.dylib */; };
		4834A85814F47B6200438E3D /* testbyteBuffer.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0D814C10022008F689F /* testbyteBuffer.c */; };
		4834A85C14F47B6200438E3D /* testenv.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0D014C10022008F689F /* testenv.c */; };
		4834A85E14F47B6200438E3D /* testlist.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0D214C10022008F689F /* testlist.c */; };
		4834A86114F47B6200438E3D /* testmore.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0D514C10022008F689F /* testmore.c */; };
		4834A86314F47B6200438E3D /* main.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0C814C10022008F689F /* main.c */; };
		4834A86414F47B6200438E3D /* CCCryptorTestFuncs.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0AE14C10022008F689F /* CCCryptorTestFuncs.c */; };
		4834A86614F47B6200438E3D /* CommonBaseEncoding.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B014C10022008F689F /* CommonBaseEncoding.c */; };
		4834A86714F47B6200438E3D /* CommonBigNum.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B114C10022008F689F /* CommonBigNum.c */; };
		4834A86814F47B6200438E3D /* CommonCMac.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B214C10022008F689F /* CommonCMac.c */; };
		4834A86914F47B6200438E3D /* CommonCryptoCTSPadding.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B314C10022008F689F /* CommonCryptoCTSPadding.c */; };
		4834A86A14F47B6200438E3D /* CommonCryptoSymCBC.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B414C10022008F689F /* CommonCryptoSymCBC.c */; };
		4834A86B14F47B6200438E3D /* CommonCryptoSymGCM.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B514C10022008F689F /* CommonCryptoSymGCM.c */; };
		4834A86C14F47B6200438E3D /* CommonCryptoSymmetricWrap.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B614C10022008F689F /* CommonCryptoSymmetricWrap.c */; };
		4834A86D14F47B6200438E3D /* CommonCryptoSymOFB.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B714C10022008F689F /* CommonCryptoSymOFB.c */; };
		4834A86E14F47B6200438E3D /* CommonCryptoSymOffset.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B814C10022008F689F /* CommonCryptoSymOffset.c */; };
		4834A86F14F47B6200438E3D /* CommonCryptoSymRC2.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0B914C10022008F689F /* CommonCryptoSymRC2.c */; };
		4834A87014F47B6200438E3D /* CommonCryptoSymRegression.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BA14C10022008F689F /* CommonCryptoSymRegression.c */; };
		4834A87114F47B6200438E3D /* CommonCryptoSymXTS.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BB14C10022008F689F /* CommonCryptoSymXTS.c */; };
		4834A87214F47B6200438E3D /* CommonCryptoSymZeroLength.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BC14C10022008F689F /* CommonCryptoSymZeroLength.c */; };
		4834A87314F47B6200438E3D /* CommonDigest.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BD14C10022008F689F /* CommonDigest.c */; };
		4834A87414F47B6200438E3D /* CommonEC.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BE14C10022008F689F /* CommonEC.c */; };
		4834A87514F47B6200438E3D /* CommonHMacClone.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0BF14C10022008F689F /* CommonHMacClone.c */; };
		4834A87614F47B6200438E3D /* CommonRandom.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0C014C10022008F689F /* CommonRandom.c */; };
		4834A87714F47B6200438E3D /* CommonRSA.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0C114C10022008F689F /* CommonRSA.c */; };
		4834A87814F47B6200438E3D /* CryptorPadFailure.c in Sources */ = {isa = PBXBuildFile; fileRef = 4823B0C314C10022008F689F /* CryptorPadFailure.c */; };
		4834A87914F47B6200438E3D /* CommonCryptoReset.c in Sources */ = {isa = PBXBuildFile; fileRef = 486BE17C14E6019B00346AC4 /* CommonCryptoReset.c */; };
		4834A88214F47C9A00438E3D /* libcommonCrypto.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 054BBEBE05F6A97700344873 /* libcommonCrypto.dylib */; };
		4836A42111A5C94A00862178 /* CommonCryptoPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A41A11A5C94A00862178 /* CommonCryptoPriv.h */; settings = {ATTRIBUTES = (Private, ); }; };
		4836A43211A5CB4700862178 /* CommonCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42B11A5CB4700862178 /* CommonCryptor.c */; };
		4836A43311A5CB4700862178 /* CommonCryptorPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A42C11A5CB4700862178 /* CommonCryptorPriv.h */; settings = {ATTRIBUTES = (Private, ); }; };
		4836A43411A5CB4700862178 /* CommonDigestPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 4836A42D11A5CB4700862178 /* CommonDigestPriv.h */; };
		4836A43511A5CB4700862178 /* CommonHMAC.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42E11A5CB4700862178 /* CommonHMAC.c */; };
		4836A43611A5CB4700862178 /* CommonKeyDerivation.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A42F11A5CB4700862178 /* CommonKeyDerivation.c */; };

		4836A43811A5CB4700862178 /* CommonSymmetricKeywrap.c in Sources */ = {isa = PBXBuildFile; fileRef = 4836A43111A5CB4700862178 /* CommonSymmetricKeywrap.c */; };
		4846CA5611A5C8B800E7DA82 /* CommonCryptorSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 4846CA5411A5C8B800E7DA82 /* CommonCryptorSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		4846CA5711A5C8B800E7DA82 /* CommonDigestSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 4846CA5511A5C8B800E7DA82 /* CommonDigestSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		484D40FF14DC96A600C93734 /* libcorecrypto.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 484D40FE14DC96A600C93734 /* libcorecrypto.dylib */; };
		4852C24A1505F8CD00676BCC /* CommonCryptoSymCFB.c in Sources */ = {isa = PBXBuildFile; fileRef = 4852C2491505F8CD00676BCC /* CommonCryptoSymCFB.c */; };
		4852C24B1505F8CD00676BCC /* CommonCryptoSymCFB.c in Sources */ = {isa = PBXBuildFile; fileRef = 4852C2491505F8CD00676BCC /* CommonCryptoSymCFB.c */; };
		4854BAD6152177CC007B5B08 /* CommonCryptoSymCTR.c in Sources */ = {isa = PBXBuildFile; fileRef = 4854BAD5152177CC007B5B08 /* CommonCryptoSymCTR.c */; };
		4854BAD7152177CC007B5B08 /* CommonCryptoSymCTR.c in Sources */ = {isa = PBXBuildFile; fileRef = 4854BAD5152177CC007B5B08 /* CommonCryptoSymCTR.c */; };
		4854F9C21116307500CAFA18 /* CommonKeyDerivation.h in Headers */ = {isa = PBXBuildFile; fileRef = 4854F9C01116307500CAFA18 /* CommonKeyDerivation.h */; settings = {ATTRIBUTES = (Public, ); }; };
		4854F9C31116307500CAFA18 /* CommonSymmetricKeywrap.h in Headers */ = {isa = PBXBuildFile; fileRef = 4854F9C11116307500CAFA18 /* CommonSymmetricKeywrap.h */; settings = {ATTRIBUTES = (Public, ); }; };

		485FED50131475A400FF0F82 /* CommonBigNumPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 485FED4A131475A400FF0F82 /* CommonBigNumPriv.h */; };

		485FED51131475A400FF0F82 /* CommonBigNum.c in Sources */ = {isa = PBXBuildFile; fileRef = 485FED4B131475A400FF0F82 /* CommonBigNum.c */; };
		485FED54131475A400FF0F82 /* CommonBigNumPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 485FED4A131475A400FF0F82 /* CommonBigNumPriv.h */; };
		485FED55131475A400FF0F82 /* CommonBigNum.c in Sources */ = {isa = PBXBuildFile; fileRef = 485FED4B131475A400FF0F82 /* CommonBigNum.c */; };

		485FED56131475A400FF0F82 /* CommonBigNumPriv.h in Headers */ = {isa = PBXBuildFile; fileRef = 485FED4A131475A400FF0F82 /* CommonBigNumPriv.h */; };

		485FED57131475A400FF0F82 /* CommonBigNum.c in Sources */ = {isa = PBXBuildFile; fileRef = 485FED4B131475A400FF0F82 /* CommonBigNum.c */; };





		48685584127B63F200B88D39 /* aes.h in Headers */ = {isa = PBXBuildFile; fileRef = 48685583127B63F200B88D39 /* aes.h */; settings = {ATTRIBUTES = (Private, ); }; };

























































		48685587127B641800B88D39 /* CommonCryptoAESShoefly.c in Sources */ = {isa = PBXBuildFile; fileRef = 48685586127B641800B88D39 /* CommonCryptoAESShoefly.c */; };
		4868BB1414B7C7F300072488 /* corecryptoSymmetricBridge.h in Headers */ = {isa = PBXBuildFile; fileRef = 4868BB1314B7C7F300072488 /* corecryptoSymmetricBridge.h */; };

		4868BB1514B7C7F300072488 /* corecryptoSymmetricBridge.h in Headers */ = {isa = PBXBuildFile; fileRef = 4868BB1314B7C7F300072488 /* corecryptoSymmetricBridge.h */; };
		4868BB1614B7C7F300072488 /* corecryptoSymmetricBridge.h in Headers */ = {isa = PBXBuildFile; fileRef = 4868BB1314B7C7F300072488 /* corecryptoSymmetricBridge.h */; };
		486BE17D14E6019B00346AC4 /* CommonCryptoReset.c in Sources */ = {isa = PBXBuildFile; fileRef = 486BE17C14E6019B00346AC4 /* CommonCryptoReset.c */; };







































		4873A7281445099D0011B4FA /* CommonCrypto.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873A7271445099D0011B4FA /* CommonCrypto.h */; settings = {ATTRIBUTES = (Public, ); }; };

		4873A72A1445099D0011B4FA /* CommonCrypto.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873A7271445099D0011B4FA /* CommonCrypto.h */; settings = {ATTRIBUTES = (Public, ); }; };

		4873A72B1445099D0011B4FA /* CommonCrypto.h in Headers */ = {isa = PBXBuildFile; fileRef = 4873A7271445099D0011B4FA /* CommonCrypto.h */; settings = {ATTRIBUTES = (Public, ); }; };

		488FCCB3139D6DD7007F2FC4 /* aes.h in Headers */ = {isa = PBXBuildFile; fileRef = 48685583127B63F200B88D39 /* aes.h */; settings = {ATTRIBUTES = (Private, ); }; };
		489D982E11A4E8C20004DB89 /* ccdebug.c in Sources */ = {isa = PBXBuildFile; fileRef = 489D982C11A4E8C20004DB89 /* ccdebug.c */; };
		489D982F11A4E8C20004DB89 /* ccdebug.h in Headers */ = {isa = PBXBuildFile; fileRef = 489D982D11A4E8C20004DB89 /* ccdebug.h */; };


		489E06F914B7AB0900B0A282 /* corecryptoSymmetricBridge.c in Sources */ = {isa = PBXBuildFile; fileRef = 489E06F814B7AB0800B0A282 /* corecryptoSymmetricBridge.c */; };
		489E06FA14B7AB0900B0A282 /* corecryptoSymmetricBridge.c in Sources */ = {isa = PBXBuildFile; fileRef = 489E06F814B7AB0800B0A282 /* corecryptoSymmetricBridge.c */; };
		489E06FB14B7AB0900B0A282 /* corecryptoSymmetricBridge.c in Sources */ = {isa = PBXBuildFile; fileRef = 489E06F814B7AB0800B0A282 /* corecryptoSymmetricBridge.c */; };
		489EECB1149809A800B44D5A /* asn1Types.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA2149809A800B44D5A /* asn1Types.h */; };

		489EECB2149809A800B44D5A /* asn1Types.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA2149809A800B44D5A /* asn1Types.h */; };
		489EECB3149809A800B44D5A /* asn1Types.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA2149809A800B44D5A /* asn1Types.h */; };
		489EECB4149809A800B44D5A /* DER_CertCrl.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA3149809A800B44D5A /* DER_CertCrl.c */; };
		489EECB5149809A800B44D5A /* DER_CertCrl.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA3149809A800B44D5A /* DER_CertCrl.c */; };
		489EECB6149809A800B44D5A /* DER_CertCrl.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA3149809A800B44D5A /* DER_CertCrl.c */; };








		489EECB7149809A800B44D5A /* DER_CertCrl.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA4149809A800B44D5A /* DER_CertCrl.h */; };
		489EECB8149809A800B44D5A /* DER_CertCrl.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA4149809A800B44D5A /* DER_CertCrl.h */; };









		489EECB9149809A800B44D5A /* DER_CertCrl.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA4149809A800B44D5A /* DER_CertCrl.h */; };
		489EECBA149809A800B44D5A /* DER_Decode.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA5149809A800B44D5A /* DER_Decode.c */; };




		489EECBB149809A800B44D5A /* DER_Decode.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA5149809A800B44D5A /* DER_Decode.c */; };
		489EECBC149809A800B44D5A /* DER_Decode.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA5149809A800B44D5A /* DER_Decode.c */; };
		489EECBD149809A800B44D5A /* DER_Decode.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA6149809A800B44D5A /* DER_Decode.h */; };



		489EECBE149809A800B44D5A /* DER_Decode.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA6149809A800B44D5A /* DER_Decode.h */; };



		489EECBF149809A800B44D5A /* DER_Decode.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA6149809A800B44D5A /* DER_Decode.h */; };
		489EECC0149809A800B44D5A /* DER_Digest.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA7149809A800B44D5A /* DER_Digest.c */; };
		489EECC1149809A800B44D5A /* DER_Digest.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA7149809A800B44D5A /* DER_Digest.c */; };



		489EECC2149809A800B44D5A /* DER_Digest.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA7149809A800B44D5A /* DER_Digest.c */; };
		489EECC3149809A800B44D5A /* DER_Digest.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA8149809A800B44D5A /* DER_Digest.h */; };
		489EECC4149809A800B44D5A /* DER_Digest.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA8149809A800B44D5A /* DER_Digest.h */; };


		489EECC5149809A800B44D5A /* DER_Digest.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECA8149809A800B44D5A /* DER_Digest.h */; };


		489EECC6149809A800B44D5A /* DER_Encode.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA9149809A800B44D5A /* DER_Encode.c */; };







		489EECC7149809A800B44D5A /* DER_Encode.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA9149809A800B44D5A /* DER_Encode.c */; };

		489EECC8149809A800B44D5A /* DER_Encode.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECA9149809A800B44D5A /* DER_Encode.c */; };
		489EECC9149809A800B44D5A /* DER_Encode.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAA149809A800B44D5A /* DER_Encode.h */; };
		489EECCA149809A800B44D5A /* DER_Encode.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAA149809A800B44D5A /* DER_Encode.h */; };
		489EECCB149809A800B44D5A /* DER_Encode.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAA149809A800B44D5A /* DER_Encode.h */; };









		489EECCC149809A800B44D5A /* DER_Keys.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECAB149809A800B44D5A /* DER_Keys.c */; };
		489EECCD149809A800B44D5A /* DER_Keys.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECAB149809A800B44D5A /* DER_Keys.c */; };









		489EECCE149809A800B44D5A /* DER_Keys.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECAB149809A800B44D5A /* DER_Keys.c */; };
		489EECCF149809A800B44D5A /* DER_Keys.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAC149809A800B44D5A /* DER_Keys.h */; };
		489EECD0149809A800B44D5A /* DER_Keys.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAC149809A800B44D5A /* DER_Keys.h */; };
		489EECD1149809A800B44D5A /* DER_Keys.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAC149809A800B44D5A /* DER_Keys.h */; };
		489EECD2149809A800B44D5A /* libDER.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAD149809A800B44D5A /* libDER.h */; };
		489EECD3149809A800B44D5A /* libDER.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAD149809A800B44D5A /* libDER.h */; };
		489EECD4149809A800B44D5A /* libDER.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAD149809A800B44D5A /* libDER.h */; };



		489EECD5149809A800B44D5A /* libDER_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAE149809A800B44D5A /* libDER_config.h */; };
		489EECD6149809A800B44D5A /* libDER_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAE149809A800B44D5A /* libDER_config.h */; };
		489EECD7149809A800B44D5A /* libDER_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECAE149809A800B44D5A /* libDER_config.h */; };
		489EECD8149809A800B44D5A /* oids.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECAF149809A800B44D5A /* oids.c */; };
		489EECD9149809A800B44D5A /* oids.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECAF149809A800B44D5A /* oids.c */; };
		489EECDA149809A800B44D5A /* oids.c in Sources */ = {isa = PBXBuildFile; fileRef = 489EECAF149809A800B44D5A /* oids.c */; };
		489EECDB149809A800B44D5A /* oids.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECB0149809A800B44D5A /* oids.h */; };
		489EECDC149809A800B44D5A /* oids.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECB0149809A800B44D5A /* oids.h */; };
		489EECDD149809A800B44D5A /* oids.h in Headers */ = {isa = PBXBuildFile; fileRef = 489EECB0149809A800B44D5A /* oids.h */; };
		489F2442141AA3D0005E80FD /* CommonCMAC.c in Sources */ = {isa = PBXBuildFile; fileRef = 489F2441141AA3D0005E80FD /* CommonCMAC.c */; };
		489F2444141AA3D0005E80FD /* CommonCMAC.c in Sources */ = {isa = PBXBuildFile; fileRef = 489F2441141AA3D0005E80FD /* CommonCMAC.c */; };




















		489F2445141AA3D0005E80FD /* CommonCMAC.c in Sources */ = {isa = PBXBuildFile; fileRef = 489F2441141AA3D0005E80FD /* CommonCMAC.c */; };
		489FD30C13187B1D00ACB86D /* CommonHMacSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 489FD30B13187B1D00ACB86D /* CommonHMacSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		489FD30E13187B1D00ACB86D /* CommonHMacSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 489FD30B13187B1D00ACB86D /* CommonHMacSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		489FD30F13187B1D00ACB86D /* CommonHMacSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 489FD30B13187B1D00ACB86D /* CommonHMacSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };

		48A5CBA2131EE096002A6E85 /* CommonGCMCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 48A5CBA0131EE096002A6E85 /* CommonGCMCryptor.c */; };
		48A5CBA6131EE096002A6E85 /* CommonGCMCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 48A5CBA0131EE096002A6E85 /* CommonGCMCryptor.c */; };
		48A5CBA8131EE096002A6E85 /* CommonGCMCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 48A5CBA0131EE096002A6E85 /* CommonGCMCryptor.c */; };
		48AC47CF1381EFDC00F584F5 /* byteBuffer.c in Sources */ = {isa = PBXBuildFile; fileRef = 48AC47CD1381EFDC00F584F5 /* byteBuffer.c */; };
		48AC47D11381EFDC00F584F5 /* byteBuffer.c in Sources */ = {isa = PBXBuildFile; fileRef = 48AC47CD1381EFDC00F584F5 /* byteBuffer.c */; };
		48AC47D21381EFDC00F584F5 /* byteBuffer.c in Sources */ = {isa = PBXBuildFile; fileRef = 48AC47CD1381EFDC00F584F5 /* byteBuffer.c */; };

		48AC47D51381EFDC00F584F5 /* byteBuffer.h in Headers */ = {isa = PBXBuildFile; fileRef = 48AC47CE1381EFDC00F584F5 /* byteBuffer.h */; };
		48AC47D71381EFDC00F584F5 /* byteBuffer.h in Headers */ = {isa = PBXBuildFile; fileRef = 48AC47CE1381EFDC00F584F5 /* byteBuffer.h */; };
		48AC47D81381EFDC00F584F5 /* byteBuffer.h in Headers */ = {isa = PBXBuildFile; fileRef = 48AC47CE1381EFDC00F584F5 /* byteBuffer.h */; };
		48B4651412848FB800311799 /* CommonRSACryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 48B4651112848FB800311799 /* CommonRSACryptor.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48B4651512848FB800311799 /* CommonRSACryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 48B4651112848FB800311799 /* CommonRSACryptor.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48B4651712848FB800311799 /* CommonRSACryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 48B4651112848FB800311799 /* CommonRSACryptor.h */; settings = {ATTRIBUTES = (Private, ); }; };

		48B4651D1284907600311799 /* CommonRSACryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 48B4651B1284907600311799 /* CommonRSACryptor.c */; };
		48B4651E1284907600311799 /* CommonRSACryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 48B4651B1284907600311799 /* CommonRSACryptor.c */; };
		48B4651F1284907600311799 /* CommonRSACryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 48B4651B1284907600311799 /* CommonRSACryptor.c */; };
		48C5CB9214FD747500F4472E /* CommonDHtest.c in Sources */ = {isa = PBXBuildFile; fileRef = 48C5CB9114FD747500F4472E /* CommonDHtest.c */; };


		48C5CB9314FD747500F4472E /* CommonDHtest.c in Sources */ = {isa = PBXBuildFile; fileRef = 48C5CB9114FD747500F4472E /* CommonDHtest.c */; };

		48CCD26514F6F189002B6043 /* CommonBigDigest.c in Sources */ = {isa = PBXBuildFile; fileRef = 48CCD26414F6F189002B6043 /* CommonBigDigest.c */; };











		48CCD26614F6F1E1002B6043 /* CommonBigDigest.c in Sources */ = {isa = PBXBuildFile; fileRef = 48CCD26414F6F189002B6043 /* CommonBigDigest.c */; };
		48D076C1130B2A510052D1AC /* CommonDH.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D076C0130B2A510052D1AC /* CommonDH.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48D076C3130B2A510052D1AC /* CommonDH.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D076C0130B2A510052D1AC /* CommonDH.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48D076C5130B2A510052D1AC /* CommonDH.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D076C0130B2A510052D1AC /* CommonDH.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48D076C8130B2A620052D1AC /* CommonECCryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D076C7130B2A620052D1AC /* CommonECCryptor.h */; settings = {ATTRIBUTES = (Private, ); }; };


		48D076CA130B2A620052D1AC /* CommonECCryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D076C7130B2A620052D1AC /* CommonECCryptor.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48D076CC130B2A620052D1AC /* CommonECCryptor.h in Headers */ = {isa = PBXBuildFile; fileRef = 48D076C7130B2A620052D1AC /* CommonECCryptor.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48D076D0130B2A9C0052D1AC /* CommonDH.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D076CE130B2A9C0052D1AC /* CommonDH.c */; };
		48D076D1130B2A9C0052D1AC /* CommonECCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D076CF130B2A9C0052D1AC /* CommonECCryptor.c */; };
		48D076D4130B2A9C0052D1AC /* CommonDH.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D076CE130B2A9C0052D1AC /* CommonDH.c */; };



		48D076D5130B2A9C0052D1AC /* CommonECCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D076CF130B2A9C0052D1AC /* CommonECCryptor.c */; };
		48D076D8130B2A9C0052D1AC /* CommonDH.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D076CE130B2A9C0052D1AC /* CommonDH.c */; };
		48D076D9130B2A9C0052D1AC /* CommonECCryptor.c in Sources */ = {isa = PBXBuildFile; fileRef = 48D076CF130B2A9C0052D1AC /* CommonECCryptor.c */; };

		48E93DCB136867F500B33DB8 /* CommonCMACSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 48E93DCA136867F500B33DB8 /* CommonCMACSPI.h */; settings = {ATTRIBUTES = (Private, ); }; };
		48E93DCC136867F500B33DB8 /* CommonCMACSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 48E93DCA136867F500B33DB8 /* CommonCMACSPI.h */; };



		48E93DCD136867F500B33DB8 /* CommonCMACSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = 48E93DCA136867F500B33DB8 /* CommonCMACSPI.h */; };




		48F5355314902894000D2D1F /* CommonRandom.c in Sources */ = {isa = PBXBuildFile; fileRef = 48F5355214902894000D2D1F /* CommonRandom.c */; };
		48F5355414902894000D2D1F /* CommonRandom.c in Sources */ = {isa = PBXBuildFile; fileRef = 48F5355214902894000D2D1F /* CommonRandom.c */; };

		48FC4BD613959D0600DA4760 /* lionCompat.h in Headers */ = {isa = PBXBuildFile; fileRef = 48FC4BD513959D0600DA4760 /* lionCompat.h */; settings = {ATTRIBUTES = (Private, ); }; };

		48FC4BD81395ACE600DA4760 /* CommonCryptoCASTShoefly.c in Sources */ = {isa = PBXBuildFile; fileRef = 48FC4BD71395ACE600DA4760 /* CommonCryptoCASTShoefly.c */; };


		48FD6C3A1354DD4000F55B8B /* ccErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = 48FD6C371354DD4000F55B8B /* ccErrors.h */; };
		48FD6C3B1354DD4000F55B8B /* ccMemory.h in Headers */ = {isa = PBXBuildFile; fileRef = 48FD6C381354DD4000F55B8B /* ccMemory.h */; };
		48FD6C401354DD4000F55B8B /* ccErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = 48FD6C371354DD4000F55B8B /* ccErrors.h */; };
		48FD6C411354DD4000F55B8B /* ccMemory.h in Headers */ = {isa = PBXBuildFile; fileRef = 48FD6C381354DD4000F55B8B /* ccMemory.h */; };
		48FD6C431354DD4000F55B8B /* ccErrors.h in Headers */ = {isa = PBXBuildFile; fileRef = 48FD6C371354DD4000F55B8B /* ccErrors.h */; };



		48FD6C441354DD4000F55B8B /* ccMemory.h in Headers */ = {isa = PBXBuildFile; fileRef = 48FD6C381354DD4000F55B8B /* ccMemory.h */; };

		4CDDFB7E133BD3BA00B4770F /* aes.h in Headers */ = {isa = PBXBuildFile; fileRef = 48685583127B63F200B88D39 /* aes.h */; settings = {ATTRIBUTES = (Private, ); }; };







		4CF7820B1339B543004A56DF /* CommonCryptoAESShoefly.c in Sources */ = {isa = PBXBuildFile; fileRef = 48685586127B641800B88D39 /* CommonCryptoAESShoefly.c */; };
		5DB80D3E14FC5CB3002C9A03 /* CommonRandom.c in Sources */ = {isa = PBXBuildFile; fileRef = 48F5355214902894000D2D1F /* CommonRandom.c */; };


		D6658D950BD8178400D18063 /* CC_crypto.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 05DF6D1109CF2D7200D9A3E8 /* CC_crypto.3cc */; };
		D6658D960BD8178400D18063 /* CC_MD2.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5B60BC6D67000878B42 /* CC_MD2.3cc */; };
		D6658D970BD8178400D18063 /* CC_MD2_Final.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5B70BC6D67000878B42 /* CC_MD2_Final.3cc */; };
		D6658D980BD8178400D18063 /* CC_MD2_Init.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5B80BC6D67000878B42 /* CC_MD2_Init.3cc */; };
		D6658D990BD8178400D18063 /* CC_MD2_Update.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5B90BC6D67000878B42 /* CC_MD2_Update.3cc */; };
		D6658D9A0BD8178400D18063 /* CC_MD4.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5BA0BC6D67000878B42 /* CC_MD4.3cc */; };
		D6658D9B0BD8178400D18063 /* CC_MD4_Final.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5BB0BC6D67000878B42 /* CC_MD4_Final.3cc */; };
531
532
533
534
535
536
537
538








539
540
541
542
543
544









545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
		D6658DC10BD8178400D18063 /* CCHmacInit.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5DF0BC6D67000878B42 /* CCHmacInit.3cc */; };
		D6658DC20BD8178400D18063 /* CCHmacUpdate.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5E00BC6D67000878B42 /* CCHmacUpdate.3cc */; };
		D6658DC30BD8178400D18063 /* CCryptorCreateFromData.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5E10BC6D67000878B42 /* CCryptorCreateFromData.3cc */; };
		D6658DC40BD8178400D18063 /* Common Crypto.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5E20BC6D67000878B42 /* Common Crypto.3cc */; };
/* End PBXBuildFile section */

/* Begin PBXBuildRule section */
		48F7F36912B2EF6000AF4587 /* PBXBuildRule */ = {








			isa = PBXBuildRule;
			compilerSpec = com.apple.compilers.gcc;
			fileType = sourcecode.c;
			isEditable = 1;
			outputFiles = (
			);









		};
		B125268E0713742A00BB8157 /* PBXBuildRule */ = {
			isa = PBXBuildRule;
			compilerSpec = com.apple.compilers.gcc;
			fileType = sourcecode.c;
			isEditable = 1;
			outputFiles = (
			);
		};
/* End PBXBuildRule section */

/* Begin PBXContainerItemProxy section */
		0511C4620A3785340028BFC3 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 05CE94290A3784D4007C91D6;
			remoteInfo = "Copy Open Source Docs";
		};
		1228ADD612037B1000B83BF9 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 054BBEBD05F6A97700344873;
			remoteInfo = commonCrypto;
		};
		12F60BE912015A2600D17AF3 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 054BBEBD05F6A97700344873;
			remoteInfo = commonCrypto;
		};
		5D936FFA110E7FFF006855B0 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 054BBEBD05F6A97700344873;
			remoteInfo = commonCrypto;
		};
		5DAD82DB1279DF6100240B9A /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 5DAD82CB1279DEF900240B9A;
			remoteInfo = UnitTestLibrary;
		};
		5DAD839D1279F22000240B9A /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 5DAD82CB1279DEF900240B9A;
			remoteInfo = UnitTestLibrary;
		};
		5DAD83D11279F6D500240B9A /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 5DAD83981279F1EC00240B9A;
			remoteInfo = CommonCryptoTestTool;
		};
		5DC8771010FFB7510012A390 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 5D735E4710FCDC04001AAD1E;
			remoteInfo = CommonCryptoUnitTest;
		};
		FC129BEC116AED0500D618D5 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 054BBEBD05F6A97700344873;
			remoteInfo = commonCrypto;
		};
/* End PBXContainerItemProxy section */







|
>
>
>
>
>
>
>
>






>
>
>
>
>
>
>
>
>



|















|




|

|



<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|

|



|
|

|



|
|

|
<
<
<
<
<
<
<







340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400














401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418







419
420
421
422
423
424
425
		D6658DC10BD8178400D18063 /* CCHmacInit.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5DF0BC6D67000878B42 /* CCHmacInit.3cc */; };
		D6658DC20BD8178400D18063 /* CCHmacUpdate.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5E00BC6D67000878B42 /* CCHmacUpdate.3cc */; };
		D6658DC30BD8178400D18063 /* CCryptorCreateFromData.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5E10BC6D67000878B42 /* CCryptorCreateFromData.3cc */; };
		D6658DC40BD8178400D18063 /* Common Crypto.3cc in CopyFiles */ = {isa = PBXBuildFile; fileRef = D671B5E20BC6D67000878B42 /* Common Crypto.3cc */; };
/* End PBXBuildFile section */

/* Begin PBXBuildRule section */
		48165DB5125AC5D50015A267 /* PBXBuildRule */ = {
			isa = PBXBuildRule;
			compilerSpec = com.apple.compilers.gcc;
			fileType = sourcecode.c;
			isEditable = 1;
			outputFiles = (
			);
		};
		48165E98125AC5F20015A267 /* PBXBuildRule */ = {
			isa = PBXBuildRule;
			compilerSpec = com.apple.compilers.gcc;
			fileType = sourcecode.c;
			isEditable = 1;
			outputFiles = (
			);
		};
		48B5F5281361D6A500134C9F /* PBXBuildRule */ = {
			isa = PBXBuildRule;
			compilerSpec = com.apple.compilers.llvmgcc42;
			fileType = sourcecode.nasm;
			isEditable = 1;
			outputFiles = (
			);
			script = "$(DEVELOPER_BIN_DIR)/nasm\n";
		};
		B125268E0713742A00BB8157 /* PBXBuildRule */ = {
			isa = PBXBuildRule;
			compilerSpec = com.apple.compilers.llvmgcc42;
			fileType = sourcecode.c;
			isEditable = 1;
			outputFiles = (
			);
		};
/* End PBXBuildRule section */

/* Begin PBXContainerItemProxy section */
		0511C4620A3785340028BFC3 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 05CE94290A3784D4007C91D6;
			remoteInfo = "Copy Open Source Docs";
		};
		4823B10C14C101CC008F689F /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 054BBEBD05F6A97700344873;
			remoteInfo = libCommonCryptoMacOSX;
		};
		4834A88314F47CA300438E3D /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;














			remoteGlobalIDString = 48165CD7125AC5D50015A267;
			remoteInfo = libCommonCryptoMacIOS;
		};
		4C58A28C13281C2100A17BAC /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 48165CD7125AC5D50015A267;
			remoteInfo = libCommonCryptoMacIOS;
		};
		4CA675181332C17900C45A71 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 48165DBA125AC5F20015A267;
			remoteInfo = libCommonCryptoMacIOSSim;
		};
		5D936FFA110E7FFF006855B0 /* PBXContainerItemProxy */ = {







			isa = PBXContainerItemProxy;
			containerPortal = 054BBEA605F6A8DE00344873 /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 054BBEBD05F6A97700344873;
			remoteInfo = commonCrypto;
		};
/* End PBXContainerItemProxy section */
633
634
635
636
637
638
639


















640
641
642
643
644
645
646
		05CE942F0A37850A007C91D6 /* CopyFiles */ = {
			isa = PBXCopyFilesBuildPhase;
			buildActionMask = 8;
			dstPath = /usr/local/OpenSourceLicenses/;
			dstSubfolderSpec = 0;
			files = (
				0511C47E0A37892C0028BFC3 /* CommonCrypto.txt in CopyFiles */,


















			);
			runOnlyForDeploymentPostprocessing = 1;
		};
		D6658DC80BD817B600D18063 /* CopyFiles */ = {
			isa = PBXCopyFilesBuildPhase;
			buildActionMask = 8;
			dstPath = /usr/share/man/man3;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
		05CE942F0A37850A007C91D6 /* CopyFiles */ = {
			isa = PBXCopyFilesBuildPhase;
			buildActionMask = 8;
			dstPath = /usr/local/OpenSourceLicenses/;
			dstSubfolderSpec = 0;
			files = (
				0511C47E0A37892C0028BFC3 /* CommonCrypto.txt in CopyFiles */,
			);
			runOnlyForDeploymentPostprocessing = 1;
		};
		4823B0DE14C10064008F689F /* CopyFiles */ = {
			isa = PBXCopyFilesBuildPhase;
			buildActionMask = 2147483647;
			dstPath = /usr/share/man/man1/;
			dstSubfolderSpec = 0;
			files = (
			);
			runOnlyForDeploymentPostprocessing = 1;
		};
		4834A87C14F47B6200438E3D /* CopyFiles */ = {
			isa = PBXCopyFilesBuildPhase;
			buildActionMask = 2147483647;
			dstPath = /usr/share/man/man1/;
			dstSubfolderSpec = 0;
			files = (
			);
			runOnlyForDeploymentPostprocessing = 1;
		};
		D6658DC80BD817B600D18063 /* CopyFiles */ = {
			isa = PBXCopyFilesBuildPhase;
			buildActionMask = 8;
			dstPath = /usr/share/man/man3;
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777

























778




779

780

781
782

783




784


785
786
787
788
789
790
791
792
793
794



795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016

1017
1018
1019
1020
1021
1022
1023
				D6658DBE0BD8178400D18063 /* CCCryptorUpdate.3cc in CopyFiles */,
				D6658DBF0BD8178400D18063 /* CCHmac.3cc in CopyFiles */,
				D6658DC00BD8178400D18063 /* CCHmacFinal.3cc in CopyFiles */,
				D6658DC10BD8178400D18063 /* CCHmacInit.3cc in CopyFiles */,
				D6658DC20BD8178400D18063 /* CCHmacUpdate.3cc in CopyFiles */,
				D6658DC30BD8178400D18063 /* CCryptorCreateFromData.3cc in CopyFiles */,
				D6658DC40BD8178400D18063 /* Common Crypto.3cc in CopyFiles */,
				48F7B00112F248C900E70774 /* CCCalibratePBKDF.3cc in CopyFiles */,
				48F7B00212F248C900E70774 /* CCCommonKeyDerivation.3cc in CopyFiles */,
				48F7B00812F248E600E70774 /* CCKeyDerivationPBKDF.3cc in CopyFiles */,
				48F7B00912F248E600E70774 /* CCSymmetricKeyUnwrap.3cc in CopyFiles */,
				48F7B00A12F248E600E70774 /* CCSymmetricKeyWrap.3cc in CopyFiles */,
				48F7B00B12F248E700E70774 /* CCSymmetricUnwrappedSize.3cc in CopyFiles */,
				48F7B00C12F248E700E70774 /* CCSymmetricWrappedSize.3cc in CopyFiles */,
			);
			runOnlyForDeploymentPostprocessing = 1;
		};
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */
		0539DC2609D4919D00AB7F89 /* opensslDES.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = opensslDES.c; sourceTree = "<group>"; };
		054BBEBE05F6A97700344873 /* libcommonCrypto.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libcommonCrypto.dylib; sourceTree = BUILT_PRODUCTS_DIR; };
		054BBEC605F6A98900344873 /* libcommonCrypto.dylib */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libcommonCrypto.dylib; sourceTree = BUILT_PRODUCTS_DIR; };
		054BBECD05F6AA7200344873 /* CommonDigest.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CommonDigest.h; sourceTree = "<group>"; };
		054BBED305F6AA8900344873 /* md2_dgst.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = md2_dgst.c; sourceTree = "<group>"; };
		054BBED405F6AA8900344873 /* md4_dgst.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = md4_dgst.c; sourceTree = "<group>"; };
		054BBED505F6AA8900344873 /* md4_locl.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = md4_locl.h; sourceTree = "<group>"; };
		054BBED605F6AA8900344873 /* md5_dgst.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = md5_dgst.c; sourceTree = "<group>"; };
		054BBED705F6AA8900344873 /* md5_locl.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = md5_locl.h; sourceTree = "<group>"; };
		054BBED805F6AA8900344873 /* md32_common.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = md32_common.h; sourceTree = "<group>"; };
		054BBEDA05F6AA8900344873 /* sha_locl.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = sha_locl.h; sourceTree = "<group>"; };
		054BBEDC05F6AA8900344873 /* sha1.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = sha1.c; sourceTree = "<group>"; };
		0585FE1209DC9873001762F6 /* c_ecb.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = c_ecb.c; sourceTree = "<group>"; };
		0585FE1309DC9873001762F6 /* c_enc.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = c_enc.c; sourceTree = "<group>"; };
		0585FE1409DC9873001762F6 /* c_skey.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = c_skey.c; sourceTree = "<group>"; };
		0585FE1609DC9873001762F6 /* cast_lcl.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = cast_lcl.h; sourceTree = "<group>"; };
		0585FE1709DC9873001762F6 /* cast_s.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = cast_s.h; sourceTree = "<group>"; };
		0585FE1809DC9873001762F6 /* ccCast.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = ccCast.c; sourceTree = "<group>"; };
		05C4416E09D4BACE002066D1 /* e_os2.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = e_os2.h; sourceTree = "<group>"; };
		05C4417209D4BB0B002066D1 /* opensslconf.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = opensslconf.h; sourceTree = "<group>"; };
		05C70C5309D471C30004B8F4 /* spr.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = spr.h; sourceTree = "<group>"; };
		05CE942B0A37850A007C91D6 /* CommonCrypto.plist */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.plist.xml; name = CommonCrypto.plist; path = doc/CommonCrypto.plist; sourceTree = "<group>"; };
		05CE942C0A37850A007C91D6 /* CommonCrypto.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CommonCrypto.txt; path = doc/CommonCrypto.txt; sourceTree = "<group>"; };
		05D8D97C09E411AA00E03504 /* CommonHMAC.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonHMAC.h; sourceTree = "<group>"; };
		05D9F61609D85F4A00AD30A7 /* CommonCryptor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCryptor.h; sourceTree = "<group>"; };
		05DF6D1109CF2D7200D9A3E8 /* CC_crypto.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_crypto.3cc; path = doc/CC_crypto.3cc; sourceTree = "<group>"; };
		05DF6D1209CF2D7200D9A3E8 /* CC_MD5.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD5.3cc; path = doc/CC_MD5.3cc; sourceTree = "<group>"; };
		05DF6D1309CF2D7200D9A3E8 /* CC_SHA.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_SHA.3cc; path = doc/CC_SHA.3cc; sourceTree = "<group>"; };
		05E319B7063890C100C4AD24 /* sha2.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = sha2.c; sourceTree = "<group>"; };
		05E319DC0638913700C4AD24 /* sha2Priv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sha2Priv.h; sourceTree = "<group>"; };
		05ECA0E409D468E200CFE5CB /* des.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = des.h; sourceTree = "<group>"; };
		05ECA0E509D468E200CFE5CB /* des_enc.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = des_enc.c; sourceTree = "<group>"; };
		05ECA0E609D468E200CFE5CB /* des_locl.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = des_locl.h; sourceTree = "<group>"; };
		05ECA0ED09D469A100CFE5CB /* set_key.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = set_key.c; sourceTree = "<group>"; };
		122ADC43121320D70027F302 /* sha256_nossse3.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = sha256_nossse3.s; sourceTree = "<group>"; };
		122ADC44121320D70027F302 /* sha256.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = sha256.s; sourceTree = "<group>"; };
		1249340112270E8900F9C9E1 /* cfb8_decrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb8_decrypt.c; sourceTree = "<group>"; };
		1249340212270E8900F9C9E1 /* cfb8_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb8_descriptor.c; sourceTree = "<group>"; };
		1249340312270E8900F9C9E1 /* cfb8_done.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb8_done.c; sourceTree = "<group>"; };
		1249340412270E8900F9C9E1 /* cfb8_encrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb8_encrypt.c; sourceTree = "<group>"; };
		1249340512270E8900F9C9E1 /* cfb8_getiv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb8_getiv.c; sourceTree = "<group>"; };
		1249340612270E8900F9C9E1 /* cfb8_setiv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb8_setiv.c; sourceTree = "<group>"; };
		1249340712270E8900F9C9E1 /* cfb8_start.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb8_start.c; sourceTree = "<group>"; };
		125B78AE11FF877D008C1AD3 /* aesedpPriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = aesedpPriv.h; sourceTree = "<group>"; };
		125B795111FF923D008C1AD3 /* XTStest */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = XTStest; sourceTree = BUILT_PRODUCTS_DIR; };
		125B796011FF92FC008C1AD3 /* crypto.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypto.c; sourceTree = "<group>"; };
		125B796111FF92FC008C1AD3 /* hexString.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = hexString.c; sourceTree = "<group>"; };
		125B796211FF92FC008C1AD3 /* hexString.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = hexString.h; sourceTree = "<group>"; };
		125B796311FF92FC008C1AD3 /* printByteBuffer.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = printByteBuffer.c; sourceTree = "<group>"; };
		125B796411FF92FC008C1AD3 /* printByteBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = printByteBuffer.h; sourceTree = "<group>"; };
		125B796511FF92FC008C1AD3 /* xtsTestVectors.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = xtsTestVectors.c; sourceTree = "<group>"; };
		125B796611FF92FC008C1AD3 /* xtsTestVectors.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = xtsTestVectors.h; sourceTree = "<group>"; };
		12790C7411F7C4BA0044EFE5 /* CommonCrypto_unittest_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CommonCrypto_unittest_deployment.xcconfig; path = Configurations/CommonCrypto_unittest_deployment.xcconfig; sourceTree = "<group>"; };
		12790C7511F7C4BA0044EFE5 /* CommonCrypto_unittest_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CommonCrypto_unittest_development.xcconfig; path = Configurations/CommonCrypto_unittest_development.xcconfig; sourceTree = "<group>"; };
		128881651203673C0050B2E9 /* CBCTest */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = CBCTest; sourceTree = BUILT_PRODUCTS_DIR; };
		12A1ADD71207419E000C30A4 /* CommonCrypto_localtest.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CommonCrypto_localtest.xcconfig; path = Configurations/CommonCrypto_localtest.xcconfig; sourceTree = "<group>"; };
		12C3F7E5122AD1B100E09D9E /* SenTestingKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SenTestingKit.framework; path = Library/Frameworks/SenTestingKit.framework; sourceTree = DEVELOPER_DIR; };
		12CC5DD8120373D1001B4FCE /* CBCTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CBCTest.h; sourceTree = "<group>"; };
		12CC5DD9120373D1001B4FCE /* CBCTest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CBCTest.c; sourceTree = "<group>"; };
		12FA0DAF11F7962100917A4E /* CommonRandomSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonRandomSPI.h; sourceTree = "<group>"; };
		12FA0DB111F7964700917A4E /* CommonRandom.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonRandom.c; sourceTree = "<group>"; };
		12FA10D011F7AACE00917A4E /* CommonCrypto_umbrellaMember_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CommonCrypto_umbrellaMember_deployment.xcconfig; path = Configurations/CommonCrypto_umbrellaMember_deployment.xcconfig; sourceTree = "<group>"; };
		12FA10D111F7AAE400917A4E /* CommonCrypto_umbrellaMember_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CommonCrypto_umbrellaMember_development.xcconfig; path = Configurations/CommonCrypto_umbrellaMember_development.xcconfig; sourceTree = "<group>"; };
		12FA10D211F7AB3E00917A4E /* CommonCrypto_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CommonCrypto_deployment.xcconfig; path = Configurations/CommonCrypto_deployment.xcconfig; sourceTree = "<group>"; };
		12FA10D311F7AB5000917A4E /* CommonCrypto_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CommonCrypto_development.xcconfig; path = Configurations/CommonCrypto_development.xcconfig; sourceTree = "<group>"; };
		12FA10D811F7ABCD00917A4E /* CommonCrypto_umbrellaMember.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CommonCrypto_umbrellaMember.xcconfig; path = Configurations/CommonCrypto_umbrellaMember.xcconfig; sourceTree = "<group>"; };
		12FBB0891238353000772329 /* CommonCrypto.exp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.exports; path = CommonCrypto.exp; sourceTree = "<group>"; };
		48096B2211A5EF900043F67F /* CommonDigest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonDigest.c; sourceTree = "<group>"; };

























		480C9AD512077BCF002EC023 /* byteBuffer.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = byteBuffer.c; sourceTree = "<group>"; };




		480C9AD612077BCF002EC023 /* byteBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = byteBuffer.h; sourceTree = "<group>"; };

		4836A41811A5C94A00862178 /* rc2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = rc2.h; path = ../CommonCryptoSPI/rc2.h; sourceTree = "<group>"; };

		4836A41911A5C94A00862178 /* opensslDES.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = opensslDES.h; path = ../CommonCryptoSPI/opensslDES.h; sourceTree = "<group>"; };
		4836A41A11A5C94A00862178 /* CommonCryptoPriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCryptoPriv.h; sourceTree = "<group>"; };

		4836A41B11A5C94A00862178 /* ccRC2.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ccRC2.h; path = ../CommonCryptoSPI/ccRC2.h; sourceTree = "<group>"; };




		4836A41C11A5C94A00862178 /* ccCast.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ccCast.h; path = ../CommonCryptoSPI/ccCast.h; sourceTree = "<group>"; };


		4836A41D11A5C94A00862178 /* cast.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = cast.h; path = ../CommonCryptoSPI/cast.h; sourceTree = "<group>"; };
		4836A42B11A5CB4700862178 /* CommonCryptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonCryptor.c; sourceTree = "<group>"; };
		4836A42C11A5CB4700862178 /* CommonCryptorPriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCryptorPriv.h; sourceTree = "<group>"; };
		4836A42D11A5CB4700862178 /* CommonDigestPriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonDigestPriv.h; sourceTree = "<group>"; };
		4836A42E11A5CB4700862178 /* CommonHMAC.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonHMAC.c; sourceTree = "<group>"; };
		4836A42F11A5CB4700862178 /* CommonKeyDerivation.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonKeyDerivation.c; sourceTree = "<group>"; };
		4836A43011A5CB4700862178 /* CommonKeyDerivationPriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonKeyDerivationPriv.h; sourceTree = "<group>"; };
		4836A43111A5CB4700862178 /* CommonSymmetricKeywrap.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonSymmetricKeywrap.c; sourceTree = "<group>"; };
		4846CA5411A5C8B800E7DA82 /* CommonCryptorSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCryptorSPI.h; sourceTree = "<group>"; };
		4846CA5511A5C8B800E7DA82 /* CommonDigestSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonDigestSPI.h; sourceTree = "<group>"; };



		4854F9C01116307500CAFA18 /* CommonKeyDerivation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonKeyDerivation.h; sourceTree = "<group>"; };
		4854F9C11116307500CAFA18 /* CommonSymmetricKeywrap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonSymmetricKeywrap.h; sourceTree = "<group>"; };
		4857A12A11BDA6E0001F5A9A /* libSystem.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libSystem.dylib; path = usr/lib/libSystem.dylib; sourceTree = SDKROOT; };
		4857A13011BDA737001F5A9A /* System.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = System.framework; path = /System/Library/Frameworks/System.framework; sourceTree = "<absolute>"; };
		4862F09411BDA1D300946BBE /* skein_ltc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = skein_ltc.h; sourceTree = "<group>"; };
		4862F09511BDA1D300946BBE /* skein_ltc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = skein_ltc.c; sourceTree = "<group>"; };
		4862F09E11BDA27200946BBE /* skein.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = skein.h; sourceTree = "<group>"; };
		4862F09F11BDA27200946BBE /* skein.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = skein.c; sourceTree = "<group>"; };
		4862F0A011BDA27200946BBE /* skein_port.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = skein_port.h; sourceTree = "<group>"; };
		4862F0A111BDA27200946BBE /* skein_iv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = skein_iv.h; sourceTree = "<group>"; };
		4862F0A211BDA27200946BBE /* skein_dropin.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = skein_dropin.h; sourceTree = "<group>"; };
		4862F0A311BDA27200946BBE /* skein_dropin.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = skein_dropin.c; sourceTree = "<group>"; };
		4862F0A411BDA27200946BBE /* skein_debug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = skein_debug.h; sourceTree = "<group>"; };
		4862F0A511BDA27200946BBE /* skein_debug.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = skein_debug.c; sourceTree = "<group>"; };
		4862F0A611BDA27200946BBE /* skein_block.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = skein_block.c; sourceTree = "<group>"; };
		4862F0A711BDA27200946BBE /* SHA3api_ref.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SHA3api_ref.h; sourceTree = "<group>"; };
		4862F0A811BDA27200946BBE /* SHA3api_ref.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SHA3api_ref.c; sourceTree = "<group>"; };
		4862F0A911BDA27200946BBE /* brg_types.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = brg_types.h; sourceTree = "<group>"; };
		4862F0AA11BDA27200946BBE /* brg_endian.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = brg_endian.h; sourceTree = "<group>"; };
		4873F33E11A4E47B00B5DDB3 /* footer.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = footer.html; sourceTree = "<group>"; };
		4873F33F11A4E47B00B5DDB3 /* header.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = header.html; sourceTree = "<group>"; };
		4873F34011A4E47B00B5DDB3 /* libTomCryptDoc.pdf */ = {isa = PBXFileReference; lastKnownFileType = image.pdf; path = libTomCryptDoc.pdf; sourceTree = "<group>"; };
		4873F34A11A4E47B00B5DDB3 /* aesedp.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = aesedp.c; sourceTree = "<group>"; };
		4873F34B11A4E47B00B5DDB3 /* aesedp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = aesedp.h; sourceTree = "<group>"; };
		4873F35311A4E47B00B5DDB3 /* cast5.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cast5.c; sourceTree = "<group>"; };
		4873F35411A4E47B00B5DDB3 /* des.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = des.c; sourceTree = "<group>"; };
		4873F35511A4E47B00B5DDB3 /* rc2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rc2.c; sourceTree = "<group>"; };
		4873F35711A4E47B00B5DDB3 /* rc4.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = rc4.h; sourceTree = "<group>"; };
		4873F35811A4E47B00B5DDB3 /* rc4_enc.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rc4_enc.c; sourceTree = "<group>"; };
		4873F35911A4E47B00B5DDB3 /* rc4_skey.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rc4_skey.c; sourceTree = "<group>"; };
		4873F35A11A4E47B00B5DDB3 /* rc5.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rc5.c; sourceTree = "<group>"; };
		4873F35D11A4E47B00B5DDB3 /* hash_file.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = hash_file.c; sourceTree = "<group>"; };
		4873F35E11A4E47B00B5DDB3 /* hash_filehandle.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = hash_filehandle.c; sourceTree = "<group>"; };
		4873F35F11A4E47B00B5DDB3 /* hash_memory.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = hash_memory.c; sourceTree = "<group>"; };
		4873F36011A4E47B00B5DDB3 /* hash_memory_multi.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = hash_memory_multi.c; sourceTree = "<group>"; };
		4873F36111A4E47B00B5DDB3 /* md2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = md2.c; sourceTree = "<group>"; };
		4873F36211A4E47B00B5DDB3 /* md4.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = md4.c; sourceTree = "<group>"; };
		4873F36311A4E47B00B5DDB3 /* md5.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = md5.c; sourceTree = "<group>"; };
		4873F36411A4E47B00B5DDB3 /* rmd128.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rmd128.c; sourceTree = "<group>"; };
		4873F36511A4E47B00B5DDB3 /* rmd160.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rmd160.c; sourceTree = "<group>"; };
		4873F36611A4E47B00B5DDB3 /* rmd256.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rmd256.c; sourceTree = "<group>"; };
		4873F36711A4E47B00B5DDB3 /* rmd320.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rmd320.c; sourceTree = "<group>"; };
		4873F36811A4E47B00B5DDB3 /* sha1.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sha1.c; sourceTree = "<group>"; };
		4873F36A11A4E47B00B5DDB3 /* sha224.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sha224.c; sourceTree = "<group>"; };
		4873F36B11A4E47B00B5DDB3 /* sha256.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sha256.c; sourceTree = "<group>"; };
		4873F36C11A4E47B00B5DDB3 /* sha384.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sha384.c; sourceTree = "<group>"; };
		4873F36D11A4E47B00B5DDB3 /* sha512.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = sha512.c; sourceTree = "<group>"; };
		4873F36F11A4E47B00B5DDB3 /* tomcrypt.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt.h; sourceTree = "<group>"; };
		4873F37011A4E47B00B5DDB3 /* tomcrypt_argchk.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_argchk.h; sourceTree = "<group>"; };
		4873F37111A4E47B00B5DDB3 /* tomcrypt_cfg.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_cfg.h; sourceTree = "<group>"; };
		4873F37211A4E47B00B5DDB3 /* tomcrypt_cipher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_cipher.h; sourceTree = "<group>"; };
		4873F37311A4E47B00B5DDB3 /* tomcrypt_custom.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_custom.h; sourceTree = "<group>"; };
		4873F37411A4E47B00B5DDB3 /* tomcrypt_hash.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_hash.h; sourceTree = "<group>"; };
		4873F37511A4E47B00B5DDB3 /* tomcrypt_mac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_mac.h; sourceTree = "<group>"; };
		4873F37611A4E47B00B5DDB3 /* tomcrypt_macros.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_macros.h; sourceTree = "<group>"; };
		4873F37711A4E47B00B5DDB3 /* tomcrypt_math.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_math.h; sourceTree = "<group>"; };
		4873F37811A4E47B00B5DDB3 /* tomcrypt_misc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_misc.h; sourceTree = "<group>"; };
		4873F37911A4E47B00B5DDB3 /* tomcrypt_mode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_mode.h; sourceTree = "<group>"; };
		4873F37A11A4E47B00B5DDB3 /* tomcrypt_pk.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_pk.h; sourceTree = "<group>"; };
		4873F37B11A4E47B00B5DDB3 /* tomcrypt_pkcs.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_pkcs.h; sourceTree = "<group>"; };
		4873F37C11A4E47B00B5DDB3 /* tomcrypt_prng.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = tomcrypt_prng.h; sourceTree = "<group>"; };
		4873F37F11A4E47B00B5DDB3 /* base64_decode.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = base64_decode.c; sourceTree = "<group>"; };
		4873F38011A4E47B00B5DDB3 /* base64_encode.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = base64_encode.c; sourceTree = "<group>"; };
		4873F38111A4E47B00B5DDB3 /* burn_stack.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = burn_stack.c; sourceTree = "<group>"; };
		4873F38311A4E47B00B5DDB3 /* crypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt.c; sourceTree = "<group>"; };
		4873F38411A4E47B00B5DDB3 /* crypt_argchk.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_argchk.c; sourceTree = "<group>"; };
		4873F38511A4E47B00B5DDB3 /* crypt_cipher_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_cipher_descriptor.c; sourceTree = "<group>"; };
		4873F38611A4E47B00B5DDB3 /* crypt_cipher_is_valid.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_cipher_is_valid.c; sourceTree = "<group>"; };
		4873F38711A4E47B00B5DDB3 /* crypt_find_cipher.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_find_cipher.c; sourceTree = "<group>"; };
		4873F38811A4E47B00B5DDB3 /* crypt_find_cipher_any.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_find_cipher_any.c; sourceTree = "<group>"; };
		4873F38911A4E47B00B5DDB3 /* crypt_find_cipher_id.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_find_cipher_id.c; sourceTree = "<group>"; };
		4873F38A11A4E47B00B5DDB3 /* crypt_find_hash.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_find_hash.c; sourceTree = "<group>"; };
		4873F38B11A4E47B00B5DDB3 /* crypt_find_hash_any.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_find_hash_any.c; sourceTree = "<group>"; };
		4873F38C11A4E47B00B5DDB3 /* crypt_find_hash_id.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_find_hash_id.c; sourceTree = "<group>"; };
		4873F38D11A4E47B00B5DDB3 /* crypt_find_hash_oid.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_find_hash_oid.c; sourceTree = "<group>"; };
		4873F38E11A4E47B00B5DDB3 /* crypt_find_prng.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_find_prng.c; sourceTree = "<group>"; };
		4873F38F11A4E47B00B5DDB3 /* crypt_fsa.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_fsa.c; sourceTree = "<group>"; };
		4873F39011A4E47B00B5DDB3 /* crypt_hash_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_hash_descriptor.c; sourceTree = "<group>"; };
		4873F39111A4E47B00B5DDB3 /* crypt_hash_is_valid.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_hash_is_valid.c; sourceTree = "<group>"; };
		4873F39211A4E47B00B5DDB3 /* crypt_ltc_mp_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_ltc_mp_descriptor.c; sourceTree = "<group>"; };
		4873F39311A4E47B00B5DDB3 /* crypt_mode_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_mode_descriptor.c; sourceTree = "<group>"; };
		4873F39411A4E47B00B5DDB3 /* crypt_prng_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_prng_descriptor.c; sourceTree = "<group>"; };
		4873F39511A4E47B00B5DDB3 /* crypt_prng_is_valid.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_prng_is_valid.c; sourceTree = "<group>"; };
		4873F39611A4E47B00B5DDB3 /* crypt_register_cipher.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_register_cipher.c; sourceTree = "<group>"; };
		4873F39711A4E47B00B5DDB3 /* crypt_register_hash.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_register_hash.c; sourceTree = "<group>"; };
		4873F39811A4E47B00B5DDB3 /* crypt_register_prng.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_register_prng.c; sourceTree = "<group>"; };
		4873F39911A4E47B00B5DDB3 /* crypt_unregister_cipher.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_unregister_cipher.c; sourceTree = "<group>"; };
		4873F39A11A4E47B00B5DDB3 /* crypt_unregister_hash.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_unregister_hash.c; sourceTree = "<group>"; };
		4873F39B11A4E47B00B5DDB3 /* crypt_unregister_prng.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = crypt_unregister_prng.c; sourceTree = "<group>"; };
		4873F39C11A4E47B00B5DDB3 /* error_to_string.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = error_to_string.c; sourceTree = "<group>"; };
		4873F39E11A4E47B00B5DDB3 /* pkcs_5_1.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = pkcs_5_1.c; sourceTree = "<group>"; };
		4873F39F11A4E47B00B5DDB3 /* pkcs_5_2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = pkcs_5_2.c; sourceTree = "<group>"; };
		4873F3A011A4E47B00B5DDB3 /* zeromem.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = zeromem.c; sourceTree = "<group>"; };
		4873F3A311A4E47B00B5DDB3 /* cbc_decrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cbc_decrypt.c; sourceTree = "<group>"; };
		4873F3A411A4E47B00B5DDB3 /* cbc_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cbc_descriptor.c; sourceTree = "<group>"; };
		4873F3A511A4E47B00B5DDB3 /* cbc_done.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cbc_done.c; sourceTree = "<group>"; };
		4873F3A611A4E47B00B5DDB3 /* cbc_encrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cbc_encrypt.c; sourceTree = "<group>"; };
		4873F3A711A4E47B00B5DDB3 /* cbc_getiv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cbc_getiv.c; sourceTree = "<group>"; };
		4873F3A811A4E47B00B5DDB3 /* cbc_setiv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cbc_setiv.c; sourceTree = "<group>"; };
		4873F3A911A4E47B00B5DDB3 /* cbc_start.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cbc_start.c; sourceTree = "<group>"; };
		4873F3AB11A4E47B00B5DDB3 /* cfb_decrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb_decrypt.c; sourceTree = "<group>"; };
		4873F3AC11A4E47B00B5DDB3 /* cfb_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb_descriptor.c; sourceTree = "<group>"; };
		4873F3AD11A4E47B00B5DDB3 /* cfb_done.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb_done.c; sourceTree = "<group>"; };
		4873F3AE11A4E47B00B5DDB3 /* cfb_encrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb_encrypt.c; sourceTree = "<group>"; };
		4873F3AF11A4E47B00B5DDB3 /* cfb_getiv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb_getiv.c; sourceTree = "<group>"; };
		4873F3B011A4E47B00B5DDB3 /* cfb_setiv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb_setiv.c; sourceTree = "<group>"; };
		4873F3B111A4E47B00B5DDB3 /* cfb_start.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = cfb_start.c; sourceTree = "<group>"; };
		4873F3B311A4E47B00B5DDB3 /* ctr_decrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ctr_decrypt.c; sourceTree = "<group>"; };
		4873F3B411A4E47B00B5DDB3 /* ctr_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ctr_descriptor.c; sourceTree = "<group>"; };
		4873F3B511A4E47B00B5DDB3 /* ctr_done.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ctr_done.c; sourceTree = "<group>"; };
		4873F3B611A4E47B00B5DDB3 /* ctr_encrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ctr_encrypt.c; sourceTree = "<group>"; };
		4873F3B711A4E47B00B5DDB3 /* ctr_getiv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ctr_getiv.c; sourceTree = "<group>"; };
		4873F3B811A4E47B00B5DDB3 /* ctr_setiv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ctr_setiv.c; sourceTree = "<group>"; };
		4873F3B911A4E47B00B5DDB3 /* ctr_start.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ctr_start.c; sourceTree = "<group>"; };
		4873F3BA11A4E47B00B5DDB3 /* ctr_test.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ctr_test.c; sourceTree = "<group>"; };
		4873F3BC11A4E47B00B5DDB3 /* ecb_decrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ecb_decrypt.c; sourceTree = "<group>"; };
		4873F3BD11A4E47B00B5DDB3 /* ecb_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ecb_descriptor.c; sourceTree = "<group>"; };
		4873F3BE11A4E47B00B5DDB3 /* ecb_done.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ecb_done.c; sourceTree = "<group>"; };
		4873F3BF11A4E47B00B5DDB3 /* ecb_encrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ecb_encrypt.c; sourceTree = "<group>"; };
		4873F3C011A4E47B00B5DDB3 /* ecb_start.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ecb_start.c; sourceTree = "<group>"; };
		4873F3D511A4E47B00B5DDB3 /* ofb_decrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ofb_decrypt.c; sourceTree = "<group>"; };
		4873F3D611A4E47B00B5DDB3 /* ofb_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ofb_descriptor.c; sourceTree = "<group>"; };
		4873F3D711A4E47B00B5DDB3 /* ofb_done.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ofb_done.c; sourceTree = "<group>"; };
		4873F3D811A4E47B00B5DDB3 /* ofb_encrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ofb_encrypt.c; sourceTree = "<group>"; };
		4873F3D911A4E47B00B5DDB3 /* ofb_getiv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ofb_getiv.c; sourceTree = "<group>"; };
		4873F3DA11A4E47B00B5DDB3 /* ofb_setiv.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ofb_setiv.c; sourceTree = "<group>"; };
		4873F3DB11A4E47B00B5DDB3 /* ofb_start.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ofb_start.c; sourceTree = "<group>"; };
		4873F3DC11A4E47B00B5DDB3 /* rc4_stream.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rc4_stream.c; sourceTree = "<group>"; };
		4873F3DD11A4E47B00B5DDB3 /* unimplemented.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = unimplemented.c; sourceTree = "<group>"; };
		4873F3DF11A4E47B00B5DDB3 /* xts_decrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = xts_decrypt.c; sourceTree = "<group>"; };
		4873F3E011A4E47B00B5DDB3 /* xts_descriptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = xts_descriptor.c; sourceTree = "<group>"; };
		4873F3E111A4E47B00B5DDB3 /* xts_done.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = xts_done.c; sourceTree = "<group>"; };
		4873F3E211A4E47B00B5DDB3 /* xts_encrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = xts_encrypt.c; sourceTree = "<group>"; };
		4873F3E311A4E47B00B5DDB3 /* xts_init.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = xts_init.c; sourceTree = "<group>"; };
		4873F3E411A4E47B00B5DDB3 /* xts_mult_x.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = xts_mult_x.c; sourceTree = "<group>"; };
		4873F3E511A4E47B00B5DDB3 /* xts_test.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = xts_test.c; sourceTree = "<group>"; };
		4873F3E811A4E47B00B5DDB3 /* ansi923pad.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ansi923pad.c; sourceTree = "<group>"; };
		4873F3E911A4E47B00B5DDB3 /* ansi923pad.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ansi923pad.h; sourceTree = "<group>"; };
		4873F3EB11A4E47B00B5DDB3 /* iso10126pad.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = iso10126pad.c; sourceTree = "<group>"; };
		4873F3EC11A4E47B00B5DDB3 /* iso10126pad.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = iso10126pad.h; sourceTree = "<group>"; };
		4873F3EE11A4E47B00B5DDB3 /* nopad.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = nopad.c; sourceTree = "<group>"; };
		4873F3EF11A4E47B00B5DDB3 /* nopad.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = nopad.h; sourceTree = "<group>"; };
		4873F3F111A4E47B00B5DDB3 /* pkcs7pad.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = pkcs7pad.c; sourceTree = "<group>"; };
		4873F3F211A4E47B00B5DDB3 /* pkcs7pad.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = pkcs7pad.h; sourceTree = "<group>"; };
		4882005B111AAD7A00798F94 /* PBKDFTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PBKDFTest.h; path = UnitTestSource/PBKDFTest.h; sourceTree = "<group>"; };
		4882005C111AAD7A00798F94 /* PBKDFTest.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = PBKDFTest.mm; path = UnitTestSource/PBKDFTest.mm; sourceTree = "<group>"; };
		489D982C11A4E8C20004DB89 /* ccdebug.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ccdebug.c; sourceTree = "<group>"; };
		489D982D11A4E8C20004DB89 /* ccdebug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccdebug.h; sourceTree = "<group>"; };
		48B4B98911ABA1B4001F1036 /* aes_modes_hw.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = aes_modes_hw.s; sourceTree = "<group>"; };
		48B4B98A11ABA1B4001F1036 /* aes_modes_asm.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = aes_modes_asm.s; sourceTree = "<group>"; };
		48B4B98B11ABA1B4001F1036 /* aesxts.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = aesxts.h; sourceTree = "<group>"; };
		48B4B98C11ABA1B4001F1036 /* aesxts.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = aesxts.c; sourceTree = "<group>"; };
		48B4B98D11ABA1B4001F1036 /* aesxts_asm.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = aesxts_asm.s; sourceTree = "<group>"; };
		48B4B98E11ABA1B4001F1036 /* ExpandKeyForEncryption.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = ExpandKeyForEncryption.s; sourceTree = "<group>"; };
		48B4B98F11ABA1B4001F1036 /* ExpandKeyForDecryption.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = ExpandKeyForDecryption.s; sourceTree = "<group>"; };
		48B4B99011ABA1B4001F1036 /* EncryptDecrypt.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = EncryptDecrypt.s; sourceTree = "<group>"; };
		48B4B99111ABA1B4001F1036 /* Data.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = Data.s; sourceTree = "<group>"; };
		48B4B99211ABA1B4001F1036 /* Context.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Context.h; sourceTree = "<group>"; };
		48B4B99311ABA1B4001F1036 /* AES.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = AES.s; sourceTree = "<group>"; };
		48B4B99511ABA1B4001F1036 /* aes_key_hw.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = aes_key_hw.s; sourceTree = "<group>"; };
		48B4B99611ABA1B4001F1036 /* aes_crypt_hw.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = aes_crypt_hw.s; sourceTree = "<group>"; };
		48D5636611A652D7008EBBBF /* aesopt.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = aesopt.h; path = ../CommonCryptoSPI/aesopt.h; sourceTree = "<group>"; };
		48D5636711A652D7008EBBBF /* aes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = aes.h; path = ../CommonCryptoSPI/aes.h; sourceTree = "<group>"; };
		48D5636B11A652EB008EBBBF /* aescrypt.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = aescrypt.c; sourceTree = "<group>"; };
		48D5636C11A652EB008EBBBF /* aeskey.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = aeskey.c; sourceTree = "<group>"; };
		48D5636D11A652EB008EBBBF /* aestab.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = aestab.c; sourceTree = "<group>"; };
		48D5636E11A652EB008EBBBF /* aestab.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = aestab.h; sourceTree = "<group>"; };
		48D5636F11A652EB008EBBBF /* ccNewGladman.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ccNewGladman.c; sourceTree = "<group>"; };
		48D5637011A652EB008EBBBF /* README */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = README; sourceTree = "<group>"; };
		48D5637711A65316008EBBBF /* AES.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = AES.c; sourceTree = "<group>"; };
		48D5637811A65316008EBBBF /* AESAssembly.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AESAssembly.h; sourceTree = "<group>"; };
		48D5637911A65316008EBBBF /* Data.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = Data.c; sourceTree = "<group>"; };
		48D5637B11A65316008EBBBF /* AES.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = AES.s; sourceTree = "<group>"; };
		48D5637C11A65316008EBBBF /* Data.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = Data.s; sourceTree = "<group>"; };
		48D5637D11A65316008EBBBF /* DecryptCBC.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = DecryptCBC.s; sourceTree = "<group>"; };
		48D5637E11A65316008EBBBF /* EncryptCBC.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = EncryptCBC.s; sourceTree = "<group>"; };
		48D5637F11A65316008EBBBF /* EncryptDecrypt.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = EncryptDecrypt.s; sourceTree = "<group>"; };
		48D5638011A65316008EBBBF /* ExpandKeyForDecryption.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = ExpandKeyForDecryption.s; sourceTree = "<group>"; };
		48D5638111A65316008EBBBF /* ExpandKeyForEncryption.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = ExpandKeyForEncryption.s; sourceTree = "<group>"; };
		48D5638211A65316008EBBBF /* ReadMe.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ReadMe.txt; sourceTree = "<group>"; };
		48D5638311A65316008EBBBF /* MakeData.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = MakeData.c; sourceTree = "<group>"; };
		48D5638411A65316008EBBBF /* makefile */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.make; path = makefile; sourceTree = "<group>"; };
		48D5638511A65316008EBBBF /* ReadMe.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ReadMe.txt; sourceTree = "<group>"; };
		48F7AFFF12F2488500E70774 /* CCCalibratePBKDF.3cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CCCalibratePBKDF.3cc; path = doc/CCCalibratePBKDF.3cc; sourceTree = "<group>"; };
		48F7B00012F2488500E70774 /* CCCommonKeyDerivation.3cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CCCommonKeyDerivation.3cc; path = doc/CCCommonKeyDerivation.3cc; sourceTree = "<group>"; };
		48F7B00312F248E600E70774 /* CCKeyDerivationPBKDF.3cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CCKeyDerivationPBKDF.3cc; path = doc/CCKeyDerivationPBKDF.3cc; sourceTree = "<group>"; };
		48F7B00412F248E600E70774 /* CCSymmetricKeyUnwrap.3cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CCSymmetricKeyUnwrap.3cc; path = doc/CCSymmetricKeyUnwrap.3cc; sourceTree = "<group>"; };
		48F7B00512F248E600E70774 /* CCSymmetricKeyWrap.3cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CCSymmetricKeyWrap.3cc; path = doc/CCSymmetricKeyWrap.3cc; sourceTree = "<group>"; };
		48F7B00612F248E600E70774 /* CCSymmetricUnwrappedSize.3cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CCSymmetricUnwrappedSize.3cc; path = doc/CCSymmetricUnwrappedSize.3cc; sourceTree = "<group>"; };
		48F7B00712F248E600E70774 /* CCSymmetricWrappedSize.3cc */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = CCSymmetricWrappedSize.3cc; path = doc/CCSymmetricWrappedSize.3cc; sourceTree = "<group>"; };
		48F7F36D12B2EF6000AF4587 /* libcommonCrypto.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libcommonCrypto.dylib; sourceTree = BUILT_PRODUCTS_DIR; };
		48F7F37712B2F05A00AF4587 /* aes.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = aes.c; sourceTree = "<group>"; };
		48F7F37812B2F05A00AF4587 /* aes_tab.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = aes_tab.c; sourceTree = "<group>"; };
		48F7F37912B2F05A00AF4587 /* ltc_aes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ltc_aes.h; sourceTree = "<group>"; };
		53B9FDE81343DD0600CA1154 /* CommonCMAC.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonCMAC.c; sourceTree = "<group>"; };
		53B9FDED1343DDB700CA1154 /* CommonCMACSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCMACSPI.h; sourceTree = "<group>"; };
		5D113BC21106441E00B412A2 /* CommonCrypto_base.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CommonCrypto_base.xcconfig; path = Configurations/CommonCrypto_base.xcconfig; sourceTree = "<group>"; };
		5D113BCB1106441E00B412A2 /* CommonCrypto_unittest_base.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = CommonCrypto_unittest_base.xcconfig; path = Configurations/CommonCrypto_unittest_base.xcconfig; sourceTree = "<group>"; };
		5D113BD41106452100B412A2 /* CommonCryptoUnitTests-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "CommonCryptoUnitTests-Info.plist"; path = "UnitTestSource/CommonCryptoUnitTests-Info.plist"; sourceTree = "<group>"; };
		5D113BD51106452100B412A2 /* CommonCryptoUnitTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CommonCryptoUnitTests.h; path = UnitTestSource/CommonCryptoUnitTests.h; sourceTree = "<group>"; };
		5D113BD61106452100B412A2 /* CommonCryptoUnitTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = CommonCryptoUnitTests.mm; path = UnitTestSource/CommonCryptoUnitTests.mm; sourceTree = "<group>"; };
		5D113BD71106452100B412A2 /* DigestTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DigestTest.h; path = UnitTestSource/DigestTest.h; sourceTree = "<group>"; };
		5D113BD81106452100B412A2 /* DigestTest.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = DigestTest.mm; path = UnitTestSource/DigestTest.mm; sourceTree = "<group>"; };
		5D113BD91106452100B412A2 /* EncryptionTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = EncryptionTest.h; path = UnitTestSource/EncryptionTest.h; sourceTree = "<group>"; };
		5D113BDA1106452100B412A2 /* EncryptionTest.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = EncryptionTest.mm; path = UnitTestSource/EncryptionTest.mm; sourceTree = "<group>"; };
		5D113BDB1106452100B412A2 /* HMACTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = HMACTest.h; path = UnitTestSource/HMACTest.h; sourceTree = "<group>"; };
		5D113BDC1106452100B412A2 /* HMACTest.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = HMACTest.mm; path = UnitTestSource/HMACTest.mm; sourceTree = "<group>"; };
		5D113BDD1106452100B412A2 /* RandomNumberService.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RandomNumberService.h; path = UnitTestSource/RandomNumberService.h; sourceTree = "<group>"; };
		5D113BDE1106452100B412A2 /* RandomNumberService.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = RandomNumberService.mm; path = UnitTestSource/RandomNumberService.mm; sourceTree = "<group>"; };
		5D57A807111B5DDE008CA573 /* SymmetricWrapTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SymmetricWrapTest.h; path = UnitTestSource/SymmetricWrapTest.h; sourceTree = "<group>"; };
		5D57A808111B5DDE008CA573 /* SymmetricWrapTest.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = SymmetricWrapTest.mm; path = UnitTestSource/SymmetricWrapTest.mm; sourceTree = "<group>"; };
		5D735E4810FCDC04001AAD1E /* CommonCryptoUnitTest.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CommonCryptoUnitTest.octest; sourceTree = BUILT_PRODUCTS_DIR; };
		5DAD82CC1279DEF900240B9A /* libCommonCryptoUnitTest.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libCommonCryptoUnitTest.a; sourceTree = BUILT_PRODUCTS_DIR; };
		5DAD82EC1279E04500240B9A /* TestToolProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TestToolProtocol.h; path = UnitTestSource/TestToolProtocol.h; sourceTree = "<group>"; };
		5DAD83991279F1EC00240B9A /* CommonCryptoTestTool */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = CommonCryptoTestTool; sourceTree = BUILT_PRODUCTS_DIR; };
		5DAD83A21279F29300240B9A /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = "<absolute>"; };
		5DAD83A71279F2B200240B9A /* main.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = main.mm; path = UnitTestSource/main.mm; sourceTree = "<group>"; };
		795CA3FD0D34431400BAE6A2 /* ccRC2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ccRC2.c; sourceTree = "<group>"; };
		795CA3FE0D34431400BAE6A2 /* rc2.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = rc2.c; sourceTree = "<group>"; };
		AAB5CBCC0DC6AB6D0019E0E6 /* sha1edp.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = sha1edp.h; sourceTree = "<group>"; };
		AAB5CBCD0DC6AB6D0019E0E6 /* sha1edpBigEndian.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = sha1edpBigEndian.s; sourceTree = "<group>"; };
		AAB5CBCE0DC6AB6D0019E0E6 /* sha1edpLittleEndian.s */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.asm; path = sha1edpLittleEndian.s; sourceTree = "<group>"; };

		D671B5B60BC6D67000878B42 /* CC_MD2.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD2.3cc; path = doc/CC_MD2.3cc; sourceTree = "<group>"; };
		D671B5B70BC6D67000878B42 /* CC_MD2_Final.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD2_Final.3cc; path = doc/CC_MD2_Final.3cc; sourceTree = "<group>"; };
		D671B5B80BC6D67000878B42 /* CC_MD2_Init.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD2_Init.3cc; path = doc/CC_MD2_Init.3cc; sourceTree = "<group>"; };
		D671B5B90BC6D67000878B42 /* CC_MD2_Update.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD2_Update.3cc; path = doc/CC_MD2_Update.3cc; sourceTree = "<group>"; };
		D671B5BA0BC6D67000878B42 /* CC_MD4.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD4.3cc; path = doc/CC_MD4.3cc; sourceTree = "<group>"; };
		D671B5BB0BC6D67000878B42 /* CC_MD4_Final.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD4_Final.3cc; path = doc/CC_MD4_Final.3cc; sourceTree = "<group>"; };
		D671B5BC0BC6D67000878B42 /* CC_MD4_Init.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD4_Init.3cc; path = doc/CC_MD4_Init.3cc; sourceTree = "<group>"; };







<
<
<
<
<
<
<






<



<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

<
<
<
<
<
<
<

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
|
>
|
>
|
|
>
|
>
>
>
>
|
>
>
|





<



>
>
>




<
<
|
|
|
<
<
<
<
<
<
<
<
<
<
|
|
<
|
|
|
|
|
|
<
<
|
<
<
<
<
|
|
|
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|
<
|
|
|
|
|
|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
|
|
|
|
<
<


|
<
|
|
<
<
<
<
<
|
|
<
<
<
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
|
|
|
|
|
<
<
<
|
<
|
<
|
<
|
|
|
<
|
<
<
<
|
<
<
<
|
|
|
|
|
>







513
514
515
516
517
518
519







520
521
522
523
524
525

526
527
528

















529
530
531
532
533
534
535































536







537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588

589
590
591
592
593
594
595
596
597
598


599
600
601










602
603

604
605
606
607
608
609


610




611
612
613
614



615

































616













617
618
619
620

621
622
623
624
625
626

627


































628


629
630
631
632


633
634
635

636
637





638
639



640
641
642
643
644
645
646
647
648
649
650
651
652





653










654
655
656
657
658



659

660

661

662
663
664

665



666



667
668
669
670
671
672
673
674
675
676
677
678
679
				D6658DBE0BD8178400D18063 /* CCCryptorUpdate.3cc in CopyFiles */,
				D6658DBF0BD8178400D18063 /* CCHmac.3cc in CopyFiles */,
				D6658DC00BD8178400D18063 /* CCHmacFinal.3cc in CopyFiles */,
				D6658DC10BD8178400D18063 /* CCHmacInit.3cc in CopyFiles */,
				D6658DC20BD8178400D18063 /* CCHmacUpdate.3cc in CopyFiles */,
				D6658DC30BD8178400D18063 /* CCryptorCreateFromData.3cc in CopyFiles */,
				D6658DC40BD8178400D18063 /* Common Crypto.3cc in CopyFiles */,







			);
			runOnlyForDeploymentPostprocessing = 1;
		};
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */

		054BBEBE05F6A97700344873 /* libcommonCrypto.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libcommonCrypto.dylib; sourceTree = BUILT_PRODUCTS_DIR; };
		054BBEC605F6A98900344873 /* libcommonCrypto.dylib */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libcommonCrypto.dylib; sourceTree = BUILT_PRODUCTS_DIR; };
		054BBECD05F6AA7200344873 /* CommonDigest.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = CommonDigest.h; sourceTree = "<group>"; };

















		05CE942B0A37850A007C91D6 /* CommonCrypto.plist */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text.plist.xml; name = CommonCrypto.plist; path = doc/CommonCrypto.plist; sourceTree = "<group>"; };
		05CE942C0A37850A007C91D6 /* CommonCrypto.txt */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CommonCrypto.txt; path = doc/CommonCrypto.txt; sourceTree = "<group>"; };
		05D8D97C09E411AA00E03504 /* CommonHMAC.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonHMAC.h; sourceTree = "<group>"; };
		05D9F61609D85F4A00AD30A7 /* CommonCryptor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCryptor.h; sourceTree = "<group>"; };
		05DF6D1109CF2D7200D9A3E8 /* CC_crypto.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_crypto.3cc; path = doc/CC_crypto.3cc; sourceTree = "<group>"; };
		05DF6D1209CF2D7200D9A3E8 /* CC_MD5.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD5.3cc; path = doc/CC_MD5.3cc; sourceTree = "<group>"; };
		05DF6D1309CF2D7200D9A3E8 /* CC_SHA.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_SHA.3cc; path = doc/CC_SHA.3cc; sourceTree = "<group>"; };































		12FA0DAF11F7962100917A4E /* CommonRandomSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonRandomSPI.h; sourceTree = "<group>"; };







		48096B2211A5EF900043F67F /* CommonDigest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonDigest.c; sourceTree = "<group>"; };
		48165DB9125AC5D50015A267 /* libcommonCrypto.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libcommonCrypto.dylib; sourceTree = BUILT_PRODUCTS_DIR; };
		48165E9C125AC5F20015A267 /* libcommonCrypto_sim.dylib */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = libcommonCrypto_sim.dylib; sourceTree = BUILT_PRODUCTS_DIR; };
		4823B0AE14C10022008F689F /* CCCryptorTestFuncs.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CCCryptorTestFuncs.c; sourceTree = "<group>"; };
		4823B0AF14C10022008F689F /* CCCryptorTestFuncs.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CCCryptorTestFuncs.h; sourceTree = "<group>"; };
		4823B0B014C10022008F689F /* CommonBaseEncoding.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonBaseEncoding.c; sourceTree = "<group>"; };
		4823B0B114C10022008F689F /* CommonBigNum.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonBigNum.c; sourceTree = "<group>"; };
		4823B0B214C10022008F689F /* CommonCMac.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCMac.c; sourceTree = "<group>"; };
		4823B0B314C10022008F689F /* CommonCryptoCTSPadding.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCryptoCTSPadding.c; sourceTree = "<group>"; };
		4823B0B414C10022008F689F /* CommonCryptoSymCBC.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymCBC.c; sourceTree = "<group>"; };
		4823B0B514C10022008F689F /* CommonCryptoSymGCM.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymGCM.c; sourceTree = "<group>"; };
		4823B0B614C10022008F689F /* CommonCryptoSymmetricWrap.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymmetricWrap.c; sourceTree = "<group>"; };
		4823B0B714C10022008F689F /* CommonCryptoSymOFB.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymOFB.c; sourceTree = "<group>"; };
		4823B0B814C10022008F689F /* CommonCryptoSymOffset.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymOffset.c; sourceTree = "<group>"; };
		4823B0B914C10022008F689F /* CommonCryptoSymRC2.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymRC2.c; sourceTree = "<group>"; };
		4823B0BA14C10022008F689F /* CommonCryptoSymRegression.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymRegression.c; sourceTree = "<group>"; };
		4823B0BB14C10022008F689F /* CommonCryptoSymXTS.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymXTS.c; sourceTree = "<group>"; };
		4823B0BC14C10022008F689F /* CommonCryptoSymZeroLength.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymZeroLength.c; sourceTree = "<group>"; };
		4823B0BD14C10022008F689F /* CommonDigest.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonDigest.c; sourceTree = "<group>"; };
		4823B0BE14C10022008F689F /* CommonEC.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonEC.c; sourceTree = "<group>"; };
		4823B0BF14C10022008F689F /* CommonHMacClone.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonHMacClone.c; sourceTree = "<group>"; };
		4823B0C014C10022008F689F /* CommonRandom.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonRandom.c; sourceTree = "<group>"; };
		4823B0C114C10022008F689F /* CommonRSA.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CommonRSA.c; sourceTree = "<group>"; };
		4823B0C314C10022008F689F /* CryptorPadFailure.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = CryptorPadFailure.c; sourceTree = "<group>"; };
		4823B0C614C10022008F689F /* Run3.pm */ = {isa = PBXFileReference; lastKnownFileType = text.script.perl; path = Run3.pm; sourceTree = "<group>"; };
		4823B0C714C10022008F689F /* MyHarness.pm */ = {isa = PBXFileReference; lastKnownFileType = text.script.perl; path = MyHarness.pm; sourceTree = "<group>"; };
		4823B0C814C10022008F689F /* main.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = main.c; sourceTree = "<group>"; };
		4823B0C914C10022008F689F /* README */ = {isa = PBXFileReference; lastKnownFileType = text; path = README; sourceTree = "<group>"; };
		4823B0CB14C10022008F689F /* security.pl */ = {isa = PBXFileReference; lastKnownFileType = text.script.perl; path = security.pl; sourceTree = "<group>"; };
		4823B0CD14C10022008F689F /* 00testtest.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = 00testtest.c; sourceTree = "<group>"; };
		4823B0CE14C10022008F689F /* run_tests.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = run_tests.sh; sourceTree = "<group>"; };
		4823B0CF14C10022008F689F /* testcpp.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = testcpp.h; sourceTree = "<group>"; };
		4823B0D014C10022008F689F /* testenv.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = testenv.c; sourceTree = "<group>"; };
		4823B0D114C10022008F689F /* testenv.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = testenv.h; sourceTree = "<group>"; };
		4823B0D214C10022008F689F /* testlist.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = testlist.c; sourceTree = "<group>"; };
		4823B0D314C10022008F689F /* testlist.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = testlist.h; sourceTree = "<group>"; };
		4823B0D414C10022008F689F /* testlistInc.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = testlistInc.h; sourceTree = "<group>"; };
		4823B0D514C10022008F689F /* testmore.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = testmore.c; sourceTree = "<group>"; };
		4823B0D614C10022008F689F /* testmore.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = testmore.h; sourceTree = "<group>"; };
		4823B0D814C10022008F689F /* testbyteBuffer.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = testbyteBuffer.c; sourceTree = "<group>"; };
		4823B0D914C10022008F689F /* testbyteBuffer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = testbyteBuffer.h; sourceTree = "<group>"; };
		4823B0DA14C10022008F689F /* capabilities.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = capabilities.h; sourceTree = "<group>"; };
		4823B0E014C10064008F689F /* CCRegression */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = CCRegression; sourceTree = BUILT_PRODUCTS_DIR; };
		4825AAF31314CDCD00413A64 /* CommonBigNum.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonBigNum.h; sourceTree = "<group>"; };
		4834A85214F47A9400438E3D /* libcorecrypto.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libcorecrypto.dylib; path = usr/lib/system/libcorecrypto.dylib; sourceTree = SDKROOT; };
		4834A88014F47B6200438E3D /* CCRegression copy */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "CCRegression copy"; sourceTree = BUILT_PRODUCTS_DIR; };
		4836A41A11A5C94A00862178 /* CommonCryptoPriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCryptoPriv.h; sourceTree = "<group>"; };
		4836A42B11A5CB4700862178 /* CommonCryptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonCryptor.c; sourceTree = "<group>"; };
		4836A42C11A5CB4700862178 /* CommonCryptorPriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCryptorPriv.h; sourceTree = "<group>"; };
		4836A42D11A5CB4700862178 /* CommonDigestPriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonDigestPriv.h; sourceTree = "<group>"; };
		4836A42E11A5CB4700862178 /* CommonHMAC.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonHMAC.c; sourceTree = "<group>"; };
		4836A42F11A5CB4700862178 /* CommonKeyDerivation.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonKeyDerivation.c; sourceTree = "<group>"; };

		4836A43111A5CB4700862178 /* CommonSymmetricKeywrap.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonSymmetricKeywrap.c; sourceTree = "<group>"; };
		4846CA5411A5C8B800E7DA82 /* CommonCryptorSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCryptorSPI.h; sourceTree = "<group>"; };
		4846CA5511A5C8B800E7DA82 /* CommonDigestSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonDigestSPI.h; sourceTree = "<group>"; };
		484D40FE14DC96A600C93734 /* libcorecrypto.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libcorecrypto.dylib; path = ../../../../../../usr/lib/system/libcorecrypto.dylib; sourceTree = "<group>"; };
		4852C2491505F8CD00676BCC /* CommonCryptoSymCFB.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymCFB.c; sourceTree = "<group>"; };
		4854BAD5152177CC007B5B08 /* CommonCryptoSymCTR.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonCryptoSymCTR.c; sourceTree = "<group>"; };
		4854F9C01116307500CAFA18 /* CommonKeyDerivation.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonKeyDerivation.h; sourceTree = "<group>"; };
		4854F9C11116307500CAFA18 /* CommonSymmetricKeywrap.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonSymmetricKeywrap.h; sourceTree = "<group>"; };
		4857A12A11BDA6E0001F5A9A /* libSystem.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libSystem.dylib; path = usr/lib/libSystem.dylib; sourceTree = SDKROOT; };
		4857A13011BDA737001F5A9A /* System.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = System.framework; path = /System/Library/Frameworks/System.framework; sourceTree = "<absolute>"; };


		485FED4A131475A400FF0F82 /* CommonBigNumPriv.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonBigNumPriv.h; sourceTree = "<group>"; };
		485FED4B131475A400FF0F82 /* CommonBigNum.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonBigNum.c; sourceTree = "<group>"; };
		486130D7126681290036EA02 /* CC_base.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_base.xcconfig; sourceTree = "<group>"; };










		486130D8126681290036EA02 /* CC_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_deployment.xcconfig; sourceTree = "<group>"; };
		486130D9126681290036EA02 /* CC_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_development.xcconfig; sourceTree = "<group>"; };

		486130DA126681290036EA02 /* CC_dynamic.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_dynamic.xcconfig; sourceTree = "<group>"; };
		486130DB126681290036EA02 /* CC_dynamic_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_dynamic_deployment.xcconfig; sourceTree = "<group>"; };
		486130DC126681290036EA02 /* CC_dynamic_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_dynamic_development.xcconfig; sourceTree = "<group>"; };
		486130DD126681290036EA02 /* CC_static.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_static.xcconfig; sourceTree = "<group>"; };
		486130DE126681290036EA02 /* CC_static_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_static_deployment.xcconfig; sourceTree = "<group>"; };
		486130DF126681290036EA02 /* CC_static_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_static_development.xcconfig; sourceTree = "<group>"; };


		486130E0126681290036EA02 /* CC_umbrellaMember.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_umbrellaMember.xcconfig; sourceTree = "<group>"; };




		486130E2126681290036EA02 /* CC_iOSClient.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_iOSClient.xcconfig; sourceTree = "<group>"; };
		486130E3126681290036EA02 /* CC_iOSClientSim.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_iOSClientSim.xcconfig; sourceTree = "<group>"; };
		486130E5126681290036EA02 /* CC_MacOSXClient.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_MacOSXClient.xcconfig; sourceTree = "<group>"; };
		486130E8126681290036EA02 /* CC_iOSClient_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_iOSClient_deployment.xcconfig; sourceTree = "<group>"; };



		486130E9126681290036EA02 /* CC_iOSClient_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_iOSClient_development.xcconfig; sourceTree = "<group>"; };

































		486130EC126681290036EA02 /* CC_iOSSim_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_iOSSim_deployment.xcconfig; sourceTree = "<group>"; };













		486130ED126681290036EA02 /* CC_iOSSim_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_iOSSim_development.xcconfig; sourceTree = "<group>"; };
		486130EE126681290036EA02 /* CC_MacOSXClient_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_MacOSXClient_deployment.xcconfig; sourceTree = "<group>"; };
		486130EF126681290036EA02 /* CC_MacOSXClient_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_MacOSXClient_development.xcconfig; sourceTree = "<group>"; };
		486130F3126681290036EA02 /* CC_localtest.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_localtest.xcconfig; sourceTree = "<group>"; };

		486130F4126681290036EA02 /* CC_unittest_base.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_unittest_base.xcconfig; sourceTree = "<group>"; };
		486130F5126681290036EA02 /* CC_unittest_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_unittest_deployment.xcconfig; sourceTree = "<group>"; };
		486130F6126681290036EA02 /* CC_unittest_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_unittest_development.xcconfig; sourceTree = "<group>"; };
		486130F7126681290036EA02 /* CC_unittest_dynamic_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_unittest_dynamic_deployment.xcconfig; sourceTree = "<group>"; };
		486130F8126681290036EA02 /* CC_unitTest_dynamic_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_unitTest_dynamic_development.xcconfig; sourceTree = "<group>"; };
		486130F9126681290036EA02 /* CC_unittest_static_deployment.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_unittest_static_deployment.xcconfig; sourceTree = "<group>"; };

		486130FA126681290036EA02 /* CC_unittest_static_development.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = CC_unittest_static_development.xcconfig; sourceTree = "<group>"; };


































		48685583127B63F200B88D39 /* aes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = aes.h; sourceTree = "<group>"; };


		48685586127B641800B88D39 /* CommonCryptoAESShoefly.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonCryptoAESShoefly.c; sourceTree = "<group>"; };
		4868BB1314B7C7F300072488 /* corecryptoSymmetricBridge.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = corecryptoSymmetricBridge.h; sourceTree = "<group>"; };
		486BE17C14E6019B00346AC4 /* CommonCryptoReset.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonCryptoReset.c; sourceTree = "<group>"; };
		4873A7271445099D0011B4FA /* CommonCrypto.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCrypto.h; sourceTree = "<group>"; };


		489D982C11A4E8C20004DB89 /* ccdebug.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = ccdebug.c; sourceTree = "<group>"; };
		489D982D11A4E8C20004DB89 /* ccdebug.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccdebug.h; sourceTree = "<group>"; };
		489E06F814B7AB0800B0A282 /* corecryptoSymmetricBridge.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = corecryptoSymmetricBridge.c; sourceTree = "<group>"; };

		489EECA2149809A800B44D5A /* asn1Types.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = asn1Types.h; sourceTree = "<group>"; };
		489EECA3149809A800B44D5A /* DER_CertCrl.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = DER_CertCrl.c; sourceTree = "<group>"; };





		489EECA4149809A800B44D5A /* DER_CertCrl.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DER_CertCrl.h; sourceTree = "<group>"; };
		489EECA5149809A800B44D5A /* DER_Decode.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = DER_Decode.c; sourceTree = "<group>"; };



		489EECA6149809A800B44D5A /* DER_Decode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DER_Decode.h; sourceTree = "<group>"; };
		489EECA7149809A800B44D5A /* DER_Digest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = DER_Digest.c; sourceTree = "<group>"; };
		489EECA8149809A800B44D5A /* DER_Digest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DER_Digest.h; sourceTree = "<group>"; };
		489EECA9149809A800B44D5A /* DER_Encode.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = DER_Encode.c; sourceTree = "<group>"; };
		489EECAA149809A800B44D5A /* DER_Encode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DER_Encode.h; sourceTree = "<group>"; };
		489EECAB149809A800B44D5A /* DER_Keys.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = DER_Keys.c; sourceTree = "<group>"; };
		489EECAC149809A800B44D5A /* DER_Keys.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DER_Keys.h; sourceTree = "<group>"; };
		489EECAD149809A800B44D5A /* libDER.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = libDER.h; sourceTree = "<group>"; };
		489EECAE149809A800B44D5A /* libDER_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = libDER_config.h; sourceTree = "<group>"; };
		489EECAF149809A800B44D5A /* oids.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = oids.c; sourceTree = "<group>"; };
		489EECB0149809A800B44D5A /* oids.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = oids.h; sourceTree = "<group>"; };
		489F2441141AA3D0005E80FD /* CommonCMAC.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonCMAC.c; sourceTree = "<group>"; };
		489FD30B13187B1D00ACB86D /* CommonHMacSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonHMacSPI.h; sourceTree = "<group>"; };





		48A5CBA0131EE096002A6E85 /* CommonGCMCryptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonGCMCryptor.c; sourceTree = "<group>"; };










		48AC47CD1381EFDC00F584F5 /* byteBuffer.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = byteBuffer.c; sourceTree = "<group>"; };
		48AC47CE1381EFDC00F584F5 /* byteBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = byteBuffer.h; sourceTree = "<group>"; };
		48B4651112848FB800311799 /* CommonRSACryptor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonRSACryptor.h; sourceTree = "<group>"; };
		48B4651B1284907600311799 /* CommonRSACryptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonRSACryptor.c; sourceTree = "<group>"; };
		48C5CB9114FD747500F4472E /* CommonDHtest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonDHtest.c; sourceTree = "<group>"; };



		48CCD26414F6F189002B6043 /* CommonBigDigest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonBigDigest.c; sourceTree = "<group>"; };

		48D076C0130B2A510052D1AC /* CommonDH.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonDH.h; sourceTree = "<group>"; };

		48D076C7130B2A620052D1AC /* CommonECCryptor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonECCryptor.h; sourceTree = "<group>"; };

		48D076CE130B2A9C0052D1AC /* CommonDH.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonDH.c; sourceTree = "<group>"; };
		48D076CF130B2A9C0052D1AC /* CommonECCryptor.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonECCryptor.c; sourceTree = "<group>"; };
		48E93DCA136867F500B33DB8 /* CommonCMACSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCMACSPI.h; sourceTree = "<group>"; };

		48F5355214902894000D2D1F /* CommonRandom.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonRandom.c; sourceTree = "<group>"; };



		48FC4BD513959D0600DA4760 /* lionCompat.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = lionCompat.h; sourceTree = "<group>"; };



		48FC4BD71395ACE600DA4760 /* CommonCryptoCASTShoefly.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = CommonCryptoCASTShoefly.c; sourceTree = "<group>"; };
		48FD6C371354DD4000F55B8B /* ccErrors.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccErrors.h; sourceTree = "<group>"; };
		48FD6C381354DD4000F55B8B /* ccMemory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ccMemory.h; sourceTree = "<group>"; };
		48FD6C631354E06A00F55B8B /* CommonCrypto.exp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.exports; path = CommonCrypto.exp; sourceTree = "<group>"; };
		48FD6C641354E06A00F55B8B /* CommonCryptoIOS5.exp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.exports; path = CommonCryptoIOS5.exp; sourceTree = "<group>"; };
		5D8037A514FECB5900E93214 /* libcorecrypto_sim.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libcorecrypto_sim.dylib; path = Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.0.sdk/usr/lib/system/libcorecrypto_sim.dylib; sourceTree = DEVELOPER_DIR; };
		D671B5B60BC6D67000878B42 /* CC_MD2.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD2.3cc; path = doc/CC_MD2.3cc; sourceTree = "<group>"; };
		D671B5B70BC6D67000878B42 /* CC_MD2_Final.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD2_Final.3cc; path = doc/CC_MD2_Final.3cc; sourceTree = "<group>"; };
		D671B5B80BC6D67000878B42 /* CC_MD2_Init.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD2_Init.3cc; path = doc/CC_MD2_Init.3cc; sourceTree = "<group>"; };
		D671B5B90BC6D67000878B42 /* CC_MD2_Update.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD2_Update.3cc; path = doc/CC_MD2_Update.3cc; sourceTree = "<group>"; };
		D671B5BA0BC6D67000878B42 /* CC_MD4.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD4.3cc; path = doc/CC_MD4.3cc; sourceTree = "<group>"; };
		D671B5BB0BC6D67000878B42 /* CC_MD4_Final.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD4_Final.3cc; path = doc/CC_MD4_Final.3cc; sourceTree = "<group>"; };
		D671B5BC0BC6D67000878B42 /* CC_MD4_Init.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CC_MD4_Init.3cc; path = doc/CC_MD4_Init.3cc; sourceTree = "<group>"; };
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115



1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136

1137
1138
1139
1140
1141
1142
1143
1144
1145

1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165


1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
		D671B5DF0BC6D67000878B42 /* CCHmacInit.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CCHmacInit.3cc; path = doc/CCHmacInit.3cc; sourceTree = "<group>"; };
		D671B5E00BC6D67000878B42 /* CCHmacUpdate.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CCHmacUpdate.3cc; path = doc/CCHmacUpdate.3cc; sourceTree = "<group>"; };
		D671B5E10BC6D67000878B42 /* CCryptorCreateFromData.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CCryptorCreateFromData.3cc; path = doc/CCryptorCreateFromData.3cc; sourceTree = "<group>"; };
		D671B5E20BC6D67000878B42 /* Common Crypto.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = "Common Crypto.3cc"; path = "doc/Common Crypto.3cc"; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
		125B794F11FF923D008C1AD3 /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
				125B795611FF925B008C1AD3 /* libcommonCrypto.dylib in Frameworks */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		128881631203673C0050B2E9 /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
				1235BCBF1207FAFC002BC892 /* libcommonCrypto.dylib in Frameworks */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		5D735E4510FCDC04001AAD1E /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
				5DAD82E11279DF7A00240B9A /* libCommonCryptoUnitTest.a in Frameworks */,
				12FA10CA11F7A01D00917A4E /* libcommonCrypto.dylib in Frameworks */,
				12C3F7E6122AD1B100E09D9E /* SenTestingKit.framework in Frameworks */,
				5DAD83A31279F29300240B9A /* Foundation.framework in Frameworks */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		5DAD82CA1279DEF900240B9A /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		5DAD83971279F1EC00240B9A /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
				5DAD839F1279F22C00240B9A /* libCommonCryptoUnitTest.a in Frameworks */,
				5DAD83A61279F29800240B9A /* Foundation.framework in Frameworks */,
				5DAD83A11279F26700240B9A /* System.framework in Frameworks */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXFrameworksBuildPhase section */

/* Begin PBXGroup section */
		054BBEA205F6A8DE00344873 = {
			isa = PBXGroup;
			children = (
				4857A13011BDA737001F5A9A /* System.framework */,



				5DB4936310FBC4E200E45951 /* Configurations */,
				054BBEB105F6A90E00344873 /* Public Headers */,
				054BBEB405F6A91E00344873 /* Source */,
				05DF6D0E09CF2D5B00D9A3E8 /* Doc */,
				5DB4940410FBE5A800E45951 /* UnitTestSource */,
				1210DF01120488B50054B6F9 /* TestTools */,
				054BBEBF05F6A97700344873 /* Products */,
				4857A12A11BDA6E0001F5A9A /* libSystem.dylib */,
				12C3F7E5122AD1B100E09D9E /* SenTestingKit.framework */,
				5DAD83A21279F29300240B9A /* Foundation.framework */,
			);
			sourceTree = "<group>";
		};
		054BBEB105F6A90E00344873 /* Public Headers */ = {
			isa = PBXGroup;
			children = (
				4854F9C01116307500CAFA18 /* CommonKeyDerivation.h */,
				4854F9C11116307500CAFA18 /* CommonSymmetricKeywrap.h */,
				054BBECD05F6AA7200344873 /* CommonDigest.h */,
				05D9F61609D85F4A00AD30A7 /* CommonCryptor.h */,
				05D8D97C09E411AA00E03504 /* CommonHMAC.h */,

			);
			name = "Public Headers";
			path = CommonCrypto;
			sourceTree = "<group>";
		};
		054BBEB405F6A91E00344873 /* Source */ = {
			isa = PBXGroup;
			children = (
				12FBB0891238353000772329 /* CommonCrypto.exp */,

				4836A42A11A5CB4700862178 /* API */,
				4846CA5311A5C8B800E7DA82 /* SPI */,
				489D982B11A4E8C20004DB89 /* Utility */,
				4873F33C11A4E47B00B5DDB3 /* libtomcrypt */,
				1210DF02120489050054B6F9 /* Legacy */,
			);
			path = Source;
			sourceTree = "<group>";
		};
		054BBEBF05F6A97700344873 /* Products */ = {
			isa = PBXGroup;
			children = (
				054BBEBE05F6A97700344873 /* libcommonCrypto.dylib */,
				054BBEC605F6A98900344873 /* libcommonCrypto.dylib */,
				5D735E4810FCDC04001AAD1E /* CommonCryptoUnitTest.octest */,
				125B795111FF923D008C1AD3 /* XTStest */,
				128881651203673C0050B2E9 /* CBCTest */,
				5DAD82CC1279DEF900240B9A /* libCommonCryptoUnitTest.a */,
				5DAD83991279F1EC00240B9A /* CommonCryptoTestTool */,
				48F7F36D12B2EF6000AF4587 /* libcommonCrypto.dylib */,


			);
			name = Products;
			sourceTree = "<group>";
		};
		0585FE1109DC9850001762F6 /* CAST */ = {
			isa = PBXGroup;
			children = (
				4836A41D11A5C94A00862178 /* cast.h */,
				4836A41C11A5C94A00862178 /* ccCast.h */,
				0585FE1209DC9873001762F6 /* c_ecb.c */,
				0585FE1309DC9873001762F6 /* c_enc.c */,
				0585FE1409DC9873001762F6 /* c_skey.c */,
				0585FE1609DC9873001762F6 /* cast_lcl.h */,
				0585FE1709DC9873001762F6 /* cast_s.h */,
				0585FE1809DC9873001762F6 /* ccCast.c */,
			);
			path = CAST;
			sourceTree = "<group>";
		};
		05D9F60109D85DA100AD30A7 /* Digest */ = {
			isa = PBXGroup;
			children = (
				122ADC43121320D70027F302 /* sha256_nossse3.s */,
				122ADC44121320D70027F302 /* sha256.s */,
				AAB5CBCC0DC6AB6D0019E0E6 /* sha1edp.h */,
				AAB5CBCD0DC6AB6D0019E0E6 /* sha1edpBigEndian.s */,
				AAB5CBCE0DC6AB6D0019E0E6 /* sha1edpLittleEndian.s */,
				054BBED305F6AA8900344873 /* md2_dgst.c */,
				054BBED405F6AA8900344873 /* md4_dgst.c */,
				054BBED505F6AA8900344873 /* md4_locl.h */,
				054BBED605F6AA8900344873 /* md5_dgst.c */,
				054BBED705F6AA8900344873 /* md5_locl.h */,
				054BBED805F6AA8900344873 /* md32_common.h */,
				054BBEDA05F6AA8900344873 /* sha_locl.h */,
				054BBEDC05F6AA8900344873 /* sha1.c */,
				05E319B7063890C100C4AD24 /* sha2.c */,
				05E319DC0638913700C4AD24 /* sha2Priv.h */,
			);
			path = Digest;
			sourceTree = "<group>";
		};
		05DF6D0E09CF2D5B00D9A3E8 /* Doc */ = {
			isa = PBXGroup;
			children = (
				48F7B00312F248E600E70774 /* CCKeyDerivationPBKDF.3cc */,
				48F7B00412F248E600E70774 /* CCSymmetricKeyUnwrap.3cc */,
				48F7B00512F248E600E70774 /* CCSymmetricKeyWrap.3cc */,
				48F7B00612F248E600E70774 /* CCSymmetricUnwrappedSize.3cc */,
				48F7B00712F248E600E70774 /* CCSymmetricWrappedSize.3cc */,
				48F7AFFF12F2488500E70774 /* CCCalibratePBKDF.3cc */,
				48F7B00012F2488500E70774 /* CCCommonKeyDerivation.3cc */,
				D671B5B60BC6D67000878B42 /* CC_MD2.3cc */,
				D671B5B70BC6D67000878B42 /* CC_MD2_Final.3cc */,
				D671B5B80BC6D67000878B42 /* CC_MD2_Init.3cc */,
				D671B5B90BC6D67000878B42 /* CC_MD2_Update.3cc */,
				D671B5BA0BC6D67000878B42 /* CC_MD4.3cc */,
				D671B5BB0BC6D67000878B42 /* CC_MD4_Final.3cc */,
				D671B5BC0BC6D67000878B42 /* CC_MD4_Init.3cc */,







|



<



|



|



|



<
|
<
<



|






|



<
<
|









|
>
>
>




<
|


|
<











>








|
>


|
<
<









<
<
<
<
|
|
>
>




<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



<
<
<
<
<
<
<







714
715
716
717
718
719
720
721
722
723
724

725
726
727
728
729
730
731
732
733
734
735
736
737
738
739

740


741
742
743
744
745
746
747
748
749
750
751
752
753
754


755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772

773
774
775
776

777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801


802
803
804
805
806
807
808
809
810




811
812
813
814
815
816
817
818





































819
820
821







822
823
824
825
826
827
828
		D671B5DF0BC6D67000878B42 /* CCHmacInit.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CCHmacInit.3cc; path = doc/CCHmacInit.3cc; sourceTree = "<group>"; };
		D671B5E00BC6D67000878B42 /* CCHmacUpdate.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CCHmacUpdate.3cc; path = doc/CCHmacUpdate.3cc; sourceTree = "<group>"; };
		D671B5E10BC6D67000878B42 /* CCryptorCreateFromData.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = CCryptorCreateFromData.3cc; path = doc/CCryptorCreateFromData.3cc; sourceTree = "<group>"; };
		D671B5E20BC6D67000878B42 /* Common Crypto.3cc */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = text; name = "Common Crypto.3cc"; path = "doc/Common Crypto.3cc"; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
		4823B0DD14C10064008F689F /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (

			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		4834A87A14F47B6200438E3D /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
				4834A88214F47C9A00438E3D /* libcommonCrypto.dylib in Frameworks */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		48CCF15612FA99B600D6DAE9 /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (

				4834A85314F47A9400438E3D /* libcorecrypto.dylib in Frameworks */,


			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		4CA674F41331747E00C45A71 /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		EEB70419131C5BCB007CF918 /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (


				484D40FF14DC96A600C93734 /* libcorecrypto.dylib in Frameworks */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXFrameworksBuildPhase section */

/* Begin PBXGroup section */
		054BBEA205F6A8DE00344873 = {
			isa = PBXGroup;
			children = (
				5D8037A514FECB5900E93214 /* libcorecrypto_sim.dylib */,
				4834A85214F47A9400438E3D /* libcorecrypto.dylib */,
				484D40FE14DC96A600C93734 /* libcorecrypto.dylib */,
				48FD6C621354E06A00F55B8B /* Exports */,
				5DB4936310FBC4E200E45951 /* Configurations */,
				054BBEB105F6A90E00344873 /* Public Headers */,
				054BBEB405F6A91E00344873 /* Source */,
				05DF6D0E09CF2D5B00D9A3E8 /* Doc */,

				4823B0AC14C10022008F689F /* CCRegression */,
				054BBEBF05F6A97700344873 /* Products */,
				4857A12A11BDA6E0001F5A9A /* libSystem.dylib */,
				4857A13011BDA737001F5A9A /* System.framework */,

			);
			sourceTree = "<group>";
		};
		054BBEB105F6A90E00344873 /* Public Headers */ = {
			isa = PBXGroup;
			children = (
				4854F9C01116307500CAFA18 /* CommonKeyDerivation.h */,
				4854F9C11116307500CAFA18 /* CommonSymmetricKeywrap.h */,
				054BBECD05F6AA7200344873 /* CommonDigest.h */,
				05D9F61609D85F4A00AD30A7 /* CommonCryptor.h */,
				05D8D97C09E411AA00E03504 /* CommonHMAC.h */,
				4873A7271445099D0011B4FA /* CommonCrypto.h */,
			);
			name = "Public Headers";
			path = CommonCrypto;
			sourceTree = "<group>";
		};
		054BBEB405F6A91E00344873 /* Source */ = {
			isa = PBXGroup;
			children = (
				489EECA1149809A800B44D5A /* libDER */,
				48CA258512C149EF002330C4 /* descriptors */,
				4836A42A11A5CB4700862178 /* API */,
				4846CA5311A5C8B800E7DA82 /* SPI */,
				489D982B11A4E8C20004DB89 /* ccUtilities */,


			);
			path = Source;
			sourceTree = "<group>";
		};
		054BBEBF05F6A97700344873 /* Products */ = {
			isa = PBXGroup;
			children = (
				054BBEBE05F6A97700344873 /* libcommonCrypto.dylib */,
				054BBEC605F6A98900344873 /* libcommonCrypto.dylib */,




				48165DB9125AC5D50015A267 /* libcommonCrypto.dylib */,
				48165E9C125AC5F20015A267 /* libcommonCrypto_sim.dylib */,
				4823B0E014C10064008F689F /* CCRegression */,
				4834A88014F47B6200438E3D /* CCRegression copy */,
			);
			name = Products;
			sourceTree = "<group>";
		};





































		05DF6D0E09CF2D5B00D9A3E8 /* Doc */ = {
			isa = PBXGroup;
			children = (







				D671B5B60BC6D67000878B42 /* CC_MD2.3cc */,
				D671B5B70BC6D67000878B42 /* CC_MD2_Final.3cc */,
				D671B5B80BC6D67000878B42 /* CC_MD2_Init.3cc */,
				D671B5B90BC6D67000878B42 /* CC_MD2_Update.3cc */,
				D671B5BA0BC6D67000878B42 /* CC_MD4.3cc */,
				D671B5BB0BC6D67000878B42 /* CC_MD4_Final.3cc */,
				D671B5BC0BC6D67000878B42 /* CC_MD4_Init.3cc */,
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287

1288
1289




1290


1291
1292
1293

1294
1295
1296

1297
1298
1299
1300
1301
1302
1303
1304
1305




1306
1307
1308
1309
1310
1311
1312
1313
1314
1315

1316
1317

1318


1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341


1342
1343






1344
1345
1346
1347
1348
1349
1350
1351
1352
1353

1354
1355
1356
1357
1358
1359
1360
1361
1362



1363
1364
1365
1366
1367
1368
1369
1370


1371



1372
1373
1374
1375
1376
1377
1378

1379

1380
1381
1382



1383


1384
1385
1386
1387
1388
1389
1390
1391
1392
1393

1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435

1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674

1675
1676
1677

1678
1679
1680

1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794

1795
1796
1797
1798
1799
1800
1801
1802
1803

1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827

1828

1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890

1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962

1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996



1997



1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015


2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028

2029
2030
2031
2032

2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044

2045
2046

2047
2048
2049
2050
2051
2052
2053
2054
2055
2056

2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076

2077
2078
2079
2080

2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095

2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126

2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164



2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181

2182
2183
2184
2185
2186
2187
2188
2189


2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372

2373

2374
2375
2376


2377
2378
2379
2380
2381












2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438

2439
2440

2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525

2526
2527
2528
2529
2530

2531
2532
2533

2534

2535
2536

2537
2538
2539
2540
2541
2542



2543
2544
2545


2546


2547


2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660

2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708







2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727






2728
2729
2730

2731
2732

2733

2734
2735
2736
2737
2738
2739


2740

2741
2742
2743





2744
2745
2746
2747
2748
2749
2750
2751
2752


2753



2754
2755
2756
2757
2758




2759
2760

2761
2762
2763
2764
2765
2766
2767


2768


2769
2770
2771
2772


2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784

2785
2786


2787






2788



2789
2790
2791
2792
2793
2794
2795






2796
2797
2798
2799
2800



2801





2802


2803

2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815


2816
2817
2818


2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833

2834









2835

2836

2837
2838
2839
2840
2841
2842
2843



2844



2845


2846


2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858

2859




2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870







2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897





2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
				05DF6D1109CF2D7200D9A3E8 /* CC_crypto.3cc */,
				05DF6D1209CF2D7200D9A3E8 /* CC_MD5.3cc */,
				05DF6D1309CF2D7200D9A3E8 /* CC_SHA.3cc */,
			);
			name = Doc;
			sourceTree = "<group>";
		};
		05ECA0E309D468BF00CFE5CB /* ccOpenssl */ = {
			isa = PBXGroup;
			children = (
				05ECA0E409D468E200CFE5CB /* des.h */,
				05C4417209D4BB0B002066D1 /* opensslconf.h */,
				05ECA0ED09D469A100CFE5CB /* set_key.c */,
				05ECA0E509D468E200CFE5CB /* des_enc.c */,
				4836A41911A5C94A00862178 /* opensslDES.h */,
				0539DC2609D4919D00AB7F89 /* opensslDES.c */,
				05C70C5309D471C30004B8F4 /* spr.h */,
				05ECA0E609D468E200CFE5CB /* des_locl.h */,
				05C4416E09D4BACE002066D1 /* e_os2.h */,
			);
			path = ccOpenssl;
			sourceTree = "<group>";
		};
		1210DF01120488B50054B6F9 /* TestTools */ = {

			isa = PBXGroup;
			children = (




				480C9ABD12077B7D002EC023 /* testUtil */,


				1288816E120367F10050B2E9 /* CBCTest */,
				125B795F11FF92FC008C1AD3 /* XTSTest */,
			);

			name = TestTools;
			sourceTree = "<group>";
		};

		1210DF02120489050054B6F9 /* Legacy */ = {
			isa = PBXGroup;
			children = (
				48D5636A11A652EB008EBBBF /* GladmanAES */,
				48D5637611A65316008EBBBF /* AESedp */,
				0585FE1109DC9850001762F6 /* CAST */,
				795CA3FC0D34431400BAE6A2 /* RC2 */,
				05D9F60109D85DA100AD30A7 /* Digest */,
				05ECA0E309D468BF00CFE5CB /* ccOpenssl */,




			);
			name = Legacy;
			sourceTree = "<group>";
		};
		1249340012270E8900F9C9E1 /* cfb8 */ = {
			isa = PBXGroup;
			children = (
				1249340112270E8900F9C9E1 /* cfb8_decrypt.c */,
				1249340212270E8900F9C9E1 /* cfb8_descriptor.c */,
				1249340312270E8900F9C9E1 /* cfb8_done.c */,

				1249340412270E8900F9C9E1 /* cfb8_encrypt.c */,
				1249340512270E8900F9C9E1 /* cfb8_getiv.c */,

				1249340612270E8900F9C9E1 /* cfb8_setiv.c */,


				1249340712270E8900F9C9E1 /* cfb8_start.c */,
			);
			path = cfb8;
			sourceTree = "<group>";
		};
		125B795F11FF92FC008C1AD3 /* XTSTest */ = {
			isa = PBXGroup;
			children = (
				125B796011FF92FC008C1AD3 /* crypto.c */,
				125B796111FF92FC008C1AD3 /* hexString.c */,
				125B796211FF92FC008C1AD3 /* hexString.h */,
				125B796311FF92FC008C1AD3 /* printByteBuffer.c */,
				125B796411FF92FC008C1AD3 /* printByteBuffer.h */,
				125B796511FF92FC008C1AD3 /* xtsTestVectors.c */,
				125B796611FF92FC008C1AD3 /* xtsTestVectors.h */,
			);
			name = XTSTest;
			path = LocalTests/XTSTest;
			sourceTree = "<group>";
		};
		1288816E120367F10050B2E9 /* CBCTest */ = {
			isa = PBXGroup;
			children = (


				12CC5DD8120373D1001B4FCE /* CBCTest.h */,
				12CC5DD9120373D1001B4FCE /* CBCTest.c */,






			);
			name = CBCTest;
			path = LocalTests/CBCTest;
			sourceTree = "<group>";
		};
		480C9ABD12077B7D002EC023 /* testUtil */ = {
			isa = PBXGroup;
			children = (
				480C9AD512077BCF002EC023 /* byteBuffer.c */,
				480C9AD612077BCF002EC023 /* byteBuffer.h */,

			);
			name = testUtil;
			path = LocalTests/testUtil;
			sourceTree = "<group>";
		};
		4836A42A11A5CB4700862178 /* API */ = {
			isa = PBXGroup;
			children = (
				12FA0DB111F7964700917A4E /* CommonRandom.c */,



				4836A42B11A5CB4700862178 /* CommonCryptor.c */,
				4836A42C11A5CB4700862178 /* CommonCryptorPriv.h */,
				4836A42E11A5CB4700862178 /* CommonHMAC.c */,
				4836A42F11A5CB4700862178 /* CommonKeyDerivation.c */,
				4836A43011A5CB4700862178 /* CommonKeyDerivationPriv.h */,
				4836A43111A5CB4700862178 /* CommonSymmetricKeywrap.c */,
				4836A42D11A5CB4700862178 /* CommonDigestPriv.h */,
				48096B2211A5EF900043F67F /* CommonDigest.c */,


				53B9FDE81343DD0600CA1154 /* CommonCMAC.c */,



			);
			path = API;
			sourceTree = "<group>";
		};
		4846CA5311A5C8B800E7DA82 /* SPI */ = {
			isa = PBXGroup;
			children = (

				12FA0DAF11F7962100917A4E /* CommonRandomSPI.h */,

				4836A41A11A5C94A00862178 /* CommonCryptoPriv.h */,
				4846CA5411A5C8B800E7DA82 /* CommonCryptorSPI.h */,
				4846CA5511A5C8B800E7DA82 /* CommonDigestSPI.h */,



				53B9FDED1343DDB700CA1154 /* CommonCMACSPI.h */,


			);
			name = SPI;
			path = CommonCryptoSPI;
			sourceTree = "<group>";
		};
		4862F09611BDA1D300946BBE /* skein */ = {
			isa = PBXGroup;
			children = (
				4862F09711BDA1D300946BBE /* Optimized_64bit */,
			);

			path = skein;
			sourceTree = "<group>";
		};
		4862F09711BDA1D300946BBE /* Optimized_64bit */ = {
			isa = PBXGroup;
			children = (
				4862F09E11BDA27200946BBE /* skein.h */,
				4862F09F11BDA27200946BBE /* skein.c */,
				4862F0A011BDA27200946BBE /* skein_port.h */,
				4862F0A111BDA27200946BBE /* skein_iv.h */,
				4862F0A211BDA27200946BBE /* skein_dropin.h */,
				4862F0A311BDA27200946BBE /* skein_dropin.c */,
				4862F0A411BDA27200946BBE /* skein_debug.h */,
				4862F0A511BDA27200946BBE /* skein_debug.c */,
				4862F0A611BDA27200946BBE /* skein_block.c */,
				4862F0A711BDA27200946BBE /* SHA3api_ref.h */,
				4862F0A811BDA27200946BBE /* SHA3api_ref.c */,
				4862F0A911BDA27200946BBE /* brg_types.h */,
				4862F0AA11BDA27200946BBE /* brg_endian.h */,
			);
			path = Optimized_64bit;
			sourceTree = "<group>";
		};
		4873F33C11A4E47B00B5DDB3 /* libtomcrypt */ = {
			isa = PBXGroup;
			children = (
				4873F33D11A4E47B00B5DDB3 /* doc */,
				4873F34111A4E47B00B5DDB3 /* src */,
			);
			path = libtomcrypt;
			sourceTree = "<group>";
		};
		4873F33D11A4E47B00B5DDB3 /* doc */ = {
			isa = PBXGroup;
			children = (
				4873F33E11A4E47B00B5DDB3 /* footer.html */,
				4873F33F11A4E47B00B5DDB3 /* header.html */,
				4873F34011A4E47B00B5DDB3 /* libTomCryptDoc.pdf */,
			);
			path = doc;
			sourceTree = "<group>";
		};

		4873F34111A4E47B00B5DDB3 /* src */ = {
			isa = PBXGroup;
			children = (
				4873F34211A4E47B00B5DDB3 /* ciphers */,
				4873F35B11A4E47B00B5DDB3 /* hashes */,
				4873F36E11A4E47B00B5DDB3 /* headers */,
				4873F37D11A4E47B00B5DDB3 /* misc */,
				4873F3A111A4E47B00B5DDB3 /* modes */,
				4873F3E611A4E47B00B5DDB3 /* padding */,
			);
			path = src;
			sourceTree = "<group>";
		};
		4873F34211A4E47B00B5DDB3 /* ciphers */ = {
			isa = PBXGroup;
			children = (
				48F7F37612B2F05A00AF4587 /* ltc_aes */,
				4873F34311A4E47B00B5DDB3 /* aesedpport */,
				4873F35311A4E47B00B5DDB3 /* cast5.c */,
				4873F35411A4E47B00B5DDB3 /* des.c */,
				4873F35511A4E47B00B5DDB3 /* rc2.c */,
				4873F35611A4E47B00B5DDB3 /* RC4 */,
				4873F35A11A4E47B00B5DDB3 /* rc5.c */,
			);
			path = ciphers;
			sourceTree = "<group>";
		};
		4873F34311A4E47B00B5DDB3 /* aesedpport */ = {
			isa = PBXGroup;
			children = (
				48B4B98911ABA1B4001F1036 /* aes_modes_hw.s */,
				48B4B98A11ABA1B4001F1036 /* aes_modes_asm.s */,
				48B4B98B11ABA1B4001F1036 /* aesxts.h */,
				48B4B98C11ABA1B4001F1036 /* aesxts.c */,
				48B4B98D11ABA1B4001F1036 /* aesxts_asm.s */,
				48B4B98E11ABA1B4001F1036 /* ExpandKeyForEncryption.s */,
				48B4B98F11ABA1B4001F1036 /* ExpandKeyForDecryption.s */,
				48B4B99011ABA1B4001F1036 /* EncryptDecrypt.s */,
				48B4B99111ABA1B4001F1036 /* Data.s */,
				48B4B99211ABA1B4001F1036 /* Context.h */,
				48B4B99311ABA1B4001F1036 /* AES.s */,
				48B4B99511ABA1B4001F1036 /* aes_key_hw.s */,
				48B4B99611ABA1B4001F1036 /* aes_crypt_hw.s */,
				4873F34A11A4E47B00B5DDB3 /* aesedp.c */,
				4873F34B11A4E47B00B5DDB3 /* aesedp.h */,
				125B78AE11FF877D008C1AD3 /* aesedpPriv.h */,
			);
			path = aesedpport;
			sourceTree = "<group>";
		};
		4873F35611A4E47B00B5DDB3 /* RC4 */ = {
			isa = PBXGroup;
			children = (
				4873F35711A4E47B00B5DDB3 /* rc4.h */,
				4873F35811A4E47B00B5DDB3 /* rc4_enc.c */,
				4873F35911A4E47B00B5DDB3 /* rc4_skey.c */,
			);
			path = RC4;
			sourceTree = "<group>";
		};
		4873F35B11A4E47B00B5DDB3 /* hashes */ = {
			isa = PBXGroup;
			children = (
				4862F09411BDA1D300946BBE /* skein_ltc.h */,
				4862F09511BDA1D300946BBE /* skein_ltc.c */,
				4862F09611BDA1D300946BBE /* skein */,
				4873F35C11A4E47B00B5DDB3 /* helper */,
				4873F36111A4E47B00B5DDB3 /* md2.c */,
				4873F36211A4E47B00B5DDB3 /* md4.c */,
				4873F36311A4E47B00B5DDB3 /* md5.c */,
				4873F36411A4E47B00B5DDB3 /* rmd128.c */,
				4873F36511A4E47B00B5DDB3 /* rmd160.c */,
				4873F36611A4E47B00B5DDB3 /* rmd256.c */,
				4873F36711A4E47B00B5DDB3 /* rmd320.c */,
				4873F36811A4E47B00B5DDB3 /* sha1.c */,
				4873F36911A4E47B00B5DDB3 /* sha2 */,
			);
			path = hashes;
			sourceTree = "<group>";
		};
		4873F35C11A4E47B00B5DDB3 /* helper */ = {
			isa = PBXGroup;
			children = (
				4873F35D11A4E47B00B5DDB3 /* hash_file.c */,
				4873F35E11A4E47B00B5DDB3 /* hash_filehandle.c */,
				4873F35F11A4E47B00B5DDB3 /* hash_memory.c */,
				4873F36011A4E47B00B5DDB3 /* hash_memory_multi.c */,
			);
			path = helper;
			sourceTree = "<group>";
		};
		4873F36911A4E47B00B5DDB3 /* sha2 */ = {
			isa = PBXGroup;
			children = (
				4873F36A11A4E47B00B5DDB3 /* sha224.c */,
				4873F36B11A4E47B00B5DDB3 /* sha256.c */,
				4873F36C11A4E47B00B5DDB3 /* sha384.c */,
				4873F36D11A4E47B00B5DDB3 /* sha512.c */,
			);
			path = sha2;
			sourceTree = "<group>";
		};
		4873F36E11A4E47B00B5DDB3 /* headers */ = {
			isa = PBXGroup;
			children = (
				4873F36F11A4E47B00B5DDB3 /* tomcrypt.h */,
				4873F37011A4E47B00B5DDB3 /* tomcrypt_argchk.h */,
				4873F37111A4E47B00B5DDB3 /* tomcrypt_cfg.h */,
				4873F37211A4E47B00B5DDB3 /* tomcrypt_cipher.h */,
				4873F37311A4E47B00B5DDB3 /* tomcrypt_custom.h */,
				4873F37411A4E47B00B5DDB3 /* tomcrypt_hash.h */,
				4873F37511A4E47B00B5DDB3 /* tomcrypt_mac.h */,
				4873F37611A4E47B00B5DDB3 /* tomcrypt_macros.h */,
				4873F37711A4E47B00B5DDB3 /* tomcrypt_math.h */,
				4873F37811A4E47B00B5DDB3 /* tomcrypt_misc.h */,
				4873F37911A4E47B00B5DDB3 /* tomcrypt_mode.h */,
				4873F37A11A4E47B00B5DDB3 /* tomcrypt_pk.h */,
				4873F37B11A4E47B00B5DDB3 /* tomcrypt_pkcs.h */,
				4873F37C11A4E47B00B5DDB3 /* tomcrypt_prng.h */,
			);
			path = headers;
			sourceTree = "<group>";
		};
		4873F37D11A4E47B00B5DDB3 /* misc */ = {
			isa = PBXGroup;
			children = (
				4873F37E11A4E47B00B5DDB3 /* base64 */,
				4873F38111A4E47B00B5DDB3 /* burn_stack.c */,
				4873F38211A4E47B00B5DDB3 /* crypt */,
				4873F39C11A4E47B00B5DDB3 /* error_to_string.c */,
				4873F39D11A4E47B00B5DDB3 /* pkcs5 */,
				4873F3A011A4E47B00B5DDB3 /* zeromem.c */,
			);
			path = misc;
			sourceTree = "<group>";
		};
		4873F37E11A4E47B00B5DDB3 /* base64 */ = {
			isa = PBXGroup;
			children = (
				4873F37F11A4E47B00B5DDB3 /* base64_decode.c */,
				4873F38011A4E47B00B5DDB3 /* base64_encode.c */,
			);
			path = base64;
			sourceTree = "<group>";
		};
		4873F38211A4E47B00B5DDB3 /* crypt */ = {
			isa = PBXGroup;
			children = (
				4873F38311A4E47B00B5DDB3 /* crypt.c */,
				4873F38411A4E47B00B5DDB3 /* crypt_argchk.c */,
				4873F38511A4E47B00B5DDB3 /* crypt_cipher_descriptor.c */,
				4873F38611A4E47B00B5DDB3 /* crypt_cipher_is_valid.c */,
				4873F38711A4E47B00B5DDB3 /* crypt_find_cipher.c */,
				4873F38811A4E47B00B5DDB3 /* crypt_find_cipher_any.c */,
				4873F38911A4E47B00B5DDB3 /* crypt_find_cipher_id.c */,
				4873F38A11A4E47B00B5DDB3 /* crypt_find_hash.c */,
				4873F38B11A4E47B00B5DDB3 /* crypt_find_hash_any.c */,
				4873F38C11A4E47B00B5DDB3 /* crypt_find_hash_id.c */,
				4873F38D11A4E47B00B5DDB3 /* crypt_find_hash_oid.c */,
				4873F38E11A4E47B00B5DDB3 /* crypt_find_prng.c */,
				4873F38F11A4E47B00B5DDB3 /* crypt_fsa.c */,
				4873F39011A4E47B00B5DDB3 /* crypt_hash_descriptor.c */,
				4873F39111A4E47B00B5DDB3 /* crypt_hash_is_valid.c */,
				4873F39211A4E47B00B5DDB3 /* crypt_ltc_mp_descriptor.c */,
				4873F39311A4E47B00B5DDB3 /* crypt_mode_descriptor.c */,
				4873F39411A4E47B00B5DDB3 /* crypt_prng_descriptor.c */,
				4873F39511A4E47B00B5DDB3 /* crypt_prng_is_valid.c */,
				4873F39611A4E47B00B5DDB3 /* crypt_register_cipher.c */,
				4873F39711A4E47B00B5DDB3 /* crypt_register_hash.c */,
				4873F39811A4E47B00B5DDB3 /* crypt_register_prng.c */,
				4873F39911A4E47B00B5DDB3 /* crypt_unregister_cipher.c */,
				4873F39A11A4E47B00B5DDB3 /* crypt_unregister_hash.c */,
				4873F39B11A4E47B00B5DDB3 /* crypt_unregister_prng.c */,
			);
			path = crypt;
			sourceTree = "<group>";
		};
		4873F39D11A4E47B00B5DDB3 /* pkcs5 */ = {
			isa = PBXGroup;
			children = (
				4873F39E11A4E47B00B5DDB3 /* pkcs_5_1.c */,
				4873F39F11A4E47B00B5DDB3 /* pkcs_5_2.c */,
			);
			path = pkcs5;
			sourceTree = "<group>";
		};
		4873F3A111A4E47B00B5DDB3 /* modes */ = {
			isa = PBXGroup;
			children = (
				1249340012270E8900F9C9E1 /* cfb8 */,
				4873F3A211A4E47B00B5DDB3 /* cbc */,
				4873F3AA11A4E47B00B5DDB3 /* cfb */,
				4873F3B211A4E47B00B5DDB3 /* ctr */,
				4873F3BB11A4E47B00B5DDB3 /* ecb */,
				4873F3D411A4E47B00B5DDB3 /* ofb */,
				4873F3DC11A4E47B00B5DDB3 /* rc4_stream.c */,
				4873F3DD11A4E47B00B5DDB3 /* unimplemented.c */,
				4873F3DE11A4E47B00B5DDB3 /* xts */,
			);
			path = modes;
			sourceTree = "<group>";
		};
		4873F3A211A4E47B00B5DDB3 /* cbc */ = {
			isa = PBXGroup;
			children = (
				4873F3A311A4E47B00B5DDB3 /* cbc_decrypt.c */,
				4873F3A411A4E47B00B5DDB3 /* cbc_descriptor.c */,
				4873F3A511A4E47B00B5DDB3 /* cbc_done.c */,
				4873F3A611A4E47B00B5DDB3 /* cbc_encrypt.c */,
				4873F3A711A4E47B00B5DDB3 /* cbc_getiv.c */,
				4873F3A811A4E47B00B5DDB3 /* cbc_setiv.c */,
				4873F3A911A4E47B00B5DDB3 /* cbc_start.c */,
			);
			path = cbc;
			sourceTree = "<group>";
		};
		4873F3AA11A4E47B00B5DDB3 /* cfb */ = {
			isa = PBXGroup;
			children = (
				4873F3AB11A4E47B00B5DDB3 /* cfb_decrypt.c */,
				4873F3AC11A4E47B00B5DDB3 /* cfb_descriptor.c */,
				4873F3AD11A4E47B00B5DDB3 /* cfb_done.c */,
				4873F3AE11A4E47B00B5DDB3 /* cfb_encrypt.c */,
				4873F3AF11A4E47B00B5DDB3 /* cfb_getiv.c */,
				4873F3B011A4E47B00B5DDB3 /* cfb_setiv.c */,
				4873F3B111A4E47B00B5DDB3 /* cfb_start.c */,
			);
			path = cfb;
			sourceTree = "<group>";
		};
		4873F3B211A4E47B00B5DDB3 /* ctr */ = {
			isa = PBXGroup;
			children = (
				4873F3B311A4E47B00B5DDB3 /* ctr_decrypt.c */,
				4873F3B411A4E47B00B5DDB3 /* ctr_descriptor.c */,
				4873F3B511A4E47B00B5DDB3 /* ctr_done.c */,
				4873F3B611A4E47B00B5DDB3 /* ctr_encrypt.c */,
				4873F3B711A4E47B00B5DDB3 /* ctr_getiv.c */,
				4873F3B811A4E47B00B5DDB3 /* ctr_setiv.c */,

				4873F3B911A4E47B00B5DDB3 /* ctr_start.c */,
				4873F3BA11A4E47B00B5DDB3 /* ctr_test.c */,
			);

			path = ctr;
			sourceTree = "<group>";
		};

		4873F3BB11A4E47B00B5DDB3 /* ecb */ = {
			isa = PBXGroup;
			children = (
				4873F3BC11A4E47B00B5DDB3 /* ecb_decrypt.c */,
				4873F3BD11A4E47B00B5DDB3 /* ecb_descriptor.c */,
				4873F3BE11A4E47B00B5DDB3 /* ecb_done.c */,
				4873F3BF11A4E47B00B5DDB3 /* ecb_encrypt.c */,
				4873F3C011A4E47B00B5DDB3 /* ecb_start.c */,
			);
			path = ecb;
			sourceTree = "<group>";
		};
		4873F3D411A4E47B00B5DDB3 /* ofb */ = {
			isa = PBXGroup;
			children = (
				4873F3D511A4E47B00B5DDB3 /* ofb_decrypt.c */,
				4873F3D611A4E47B00B5DDB3 /* ofb_descriptor.c */,
				4873F3D711A4E47B00B5DDB3 /* ofb_done.c */,
				4873F3D811A4E47B00B5DDB3 /* ofb_encrypt.c */,
				4873F3D911A4E47B00B5DDB3 /* ofb_getiv.c */,
				4873F3DA11A4E47B00B5DDB3 /* ofb_setiv.c */,
				4873F3DB11A4E47B00B5DDB3 /* ofb_start.c */,
			);
			path = ofb;
			sourceTree = "<group>";
		};
		4873F3DE11A4E47B00B5DDB3 /* xts */ = {
			isa = PBXGroup;
			children = (
				4873F3DF11A4E47B00B5DDB3 /* xts_decrypt.c */,
				4873F3E011A4E47B00B5DDB3 /* xts_descriptor.c */,
				4873F3E111A4E47B00B5DDB3 /* xts_done.c */,
				4873F3E211A4E47B00B5DDB3 /* xts_encrypt.c */,
				4873F3E311A4E47B00B5DDB3 /* xts_init.c */,
				4873F3E411A4E47B00B5DDB3 /* xts_mult_x.c */,
				4873F3E511A4E47B00B5DDB3 /* xts_test.c */,
			);
			path = xts;
			sourceTree = "<group>";
		};
		4873F3E611A4E47B00B5DDB3 /* padding */ = {
			isa = PBXGroup;
			children = (
				4873F3E711A4E47B00B5DDB3 /* ansix923 */,
				4873F3EA11A4E47B00B5DDB3 /* iso10126 */,
				4873F3ED11A4E47B00B5DDB3 /* nopadding */,
				4873F3F011A4E47B00B5DDB3 /* pkcs7 */,
			);
			path = padding;
			sourceTree = "<group>";
		};
		4873F3E711A4E47B00B5DDB3 /* ansix923 */ = {
			isa = PBXGroup;
			children = (
				4873F3E811A4E47B00B5DDB3 /* ansi923pad.c */,
				4873F3E911A4E47B00B5DDB3 /* ansi923pad.h */,
			);
			path = ansix923;
			sourceTree = "<group>";
		};
		4873F3EA11A4E47B00B5DDB3 /* iso10126 */ = {
			isa = PBXGroup;
			children = (
				4873F3EB11A4E47B00B5DDB3 /* iso10126pad.c */,
				4873F3EC11A4E47B00B5DDB3 /* iso10126pad.h */,
			);
			path = iso10126;
			sourceTree = "<group>";
		};
		4873F3ED11A4E47B00B5DDB3 /* nopadding */ = {
			isa = PBXGroup;
			children = (
				4873F3EE11A4E47B00B5DDB3 /* nopad.c */,
				4873F3EF11A4E47B00B5DDB3 /* nopad.h */,
			);
			path = nopadding;
			sourceTree = "<group>";
		};
		4873F3F011A4E47B00B5DDB3 /* pkcs7 */ = {
			isa = PBXGroup;
			children = (
				4873F3F111A4E47B00B5DDB3 /* pkcs7pad.c */,
				4873F3F211A4E47B00B5DDB3 /* pkcs7pad.h */,
			);
			path = pkcs7;
			sourceTree = "<group>";
		};
		489D982B11A4E8C20004DB89 /* Utility */ = {
			isa = PBXGroup;
			children = (
				489D982C11A4E8C20004DB89 /* ccdebug.c */,
				489D982D11A4E8C20004DB89 /* ccdebug.h */,
			);
			name = Utility;
			path = ccUtilities;
			sourceTree = "<group>";
		};
		48D5636A11A652EB008EBBBF /* GladmanAES */ = {
			isa = PBXGroup;
			children = (
				48D5636B11A652EB008EBBBF /* aescrypt.c */,
				48D5636C11A652EB008EBBBF /* aeskey.c */,
				48D5636D11A652EB008EBBBF /* aestab.c */,
				48D5636E11A652EB008EBBBF /* aestab.h */,
				48D5636F11A652EB008EBBBF /* ccNewGladman.c */,
				48D5637011A652EB008EBBBF /* README */,
			);
			path = GladmanAES;
			sourceTree = "<group>";
		};
		48D5637611A65316008EBBBF /* AESedp */ = {
			isa = PBXGroup;
			children = (
				48D5636611A652D7008EBBBF /* aesopt.h */,

				48D5636711A652D7008EBBBF /* aes.h */,
				48D5637711A65316008EBBBF /* AES.c */,
				48D5637811A65316008EBBBF /* AESAssembly.h */,
				48D5637911A65316008EBBBF /* Data.c */,
				48D5637A11A65316008EBBBF /* Intel */,
				48D5638311A65316008EBBBF /* MakeData.c */,
				48D5638411A65316008EBBBF /* makefile */,
				48D5638511A65316008EBBBF /* ReadMe.txt */,
			);

			path = AESedp;
			sourceTree = "<group>";
		};
		48D5637A11A65316008EBBBF /* Intel */ = {
			isa = PBXGroup;
			children = (
				48D5637B11A65316008EBBBF /* AES.s */,
				48D5637C11A65316008EBBBF /* Data.s */,
				48D5637D11A65316008EBBBF /* DecryptCBC.s */,
				48D5637E11A65316008EBBBF /* EncryptCBC.s */,
				48D5637F11A65316008EBBBF /* EncryptDecrypt.s */,
				48D5638011A65316008EBBBF /* ExpandKeyForDecryption.s */,
				48D5638111A65316008EBBBF /* ExpandKeyForEncryption.s */,
				48D5638211A65316008EBBBF /* ReadMe.txt */,
			);
			path = Intel;
			sourceTree = "<group>";
		};
		48F7F37612B2F05A00AF4587 /* ltc_aes */ = {
			isa = PBXGroup;
			children = (
				48F7F37712B2F05A00AF4587 /* aes.c */,
				48F7F37812B2F05A00AF4587 /* aes_tab.c */,
				48F7F37912B2F05A00AF4587 /* ltc_aes.h */,

			);

			path = ltc_aes;
			sourceTree = "<group>";
		};
		5DB4936310FBC4E200E45951 /* Configurations */ = {
			isa = PBXGroup;
			children = (
				5D113BC21106441E00B412A2 /* CommonCrypto_base.xcconfig */,
				12FA10D211F7AB3E00917A4E /* CommonCrypto_deployment.xcconfig */,
				12FA10D311F7AB5000917A4E /* CommonCrypto_development.xcconfig */,
				12FA10D811F7ABCD00917A4E /* CommonCrypto_umbrellaMember.xcconfig */,
				12FA10D011F7AACE00917A4E /* CommonCrypto_umbrellaMember_deployment.xcconfig */,
				12FA10D111F7AAE400917A4E /* CommonCrypto_umbrellaMember_development.xcconfig */,
				5D113BCB1106441E00B412A2 /* CommonCrypto_unittest_base.xcconfig */,
				12790C7411F7C4BA0044EFE5 /* CommonCrypto_unittest_deployment.xcconfig */,
				12790C7511F7C4BA0044EFE5 /* CommonCrypto_unittest_development.xcconfig */,
				12A1ADD71207419E000C30A4 /* CommonCrypto_localtest.xcconfig */,
			);
			name = Configurations;
			sourceTree = "<group>";
		};
		5DB4940410FBE5A800E45951 /* UnitTestSource */ = {
			isa = PBXGroup;
			children = (
				5D57A807111B5DDE008CA573 /* SymmetricWrapTest.h */,
				5D57A808111B5DDE008CA573 /* SymmetricWrapTest.mm */,
				4882005B111AAD7A00798F94 /* PBKDFTest.h */,
				4882005C111AAD7A00798F94 /* PBKDFTest.mm */,
				5D113BD41106452100B412A2 /* CommonCryptoUnitTests-Info.plist */,
				5D113BD51106452100B412A2 /* CommonCryptoUnitTests.h */,
				5D113BD61106452100B412A2 /* CommonCryptoUnitTests.mm */,
				5D113BD71106452100B412A2 /* DigestTest.h */,
				5D113BD81106452100B412A2 /* DigestTest.mm */,
				5D113BD91106452100B412A2 /* EncryptionTest.h */,
				5D113BDA1106452100B412A2 /* EncryptionTest.mm */,
				5D113BDB1106452100B412A2 /* HMACTest.h */,
				5D113BDC1106452100B412A2 /* HMACTest.mm */,
				5D113BDD1106452100B412A2 /* RandomNumberService.h */,
				5D113BDE1106452100B412A2 /* RandomNumberService.mm */,
				5DAD82EC1279E04500240B9A /* TestToolProtocol.h */,
				5DAD83A71279F2B200240B9A /* main.mm */,
			);
			name = UnitTestSource;
			sourceTree = "<group>";
		};
		795CA3FC0D34431400BAE6A2 /* RC2 */ = {
			isa = PBXGroup;
			children = (
				4836A41811A5C94A00862178 /* rc2.h */,
				4836A41B11A5C94A00862178 /* ccRC2.h */,
				795CA3FD0D34431400BAE6A2 /* ccRC2.c */,
				795CA3FE0D34431400BAE6A2 /* rc2.c */,
			);
			path = RC2;
			sourceTree = "<group>";
		};
/* End PBXGroup section */

/* Begin PBXHeadersBuildPhase section */
		054BBEBA05F6A97700344873 /* Headers */ = {
			isa = PBXHeadersBuildPhase;
			buildActionMask = 2147483647;
			files = (

				054BBECE05F6AA7200344873 /* CommonDigest.h in Headers */,
				054BBEE005F6AA8900344873 /* md4_locl.h in Headers */,
				054BBEE205F6AA8900344873 /* md5_locl.h in Headers */,
				054BBEE305F6AA8900344873 /* md32_common.h in Headers */,
				054BBEE505F6AA8900344873 /* sha_locl.h in Headers */,
				05E319DD0638913700C4AD24 /* sha2Priv.h in Headers */,
				5302E4201343E3CE003037FA /* CommonCMACSPI.h in Headers */,
				05C70C5509D471C30004B8F4 /* spr.h in Headers */,
				05C4414409D49F28002066D1 /* des.h in Headers */,
				05C4414609D49F29002066D1 /* des_locl.h in Headers */,
				05C4416F09D4BACE002066D1 /* e_os2.h in Headers */,
				05C4417309D4BB0B002066D1 /* opensslconf.h in Headers */,
				05D9F61909D85F4A00AD30A7 /* CommonCryptor.h in Headers */,
				0585FE1D09DC9873001762F6 /* cast_lcl.h in Headers */,
				0585FE1E09DC9873001762F6 /* cast_s.h in Headers */,
				05D8D97D09E411AB00E03504 /* CommonHMAC.h in Headers */,
				4854F9C21116307500CAFA18 /* CommonKeyDerivation.h in Headers */,
				4854F9C31116307500CAFA18 /* CommonSymmetricKeywrap.h in Headers */,
				4873F40511A4E47B00B5DDB3 /* rc4.h in Headers */,
				4873F41911A4E47B00B5DDB3 /* tomcrypt.h in Headers */,
				4873F41A11A4E47B00B5DDB3 /* tomcrypt_argchk.h in Headers */,
				4873F41B11A4E47B00B5DDB3 /* tomcrypt_cfg.h in Headers */,
				4873F41C11A4E47B00B5DDB3 /* tomcrypt_cipher.h in Headers */,
				4873F41D11A4E47B00B5DDB3 /* tomcrypt_custom.h in Headers */,
				4873F41E11A4E47B00B5DDB3 /* tomcrypt_hash.h in Headers */,
				4873F41F11A4E47B00B5DDB3 /* tomcrypt_mac.h in Headers */,
				4873F42011A4E47B00B5DDB3 /* tomcrypt_macros.h in Headers */,
				4873F42111A4E47B00B5DDB3 /* tomcrypt_math.h in Headers */,
				4873F42211A4E47B00B5DDB3 /* tomcrypt_misc.h in Headers */,
				4873F42311A4E47B00B5DDB3 /* tomcrypt_mode.h in Headers */,
				4873F42411A4E47B00B5DDB3 /* tomcrypt_pk.h in Headers */,
				4873F42511A4E47B00B5DDB3 /* tomcrypt_pkcs.h in Headers */,
				4873F42611A4E47B00B5DDB3 /* tomcrypt_prng.h in Headers */,
				4873F48411A4E47B00B5DDB3 /* ansi923pad.h in Headers */,
				4873F48611A4E47B00B5DDB3 /* iso10126pad.h in Headers */,
				4873F48811A4E47B00B5DDB3 /* nopad.h in Headers */,
				4873F48A11A4E47B00B5DDB3 /* pkcs7pad.h in Headers */,
				489D982F11A4E8C20004DB89 /* ccdebug.h in Headers */,
				4846CA5611A5C8B800E7DA82 /* CommonCryptorSPI.h in Headers */,
				4846CA5711A5C8B800E7DA82 /* CommonDigestSPI.h in Headers */,
				4836A41F11A5C94A00862178 /* rc2.h in Headers */,
				4836A42011A5C94A00862178 /* opensslDES.h in Headers */,
				4836A42111A5C94A00862178 /* CommonCryptoPriv.h in Headers */,
				4836A42211A5C94A00862178 /* ccRC2.h in Headers */,
				4836A42311A5C94A00862178 /* ccCast.h in Headers */,
				4836A42411A5C94A00862178 /* cast.h in Headers */,
				4836A43311A5CB4700862178 /* CommonCryptorPriv.h in Headers */,
				4836A43411A5CB4700862178 /* CommonDigestPriv.h in Headers */,
				4836A43711A5CB4700862178 /* CommonKeyDerivationPriv.h in Headers */,
				48D5636811A652D7008EBBBF /* aesopt.h in Headers */,
				48D5636911A652D7008EBBBF /* aes.h in Headers */,
				48D5637411A652EB008EBBBF /* aestab.h in Headers */,
				48D5638711A65316008EBBBF /* AESAssembly.h in Headers */,
				485A566D11AE4BB4003DDC41 /* aesedp.h in Headers */,
				4862F09811BDA1D300946BBE /* skein_ltc.h in Headers */,
				4862F0AB11BDA27200946BBE /* skein.h in Headers */,
				4862F0AD11BDA27200946BBE /* skein_port.h in Headers */,
				4862F0AE11BDA27200946BBE /* skein_iv.h in Headers */,
				4862F0AF11BDA27200946BBE /* skein_dropin.h in Headers */,
				4862F0B111BDA27200946BBE /* skein_debug.h in Headers */,
				4862F0B411BDA27200946BBE /* SHA3api_ref.h in Headers */,
				4862F0B611BDA27200946BBE /* brg_types.h in Headers */,
				4862F0B711BDA27200946BBE /* brg_endian.h in Headers */,
				12FA0DB011F7962100917A4E /* CommonRandomSPI.h in Headers */,
				125B78AF11FF877D008C1AD3 /* aesedpPriv.h in Headers */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		48F7F29812B2EF6000AF4587 /* Headers */ = {
			isa = PBXHeadersBuildPhase;
			buildActionMask = 2147483647;
			files = (

				48F7F29912B2EF6000AF4587 /* CommonDigest.h in Headers */,
				48F7F29A12B2EF6000AF4587 /* md4_locl.h in Headers */,
				48F7F29B12B2EF6000AF4587 /* md5_locl.h in Headers */,
				48F7F29C12B2EF6000AF4587 /* md32_common.h in Headers */,
				48F7F29D12B2EF6000AF4587 /* sha_locl.h in Headers */,
				48F7F29E12B2EF6000AF4587 /* sha2Priv.h in Headers */,
				48F7F29F12B2EF6000AF4587 /* spr.h in Headers */,
				48F7F2A012B2EF6000AF4587 /* des.h in Headers */,
				48F7F2A112B2EF6000AF4587 /* des_locl.h in Headers */,
				48F7F2A212B2EF6000AF4587 /* e_os2.h in Headers */,
				48F7F2A312B2EF6000AF4587 /* opensslconf.h in Headers */,
				48F7F2A412B2EF6000AF4587 /* CommonCryptor.h in Headers */,
				48F7F2A512B2EF6000AF4587 /* cast_lcl.h in Headers */,
				48F7F2A612B2EF6000AF4587 /* cast_s.h in Headers */,
				48F7F2A712B2EF6000AF4587 /* CommonHMAC.h in Headers */,
				48F7F2A812B2EF6000AF4587 /* CommonKeyDerivation.h in Headers */,
				48F7F2A912B2EF6000AF4587 /* CommonSymmetricKeywrap.h in Headers */,
				48F7F2AA12B2EF6000AF4587 /* rc4.h in Headers */,
				48F7F2AB12B2EF6000AF4587 /* tomcrypt.h in Headers */,
				48F7F2AC12B2EF6000AF4587 /* tomcrypt_argchk.h in Headers */,
				48F7F2AD12B2EF6000AF4587 /* tomcrypt_cfg.h in Headers */,
				48F7F2AE12B2EF6000AF4587 /* tomcrypt_cipher.h in Headers */,
				48F7F2AF12B2EF6000AF4587 /* tomcrypt_custom.h in Headers */,
				48F7F2B012B2EF6000AF4587 /* tomcrypt_hash.h in Headers */,
				48F7F2B112B2EF6000AF4587 /* tomcrypt_mac.h in Headers */,
				48F7F2B212B2EF6000AF4587 /* tomcrypt_macros.h in Headers */,
				48F7F2B312B2EF6000AF4587 /* tomcrypt_math.h in Headers */,
				48F7F2B412B2EF6000AF4587 /* tomcrypt_misc.h in Headers */,
				48F7F2B512B2EF6000AF4587 /* tomcrypt_mode.h in Headers */,
				48F7F2B612B2EF6000AF4587 /* tomcrypt_pk.h in Headers */,
				48F7F2B712B2EF6000AF4587 /* tomcrypt_pkcs.h in Headers */,
				48F7F2B812B2EF6000AF4587 /* tomcrypt_prng.h in Headers */,
				48F7F2B912B2EF6000AF4587 /* ansi923pad.h in Headers */,
				48F7F2BA12B2EF6000AF4587 /* iso10126pad.h in Headers */,



				48F7F2BB12B2EF6000AF4587 /* nopad.h in Headers */,



				48F7F2BC12B2EF6000AF4587 /* pkcs7pad.h in Headers */,
				48F7F2BD12B2EF6000AF4587 /* ccdebug.h in Headers */,
				48F7F2BE12B2EF6000AF4587 /* CommonCryptorSPI.h in Headers */,
				48F7F2BF12B2EF6000AF4587 /* CommonDigestSPI.h in Headers */,
				48F7F2C012B2EF6000AF4587 /* rc2.h in Headers */,
				48F7F2C112B2EF6000AF4587 /* opensslDES.h in Headers */,
				48F7F2C212B2EF6000AF4587 /* CommonCryptoPriv.h in Headers */,
				48F7F2C312B2EF6000AF4587 /* ccRC2.h in Headers */,
				48F7F2C412B2EF6000AF4587 /* ccCast.h in Headers */,
				48F7F2C512B2EF6000AF4587 /* cast.h in Headers */,
				48F7F2C612B2EF6000AF4587 /* CommonCryptorPriv.h in Headers */,
				48F7F2C712B2EF6000AF4587 /* CommonDigestPriv.h in Headers */,
				48F7F2C812B2EF6000AF4587 /* CommonKeyDerivationPriv.h in Headers */,
				48F7F2C912B2EF6000AF4587 /* aesopt.h in Headers */,
				48F7F2CA12B2EF6000AF4587 /* aes.h in Headers */,
				48F7F2CB12B2EF6000AF4587 /* aestab.h in Headers */,
				48F7F2CC12B2EF6000AF4587 /* AESAssembly.h in Headers */,
				48F7F2CE12B2EF6000AF4587 /* skein_ltc.h in Headers */,


				48F7F2CF12B2EF6000AF4587 /* skein.h in Headers */,
				48F7F2D012B2EF6000AF4587 /* skein_port.h in Headers */,
				48F7F2D112B2EF6000AF4587 /* skein_iv.h in Headers */,
				48F7F2D212B2EF6000AF4587 /* skein_dropin.h in Headers */,
				48F7F2D312B2EF6000AF4587 /* skein_debug.h in Headers */,
				48F7F2D412B2EF6000AF4587 /* SHA3api_ref.h in Headers */,
				48F7F2D512B2EF6000AF4587 /* brg_types.h in Headers */,
				48F7F2D612B2EF6000AF4587 /* brg_endian.h in Headers */,
				48F7F2D712B2EF6000AF4587 /* CommonRandomSPI.h in Headers */,
				48F7F37C12B2F05A00AF4587 /* ltc_aes.h in Headers */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};

		5DAD82C81279DEF900240B9A /* Headers */ = {
			isa = PBXHeadersBuildPhase;
			buildActionMask = 2147483647;
			files = (

			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXHeadersBuildPhase section */

/* Begin PBXNativeTarget section */
		054BBEBD05F6A97700344873 /* commonCrypto */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = C27AD07D0987FCDA001272E0 /* Build configuration list for PBXNativeTarget "commonCrypto" */;
			buildPhases = (
				054BBEBA05F6A97700344873 /* Headers */,
				054BBEBB05F6A97700344873 /* Sources */,

			);
			buildRules = (

				B125268E0713742A00BB8157 /* PBXBuildRule */,
			);
			dependencies = (
			);
			name = commonCrypto;
			productName = commonCrypto;
			productReference = 054BBEBE05F6A97700344873 /* libcommonCrypto.dylib */;
			productType = "com.apple.product-type.library.dynamic";
		};
		125B795011FF923D008C1AD3 /* XTStest */ = {

			isa = PBXNativeTarget;
			buildConfigurationList = 125B795711FF9279008C1AD3 /* Build configuration list for PBXNativeTarget "XTStest" */;
			buildPhases = (
				125B794E11FF923D008C1AD3 /* Sources */,
				125B794F11FF923D008C1AD3 /* Frameworks */,
			);
			buildRules = (
			);
			dependencies = (
				12F60BEA12015A2600D17AF3 /* PBXTargetDependency */,
			);
			name = XTStest;
			productName = XTStest;
			productReference = 125B795111FF923D008C1AD3 /* XTStest */;
			productType = "com.apple.product-type.tool";
		};
		128881641203673C0050B2E9 /* CBCTest */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 128881691203675B0050B2E9 /* Build configuration list for PBXNativeTarget "CBCTest" */;
			buildPhases = (

				128881621203673C0050B2E9 /* Sources */,
				128881631203673C0050B2E9 /* Frameworks */,
			);
			buildRules = (

			);
			dependencies = (
				1228ADD712037B1000B83BF9 /* PBXTargetDependency */,
			);
			name = CBCTest;
			productName = CBCTest;
			productReference = 128881651203673C0050B2E9 /* CBCTest */;
			productType = "com.apple.product-type.tool";
		};
		48F7F29712B2EF6000AF4587 /* commonCryptoOpenSource */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 48F7F36A12B2EF6000AF4587 /* Build configuration list for PBXNativeTarget "commonCryptoOpenSource" */;
			buildPhases = (
				48F7F29812B2EF6000AF4587 /* Headers */,
				48F7F2D912B2EF6000AF4587 /* Sources */,

			);
			buildRules = (
				48F7F36912B2EF6000AF4587 /* PBXBuildRule */,
			);
			dependencies = (
			);
			name = commonCryptoOpenSource;
			productName = commonCrypto;
			productReference = 48F7F36D12B2EF6000AF4587 /* libcommonCrypto.dylib */;
			productType = "com.apple.product-type.library.dynamic";
		};
		5D735E4710FCDC04001AAD1E /* CommonCryptoUnitTest */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 5D735E4D10FCDC04001AAD1E /* Build configuration list for PBXNativeTarget "CommonCryptoUnitTest" */;
			buildPhases = (
				5D735E4410FCDC04001AAD1E /* Sources */,
				5D735E4510FCDC04001AAD1E /* Frameworks */,
				5D735E4610FCDC04001AAD1E /* ShellScript */,
			);
			buildRules = (
			);
			dependencies = (
				FC129BED116AED0500D618D5 /* PBXTargetDependency */,
				5DAD82DC1279DF6100240B9A /* PBXTargetDependency */,
			);
			name = CommonCryptoUnitTest;
			productName = CommonCryptoUnitTest;
			productReference = 5D735E4810FCDC04001AAD1E /* CommonCryptoUnitTest.octest */;
			productType = "com.apple.product-type.bundle";
		};
		5DAD82CB1279DEF900240B9A /* UnitTestLibrary */ = {

			isa = PBXNativeTarget;
			buildConfigurationList = 5DAD82E61279DFA700240B9A /* Build configuration list for PBXNativeTarget "UnitTestLibrary" */;
			buildPhases = (
				5DAD82C81279DEF900240B9A /* Headers */,
				5DAD82C91279DEF900240B9A /* Sources */,
				5DAD82CA1279DEF900240B9A /* Frameworks */,
			);
			buildRules = (
			);
			dependencies = (
			);
			name = UnitTestLibrary;
			productName = UnitTestLibrary;
			productReference = 5DAD82CC1279DEF900240B9A /* libCommonCryptoUnitTest.a */;
			productType = "com.apple.product-type.library.static";
		};
		5DAD83981279F1EC00240B9A /* CommonCryptoTestTool */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 5DAD83A01279F24B00240B9A /* Build configuration list for PBXNativeTarget "CommonCryptoTestTool" */;
			buildPhases = (
				5DAD83961279F1EC00240B9A /* Sources */,
				5DAD83971279F1EC00240B9A /* Frameworks */,
			);
			buildRules = (
			);
			dependencies = (
				5DAD839E1279F22000240B9A /* PBXTargetDependency */,
			);
			name = CommonCryptoTestTool;
			productName = CommonCryptoTestTool;
			productReference = 5DAD83991279F1EC00240B9A /* CommonCryptoTestTool */;
			productType = "com.apple.product-type.tool";
		};
/* End PBXNativeTarget section */

/* Begin PBXProject section */
		054BBEA605F6A8DE00344873 /* Project object */ = {
			isa = PBXProject;



			buildConfigurationList = C27AD0910987FCDA001272E0 /* Build configuration list for PBXProject "CommonCrypto" */;
			compatibilityVersion = "Xcode 3.2";
			developmentRegion = English;
			hasScannedForEncodings = 1;
			knownRegions = (
				English,
				Japanese,
				French,
				German,
			);
			mainGroup = 054BBEA205F6A8DE00344873;
			productRefGroup = 054BBEBF05F6A97700344873 /* Products */;
			projectDirPath = "";
			projectRoot = "";
			targets = (
				054BBEB705F6A93300344873 /* world */,
				054BBEBD05F6A97700344873 /* commonCrypto */,

				05CE94290A3784D4007C91D6 /* Copy Open Source Docs */,
				5D735E4710FCDC04001AAD1E /* CommonCryptoUnitTest */,
				5DC876F710FFB6BC0012A390 /* Unit Test World */,
				125B795011FF923D008C1AD3 /* XTStest */,
				128881641203673C0050B2E9 /* CBCTest */,
				5DAD82CB1279DEF900240B9A /* UnitTestLibrary */,
				5DAD83981279F1EC00240B9A /* CommonCryptoTestTool */,
				48F7F29712B2EF6000AF4587 /* commonCryptoOpenSource */,


			);
		};
/* End PBXProject section */

/* Begin PBXShellScriptBuildPhase section */
		5D735E4610FCDC04001AAD1E /* ShellScript */ = {
			isa = PBXShellScriptBuildPhase;
			buildActionMask = 2147483647;
			files = (
			);
			inputPaths = (
			);
			outputPaths = (
			);
			runOnlyForDeploymentPostprocessing = 0;
			shellPath = /bin/sh;
			shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n";
		};
/* End PBXShellScriptBuildPhase section */

/* Begin PBXSourcesBuildPhase section */
		054BBEBB05F6A97700344873 /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				5302E41F1343E367003037FA /* CommonCMAC.c in Sources */,
				AAAF0B9E0DC7A3DA0044DA03 /* sha1edpBigEndian.s in Sources */,
				AAAF0B9F0DC7A3DA0044DA03 /* sha1edpLittleEndian.s in Sources */,
				054BBEDE05F6AA8900344873 /* md2_dgst.c in Sources */,
				054BBEDF05F6AA8900344873 /* md4_dgst.c in Sources */,
				054BBEE105F6AA8900344873 /* md5_dgst.c in Sources */,
				054BBEE705F6AA8900344873 /* sha1.c in Sources */,
				05E319BD063890C100C4AD24 /* sha2.c in Sources */,
				05ECA0EE09D469A100CFE5CB /* set_key.c in Sources */,
				0539DC2809D4919D00AB7F89 /* opensslDES.c in Sources */,
				05C4414509D49F29002066D1 /* des_enc.c in Sources */,
				0585FE1909DC9873001762F6 /* c_ecb.c in Sources */,
				0585FE1A09DC9873001762F6 /* c_enc.c in Sources */,
				0585FE1B09DC9873001762F6 /* c_skey.c in Sources */,
				0585FE1F09DC9873001762F6 /* ccCast.c in Sources */,
				795CA41E0D34459D00BAE6A2 /* ccRC2.c in Sources */,
				795CA41F0D34459D00BAE6A2 /* rc2.c in Sources */,
				4873F40211A4E47B00B5DDB3 /* cast5.c in Sources */,
				4873F40311A4E47B00B5DDB3 /* des.c in Sources */,
				4873F40411A4E47B00B5DDB3 /* rc2.c in Sources */,
				4873F40611A4E47B00B5DDB3 /* rc4_enc.c in Sources */,
				4873F40711A4E47B00B5DDB3 /* rc4_skey.c in Sources */,
				4873F40811A4E47B00B5DDB3 /* rc5.c in Sources */,
				4873F40911A4E47B00B5DDB3 /* hash_file.c in Sources */,
				4873F40A11A4E47B00B5DDB3 /* hash_filehandle.c in Sources */,
				4873F40B11A4E47B00B5DDB3 /* hash_memory.c in Sources */,
				4873F40C11A4E47B00B5DDB3 /* hash_memory_multi.c in Sources */,
				4873F40D11A4E47B00B5DDB3 /* md2.c in Sources */,
				4873F40E11A4E47B00B5DDB3 /* md4.c in Sources */,
				4873F40F11A4E47B00B5DDB3 /* md5.c in Sources */,
				4873F41011A4E47B00B5DDB3 /* rmd128.c in Sources */,
				4873F41111A4E47B00B5DDB3 /* rmd160.c in Sources */,
				4873F41211A4E47B00B5DDB3 /* rmd256.c in Sources */,
				4873F41311A4E47B00B5DDB3 /* rmd320.c in Sources */,
				4873F41411A4E47B00B5DDB3 /* sha1.c in Sources */,
				4873F41611A4E47B00B5DDB3 /* sha256.c in Sources */,
				4873F41811A4E47B00B5DDB3 /* sha512.c in Sources */,
				4873F42A11A4E47B00B5DDB3 /* crypt.c in Sources */,
				4873F42B11A4E47B00B5DDB3 /* crypt_argchk.c in Sources */,
				4873F42C11A4E47B00B5DDB3 /* crypt_cipher_descriptor.c in Sources */,
				4873F42D11A4E47B00B5DDB3 /* crypt_cipher_is_valid.c in Sources */,
				4873F42E11A4E47B00B5DDB3 /* crypt_find_cipher.c in Sources */,
				4873F42F11A4E47B00B5DDB3 /* crypt_find_cipher_any.c in Sources */,
				4873F43011A4E47B00B5DDB3 /* crypt_find_cipher_id.c in Sources */,
				4873F43111A4E47B00B5DDB3 /* crypt_find_hash.c in Sources */,
				4873F43211A4E47B00B5DDB3 /* crypt_find_hash_any.c in Sources */,
				4873F43311A4E47B00B5DDB3 /* crypt_find_hash_id.c in Sources */,
				4873F43411A4E47B00B5DDB3 /* crypt_find_hash_oid.c in Sources */,
				4873F43511A4E47B00B5DDB3 /* crypt_find_prng.c in Sources */,
				4873F43711A4E47B00B5DDB3 /* crypt_hash_descriptor.c in Sources */,
				4873F43811A4E47B00B5DDB3 /* crypt_hash_is_valid.c in Sources */,
				4873F43911A4E47B00B5DDB3 /* crypt_ltc_mp_descriptor.c in Sources */,
				4873F43A11A4E47B00B5DDB3 /* crypt_mode_descriptor.c in Sources */,
				4873F43D11A4E47B00B5DDB3 /* crypt_register_cipher.c in Sources */,
				4873F43E11A4E47B00B5DDB3 /* crypt_register_hash.c in Sources */,
				4873F44011A4E47B00B5DDB3 /* crypt_unregister_cipher.c in Sources */,
				4873F44111A4E47B00B5DDB3 /* crypt_unregister_hash.c in Sources */,
				4873F44311A4E47B00B5DDB3 /* error_to_string.c in Sources */,
				4873F44611A4E47B00B5DDB3 /* zeromem.c in Sources */,
				4873F44711A4E47B00B5DDB3 /* cbc_decrypt.c in Sources */,
				4873F44811A4E47B00B5DDB3 /* cbc_descriptor.c in Sources */,
				4873F44911A4E47B00B5DDB3 /* cbc_done.c in Sources */,
				4873F44A11A4E47B00B5DDB3 /* cbc_encrypt.c in Sources */,
				4873F44B11A4E47B00B5DDB3 /* cbc_getiv.c in Sources */,
				4873F44C11A4E47B00B5DDB3 /* cbc_setiv.c in Sources */,
				4873F44D11A4E47B00B5DDB3 /* cbc_start.c in Sources */,
				4873F44E11A4E47B00B5DDB3 /* cfb_decrypt.c in Sources */,
				4873F44F11A4E47B00B5DDB3 /* cfb_descriptor.c in Sources */,
				4873F45011A4E47B00B5DDB3 /* cfb_done.c in Sources */,
				4873F45111A4E47B00B5DDB3 /* cfb_encrypt.c in Sources */,
				4873F45211A4E47B00B5DDB3 /* cfb_getiv.c in Sources */,
				4873F45311A4E47B00B5DDB3 /* cfb_setiv.c in Sources */,
				4873F45411A4E47B00B5DDB3 /* cfb_start.c in Sources */,
				4873F45511A4E47B00B5DDB3 /* ctr_decrypt.c in Sources */,
				4873F45611A4E47B00B5DDB3 /* ctr_descriptor.c in Sources */,
				4873F45711A4E47B00B5DDB3 /* ctr_done.c in Sources */,
				4873F45811A4E47B00B5DDB3 /* ctr_encrypt.c in Sources */,
				4873F45911A4E47B00B5DDB3 /* ctr_getiv.c in Sources */,
				4873F45A11A4E47B00B5DDB3 /* ctr_setiv.c in Sources */,
				4873F45B11A4E47B00B5DDB3 /* ctr_start.c in Sources */,
				4873F45C11A4E47B00B5DDB3 /* ctr_test.c in Sources */,
				4873F45D11A4E47B00B5DDB3 /* ecb_decrypt.c in Sources */,
				4873F45E11A4E47B00B5DDB3 /* ecb_descriptor.c in Sources */,
				4873F45F11A4E47B00B5DDB3 /* ecb_done.c in Sources */,
				4873F46011A4E47B00B5DDB3 /* ecb_encrypt.c in Sources */,
				4873F46111A4E47B00B5DDB3 /* ecb_start.c in Sources */,
				4873F47311A4E47B00B5DDB3 /* ofb_decrypt.c in Sources */,
				4873F47411A4E47B00B5DDB3 /* ofb_descriptor.c in Sources */,
				4873F47511A4E47B00B5DDB3 /* ofb_done.c in Sources */,
				4873F47611A4E47B00B5DDB3 /* ofb_encrypt.c in Sources */,
				4873F47711A4E47B00B5DDB3 /* ofb_getiv.c in Sources */,
				4873F47811A4E47B00B5DDB3 /* ofb_setiv.c in Sources */,
				4873F47911A4E47B00B5DDB3 /* ofb_start.c in Sources */,
				4873F47A11A4E47B00B5DDB3 /* rc4_stream.c in Sources */,
				4873F47B11A4E47B00B5DDB3 /* unimplemented.c in Sources */,
				4873F47C11A4E47B00B5DDB3 /* xts_decrypt.c in Sources */,
				4873F47D11A4E47B00B5DDB3 /* xts_descriptor.c in Sources */,
				4873F47E11A4E47B00B5DDB3 /* xts_done.c in Sources */,
				4873F47F11A4E47B00B5DDB3 /* xts_encrypt.c in Sources */,
				4873F48011A4E47B00B5DDB3 /* xts_init.c in Sources */,
				4873F48111A4E47B00B5DDB3 /* xts_mult_x.c in Sources */,
				4873F48211A4E47B00B5DDB3 /* xts_test.c in Sources */,
				4873F48311A4E47B00B5DDB3 /* ansi923pad.c in Sources */,
				4873F48511A4E47B00B5DDB3 /* iso10126pad.c in Sources */,
				4873F48711A4E47B00B5DDB3 /* nopad.c in Sources */,
				4873F48911A4E47B00B5DDB3 /* pkcs7pad.c in Sources */,
				489D982E11A4E8C20004DB89 /* ccdebug.c in Sources */,
				4836A43211A5CB4700862178 /* CommonCryptor.c in Sources */,
				4836A43511A5CB4700862178 /* CommonHMAC.c in Sources */,
				4836A43611A5CB4700862178 /* CommonKeyDerivation.c in Sources */,
				4836A43811A5CB4700862178 /* CommonSymmetricKeywrap.c in Sources */,
				48096B2311A5EF900043F67F /* CommonDigest.c in Sources */,
				48D5637111A652EB008EBBBF /* aescrypt.c in Sources */,
				48D5637211A652EB008EBBBF /* aeskey.c in Sources */,
				48D5637311A652EB008EBBBF /* aestab.c in Sources */,
				48D5637511A652EB008EBBBF /* ccNewGladman.c in Sources */,
				48D5638611A65316008EBBBF /* AES.c in Sources */,
				48D5638911A65316008EBBBF /* AES.s in Sources */,
				48D5638B11A65316008EBBBF /* DecryptCBC.s in Sources */,
				48D5638C11A65316008EBBBF /* EncryptCBC.s in Sources */,
				485A566C11AE4BB2003DDC41 /* aesedp.c in Sources */,
				48161AFF11AF011B009A14CE /* AES.s in Sources */,
				48161B0011AF0123009A14CE /* aes_crypt_hw.s in Sources */,
				48161B0111AF0124009A14CE /* aes_key_hw.s in Sources */,
				48161B0211AF0124009A14CE /* aes_modes_asm.s in Sources */,
				48161B0311AF0125009A14CE /* aes_modes_hw.s in Sources */,
				4862F09911BDA1D300946BBE /* skein_ltc.c in Sources */,
				4862F0AC11BDA27200946BBE /* skein.c in Sources */,
				4862F0B011BDA27200946BBE /* skein_dropin.c in Sources */,
				4862F0B211BDA27200946BBE /* skein_debug.c in Sources */,
				4862F0B311BDA27200946BBE /* skein_block.c in Sources */,
				4862F0B511BDA27200946BBE /* SHA3api_ref.c in Sources */,
				12FA0DB211F7964700917A4E /* CommonRandom.c in Sources */,
				12B5D56D11FF437500626A60 /* aesxts.c in Sources */,
				12B5D56E11FF437A00626A60 /* aesxts_asm.s in Sources */,
				122ADC45121320D70027F302 /* sha256_nossse3.s in Sources */,
				122ADC46121320D70027F302 /* sha256.s in Sources */,
				1249340812270E8900F9C9E1 /* cfb8_decrypt.c in Sources */,
				1249340912270E8900F9C9E1 /* cfb8_descriptor.c in Sources */,
				1249340A12270E8900F9C9E1 /* cfb8_done.c in Sources */,
				1249340B12270E8900F9C9E1 /* cfb8_encrypt.c in Sources */,
				1249340C12270E8900F9C9E1 /* cfb8_getiv.c in Sources */,
				1249340D12270E8900F9C9E1 /* cfb8_setiv.c in Sources */,
				1249340E12270E8900F9C9E1 /* cfb8_start.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		125B794E11FF923D008C1AD3 /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				125B796711FF92FC008C1AD3 /* crypto.c in Sources */,
				125B796811FF92FC008C1AD3 /* hexString.c in Sources */,
				125B796911FF92FC008C1AD3 /* printByteBuffer.c in Sources */,
				125B796A11FF92FC008C1AD3 /* xtsTestVectors.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};

		128881621203673C0050B2E9 /* Sources */ = {

			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (


				12CC5DDA120373D1001B4FCE /* CBCTest.c in Sources */,
				480C9AD712077BCF002EC023 /* byteBuffer.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};












		48F7F2D912B2EF6000AF4587 /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				48F7F2DC12B2EF6000AF4587 /* md2_dgst.c in Sources */,
				48F7F2DD12B2EF6000AF4587 /* md4_dgst.c in Sources */,
				48F7F2DE12B2EF6000AF4587 /* md5_dgst.c in Sources */,
				48F7F2DF12B2EF6000AF4587 /* sha1.c in Sources */,
				48F7F2E012B2EF6000AF4587 /* sha2.c in Sources */,
				48F7F2E112B2EF6000AF4587 /* set_key.c in Sources */,
				48F7F2E212B2EF6000AF4587 /* opensslDES.c in Sources */,
				48F7F2E312B2EF6000AF4587 /* des_enc.c in Sources */,
				48F7F2E412B2EF6000AF4587 /* c_ecb.c in Sources */,
				48F7F2E512B2EF6000AF4587 /* c_enc.c in Sources */,
				48F7F2E612B2EF6000AF4587 /* c_skey.c in Sources */,
				48F7F2E712B2EF6000AF4587 /* ccCast.c in Sources */,
				48F7F2E812B2EF6000AF4587 /* ccRC2.c in Sources */,
				48F7F2E912B2EF6000AF4587 /* rc2.c in Sources */,
				48F7F2EA12B2EF6000AF4587 /* cast5.c in Sources */,
				48F7F2EB12B2EF6000AF4587 /* des.c in Sources */,
				48F7F2EC12B2EF6000AF4587 /* rc2.c in Sources */,
				48F7F2ED12B2EF6000AF4587 /* rc4_enc.c in Sources */,
				48F7F2EE12B2EF6000AF4587 /* rc4_skey.c in Sources */,
				48F7F2EF12B2EF6000AF4587 /* rc5.c in Sources */,
				48F7F2F012B2EF6000AF4587 /* hash_file.c in Sources */,
				48F7F2F112B2EF6000AF4587 /* hash_filehandle.c in Sources */,
				48F7F2F212B2EF6000AF4587 /* hash_memory.c in Sources */,
				48F7F2F312B2EF6000AF4587 /* hash_memory_multi.c in Sources */,
				48F7F2F412B2EF6000AF4587 /* md2.c in Sources */,
				48F7F2F512B2EF6000AF4587 /* md4.c in Sources */,
				48F7F2F612B2EF6000AF4587 /* md5.c in Sources */,
				48F7F2F712B2EF6000AF4587 /* rmd128.c in Sources */,
				48F7F2F812B2EF6000AF4587 /* rmd160.c in Sources */,
				48F7F2F912B2EF6000AF4587 /* rmd256.c in Sources */,
				48F7F2FA12B2EF6000AF4587 /* rmd320.c in Sources */,
				48F7F2FB12B2EF6000AF4587 /* sha1.c in Sources */,
				48F7F2FC12B2EF6000AF4587 /* sha256.c in Sources */,
				48F7F2FD12B2EF6000AF4587 /* sha512.c in Sources */,
				48F7F2FE12B2EF6000AF4587 /* crypt.c in Sources */,
				48F7F2FF12B2EF6000AF4587 /* crypt_argchk.c in Sources */,
				48F7F30012B2EF6000AF4587 /* crypt_cipher_descriptor.c in Sources */,
				48F7F30112B2EF6000AF4587 /* crypt_cipher_is_valid.c in Sources */,
				48F7F30212B2EF6000AF4587 /* crypt_find_cipher.c in Sources */,
				48F7F30312B2EF6000AF4587 /* crypt_find_cipher_any.c in Sources */,
				48F7F30412B2EF6000AF4587 /* crypt_find_cipher_id.c in Sources */,
				48F7F30512B2EF6000AF4587 /* crypt_find_hash.c in Sources */,
				48F7F30612B2EF6000AF4587 /* crypt_find_hash_any.c in Sources */,
				48F7F30712B2EF6000AF4587 /* crypt_find_hash_id.c in Sources */,
				48F7F30812B2EF6000AF4587 /* crypt_find_hash_oid.c in Sources */,
				48F7F30912B2EF6000AF4587 /* crypt_find_prng.c in Sources */,
				48F7F30A12B2EF6000AF4587 /* crypt_hash_descriptor.c in Sources */,
				48F7F30B12B2EF6000AF4587 /* crypt_hash_is_valid.c in Sources */,
				48F7F30C12B2EF6000AF4587 /* crypt_ltc_mp_descriptor.c in Sources */,
				48F7F30D12B2EF6000AF4587 /* crypt_mode_descriptor.c in Sources */,
				48F7F30E12B2EF6000AF4587 /* crypt_register_cipher.c in Sources */,
				48F7F30F12B2EF6000AF4587 /* crypt_register_hash.c in Sources */,
				48F7F31012B2EF6000AF4587 /* crypt_unregister_cipher.c in Sources */,

				48F7F31112B2EF6000AF4587 /* crypt_unregister_hash.c in Sources */,
				48F7F31212B2EF6000AF4587 /* error_to_string.c in Sources */,

				48F7F31312B2EF6000AF4587 /* zeromem.c in Sources */,
				48F7F31412B2EF6000AF4587 /* cbc_decrypt.c in Sources */,
				48F7F31512B2EF6000AF4587 /* cbc_descriptor.c in Sources */,
				48F7F31612B2EF6000AF4587 /* cbc_done.c in Sources */,
				48F7F31712B2EF6000AF4587 /* cbc_encrypt.c in Sources */,
				48F7F31812B2EF6000AF4587 /* cbc_getiv.c in Sources */,
				48F7F31912B2EF6000AF4587 /* cbc_setiv.c in Sources */,
				48F7F31A12B2EF6000AF4587 /* cbc_start.c in Sources */,
				48F7F31B12B2EF6000AF4587 /* cfb_decrypt.c in Sources */,
				48F7F31C12B2EF6000AF4587 /* cfb_descriptor.c in Sources */,
				48F7F31D12B2EF6000AF4587 /* cfb_done.c in Sources */,
				48F7F31E12B2EF6000AF4587 /* cfb_encrypt.c in Sources */,
				48F7F31F12B2EF6000AF4587 /* cfb_getiv.c in Sources */,
				48F7F32012B2EF6000AF4587 /* cfb_setiv.c in Sources */,
				48F7F32112B2EF6000AF4587 /* cfb_start.c in Sources */,
				48F7F32212B2EF6000AF4587 /* ctr_decrypt.c in Sources */,
				48F7F32312B2EF6000AF4587 /* ctr_descriptor.c in Sources */,
				48F7F32412B2EF6000AF4587 /* ctr_done.c in Sources */,
				48F7F32512B2EF6000AF4587 /* ctr_encrypt.c in Sources */,
				48F7F32612B2EF6000AF4587 /* ctr_getiv.c in Sources */,
				48F7F32712B2EF6000AF4587 /* ctr_setiv.c in Sources */,
				48F7F32812B2EF6000AF4587 /* ctr_start.c in Sources */,
				48F7F32912B2EF6000AF4587 /* ctr_test.c in Sources */,
				48F7F32A12B2EF6000AF4587 /* ecb_decrypt.c in Sources */,
				48F7F32B12B2EF6000AF4587 /* ecb_descriptor.c in Sources */,
				48F7F32C12B2EF6000AF4587 /* ecb_done.c in Sources */,
				48F7F32D12B2EF6000AF4587 /* ecb_encrypt.c in Sources */,
				48F7F32E12B2EF6000AF4587 /* ecb_start.c in Sources */,
				48F7F32F12B2EF6000AF4587 /* ofb_decrypt.c in Sources */,
				48F7F33012B2EF6000AF4587 /* ofb_descriptor.c in Sources */,
				48F7F33112B2EF6000AF4587 /* ofb_done.c in Sources */,
				48F7F33212B2EF6000AF4587 /* ofb_encrypt.c in Sources */,
				48F7F33312B2EF6000AF4587 /* ofb_getiv.c in Sources */,
				48F7F33412B2EF6000AF4587 /* ofb_setiv.c in Sources */,
				48F7F33512B2EF6000AF4587 /* ofb_start.c in Sources */,
				48F7F33612B2EF6000AF4587 /* rc4_stream.c in Sources */,
				48F7F33712B2EF6000AF4587 /* unimplemented.c in Sources */,
				48F7F33812B2EF6000AF4587 /* xts_decrypt.c in Sources */,
				48F7F33912B2EF6000AF4587 /* xts_descriptor.c in Sources */,
				48F7F33A12B2EF6000AF4587 /* xts_done.c in Sources */,
				48F7F33B12B2EF6000AF4587 /* xts_encrypt.c in Sources */,
				48F7F33C12B2EF6000AF4587 /* xts_init.c in Sources */,
				48F7F33D12B2EF6000AF4587 /* xts_mult_x.c in Sources */,
				48F7F33E12B2EF6000AF4587 /* xts_test.c in Sources */,
				48F7F33F12B2EF6000AF4587 /* ansi923pad.c in Sources */,
				48F7F34012B2EF6000AF4587 /* iso10126pad.c in Sources */,
				48F7F34112B2EF6000AF4587 /* nopad.c in Sources */,
				48F7F34212B2EF6000AF4587 /* pkcs7pad.c in Sources */,
				48F7F34312B2EF6000AF4587 /* ccdebug.c in Sources */,
				48F7F34412B2EF6000AF4587 /* CommonCryptor.c in Sources */,
				48F7F34512B2EF6000AF4587 /* CommonHMAC.c in Sources */,
				48F7F34612B2EF6000AF4587 /* CommonKeyDerivation.c in Sources */,
				48F7F34712B2EF6000AF4587 /* CommonSymmetricKeywrap.c in Sources */,
				48F7F34812B2EF6000AF4587 /* CommonDigest.c in Sources */,
				48F7F34912B2EF6000AF4587 /* aescrypt.c in Sources */,
				48F7F34A12B2EF6000AF4587 /* aeskey.c in Sources */,
				48F7F34B12B2EF6000AF4587 /* aestab.c in Sources */,
				48F7F34C12B2EF6000AF4587 /* ccNewGladman.c in Sources */,
				48F7F34D12B2EF6000AF4587 /* AES.c in Sources */,
				48F7F34E12B2EF6000AF4587 /* AES.s in Sources */,
				48F7F34F12B2EF6000AF4587 /* DecryptCBC.s in Sources */,
				48F7F35012B2EF6000AF4587 /* EncryptCBC.s in Sources */,
				48F7F35712B2EF6000AF4587 /* skein_ltc.c in Sources */,
				48F7F35812B2EF6000AF4587 /* skein.c in Sources */,
				48F7F35912B2EF6000AF4587 /* skein_dropin.c in Sources */,
				48F7F35A12B2EF6000AF4587 /* skein_debug.c in Sources */,
				48F7F35B12B2EF6000AF4587 /* skein_block.c in Sources */,
				48F7F35C12B2EF6000AF4587 /* SHA3api_ref.c in Sources */,
				48F7F35D12B2EF6000AF4587 /* CommonRandom.c in Sources */,
				48F7F36212B2EF6000AF4587 /* cfb8_decrypt.c in Sources */,
				48F7F36312B2EF6000AF4587 /* cfb8_descriptor.c in Sources */,
				48F7F36412B2EF6000AF4587 /* cfb8_done.c in Sources */,
				48F7F36512B2EF6000AF4587 /* cfb8_encrypt.c in Sources */,
				48F7F36612B2EF6000AF4587 /* cfb8_getiv.c in Sources */,
				48F7F36712B2EF6000AF4587 /* cfb8_setiv.c in Sources */,
				48F7F36812B2EF6000AF4587 /* cfb8_start.c in Sources */,
				48F7F37A12B2F05A00AF4587 /* aes.c in Sources */,
				48F7F37B12B2F05A00AF4587 /* aes_tab.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		5D735E4410FCDC04001AAD1E /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (

				5D113BE01106452100B412A2 /* CommonCryptoUnitTests.mm in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		5DAD82C91279DEF900240B9A /* Sources */ = {

			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (

				5DAD82CF1279DF2B00240B9A /* DigestTest.mm in Sources */,

				5DAD82D01279DF2B00240B9A /* EncryptionTest.mm in Sources */,
				5DAD82D11279DF2B00240B9A /* HMACTest.mm in Sources */,

				5DAD82D21279DF2B00240B9A /* RandomNumberService.mm in Sources */,
				5DAD82D31279DF2B00240B9A /* PBKDFTest.mm in Sources */,
				5DAD82D41279DF2B00240B9A /* SymmetricWrapTest.mm in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};



		5DAD83961279F1EC00240B9A /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;


			files = (


				5DAD83AF1279F4C400240B9A /* main.mm in Sources */,


			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXSourcesBuildPhase section */

/* Begin PBXTargetDependency section */
		0511C4630A3785340028BFC3 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 05CE94290A3784D4007C91D6 /* Copy Open Source Docs */;
			targetProxy = 0511C4620A3785340028BFC3 /* PBXContainerItemProxy */;
		};
		1228ADD712037B1000B83BF9 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 054BBEBD05F6A97700344873 /* commonCrypto */;
			targetProxy = 1228ADD612037B1000B83BF9 /* PBXContainerItemProxy */;
		};
		12F60BEA12015A2600D17AF3 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 054BBEBD05F6A97700344873 /* commonCrypto */;
			targetProxy = 12F60BE912015A2600D17AF3 /* PBXContainerItemProxy */;
		};
		5D936FFB110E7FFF006855B0 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 054BBEBD05F6A97700344873 /* commonCrypto */;
			targetProxy = 5D936FFA110E7FFF006855B0 /* PBXContainerItemProxy */;
		};
		5DAD82DC1279DF6100240B9A /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 5DAD82CB1279DEF900240B9A /* UnitTestLibrary */;
			targetProxy = 5DAD82DB1279DF6100240B9A /* PBXContainerItemProxy */;
		};
		5DAD839E1279F22000240B9A /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 5DAD82CB1279DEF900240B9A /* UnitTestLibrary */;
			targetProxy = 5DAD839D1279F22000240B9A /* PBXContainerItemProxy */;
		};
		5DAD83D21279F6D500240B9A /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 5DAD83981279F1EC00240B9A /* CommonCryptoTestTool */;
			targetProxy = 5DAD83D11279F6D500240B9A /* PBXContainerItemProxy */;
		};
		5DC8771110FFB7510012A390 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 5D735E4710FCDC04001AAD1E /* CommonCryptoUnitTest */;
			targetProxy = 5DC8771010FFB7510012A390 /* PBXContainerItemProxy */;
		};
		FC129BED116AED0500D618D5 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 054BBEBD05F6A97700344873 /* commonCrypto */;
			targetProxy = FC129BEC116AED0500D618D5 /* PBXContainerItemProxy */;
		};
/* End PBXTargetDependency section */

/* Begin XCBuildConfiguration section */
		05CE94320A37850A007C91D6 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				COPY_PHASE_STRIP = YES;
				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
				PRODUCT_NAME = "Copy Open Source Docs";
				ZERO_LINK = NO;
			};
			name = Release;
		};
		125B795311FF923E008C1AD3 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12A1ADD71207419E000C30A4 /* CommonCrypto_localtest.xcconfig */;
			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = NO;
				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
				COPY_PHASE_STRIP = YES;
				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
				GCC_ENABLE_FIX_AND_CONTINUE = NO;
				GCC_MODEL_TUNING = G5;
				INSTALL_PATH = /usr/local/bin;
				ONLY_ACTIVE_ARCH = YES;
				PREBINDING = NO;
				PRODUCT_NAME = XTStest;
				ZERO_LINK = NO;
			};
			name = Release;
		};
		125B795411FF923E008C1AD3 /* Development */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12A1ADD71207419E000C30A4 /* CommonCrypto_localtest.xcconfig */;
			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = NO;
				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
				COPY_PHASE_STRIP = NO;
				GCC_DYNAMIC_NO_PIC = NO;
				GCC_ENABLE_FIX_AND_CONTINUE = YES;
				GCC_MODEL_TUNING = G5;
				GCC_OPTIMIZATION_LEVEL = 0;
				INSTALL_PATH = /usr/local/bin;
				ONLY_ACTIVE_ARCH = YES;
				PREBINDING = NO;
				PRODUCT_NAME = XTStest;
			};
			name = Development;
		};
		128881671203673D0050B2E9 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12A1ADD71207419E000C30A4 /* CommonCrypto_localtest.xcconfig */;
			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = NO;
				COPY_PHASE_STRIP = YES;
				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
				GCC_ENABLE_FIX_AND_CONTINUE = NO;
				GCC_MODEL_TUNING = G5;
				INSTALL_PATH = /usr/local/bin;
				PREBINDING = NO;
				PRODUCT_NAME = CBCTest;
				ZERO_LINK = NO;

			};
			name = Release;
		};
		128881681203673D0050B2E9 /* Development */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12A1ADD71207419E000C30A4 /* CommonCrypto_localtest.xcconfig */;
			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = NO;
				COPY_PHASE_STRIP = NO;
				GCC_DYNAMIC_NO_PIC = NO;
				GCC_ENABLE_FIX_AND_CONTINUE = YES;
				GCC_MODEL_TUNING = G5;
				GCC_OPTIMIZATION_LEVEL = 0;
				INSTALL_PATH = /usr/local/bin;
				PREBINDING = NO;
				PRODUCT_NAME = CBCTest;
			};
			name = Development;
		};
		12F25D8511F7BF8A0036BC8E /* Development */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
			};
			name = Development;
		};
		12F25D8611F7BF8A0036BC8E /* Development */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12FA10D311F7AB5000917A4E /* CommonCrypto_development.xcconfig */;
			buildSettings = {
				COPY_PHASE_STRIP = YES;
				OTHER_CFLAGS = "";
				OTHER_LDFLAGS = "";
				OTHER_REZFLAGS = "";
				PRODUCT_NAME = world;
				SECTORDER_FLAGS = "";
				WARNING_CFLAGS = (
					"-Wmost",
					"-Wno-four-char-constants",
					"-Wno-unknown-pragmas",
				);
			};
			name = Development;
		};
		12F25D8711F7BF8A0036BC8E /* Development */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12FA10D111F7AAE400917A4E /* CommonCrypto_umbrellaMember_development.xcconfig */;
			buildSettings = {
				EXPORTED_SYMBOLS_FILE = Source/CommonCrypto.exp;







				OTHER_LDFLAGS = "";
				SDKROOT = "";
			};
			name = Development;
		};
		12F25D8811F7BF8A0036BC8E /* Development */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				COPY_PHASE_STRIP = YES;
				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
				PRODUCT_NAME = "Copy Open Source Docs";
				ZERO_LINK = NO;
			};
			name = Development;
		};
		12F25D8911F7BF8A0036BC8E /* Development */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12790C7511F7C4BA0044EFE5 /* CommonCrypto_unittest_development.xcconfig */;
			buildSettings = {






				FRAMEWORK_SEARCH_PATHS = (
					"$(inherited)",
					"\"$(DEVELOPER_FRAMEWORKS_DIR)\"",

				);
				GCC_ENABLE_OBJC_GC = supported;

				LIBRARY_SEARCH_PATHS = "";

			};
			name = Development;
		};
		12F25D8A11F7BF8A0036BC8E /* Development */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12790C7511F7C4BA0044EFE5 /* CommonCrypto_unittest_development.xcconfig */;


			buildSettings = {

				COPY_PHASE_STRIP = YES;
				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
				GCC_ENABLE_FIX_AND_CONTINUE = NO;





				PRODUCT_NAME = "Unit Test World";
				ZERO_LINK = NO;
			};
			name = Development;
		};
		48F7F36B12B2EF6000AF4587 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12FA10D011F7AACE00917A4E /* CommonCrypto_umbrellaMember_deployment.xcconfig */;
			buildSettings = {


				EXPORTED_SYMBOLS_FILE = Source/CommonCrypto.exp;



				OTHER_CFLAGS = (
					"-fstack-protector-all",
					"-D__OPEN_SOURCE__",
					"-Wstack-protector",
				);




				OTHER_LDFLAGS = "";
				SDKROOT = "";

			};
			name = Release;
		};
		48F7F36C12B2EF6000AF4587 /* Development */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12FA10D111F7AAE400917A4E /* CommonCrypto_umbrellaMember_development.xcconfig */;
			buildSettings = {


				EXPORTED_SYMBOLS_FILE = Source/CommonCrypto.exp;


				OTHER_CFLAGS = (
					"-fstack-protector-all",
					"-D__OPEN_SOURCE__",
					"-Wstack-protector",


				);
				OTHER_LDFLAGS = "";
				SDKROOT = "";
			};
			name = Development;
		};
		5D735E4B10FCDC04001AAD1E /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12790C7411F7C4BA0044EFE5 /* CommonCrypto_unittest_deployment.xcconfig */;
			buildSettings = {
				FRAMEWORK_SEARCH_PATHS = (
					"$(inherited)",

					"\"$(DEVELOPER_FRAMEWORKS_DIR)\"",
				);


				GCC_ENABLE_OBJC_GC = supported;






				LIBRARY_SEARCH_PATHS = "";



			};
			name = Release;
		};
		5DAD82CD1279DEFA00240B9A /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12790C7411F7C4BA0044EFE5 /* CommonCrypto_unittest_deployment.xcconfig */;
			buildSettings = {






				GCC_ENABLE_OBJC_GC = supported;
			};
			name = Release;
		};
		5DAD82CE1279DEFA00240B9A /* Development */ = {



			isa = XCBuildConfiguration;





			baseConfigurationReference = 12790C7511F7C4BA0044EFE5 /* CommonCrypto_unittest_development.xcconfig */;


			buildSettings = {

				GCC_ENABLE_OBJC_GC = supported;
			};
			name = Development;
		};
		5DAD839B1279F1ED00240B9A /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12790C7411F7C4BA0044EFE5 /* CommonCrypto_unittest_deployment.xcconfig */;
			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = NO;
				COPY_PHASE_STRIP = YES;
				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
				GCC_ENABLE_FIX_AND_CONTINUE = NO;


				GCC_MODEL_TUNING = G5;
				GCC_PRECOMPILE_PREFIX_HEADER = YES;
				GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h";


				INSTALL_PATH = /usr/local/bin;
				OTHER_LDFLAGS = (
					"-framework",
					Foundation,
					"-framework",
					AppKit,
				);
				PREBINDING = NO;
				PRODUCT_NAME = CommonCryptoTestTool;
				ZERO_LINK = NO;
			};
			name = Release;
		};
		5DAD839C1279F1ED00240B9A /* Development */ = {
			isa = XCBuildConfiguration;

			baseConfigurationReference = 12790C7511F7C4BA0044EFE5 /* CommonCrypto_unittest_development.xcconfig */;









			buildSettings = {

				ALWAYS_SEARCH_USER_PATHS = NO;

				COPY_PHASE_STRIP = NO;
				GCC_DYNAMIC_NO_PIC = NO;
				GCC_ENABLE_FIX_AND_CONTINUE = YES;
				GCC_MODEL_TUNING = G5;
				GCC_OPTIMIZATION_LEVEL = 0;
				GCC_PRECOMPILE_PREFIX_HEADER = YES;
				GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h";



				INSTALL_PATH = /usr/local/bin;



				OTHER_LDFLAGS = (


					"-framework",


					Foundation,
				);
				PREBINDING = NO;
				PRODUCT_NAME = CommonCryptoTestTool;
			};
			name = Development;
		};
		5DC876F910FFB6BC0012A390 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12790C7411F7C4BA0044EFE5 /* CommonCrypto_unittest_deployment.xcconfig */;
			buildSettings = {
				COPY_PHASE_STRIP = YES;

				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";




				GCC_ENABLE_FIX_AND_CONTINUE = NO;
				PRODUCT_NAME = "Unit Test World";
				ZERO_LINK = NO;
			};
			name = Release;
		};
		C27AD07F0987FCDA001272E0 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12FA10D011F7AACE00917A4E /* CommonCrypto_umbrellaMember_deployment.xcconfig */;
			buildSettings = {
				EXPORTED_SYMBOLS_FILE = Source/CommonCrypto.exp;







				OTHER_LDFLAGS = "";
				SDKROOT = "";
			};
			name = Release;
		};
		C27AD08F0987FCDA001272E0 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 12FA10D211F7AB3E00917A4E /* CommonCrypto_deployment.xcconfig */;
			buildSettings = {
				COPY_PHASE_STRIP = YES;
				OTHER_CFLAGS = "";
				OTHER_LDFLAGS = "";
				OTHER_REZFLAGS = "";
				PRODUCT_NAME = world;
				SECTORDER_FLAGS = "";
				WARNING_CFLAGS = (
					"-Wmost",
					"-Wno-four-char-constants",
					"-Wno-unknown-pragmas",
				);
			};
			name = Release;
		};
		C27AD0930987FCDA001272E0 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";





			};
			name = Release;
		};
/* End XCBuildConfiguration section */

/* Begin XCConfigurationList section */
		05CE94300A37850A007C91D6 /* Build configuration list for PBXAggregateTarget "Copy Open Source Docs" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				05CE94320A37850A007C91D6 /* Release */,
				12F25D8811F7BF8A0036BC8E /* Development */,
				);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
			};
		125B795711FF9279008C1AD3 /* Build configuration list for PBXNativeTarget "XTStest" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				125B795311FF923E008C1AD3 /* Release */,
				125B795411FF923E008C1AD3 /* Development */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		128881691203675B0050B2E9 /* Build configuration list for PBXNativeTarget "CBCTest" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				128881671203673D0050B2E9 /* Release */,
				128881681203673D0050B2E9 /* Development */,
				);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
			};
		48F7F36A12B2EF6000AF4587 /* Build configuration list for PBXNativeTarget "commonCryptoOpenSource" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				48F7F36B12B2EF6000AF4587 /* Release */,
				48F7F36C12B2EF6000AF4587 /* Development */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		5D735E4D10FCDC04001AAD1E /* Build configuration list for PBXNativeTarget "CommonCryptoUnitTest" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				5D735E4B10FCDC04001AAD1E /* Release */,
				12F25D8911F7BF8A0036BC8E /* Development */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		5DAD82E61279DFA700240B9A /* Build configuration list for PBXNativeTarget "UnitTestLibrary" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				5DAD82CD1279DEFA00240B9A /* Release */,
				5DAD82CE1279DEFA00240B9A /* Development */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		5DAD83A01279F24B00240B9A /* Build configuration list for PBXNativeTarget "CommonCryptoTestTool" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				5DAD839B1279F1ED00240B9A /* Release */,
				5DAD839C1279F1ED00240B9A /* Development */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		5DC876FB10FFB6DA0012A390 /* Build configuration list for PBXAggregateTarget "Unit Test World" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				5DC876F910FFB6BC0012A390 /* Release */,
				12F25D8A11F7BF8A0036BC8E /* Development */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		C27AD07D0987FCDA001272E0 /* Build configuration list for PBXNativeTarget "commonCrypto" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				C27AD07F0987FCDA001272E0 /* Release */,
				12F25D8711F7BF8A0036BC8E /* Development */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		C27AD08D0987FCDA001272E0 /* Build configuration list for PBXAggregateTarget "world" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				C27AD08F0987FCDA001272E0 /* Release */,
				12F25D8611F7BF8A0036BC8E /* Development */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		C27AD0910987FCDA001272E0 /* Build configuration list for PBXProject "CommonCrypto" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				C27AD0930987FCDA001272E0 /* Release */,
				12F25D8511F7BF8A0036BC8E /* Development */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
/* End XCConfigurationList section */
	};
	rootObject = 054BBEA605F6A8DE00344873 /* Project object */;
}







|


|
|
|
|
|
<
|
<
|

|


<
>


>
>
>
>
|
>
>
|
|
<
>
|
|
<
>
|
|
|
|
|
|
|
|
|
>
>
>
>

|


|


|
|
<
>
|
|
>
|
>
>
|

|


|


|
<
<
<
<
<
<

<
|


|


>
>
|
|
>
>
>
>
>
>

<
|


|


|
|
>

<
|





|
>
>
>




<



>
>
|
>
>
>







>
|
>



>
>
>
|
>
>





|


|
<
>
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
>
|
|
|
|
|
<
<
<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|


|


|
|
|

|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|


|
|
|
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<

<
<
<
<
<
|
<
<
<
<
<
<
<
<
|


<
<
<
<
<
<
<
<
<
<
<
|
<
<
<


<
<
<
<
<
<
>
|
|
<
>
|
|
<
>
|
<
<
<
<
<
<
<

|
<
<
<
<
<
<
<
<
<
<
<
<
<
|


|

<
<
<
<
<
<
<
<
<
<
<
<
<
<

<
<
<
<
<
<
<
<
<
<
<
|
|
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



<



|


|
|
<
|
|
|
<
<
<
<
|
<
<
|
>
|
|
|
|
|
|
|
<

>
|


|


<
<
|
<
|
<
<
<

|


|


|
<
<
>

>
|





|
|
|
|
<
<
<
<
<
<


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<









>

<
<
<
<
<
<
<
<
<
<
<

<
<



|
|
<
|
<
<
|
|
|
|
|
|
|
|
|
|
|
<
<
<
|
<
<
<
|
|
|
|
<
<
<
<
|
|
|
|
|
|
<
|
<
|
<
|
|
<
<



|



>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
>
>
>
|
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
<
|
>
>
|
|
|
|
|
|
|
|
|
|
<
<
<
>
|
|
|
|
>






|

|



>


>




|




<
>

|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

>
|
|


>


<

|
|
|
|

|

|

|
|
>


|



|

|


|

|

|
|
|




|
<

|
|
|
|

<
>

|

<
|
|
<
|

<
<
<
<
<
<
<
<
<
<
<
<
<
<



|

|
|
|







>
>
>
















|
>

|
<
<
<
<
|
|
>
>





|

|






|

|








<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






|
|
|
|
|
<
<
<
|
<
<
<
<
<
|
|
<
<
<
<
|
|
|
<
|
|
|
|
<
|
<
<



|



|
|
|
|
<
<
<
>
|
>
|
<
|
>
>
|
|
<
<
<
>
>
>
>
>
>
>
>
>
>
>
>
|



<
<
<
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
|
<
<
|
|
|
<
|
<
|
<
<
<
|
<
>
|
<
>
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
<
<
<
<
<
<
<
<
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
<
|
|
|
<
|
<
<
|
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



|



>
|
<
|
<
|
>
|
|
|
>
|
>
|
|
>
|
|
|
<
<
<
>
>
>
|
|
<
>
>
|
>
>
|
>
>











|

|
|

|

|
|

|

|
|

|

<
<
<
<
<
<
<
<
<
<
|
|

|

<
<
<
<
<
|
|














<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|

<

<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
|
|
<
<
<
<
<
|
>

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|

<
<
<
<
<
<
|

<













|

|

|

|
>
>
>
>
>
>
>



|

|







|

|

|

>
>
>
>
>
>
|

|
>

<
>
|
>

|

|

|
>
>
|
>
|
|
|
>
>
>
>
>
|
|

|

|

|

>
>
|
>
>
>
|
<
<
<
<
>
>
>
>
|
|
>



|

|

>
>
|
>
>
|
<
<
|
>
>

|
|

|

|

<

|
|
>
|
<
>
>
|
>
>
>
>
>
>
|
>
>
>



|

<

>
>
>
>
>
>
|
<
|
<
|
>
>
>
|
>
>
>
>
>
|
>
>
|
>
|

|

|

<


|
<
|
>
>
|
|
<
>
>
|
|
<
<
<
|
<
|
|
|



|

>
|
>
>
>
>
>
>
>
>
>
|
>
|
>
|
|
|
|
|
|
<
>
>
>
|
>
>
>
|
>
>
|
>
>
|
<
|
|

|

|

|

|
>
|
>
>
>
>
|
|
<

|



|

|
>
>
>
>
>
>
>







<



















>
>
>
>
>










|
|


|
|


|
|




|


|
|
|


|
|


|
|




|


|
|




|


|
|




<
<
<
<
<
<
<
<
<
|


|
|




|



|








|








|








869
870
871
872
873
874
875
876
877
878
879
880
881
882
883

884

885
886
887
888
889

890
891
892
893
894
895
896
897
898
899
900
901

902
903
904

905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927

928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943






944

945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961

962
963
964
965
966
967
968
969
970
971

972
973
974
975
976
977
978
979
980
981
982
983
984
985

986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022

1023
1024
1025








































1026
1027
1028
1029
1030
1031




1032














1033






















1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044









































1045
1046











































1047
1048
1049
1050
1051
1052
1053
1054
1055






































1056






1057





1058








1059
1060
1061











1062



1063
1064






1065
1066
1067

1068
1069
1070

1071
1072







1073
1074













1075
1076
1077
1078
1079














1080











1081
1082








1083








1084
















1085
1086
1087

1088
1089
1090
1091
1092
1093
1094
1095

1096
1097
1098




1099


1100
1101
1102
1103
1104
1105
1106
1107
1108

1109
1110
1111
1112
1113
1114
1115
1116


1117

1118



1119
1120
1121
1122
1123
1124
1125
1126


1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139






1140
1141



































1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152











1153


1154
1155
1156
1157
1158

1159


1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170



1171



1172
1173
1174
1175




1176
1177
1178
1179
1180
1181

1182

1183

1184
1185


1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220

1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245

1246
1247
1248

1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261



1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292

1293
1294
1295

















1296
1297
1298
1299
1300
1301
1302
1303
1304

1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340

1341
1342
1343
1344
1345
1346

1347
1348
1349
1350

1351
1352

1353
1354














1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392




1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
















1422

























































































1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433



1434





1435
1436




1437
1438
1439

1440
1441
1442
1443

1444


1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455



1456
1457
1458
1459

1460
1461
1462
1463
1464



1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480



1481
1482


















1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495


1496


1497
1498
1499

1500

1501



1502

1503
1504

1505
1506
1507
1508
1509
1510
1511
1512
1513
1514

1515
1516
1517
1518
1519








1520
1521
1522
1523
1524
1525

1526
1527
1528
1529
1530
1531
1532
1533

1534
1535
1536

1537


1538











1539



















1540
1541
1542
1543
1544
1545
1546
1547
1548

1549

1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563



1564
1565
1566
1567
1568

1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604










1605
1606
1607
1608
1609





1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625


















1626
1627

1628









1629









1630
1631





1632
1633
1634
















1635
1636






1637
1638

1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695

1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732




1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752


1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763

1764
1765
1766
1767
1768

1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786

1787
1788
1789
1790
1791
1792
1793
1794

1795

1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816

1817
1818
1819

1820
1821
1822
1823
1824

1825
1826
1827
1828



1829

1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858

1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872

1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890

1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912

1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996









1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
				05DF6D1109CF2D7200D9A3E8 /* CC_crypto.3cc */,
				05DF6D1209CF2D7200D9A3E8 /* CC_MD5.3cc */,
				05DF6D1309CF2D7200D9A3E8 /* CC_SHA.3cc */,
			);
			name = Doc;
			sourceTree = "<group>";
		};
		4823B0AC14C10022008F689F /* CCRegression */ = {
			isa = PBXGroup;
			children = (
				4823B0AD14C10022008F689F /* CommonCrypto */,
				4823B0C414C10022008F689F /* inc */,
				4823B0C814C10022008F689F /* main.c */,
				4823B0C914C10022008F689F /* README */,
				4823B0CA14C10022008F689F /* runscript */,

				4823B0CC14C10022008F689F /* test */,

				4823B0D714C10022008F689F /* util */,
			);
			path = CCRegression;
			sourceTree = "<group>";
		};

		4823B0AD14C10022008F689F /* CommonCrypto */ = {
			isa = PBXGroup;
			children = (
				4823B0AE14C10022008F689F /* CCCryptorTestFuncs.c */,
				4823B0AF14C10022008F689F /* CCCryptorTestFuncs.h */,
				4823B0B014C10022008F689F /* CommonBaseEncoding.c */,
				4823B0B114C10022008F689F /* CommonBigNum.c */,
				4823B0B214C10022008F689F /* CommonCMac.c */,
				4823B0B314C10022008F689F /* CommonCryptoCTSPadding.c */,
				4823B0B414C10022008F689F /* CommonCryptoSymCBC.c */,
				4823B0B514C10022008F689F /* CommonCryptoSymGCM.c */,
				4823B0B614C10022008F689F /* CommonCryptoSymmetricWrap.c */,

				4852C2491505F8CD00676BCC /* CommonCryptoSymCFB.c */,
				4823B0B714C10022008F689F /* CommonCryptoSymOFB.c */,
				4823B0B814C10022008F689F /* CommonCryptoSymOffset.c */,

				4823B0B914C10022008F689F /* CommonCryptoSymRC2.c */,
				4823B0BA14C10022008F689F /* CommonCryptoSymRegression.c */,
				486BE17C14E6019B00346AC4 /* CommonCryptoReset.c */,
				4823B0BB14C10022008F689F /* CommonCryptoSymXTS.c */,
				4823B0BC14C10022008F689F /* CommonCryptoSymZeroLength.c */,
				4823B0BD14C10022008F689F /* CommonDigest.c */,
				4823B0BE14C10022008F689F /* CommonEC.c */,
				4823B0BF14C10022008F689F /* CommonHMacClone.c */,
				4823B0C014C10022008F689F /* CommonRandom.c */,
				4823B0C114C10022008F689F /* CommonRSA.c */,
				4823B0C314C10022008F689F /* CryptorPadFailure.c */,
				48CCD26414F6F189002B6043 /* CommonBigDigest.c */,
				48C5CB9114FD747500F4472E /* CommonDHtest.c */,
				4854BAD5152177CC007B5B08 /* CommonCryptoSymCTR.c */,
			);
			path = CommonCrypto;
			sourceTree = "<group>";
		};
		4823B0C414C10022008F689F /* inc */ = {
			isa = PBXGroup;
			children = (
				4823B0C514C10022008F689F /* IPC */,
				4823B0C714C10022008F689F /* MyHarness.pm */,

			);
			path = inc;
			sourceTree = "<group>";
		};
		4823B0C514C10022008F689F /* IPC */ = {
			isa = PBXGroup;
			children = (
				4823B0C614C10022008F689F /* Run3.pm */,
			);
			path = IPC;
			sourceTree = "<group>";
		};
		4823B0CA14C10022008F689F /* runscript */ = {
			isa = PBXGroup;
			children = (
				4823B0CB14C10022008F689F /* security.pl */,






			);

			path = runscript;
			sourceTree = "<group>";
		};
		4823B0CC14C10022008F689F /* test */ = {
			isa = PBXGroup;
			children = (
				4823B0CD14C10022008F689F /* 00testtest.c */,
				4823B0CE14C10022008F689F /* run_tests.sh */,
				4823B0CF14C10022008F689F /* testcpp.h */,
				4823B0D014C10022008F689F /* testenv.c */,
				4823B0D114C10022008F689F /* testenv.h */,
				4823B0D214C10022008F689F /* testlist.c */,
				4823B0D314C10022008F689F /* testlist.h */,
				4823B0D414C10022008F689F /* testlistInc.h */,
				4823B0D514C10022008F689F /* testmore.c */,
				4823B0D614C10022008F689F /* testmore.h */,
			);

			path = test;
			sourceTree = "<group>";
		};
		4823B0D714C10022008F689F /* util */ = {
			isa = PBXGroup;
			children = (
				4823B0D814C10022008F689F /* testbyteBuffer.c */,
				4823B0D914C10022008F689F /* testbyteBuffer.h */,
				4823B0DA14C10022008F689F /* capabilities.h */,
			);

			path = util;
			sourceTree = "<group>";
		};
		4836A42A11A5CB4700862178 /* API */ = {
			isa = PBXGroup;
			children = (
				489F2441141AA3D0005E80FD /* CommonCMAC.c */,
				48A5CBA0131EE096002A6E85 /* CommonGCMCryptor.c */,
				48685586127B641800B88D39 /* CommonCryptoAESShoefly.c */,
				48FC4BD71395ACE600DA4760 /* CommonCryptoCASTShoefly.c */,
				4836A42B11A5CB4700862178 /* CommonCryptor.c */,
				4836A42C11A5CB4700862178 /* CommonCryptorPriv.h */,
				4836A42E11A5CB4700862178 /* CommonHMAC.c */,
				4836A42F11A5CB4700862178 /* CommonKeyDerivation.c */,

				4836A43111A5CB4700862178 /* CommonSymmetricKeywrap.c */,
				4836A42D11A5CB4700862178 /* CommonDigestPriv.h */,
				48096B2211A5EF900043F67F /* CommonDigest.c */,
				48B4651B1284907600311799 /* CommonRSACryptor.c */,
				48D076CF130B2A9C0052D1AC /* CommonECCryptor.c */,
				48D076CE130B2A9C0052D1AC /* CommonDH.c */,
				485FED4A131475A400FF0F82 /* CommonBigNumPriv.h */,
				485FED4B131475A400FF0F82 /* CommonBigNum.c */,
				48F5355214902894000D2D1F /* CommonRandom.c */,
			);
			path = API;
			sourceTree = "<group>";
		};
		4846CA5311A5C8B800E7DA82 /* SPI */ = {
			isa = PBXGroup;
			children = (
				48FC4BD513959D0600DA4760 /* lionCompat.h */,
				48E93DCA136867F500B33DB8 /* CommonCMACSPI.h */,
				48685583127B63F200B88D39 /* aes.h */,
				4836A41A11A5C94A00862178 /* CommonCryptoPriv.h */,
				4846CA5411A5C8B800E7DA82 /* CommonCryptorSPI.h */,
				4846CA5511A5C8B800E7DA82 /* CommonDigestSPI.h */,
				12FA0DAF11F7962100917A4E /* CommonRandomSPI.h */,
				48B4651112848FB800311799 /* CommonRSACryptor.h */,
				48D076C7130B2A620052D1AC /* CommonECCryptor.h */,
				48D076C0130B2A510052D1AC /* CommonDH.h */,
				489FD30B13187B1D00ACB86D /* CommonHMacSPI.h */,
				4825AAF31314CDCD00413A64 /* CommonBigNum.h */,
			);
			name = SPI;
			path = CommonCryptoSPI;
			sourceTree = "<group>";
		};
		486130D6126681290036EA02 /* components */ = {
			isa = PBXGroup;
			children = (
				486130D7126681290036EA02 /* CC_base.xcconfig */,

				486130D8126681290036EA02 /* CC_deployment.xcconfig */,
				486130D9126681290036EA02 /* CC_development.xcconfig */,
				486130DA126681290036EA02 /* CC_dynamic.xcconfig */,








































				486130DB126681290036EA02 /* CC_dynamic_deployment.xcconfig */,
				486130DC126681290036EA02 /* CC_dynamic_development.xcconfig */,
				486130DD126681290036EA02 /* CC_static.xcconfig */,
				486130DE126681290036EA02 /* CC_static_deployment.xcconfig */,
				486130DF126681290036EA02 /* CC_static_development.xcconfig */,
				486130E0126681290036EA02 /* CC_umbrellaMember.xcconfig */,




			);














			name = components;






















			path = Configurations/components;
			sourceTree = "<group>";
		};
		486130E1126681290036EA02 /* platforms */ = {
			isa = PBXGroup;
			children = (
				486130E2126681290036EA02 /* CC_iOSClient.xcconfig */,
				486130E3126681290036EA02 /* CC_iOSClientSim.xcconfig */,
				486130E5126681290036EA02 /* CC_MacOSXClient.xcconfig */,
			);
			name = platforms;









































			path = Configurations/platforms;
			sourceTree = "<group>";











































		};
		486130E7126681290036EA02 /* targets */ = {
			isa = PBXGroup;
			children = (
				486130E8126681290036EA02 /* CC_iOSClient_deployment.xcconfig */,
				486130E9126681290036EA02 /* CC_iOSClient_development.xcconfig */,
				486130EC126681290036EA02 /* CC_iOSSim_deployment.xcconfig */,
				486130ED126681290036EA02 /* CC_iOSSim_development.xcconfig */,
				486130EE126681290036EA02 /* CC_MacOSXClient_deployment.xcconfig */,






































				486130EF126681290036EA02 /* CC_MacOSXClient_development.xcconfig */,






			);





			name = targets;








			path = Configurations/targets;
			sourceTree = "<group>";
		};











		486130F2126681290036EA02 /* tests */ = {



			isa = PBXGroup;
			children = (






				486130F3126681290036EA02 /* CC_localtest.xcconfig */,
				486130F4126681290036EA02 /* CC_unittest_base.xcconfig */,
				486130F5126681290036EA02 /* CC_unittest_deployment.xcconfig */,

				486130F6126681290036EA02 /* CC_unittest_development.xcconfig */,
				486130F7126681290036EA02 /* CC_unittest_dynamic_deployment.xcconfig */,
				486130F8126681290036EA02 /* CC_unitTest_dynamic_development.xcconfig */,

				486130F9126681290036EA02 /* CC_unittest_static_deployment.xcconfig */,
				486130FA126681290036EA02 /* CC_unittest_static_development.xcconfig */,







			);
			name = tests;













			path = Configurations/tests;
			sourceTree = "<group>";
		};
		489D982B11A4E8C20004DB89 /* ccUtilities */ = {
			isa = PBXGroup;














			children = (











				48AC47CD1381EFDC00F584F5 /* byteBuffer.c */,
				48AC47CE1381EFDC00F584F5 /* byteBuffer.h */,








				48FD6C371354DD4000F55B8B /* ccErrors.h */,








				48FD6C381354DD4000F55B8B /* ccMemory.h */,
















				489D982C11A4E8C20004DB89 /* ccdebug.c */,
				489D982D11A4E8C20004DB89 /* ccdebug.h */,
			);

			path = ccUtilities;
			sourceTree = "<group>";
		};
		489EECA1149809A800B44D5A /* libDER */ = {
			isa = PBXGroup;
			children = (
				489EECA2149809A800B44D5A /* asn1Types.h */,
				489EECA3149809A800B44D5A /* DER_CertCrl.c */,

				489EECA4149809A800B44D5A /* DER_CertCrl.h */,
				489EECA5149809A800B44D5A /* DER_Decode.c */,
				489EECA6149809A800B44D5A /* DER_Decode.h */,




				489EECA7149809A800B44D5A /* DER_Digest.c */,


				489EECA8149809A800B44D5A /* DER_Digest.h */,
				489EECA9149809A800B44D5A /* DER_Encode.c */,
				489EECAA149809A800B44D5A /* DER_Encode.h */,
				489EECAB149809A800B44D5A /* DER_Keys.c */,
				489EECAC149809A800B44D5A /* DER_Keys.h */,
				489EECAD149809A800B44D5A /* libDER.h */,
				489EECAE149809A800B44D5A /* libDER_config.h */,
				489EECAF149809A800B44D5A /* oids.c */,
				489EECB0149809A800B44D5A /* oids.h */,

			);
			name = libDER;
			path = libDER/libDER;
			sourceTree = "<group>";
		};
		48CA258512C149EF002330C4 /* descriptors */ = {
			isa = PBXGroup;
			children = (


				489E06F814B7AB0800B0A282 /* corecryptoSymmetricBridge.c */,

				4868BB1314B7C7F300072488 /* corecryptoSymmetricBridge.h */,



			);
			path = descriptors;
			sourceTree = "<group>";
		};
		48FD6C621354E06A00F55B8B /* Exports */ = {
			isa = PBXGroup;
			children = (
				48FD6C631354E06A00F55B8B /* CommonCrypto.exp */,


				48FD6C641354E06A00F55B8B /* CommonCryptoIOS5.exp */,
			);
			name = Exports;
			path = Source/Exports;
			sourceTree = "<group>";
		};
		5DB4936310FBC4E200E45951 /* Configurations */ = {
			isa = PBXGroup;
			children = (
				486130D6126681290036EA02 /* components */,
				486130E1126681290036EA02 /* platforms */,
				486130E7126681290036EA02 /* targets */,
				486130F2126681290036EA02 /* tests */,






			);
			name = Configurations;



































			sourceTree = "<group>";
		};
/* End PBXGroup section */

/* Begin PBXHeadersBuildPhase section */
		054BBEBA05F6A97700344873 /* Headers */ = {
			isa = PBXHeadersBuildPhase;
			buildActionMask = 2147483647;
			files = (
				4873A7281445099D0011B4FA /* CommonCrypto.h in Headers */,
				054BBECE05F6AA7200344873 /* CommonDigest.h in Headers */,











				05D9F61909D85F4A00AD30A7 /* CommonCryptor.h in Headers */,


				05D8D97D09E411AB00E03504 /* CommonHMAC.h in Headers */,
				4854F9C21116307500CAFA18 /* CommonKeyDerivation.h in Headers */,
				4854F9C31116307500CAFA18 /* CommonSymmetricKeywrap.h in Headers */,
				489FD30E13187B1D00ACB86D /* CommonHMacSPI.h in Headers */,
				488FCCB3139D6DD7007F2FC4 /* aes.h in Headers */,

				4836A43311A5CB4700862178 /* CommonCryptorPriv.h in Headers */,


				4825AAF81314CDCD00413A64 /* CommonBigNum.h in Headers */,
				48E93DCB136867F500B33DB8 /* CommonCMACSPI.h in Headers */,
				48D076C3130B2A510052D1AC /* CommonDH.h in Headers */,
				48D076CA130B2A620052D1AC /* CommonECCryptor.h in Headers */,
				48B4651512848FB800311799 /* CommonRSACryptor.h in Headers */,
				48FC4BD613959D0600DA4760 /* lionCompat.h in Headers */,
				489D982F11A4E8C20004DB89 /* ccdebug.h in Headers */,
				4846CA5611A5C8B800E7DA82 /* CommonCryptorSPI.h in Headers */,
				4846CA5711A5C8B800E7DA82 /* CommonDigestSPI.h in Headers */,
				4836A42111A5C94A00862178 /* CommonCryptoPriv.h in Headers */,
				4836A43411A5CB4700862178 /* CommonDigestPriv.h in Headers */,



				12FA0DB011F7962100917A4E /* CommonRandomSPI.h in Headers */,



				485FED56131475A400FF0F82 /* CommonBigNumPriv.h in Headers */,
				48FD6C401354DD4000F55B8B /* ccErrors.h in Headers */,
				48FD6C411354DD4000F55B8B /* ccMemory.h in Headers */,
				48AC47D51381EFDC00F584F5 /* byteBuffer.h in Headers */,




				489EECB1149809A800B44D5A /* asn1Types.h in Headers */,
				489EECB7149809A800B44D5A /* DER_CertCrl.h in Headers */,
				489EECBD149809A800B44D5A /* DER_Decode.h in Headers */,
				489EECC3149809A800B44D5A /* DER_Digest.h in Headers */,
				489EECC9149809A800B44D5A /* DER_Encode.h in Headers */,
				489EECCF149809A800B44D5A /* DER_Keys.h in Headers */,

				489EECD2149809A800B44D5A /* libDER.h in Headers */,

				489EECD5149809A800B44D5A /* libDER_config.h in Headers */,

				489EECDB149809A800B44D5A /* oids.h in Headers */,
				4868BB1414B7C7F300072488 /* corecryptoSymmetricBridge.h in Headers */,


			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		48165CD8125AC5D50015A267 /* Headers */ = {
			isa = PBXHeadersBuildPhase;
			buildActionMask = 2147483647;
			files = (
				4873A72A1445099D0011B4FA /* CommonCrypto.h in Headers */,
				48165CD9125AC5D50015A267 /* CommonDigest.h in Headers */,
				48165CDA125AC5D50015A267 /* CommonCryptor.h in Headers */,
				48165CDB125AC5D50015A267 /* CommonHMAC.h in Headers */,
				48165CDC125AC5D50015A267 /* CommonKeyDerivation.h in Headers */,
				48165CDD125AC5D50015A267 /* CommonSymmetricKeywrap.h in Headers */,
				48165CF0125AC5D50015A267 /* ccdebug.h in Headers */,
				48165CF1125AC5D50015A267 /* CommonCryptorSPI.h in Headers */,
				48165CF2125AC5D50015A267 /* CommonDigestSPI.h in Headers */,
				48165CF3125AC5D50015A267 /* CommonCryptoPriv.h in Headers */,
				48165CF4125AC5D50015A267 /* CommonCryptorPriv.h in Headers */,
				48165CF5125AC5D50015A267 /* CommonDigestPriv.h in Headers */,
				48165CF7125AC5D50015A267 /* CommonRandomSPI.h in Headers */,
				48685584127B63F200B88D39 /* aes.h in Headers */,
				48B4651412848FB800311799 /* CommonRSACryptor.h in Headers */,
				48D076C1130B2A510052D1AC /* CommonDH.h in Headers */,
				48D076C8130B2A620052D1AC /* CommonECCryptor.h in Headers */,
				489FD30C13187B1D00ACB86D /* CommonHMacSPI.h in Headers */,
				485FED54131475A400FF0F82 /* CommonBigNumPriv.h in Headers */,
				4825AAF61314CDCD00413A64 /* CommonBigNum.h in Headers */,
				48FD6C3A1354DD4000F55B8B /* ccErrors.h in Headers */,
				48FD6C3B1354DD4000F55B8B /* ccMemory.h in Headers */,
				48E93DCC136867F500B33DB8 /* CommonCMACSPI.h in Headers */,
				48AC47D71381EFDC00F584F5 /* byteBuffer.h in Headers */,
				489EECB2149809A800B44D5A /* asn1Types.h in Headers */,
				489EECB8149809A800B44D5A /* DER_CertCrl.h in Headers */,
				489EECBE149809A800B44D5A /* DER_Decode.h in Headers */,
				489EECC4149809A800B44D5A /* DER_Digest.h in Headers */,

				489EECCA149809A800B44D5A /* DER_Encode.h in Headers */,
				489EECD0149809A800B44D5A /* DER_Keys.h in Headers */,
				489EECD3149809A800B44D5A /* libDER.h in Headers */,
				489EECD6149809A800B44D5A /* libDER_config.h in Headers */,
				489EECDC149809A800B44D5A /* oids.h in Headers */,
				4868BB1514B7C7F300072488 /* corecryptoSymmetricBridge.h in Headers */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		48165DBB125AC5F20015A267 /* Headers */ = {
			isa = PBXHeadersBuildPhase;
			buildActionMask = 2147483647;
			files = (
				4873A72B1445099D0011B4FA /* CommonCrypto.h in Headers */,
				48165DBC125AC5F20015A267 /* CommonDigest.h in Headers */,
				48165DBD125AC5F20015A267 /* CommonCryptor.h in Headers */,
				48165DBE125AC5F20015A267 /* CommonHMAC.h in Headers */,
				48165DBF125AC5F20015A267 /* CommonKeyDerivation.h in Headers */,
				48165DC0125AC5F20015A267 /* CommonSymmetricKeywrap.h in Headers */,
				48165DD3125AC5F20015A267 /* ccdebug.h in Headers */,
				48165DD4125AC5F20015A267 /* CommonCryptorSPI.h in Headers */,
				48165DD5125AC5F20015A267 /* CommonDigestSPI.h in Headers */,
				48165DD6125AC5F20015A267 /* CommonCryptoPriv.h in Headers */,
				48165DD7125AC5F20015A267 /* CommonCryptorPriv.h in Headers */,
				48165DD8125AC5F20015A267 /* CommonDigestPriv.h in Headers */,

				48165DDA125AC5F20015A267 /* CommonRandomSPI.h in Headers */,
				48B4651712848FB800311799 /* CommonRSACryptor.h in Headers */,
				48D076C5130B2A510052D1AC /* CommonDH.h in Headers */,

				48D076CC130B2A620052D1AC /* CommonECCryptor.h in Headers */,
				489FD30F13187B1D00ACB86D /* CommonHMacSPI.h in Headers */,
				485FED50131475A400FF0F82 /* CommonBigNumPriv.h in Headers */,
				4825AAF71314CDCD00413A64 /* CommonBigNum.h in Headers */,
				4CDDFB7E133BD3BA00B4770F /* aes.h in Headers */,
				48FD6C431354DD4000F55B8B /* ccErrors.h in Headers */,
				48FD6C441354DD4000F55B8B /* ccMemory.h in Headers */,
				48E93DCD136867F500B33DB8 /* CommonCMACSPI.h in Headers */,
				48AC47D81381EFDC00F584F5 /* byteBuffer.h in Headers */,
				489EECB3149809A800B44D5A /* asn1Types.h in Headers */,
				489EECB9149809A800B44D5A /* DER_CertCrl.h in Headers */,
				489EECBF149809A800B44D5A /* DER_Decode.h in Headers */,
				489EECC5149809A800B44D5A /* DER_Digest.h in Headers */,



				489EECCB149809A800B44D5A /* DER_Encode.h in Headers */,
				489EECD1149809A800B44D5A /* DER_Keys.h in Headers */,
				489EECD4149809A800B44D5A /* libDER.h in Headers */,
				489EECD7149809A800B44D5A /* libDER_config.h in Headers */,
				489EECDD149809A800B44D5A /* oids.h in Headers */,
				4868BB1614B7C7F300072488 /* corecryptoSymmetricBridge.h in Headers */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXHeadersBuildPhase section */

/* Begin PBXNativeTarget section */
		054BBEBD05F6A97700344873 /* libCommonCryptoMacOSX */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = C27AD07D0987FCDA001272E0 /* Build configuration list for PBXNativeTarget "libCommonCryptoMacOSX" */;
			buildPhases = (
				054BBEBA05F6A97700344873 /* Headers */,
				054BBEBB05F6A97700344873 /* Sources */,
				EEB70419131C5BCB007CF918 /* Frameworks */,
			);
			buildRules = (
				48B5F5281361D6A500134C9F /* PBXBuildRule */,
				B125268E0713742A00BB8157 /* PBXBuildRule */,
			);
			dependencies = (
			);
			name = libCommonCryptoMacOSX;
			productName = commonCrypto;
			productReference = 054BBEBE05F6A97700344873 /* libcommonCrypto.dylib */;
			productType = "com.apple.product-type.library.dynamic";
		};

		48165CD7125AC5D50015A267 /* libCommonCryptoMacIOS */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 48165DB6125AC5D50015A267 /* Build configuration list for PBXNativeTarget "libCommonCryptoMacIOS" */;

















			buildPhases = (
				48165CD8125AC5D50015A267 /* Headers */,
				48165D30125AC5D50015A267 /* Sources */,
				48CCF15612FA99B600D6DAE9 /* Frameworks */,
			);
			buildRules = (
				48165DB5125AC5D50015A267 /* PBXBuildRule */,
			);
			dependencies = (

			);
			name = libCommonCryptoMacIOS;
			productName = commonCrypto;
			productReference = 48165DB9125AC5D50015A267 /* libcommonCrypto.dylib */;
			productType = "com.apple.product-type.library.dynamic";
		};
		48165DBA125AC5F20015A267 /* libCommonCryptoMacIOSSim */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 48165E99125AC5F20015A267 /* Build configuration list for PBXNativeTarget "libCommonCryptoMacIOSSim" */;
			buildPhases = (
				48165DBB125AC5F20015A267 /* Headers */,
				48165E13125AC5F20015A267 /* Sources */,
				4CA674F41331747E00C45A71 /* Frameworks */,
			);
			buildRules = (
				48165E98125AC5F20015A267 /* PBXBuildRule */,
			);
			dependencies = (
			);
			name = libCommonCryptoMacIOSSim;
			productName = commonCrypto;
			productReference = 48165E9C125AC5F20015A267 /* libcommonCrypto_sim.dylib */;
			productType = "com.apple.product-type.library.dynamic";
		};
		4823B0DF14C10064008F689F /* CCRegression */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 4823B0E714C10064008F689F /* Build configuration list for PBXNativeTarget "CCRegression" */;
			buildPhases = (
				4823B0DC14C10064008F689F /* Sources */,
				4823B0DD14C10064008F689F /* Frameworks */,
				4823B0DE14C10064008F689F /* CopyFiles */,
			);
			buildRules = (
			);
			dependencies = (
				4823B10D14C101CC008F689F /* PBXTargetDependency */,

			);
			name = CCRegression;
			productName = CCRegression;
			productReference = 4823B0E014C10064008F689F /* CCRegression */;
			productType = "com.apple.product-type.tool";
		};

		4834A85414F47B6200438E3D /* CCRegressionIos */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 4834A87D14F47B6200438E3D /* Build configuration list for PBXNativeTarget "CCRegressionIos" */;
			buildPhases = (

				4834A85714F47B6200438E3D /* Sources */,
				4834A87A14F47B6200438E3D /* Frameworks */,

				4834A87C14F47B6200438E3D /* CopyFiles */,
			);














			buildRules = (
			);
			dependencies = (
				4834A88414F47CA300438E3D /* PBXTargetDependency */,
			);
			name = CCRegressionIos;
			productName = CCRegression;
			productReference = 4834A88014F47B6200438E3D /* CCRegression copy */;
			productType = "com.apple.product-type.tool";
		};
/* End PBXNativeTarget section */

/* Begin PBXProject section */
		054BBEA605F6A8DE00344873 /* Project object */ = {
			isa = PBXProject;
			attributes = {
				LastUpgradeCheck = 0440;
			};
			buildConfigurationList = C27AD0910987FCDA001272E0 /* Build configuration list for PBXProject "CommonCrypto" */;
			compatibilityVersion = "Xcode 3.2";
			developmentRegion = English;
			hasScannedForEncodings = 1;
			knownRegions = (
				English,
				Japanese,
				French,
				German,
			);
			mainGroup = 054BBEA205F6A8DE00344873;
			productRefGroup = 054BBEBF05F6A97700344873 /* Products */;
			projectDirPath = "";
			projectRoot = "";
			targets = (
				054BBEB705F6A93300344873 /* world */,
				4C99FCB61326E14F0040AD38 /* commonCryptoMacIOS */,
				4CA675141332C16C00C45A71 /* CommonCrypto_Sim */,
				05CE94290A3784D4007C91D6 /* Copy Open Source Docs */,
				054BBEBD05F6A97700344873 /* libCommonCryptoMacOSX */,




				48165CD7125AC5D50015A267 /* libCommonCryptoMacIOS */,
				48165DBA125AC5F20015A267 /* libCommonCryptoMacIOSSim */,
				4823B0DF14C10064008F689F /* CCRegression */,
				4834A85414F47B6200438E3D /* CCRegressionIos */,
			);
		};
/* End PBXProject section */

/* Begin PBXShellScriptBuildPhase section */
		4CA6751A1332C18C00C45A71 /* ShellScript */ = {
			isa = PBXShellScriptBuildPhase;
			buildActionMask = 8;
			files = (
			);
			inputPaths = (
			);
			outputPaths = (
			);
			runOnlyForDeploymentPostprocessing = 1;
			shellPath = /bin/sh;
			shellScript = "set -x\ncd $DSTROOT\nmkdir -p ${SDKROOT#/}\ntar cf - usr | tar xvfC - ${SDKROOT#/}\nrm -rf usr";
		};
/* End PBXShellScriptBuildPhase section */

/* Begin PBXSourcesBuildPhase section */
		054BBEBB05F6A97700344873 /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
















				48067F871362405D005DDEBC /* CommonCryptoAESShoefly.c in Sources */,

























































































				489D982E11A4E8C20004DB89 /* ccdebug.c in Sources */,
				4836A43211A5CB4700862178 /* CommonCryptor.c in Sources */,
				4836A43511A5CB4700862178 /* CommonHMAC.c in Sources */,
				4836A43611A5CB4700862178 /* CommonKeyDerivation.c in Sources */,
				4836A43811A5CB4700862178 /* CommonSymmetricKeywrap.c in Sources */,
				48096B2311A5EF900043F67F /* CommonDigest.c in Sources */,
				48B4651D1284907600311799 /* CommonRSACryptor.c in Sources */,
				48D076D4130B2A9C0052D1AC /* CommonDH.c in Sources */,
				48D076D5130B2A9C0052D1AC /* CommonECCryptor.c in Sources */,
				48A5CBA6131EE096002A6E85 /* CommonGCMCryptor.c in Sources */,
				485FED57131475A400FF0F82 /* CommonBigNum.c in Sources */,



				48AC47CF1381EFDC00F584F5 /* byteBuffer.c in Sources */,





				48FC4BD81395ACE600DA4760 /* CommonCryptoCASTShoefly.c in Sources */,
				489F2442141AA3D0005E80FD /* CommonCMAC.c in Sources */,




				48F5355314902894000D2D1F /* CommonRandom.c in Sources */,
				489EECB4149809A800B44D5A /* DER_CertCrl.c in Sources */,
				489EECBA149809A800B44D5A /* DER_Decode.c in Sources */,

				489EECC0149809A800B44D5A /* DER_Digest.c in Sources */,
				489EECC6149809A800B44D5A /* DER_Encode.c in Sources */,
				489EECCC149809A800B44D5A /* DER_Keys.c in Sources */,
				489EECD8149809A800B44D5A /* oids.c in Sources */,

				489E06F914B7AB0900B0A282 /* corecryptoSymmetricBridge.c in Sources */,


			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		48165D30125AC5D50015A267 /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				48165D78125AC5D50015A267 /* ccdebug.c in Sources */,
				48165D79125AC5D50015A267 /* CommonCryptor.c in Sources */,
				48165D7A125AC5D50015A267 /* CommonHMAC.c in Sources */,
				48165D7B125AC5D50015A267 /* CommonKeyDerivation.c in Sources */,



				48165D7C125AC5D50015A267 /* CommonSymmetricKeywrap.c in Sources */,
				48165D7D125AC5D50015A267 /* CommonDigest.c in Sources */,
				48685587127B641800B88D39 /* CommonCryptoAESShoefly.c in Sources */,
				48B4651E1284907600311799 /* CommonRSACryptor.c in Sources */,

				48D076D0130B2A9C0052D1AC /* CommonDH.c in Sources */,
				48D076D1130B2A9C0052D1AC /* CommonECCryptor.c in Sources */,
				48A5CBA2131EE096002A6E85 /* CommonGCMCryptor.c in Sources */,
				485FED55131475A400FF0F82 /* CommonBigNum.c in Sources */,
				48AC47D11381EFDC00F584F5 /* byteBuffer.c in Sources */,



				489F2444141AA3D0005E80FD /* CommonCMAC.c in Sources */,
				48F5355414902894000D2D1F /* CommonRandom.c in Sources */,
				489EECB5149809A800B44D5A /* DER_CertCrl.c in Sources */,
				489EECBB149809A800B44D5A /* DER_Decode.c in Sources */,
				489EECC1149809A800B44D5A /* DER_Digest.c in Sources */,
				489EECC7149809A800B44D5A /* DER_Encode.c in Sources */,
				489EECCD149809A800B44D5A /* DER_Keys.c in Sources */,
				489EECD9149809A800B44D5A /* oids.c in Sources */,
				489E06FA14B7AB0900B0A282 /* corecryptoSymmetricBridge.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		48165E13125AC5F20015A267 /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (



				48165E5B125AC5F20015A267 /* ccdebug.c in Sources */,
				48165E5C125AC5F20015A267 /* CommonCryptor.c in Sources */,


















				48165E5D125AC5F20015A267 /* CommonHMAC.c in Sources */,
				48165E5E125AC5F20015A267 /* CommonKeyDerivation.c in Sources */,
				48165E5F125AC5F20015A267 /* CommonSymmetricKeywrap.c in Sources */,
				48165E60125AC5F20015A267 /* CommonDigest.c in Sources */,
				48B4651F1284907600311799 /* CommonRSACryptor.c in Sources */,
				48D076D8130B2A9C0052D1AC /* CommonDH.c in Sources */,
				48D076D9130B2A9C0052D1AC /* CommonECCryptor.c in Sources */,
				48A5CBA8131EE096002A6E85 /* CommonGCMCryptor.c in Sources */,
				485FED51131475A400FF0F82 /* CommonBigNum.c in Sources */,
				4CF7820B1339B543004A56DF /* CommonCryptoAESShoefly.c in Sources */,
				48AC47D21381EFDC00F584F5 /* byteBuffer.c in Sources */,
				489F2445141AA3D0005E80FD /* CommonCMAC.c in Sources */,
				489EECB6149809A800B44D5A /* DER_CertCrl.c in Sources */,


				489EECBC149809A800B44D5A /* DER_Decode.c in Sources */,


				489EECC2149809A800B44D5A /* DER_Digest.c in Sources */,
				489EECC8149809A800B44D5A /* DER_Encode.c in Sources */,
				489EECCE149809A800B44D5A /* DER_Keys.c in Sources */,

				489EECDA149809A800B44D5A /* oids.c in Sources */,

				489E06FB14B7AB0900B0A282 /* corecryptoSymmetricBridge.c in Sources */,



				5DB80D3E14FC5CB3002C9A03 /* CommonRandom.c in Sources */,

			);
			runOnlyForDeploymentPostprocessing = 0;

		};
		4823B0DC14C10064008F689F /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				4823B10914C1017C008F689F /* testbyteBuffer.c in Sources */,
				4823B10214C1016B008F689F /* testenv.c in Sources */,
				4823B10414C1016B008F689F /* testlist.c in Sources */,
				4823B10714C1016B008F689F /* testmore.c in Sources */,
				4823B10014C10155008F689F /* main.c in Sources */,

				4823B0EA14C1013F008F689F /* CCCryptorTestFuncs.c in Sources */,
				4823B0EC14C1013F008F689F /* CommonBaseEncoding.c in Sources */,
				4823B0ED14C1013F008F689F /* CommonBigNum.c in Sources */,
				4823B0EE14C1013F008F689F /* CommonCMac.c in Sources */,
				4823B0EF14C1013F008F689F /* CommonCryptoCTSPadding.c in Sources */,








				4823B0F014C1013F008F689F /* CommonCryptoSymCBC.c in Sources */,
				4823B0F114C1013F008F689F /* CommonCryptoSymGCM.c in Sources */,
				4823B0F214C1013F008F689F /* CommonCryptoSymmetricWrap.c in Sources */,
				4823B0F314C1013F008F689F /* CommonCryptoSymOFB.c in Sources */,
				4823B0F414C1013F008F689F /* CommonCryptoSymOffset.c in Sources */,
				4823B0F514C1013F008F689F /* CommonCryptoSymRC2.c in Sources */,

				4823B0F614C1013F008F689F /* CommonCryptoSymRegression.c in Sources */,
				4823B0F714C1013F008F689F /* CommonCryptoSymXTS.c in Sources */,
				4823B0F814C1013F008F689F /* CommonCryptoSymZeroLength.c in Sources */,
				4823B0F914C1013F008F689F /* CommonDigest.c in Sources */,
				4823B0FA14C1013F008F689F /* CommonEC.c in Sources */,
				4823B0FB14C1013F008F689F /* CommonHMacClone.c in Sources */,
				4823B0FC14C1013F008F689F /* CommonRandom.c in Sources */,
				4823B0FD14C1013F008F689F /* CommonRSA.c in Sources */,

				4823B0FF14C1013F008F689F /* CryptorPadFailure.c in Sources */,
				486BE17D14E6019B00346AC4 /* CommonCryptoReset.c in Sources */,
				48CCD26514F6F189002B6043 /* CommonBigDigest.c in Sources */,

				48C5CB9214FD747500F4472E /* CommonDHtest.c in Sources */,


				4852C24A1505F8CD00676BCC /* CommonCryptoSymCFB.c in Sources */,











				4854BAD6152177CC007B5B08 /* CommonCryptoSymCTR.c in Sources */,



















			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		4834A85714F47B6200438E3D /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				48CCD26614F6F1E1002B6043 /* CommonBigDigest.c in Sources */,
				4834A85814F47B6200438E3D /* testbyteBuffer.c in Sources */,

				4834A85C14F47B6200438E3D /* testenv.c in Sources */,

				4834A85E14F47B6200438E3D /* testlist.c in Sources */,
				4834A86114F47B6200438E3D /* testmore.c in Sources */,
				4834A86314F47B6200438E3D /* main.c in Sources */,
				4834A86414F47B6200438E3D /* CCCryptorTestFuncs.c in Sources */,
				4834A86614F47B6200438E3D /* CommonBaseEncoding.c in Sources */,
				4834A86714F47B6200438E3D /* CommonBigNum.c in Sources */,
				4834A86814F47B6200438E3D /* CommonCMac.c in Sources */,
				4834A86914F47B6200438E3D /* CommonCryptoCTSPadding.c in Sources */,
				4834A86A14F47B6200438E3D /* CommonCryptoSymCBC.c in Sources */,
				4834A86B14F47B6200438E3D /* CommonCryptoSymGCM.c in Sources */,
				4834A86C14F47B6200438E3D /* CommonCryptoSymmetricWrap.c in Sources */,
				4834A86D14F47B6200438E3D /* CommonCryptoSymOFB.c in Sources */,
				4834A86E14F47B6200438E3D /* CommonCryptoSymOffset.c in Sources */,
				4834A86F14F47B6200438E3D /* CommonCryptoSymRC2.c in Sources */,



				4834A87014F47B6200438E3D /* CommonCryptoSymRegression.c in Sources */,
				4834A87114F47B6200438E3D /* CommonCryptoSymXTS.c in Sources */,
				4834A87214F47B6200438E3D /* CommonCryptoSymZeroLength.c in Sources */,
				4834A87314F47B6200438E3D /* CommonDigest.c in Sources */,
				4834A87414F47B6200438E3D /* CommonEC.c in Sources */,

				4834A87514F47B6200438E3D /* CommonHMacClone.c in Sources */,
				4834A87614F47B6200438E3D /* CommonRandom.c in Sources */,
				4834A87714F47B6200438E3D /* CommonRSA.c in Sources */,
				4834A87814F47B6200438E3D /* CryptorPadFailure.c in Sources */,
				4834A87914F47B6200438E3D /* CommonCryptoReset.c in Sources */,
				48C5CB9314FD747500F4472E /* CommonDHtest.c in Sources */,
				4852C24B1505F8CD00676BCC /* CommonCryptoSymCFB.c in Sources */,
				4854BAD7152177CC007B5B08 /* CommonCryptoSymCTR.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXSourcesBuildPhase section */

/* Begin PBXTargetDependency section */
		0511C4630A3785340028BFC3 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 05CE94290A3784D4007C91D6 /* Copy Open Source Docs */;
			targetProxy = 0511C4620A3785340028BFC3 /* PBXContainerItemProxy */;
		};
		4823B10D14C101CC008F689F /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 054BBEBD05F6A97700344873 /* libCommonCryptoMacOSX */;
			targetProxy = 4823B10C14C101CC008F689F /* PBXContainerItemProxy */;
		};
		4834A88414F47CA300438E3D /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 48165CD7125AC5D50015A267 /* libCommonCryptoMacIOS */;
			targetProxy = 4834A88314F47CA300438E3D /* PBXContainerItemProxy */;
		};
		4C58A28D13281C2100A17BAC /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 48165CD7125AC5D50015A267 /* libCommonCryptoMacIOS */;
			targetProxy = 4C58A28C13281C2100A17BAC /* PBXContainerItemProxy */;
		};
		4CA675191332C17900C45A71 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;










			target = 48165DBA125AC5F20015A267 /* libCommonCryptoMacIOSSim */;
			targetProxy = 4CA675181332C17900C45A71 /* PBXContainerItemProxy */;
		};
		5D936FFB110E7FFF006855B0 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;





			target = 054BBEBD05F6A97700344873 /* libCommonCryptoMacOSX */;
			targetProxy = 5D936FFA110E7FFF006855B0 /* PBXContainerItemProxy */;
		};
/* End PBXTargetDependency section */

/* Begin XCBuildConfiguration section */
		05CE94320A37850A007C91D6 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				COPY_PHASE_STRIP = YES;
				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
				PRODUCT_NAME = "Copy Open Source Docs";
				ZERO_LINK = NO;
			};
			name = Release;
		};


















		12F25D8511F7BF8A0036BC8E /* Debug */ = {
			isa = XCBuildConfiguration;

			buildSettings = {









				GCC_PRECOMPILE_PREFIX_HEADER = NO;









				GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
				INFOPLIST_OUTPUT_FORMAT = binary;





				SDKROOT = iphoneos.internal;
				USER_HEADER_SEARCH_PATHS = "/Users/murf/BuildProducts/Build/Products/Debug/usr/local/include /Users/murf/BuildProducts/Build/Products/Debug/usr/include";
			};
















			name = Debug;
		};






		12F25D8611F7BF8A0036BC8E /* Debug */ = {
			isa = XCBuildConfiguration;

			buildSettings = {
				COPY_PHASE_STRIP = YES;
				OTHER_CFLAGS = "";
				OTHER_LDFLAGS = "";
				OTHER_REZFLAGS = "";
				PRODUCT_NAME = world;
				SECTORDER_FLAGS = "";
				WARNING_CFLAGS = (
					"-Wmost",
					"-Wno-four-char-constants",
					"-Wno-unknown-pragmas",
				);
			};
			name = Debug;
		};
		12F25D8711F7BF8A0036BC8E /* Debug */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 486130EF126681290036EA02 /* CC_MacOSXClient_development.xcconfig */;
			buildSettings = {
				EXPORTED_SYMBOLS_FILE = "$(SRCROOT)/Source/Exports/CommonCrypto.exp";
				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
				LIBRARY_SEARCH_PATHS = (
					"$(inherited)",
					"\"$(SYMROOT)\"/**",
					"\"$(SRCROOT)/../../BuildProducts/Products/Products/Debug\"",
					/usr/lib/system,
				);
				OTHER_LDFLAGS = "";
				SDKROOT = "";
			};
			name = Debug;
		};
		12F25D8811F7BF8A0036BC8E /* Debug */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				COPY_PHASE_STRIP = YES;
				GCC_GENERATE_DEBUGGING_SYMBOLS = NO;
				PRODUCT_NAME = "Copy Open Source Docs";
				ZERO_LINK = NO;
			};
			name = Debug;
		};
		48165DB7125AC5D50015A267 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 486130E8126681290036EA02 /* CC_iOSClient_deployment.xcconfig */;
			buildSettings = {
				ARCHS = "$(ARCHS_STANDARD_32_BIT)";
				CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
				EXPORTED_SYMBOLS_FILE = "$(SRCROOT)/Source/Exports/CommonCryptoIOS5.exp";
				GCC_ENABLE_CPP_EXCEPTIONS = YES;
				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
				HEADER_SEARCH_PATHS = "";
				LIBRARY_SEARCH_PATHS = (
					"$(inherited)",
					"\"$(SYMROOT)\"/**",
					"\"$(SDKROOT)/usr/lib/system\"",
				);

				ORDER_FILE = "$(SDKROOT)/AppleInternal/OrderFiles/libcommonCrypto.order";
				OTHER_LDFLAGS = "";
				SDKROOT = iphoneos.internal;
			};
			name = Release;
		};
		48165DB8125AC5D50015A267 /* Debug */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 486130E9126681290036EA02 /* CC_iOSClient_development.xcconfig */;
			buildSettings = {
				ARCHS = "$(ARCHS_STANDARD_32_BIT)";
				CONFIGURATION_BUILD_DIR = "$(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)";
				EXPORTED_SYMBOLS_FILE = "$(SRCROOT)/Source/Exports/CommonCryptoIOS5.exp";
				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
				HEADER_SEARCH_PATHS = "";
				LIBRARY_SEARCH_PATHS = (
					"$(inherited)",
					"\"$(SRCROOT)/../../BuildProducts/Release-iphoneos\"",
					"\"$(SDKROOT)/usr/lib/system\"",
				);
				ORDER_FILE = "$(SDKROOT)/AppleInternal/OrderFiles/libcommonCrypto.order";
				OTHER_LDFLAGS = "";
				SDKROOT = iphoneos.internal;
			};
			name = Debug;
		};
		48165E9A125AC5F20015A267 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 486130EC126681290036EA02 /* CC_iOSSim_deployment.xcconfig */;
			buildSettings = {
				ARCHS = "$(ARCHS_STANDARD_32_BIT)";
				DEAD_CODE_STRIPPING = NO;
				EXPORTED_SYMBOLS_FILE = "$(SRCROOT)/Source/Exports/CommonCryptoIOS5.exp";
				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
				GCC_VERSION = "";
				IPHONEOS_DEPLOYMENT_TARGET = 5.0;
				LIBRARY_SEARCH_PATHS = (




					"\"$(SYMROOT)\"/**",
					"\"$(SDKROOT)/usr/lib/system\"",
					"\"$(DEVELOPER_DIR)/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.0.sdk/usr/lib/system\"",
				);
				OTHER_LDFLAGS = "-lcorecrypto_sim";
				SDKROOT = iphoneos.internal;
				VALID_ARCHS = "armv6 i386 x86_64";
			};
			name = Release;
		};
		48165E9B125AC5F20015A267 /* Debug */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 486130ED126681290036EA02 /* CC_iOSSim_development.xcconfig */;
			buildSettings = {
				ARCHS = "$(ARCHS_STANDARD_32_BIT)";
				DEAD_CODE_STRIPPING = NO;
				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
				GCC_VERSION = "";
				IPHONEOS_DEPLOYMENT_TARGET = 5.0;
				LIBRARY_SEARCH_PATHS = (


					"$(inherited)",
					"\"$(SDKROOT)/usr/lib/system\"",
					"\"$(DEVELOPER_DIR)/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.0.sdk/usr/lib/system\"",
				);
				OTHER_LDFLAGS = "-lcorecrypto_sim";
				SDKROOT = iphoneos.internal;
			};
			name = Debug;
		};
		4823B0E814C10064008F689F /* Release */ = {
			isa = XCBuildConfiguration;

			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = NO;
				ARCHS = "$(ARCHS_STANDARD_64_BIT)";
				CLANG_ENABLE_OBJC_ARC = YES;
				COPY_PHASE_STRIP = YES;

				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
				GCC_C_LANGUAGE_STANDARD = gnu99;
				GCC_ENABLE_OBJC_EXCEPTIONS = YES;
				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
				GCC_WARN_ABOUT_RETURN_TYPE = YES;
				GCC_WARN_UNINITIALIZED_AUTOS = YES;
				GCC_WARN_UNUSED_VARIABLE = YES;
				INSTALL_PATH = /usr/local/tests/CommonCrypto;
				LIBRARY_SEARCH_PATHS = "$(CONFIGURATION_BUILD_DIR)";
				MACOSX_DEPLOYMENT_TARGET = 10.8;
				PRODUCT_NAME = "$(TARGET_NAME)";
				SDKROOT = "";
			};
			name = Release;
		};
		4823B0E914C10064008F689F /* Debug */ = {
			isa = XCBuildConfiguration;

			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = NO;
				ARCHS = "$(ARCHS_STANDARD_64_BIT)";
				CLANG_ENABLE_OBJC_ARC = YES;
				COPY_PHASE_STRIP = NO;
				GCC_C_LANGUAGE_STANDARD = gnu99;
				GCC_DYNAMIC_NO_PIC = NO;
				GCC_ENABLE_OBJC_EXCEPTIONS = YES;

				GCC_OPTIMIZATION_LEVEL = 0;

				GCC_PREPROCESSOR_DEFINITIONS = (
					"DEBUG=1",
					"$(inherited)",
				);
				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
				GCC_WARN_ABOUT_RETURN_TYPE = YES;
				GCC_WARN_UNINITIALIZED_AUTOS = YES;
				GCC_WARN_UNUSED_VARIABLE = YES;
				INSTALL_PATH = /usr/local/tests/CommonCrypto;
				LIBRARY_SEARCH_PATHS = "$(CONFIGURATION_BUILD_DIR)";
				MACOSX_DEPLOYMENT_TARGET = 10.8;
				ONLY_ACTIVE_ARCH = YES;
				PRODUCT_NAME = "$(TARGET_NAME)";
				SDKROOT = "";
			};
			name = Debug;
		};
		4834A87E14F47B6200438E3D /* Release */ = {
			isa = XCBuildConfiguration;

			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = NO;
				ARCHS = "$(ARCHS_STANDARD_32_BIT)";

				CLANG_ENABLE_OBJC_ARC = YES;
				COPY_PHASE_STRIP = YES;
				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
				GCC_C_LANGUAGE_STANDARD = gnu99;
				GCC_ENABLE_OBJC_EXCEPTIONS = YES;

				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
				GCC_WARN_ABOUT_RETURN_TYPE = YES;
				GCC_WARN_UNINITIALIZED_AUTOS = YES;



				GCC_WARN_UNUSED_VARIABLE = YES;

				MACOSX_DEPLOYMENT_TARGET = "";
				PRODUCT_NAME = "CCRegression copy";
				SDKROOT = iphoneos.internal;
			};
			name = Release;
		};
		4834A87F14F47B6200438E3D /* Debug */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = NO;
				ARCHS = "$(ARCHS_STANDARD_32_BIT)";
				CLANG_ENABLE_OBJC_ARC = YES;
				COPY_PHASE_STRIP = NO;
				GCC_C_LANGUAGE_STANDARD = gnu99;
				GCC_DYNAMIC_NO_PIC = NO;
				GCC_ENABLE_OBJC_EXCEPTIONS = YES;
				GCC_OPTIMIZATION_LEVEL = 0;
				GCC_PREPROCESSOR_DEFINITIONS = (
					"DEBUG=1",
					"$(inherited)",
				);
				GCC_SYMBOLS_PRIVATE_EXTERN = NO;
				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
				GCC_WARN_ABOUT_RETURN_TYPE = YES;
				GCC_WARN_UNINITIALIZED_AUTOS = YES;
				GCC_WARN_UNUSED_VARIABLE = YES;
				MACOSX_DEPLOYMENT_TARGET = "";
				ONLY_ACTIVE_ARCH = YES;

				PRODUCT_NAME = "CCRegression copy";
				SDKROOT = iphoneos.internal;
			};
			name = Debug;
		};
		4C99FCB81326E14F0040AD38 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				PRODUCT_NAME = "$(TARGET_NAME)";
			};
			name = Release;
		};
		4C99FCB91326E14F0040AD38 /* Debug */ = {
			isa = XCBuildConfiguration;

			buildSettings = {
				PRODUCT_NAME = "$(TARGET_NAME)";
			};
			name = Debug;
		};
		4CA675161332C16C00C45A71 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 486130EC126681290036EA02 /* CC_iOSSim_deployment.xcconfig */;
			buildSettings = {
				PRODUCT_NAME = "$(TARGET_NAME)";
			};
			name = Release;
		};
		4CA675171332C16C00C45A71 /* Debug */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 486130ED126681290036EA02 /* CC_iOSSim_development.xcconfig */;
			buildSettings = {
				PRODUCT_NAME = "$(TARGET_NAME)";

			};
			name = Debug;
		};
		C27AD07F0987FCDA001272E0 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 486130EE126681290036EA02 /* CC_MacOSXClient_deployment.xcconfig */;
			buildSettings = {
				EXPORTED_SYMBOLS_FILE = "$(SRCROOT)/Source/Exports/CommonCrypto.exp";
				GCC_VERSION = com.apple.compilers.llvm.clang.1_0;
				LIBRARY_SEARCH_PATHS = (
					"$(inherited)",
					"\"$(SYMROOT)\"/**",
					"\"$(SRCROOT)/../../BuildProducts/Products/Products/Debug\"",
					/usr/lib/system,
				);
				OTHER_LDFLAGS = "";
				SDKROOT = "";
			};
			name = Release;
		};
		C27AD08F0987FCDA001272E0 /* Release */ = {
			isa = XCBuildConfiguration;

			buildSettings = {
				COPY_PHASE_STRIP = YES;
				OTHER_CFLAGS = "";
				OTHER_LDFLAGS = "";
				OTHER_REZFLAGS = "";
				PRODUCT_NAME = world;
				SECTORDER_FLAGS = "";
				WARNING_CFLAGS = (
					"-Wmost",
					"-Wno-four-char-constants",
					"-Wno-unknown-pragmas",
				);
			};
			name = Release;
		};
		C27AD0930987FCDA001272E0 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
				GCC_PRECOMPILE_PREFIX_HEADER = NO;
				GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
				INFOPLIST_OUTPUT_FORMAT = binary;
				SDKROOT = iphoneos.internal;
				USER_HEADER_SEARCH_PATHS = "/Users/murf/BuildProducts/Build/Products/Debug/usr/local/include /Users/murf/BuildProducts/Build/Products/Debug/usr/include";
			};
			name = Release;
		};
/* End XCBuildConfiguration section */

/* Begin XCConfigurationList section */
		05CE94300A37850A007C91D6 /* Build configuration list for PBXAggregateTarget "Copy Open Source Docs" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				05CE94320A37850A007C91D6 /* Release */,
				12F25D8811F7BF8A0036BC8E /* Debug */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		48165DB6125AC5D50015A267 /* Build configuration list for PBXNativeTarget "libCommonCryptoMacIOS" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				48165DB7125AC5D50015A267 /* Release */,
				48165DB8125AC5D50015A267 /* Debug */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		48165E99125AC5F20015A267 /* Build configuration list for PBXNativeTarget "libCommonCryptoMacIOSSim" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				48165E9A125AC5F20015A267 /* Release */,
				48165E9B125AC5F20015A267 /* Debug */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		4823B0E714C10064008F689F /* Build configuration list for PBXNativeTarget "CCRegression" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				4823B0E814C10064008F689F /* Release */,
				4823B0E914C10064008F689F /* Debug */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		4834A87D14F47B6200438E3D /* Build configuration list for PBXNativeTarget "CCRegressionIos" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				4834A87E14F47B6200438E3D /* Release */,
				4834A87F14F47B6200438E3D /* Debug */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		4C99FCB71326E14F0040AD38 /* Build configuration list for PBXAggregateTarget "commonCryptoMacIOS" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				4C99FCB81326E14F0040AD38 /* Release */,
				4C99FCB91326E14F0040AD38 /* Debug */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};









		4CA675151332C16C00C45A71 /* Build configuration list for PBXAggregateTarget "CommonCrypto_Sim" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				4CA675161332C16C00C45A71 /* Release */,
				4CA675171332C16C00C45A71 /* Debug */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		C27AD07D0987FCDA001272E0 /* Build configuration list for PBXNativeTarget "libCommonCryptoMacOSX" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				C27AD07F0987FCDA001272E0 /* Release */,
				12F25D8711F7BF8A0036BC8E /* Debug */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		C27AD08D0987FCDA001272E0 /* Build configuration list for PBXAggregateTarget "world" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				C27AD08F0987FCDA001272E0 /* Release */,
				12F25D8611F7BF8A0036BC8E /* Debug */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		C27AD0910987FCDA001272E0 /* Build configuration list for PBXProject "CommonCrypto" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				C27AD0930987FCDA001272E0 /* Release */,
				12F25D8511F7BF8A0036BC8E /* Debug */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
/* End XCConfigurationList section */
	};
	rootObject = 054BBEA605F6A8DE00344873 /* Project object */;
}

Added CommonCrypto.xcodeproj/project.xcworkspace/contents.xcworkspacedata.















>
>
>
>
>
>
>
1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
   version = "1.0">
   <FileRef
      location = "self:CommonCrypto.xcodeproj">
   </FileRef>
</Workspace>

Added CommonCrypto.xcodeproj/project.xcworkspace/xcuserdata/jimmur.xcuserdatad/UserInterfaceState.xcuserstate.

cannot compute difference between binary files

Added CommonCrypto.xcodeproj/project.xcworkspace/xcuserdata/stripes.xcuserdatad/UserInterfaceState.xcuserstate.

more than 10,000 changes

Added CommonCrypto.xcodeproj/project.xcworkspace/xcuserdata/stripes.xcuserdatad/WorkspaceSettings.xcsettings.

















>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>IDEWorkspaceUserSettings_BuildLocationStyle</key>
	<integer>2</integer>
</dict>
</plist>

Added CommonCrypto.xcodeproj/xcshareddata/xcschemes/CCRegression.xcscheme.











































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4823B0DF14C10064008F689F"
               BuildableName = "CCRegression"
               BlueprintName = "CCRegression"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
      <MacroExpansion>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4823B0DF14C10064008F689F"
            BuildableName = "CCRegression"
            BlueprintName = "CCRegression"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </MacroExpansion>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4823B0DF14C10064008F689F"
            BuildableName = "CCRegression"
            BlueprintName = "CCRegression"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4823B0DF14C10064008F689F"
            BuildableName = "CCRegression"
            BlueprintName = "CCRegression"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcshareddata/xcschemes/CCRegressionIos.xcscheme.











































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4834A85414F47B6200438E3D"
               BuildableName = "CCRegression copy"
               BlueprintName = "CCRegressionIos"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
      <MacroExpansion>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4834A85414F47B6200438E3D"
            BuildableName = "CCRegression copy"
            BlueprintName = "CCRegressionIos"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </MacroExpansion>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4834A85414F47B6200438E3D"
            BuildableName = "CCRegression copy"
            BlueprintName = "CCRegressionIos"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4834A85414F47B6200438E3D"
            BuildableName = "CCRegression copy"
            BlueprintName = "CCRegressionIos"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcshareddata/xcschemes/Copy Open Source Docs.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "05CE94290A3784D4007C91D6"
               BuildableName = "Copy Open Source Docs"
               BlueprintName = "Copy Open Source Docs"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcshareddata/xcschemes/libCommonCryptoMacIOS.xcscheme.



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48165CD7125AC5D50015A267"
               BuildableName = "libcommonCrypto.dylib"
               BlueprintName = "libCommonCryptoMacIOS"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcshareddata/xcschemes/libCommonCryptoMacIOSSim.xcscheme.



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48165DBA125AC5F20015A267"
               BuildableName = "libcommonCrypto_sim.dylib"
               BlueprintName = "libCommonCryptoMacIOSSim"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcshareddata/xcschemes/libCommonCryptoMacOSX.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "054BBEBD05F6A97700344873"
               BuildableName = "libcommonCrypto.dylib"
               BlueprintName = "libCommonCryptoMacOSX"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcshareddata/xcschemes/world.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "054BBEB705F6A93300344873"
               BuildableName = "world"
               BlueprintName = "world"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist.











>
>
>
>
>
1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
   type = "1"
   version = "1.0">
</Bucket>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/CCRegression.xcscheme.











































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4823B0DF14C10064008F689F"
               BuildableName = "CCRegression"
               BlueprintName = "CCRegression"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
      <MacroExpansion>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4823B0DF14C10064008F689F"
            BuildableName = "CCRegression"
            BlueprintName = "CCRegression"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </MacroExpansion>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4823B0DF14C10064008F689F"
            BuildableName = "CCRegression"
            BlueprintName = "CCRegression"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4823B0DF14C10064008F689F"
            BuildableName = "CCRegression"
            BlueprintName = "CCRegression"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/CCRegressionIos.xcscheme.











































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4834A85414F47B6200438E3D"
               BuildableName = "CCRegression copy"
               BlueprintName = "CCRegressionIos"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
      <MacroExpansion>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4834A85414F47B6200438E3D"
            BuildableName = "CCRegression copy"
            BlueprintName = "CCRegressionIos"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </MacroExpansion>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4834A85414F47B6200438E3D"
            BuildableName = "CCRegression copy"
            BlueprintName = "CCRegressionIos"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4834A85414F47B6200438E3D"
            BuildableName = "CCRegression copy"
            BlueprintName = "CCRegressionIos"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/CommonCrypto_Sim.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4CA675141332C16C00C45A71"
               BuildableName = "CommonCrypto_Sim"
               BlueprintName = "CommonCrypto_Sim"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/Copy Open Source Docs.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "05CE94290A3784D4007C91D6"
               BuildableName = "Copy Open Source Docs"
               BlueprintName = "Copy Open Source Docs"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/cc_fips_dbrg_test.xcscheme.















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.7">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4C58A2511326F26000A17BAC"
               BuildableName = "cc_fips_drgb_test"
               BlueprintName = "cc_fips_dbrg_test"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
      <MacroExpansion>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4C58A2511326F26000A17BAC"
            BuildableName = "cc_fips_drgb_test"
            BlueprintName = "cc_fips_dbrg_test"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </MacroExpansion>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4C58A2511326F26000A17BAC"
            BuildableName = "cc_fips_drgb_test"
            BlueprintName = "cc_fips_dbrg_test"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4C58A2511326F26000A17BAC"
            BuildableName = "cc_fips_drgb_test"
            BlueprintName = "cc_fips_dbrg_test"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
   <InstallAction
      buildConfiguration = "Development">
   </InstallAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/cc_fips_test.xcscheme.















































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.7">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4C3CAC17132066C700AA3D18"
               BuildableName = "cc_fips_test"
               BlueprintName = "cc_fips_test"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
      <MacroExpansion>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4C3CAC17132066C700AA3D18"
            BuildableName = "cc_fips_test"
            BlueprintName = "cc_fips_test"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </MacroExpansion>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4C3CAC17132066C700AA3D18"
            BuildableName = "cc_fips_test"
            BlueprintName = "cc_fips_test"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4C3CAC17132066C700AA3D18"
            BuildableName = "cc_fips_test"
            BlueprintName = "cc_fips_test"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
   <InstallAction
      buildConfiguration = "Development">
   </InstallAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/cc_ios_tommath.xcscheme.

























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.7">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48CCEF5612FA879900D6DAE9"
               BuildableName = "libcc_tommath.a"
               BlueprintName = "cc_ios_tommath"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
   <InstallAction
      buildConfiguration = "Development">
   </InstallAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/cc_macosx_tommath.xcscheme.

























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.7">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48FD68BF1354BCB900F55B8B"
               BuildableName = "libcc_tommath.a"
               BlueprintName = "cc_macosx_tommath"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
   <InstallAction
      buildConfiguration = "Development">
   </InstallAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/commonCryptoMacIOS.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4C99FCB61326E14F0040AD38"
               BuildableName = "commonCryptoMacIOS"
               BlueprintName = "commonCryptoMacIOS"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/commonCryptoMacIOSKext.xcscheme.

























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.7">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48166063125AC64C0015A267"
               BuildableName = "libiOScommonCrypto.dylib"
               BlueprintName = "commonCryptoMacIOSKext"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
   <InstallAction
      buildConfiguration = "Development">
   </InstallAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/commonCryptoMacOSXKext.xcscheme.

























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.7">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "EEBECDF8125E691800034935"
               BuildableName = "commonCryptoMacOSXKext.kext"
               BlueprintName = "commonCryptoMacOSXKext"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
   <InstallAction
      buildConfiguration = "Development">
   </InstallAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/libCommonCryptoMacIOS.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48165CD7125AC5D50015A267"
               BuildableName = "libcommonCrypto.dylib"
               BlueprintName = "libCommonCryptoMacIOS"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/libCommonCryptoMacIOSSim.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48165DBA125AC5F20015A267"
               BuildableName = "libcommonCrypto_sim.dylib"
               BlueprintName = "libCommonCryptoMacIOSSim"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/libCommonCryptoMacOSS.xcscheme.

























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.7">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48165E9D125AC6100015A267"
               BuildableName = "liboSScommonCrypto.dylib"
               BlueprintName = "libCommonCryptoMacOSS"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
   <InstallAction
      buildConfiguration = "Development">
   </InstallAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/libCommonCryptoMacOSX.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "054BBEBD05F6A97700344873"
               BuildableName = "libcommonCrypto.dylib"
               BlueprintName = "libCommonCryptoMacOSX"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/world.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "054BBEB705F6A93300344873"
               BuildableName = "world"
               BlueprintName = "world"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug"
      ignoresPersistentStateOnLaunch = "NO"
      debugDocumentVersioning = "YES"
      allowLocationSimulation = "YES">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release"
      debugDocumentVersioning = "YES">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/jimmur.xcuserdatad/xcschemes/xcschememanagement.plist.

























































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>SchemeUserState</key>
	<dict>
		<key>CCRegression.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>11</integer>
		</dict>
		<key>CCRegressionIos.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>4</integer>
		</dict>
		<key>CommonCrypto_Sim.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>13</integer>
		</dict>
		<key>Copy Open Source Docs.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>21</integer>
		</dict>
		<key>cc_fips_dbrg_test.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>30</integer>
		</dict>
		<key>cc_fips_test.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>35</integer>
		</dict>
		<key>cc_ios_tommath.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>29</integer>
		</dict>
		<key>cc_macosx_tommath.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>31</integer>
		</dict>
		<key>commonCryptoMacIOS.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>8</integer>
		</dict>
		<key>commonCryptoMacIOSKext.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>33</integer>
		</dict>
		<key>commonCryptoMacOSXKext.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>32</integer>
		</dict>
		<key>libCommonCryptoMacIOS.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>7</integer>
		</dict>
		<key>libCommonCryptoMacIOSSim.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>16</integer>
		</dict>
		<key>libCommonCryptoMacOSS.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>34</integer>
		</dict>
		<key>libCommonCryptoMacOSX.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>2</integer>
		</dict>
		<key>world.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>20</integer>
		</dict>
	</dict>
	<key>SuppressBuildableAutocreation</key>
	<dict>
		<key>054BBEB705F6A93300344873</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>054BBEBD05F6A97700344873</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>05CE94290A3784D4007C91D6</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48165CD7125AC5D50015A267</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48165DBA125AC5F20015A267</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48165E9D125AC6100015A267</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48166063125AC64C0015A267</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>4823B0DF14C10064008F689F</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>4834A85414F47B6200438E3D</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48CCEF5612FA879900D6DAE9</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48FD68BF1354BCB900F55B8B</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>4C3CAC17132066C700AA3D18</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>4C58A2511326F26000A17BAC</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>4C99FCB61326E14F0040AD38</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>4CA675141332C16C00C45A71</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>EEBECDF8125E691800034935</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
	</dict>
</dict>
</plist>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist.











>
>
>
>
>
1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
   type = "1"
   version = "1.0">
</Bucket>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/CBCTest.xcscheme.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "128881641203673C0050B2E9"
               BuildableName = "CBCTest"
               BlueprintName = "CBCTest"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "128881641203673C0050B2E9"
            BuildableName = "CBCTest"
            BlueprintName = "CBCTest"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "128881641203673C0050B2E9"
            BuildableName = "CBCTest"
            BlueprintName = "CBCTest"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/Copy Open Source Docs.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "05CE94290A3784D4007C91D6"
               BuildableName = "Copy Open Source Docs"
               BlueprintName = "Copy Open Source Docs"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/Unit Test World.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "5DC876F710FFB6BC0012A390"
               BuildableName = "Unit Test World"
               BlueprintName = "Unit Test World"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/XTStest.xcscheme.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "125B795011FF923D008C1AD3"
               BuildableName = "XTStest"
               BlueprintName = "XTStest"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "125B795011FF923D008C1AD3"
            BuildableName = "XTStest"
            BlueprintName = "XTStest"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "125B795011FF923D008C1AD3"
            BuildableName = "XTStest"
            BlueprintName = "XTStest"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/cc_fips_dbrg_test.xcscheme.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4C58A2511326F26000A17BAC"
               BuildableName = "cc_fips_drgb_test"
               BlueprintName = "cc_fips_dbrg_test"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4C58A2511326F26000A17BAC"
            BuildableName = "cc_fips_drgb_test"
            BlueprintName = "cc_fips_dbrg_test"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4C58A2511326F26000A17BAC"
            BuildableName = "cc_fips_drgb_test"
            BlueprintName = "cc_fips_dbrg_test"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/cc_fips_test.xcscheme.

























































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4C3CAC17132066C700AA3D18"
               BuildableName = "cc_fips_test"
               BlueprintName = "cc_fips_test"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4C3CAC17132066C700AA3D18"
            BuildableName = "cc_fips_test"
            BlueprintName = "cc_fips_test"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
      <BuildableProductRunnable>
         <BuildableReference
            BuildableIdentifier = "primary"
            BlueprintIdentifier = "4C3CAC17132066C700AA3D18"
            BuildableName = "cc_fips_test"
            BlueprintName = "cc_fips_test"
            ReferencedContainer = "container:CommonCrypto.xcodeproj">
         </BuildableReference>
      </BuildableProductRunnable>
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/commonCryptoMacIOS.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "4C99FCB61326E14F0040AD38"
               BuildableName = "commonCryptoMacIOS"
               BlueprintName = "commonCryptoMacIOS"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/commonCryptoMacIOSKext.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48166063125AC64C0015A267"
               BuildableName = "libiOScommonCrypto.dylib"
               BlueprintName = "commonCryptoMacIOSKext"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/commonCryptoMacIOSSim 2.xcscheme.





















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Debug">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Debug">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Debug">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/commonCryptoMacIOSSim.xcscheme.









































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48165DBA125AC5F20015A267"
               BuildableName = "libcommonCrypto_sim.dylib"
               BlueprintName = "libCommonCryptoMacIOSSim"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
         <TestableReference
            skipped = "NO">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48547185125B9483008158B1"
               BuildableName = "CommonCryptoUnitTest.octest"
               BlueprintName = "CommonCryptoUnitTestIOSSim"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </TestableReference>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/commonCryptoMacOSS.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48165E9D125AC6100015A267"
               BuildableName = "liboSScommonCrypto.dylib"
               BlueprintName = "commonCryptoMacOSS"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/commonCryptoMacOSX.xcscheme.









































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "054BBEBD05F6A97700344873"
               BuildableName = "libcommonCrypto.dylib"
               BlueprintName = "commonCryptoMacOSX"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
         <TestableReference
            skipped = "NO">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "5D735E4710FCDC04001AAD1E"
               BuildableName = "CommonCryptoUnitTest.octest"
               BlueprintName = "CommonCryptoUnitTestMacOSX"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </TestableReference>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/commonCryptoMacOSXKext.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "EEBECDF8125E691800034935"
               BuildableName = "commonCryptoMacOSXKext.kext"
               BlueprintName = "commonCryptoMacOSXKext"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/libCommonCryptoMacIOS.xcscheme.









































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48165CD7125AC5D50015A267"
               BuildableName = "libcommonCrypto.dylib"
               BlueprintName = "libCommonCryptoMacIOS"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
         <TestableReference
            skipped = "NO">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48547171125B9465008158B1"
               BuildableName = "CommonCryptoUnitTest.octest"
               BlueprintName = "CommonCryptoUnitTestIOS"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </TestableReference>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/tommath.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "48CCEF5612FA879900D6DAE9"
               BuildableName = "libtommath.a"
               BlueprintName = "tommath"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/world.xcscheme.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
   version = "1.3">
   <BuildAction
      parallelizeBuildables = "YES"
      buildImplicitDependencies = "YES">
      <BuildActionEntries>
         <BuildActionEntry
            buildForTesting = "YES"
            buildForRunning = "YES"
            buildForProfiling = "YES"
            buildForArchiving = "YES"
            buildForAnalyzing = "YES">
            <BuildableReference
               BuildableIdentifier = "primary"
               BlueprintIdentifier = "054BBEB705F6A93300344873"
               BuildableName = "world"
               BlueprintName = "world"
               ReferencedContainer = "container:CommonCrypto.xcodeproj">
            </BuildableReference>
         </BuildActionEntry>
      </BuildActionEntries>
   </BuildAction>
   <TestAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      shouldUseLaunchSchemeArgsEnv = "YES"
      buildConfiguration = "Development">
      <Testables>
      </Testables>
   </TestAction>
   <LaunchAction
      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.GDB"
      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.GDB"
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      launchStyle = "0"
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Development">
      <AdditionalOptions>
      </AdditionalOptions>
   </LaunchAction>
   <ProfileAction
      displayScaleIsEnabled = "NO"
      displayScale = "1.00"
      shouldUseLaunchSchemeArgsEnv = "YES"
      savedToolIdentifier = ""
      useCustomWorkingDirectory = "NO"
      buildConfiguration = "Release">
   </ProfileAction>
   <AnalyzeAction
      buildConfiguration = "Development">
   </AnalyzeAction>
   <ArchiveAction
      buildConfiguration = "Release"
      revealArchiveInOrganizer = "YES">
   </ArchiveAction>
</Scheme>

Added CommonCrypto.xcodeproj/xcuserdata/stripes.xcuserdatad/xcschemes/xcschememanagement.plist.























































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>SchemeUserState</key>
	<dict>
		<key>CBCTest.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>12</integer>
		</dict>
		<key>Copy Open Source Docs.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>2</integer>
		</dict>
		<key>Unit Test World.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>8</integer>
		</dict>
		<key>XTStest.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>13</integer>
		</dict>
		<key>cc_fips_dbrg_test.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>5</integer>
		</dict>
		<key>cc_fips_test.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>1</integer>
		</dict>
		<key>commonCryptoMacIOS.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>9</integer>
		</dict>
		<key>commonCryptoMacIOSKext.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>14</integer>
		</dict>
		<key>commonCryptoMacIOSSim 2.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>15</integer>
		</dict>
		<key>commonCryptoMacIOSSim.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>11</integer>
		</dict>
		<key>commonCryptoMacOSS.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>4</integer>
		</dict>
		<key>commonCryptoMacOSX.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>7</integer>
		</dict>
		<key>commonCryptoMacOSXKext.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>6</integer>
		</dict>
		<key>libCommonCryptoMacIOS.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>0</integer>
		</dict>
		<key>tommath.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>3</integer>
		</dict>
		<key>world.xcscheme</key>
		<dict>
			<key>orderHint</key>
			<integer>10</integer>
		</dict>
	</dict>
	<key>SuppressBuildableAutocreation</key>
	<dict>
		<key>054BBEB705F6A93300344873</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>054BBEBD05F6A97700344873</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>05CE94290A3784D4007C91D6</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>125B795011FF923D008C1AD3</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>128881641203673C0050B2E9</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48165CD7125AC5D50015A267</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48165DBA125AC5F20015A267</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48165E9D125AC6100015A267</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48166063125AC64C0015A267</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48547171125B9465008158B1</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48547185125B9483008158B1</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>48CCEF5612FA879900D6DAE9</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>4C3CAC17132066C700AA3D18</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>4C58A2511326F26000A17BAC</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>4C99FCB61326E14F0040AD38</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>4CA675141332C16C00C45A71</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>5D735E4710FCDC04001AAD1E</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>5DC876F710FFB6BC0012A390</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
		<key>EEBECDF8125E691800034935</key>
		<dict>
			<key>primary</key>
			<true/>
		</dict>
	</dict>
</dict>
</plist>

Added CommonCrypto/CommonCrypto.h.





































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* 
 * Copyright (c) 2006-2012 Apple, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef __COMMONCRYPTO_PUBLIC__
#define __COMMONCRYPTO_PUBLIC__

#include <CommonCrypto/CommonCryptor.h>
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#include <CommonCrypto/CommonKeyDerivation.h>
#include <CommonCrypto/CommonSymmetricKeywrap.h>

#endif /* __COMMONCRYPTO_PUBLIC__ */

Changes to CommonCrypto/CommonCryptor.h.

1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at

|







1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2006-2010 Apple, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

70
71
72
73
74
75
76
77
78
79
80

81

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116

117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141

142
143
144
145
146
147
148
149

150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197


198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423


424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453

454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488

489
490
491
492
493
494
495
496
497

498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548










































































































































549
550
551
552
553
554
555
556
557
558
559

560
561
562
563
564
565
566
567
568
569
570
571




572
573
574
575
576
577
578
579
580
581
582

583
584
585
586
587
588

589
590


591
592
593
594
595
596

597
598
599
600
601
602
603
604

605
606
607
608
609
610
611


612
613

614
615
616
617
618
619
620
621
622
623


624
625
626
627
628
629
630
631
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*!
	@header		CommonCryptor.h
	@abstract	Generic interface for symmetric encryption. 
	
    @discussion This interface provides access to a number of symmetric 
                encryption algorithms. Symmetric encryption algorithms come 
                in two "flavors" -  block ciphers, and stream ciphers. Block
                ciphers process data (while both encrypting and decrypting) 
                in discrete chunks of  data called blocks; stream ciphers 
                operate on arbitrary sized data. 
				
				The object declared in this interface, CCCryptor, provides
				access to both block ciphers and stream ciphers with the same
				API; however some options are available for block ciphers that
				do not apply to stream ciphers. 
				
				The general operation of a CCCryptor is: initialize it
				with raw key data and other optional fields with CCCryptorCreate(); 
				process input data via one or more calls to CCCryptorUpdate(), 
				each of which may result in output data being written to 
				caller-supplied memory; and obtain possible remaining output data 
				with CCCryptorFinal(). The CCCryptor is disposed of via 
				CCCryptorRelease(), or it can be reused (with the same key data 
				as provided to CCCryptorCreate()) by calling CCCryptorReset(). 

				
				CCCryptors can be dynamically allocated by this module, or 
				their memory can be allocated by the caller. See discussion for
				CCCryptorCreate() and CCCryptorCreateFromData() for information 
				on CCCryptor allocation.
				
				One option for block ciphers is padding, as defined in PKCS7;
				when padding is enabled, the total amount of data encrypted
				does not have to be an even multiple of the block size, and 
				the actual length of plaintext is calculated during decryption. 
				
				Another option for block ciphers is Cipher Block Chaining, known
				as CBC mode. When using CBC mode, an Initialization Vector (IV)
				is provided along with the key when starting an encrypt
				or decrypt operation. If CBC mode is selected and no IV is 
				provided, an IV of all zeroes will be used. 
				
				CCCryptor also implements block bufferring, so that individual
				calls to CCCryptorUpdate() do not have to provide data whose length
				is aligned to the block size. (If padding is disabled, encrypting
				with block ciphers does require that the *total* length of data
				input to CCCryptorUpdate() call(s) be aligned to the block size.)

	
				A given CCCryptor can only be used by one thread at a time;
				multiple threads can use safely different CCCryptors at the
				same time. 				
*/

#ifndef	_CC_COMMON_CRYPTOR_
#define	_CC_COMMON_CRYPTOR_

#include <stdbool.h>
#include <stdint.h>

#include <stddef.h>

#include <Availability.h>

#ifdef __cplusplus
extern "C" {
#endif

/*!
	@typedef	CCCryptorRef
	@abstract	Opaque reference to a CCCryptor object.
 */
typedef struct _CCCryptor *CCCryptorRef;

/*!
	@enum		CCCryptorStatus
	@abstract	Return values from CommonCryptor operations.
	
	@constant	kCCSuccess			Operation completed normally.
	@constant	kCCParamError		Illegal parameter value.
    @constant   kCCBufferTooSmall   Insufficent buffer provided for specified 
                                    operation.
	@constant	kCCMemoryFailure	Memory allocation failure. 
	@constant	kCCAlignmentError	Input size was not aligned properly. 
    @constant   kCCDecodeError      Input data did not decode or decrypt 
                                    properly.
    @constant   kCCUnimplemented    Function not implemented for the current 
                                    algorithm.
 */
enum {
	kCCSuccess			= 0,
	kCCParamError		= -4300,
	kCCBufferTooSmall	= -4301,
	kCCMemoryFailure	= -4302,
	kCCAlignmentError	= -4303,
	kCCDecodeError		= -4304,
	kCCUnimplemented	= -4305

};
typedef int32_t CCCryptorStatus;

/*!
	@enum		CCOperation
	@abstract	Operations that an CCCryptor can perform.
	
	@constant	kCCEncrypt	Symmetric encryption.
	@constant	kCCDecrypt	Symmetric decryption.
*/
enum {
	kCCEncrypt = 0,	
	kCCDecrypt,		
};
typedef uint32_t CCOperation;

/*!
	@enum		CCAlgorithm
	@abstract	Encryption algorithms implemented by this module.
	
	@constant	kCCAlgorithmAES128	Advanced Encryption Standard, 128-bit block
	@constant	kCCAlgorithmDES		Data Encryption Standard
	@constant	kCCAlgorithm3DES	Triple-DES, three key, EDE configuration
	@constant	kCCAlgorithmCAST	CAST
	@constant	kCCAlgorithmRC4		RC4 stream cipher

*/
enum {
	kCCAlgorithmAES128 = 0,
	kCCAlgorithmDES,		
	kCCAlgorithm3DES,		
	kCCAlgorithmCAST,		
	kCCAlgorithmRC4,
	kCCAlgorithmRC2		

};
typedef uint32_t CCAlgorithm;

/*!
	@enum		CCOptions
	@abstract	Options flags, passed to CCCryptorCreate().
	
	@constant	kCCOptionPKCS7Padding	Perform PKCS7 padding. 
	@constant	kCCOptionECBMode		Electronic Code Book Mode. 
										Default is CBC.
*/
enum {
	/* options for block ciphers */
	kCCOptionPKCS7Padding	= 0x0001,
	kCCOptionECBMode		= 0x0002
	/* stream ciphers currently have no options */
};
typedef uint32_t CCOptions;

/*!
	@enum			Key sizes
	
	@discussion		Key sizes, in bytes, for supported algorithms. 
	
	@constant kCCKeySizeAES128		128 bit AES key size.
	@constant kCCKeySizeAES192		192 bit AES key size.
	@constant kCCKeySizeAES256		256 bit AES key size.
	@constant kCCKeySizeDES			DES key size.
	@constant kCCKeySize3DES		Triple DES key size.
	@constant kCCKeySizeMinCAST		CAST minimum key size.
	@constant kCCKeySizeMaxCAST		CAST maximum key size.
	@constant kCCKeySizeMinRC4		RC4 minimum key size.
	@constant kCCKeySizeMaxRC4		RC4 maximum key size.
	
	@discussion		DES and TripleDES have fixed key sizes.
					AES has three discrete key sizes.
					CAST and RC4 have variable key sizes.
*/
enum {
	kCCKeySizeAES128	= 16,
	kCCKeySizeAES192	= 24,
	kCCKeySizeAES256	= 32,
	kCCKeySizeDES		= 8,
	kCCKeySize3DES		= 24,
	kCCKeySizeMinCAST	= 5,
	kCCKeySizeMaxCAST	= 16,
	kCCKeySizeMinRC4	= 1,
	kCCKeySizeMaxRC4	= 512,


	kCCKeySizeMinRC2	= 1,
	kCCKeySizeMaxRC2	= 128
};

/*!
	@enum			Block sizes
	
	@discussion		Block sizes, in bytes, for supported algorithms. 
	
	@constant kCCBlockSizeAES128	AES block size (currently, only 128-bit 
									blocks are supported).
	@constant kCCBlockSizeDES		DES block size.
	@constant kCCBlockSize3DES		Triple DES block size.
	@constant kCCBlockSizeCAST		CAST block size.
*/
enum {
	/* AES */
	kCCBlockSizeAES128	= 16,
	/* DES */
	kCCBlockSizeDES		= 8,
	/* 3DES */
	kCCBlockSize3DES	= 8,
	/* CAST */
	kCCBlockSizeCAST	= 8,
	kCCBlockSizeRC2		= 8,

};

/*!
	@enum		Minimum context sizes
	@discussion	Minimum context sizes, for caller-allocated CCCryptorRefs.
				To minimize dynamic allocation memory, a caller can create 
				a CCCryptorRef by passing caller-supplied memory to the 
				CCCryptorCreateFromData() function.
	
				These constants define the minimum amount of memory, in 
				bytes, needed for CCCryptorRefs for each supported algorithm. 
	
				Note: these constants are valid for the current version of 
				this library; they may change in subsequent releases, so 
				applications wishing to allocate their own memory for use 
				in creating CCCryptorRefs must be prepared to deal with 
				a kCCBufferTooSmall return from CCCryptorCreateFromData().
				See discussion for the CCCryptorCreateFromData() function.
	
    @constant kCCContextSizeAES128 - Minimum context size for kCCAlgorithmAES128.
    @constant kCCContextSizeDES    - Minimum context size for kCCAlgorithmDES.
    @constant kCCContextSize3DES   - Minimum context size for kCCAlgorithm3DES.
    @constant kCCContextSizeCAST   - Minimum context size for kCCAlgorithmCAST.
    @constant kCCContextSizeRC4    - Minimum context size for kCCAlgorithmRC4.
*/
    
enum {
    kCCContextSizeGENERIC   = 4096,
    kCCContextSizeAES128    = 4096,
    kCCContextSizeDES       = 4096,
    kCCContextSize3DES      = 4096,
    kCCContextSizeCAST      = 4096,
    kCCContextSizeRC4       = 4096
};



/*!
	@function	CCCryptorCreate
	@abstract	Create a cryptographic context. 
	
    @param      op          Defines the basic operation: kCCEncrypt or 
                            kCCDecrypt.
	
	@param		alg			Defines the algorithm.
	
	@param		options		A word of flags defining options. See discussion
							for the CCOptions type.
							
	@param		key			Raw key material, length keyLength bytes. 
	
	@param		keyLength	Length of key material. Must be appropriate 
							for	the selected operation and algorithm. Some 
							algorithms  provide for varying key lengths.

	@param		iv			Initialization vector, optional. Used by 
							block ciphers when Cipher Block Chaining (CBC) 
							mode is enabled. If present, must be the same
							length as the selected algorithm's block size. 
							If CBC mode is selected (by the absence of the 
							kCCOptionECBMode bit in the options flags) and no 
							IV is present, a NULL (all zeroes) IV will be used. 
							This parameter is ignored if ECB mode is used or
							if a stream cipher algorithm is selected. 

	@param		cryptorRef	A (required) pointer to the returned CCCryptorRef. 

	@result		Possible error returns are kCCParamError and kCCMemoryFailure.
*/
CCCryptorStatus CCCryptorCreate(
	CCOperation op,             /* kCCEncrypt, etc. */
	CCAlgorithm alg,            /* kCCAlgorithmDES, etc. */
	CCOptions options,          /* kCCOptionPKCS7Padding, etc. */
	const void *key,            /* raw key material */
	size_t keyLength,	
	const void *iv,             /* optional initialization vector */
    CCCryptorRef *cryptorRef)  /* RETURNED */
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

/*!
	@function	CCCryptorCreateFromData
	@abstract	Create a cryptographic context using caller-supplied memory. 
	
    @param      op          Defines the basic operation: kCCEncrypt or 
                            kCCDecrypt.
	
	@param		alg			Defines the algorithm.
	
	@param		options		A word of flags defining options. See discussion
							for the CCOptions type.
							
	@param		key			Raw key material, length keyLength bytes. 
	
	@param		keyLength	Length of key material. Must be appropriate 
							for	the selected operation and algorithm. Some 
							algorithms  provide for varying key lengths.

	@param		iv			Initialization vector, optional. Used by 
							block ciphers when Cipher Block Chaining (CBC) 
							mode is enabled. If present, must be the same
							length as the selected algorithm's block size. 
							If CBC mode is selected (by the absence of the 
							kCCOptionECBMode bit in the options flags) and no 
							IV is present, a NULL (all zeroes) IV will be used. 
							This parameter is ignored if ECB mode is used or
							if a stream cipher algorithm is selected. 

	@param		data		A pointer to caller-supplied memory from which the 
							CCCryptorRef will be created. 
							
	@param		dataLength	The size of the caller-supplied memory in bytes. 
	
	@param		cryptorRef	A (required) pointer to the returned CCCryptorRef. 
	
	@param		dataUsed	Optional. If present, the actual number of bytes of 
							the caller-supplied memory which was consumed by
							creation of the CCCryptorRef is returned here. Also,
							if the supplied memory is of insufficent size to create
							a CCCryptorRef, kCCBufferTooSmall is returned, and
							the minimum required buffer size is returned via this
							parameter if present. 
								
	@result		Possible error returns are kCCParamError and kCCBufferTooSmall.
				
	@discussion	The CCCryptorRef created by this function *may* be disposed of
				via CCCRyptorRelease; that call is not strictly necessary, but
				if it's not performed, good security practice dictates that the
				caller should zero the memory provided to create the CCCryptorRef
				when the caller is finished using the CCCryptorRef. 
*/
CCCryptorStatus CCCryptorCreateFromData(
	CCOperation op,             /* kCCEncrypt, etc. */
	CCAlgorithm alg,            /* kCCAlgorithmDES, etc. */
	CCOptions options,          /* kCCOptionPKCS7Padding, etc. */
	const void *key,            /* raw key material */
	size_t keyLength,	
	const void *iv,             /* optional initialization vector */
	const void *data,			/* caller-supplied memory */
	size_t dataLength,			/* length of data in bytes */
	CCCryptorRef *cryptorRef,   /* RETURNED */
    size_t *dataUsed)           /* optional, RETURNED */
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

/*!
	@function	CCCryptorRelease
	@abstract	Free a context created by CCCryptorCreate or 
				CCCryptorCreateFromData().
	
	@param		cryptorRef	The CCCryptorRef to release.
	
	@result		The only possible error return is kCCParamError resulting
				from passing in a null CCCryptorRef. 
*/
CCCryptorStatus CCCryptorRelease(
    CCCryptorRef cryptorRef)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);
	
/*!
	@function	CCCryptorUpdate
	@abstract	Process (encrypt, decrypt) some data. The result, if any,
				is written to a caller-provided buffer. 
				
	@param		cryptorRef		A CCCryptorRef created via CCCryptorCreate() or
								CCCryptorCreateFromData().
	@param		dataIn			Data to process, length dataInLength bytes.
	@param		dataInLength	Length of data to process.
	@param		dataOut			Result is written here. Allocated by caller. 
								Encryption and decryption can be performed
								"in-place", with the same buffer used for 
								input and output. 
	@param		dataOutAvailable The size of the dataOut buffer in bytes.  
	@param		dataOutMoved	On successful return, the number of bytes written 
								to dataOut.
								
	@result		kCCBufferTooSmall indicates insufficent space in the dataOut
								buffer. The caller can use CCCryptorGetOutputLength() 

								to determine the required output buffer size in this 
								case. The operation can be retried; no state is lost 
								when this is returned. 
								
	@discussion	This routine can be called multiple times. The caller does
				not need to align input data lengths to block sizes; input is
				bufferred as necessary for block ciphers. 
				 
				When performing symmetric encryption with block ciphers,
				and padding is enabled via kCCOptionPKCS7Padding, the total
				number of bytes provided by all the calls to this function 
				when encrypting can be arbitrary (i.e., the total number
				of bytes does not have to be block aligned). However if
				padding is disabled, or when decrypting, the total number
				of bytes does have to be aligned to the block size; otherwise
				CCCryptFinal() will return kCCAlignmentError. 
				
				A general rule for the size of the output buffer which must be
				provided by the caller is that for block ciphers, the output 
				length is never larger than the input length plus the block size.
				For stream ciphers, the output length is always exactly the same
				as the input length. See the discussion for CCCryptorGetOutputLength()
				for more information on this topic. 
				 
				Generally, when all data has been processed, call CCCryptorFinal().


				In the following cases, the CCCryptorFinal() is superfluous as
				it will not yield any data nor return an error:
				1. Encrypting or decrypting with a block cipher with padding 
				   disabled, when the total amount of data provided to 
				   CCCryptorUpdate() is an integral multiple of the block size. 
				2. Encrypting or decrypting with a stream cipher. 
 */
CCCryptorStatus CCCryptorUpdate(
	CCCryptorRef cryptorRef,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut,				/* data RETURNED here */
	size_t dataOutAvailable,
    size_t *dataOutMoved)       /* number of bytes written */
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

/*!
	@function	CCCryptorFinal
	@abstract	Finish an encrypt or decrypt operation, and obtain the (possible)
				final data output. 
			
	@param		cryptorRef		A CCCryptorRef created via CCCryptorCreate() or
								CCCryptorCreateFromData().
	@param		dataOut			Result is written here. Allocated by caller. 
	@param		dataOutAvailable The size of the dataOut buffer in bytes.  
	@param		dataOutMoved	On successful return, the number of bytes written 
								to dataOut.
		
	@result		kCCBufferTooSmall indicates insufficent space in the dataOut
								buffer. The caller can use CCCryptorGetOutputLength() 

								to determine the required output buffer size in this 
								case. The operation can be retried; no state is lost 
								when this is returned. 
				kCCAlignmentError When decrypting, or when encrypting with a
								block cipher with padding disabled, 
								kCCAlignmentError will be returned if the total 
								number of bytes provided to CCCryptUpdate() is 
								not an integral multiple of	the current 
								algorithm's block size. 
				kCCDecodeError  Indicates garbled ciphertext or the 
								wrong key during decryption. This can only
								be returned while decrypting with padding
								enabled. 
								
	@discussion	Except when kCCBufferTooSmall is returned, the CCCryptorRef
				can no longer be used for subsequent operations unless
				CCCryptorReset() is called on it. 
				
				It is not necessary to call CCCryptorFinal() when performing 
				symmetric encryption or decryption if padding is disabled, or
				when using a stream cipher.  
				
				It is not necessary to call CCCryptorFinal() prior to 
				CCCryptorRelease() when aborting an operation.
 */
CCCryptorStatus CCCryptorFinal(
	CCCryptorRef cryptorRef,
	void *dataOut,
	size_t dataOutAvailable,
    size_t *dataOutMoved)       /* number of bytes written */
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

/*!
	@function	CCCryptorGetOutputLength
	@abstract	Determine output buffer size required to process a given input size. 

	
	@param		cryptorRef	A CCCryptorRef created via CCCryptorCreate() or
							CCCryptorCreateFromData().
	@param		inputLength	The length of data which will be provided to 
							CCCryptorUpdate().
	@param		final		If false, the returned value will indicate the output 
							buffer space needed when 'inputLength' bytes are 
							provided to	CCCryptorUpdate(). When 'final' is true, 
							the returned value will indicate the total combined 

							buffer space needed when 'inputLength' bytes are 
							provided to	CCCryptorUpdate() and then CCCryptorFinal()
							is called. 
							
	@result The maximum buffer space need to perform CCCryptorUpdate() and optionally
			CCCryptorFinal(). 
			
	@discussion	Some general rules apply that allow clients of this module to
				know a priori how much output buffer space will be required
				in a given situation. For stream ciphers, the output size is
				always equal to the input size, and CCCryptorFinal() never 
				produces any data. For block ciphers, the output size will
				always be less than or equal to the input size plus the size
				of one block. For block ciphers, if the input size provided 
				to each call to CCCryptorUpdate() is is an integral multiple 
				of the block size, then the output size for each call to 
				CCCryptorUpdate() is less than or equal to the input size
				for that call to CCCryptorUpdate(). CCCryptorFinal() only 
				produces output when using a block cipher with padding enabled. 
*/
size_t CCCryptorGetOutputLength(
	CCCryptorRef cryptorRef,
	size_t inputLength,
    bool final)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

	
/*!
	@function	CCCryptorReset
	@abstract	Reinitializes an existing CCCryptorRef with a (possibly)
				new initialization vector. The CCCryptorRef's key is
				unchanged. Not implemented for stream ciphers. 
				
	@param		cryptorRef	A CCCryptorRef created via CCCryptorCreate() or
							CCCryptorCreateFromData().
	@param		iv			Optional initialization vector; if present, must
							be the same size as the current algorithm's block
							size. 
							
	@result		The the only possible errors are kCCParamError and 
				kCCUnimplemented.
	
	@discussion This can be called on a CCCryptorRef with data pending (i.e.
				in a padded mode operation before CCCryptFinal is called); 
				however any pending data will be lost in that case. 
*/
CCCryptorStatus CCCryptorReset(
	CCCryptorRef cryptorRef,
    const void *iv)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);












































































































































/*!
	@function	CCCrypt
	@abstract	Stateless, one-shot encrypt or decrypt operation.
				This basically performs a sequence of CCCrytorCreate(),
				CCCryptorUpdate(), CCCryptorFinal(), and CCCryptorRelease().
	
	@param		alg				Defines the encryption algorithm.
	
	
	@param		op				Defines the basic operation: kCCEncrypt or kCCDecrypt.

	
	@param		options			A word of flags defining options. See discussion
								for the CCOptions type.
	
	@param		key				Raw key material, length keyLength bytes. 
	
	@param		keyLength		Length of key material. Must be appropriate 
								for	the select algorithm. Some algorithms may 
								provide for varying key lengths.
	
	@param		iv				Initialization vector, optional. Used for 
								Cipher Block Chaining (CBC) mode. If present, 




								must be the same length as the selected 
								algorithm's block size. If CBC mode is
								selected (by the absence of any mode bits in 
								the options	flags) and no IV is present, a 
								NULL (all zeroes) IV will be used. This is 
								ignored if ECB mode is used or if a stream 
								cipher algorithm is selected. 
	
	@param		dataIn			Data to encrypt or decrypt, length dataInLength 
								bytes. 
	

	@param		dataInLength	Length of data to encrypt or decrypt.
	
	@param		dataOut			Result is written here. Allocated by caller. 
								Encryption and decryption can be performed
								"in-place", with the same buffer used for 
								input and output. 

	
	@param		dataOutAvailable The size of the dataOut buffer in bytes.  


	
	@param		dataOutMoved	On successful return, the number of bytes written 
								to dataOut. If kCCBufferTooSmall is returned as 
								a result of insufficient buffer space being 
								provided, the required buffer space is returned
								here. 

		
	@result		kCCBufferTooSmall indicates insufficent space in the dataOut
								buffer. In this case, the *dataOutMoved 
								parameter will indicate the size of the buffer
								needed to complete the operation. The 
								operation can be retried with minimal runtime 
								penalty. 
				kCCAlignmentError indicates that dataInLength was not properly 

                                aligned. This can only be returned for block 
								ciphers, and then only when decrypting or when 
								encrypting with block with padding disabled. 
				kCCDecodeError	Indicates improperly formatted ciphertext or
								a "wrong key" error; occurs only during decrypt
								operations. 
 */


CCCryptorStatus CCCrypt(
	CCOperation op,			/* kCCEncrypt, etc. */

	CCAlgorithm alg,		/* kCCAlgorithmAES128, etc. */
	CCOptions options,		/* kCCOptionPKCS7Padding, etc. */
	const void *key,
	size_t keyLength,
	const void *iv,			/* optional initialization vector */
	const void *dataIn,		/* optional per op and alg */
	size_t dataInLength,
	void *dataOut,			/* data RETURNED here */
	size_t dataOutAvailable,
    size_t *dataOutMoved)


    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);


#ifdef __cplusplus
}
#endif

#endif	/* _CC_COMMON_CRYPTOR_ */







|
|
|






|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|


|
|



>

>







|
|




|
|
|
|
|


|
|






|
|
|
|
|
|
|
>




|
|
|
|
|


|
|




|
|
|
|
|
|
|
|
>


|
|
|
|
|
|
>




|
|
|
|
|
|


|
|
|
|




|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|
|
|
|
|
|
|
|
|
>
>
|
|



|
|
|
|
|
|
|
|
|


|
|
|
|
|
|
|
|
|
>



|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|








<
|
|
|
|
|

|



|
|
|


|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|

|


|
|
|
|
|
|

|


|
|
|


|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|
|
|
|
|
|
|
|
|

|


|
|
|
|
|
|
|
|



|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
|
|
|
|
|
|


|
|
|
|
|

|


|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|
|
|

|


|
|
>
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|
|

|

|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|

|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|
|
<
<
|
|
|
|
<
>
|
<
|
|
|
|
|
|
<
|
<
|
>
>
>
>
|
|
<
<
|
<
<
<
<
<
|
>
|
|
|
|
|
|
>
|
<
>
>
|
<
<
|
|
|
>
|
<
|
|
|
<
|
|
>
|
|
<
<
<
<

>
>
|
|
>
|
|
<
<
|
|
|
|
|
|
>
>
|
|
<




|
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259

260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705


706
707
708
709

710
711

712
713
714
715
716
717

718

719
720
721
722
723
724
725


726





727
728
729
730
731
732
733
734
735
736

737
738
739


740
741
742
743
744

745
746
747

748
749
750
751
752




753
754
755
756
757
758
759
760


761
762
763
764
765
766
767
768
769
770

771
772
773
774
775
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*!
    @header     CommonCryptor.h
    @abstract   Generic interface for symmetric encryption. 
    
    @discussion This interface provides access to a number of symmetric 
                encryption algorithms. Symmetric encryption algorithms come 
                in two "flavors" -  block ciphers, and stream ciphers. Block
                ciphers process data (while both encrypting and decrypting) 
                in discrete chunks of  data called blocks; stream ciphers 
                operate on arbitrary sized data. 
                
                The object declared in this interface, CCCryptor, provides
                access to both block ciphers and stream ciphers with the same
                API; however some options are available for block ciphers that
                do not apply to stream ciphers. 
                
                The general operation of a CCCryptor is: initialize it
                with raw key data and other optional fields with
                CCCryptorCreate(); process input data via one or more calls to
                CCCryptorUpdate(), each of which may result in output data
                being written to caller-supplied memory; and obtain possible
                remaining output data with CCCryptorFinal(). The CCCryptor is
                disposed of via CCCryptorRelease(), or it can be reused (with
                the same key data as provided to CCCryptorCreate()) by calling
                CCCryptorReset(). 
                
                CCCryptors can be dynamically allocated by this module, or 
                their memory can be allocated by the caller. See discussion for
                CCCryptorCreate() and CCCryptorCreateFromData() for information 
                on CCCryptor allocation.
                
                One option for block ciphers is padding, as defined in PKCS7;
                when padding is enabled, the total amount of data encrypted
                does not have to be an even multiple of the block size, and 
                the actual length of plaintext is calculated during decryption. 
                
                Another option for block ciphers is Cipher Block Chaining, known
                as CBC mode. When using CBC mode, an Initialization Vector (IV)
                is provided along with the key when starting an encrypt
                or decrypt operation. If CBC mode is selected and no IV is 
                provided, an IV of all zeroes will be used. 
                
                CCCryptor also implements block bufferring, so that individual
                calls to CCCryptorUpdate() do not have to provide data whose
                length is aligned to the block size. (If padding is disabled,
                encrypting with block ciphers does require that the *total*
                length of data input to CCCryptorUpdate() call(s) be aligned
                to the block size.)
    
                A given CCCryptor can only be used by one thread at a time;
                multiple threads can use safely different CCCryptors at the
                same time.              
*/

#ifndef _CC_COMMON_CRYPTOR_
#define _CC_COMMON_CRYPTOR_

#include <stdbool.h>
#include <stdint.h>
#ifndef KERNEL
#include <stddef.h>
#endif /* KERNEL */
#include <Availability.h>

#ifdef __cplusplus
extern "C" {
#endif

/*!
    @typedef    CCCryptorRef
    @abstract   Opaque reference to a CCCryptor object.
 */
typedef struct _CCCryptor *CCCryptorRef;

/*!
    @enum       CCCryptorStatus
    @abstract   Return values from CommonCryptor operations.
    
    @constant   kCCSuccess          Operation completed normally.
    @constant   kCCParamError       Illegal parameter value.
    @constant   kCCBufferTooSmall   Insufficent buffer provided for specified 
                                    operation.
    @constant   kCCMemoryFailure    Memory allocation failure. 
    @constant   kCCAlignmentError   Input size was not aligned properly. 
    @constant   kCCDecodeError      Input data did not decode or decrypt 
                                    properly.
    @constant   kCCUnimplemented    Function not implemented for the current 
                                    algorithm.
 */
enum {
    kCCSuccess          = 0,
    kCCParamError       = -4300,
    kCCBufferTooSmall   = -4301,
    kCCMemoryFailure    = -4302,
    kCCAlignmentError   = -4303,
    kCCDecodeError      = -4304,
    kCCUnimplemented    = -4305,
    kCCOverflow         = -4306
};
typedef int32_t CCCryptorStatus;

/*!
    @enum       CCOperation
    @abstract   Operations that an CCCryptor can perform.
    
    @constant   kCCEncrypt  Symmetric encryption.
    @constant   kCCDecrypt  Symmetric decryption.
*/
enum {
    kCCEncrypt = 0, 
    kCCDecrypt,     
};
typedef uint32_t CCOperation;

/*!
    @enum       CCAlgorithm
    @abstract   Encryption algorithms implemented by this module.
    
    @constant   kCCAlgorithmAES128  Advanced Encryption Standard, 128-bit block
    @constant   kCCAlgorithmDES     Data Encryption Standard
    @constant   kCCAlgorithm3DES    Triple-DES, three key, EDE configuration
    @constant   kCCAlgorithmCAST    CAST
 	@constant   kCCAlgorithmRC4     RC4 stream cipher
 	@constant   kCCAlgorithmBlowfish    Blowfish block cipher
*/
enum {
    kCCAlgorithmAES128 = 0,
    kCCAlgorithmDES,        
    kCCAlgorithm3DES,       
    kCCAlgorithmCAST,       
    kCCAlgorithmRC4,
    kCCAlgorithmRC2,   
    kCCAlgorithmBlowfish    
};
typedef uint32_t CCAlgorithm;

/*!
    @enum       CCOptions
    @abstract   Options flags, passed to CCCryptorCreate().
    
    @constant   kCCOptionPKCS7Padding   Perform PKCS7 padding. 
    @constant   kCCOptionECBMode        Electronic Code Book Mode. 
                                        Default is CBC.
*/
enum {
    /* options for block ciphers */
    kCCOptionPKCS7Padding   = 0x0001,
    kCCOptionECBMode        = 0x0002
    /* stream ciphers currently have no options */
};
typedef uint32_t CCOptions;

/*!
    @enum           Key sizes
    
    @discussion     Key sizes, in bytes, for supported algorithms. 
    
    @constant kCCKeySizeAES128      128 bit AES key size.
    @constant kCCKeySizeAES192      192 bit AES key size.
    @constant kCCKeySizeAES256      256 bit AES key size.
    @constant kCCKeySizeDES         DES key size.
    @constant kCCKeySize3DES        Triple DES key size.
    @constant kCCKeySizeMinCAST     CAST minimum key size.
    @constant kCCKeySizeMaxCAST     CAST maximum key size.
    @constant kCCKeySizeMinRC4      RC4 minimum key size.
    @constant kCCKeySizeMaxRC4      RC4 maximum key size.
    
    @discussion     DES and TripleDES have fixed key sizes.
                    AES has three discrete key sizes.
                    CAST and RC4 have variable key sizes.
*/
enum {
    kCCKeySizeAES128          = 16,
    kCCKeySizeAES192          = 24,
    kCCKeySizeAES256          = 32,
    kCCKeySizeDES             = 8,
    kCCKeySize3DES            = 24,
    kCCKeySizeMinCAST         = 5,
    kCCKeySizeMaxCAST         = 16,
    kCCKeySizeMinRC4          = 1,
    kCCKeySizeMaxRC4          = 512,
    kCCKeySizeMinRC2          = 1,
    kCCKeySizeMaxRC2          = 128,
    kCCKeySizeMinBlowfish     = 8,
    kCCKeySizeMaxBlowfish     = 56,
};

/*!
    @enum           Block sizes
    
    @discussion     Block sizes, in bytes, for supported algorithms. 
    
    @constant kCCBlockSizeAES128    AES block size (currently, only 128-bit 
                                    blocks are supported).
    @constant kCCBlockSizeDES       DES block size.
    @constant kCCBlockSize3DES      Triple DES block size.
    @constant kCCBlockSizeCAST      CAST block size.
*/
enum {
    /* AES */
    kCCBlockSizeAES128        = 16,
    /* DES */
    kCCBlockSizeDES           = 8,
    /* 3DES */
    kCCBlockSize3DES          = 8,
    /* CAST */
    kCCBlockSizeCAST          = 8,
    kCCBlockSizeRC2           = 8,
    kCCBlockSizeBlowfish      = 8,
};

/*!
    @enum       Minimum context sizes
    @discussion Minimum context sizes, for caller-allocated CCCryptorRefs.
                To minimize dynamic allocation memory, a caller can create 
                a CCCryptorRef by passing caller-supplied memory to the 
                CCCryptorCreateFromData() function.
    
                These constants define the minimum amount of memory, in 
                bytes, needed for CCCryptorRefs for each supported algorithm. 
    
                Note: these constants are valid for the current version of 
                this library; they may change in subsequent releases, so 
                applications wishing to allocate their own memory for use 
                in creating CCCryptorRefs must be prepared to deal with 
                a kCCBufferTooSmall return from CCCryptorCreateFromData().
                See discussion for the CCCryptorCreateFromData() function.
    
    @constant kCCContextSizeAES128 - Minimum context size for kCCAlgorithmAES128.
    @constant kCCContextSizeDES    - Minimum context size for kCCAlgorithmDES.
    @constant kCCContextSize3DES   - Minimum context size for kCCAlgorithm3DES.
    @constant kCCContextSizeCAST   - Minimum context size for kCCAlgorithmCAST.
    @constant kCCContextSizeRC4    - Minimum context size for kCCAlgorithmRC4.
*/
    
enum {

    kCCContextSizeAES128	= 404,
    kCCContextSizeDES		= 240,
    kCCContextSize3DES		= 496,
    kCCContextSizeCAST		= 240,
    kCCContextSizeRC4		= 1072
};
    


/*!
    @function   CCCryptorCreate
    @abstract   Create a cryptographic context. 
    
    @param      op          Defines the basic operation: kCCEncrypt or 
                            kCCDecrypt.
    
    @param      alg         Defines the algorithm.
    
    @param      options     A word of flags defining options. See discussion
                            for the CCOptions type.
                            
    @param      key         Raw key material, length keyLength bytes. 
    
    @param      keyLength   Length of key material. Must be appropriate 
                            for the selected operation and algorithm. Some 
                            algorithms  provide for varying key lengths.

    @param      iv          Initialization vector, optional. Used by 
                            block ciphers when Cipher Block Chaining (CBC) 
                            mode is enabled. If present, must be the same
                            length as the selected algorithm's block size. 
                            If CBC mode is selected (by the absence of the 
                            kCCOptionECBMode bit in the options flags) and no 
                            IV is present, a NULL (all zeroes) IV will be used. 
                            This parameter is ignored if ECB mode is used or
                            if a stream cipher algorithm is selected. 

    @param      cryptorRef  A (required) pointer to the returned CCCryptorRef. 

    @result     Possible error returns are kCCParamError and kCCMemoryFailure.
*/
CCCryptorStatus CCCryptorCreate(
    CCOperation op,             /* kCCEncrypt, etc. */
    CCAlgorithm alg,            /* kCCAlgorithmDES, etc. */
    CCOptions options,          /* kCCOptionPKCS7Padding, etc. */
    const void *key,            /* raw key material */
    size_t keyLength,   
    const void *iv,             /* optional initialization vector */
    CCCryptorRef *cryptorRef)  /* RETURNED */
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_4_0);

/*!
    @function   CCCryptorCreateFromData
    @abstract   Create a cryptographic context using caller-supplied memory. 
    
    @param      op          Defines the basic operation: kCCEncrypt or 
                            kCCDecrypt.
    
    @param      alg         Defines the algorithm.
    
    @param      options     A word of flags defining options. See discussion
                            for the CCOptions type.
                            
    @param      key         Raw key material, length keyLength bytes. 
    
    @param      keyLength   Length of key material. Must be appropriate 
                            for the selected operation and algorithm. Some 
                            algorithms  provide for varying key lengths.

    @param      iv          Initialization vector, optional. Used by 
                            block ciphers when Cipher Block Chaining (CBC) 
                            mode is enabled. If present, must be the same
                            length as the selected algorithm's block size. 
                            If CBC mode is selected (by the absence of the 
                            kCCOptionECBMode bit in the options flags) and no 
                            IV is present, a NULL (all zeroes) IV will be used. 
                            This parameter is ignored if ECB mode is used or
                            if a stream cipher algorithm is selected. 

    @param      data        A pointer to caller-supplied memory from which the 
                            CCCryptorRef will be created. 
                            
    @param      dataLength  The size of the caller-supplied memory in bytes. 
    
    @param      cryptorRef  A (required) pointer to the returned CCCryptorRef. 
    
    @param      dataUsed    Optional. If present, the actual number of bytes of 
                            the caller-supplied memory which was consumed by
                            creation of the CCCryptorRef is returned here. Also,
                            if the supplied memory is of insufficent size to create
                            a CCCryptorRef, kCCBufferTooSmall is returned, and
                            the minimum required buffer size is returned via this
                            parameter if present. 
                                
    @result     Possible error returns are kCCParamError and kCCBufferTooSmall.
                
    @discussion The CCCryptorRef created by this function *may* be disposed of
                via CCCRyptorRelease; that call is not strictly necessary, but
                if it's not performed, good security practice dictates that the
                caller should zero the memory provided to create the CCCryptorRef
                when the caller is finished using the CCCryptorRef. 
*/
CCCryptorStatus CCCryptorCreateFromData(
    CCOperation op,             /* kCCEncrypt, etc. */
    CCAlgorithm alg,            /* kCCAlgorithmDES, etc. */
    CCOptions options,          /* kCCOptionPKCS7Padding, etc. */
    const void *key,            /* raw key material */
    size_t keyLength,   
    const void *iv,             /* optional initialization vector */
    const void *data,           /* caller-supplied memory */
    size_t dataLength,          /* length of data in bytes */
    CCCryptorRef *cryptorRef,   /* RETURNED */
    size_t *dataUsed)           /* optional, RETURNED */
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_4_0);

/*!
    @function   CCCryptorRelease
    @abstract   Free a context created by CCCryptorCreate or 
                CCCryptorCreateFromData().
    
    @param      cryptorRef  The CCCryptorRef to release.
    
    @result     The only possible error return is kCCParamError resulting
                from passing in a null CCCryptorRef. 
*/
CCCryptorStatus CCCryptorRelease(
    CCCryptorRef cryptorRef)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_4_0);
    
/*!
    @function   CCCryptorUpdate
    @abstract   Process (encrypt, decrypt) some data. The result, if any,
                is written to a caller-provided buffer. 
                
    @param      cryptorRef      A CCCryptorRef created via CCCryptorCreate() or
                                CCCryptorCreateFromData().
    @param      dataIn          Data to process, length dataInLength bytes.
    @param      dataInLength    Length of data to process.
    @param      dataOut         Result is written here. Allocated by caller. 
                                Encryption and decryption can be performed
                                "in-place", with the same buffer used for 
                                input and output. 
    @param      dataOutAvailable The size of the dataOut buffer in bytes.  
    @param      dataOutMoved    On successful return, the number of bytes
    				written to dataOut.
                                
    @result     kCCBufferTooSmall indicates insufficent space in the dataOut
                                buffer. The caller can use
				CCCryptorGetOutputLength() to determine the
				required output buffer size in this case. The
				operation can be retried; no state is lost 
                                when this is returned. 
                                
    @discussion This routine can be called multiple times. The caller does
                not need to align input data lengths to block sizes; input is
                bufferred as necessary for block ciphers. 
                 
                When performing symmetric encryption with block ciphers,
                and padding is enabled via kCCOptionPKCS7Padding, the total
                number of bytes provided by all the calls to this function 
                when encrypting can be arbitrary (i.e., the total number
                of bytes does not have to be block aligned). However if
                padding is disabled, or when decrypting, the total number
                of bytes does have to be aligned to the block size; otherwise
                CCCryptFinal() will return kCCAlignmentError. 
                
                A general rule for the size of the output buffer which must be
                provided by the caller is that for block ciphers, the output 
                length is never larger than the input length plus the block size.
                For stream ciphers, the output length is always exactly the same
                as the input length. See the discussion for
		CCCryptorGetOutputLength() for more information on this topic. 
                 
                Generally, when all data has been processed, call
		CCCryptorFinal().

                In the following cases, the CCCryptorFinal() is superfluous as
                it will not yield any data nor return an error:
                1. Encrypting or decrypting with a block cipher with padding 
                   disabled, when the total amount of data provided to 
                   CCCryptorUpdate() is an integral multiple of the block size. 
                2. Encrypting or decrypting with a stream cipher. 
 */
CCCryptorStatus CCCryptorUpdate(
    CCCryptorRef cryptorRef,
    const void *dataIn,
    size_t dataInLength,
    void *dataOut,              /* data RETURNED here */
    size_t dataOutAvailable,
    size_t *dataOutMoved)       /* number of bytes written */
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_4_0);

/*!
    @function   CCCryptorFinal
    @abstract   Finish an encrypt or decrypt operation, and obtain the (possible)
                final data output. 
            
    @param      cryptorRef      A CCCryptorRef created via CCCryptorCreate() or
                                CCCryptorCreateFromData().
    @param      dataOut         Result is written here. Allocated by caller. 
    @param      dataOutAvailable The size of the dataOut buffer in bytes.  
    @param      dataOutMoved    On successful return, the number of bytes
    				written to dataOut.
        
    @result     kCCBufferTooSmall indicates insufficent space in the dataOut
                                buffer. The caller can use
				CCCryptorGetOutputLength() to determine the
				required output buffer size in this case. The
				operation can be retried; no state is lost 
                                when this is returned. 
                kCCAlignmentError When decrypting, or when encrypting with a
                                block cipher with padding disabled, 
                                kCCAlignmentError will be returned if the total 
                                number of bytes provided to CCCryptUpdate() is 
                                not an integral multiple of the current 
                                algorithm's block size. 
                kCCDecodeError  Indicates garbled ciphertext or the 
                                wrong key during decryption. This can only
                                be returned while decrypting with padding
                                enabled. 
                                
    @discussion Except when kCCBufferTooSmall is returned, the CCCryptorRef
                can no longer be used for subsequent operations unless
                CCCryptorReset() is called on it. 
                
                It is not necessary to call CCCryptorFinal() when performing 
                symmetric encryption or decryption if padding is disabled, or
                when using a stream cipher.  
                
                It is not necessary to call CCCryptorFinal() prior to 
                CCCryptorRelease() when aborting an operation.
 */
CCCryptorStatus CCCryptorFinal(
    CCCryptorRef cryptorRef,
    void *dataOut,
    size_t dataOutAvailable,
    size_t *dataOutMoved)       /* number of bytes written */
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_4_0);

/*!
    @function   CCCryptorGetOutputLength
    @abstract   Determine output buffer size required to process a given input
    		size. 
    
    @param      cryptorRef  A CCCryptorRef created via CCCryptorCreate() or
                            CCCryptorCreateFromData().
    @param      inputLength The length of data which will be provided to 
                            CCCryptorUpdate().
    @param      final       If false, the returned value will indicate the
    			    output buffer space needed when 'inputLength'
			    bytes are provided to CCCryptorUpdate(). When
			    'final' is true, the returned value will indicate
			    the total combined buffer space needed when
			    'inputLength' bytes are provided to
			    CCCryptorUpdate() and then CCCryptorFinal() is
			    called. 
                            
    @result The maximum buffer space need to perform CCCryptorUpdate() and
    	    optionally CCCryptorFinal(). 
            
    @discussion Some general rules apply that allow clients of this module to
                know a priori how much output buffer space will be required
                in a given situation. For stream ciphers, the output size is
                always equal to the input size, and CCCryptorFinal() never 
                produces any data. For block ciphers, the output size will
                always be less than or equal to the input size plus the size
                of one block. For block ciphers, if the input size provided 
                to each call to CCCryptorUpdate() is is an integral multiple 
                of the block size, then the output size for each call to 
                CCCryptorUpdate() is less than or equal to the input size
                for that call to CCCryptorUpdate(). CCCryptorFinal() only 
                produces output when using a block cipher with padding enabled. 
*/
size_t CCCryptorGetOutputLength(
    CCCryptorRef cryptorRef,
    size_t inputLength,
    bool final)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_4_0);

    
/*!
    @function   CCCryptorReset
    @abstract   Reinitializes an existing CCCryptorRef with a (possibly)
                new initialization vector. The CCCryptorRef's key is
                unchanged. Not implemented for stream ciphers. 
                
    @param      cryptorRef  A CCCryptorRef created via CCCryptorCreate() or
                            CCCryptorCreateFromData().
    @param      iv          Optional initialization vector; if present, must
                            be the same size as the current algorithm's block
                            size. 
                            
    @result     The the only possible errors are kCCParamError and 
                kCCUnimplemented.
    
    @discussion This can be called on a CCCryptorRef with data pending (i.e.
                in a padded mode operation before CCCryptFinal is called); 
                however any pending data will be lost in that case. 
*/
CCCryptorStatus CCCryptorReset(
    CCCryptorRef cryptorRef,
    const void *iv)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_4_0);


/*!
    @function   CCCrypt
    @abstract   Stateless, one-shot encrypt or decrypt operation.
                This basically performs a sequence of CCCrytorCreate(),
                CCCryptorUpdate(), CCCryptorFinal(), and CCCryptorRelease().
    
    @param      alg             Defines the encryption algorithm.
    
    
    @param      op              Defines the basic operation: kCCEncrypt or
    				kCCDecrypt.
    
    @param      options         A word of flags defining options. See discussion
                                for the CCOptions type.
    
    @param      key             Raw key material, length keyLength bytes. 
    
    @param      keyLength       Length of key material. Must be appropriate 
                                for the select algorithm. Some algorithms may 
                                provide for varying key lengths.
    
    @param      iv              Initialization vector, optional. Used for 
                                Cipher Block Chaining (CBC) mode. If present, 
                                must be the same length as the selected 
                                algorithm's block size. If CBC mode is
                                selected (by the absence of any mode bits in 
                                the options flags) and no IV is present, a 
                                NULL (all zeroes) IV will be used. This is 
                                ignored if ECB mode is used or if a stream 
                                cipher algorithm is selected. 
    
    @param      dataIn          Data to encrypt or decrypt, length dataInLength 
                                bytes. 
    
    @param      dataInLength    Length of data to encrypt or decrypt.
    
    @param      dataOut         Result is written here. Allocated by caller. 
                                Encryption and decryption can be performed
                                "in-place", with the same buffer used for 
                                input and output. 
    
    @param      dataOutAvailable The size of the dataOut buffer in bytes.  
    
    @param      dataOutMoved    On successful return, the number of bytes
    				written to dataOut. If kCCBufferTooSmall is
				returned as a result of insufficient buffer
				space being provided, the required buffer space
				is returned here. 
        
    @result     kCCBufferTooSmall indicates insufficent space in the dataOut
                                buffer. In this case, the *dataOutMoved 
                                parameter will indicate the size of the buffer
                                needed to complete the operation. The 
                                operation can be retried with minimal runtime 
                                penalty. 
                kCCAlignmentError indicates that dataInLength was not properly 
                                aligned. This can only be returned for block 
                                ciphers, and then only when decrypting or when 
                                encrypting with block with padding disabled. 
                kCCDecodeError  Indicates improperly formatted ciphertext or
                                a "wrong key" error; occurs only during decrypt
                                operations. 
 */
    
CCCryptorStatus CCCrypt(
    CCOperation op,         /* kCCEncrypt, etc. */
    CCAlgorithm alg,        /* kCCAlgorithmAES128, etc. */
    CCOptions options,      /* kCCOptionPKCS7Padding, etc. */
    const void *key,
    size_t keyLength,
    const void *iv,         /* optional initialization vector */
    const void *dataIn,     /* optional per op and alg */
    size_t dataInLength,
    void *dataOut,          /* data RETURNED here */
    size_t dataOutAvailable,
    size_t *dataOutMoved)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_4_0);


/*!
    @enum       Cipher Modes
    @discussion These are the selections available for modes of operation for
				use with block ciphers.  If RC4 is selected as the cipher (a stream
				cipher) the only correct mode is kCCModeRC4.
    
    @constant kCCModeECB - Electronic Code Book Mode.
    @constant kCCModeCBC - Cipher Block Chaining Mode.
    @constant kCCModeCFB - Cipher Feedback Mode.
    @constant kCCModeOFB - Output Feedback Mode.
    @constant kCCModeXTS - XEX-based Tweaked CodeBook Mode.
    @constant kCCModeRC4 - RC4 as a streaming cipher is handled internally as a mode.
    @constant kCCModeCFB8 - Cipher Feedback Mode producing 8 bits per round.
*/


enum {
	kCCModeECB		= 1,
	kCCModeCBC		= 2,
	kCCModeCFB		= 3,
	kCCModeCTR		= 4,
	kCCModeF8		= 5, // Unimplemented for now (not included)
	kCCModeLRW		= 6, // Unimplemented for now (not included)
	kCCModeOFB		= 7,
	kCCModeXTS		= 8,
	kCCModeRC4		= 9,
	kCCModeCFB8		= 10,
};
typedef uint32_t CCMode;

/*!
    @enum       Padding for Block Ciphers
    @discussion These are the padding options available for block modes.
    
    @constant ccNoPadding -  No padding.
    @constant ccPKCS7Padding - PKCS7 Padding.
*/

enum {
	ccNoPadding			= 0,
	ccPKCS7Padding		= 1,
};
typedef uint32_t CCPadding;

/*!
    @enum       Mode options - so far only used for CTR mode
    @discussion Values used to specify options for modes.
    
    @constant kCCModeOptionCTR_LE - CTR Mode Little Endian.
    @constant kCCModeOptionCTR_BE - CTR Mode Big Endian.
*/

enum {
	kCCModeOptionCTR_LE	= 0x0001,
	kCCModeOptionCTR_BE = 0x0002
};

typedef uint32_t CCModeOptions;

/*!
     @function   CCCryptorCreateWithMode
     @abstract   Create a cryptographic context. 


     
     @param      op         Defines the basic operation: kCCEncrypt or 
                            kCCDecrypt.
     

     @param     mode		Specifies the cipher mode to use for operations.
     

     @param      alg        Defines the algorithm.
     
     @param		padding		Specifies the padding to use.
     
     @param      iv         Initialization vector, optional. Used by 
                            block ciphers with the following modes:

     

                            Cipher Block Chaining (CBC) 
                            Cipher Feedback (CFB and CFB8)
                            Output Feedback (OFB)
                            Counter (CTR)
     
                            If present, must be the same length as the selected
                            algorithm's block size.  If no IV is present, a NULL


                            (all zeroes) IV will be used. 





     
                            This parameter is ignored if ECB mode is used or
                            if a stream cipher algorithm is selected. 
     
     @param      key         Raw key material, length keyLength bytes. 
     
     @param      keyLength   Length of key material. Must be appropriate 
                            for the selected operation and algorithm. Some 
                            algorithms  provide for varying key lengths.
     

     @param      tweak      Raw key material, length keyLength bytes. Used for the
                            tweak key in XEX-based Tweaked CodeBook (XTS) mode.
     


     @param      tweakLength   Length of tweak key material. Must be appropriate 
                            for the selected operation and algorithm. Some 
                            algorithms  provide for varying key lengths.  For XTS 
                            this is the same length as the encryption key.
     

     @param		numRounds	The number of rounds of the cipher to use.  0 uses the default.
     
     @param      options    A word of flags defining options. See discussion

                            for the CCModeOptions type.
     
     @param      cryptorRef  A (required) pointer to the returned CCCryptorRef. 
     
     @result     Possible error returns are kCCParamError and kCCMemoryFailure.




 */
    

CCCryptorStatus CCCryptorCreateWithMode(
    CCOperation 	op,				/* kCCEncrypt, kCCEncrypt */
    CCMode			mode,
    CCAlgorithm		alg,
    CCPadding		padding,		


    const void 		*iv,			/* optional initialization vector */
    const void 		*key,			/* raw key material */
    size_t 			keyLength,	
    const void 		*tweak,			/* raw tweak material */
    size_t 			tweakLength,	
    int				numRounds,		/* 0 == default */
    CCModeOptions 	options,
    CCCryptorRef	*cryptorRef)	/* RETURNED */
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    

#ifdef __cplusplus
}
#endif

#endif  /* _CC_COMMON_CRYPTOR_ */

Changes to CommonCrypto/CommonDigest.h.

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 * CommonDigest.h - common digest routines: MD2, MD4, MD5, SHA1.
 */
 
#ifndef	_CC_COMMON_DIGEST_H_
#define _CC_COMMON_DIGEST_H_

#include <stdint.h>
#include <Availability.h>

#ifdef __cplusplus
extern "C" {







|







21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 * CommonDigest.h - common digest routines: MD2, MD4, MD5, SHA1.
 */
 
#ifndef _CC_COMMON_DIGEST_H_
#define _CC_COMMON_DIGEST_H_

#include <stdint.h>
#include <Availability.h>

#ifdef __cplusplus
extern "C" {
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
 * calculation and place the result in the caller-supplied buffer
 * indicated by the md parameter. They return the md parameter.
 * Unlike the opensssl counterparts, these one-shot functions require
 * a non-NULL md pointer. Passing in NULL for the md parameter 
 * results in a NULL return and no digest calculation. 
 */
 
typedef uint32_t CC_LONG;		/* 32 bit unsigned integer */
typedef uint64_t CC_LONG64;		/* 64 bit unsigned integer */

/*** MD2 ***/

#define CC_MD2_DIGEST_LENGTH	16			/* digest length in bytes */
#define CC_MD2_BLOCK_BYTES		64			/* block size in bytes */
#define CC_MD2_BLOCK_LONG       (CC_MD2_BLOCK_BYTES / sizeof(CC_LONG))

typedef struct CC_MD2state_st
{
    int num;
    unsigned char data[CC_MD2_DIGEST_LENGTH];
    CC_LONG cksm[CC_MD2_BLOCK_LONG];
	CC_LONG state[CC_MD2_BLOCK_LONG];
} CC_MD2_CTX;

extern int CC_MD2_Init(CC_MD2_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_MD2_Update(CC_MD2_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_MD2_Final(unsigned char *md, CC_MD2_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern unsigned char *CC_MD2(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

/*** MD4 ***/

#define CC_MD4_DIGEST_LENGTH	16			/* digest length in bytes */
#define CC_MD4_BLOCK_BYTES		64			/* block size in bytes */
#define CC_MD4_BLOCK_LONG       (CC_MD4_BLOCK_BYTES / sizeof(CC_LONG))

typedef struct CC_MD4state_st
{
	CC_LONG A,B,C,D;
	CC_LONG Nl,Nh;
	CC_LONG data[CC_MD4_BLOCK_LONG];
	int num;
} CC_MD4_CTX;

extern int CC_MD4_Init(CC_MD4_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_MD4_Update(CC_MD4_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_MD4_Final(unsigned char *md, CC_MD4_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern unsigned char *CC_MD4(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);


/*** MD5 ***/

#define CC_MD5_DIGEST_LENGTH	16			/* digest length in bytes */
#define CC_MD5_BLOCK_BYTES		64			/* block size in bytes */
#define CC_MD5_BLOCK_LONG       (CC_MD5_BLOCK_BYTES / sizeof(CC_LONG))

typedef struct CC_MD5state_st
{
	CC_LONG A,B,C,D;
	CC_LONG Nl,Nh;
	CC_LONG data[CC_MD5_BLOCK_LONG];
	int num;
} CC_MD5_CTX;

extern int CC_MD5_Init(CC_MD5_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_MD5_Update(CC_MD5_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_MD5_Final(unsigned char *md, CC_MD5_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);


/*** SHA1 ***/

#define CC_SHA1_DIGEST_LENGTH	20			/* digest length in bytes */
#define CC_SHA1_BLOCK_BYTES		64			/* block size in bytes */
#define CC_SHA1_BLOCK_LONG      (CC_SHA1_BLOCK_BYTES / sizeof(CC_LONG))

typedef struct CC_SHA1state_st
{
	CC_LONG h0,h1,h2,h3,h4;
	CC_LONG Nl,Nh;
	CC_LONG data[CC_SHA1_BLOCK_LONG];
	int num;
} CC_SHA1_CTX;

extern int CC_SHA1_Init(CC_SHA1_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_SHA1_Update(CC_SHA1_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_SHA1_Final(unsigned char *md, CC_SHA1_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern unsigned char *CC_SHA1(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);


/*** SHA224 ***/
#define CC_SHA224_DIGEST_LENGTH		28			/* digest length in bytes */
#define CC_SHA224_BLOCK_BYTES		64			/* block size in bytes */

/* same context struct is used for SHA224 and SHA256 */
typedef struct CC_SHA256state_st
{   CC_LONG count[2];
    CC_LONG hash[8];
    CC_LONG wbuf[16];
} CC_SHA256_CTX;

extern int CC_SHA224_Init(CC_SHA256_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_SHA224_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_SHA224_Final(unsigned char *md, CC_SHA256_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern unsigned char *CC_SHA224(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);


/*** SHA256 ***/

#define CC_SHA256_DIGEST_LENGTH		32			/* digest length in bytes */
#define CC_SHA256_BLOCK_BYTES		64			/* block size in bytes */

extern int CC_SHA256_Init(CC_SHA256_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_SHA256_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_SHA256_Final(unsigned char *md, CC_SHA256_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern unsigned char *CC_SHA256(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);


/*** SHA384 ***/

#define CC_SHA384_DIGEST_LENGTH		48			/* digest length in bytes */
#define CC_SHA384_BLOCK_BYTES      128			/* block size in bytes */

/* same context struct is used for SHA384 and SHA512 */
typedef struct CC_SHA512state_st
{   CC_LONG64 count[2];
    CC_LONG64 hash[8];
    CC_LONG64 wbuf[16];
} CC_SHA512_CTX;

extern int CC_SHA384_Init(CC_SHA512_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_SHA384_Update(CC_SHA512_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_SHA384_Final(unsigned char *md, CC_SHA512_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern unsigned char *CC_SHA384(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);


/*** SHA512 ***/

#define CC_SHA512_DIGEST_LENGTH		64			/* digest length in bytes */
#define CC_SHA512_BLOCK_BYTES      128			/* block size in bytes */

extern int CC_SHA512_Init(CC_SHA512_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_SHA512_Update(CC_SHA512_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern int CC_SHA512_Final(unsigned char *md, CC_SHA512_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

extern unsigned char *CC_SHA512(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

/*
 * To use the above digest functions with existing code which uses
 * the corresponding openssl functions, #define the symbol 
 * COMMON_DIGEST_FOR_OPENSSL in your client code (BEFORE including
 * this file), and simply link against libSystem (or System.framework)
 * instead of libcrypto.
 *
 * You can *NOT* mix and match functions operating on a given data
 * type from the two implementations; i.e., if you do a CC_MD5_Init()
 * on a CC_MD5_CTX object, do not assume that you can do an openssl-style
 * MD5_Update() on that same context.
 */
 
#ifdef	COMMON_DIGEST_FOR_OPENSSL

#define MD2_DIGEST_LENGTH			CC_MD2_DIGEST_LENGTH
#define MD2_CTX						CC_MD2_CTX
#define MD2_Init					CC_MD2_Init
#define MD2_Update					CC_MD2_Update
#define MD2_Final					CC_MD2_Final

#define MD4_DIGEST_LENGTH			CC_MD4_DIGEST_LENGTH
#define MD4_CTX						CC_MD4_CTX
#define MD4_Init					CC_MD4_Init
#define MD4_Update					CC_MD4_Update
#define MD4_Final					CC_MD4_Final

#define MD5_DIGEST_LENGTH			CC_MD5_DIGEST_LENGTH
#define MD5_CTX						CC_MD5_CTX
#define MD5_Init					CC_MD5_Init
#define MD5_Update					CC_MD5_Update
#define MD5_Final					CC_MD5_Final

#define SHA_DIGEST_LENGTH			CC_SHA1_DIGEST_LENGTH
#define SHA_CTX						CC_SHA1_CTX
#define SHA1_Init					CC_SHA1_Init
#define SHA1_Update					CC_SHA1_Update
#define SHA1_Final					CC_SHA1_Final

#define SHA224_DIGEST_LENGTH		CC_SHA224_DIGEST_LENGTH
#define SHA256_CTX					CC_SHA256_CTX
#define SHA224_Init					CC_SHA224_Init
#define SHA224_Update				CC_SHA224_Update
#define SHA224_Final				CC_SHA224_Final

#define SHA256_DIGEST_LENGTH		CC_SHA256_DIGEST_LENGTH
#define SHA256_Init					CC_SHA256_Init
#define SHA256_Update				CC_SHA256_Update
#define SHA256_Final				CC_SHA256_Final

#define SHA384_DIGEST_LENGTH		CC_SHA384_DIGEST_LENGTH
#define SHA512_CTX					CC_SHA512_CTX
#define SHA384_Init					CC_SHA384_Init
#define SHA384_Update				CC_SHA384_Update
#define SHA384_Final				CC_SHA384_Final

#define SHA512_DIGEST_LENGTH		CC_SHA512_DIGEST_LENGTH
#define SHA512_Init					CC_SHA512_Init
#define SHA512_Update				CC_SHA512_Update
#define SHA512_Final				CC_SHA512_Final


#endif	/* COMMON_DIGEST_FOR_OPENSSL */

/*
 * In a manner similar to that described above for openssl 
 * compatibility, these macros can be used to provide compatiblity 
 * with legacy implementations of MD5 using the interface defined 
 * in RFC 1321.
 */
 
#ifdef	COMMON_DIGEST_FOR_RFC_1321

#define MD5_CTX						CC_MD5_CTX
#define MD5Init						CC_MD5_Init
#define MD5Update					CC_MD5_Update
void MD5Final (unsigned char [16], MD5_CTX *)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

#endif	/* COMMON_DIGEST_FOR_RFC_1321 */

#ifdef __cplusplus
}
#endif

#endif	/* _CC_COMMON_DIGEST_H_ */







|
|



|
|







|



|


|


|


|



|
|




|
|
|
|



|


|


|


|




|
|




|
|
|
|



|


|


|


|




|
|




|
|
|
|



|


|


|


|



|
|









|


|


|


|




|
|


|


|


|


|




|
|









|


|


|


|




|
|


|


|


|


|














|

|
|
|
|
|

|
|
|
|
|

|
|
|
|
|

|
|
|
|
|

|
|
|
|
|

|
|
|
|

|
|
|
|
|

|
|
|
|


|








|

|
|
|

|

|





|
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
 * calculation and place the result in the caller-supplied buffer
 * indicated by the md parameter. They return the md parameter.
 * Unlike the opensssl counterparts, these one-shot functions require
 * a non-NULL md pointer. Passing in NULL for the md parameter 
 * results in a NULL return and no digest calculation. 
 */
 
typedef uint32_t CC_LONG;       /* 32 bit unsigned integer */
typedef uint64_t CC_LONG64;     /* 64 bit unsigned integer */

/*** MD2 ***/

#define CC_MD2_DIGEST_LENGTH    16          /* digest length in bytes */
#define CC_MD2_BLOCK_BYTES      64          /* block size in bytes */
#define CC_MD2_BLOCK_LONG       (CC_MD2_BLOCK_BYTES / sizeof(CC_LONG))

typedef struct CC_MD2state_st
{
    int num;
    unsigned char data[CC_MD2_DIGEST_LENGTH];
    CC_LONG cksm[CC_MD2_BLOCK_LONG];
    CC_LONG state[CC_MD2_BLOCK_LONG];
} CC_MD2_CTX;

extern int CC_MD2_Init(CC_MD2_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_MD2_Update(CC_MD2_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_MD2_Final(unsigned char *md, CC_MD2_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern unsigned char *CC_MD2(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

/*** MD4 ***/

#define CC_MD4_DIGEST_LENGTH    16          /* digest length in bytes */
#define CC_MD4_BLOCK_BYTES      64          /* block size in bytes */
#define CC_MD4_BLOCK_LONG       (CC_MD4_BLOCK_BYTES / sizeof(CC_LONG))

typedef struct CC_MD4state_st
{
    CC_LONG A,B,C,D;
    CC_LONG Nl,Nh;
    CC_LONG data[CC_MD4_BLOCK_LONG];
    uint32_t num;
} CC_MD4_CTX;

extern int CC_MD4_Init(CC_MD4_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_MD4_Update(CC_MD4_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_MD4_Final(unsigned char *md, CC_MD4_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern unsigned char *CC_MD4(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);


/*** MD5 ***/

#define CC_MD5_DIGEST_LENGTH    16          /* digest length in bytes */
#define CC_MD5_BLOCK_BYTES      64          /* block size in bytes */
#define CC_MD5_BLOCK_LONG       (CC_MD5_BLOCK_BYTES / sizeof(CC_LONG))

typedef struct CC_MD5state_st
{
    CC_LONG A,B,C,D;
    CC_LONG Nl,Nh;
    CC_LONG data[CC_MD5_BLOCK_LONG];
    int num;
} CC_MD5_CTX;

extern int CC_MD5_Init(CC_MD5_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_MD5_Update(CC_MD5_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_MD5_Final(unsigned char *md, CC_MD5_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);


/*** SHA1 ***/

#define CC_SHA1_DIGEST_LENGTH   20          /* digest length in bytes */
#define CC_SHA1_BLOCK_BYTES     64          /* block size in bytes */
#define CC_SHA1_BLOCK_LONG      (CC_SHA1_BLOCK_BYTES / sizeof(CC_LONG))

typedef struct CC_SHA1state_st
{
    CC_LONG h0,h1,h2,h3,h4;
    CC_LONG Nl,Nh;
    CC_LONG data[CC_SHA1_BLOCK_LONG];
    int num;
} CC_SHA1_CTX;

extern int CC_SHA1_Init(CC_SHA1_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_SHA1_Update(CC_SHA1_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_SHA1_Final(unsigned char *md, CC_SHA1_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern unsigned char *CC_SHA1(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);


/*** SHA224 ***/
#define CC_SHA224_DIGEST_LENGTH     28          /* digest length in bytes */
#define CC_SHA224_BLOCK_BYTES       64          /* block size in bytes */

/* same context struct is used for SHA224 and SHA256 */
typedef struct CC_SHA256state_st
{   CC_LONG count[2];
    CC_LONG hash[8];
    CC_LONG wbuf[16];
} CC_SHA256_CTX;

extern int CC_SHA224_Init(CC_SHA256_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_SHA224_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_SHA224_Final(unsigned char *md, CC_SHA256_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern unsigned char *CC_SHA224(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);


/*** SHA256 ***/

#define CC_SHA256_DIGEST_LENGTH     32          /* digest length in bytes */
#define CC_SHA256_BLOCK_BYTES       64          /* block size in bytes */

extern int CC_SHA256_Init(CC_SHA256_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_SHA256_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_SHA256_Final(unsigned char *md, CC_SHA256_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern unsigned char *CC_SHA256(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);


/*** SHA384 ***/

#define CC_SHA384_DIGEST_LENGTH     48          /* digest length in bytes */
#define CC_SHA384_BLOCK_BYTES      128          /* block size in bytes */

/* same context struct is used for SHA384 and SHA512 */
typedef struct CC_SHA512state_st
{   CC_LONG64 count[2];
    CC_LONG64 hash[8];
    CC_LONG64 wbuf[16];
} CC_SHA512_CTX;

extern int CC_SHA384_Init(CC_SHA512_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_SHA384_Update(CC_SHA512_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_SHA384_Final(unsigned char *md, CC_SHA512_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern unsigned char *CC_SHA384(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);


/*** SHA512 ***/

#define CC_SHA512_DIGEST_LENGTH     64          /* digest length in bytes */
#define CC_SHA512_BLOCK_BYTES      128          /* block size in bytes */

extern int CC_SHA512_Init(CC_SHA512_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_SHA512_Update(CC_SHA512_CTX *c, const void *data, CC_LONG len)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern int CC_SHA512_Final(unsigned char *md, CC_SHA512_CTX *c)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

extern unsigned char *CC_SHA512(const void *data, CC_LONG len, unsigned char *md)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

/*
 * To use the above digest functions with existing code which uses
 * the corresponding openssl functions, #define the symbol 
 * COMMON_DIGEST_FOR_OPENSSL in your client code (BEFORE including
 * this file), and simply link against libSystem (or System.framework)
 * instead of libcrypto.
 *
 * You can *NOT* mix and match functions operating on a given data
 * type from the two implementations; i.e., if you do a CC_MD5_Init()
 * on a CC_MD5_CTX object, do not assume that you can do an openssl-style
 * MD5_Update() on that same context.
 */
 
#ifdef  COMMON_DIGEST_FOR_OPENSSL

#define MD2_DIGEST_LENGTH           CC_MD2_DIGEST_LENGTH
#define MD2_CTX                     CC_MD2_CTX
#define MD2_Init                    CC_MD2_Init
#define MD2_Update                  CC_MD2_Update
#define MD2_Final                   CC_MD2_Final

#define MD4_DIGEST_LENGTH           CC_MD4_DIGEST_LENGTH
#define MD4_CTX                     CC_MD4_CTX
#define MD4_Init                    CC_MD4_Init
#define MD4_Update                  CC_MD4_Update
#define MD4_Final                   CC_MD4_Final

#define MD5_DIGEST_LENGTH           CC_MD5_DIGEST_LENGTH
#define MD5_CTX                     CC_MD5_CTX
#define MD5_Init                    CC_MD5_Init
#define MD5_Update                  CC_MD5_Update
#define MD5_Final                   CC_MD5_Final

#define SHA_DIGEST_LENGTH           CC_SHA1_DIGEST_LENGTH
#define SHA_CTX                     CC_SHA1_CTX
#define SHA1_Init                   CC_SHA1_Init
#define SHA1_Update                 CC_SHA1_Update
#define SHA1_Final                  CC_SHA1_Final

#define SHA224_DIGEST_LENGTH        CC_SHA224_DIGEST_LENGTH
#define SHA256_CTX                  CC_SHA256_CTX
#define SHA224_Init                 CC_SHA224_Init
#define SHA224_Update               CC_SHA224_Update
#define SHA224_Final                CC_SHA224_Final

#define SHA256_DIGEST_LENGTH        CC_SHA256_DIGEST_LENGTH
#define SHA256_Init                 CC_SHA256_Init
#define SHA256_Update               CC_SHA256_Update
#define SHA256_Final                CC_SHA256_Final

#define SHA384_DIGEST_LENGTH        CC_SHA384_DIGEST_LENGTH
#define SHA512_CTX                  CC_SHA512_CTX
#define SHA384_Init                 CC_SHA384_Init
#define SHA384_Update               CC_SHA384_Update
#define SHA384_Final                CC_SHA384_Final

#define SHA512_DIGEST_LENGTH        CC_SHA512_DIGEST_LENGTH
#define SHA512_Init                 CC_SHA512_Init
#define SHA512_Update               CC_SHA512_Update
#define SHA512_Final                CC_SHA512_Final


#endif  /* COMMON_DIGEST_FOR_OPENSSL */

/*
 * In a manner similar to that described above for openssl 
 * compatibility, these macros can be used to provide compatiblity 
 * with legacy implementations of MD5 using the interface defined 
 * in RFC 1321.
 */
 
#ifdef  COMMON_DIGEST_FOR_RFC_1321

#define MD5_CTX                     CC_MD5_CTX
#define MD5Init                     CC_MD5_Init
#define MD5Update                   CC_MD5_Update
void MD5Final (unsigned char [16], MD5_CTX *)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

#endif  /* COMMON_DIGEST_FOR_RFC_1321 */

#ifdef __cplusplus
}
#endif

#endif  /* _CC_COMMON_DIGEST_H_ */

Changes to CommonCrypto/CommonHMAC.h.

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*!
	@header		CommonHMAC.h
	@abstract	Keyed Message Authentication Code (HMAC) functions.
 */
 
#ifndef	_CC_COMMON_HMAC_H_
#define _CC_COMMON_HMAC_H_

#include <CommonCrypto/CommonDigest.h>
#include <sys/types.h>
#include <Availability.h>

#ifdef __cplusplus
extern "C" {
#endif

/*!
	@enum		CCHmacAlgorithm
	@abstract	Algorithms implemented in this module.

	@constant	kCCHmacAlgSHA1		HMAC with SHA1 digest
	@constant	kCCHmacAlgMD5		HMAC with MD5 digest
	@constant	kCCHmacAlgSHA256	HMAC with SHA256 digest
	@constant	kCCHmacAlgSHA384	HMAC with SHA384 digest
	@constant	kCCHmacAlgSHA512	HMAC with SHA512 digest
	@constant	kCCHmacAlgSHA224	HMAC with SHA224 digest
 */
enum {
	kCCHmacAlgSHA1,
	kCCHmacAlgMD5,
	kCCHmacAlgSHA256,
	kCCHmacAlgSHA384,
	kCCHmacAlgSHA512,
	kCCHmacAlgSHA224
};
typedef uint32_t CCHmacAlgorithm;

/*!
	@typedef	CCHmacContext
	@abstract	HMAC context. 
 */
#define CC_HMAC_CONTEXT_SIZE	96	
typedef struct {
	uint32_t			ctx[CC_HMAC_CONTEXT_SIZE];
} CCHmacContext;

/*!
	@function	CCHmacInit
	@abstract	Initialize an CCHmacContext with provided raw key bytes.
	
	@param		ctx			An HMAC context.
	@param		algorithm	HMAC algorithm to perform. 
	@param		key			Raw key bytes.
	@param		keyLength	Length of raw key bytes; can be any 
							length including zero. 
 */
void CCHmacInit(
	CCHmacContext *ctx, 
	CCHmacAlgorithm algorithm,	
	const void *key,
    size_t keyLength)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);
            
	
/*!
	@function	CCHmacUpdate
	@abstract	Process some data.
	
	@param		ctx			An HMAC context.
	@param		data		Data to process.
	@param		dataLength	Length of data to process, in bytes.
	
	@discussion	This can be called multiple times.
 */
void CCHmacUpdate(
	CCHmacContext *ctx, 
	const void *data,
    size_t dataLength)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

	
/*!
	@function	CCHmacFinal
	@abstract	Obtain the final Message Authentication Code.
	
	@param		ctx			An HMAC context.
	@param		macOut		Destination of MAC; allocated by caller. 
	
	@discussion	The length of the MAC written to *macOut is the same as 
				the digest length associated with the HMAC algorithm:
	
				kCCHmacSHA1 : CC_SHA1_DIGEST_LENGTH
				
				kCCHmacMD5  : CC_MD5_DIGEST_LENGTH
 */
void CCHmacFinal(
	CCHmacContext *ctx, 
    void *macOut)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

	
/*
 * Stateless, one-shot HMAC function. 
 * Output is written to caller-supplied buffer, as in CCHmacFinal().
 */
void CCHmac(
	CCHmacAlgorithm algorithm,	/* kCCHmacSHA1, kCCHmacMD5 */
	const void *key,
	size_t keyLength,			/* length of key in bytes */
	const void *data,
	size_t dataLength,			/* length of data in bytes */
    void *macOut)               /* MAC written here */
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_NA);

#ifdef __cplusplus
}
#endif

#endif	/* _CC_COMMON_HMAC_H_ */







|
|


|











|
|

|
|
|
|
|
|


|
|
|
|
|
|




|
|

|

|



|
|
|
|
|
|
|
|


|
|
|

|

|

|
|
|
|
|
|
|
|


|
|

|

|

|
|
|
|
|
|
|
|
|
|
|
|


|

|

|





|
|
|
|
|

|





|
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*!
    @header     CommonHMAC.h
    @abstract   Keyed Message Authentication Code (HMAC) functions.
 */
 
#ifndef _CC_COMMON_HMAC_H_
#define _CC_COMMON_HMAC_H_

#include <CommonCrypto/CommonDigest.h>
#include <sys/types.h>
#include <Availability.h>

#ifdef __cplusplus
extern "C" {
#endif

/*!
    @enum       CCHmacAlgorithm
    @abstract   Algorithms implemented in this module.

    @constant   kCCHmacAlgSHA1      HMAC with SHA1 digest
    @constant   kCCHmacAlgMD5       HMAC with MD5 digest
    @constant   kCCHmacAlgSHA256    HMAC with SHA256 digest
    @constant   kCCHmacAlgSHA384    HMAC with SHA384 digest
    @constant   kCCHmacAlgSHA512    HMAC with SHA512 digest
    @constant   kCCHmacAlgSHA224    HMAC with SHA224 digest
 */
enum {
    kCCHmacAlgSHA1,
    kCCHmacAlgMD5,
    kCCHmacAlgSHA256,
    kCCHmacAlgSHA384,
    kCCHmacAlgSHA512,
    kCCHmacAlgSHA224
};
typedef uint32_t CCHmacAlgorithm;

/*!
    @typedef    CCHmacContext
    @abstract   HMAC context. 
 */
#define CC_HMAC_CONTEXT_SIZE    96  
typedef struct {
    uint32_t            ctx[CC_HMAC_CONTEXT_SIZE];
} CCHmacContext;

/*!
    @function   CCHmacInit
    @abstract   Initialize an CCHmacContext with provided raw key bytes.
    
    @param      ctx         An HMAC context.
    @param      algorithm   HMAC algorithm to perform. 
    @param      key         Raw key bytes.
    @param      keyLength   Length of raw key bytes; can be any 
                            length including zero. 
 */
void CCHmacInit(
    CCHmacContext *ctx, 
    CCHmacAlgorithm algorithm,  
    const void *key,
    size_t keyLength)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);
            
    
/*!
    @function   CCHmacUpdate
    @abstract   Process some data.
    
    @param      ctx         An HMAC context.
    @param      data        Data to process.
    @param      dataLength  Length of data to process, in bytes.
    
    @discussion This can be called multiple times.
 */
void CCHmacUpdate(
    CCHmacContext *ctx, 
    const void *data,
    size_t dataLength)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

    
/*!
    @function   CCHmacFinal
    @abstract   Obtain the final Message Authentication Code.
    
    @param      ctx         An HMAC context.
    @param      macOut      Destination of MAC; allocated by caller. 
    
    @discussion The length of the MAC written to *macOut is the same as 
                the digest length associated with the HMAC algorithm:
    
                kCCHmacSHA1 : CC_SHA1_DIGEST_LENGTH
                
                kCCHmacMD5  : CC_MD5_DIGEST_LENGTH
 */
void CCHmacFinal(
    CCHmacContext *ctx, 
    void *macOut)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

    
/*
 * Stateless, one-shot HMAC function. 
 * Output is written to caller-supplied buffer, as in CCHmacFinal().
 */
void CCHmac(
    CCHmacAlgorithm algorithm,  /* kCCHmacSHA1, kCCHmacMD5 */
    const void *key,
    size_t keyLength,           /* length of key in bytes */
    const void *data,
    size_t dataLength,          /* length of data in bytes */
    void *macOut)               /* MAC written here */
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

#ifdef __cplusplus
}
#endif

#endif  /* _CC_COMMON_HMAC_H_ */

Changes to CommonCrypto/CommonKeyDerivation.h.

20
21
22
23
24
25
26
27
28
29

30

31
32
33
34
35
36
37
38
39
40
41
42
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef _CC_PBKDF_H_
#define _CC_PBKDF_H_

#include <sys/types.h>
#include <sys/param.h>


#include <string.h>

#include <limits.h>
#include <stdlib.h>

#include <Availability.h>

#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>


#ifdef __cplusplus
extern "C" {
#endif







|
|
|
>
|
>


|
<
<







20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35


36
37
38
39
40
41
42
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef _CC_PBKDF_H_
#define _CC_PBKDF_H_

#include <sys/param.h>
#include <string.h>
#include <Availability.h>
#ifdef KERNEL
#include <machine/limits.h>
#else
#include <limits.h>
#include <stdlib.h>
#endif /* KERNEL */


#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>


#ifdef __cplusplus
extern "C" {
#endif
88
89
90
91
92
93
94
95
96

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
 
 * kCCPRFHmacAlgSHA1
 * kCCPRFHmacAlgSHA224
 * kCCPRFHmacAlgSHA256
 * kCCPRFHmacAlgSHA384
 * kCCPRFHmacAlgSHA512
 
 @result     kCCParamError can result from bad values for the password, salt, 
                and unwrapped key pointers as well as a bad value for the prf function.

 
 */

int 
CCKeyDerivationPBKDF( CCPBKDFAlgorithm algorithm, const char *password, size_t passwordLen,
                      const uint8_t *salt, size_t saltLen,
                      CCPseudoRandomAlgorithm prf, uint rounds, 
                      uint8_t *derivedKey, size_t derivedKeyLen)
                      __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*
 * All lengths are in bytes - not bits.
 */

/*
 







|
|
>








|







88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
 
 * kCCPRFHmacAlgSHA1
 * kCCPRFHmacAlgSHA224
 * kCCPRFHmacAlgSHA256
 * kCCPRFHmacAlgSHA384
 * kCCPRFHmacAlgSHA512
 
 @result     kCCParamError can result from bad values for the password, salt,
 	     and unwrapped key pointers as well as a bad value for the prf
	     function.
 
 */

int 
CCKeyDerivationPBKDF( CCPBKDFAlgorithm algorithm, const char *password, size_t passwordLen,
                      const uint8_t *salt, size_t saltLen,
                      CCPseudoRandomAlgorithm prf, uint rounds, 
                      uint8_t *derivedKey, size_t derivedKeyLen)
                      __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*
 * All lengths are in bytes - not bits.
 */

/*
 
125
126
127
128
129
130
131
132
133
134
135
136
137
138
 @result the number of iterations to use for the desired processing time.
 
 */

uint
CCCalibratePBKDF(CCPBKDFAlgorithm algorithm, size_t passwordLen, size_t saltLen,
                 CCPseudoRandomAlgorithm prf, size_t derivedKeyLen, uint32_t msec)
                 __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

#ifdef __cplusplus
}
#endif

#endif  /* _CC_PBKDF_H_ */







|






126
127
128
129
130
131
132
133
134
135
136
137
138
139
 @result the number of iterations to use for the desired processing time.
 
 */

uint
CCCalibratePBKDF(CCPBKDFAlgorithm algorithm, size_t passwordLen, size_t saltLen,
                 CCPseudoRandomAlgorithm prf, size_t derivedKeyLen, uint32_t msec)
                 __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

#ifdef __cplusplus
}
#endif

#endif  /* _CC_PBKDF_H_ */

Changes to CommonCrypto/CommonSymmetricKeywrap.h.

25
26
27
28
29
30
31



32
33

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#define _CC_SYMKEYWRAP_H_

#include <sys/types.h>
#include <sys/param.h>
#include <stdint.h>

#include <string.h>



#include <limits.h>
#include <stdlib.h>

#include <Availability.h>


#ifdef __cplusplus
extern "C" {
#endif
    
enum {
    kCCWRAPAES = 1,
};

extern const uint8_t *CCrfc3394_iv  __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
extern const size_t CCrfc3394_ivLen  __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

typedef uint32_t CCWrappingAlgorithm;

/*!
 @function  CCSymmetricKeyWrap
 @abstract  Wrap a symmetric key with a Key Encryption Key (KEK).  
 







>
>
>


>











|
|







25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#define _CC_SYMKEYWRAP_H_

#include <sys/types.h>
#include <sys/param.h>
#include <stdint.h>

#include <string.h>
#ifdef KERNEL
#include <machine/limits.h>
#else
#include <limits.h>
#include <stdlib.h>
#endif /* KERNEL */
#include <Availability.h>


#ifdef __cplusplus
extern "C" {
#endif
    
enum {
    kCCWRAPAES = 1,
};

extern const uint8_t *CCrfc3394_iv  __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0);
extern const size_t CCrfc3394_ivLen  __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_5_0);

typedef uint32_t CCWrappingAlgorithm;

/*!
 @function  CCSymmetricKeyWrap
 @abstract  Wrap a symmetric key with a Key Encryption Key (KEK).  
 
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92

int  
CCSymmetricKeyWrap( CCWrappingAlgorithm algorithm, 
                   const uint8_t *iv, const size_t ivLen,
                   const uint8_t *kek, size_t kekLen,
                   const uint8_t *rawKey, size_t rawKeyLen,
                   uint8_t  *wrappedKey, size_t *wrappedKeyLen)
                   __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*!
 @function  CCSymmetricKeyUnwrap
 @abstract  Unwrap a symmetric key with a Key Encryption Key (KEK).  
 
 @param algorithm       Currently only AES Keywrapping (rfc3394) is available 
                        via kCCWRAPAES







|







82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

int  
CCSymmetricKeyWrap( CCWrappingAlgorithm algorithm, 
                   const uint8_t *iv, const size_t ivLen,
                   const uint8_t *kek, size_t kekLen,
                   const uint8_t *rawKey, size_t rawKeyLen,
                   uint8_t  *wrappedKey, size_t *wrappedKeyLen)
                   __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 @function  CCSymmetricKeyUnwrap
 @abstract  Unwrap a symmetric key with a Key Encryption Key (KEK).  
 
 @param algorithm       Currently only AES Keywrapping (rfc3394) is available 
                        via kCCWRAPAES
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

int  
CCSymmetricKeyUnwrap( CCWrappingAlgorithm algorithm,
                     const uint8_t *iv, const size_t ivLen,
                     const uint8_t *kek, size_t kekLen,
                     const uint8_t  *wrappedKey, size_t wrappedKeyLen,
                     uint8_t  *rawKey, size_t *rawKeyLen)
                     __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*!
 @function  CCSymmetricWrappedSize
 @abstract  Determine the buffer size required to hold a key wrapped with 
            CCAESKeyWrap().  
 
 @param     algorithm       Currently only AES Keywrapping (rfc3394) is 
                            available via kCCWRAPAES
 @param     rawKeyLen       The length of the key in bytes.
 @result    The length of the resulting wrapped key.
 */

size_t
CCSymmetricWrappedSize( CCWrappingAlgorithm algorithm, size_t rawKeyLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*!
 @function  CCSymmetricUnwrappedSize
 @abstract  Determine the buffer size required to hold a key unwrapped with 
            CCAESKeyUnwrap().  
 
 @param     algorithm       Currently only AES Keywrapping (rfc3394) is 
                            available via kCCWRAPAES
 @param     wrappedKeyLen   The length of the wrapped key in bytes.
 @result    The length of the resulting raw key.
 */

size_t
CCSymmetricUnwrappedSize( CCWrappingAlgorithm algorithm, size_t wrappedKeyLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

#ifdef __cplusplus
}
#endif

#endif /* _CC_SYMKEYWRAP_H_ */







|














|














|






118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161

int  
CCSymmetricKeyUnwrap( CCWrappingAlgorithm algorithm,
                     const uint8_t *iv, const size_t ivLen,
                     const uint8_t *kek, size_t kekLen,
                     const uint8_t  *wrappedKey, size_t wrappedKeyLen,
                     uint8_t  *rawKey, size_t *rawKeyLen)
                     __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 @function  CCSymmetricWrappedSize
 @abstract  Determine the buffer size required to hold a key wrapped with 
            CCAESKeyWrap().  
 
 @param     algorithm       Currently only AES Keywrapping (rfc3394) is 
                            available via kCCWRAPAES
 @param     rawKeyLen       The length of the key in bytes.
 @result    The length of the resulting wrapped key.
 */

size_t
CCSymmetricWrappedSize( CCWrappingAlgorithm algorithm, size_t rawKeyLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 @function  CCSymmetricUnwrappedSize
 @abstract  Determine the buffer size required to hold a key unwrapped with 
            CCAESKeyUnwrap().  
 
 @param     algorithm       Currently only AES Keywrapping (rfc3394) is 
                            available via kCCWRAPAES
 @param     wrappedKeyLen   The length of the wrapped key in bytes.
 @result    The length of the resulting raw key.
 */

size_t
CCSymmetricUnwrappedSize( CCWrappingAlgorithm algorithm, size_t wrappedKeyLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

#ifdef __cplusplus
}
#endif

#endif /* _CC_SYMKEYWRAP_H_ */

Deleted Configurations/CommonCrypto_base.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
//
//  CommonCrypto_base.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the shared settings for all targets of the
// CommonCrypto XCode Project

// **************************************************************************
// * Begin Project Section
// **************************************************************************

PRODUCT_NAME = commonCrypto

ARCHS = $(NATIVE_ARCH) $(ARCHS_STANDARD_64_BIT) arm

// Minimum OS version
MACOSX_DEPLOYMENT_TARGET =

BUILD_VARIANTS = normal profile debug

//
// Directory Names
//

CC_PATH_BASE = $(PROJECT_DIR)
CC_PATH_XCCONFIGS = $(CC_PATH_BASE)/Configurations
CC_PATH_PUBLIC_HEADERS = $(CC_PATH_BASE)/CommonCrypto
CC_PATH_SOURCE = $(CC_PATH_BASE)/Source

// This REALLY should come from an include from a truly global XCCONFIG file
// This can easily be retrofitted when we have more projects using this 
// system

CONFIGURATION_BUILD_DIR = $(BUILD_DIR)/$(CONFIGURATION)

PUBLIC_HEADERS_FOLDER_PATH = /usr/include/CommonCrypto
PRIVATE_HEADERS_FOLDER_PATH = /usr/local/include/CommonCrypto
HEADER_SEARCH_PATHS =
USER_HEADER_SEARCH_PATHS = $(CC_PATH_SOURCE)

// Include user path in header search
ALWAYS_SEARCH_USER_PATHS = YES

// Deal with "installation"  This may not be necessary but it will not hurt either
INSTALL_PATH = /usr/lib/system
INSTALL_OWNER = root
INSTALL_GROUP = wheel

// Deal with project versioning
CURRENT_PROJECT_VERSION = $(RC_ProjectSourceVersion)
VERSIONING_SYSTEM = apple-generic
VERSION_INFO_BUILDER = $(USER)

DYLIB_COMPATIBILITY_VERSION = 1
DYLIB_CURRENT_VERSION = $(RC_ProjectSourceVersion)

EXECUTABLE_PREFIX = lib

// **************************************************************************
// * End Project Section
// **************************************************************************

// **************************************************************************
// * Begin Code Signing Section
// **************************************************************************

CODE_SIGN_IDENTITY = 
CODE_SIGN_RESOURCE_RULES_PATH = 
OTHER_CODE_SIGN_FLAGS =

// **************************************************************************
// * End Code Signing Section
// **************************************************************************

// **************************************************************************
// * Begin Compiler Section
// **************************************************************************

// Compiler version: I would LOVE to use CLANG but CLANG currently does
// not support C++ very well
GCC_VERSION = com.apple.compilers.llvmgcc42

GCC_C_LANGUAGE_STANDARD = gnu99

// Debugging information.  
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym

// Tuning
GCC_MODEL_TUNING = G4

// GCC Flags
GCC_AUTO_VECTORIZATION = NO

// Ensure position independent code generation
GCC_DYNAMIC_NO_PIC = NO
GCC_ENABLE_FIX_AND_CONTINUE = NO
GCC_ENABLE_KERNEL_DEVELOPMENT = NO
GCC_ENABLE_SSE3_EXTENSIONS = NO
GCC_ENABLE_SSE41_EXTENSIONS = NO
GCC_ENABLE_SSE42_EXTENSIONS = NO
GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS = NO
GCC_ENABLE_SYMBOL_SEPARATION = NO
GCC_FAST_MATH = NO

// Test Coverage
GCC_GENERATE_TEST_COVERAGE_FILES = NO
GCC_INLINES_ARE_PRIVATE_EXTERN = NO
GCC_INSTRUMENT_PROGRAM_FLOW_ARCS = NO
GCC_MODEL_PPC64 = NO
GCC_NO_COMMON_BLOCKS = NO

// Objective-C++ destructors
GCC_OBJC_CALL_CXX_CDTORS = NO
GCC_STRICT_ALIASING = NO
GCC_SYMBOLS_PRIVATE_EXTERN = YES
GCC_UNROLL_LOOPS = NO
GCC_FEEDBACK_DIRECTED_OPTIMIZATION = off

GCC_FAST_OBJC_DISPATCH = YES
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
GCC_REUSE_STRINGS = YES
GCC_THREADSAFE_STATICS = YES
GCC_DEBUGGING_SYMBOLS = default

// Garbage collection
GCC_ENABLE_OBJC_GC = unsupported

// Language Flags

// Prefix file Should we have one of these?
GCC_PRECOMPILE_PREFIX_HEADER = NO
GCC_PREFIX_HEADER = 

GCC_ALTIVEC_EXTENSIONS = NO
GCC_CHAR_IS_UNSIGNED_CHAR = NO
GCC_CHECK_RETURN_VALUE_OF_OPERATOR_NEW = NO
GCC_ENABLE_FLOATING_POINT_LIBRARY_CALLS = NO
GCC_ENABLE_TRIGRAPHS = NO
GCC_FORCE_CPU_SUBTYPE_ALL = NO
GCC_INCREASE_PRECOMPILED_HEADER_SHARING = NO
GCC_ONE_BYTE_BOOL = NO
GCC_SHORT_ENUMS = NO
GCC_USE_INDIRECT_FUNCTION_CALLS = NO
GCC_USE_REGISTER_FUNCTION_CALLS = NO
GCC_CW_ASM_SYNTAX = YES
GCC_ENABLE_ASM_KEYWORD = YES
GCC_ENABLE_BUILTIN_FUNCTIONS = YES
GCC_ENABLE_CPP_EXCEPTIONS = YES
GCC_ENABLE_CPP_RTTI = YES
GCC_ENABLE_OBJC_EXCEPTIONS = YES
GCC_ENABLE_PASCAL_STRINGS = YES
GCC_LINK_WITH_DYNAMIC_LIBRARIES = YES
GCC_USE_STANDARD_INCLUDE_SEARCHING = YES

// WARNINGS
//
// I am including most warnings in this list, If problems occur they can
// be commented out or changed to be NO

WARNING_CFLAGS = -Wall

GCC_TREAT_WARNINGS_AS_ERRORS = YES

// Should any of these be YES?
GCC_WARN_PEDANTIC = NO


GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES 
GCC_TREAT_NONCONFORMANT_CODE_ERRORS_AS_WARNINGS = YES
GCC_WARN_64_TO_32_BIT_CONVERSION = YES
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES
GCC_WARN_ABOUT_MISSING_NEWLINE = YES
GCC_WARN_EFFECTIVE_CPLUSPLUS_VIOLATIONS = YES
GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES
GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES
GCC_WARN_INHIBIT_ALL_WARNINGS = YES
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES
GCC_WARN_MISSING_PARENTHESES = YES
GCC_WARN_MULTIPLE_DEFINITION_TYPES_FOR_SELECTOR = YES
GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES
GCC_WARN_PEDANTIC = YES
GCC_WARN_PROTOTYPE_CONVERSION = YES
GCC_WARN_SHADOW = YES
GCC_WARN_SIGN_COMPARE = YES
GCC_WARN_STRICT_SELECTOR_MATCH = YES
GCC_WARN_UNDECLARED_SELECTOR = YES
GCC_WARN_UNKNOWN_PRAGMAS = YES
GCC_WARN_UNUSED_PARAMETER = YES
GCC_WARN_UNUSED_VARIABLE = YES

GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = YES
GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = YES
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES
GCC_WARN_ABOUT_POINTER_SIGNEDNESS = YES
GCC_WARN_ABOUT_RETURN_TYPE = YES
GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL = YES
GCC_WARN_CHECK_SWITCH_STATEMENTS = YES
GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES
GCC_WARN_UNINITIALIZED_AUTOS = YES
GCC_WARN_UNUSED_FUNCTION = YES
GCC_WARN_UNUSED_LABEL = YES

OTHER_CFLAGS = -fstack-protector-all -Wstack-protector -DSHA256_USE_ASSEMBLY=1

GCC_PREPROCESSOR_DEFINITIONS = _FORTIFY_SOURCE=2

// **************************************************************************
// * End Compiler Section
// **************************************************************************

// **************************************************************************
// * Begin Linker Section
// **************************************************************************

// OTHER_LDFLAGS
// Set up a three tiered set of variables for linker flags
// This will allow for adding linker flags and not run into
// the XCCONFIG "bug" of not being able to set FOO = $(FOO) bar


DEAD_CODE_STRIPPING = YES
GENERATE_MASTER_OBJECT_FILE = NO
KEEP_PRIVATE_EXTERNS = NO

// Should this be yes?
LD_GENERATE_MAP_FILE = NO

LINKER_DISPLAYS_MANGLED_NAMES = NO
PRESERVE_DEAD_CODE_INITS_AND_TERMS = NO
SEPARATE_SYMBOL_EDIT = NO
LINK_WITH_STANDARD_LIBRARIES = YES
PREBINDING = NO

// **************************************************************************
// * End Linker Section
// **************************************************************************

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































































































































































































































Deleted Configurations/CommonCrypto_deployment.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//
//  CommonCrypto_deployment.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the deployment settings for all targets

#include "CommonCrypto_base.xcconfig"

// Debug build set optimization level to s
GCC_OPTIMIZATION_LEVEL = s

GCC_PREPROCESSOR_DEFINITIONS_PROJECT = NDEBUG

COPY_PHASE_STRIP = YES

WARNING_CFLAGS = -Wall
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































Deleted Configurations/CommonCrypto_development.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//
//  CommonCrypto_debug.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the development settings for all targets

#include "CommonCrypto_base.xcconfig"

// Debug build set optimization level to 1
GCC_OPTIMIZATION_LEVEL = 0

// This was at odds with the base defining GCC_PREPROCESSOR_DEFINITIONS - it got
// overidden by it.  I copied the base value (_FORTIFY_SOURCE=2) and added DEBUG
// to create a debug level override for GCC_PREPROCESSOR_DEFINITIONS

// GCC_PREPROCESSOR_DEFINITIONS_PROJECT = DEBUG
GCC_PREPROCESSOR_DEFINITIONS = _FORTIFY_SOURCE=2 DEBUG

COPY_PHASE_STRIP = NO

WARNING_CFLAGS = -Wall

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































Deleted Configurations/CommonCrypto_dynamic.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//
//  CommonCrypto_dynamic.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file defines settings that specific for dynamic libraries

STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = Dynamic

EXECUTABLE_EXTENSION = dylib

LIBRARY_STYLE = Dynamic
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























Deleted Configurations/CommonCrypto_dynamic_deployment.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
//
//  CommonCrypto_dynamic_deployment.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file is for the deployment version of the dynamic CommonCrypto Library

#include "CommonCrypto_deployment.xcconfig"
#include "CommonCrypto_dynamic.xcconfig"
<
<
<
<
<
<
<
<
<
<
<
<
























Deleted Configurations/CommonCrypto_dynamic_development.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
//
//  CommonCrypto_dynamic_development.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file is for the development version of the dynamic CommonCrypto Library

#include "CommonCrypto_development.xcconfig"
#include "CommonCrypto_dynamic.xcconfig"
<
<
<
<
<
<
<
<
<
<
<
<
























Deleted Configurations/CommonCrypto_localtest.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
//
//  CommonCrypto_unittest_base.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

ARCHS = $(NATIVE_ARCH) $(ARCHS_STANDARD_64_BIT)
GCC_OPTIMIZATION_LEVEL = s
GCC_PREPROCESSOR_DEFINITIONS = _FORTIFY_SOURCE=2 DEBUG
COPY_PHASE_STRIP = NO
WARNING_CFLAGS = -Wall
<
<
<
<
<
<
<
<
<
<
<
<
<


























Deleted Configurations/CommonCrypto_static.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//
//  CommonCrypto_static.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file defines settings that specific for static libraries

STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = Dynamic

EXECUTABLE_EXTENSION = a

LIBRARY_STYLE = Static
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























Deleted Configurations/CommonCrypto_static_deployment.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
//
//  CommonCrypto_static_deployment.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file is for the deployment version of the static CommonCrypto Library

#include "CommonCrypto_deployment.xcconfig"
#include "CommonCrypto_static.xcconfig"
<
<
<
<
<
<
<
<
<
<
<
<
























Deleted Configurations/CommonCrypto_static_development.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
//
//  CommonCrypto_static_development.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file is for the development version of the static CommonCrypto Library

#include "CommonCrypto_development.xcconfig"
#include "CommonCrypto_static.xcconfig"
<
<
<
<
<
<
<
<
<
<
<
<
























Deleted Configurations/CommonCrypto_umbrellaMember.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//
//  CommonCrypto_umbrellaMember.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines settings that specific for umbrella member libraries

OTHER_LDFLAGS = -Wl -umbrella System -allowable_client otest -allowable_client CommonCryptoUnitTest -allowable_client XTSTest -allowable_client CBCTest

STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = Dynamic

EXECUTABLE_EXTENSION = dylib

LIBRARY_STYLE = Dynamic
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































Deleted Configurations/CommonCrypto_umbrellaMember_deployment.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
//
//  CommonCrypto_umbrellaMember_deployment.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//


// This XCCONFIG file is for the deployment version of the umbrella member for System CommonCrypto Library

#include "CommonCrypto_deployment.xcconfig"
#include "CommonCrypto_umbrellaMember.xcconfig"
<
<
<
<
<
<
<
<
<
<
<
<
<


























Deleted Configurations/CommonCrypto_umbrellaMember_development.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
//
//  CommonCrypto_umbrellaMember_development.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file is for the development version of the umbrella member for System CommonCrypto Library

#include "CommonCrypto_development.xcconfig"
#include "CommonCrypto_umbrellaMember.xcconfig"
<
<
<
<
<
<
<
<
<
<
<
<
























Deleted Configurations/CommonCrypto_unitTest_dynamic_development.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
//
//  CommonCrypto_unitTest_dynamic_development.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#include "CommonCrypto_unittest_development.xcconfig"

LIBRARY_STYLE = Dynamic
<
<
<
<
<
<
<
<
<
<
<






















Deleted Configurations/CommonCrypto_unittest_base.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//
//  CommonCrypto_unittest_base.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the shared settings for all unit test targets of the
// CommonCrypto XCode Project


// **************************************************************************
// * Begin Project Section
// **************************************************************************

CC_PATH_BASE = $(PROJECT_DIR)
CC_PATH_UNIT_TEST_SOURCE = $(CC_PATH_BASE)/UnitTestSource

PRODUCT_NAME = CommonCryptoUnitTest

ARCHS = $(NATIVE_ARCH) $(ARCHS_STANDARD_64_BIT)

OTHER_LDFLAGS = -framework Cocoa -framework SenTestingKit

WRAPPER_EXTENSION = octest

FRAMEWORK_SEARCH_PATHS = $(DEVELOPER_FRAMEWORKS_DIR)

GCC_PREFIX_HEADER = $(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h

INFOPLIST_FILE = $(CC_PATH_UNIT_TEST_SOURCE)/CommonCryptoUnitTests-Info.plist

OBJC_DISABLE_GC = NO

// **************************************************************************
// * End Project Section
// **************************************************************************

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































Deleted Configurations/CommonCrypto_unittest_deployment.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//
//  CommonCrypto_unittest_base.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the deployment setting for  unit test targets of the
// CommonCrypto XCode Project

#include "CommonCrypto_unittest_base.xcconfig"

GCC_OPTIMIZATION_LEVEL = s

GCC_PREPROCESSOR_DEFINITIONS_PROJECT = NDEBUG

COPY_PHASE_STRIP = YES

WARNING_CFLAGS = -Wall
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































Deleted Configurations/CommonCrypto_unittest_development.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//
//  CommonCrypto_unittest_base.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the development setting for  unit test targets of the
// CommonCrypto XCode Project

#include "CommonCrypto_unittest_base.xcconfig"

GCC_OPTIMIZATION_LEVEL = 0

GCC_PREPROCESSOR_DEFINITIONS_PROJECT = DEBUG

COPY_PHASE_STRIP = NO

WARNING_CFLAGS = -Wall
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































Deleted Configurations/CommonCrypto_unittest_dynamic_deployment.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
//
//  CommonCrypto_unittest_dynamic_deployment.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#include "CommonCrypto_unittest_deployment.xcconfig"

LIBRARY_STYLE = Dynamic
<
<
<
<
<
<
<
<
<
<
<






















Deleted Configurations/CommonCrypto_unittest_static_deployment.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
//
//  CommonCrypto_unittest_static_deployment.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#include "CommonCrypto_unittest_deployment.xcconfig"

LIBRARY_STYLE = Static
<
<
<
<
<
<
<
<
<
<
<






















Deleted Configurations/CommonCrypto_unittest_static_development.xcconfig.

1
2
3
4
5
6
7
8
9
10
11
//
//  CommonCrypto_unittest_static_development.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#include "CommonCrypto_unittest_development.xcconfig"

LIBRARY_STYLE = Static
<
<
<
<
<
<
<
<
<
<
<






















Added Configurations/components/CC_base.xcconfig.



























































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
//
//  CommonCrypto_base.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the shared settings for all targets of the
// CommonCrypto XCode Project

// **************************************************************************
// * Begin Project Section
// **************************************************************************


ARCHS = $(NATIVE_ARCH) $(ARCHS_STANDARD_64_BIT) arm

// Minimum OS version
MACOSX_DEPLOYMENT_TARGET =

BUILD_VARIANTS = normal profile debug

//
// Directory Names
//

CC_PATH_BASE = $(PROJECT_DIR)
CC_PATH_XCCONFIGS = $(CC_PATH_BASE)/Configurations
CC_PATH_PUBLIC_HEADERS = $(CC_PATH_BASE)/CommonCrypto
CC_PATH_SOURCE = $(CC_PATH_BASE)/Source

// This REALLY should come from an include from a truly global XCCONFIG file
// This can easily be retrofitted when we have more projects using this 
// system

CONFIGURATION_BUILD_DIR = $(BUILD_DIR)/$(CONFIGURATION)

PUBLIC_HEADERS_FOLDER_PATH = /usr/include/CommonCrypto
PRIVATE_HEADERS_FOLDER_PATH = /usr/local/include/CommonCrypto
HEADER_SEARCH_PATHS =
// USER_HEADER_SEARCH_PATHS = $(CC_PATH_SOURCE)

// Include user path in header search
ALWAYS_SEARCH_USER_PATHS = YES

// Deal with "installation"  This may not be necessary but it will not hurt either
INSTALL_PATH = /usr/lib/system
INSTALL_OWNER = root
INSTALL_GROUP = wheel

// Deal with project versioning
MYVERSION = 50000
CURRENT_PROJECT_VERSION = $(MYVERSION)
VERSIONING_SYSTEM = apple-generic
VERSION_INFO_BUILDER = $(USER)

DYLIB_COMPATIBILITY_VERSION = 1
DYLIB_CURRENT_VERSION = $(MYVERSION)

EXECUTABLE_PREFIX = lib

// **************************************************************************
// * End Project Section
// **************************************************************************

// **************************************************************************
// * Begin Code Signing Section
// **************************************************************************

CODE_SIGN_IDENTITY = 
CODE_SIGN_RESOURCE_RULES_PATH = 
OTHER_CODE_SIGN_FLAGS =

// **************************************************************************
// * End Code Signing Section
// **************************************************************************

// **************************************************************************
// * Begin Compiler Section
// **************************************************************************

// Compiler version: Unset - setting this can cause problems between build
// trains.
GCC_VERSION = com.apple.compilers.llvm.clang.1_0

// Debugging information.  
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym

// Tuning
GCC_MODEL_TUNING = G4

// GCC Flags
GCC_AUTO_VECTORIZATION = NO

// Ensure position independent code generation
GCC_DYNAMIC_NO_PIC = NO
GCC_ENABLE_FIX_AND_CONTINUE = NO
GCC_ENABLE_KERNEL_DEVELOPMENT = NO
GCC_ENABLE_SSE3_EXTENSIONS = NO
GCC_ENABLE_SSE41_EXTENSIONS = NO
GCC_ENABLE_SSE42_EXTENSIONS = NO
GCC_ENABLE_SUPPLEMENTAL_SSE3_INSTRUCTIONS = NO
GCC_ENABLE_SYMBOL_SEPARATION = NO
GCC_FAST_MATH = NO

// Test Coverage
GCC_GENERATE_TEST_COVERAGE_FILES = NO
GCC_INLINES_ARE_PRIVATE_EXTERN = NO
GCC_INSTRUMENT_PROGRAM_FLOW_ARCS = NO
GCC_MODEL_PPC64 = NO
GCC_NO_COMMON_BLOCKS = NO

// Objective-C++ destructors
GCC_OBJC_CALL_CXX_CDTORS = NO
GCC_STRICT_ALIASING = NO
GCC_SYMBOLS_PRIVATE_EXTERN = YES
GCC_UNROLL_LOOPS = NO
GCC_FEEDBACK_DIRECTED_OPTIMIZATION = off

GCC_FAST_OBJC_DISPATCH = YES
GCC_GENERATE_DEBUGGING_SYMBOLS = YES
GCC_REUSE_STRINGS = YES
GCC_THREADSAFE_STATICS = YES
GCC_DEBUGGING_SYMBOLS = default

// Garbage collection
GCC_ENABLE_OBJC_GC = unsupported

// Language Flags

// Prefix file Should we have one of these?
GCC_PRECOMPILE_PREFIX_HEADER = NO
GCC_PREFIX_HEADER = 

GCC_ALTIVEC_EXTENSIONS = NO
GCC_CHAR_IS_UNSIGNED_CHAR = NO
GCC_CHECK_RETURN_VALUE_OF_OPERATOR_NEW = NO
GCC_ENABLE_FLOATING_POINT_LIBRARY_CALLS = NO
GCC_ENABLE_TRIGRAPHS = NO
GCC_FORCE_CPU_SUBTYPE_ALL = NO
GCC_INCREASE_PRECOMPILED_HEADER_SHARING = NO
GCC_ONE_BYTE_BOOL = NO
GCC_SHORT_ENUMS = NO
GCC_USE_INDIRECT_FUNCTION_CALLS = NO
GCC_USE_REGISTER_FUNCTION_CALLS = NO
GCC_CW_ASM_SYNTAX = YES
GCC_ENABLE_ASM_KEYWORD = YES
GCC_ENABLE_BUILTIN_FUNCTIONS = YES
GCC_ENABLE_CPP_EXCEPTIONS = YES
GCC_ENABLE_CPP_RTTI = YES
GCC_ENABLE_OBJC_EXCEPTIONS = YES
GCC_ENABLE_PASCAL_STRINGS = YES
GCC_LINK_WITH_DYNAMIC_LIBRARIES = YES
GCC_USE_STANDARD_INCLUDE_SEARCHING = YES

// WARNINGS
//
// I am including most warnings in this list, If problems occur they can
// be commented out or changed to be NO

WARNING_CFLAGS = -Wall

GCC_TREAT_WARNINGS_AS_ERRORS = YES

// Should any of these be YES?
GCC_WARN_PEDANTIC = NO


GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES 
GCC_TREAT_NONCONFORMANT_CODE_ERRORS_AS_WARNINGS = YES
GCC_WARN_64_TO_32_BIT_CONVERSION = YES
GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES
GCC_WARN_ABOUT_MISSING_NEWLINE = YES
GCC_WARN_EFFECTIVE_CPLUSPLUS_VIOLATIONS = YES
GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES
GCC_WARN_HIDDEN_VIRTUAL_FUNCTIONS = YES
GCC_WARN_INHIBIT_ALL_WARNINGS = YES
GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES
GCC_WARN_MISSING_PARENTHESES = YES
GCC_WARN_MULTIPLE_DEFINITION_TYPES_FOR_SELECTOR = YES
GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES
GCC_WARN_PROTOTYPE_CONVERSION = YES
GCC_WARN_SHADOW = YES
GCC_WARN_SIGN_COMPARE = YES
GCC_WARN_STRICT_SELECTOR_MATCH = YES
GCC_WARN_UNDECLARED_SELECTOR = YES
GCC_WARN_UNKNOWN_PRAGMAS = YES
GCC_WARN_UNUSED_PARAMETER = YES
GCC_WARN_UNUSED_VARIABLE = YES

GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = YES
GCC_WARN_ABOUT_INVALID_OFFSETOF_MACRO = YES
GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES
GCC_WARN_ABOUT_POINTER_SIGNEDNESS = YES
GCC_WARN_ABOUT_RETURN_TYPE = YES
GCC_WARN_ALLOW_INCOMPLETE_PROTOCOL = YES
GCC_WARN_CHECK_SWITCH_STATEMENTS = YES
GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES
GCC_WARN_UNINITIALIZED_AUTOS = YES
GCC_WARN_UNUSED_FUNCTION = YES
GCC_WARN_UNUSED_LABEL = YES


GCC_PREPROCESSOR_DEFINITIONS = _FORTIFY_SOURCE=2

// **************************************************************************
// * End Compiler Section
// **************************************************************************

// **************************************************************************
// * Begin Linker Section
// **************************************************************************

// OTHER_LDFLAGS
// Set up a three tiered set of variables for linker flags
// This will allow for adding linker flags and not run into
// the XCCONFIG "bug" of not being able to set FOO = $(FOO) bar


DEAD_CODE_STRIPPING = YES
GENERATE_MASTER_OBJECT_FILE = NO
KEEP_PRIVATE_EXTERNS = NO

// Should this be yes?
LD_GENERATE_MAP_FILE = NO

LINKER_DISPLAYS_MANGLED_NAMES = NO
PRESERVE_DEAD_CODE_INITS_AND_TERMS = NO
SEPARATE_SYMBOL_EDIT = NO
LINK_WITH_STANDARD_LIBRARIES = YES
PREBINDING = NO

// **************************************************************************
// * End Linker Section
// **************************************************************************

Added Configurations/components/CC_deployment.xcconfig.









































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//
//  CommonCrypto_deployment.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the deployment settings for all targets

#include "CC_base.xcconfig"

// Debug build set optimization level to s
GCC_OPTIMIZATION_LEVEL = s

GCC_PREPROCESSOR_DEFINITIONS_PROJECT = NDEBUG

COPY_PHASE_STRIP = YES

WARNING_CFLAGS = -Wall

Added Configurations/components/CC_development.xcconfig.





















































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//
//  CommonCrypto_debug.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the development settings for all targets

#include "CC_base.xcconfig"

// Debug build set optimization level to 1
GCC_OPTIMIZATION_LEVEL = 0

// This was at odds with the base defining GCC_PREPROCESSOR_DEFINITIONS - it got
// overidden by it.  I copied the base value (_FORTIFY_SOURCE=2) and added DEBUG
// to create a debug level override for GCC_PREPROCESSOR_DEFINITIONS

// GCC_PREPROCESSOR_DEFINITIONS_PROJECT = DEBUG
GCC_PREPROCESSOR_DEFINITIONS = _FORTIFY_SOURCE=2 DEBUG

COPY_PHASE_STRIP = NO

WARNING_CFLAGS = -Wall

Added Configurations/components/CC_dynamic.xcconfig.































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//
//  CommonCrypto_dynamic.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file defines settings that specific for dynamic libraries

STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = Dynamic

EXECUTABLE_EXTENSION = dylib

LIBRARY_STYLE = Dynamic

Added Configurations/components/CC_dynamic_deployment.xcconfig.

























>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
//
//  CC_dynamic_deployment.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file is for the deployment version of the dynamic CommonCrypto Library

#include "CC_deployment.xcconfig"
#include "CC_dynamic.xcconfig"

Added Configurations/components/CC_dynamic_development.xcconfig.

























>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
//
//  CC_dynamic_development.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file is for the development version of the dynamic CommonCrypto Library

#include "CC_development.xcconfig"
#include "CC_dynamic.xcconfig"

Added Configurations/components/CC_kernel.xcconfig.













































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//
//  CC_kernel_development.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the settings for kernel kext targets

GCC_ENABLE_KERNEL_DEVELOPMENT = YES
KERNEL_MODULE = YES
WRAPPER_EXTENSION = kext

// GCC_WARN_PEDANTIC is a problem for non-ISO compliant kernel headers
GCC_WARN_PEDANTIC = NO
DEAD_CODE_STRIPPING = NO

// Standard paths for kexts
INSTALL_PATH = "$(SYSTEM_LIBRARY_DIR)/Extensions"
PRIVATE_HEADERS_FOLDER_PATH = "$(KEXT_FRAMEWORK)/Contents/PrivateHeaders/$(KEXT_FAMILY_NAME)"
PUBLIC_HEADERS_FOLDER_PATH = "$(KEXT_FRAMEWORK)/Contents/Headers/$(KEXT_FAMILY_NAME)"

Added Configurations/components/CC_kernel_deployment.xcconfig.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
//
//  CC_kernel_deployment.xcconfig
//  CommonCrypto
//
//  Created by Stacey Son on 10/20/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file is for the deployment version of the kernel CommonCrypto kext.

#include "CC_deployment.xcconfig"

#include "CC_kernel.xcconfig"

Added Configurations/components/CC_kernel_development.xcconfig.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
//
//  CC_kernel_development.xcconfig
//  CommonCrypto
//
//  Created by Stacey Son on 10/20/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file is for the development version of the kernel CommonCrypto kext.

#include "CC_development.xcconfig"

#include "CC_kernel.xcconfig"

Added Configurations/components/CC_static.xcconfig.































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//
//  CC_static.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file defines settings that specific for static libraries

STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = Dynamic

EXECUTABLE_EXTENSION = a

LIBRARY_STYLE = Static

Added Configurations/components/CC_static_deployment.xcconfig.

























>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
//
//  CC_static_deployment.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file is for the deployment version of the static CommonCrypto Library

#include "CC_deployment.xcconfig"
#include "CC_static.xcconfig"

Added Configurations/components/CC_static_development.xcconfig.

























>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
//
//  CC_static_development.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

// This XCCONFIG file is for the development version of the static CommonCrypto Library

#include "CC_development.xcconfig"
#include "CC_static.xcconfig"

Added Configurations/components/CC_umbrellaMember.xcconfig.



































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//
//  CC_umbrellaMember.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines settings that specific for umbrella member libraries

OTHER_LDFLAGS = -Wl -umbrella System -allowable_client otest -allowable_client CommonCryptoUnitTest -allowable_client XTSTest -allowable_client CBCTest -allowable_client tcCryptoTool -allowable_client bigcbc

STANDARD_C_PLUS_PLUS_LIBRARY_TYPE = Dynamic

EXECUTABLE_EXTENSION = dylib

LIBRARY_STYLE = Dynamic

Added Configurations/platforms/CC_MacOSXClient.xcconfig.





















>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
//
//  MacOSXClient.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.

SDKROOT = macosx10.6
OTHER_CFLAGS = -fstack-protector-all -Wstack-protector -DSHA256_USE_ASSEMBLY=1 -DCC_MACOSX
PRODUCT_NAME = commonCrypto

Added Configurations/platforms/CC_iOSClient.xcconfig.





















>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
//
//  MacOSXClient.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.

SDKROOT = iphoneos5.0.internal
OTHER_CFLAGS = -fstack-protector-all -Wstack-protector -DSHA256_USE_ASSEMBLY=1 -DCC_iOS
PRODUCT_NAME = commonCrypto

Added Configurations/platforms/CC_iOSClientSim.xcconfig.

























>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
//
//  MacOSXClient.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.

//SDKROOT = iphonesimulator5.0
OTHER_CFLAGS = -fstack-protector-all -Wstack-protector -DSHA256_USE_ASSEMBLY=1 -DCC_iOS_SIM
PRODUCT_NAME = commonCrypto_sim
PRIVATE_HEADERS_FOLDER_PATH = $(SDKROOT)/usr/local/include/CommonCrypto
PUBLIC_HEADERS_FOLDER_PATH = $(SDKROOT)/usr/include/CommonCrypto

Added Configurations/targets/CC_MacOSXClient_deployment.xcconfig.





























>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//
//  CommonCrypto_MacOSXClient_deployment.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//


// This XCCONFIG file is for the deployment version of the CommonCrypto umbrella member for System CommonCrypto Library for MacOSX

#include "../components/CC_deployment.xcconfig"
#include "../components/CC_umbrellaMember.xcconfig"
#include "../platforms/CC_MacOSXClient.xcconfig"

Added Configurations/targets/CC_MacOSXClient_development.xcconfig.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
//
//  CommonCrypto_MacOSXClient_development.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file is for the development version of the CommonCrypto umbrella member for System CommonCrypto Library for MacOSX

#include "../components/CC_development.xcconfig"
#include "../components/CC_umbrellaMember.xcconfig"
#include "../platforms/CC_MacOSXClient.xcconfig"

Added Configurations/targets/CC_iOSClient_deployment.xcconfig.





























>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//
//  CommonCrypto_MacOSXClient_deployment.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//


// This XCCONFIG file is for the deployment version of the umbrella member for System CommonCrypto Library

#include "../components/CC_deployment.xcconfig"
#include "../components/CC_umbrellaMember.xcconfig"
#include "../platforms/CC_iOSClient.xcconfig"

Added Configurations/targets/CC_iOSClient_development.xcconfig.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
//
//  CC_MacOSXClient_development.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file is for the development version of the CommonCrypto umbrella member for System CommonCrypto Library for MacOSX

#include "../components/CC_development.xcconfig"
#include "../components/CC_umbrellaMember.xcconfig"
#include "../platforms/CC_iOSClient.xcconfig"

Added Configurations/targets/CC_iOSSim_deployment.xcconfig.





























>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//
//  CC_MacOSXClient_deployment.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//


// This XCCONFIG file is for the deployment version of the umbrella member for System CommonCrypto Library

#include "../components/CC_deployment.xcconfig"
#include "../components/CC_umbrellaMember.xcconfig"
#include "../platforms/CC_iOSClientSim.xcconfig"

Added Configurations/targets/CC_iOSSim_development.xcconfig.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
//
//  CC_MacOSXClient_development.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file is for the development version of the CommonCrypto umbrella member for System CommonCrypto Library for MacOSX

#include "../components/CC_development.xcconfig"
#include "../components/CC_umbrellaMember.xcconfig"
#include "../platforms/CC_iOSClientSim.xcconfig"

Added Configurations/tests/CC_localtest.xcconfig.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
//
//  CommonCrypto_unittest_base.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

ARCHS = $(NATIVE_ARCH) $(ARCHS_STANDARD_64_BIT) arm
GCC_OPTIMIZATION_LEVEL = 0
GCC_PREPROCESSOR_DEFINITIONS = _FORTIFY_SOURCE=2 DEBUG
COPY_PHASE_STRIP = NO
WARNING_CFLAGS = -Wall

Added Configurations/tests/CC_unitTest_dynamic_development.xcconfig.























>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
//
//  CommonCrypto_unitTest_dynamic_development.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#include "CC_unittest_development.xcconfig"

LIBRARY_STYLE = Dynamic

Added Configurations/tests/CC_unittest_base.xcconfig.















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//
//  CommonCrypto_unittest_base.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the shared settings for all unit test targets of the
// CommonCrypto XCode Project


// **************************************************************************
// * Begin Project Section
// **************************************************************************

CC_PATH_BASE = $(PROJECT_DIR)
CC_PATH_UNIT_TEST_SOURCE = $(CC_PATH_BASE)/UnitTestSource

PRODUCT_NAME = CommonCryptoUnitTest

ARCHS = $(NATIVE_ARCH) $(ARCHS_STANDARD_64_BIT) arm

OTHER_LDFLAGS = -framework Cocoa -framework SenTestingKit

WRAPPER_EXTENSION = octest

FRAMEWORK_SEARCH_PATHS = $(DEVELOPER_FRAMEWORKS_DIR)

GCC_PREFIX_HEADER = $(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h

INFOPLIST_FILE = $(CC_PATH_UNIT_TEST_SOURCE)/CommonCryptoUnitTests-Info.plist

OBJC_DISABLE_GC = NO

// **************************************************************************
// * End Project Section
// **************************************************************************

Added Configurations/tests/CC_unittest_deployment.xcconfig.









































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//
//  CommonCrypto_unittest_base.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the deployment setting for  unit test targets of the
// CommonCrypto XCode Project

#include "CC_unittest_base.xcconfig"

GCC_OPTIMIZATION_LEVEL = s

GCC_PREPROCESSOR_DEFINITIONS_PROJECT = NDEBUG

COPY_PHASE_STRIP = YES

WARNING_CFLAGS = -Wall

Added Configurations/tests/CC_unittest_development.xcconfig.









































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//
//  CommonCrypto_unittest_base.xcconfig
//  CommonCrypto
//
//  InfoSec Standard Configuration
//  Copyright 2010 Apple Inc. All rights reserved.
//

// This XCCONFIG file defines the development setting for  unit test targets of the
// CommonCrypto XCode Project

#include "CC_unittest_base.xcconfig"

GCC_OPTIMIZATION_LEVEL = 0

GCC_PREPROCESSOR_DEFINITIONS_PROJECT = DEBUG

COPY_PHASE_STRIP = NO

WARNING_CFLAGS = -Wall

Added Configurations/tests/CC_unittest_dynamic_deployment.xcconfig.























>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
//
//  CommonCrypto_unittest_dynamic_deployment.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#include "CC_unittest_deployment.xcconfig"

LIBRARY_STYLE = Dynamic

Added Configurations/tests/CC_unittest_static_deployment.xcconfig.























>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
//
//  CommonCrypto_unittest_static_deployment.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#include "CC_unittest_deployment.xcconfig"

LIBRARY_STYLE = Static

Added Configurations/tests/CC_unittest_static_development.xcconfig.























>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
//
//  CommonCrypto_unittest_static_development.xcconfig
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#include "CC_unittest_development.xcconfig"

LIBRARY_STYLE = Static

Deleted LocalTests/CBCTest/CBCTest.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  CBCTest.c
 *  CommonCrypto
 */

#include "CBCTest.h"

static void
doCBCTestCase(int caseNumber, int direction, int dataLenBits, char *ivStr, char *cipherText, char *plainText, char *keyStr)
{
	char keyString[300];
    int ckLen, keyLength;
    byteBuffer key, tweak, iv;
    byteBuffer pt, ct;
	CCCryptorRef encCryptorRef;
	CCCryptorStatus retval;
    char dataOut[4096];
    int passed = 0;
    int dataLen;
    size_t dataOutMoved;
    
    ckLen = strlen(keyStr);
    strncpy(keyString, keyStr, ckLen);
    keyString[ckLen] = 0;
    
    keyLength = ckLen/2;
    
    key = hexStringToBytes(keyString);
    tweak = NULL;
    iv = hexStringToBytes(ivStr);
    
    encCryptorRef = NULL;
    
    if(plainText) pt = hexStringToBytes(plainText);
    else pt=NULL;
    if(cipherText) ct = hexStringToBytes(cipherText);
    else ct=NULL;
    
    
    printf("\n\nKey       %s\n", keyStr);
    printf("IV        %s\n", ivStr);
    printf("Plaintext %s\n", plainText);
    
    if((retval = CCCryptorCreateWithMode(0, kCCModeCBC, kCCAlgorithmAES128, ccDefaultPadding, NULL, key->bytes, key->len, tweak, 0, 0, 0,  &encCryptorRef)) == kCCSuccess) {
        if(direction == ENCRYPT) {
            dataLen = pt->len;
            if((retval = CCCryptorEncryptDataBlock(encCryptorRef, iv->bytes, pt->bytes, dataLen, dataOut)) == kCCSuccess) {
                byteBuffer bb = bytesToBytes(dataOut, dataLen);
                if(!ct) {
                    printf("Output    %s\n", bytesToHexString(bb));
                    passed = 3;
                }
                else if (!bytesAreEqual(ct, bb))
                    printf("Encrypt (%d) Output %s\nEncrypt (%d) Expect %s\n", dataLen, bytesToHexString(bb), dataLen, cipherText);
                else 
                    passed = 1;
            } else  printf("Failed to encrypt %d\n", retval);
        } else {
            dataLen = ct->len;
            if((retval = CCCryptorDecryptDataBlock(encCryptorRef, iv->bytes, ct->bytes, dataLen, dataOut)) == kCCSuccess) {
                byteBuffer bb = bytesToBytes(dataOut, dataLen);
                if(!pt) {
                    printf("Output    %s\n", bytesToHexString(bb));
                    passed = 3;
                }
                else if (!bytesAreEqual(pt, bb)) 
                    printf("Decrypt Output %s\nDecrypt Expect %s\n", bytesToHexString(bb), plainText);
                else passed = 1;
        	} else  printf("Failed to decrypt %d\n", retval);
    	}
        
        if((retval = CCCryptorFinal(encCryptorRef, dataOut, 0, &dataOutMoved)) != kCCSuccess) printf("Finalize failed\n");
    } else {
        printf("Failed to create Cryptor\n");
    }
    
    
	if(passed != 3) printf("Case %d Direction %s DataLen %d Test %s\n", caseNumber, (direction == ENCRYPT) ? "Encrypt": "Decrypt", dataLen, (passed) ? "Pass": "Fail");
    else printf("\n");
    free(pt);
    free(ct);
    free(key);
    free(tweak);
    free(iv);
    
}

int main (int argc, const char * argv[]) {
    int direction;
	int caseNumber;
	int dataLen;
	char *keyStr;
	char *iv;
	char *plainText;
	char *cipherText;
    
    direction = DECRYPT;
    caseNumber = 500;
	dataLen = 8192;
	keyStr = "badfd2102e1e180a634204249c5a6933";
	iv = "84c06c16c151007ca9ed9bb926e66eec";
	cipherText = "4b52b5e85aecaaaf886bd9e8805390c62e12e13357e4beb3b713e37d217c6f7a9e432a04f87bd8a4dd0ef79eb7bf41b5a2a27e63361d7cb7af7b3c9a8f0b56ae27dc9cfd6c10eb1a79c7be35d31c3965b8e7099775f7644029bd79321f5dd12c55280a30fabd1b95e27c2d4dec6ca4d8716f36e7abe3408f5120560b573e5495ae7aad668fa84d6a8a1156c231a5b6d983ece3e27d199a806dc629c1a60c08ccb0e4807d9fed88f28ce0f59583708f540f97110b2620b1679220abe13e3c4b727186b289794583b20154ce9a07a284df3e63572f462142cae8949d7dd6f2b26fb90d556ec75e93dd33b59d697883312af89e52945b9baedfebe28759cdba4dfbf6e6f201b087478642cf0b34f983593c68947e4ee05bd17716e6cfb7c74c876c0ba650f3979f5eceb72a71d0d46aac4474ae2048d2a9884aa12e292950c77b17de11e8d3e895e60b1c584b1c8d9edd40ba7917e396d1d3bfd1941923aa40213195e8b8f7f4d5ae1057cbecdf89c8959745d1fcece59115819dc661e7b097c132e8f98720a57a83469cb82c374fdebc97badd7cef8d160a7f27d50f35b7e4af6f1b78361828e32a55b25fd56efbc12f8fcb7e2e4f882afa0c7747a455a1fae00a561cbb878e01b32fafb23f397371a8b3441c8da654b902d8489383542188821859a44f0fb2b63a49835f8ba5f0231ff0f8f5fc3d5c812331b11e39bc03394e28";
	plainText  = "fb58510beb65062c525a3de42d934d4b4ec433d600a1467142751886a10e7bf96f236c196d12dcf0698e09efc79a4bea072bc0830da8886674cf6174206cca2d4e9e543f0016ec4dcc602ffd0a417c722879e259497f89aee5ad99a4f65887058242250fbe44f61eab5e668adbb780a4cba97393f6ff152c13c39b57ed727bb94cf19d1b4a55f45cceb22b6c4f26f736d20a48cb6230578591c8d33d72b778d30b304818b20d918ef654cabeae1038f2a0db5170d2b4df38c6efc887bc1f837fba34e97daf8920414b748a909ad5ef56fb47fa53c680aae808f3e6065689339728251e18cd264f5385c969f87104099563a411cfe681d19134e9479e059d09b69f5010912291d0232f733a2688b3042ec4e82ce5163c384ee54a9f10e48a8ab46fd7147351dd8514bda5d8c4ce8babcc3ef82dbf44799fc59e37d8f3c99506d2168c84d8381f4f9a84cbce7bd0bb4bbbcdef0c626356d3ca126c8776e3a291881af518e23dbd067016c5898bed5f64d6e8f8acefba83f92b0c318ec7b905165fb6b81bc60528c0a0e3db38ab1ee6f37e56dbf270c0751674e0ddb1a6076d8f78084ce31f0d3673e638e0110575b16d9d9f151c1b9aca8d15d7a8111c0de5acf5ae3b307e8064c90329e421e3434a1ecd253b153447c21c79c9946666dae444c49a31b1f94da603a8377168dc4f874e98fff5ae89dd35d44e89df5748223b7a24";
    
    
	doCBCTestCase(caseNumber, direction, dataLen, iv, cipherText, plainText, keyStr);
    
    /* taken from the AES_KAT test file CBCVarKey128e.txt */
    printf("\nIV and Plaintext == 00000...\n");
    direction = ENCRYPT;
    caseNumber = 3;
	dataLen = 256;
    keyStr = "f0000000000000000000000000000000";
    iv = "00000000000000000000000000000000";
    plainText = "00000000000000000000000000000000";
    cipherText = "970014d634e2b7650777e8e84d03ccd8";
	doCBCTestCase(caseNumber, direction, dataLen, iv, cipherText, plainText, keyStr);

    
    /* taken from the AES_KAT test file CBCVarKey128e.txt */
    printf("\nIV  == a0a0..\n");
    direction = ENCRYPT;
    caseNumber = 3;
	dataLen = 256;
    keyStr = "f0000000000000000000000000000000";
    iv =        "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0";
    plainText = "00000000000000000000000000000000";
    cipherText = NULL;
	doCBCTestCase(caseNumber, direction, dataLen, iv, cipherText, plainText, keyStr);

    /* taken from the AES_KAT test file CBCVarKey128e.txt */
    printf("\nplaintext  == a0a0..\n");
    direction = ENCRYPT;
    caseNumber = 3;
	dataLen = 256;
    keyStr = "f0000000000000000000000000000000";
    iv =        "00000000000000000000000000000000";
    plainText = "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0";
    cipherText = NULL;
	doCBCTestCase(caseNumber, direction, dataLen, iv, cipherText, plainText, keyStr);

    printf("\nIV and Plaintext == 00 key is all F's\n");
    direction = ENCRYPT;
    caseNumber = 3;
	dataLen = 256;
    keyStr =    "ffffffffffffffffffffffffffffffff";
    iv =        "00000000000000000000000000000000";
    plainText = "00000000000000000000000000000000";
    cipherText = NULL;
	doCBCTestCase(caseNumber, direction, dataLen, iv, cipherText, plainText, keyStr);

    direction = ENCRYPT;
    caseNumber = 3;
	dataLen = 512;
    keyStr =    "ffffffffffffffffffffffffffffffff";
    iv =        "00000000000000000000000000000000";
    plainText = "00000000000000000000000000000000a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0";
    cipherText = NULL;
	doCBCTestCase(caseNumber, direction, dataLen, iv, cipherText, plainText, keyStr);

    direction = ENCRYPT;
    caseNumber = 3;
	dataLen = 512;
    keyStr =    "ffffffffffffffffffffffffffffffff";
    iv =        "a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0";
    plainText = "00000000000000000000000000000000a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0";
    cipherText = NULL;
	doCBCTestCase(caseNumber, direction, dataLen, iv, cipherText, plainText, keyStr);
    return 0;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































































































































Deleted LocalTests/CBCTest/CBCTest.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  CBCTest.h
 *  CommonCrypto
 */

#include <stdio.h>
#include <CommonCrypto/CommonCryptor.h>
#include </usr/local/include/CommonCrypto/CommonCryptorSPI.h>
#include "byteBuffer.h"

#ifndef _XXXX_H_
#define _XXXX_H_

#ifdef __cplusplus
extern "C" {
#endif


#define ENCRYPT 0
#define DECRYPT 1





#ifdef __cplusplus
}
#endif

#endif  /* _XXXX_H_ */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































Deleted LocalTests/XTSTest/crypto.c.

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <CommonCrypto/CommonCryptor.h>
#include </usr/local/include/CommonCrypto/CommonCryptorSPI.h>

static int keyLength = 16;
static int dataLength = 512;


int main (int argc, const char * argv[]) {
    runAllVectors();
    return 0;
}
<
<
<
<
<
<
<
<
<
<
<
<
























Deleted LocalTests/XTSTest/hexString.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 *  hexString.c
 *  byteutils
 *
 *  Created by Richard Murphy on 3/7/10.
 *  Copyright 2010 McKenzie-Murphy. All rights reserved.
 *
 */

#include "hexString.h"

/* utility function to convert hex character representation to their nibble (4 bit) values */
static uint8_t
nibbleFromChar(char c)
{
	if(c >= '0' && c <= '9') return c - '0';
	if(c >= 'a' && c <= 'f') return c - 'a' + 10;
	if(c >= 'A' && c <= 'F') return c - 'A' + 10;
	return 255;
}

/* Convert a string of characters representing a hex buffer into a series of bytes of that real value */
uint8_t
*hexStringToBytes(char *inhex)
{
	uint8_t *retval;
	uint8_t *p;
	int len, i;
	
    len = strlen(inhex) / 2;
	retval = malloc(len+1);
	for(i=0, p = (uint8_t *) inhex; i<len; i++) {
		retval[i] = (nibbleFromChar(*p) << 4) | nibbleFromChar(*(p+1));
		p += 2;
	}
    retval[len] = 0;
	return retval;
}

static char byteMap[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
static int byteMapLen = sizeof(byteMap);

/* Utility function to convert nibbles (4 bit values) into a hex character representation */
static char
nibbleToChar(uint8_t nibble)
{
	if(nibble < byteMapLen) return byteMap[nibble];
	return '*';
}

/* Convert a buffer of binary values into a hex string representation */
char
*bytesToHexString(uint8_t *bytes, size_t buflen)
{
	char *retval;
	int i;
	
	retval = malloc(buflen*2 + 1);
	for(i=0; i<buflen; i++) {
		retval[i*2] = nibbleToChar(bytes[i] >> 4);
		retval[i*2+1] = nibbleToChar(bytes[i] & 0x0f);
	}
    retval[i] = '\0';
	return retval;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































Deleted LocalTests/XTSTest/hexString.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
 *  hexString.h
 *  byteutils
 *
 *  Created by Richard Murphy on 3/7/10.
 *  Copyright 2010 McKenzie-Murphy. All rights reserved.
 *
 */

#include <stdint.h>
#include <stdlib.h>
#include <string.h>

uint8_t
*hexStringToBytes(char *inhex);

char
*bytesToHexString(uint8_t *bytes, size_t buflen);
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































Deleted LocalTests/XTSTest/printByteBuffer.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
 *  printByteBuffer.c
 *  byteutils
 *
 *  Created by Richard Murphy on 3/7/10.
 *  Copyright 2010 McKenzie-Murphy. All rights reserved.
 *
 */

#include "printByteBuffer.h"

void printByteBuffer(uint8_t *buff, size_t len, char *name)
{
	int i;
	printf("Dumping %d bytes from %s\n", len, name);
	for(i=0; i<len; i++) {
		if(i > 0 && !(i%8)) putchar(' ');
		if(i > 0 && !(i%64)) putchar('\n');
		printf("%02x", buff[i]);
	}
	putchar('\n');
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































Deleted LocalTests/XTSTest/printByteBuffer.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
 *  printByteBuffer.h
 *  byteutils
 *
 *  Created by Richard Murphy on 3/7/10.
 *  Copyright 2010 McKenzie-Murphy. All rights reserved.
 *
 */

#include <stdint.h>
#include <stdio.h>

void printByteBuffer(uint8_t *buff, size_t len, char *name);

<
<
<
<
<
<
<
<
<
<
<
<
<
<




























Deleted LocalTests/XTSTest/xtsTestVectors.c.

more than 10,000 changes

Deleted LocalTests/XTSTest/xtsTestVectors.h.

1
2
3
4
5
6
7
8
9
/*
 *  xtsTestVectors.h
 *  XTSTest
 *
 *  Created by Richard Murphy on 6/24/10.
 *  Copyright 2010 McKenzie-Murphy. All rights reserved.
 *
 */

<
<
<
<
<
<
<
<
<


















Deleted LocalTests/ccSymTest.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
/* Copyright 2006 Apple Computer, Inc.
 *
 * ccSymTest.c - test CommonCrypto symmetric encrypt/decrypt.
 */
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <CommonCrypto/CommonCryptor.h>
#include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacErrors.h>
#include "common.h"

/*
 * Defaults.
 */
#define LOOPS_DEF		500
#define MIN_DATA_SIZE	8
#define MAX_DATA_SIZE	10000						/* bytes */
#define MAX_KEY_SIZE	kCCKeySizeMaxRC4			/* bytes */
#define MAX_BLOCK_SIZE	kCCBlockSizeAES128			/* bytes */
#define LOOP_NOTIFY		250

/*
 * Enumerate algs our own way to allow iteration.
 */
typedef enum {
	ALG_AES_128 = 1,	/* 128 bit block, 128 bit key */
	ALG_AES_192,		/* 128 bit block, 192 bit key */
	ALG_AES_256,		/* 128 bit block, 256 bit key */
	ALG_DES,
	ALG_3DES,
	ALG_CAST,
	ALG_RC4,
	/* these aren't in CommonCrypto (yet?) */
	ALG_RC2,
	ALG_RC5,
	ALG_BFISH,
	ALG_ASC,
	ALG_NULL					/* normally not used */
} SymAlg;
#define ALG_FIRST			ALG_AES_128
#define ALG_LAST			ALG_RC4


#define LOG_SIZE			0
#if		LOG_SIZE
#define logSize(s)	printf s
#else
#define logSize(s)
#endif

static void usage(char **argv)
{
	printf("usage: %s [options]\n", argv[0]);
	printf("   Options:\n");
	printf("   a=algorithm (d=DES; 3=3DES; a=AES128; n=AES192; A=AES256; \n");
	printf("     c=CAST; 4=RC4; default=all)\n");
	printf("   l=loops (default=%d; 0=forever)\n", LOOPS_DEF);
	printf("   m=maxPtextSize (default=%d)\n", MAX_DATA_SIZE);
	printf("   n=minPtextSize (default=%d)\n", MIN_DATA_SIZE);
	printf("   k=keySizeInBytes\n");
	printf("   p=pauseInterval (default=0, no pause)\n");
	printf("   o (no padding, well-aligned plaintext)\n");
	printf("   e (ECB only)\n");
	printf("   E (CBC only, no ECB)\n");
	printf("   u (no multi-update ops)\n");
	printf("   U (only multi-update ops)\n");
	printf("   x (always allocate context)\n");
	printf("   X (never allocate context)\n");
	printf("   v(erbose)\n");
	printf("   q(uiet)\n");
	printf("   h(elp)\n");
	exit(1);
}

static void printCCError(const char *str, CCCryptorStatus crtn)
{
	const char *errStr;
	char unknownStr[200];
	
	switch(crtn) {
		case kCCSuccess: errStr = "kCCSuccess"; break;
		case kCCParamError: errStr = "kCCParamError"; break;
		case kCCBufferTooSmall: errStr = "kCCBufferTooSmall"; break;
		case kCCMemoryFailure: errStr = "kCCMemoryFailure"; break;
		case kCCAlignmentError: errStr = "kCCAlignmentError"; break;
		case kCCDecodeError: errStr = "kCCDecodeError"; break;
		case kCCUnimplemented: errStr = "kCCUnimplemented"; break;
		default:
			sprintf(unknownStr, "Unknown(%ld)\n", (long)crtn);
			errStr = unknownStr;
			break;
	}
	printf("***%s returned %s\n", str, errStr);
}

/* max context size */
#define CC_MAX_CTX_SIZE	kCCContextSizeRC4

/* 
 * We write a marker at end of expected output and at end of caller-allocated 
 * CCCryptorRef, and check at the end to make sure they weren't written 
 */
#define MARKER_LENGTH	8
#define MARKER_BYTE		0x7e

/* 
 * Test harness for CCCryptor with lots of options. 
 */
CCCryptorStatus doCCCrypt(
	bool forEncrypt,
	CCAlgorithm encrAlg,			
	bool doCbc,
	bool doPadding,
	const void *keyBytes, size_t keyLen,
	const void *iv,
	bool randUpdates,
	bool inPlace,								/* !doPadding only */
	size_t ctxSize,								/* if nonzero, we allocate ctx */
	bool askOutSize,
	const uint8_t *inText, size_t inTextLen,
	uint8_t **outText, size_t *outTextLen)		/* both returned, WE malloc */
{
	CCCryptorRef	cryptor = NULL;
	CCCryptorStatus crtn;
	CCOperation		op = forEncrypt ? kCCEncrypt : kCCDecrypt;
	CCOptions		options = 0;
	uint8_t			*outBuf = NULL;			/* mallocd output buffer */
	uint8_t			*outp;					/* running ptr into outBuf */
	const uint8		*inp;					/* running ptr into inText */
	size_t			outLen;					/* bytes remaining in outBuf */
	size_t			toMove;					/* bytes remaining in inText */
	size_t			thisMoveOut;			/* output from CCCryptUpdate()/CCCryptFinal() */
	size_t			outBytes;				/* total bytes actually produced in outBuf */
	char			ctx[CC_MAX_CTX_SIZE];	/* for CCCryptorCreateFromData() */
	uint8_t			*textMarker = NULL;		/* 8 bytes of marker here after expected end of 
											 * output */
	char			*ctxMarker = NULL;		/* ditto for caller-provided context */
	unsigned		dex;
	size_t			askedOutSize;			/* from the lib */
	size_t			thisOutLen;				/* dataOutAvailable we use */
	
	if(ctxSize > CC_MAX_CTX_SIZE) {
		printf("***HEY! Adjust CC_MAX_CTX_SIZE!\n");
		exit(1);
	}
	if(!doCbc) {
		options |= kCCOptionECBMode;
	}
	if(doPadding) {
		options |= kCCOptionPKCS7Padding;
	}
	
	/* just hack this one */
	outLen = inTextLen;
	if(forEncrypt) {
		outLen += MAX_BLOCK_SIZE;
	}
	
	outBuf = (uint8_t *)malloc(outLen + MARKER_LENGTH);
	memset(outBuf, 0xEE, outLen + MARKER_LENGTH);
	
	/* library should not touch this memory */
	textMarker = outBuf + outLen;
	memset(textMarker, MARKER_BYTE, MARKER_LENGTH);
	
	/* subsequent errors to errOut: */

	if(inPlace) {
		memmove(outBuf, inText, inTextLen);
		inp = outBuf;
	}
	else {
		inp = inText;
	}

	if(!randUpdates) {
		/* one shot */
		if(askOutSize) {
			crtn = CCCrypt(op, encrAlg, options,
				keyBytes, keyLen, iv,
				inp, inTextLen,
				outBuf, 0, &askedOutSize);
			if(crtn != kCCBufferTooSmall) {
				printf("***Did not get kCCBufferTooSmall as expected\n");
				printf("   alg %d inTextLen %lu cbc %d padding %d keyLen %lu\n",
					(int)encrAlg, (unsigned long)inTextLen, (int)doCbc, (int)doPadding,
					(unsigned long)keyLen);
				printCCError("CCCrypt", crtn);
				crtn = -1;
				goto errOut;
			}
			outLen = askedOutSize;
		}
		crtn = CCCrypt(op, encrAlg, options,
			keyBytes, keyLen, iv,
			inp, inTextLen,
			outBuf, outLen, &outLen);
		if(crtn) {
			printCCError("CCCrypt", crtn);
			goto errOut;
		}
		*outText = outBuf;
		*outTextLen = outLen;
		goto errOut;
	}
	
	/* random multi updates */
	if(ctxSize) {
		size_t ctxSizeCreated;
		
		if(askOutSize) {
			crtn = CCCryptorCreateFromData(op, encrAlg, options,
				keyBytes, keyLen, iv,
				ctx, 0 /* ctxSize */,
				&cryptor, &askedOutSize);
			if(crtn != kCCBufferTooSmall) {
				printf("***Did not get kCCBufferTooSmall as expected\n");
				printCCError("CCCryptorCreateFromData", crtn);
				crtn = -1;
				goto errOut;
			}
			ctxSize = askedOutSize;
		}
		crtn = CCCryptorCreateFromData(op, encrAlg, options,
			keyBytes, keyLen, iv,
			ctx, ctxSize, &cryptor, &ctxSizeCreated);
		if(crtn) {
			printCCError("CCCryptorCreateFromData", crtn);
			return crtn;
		}
		ctxMarker = ctx + ctxSizeCreated;
		memset(ctxMarker, MARKER_BYTE, MARKER_LENGTH);
	}
	else {
		crtn = CCCryptorCreate(op, encrAlg, options,
			keyBytes, keyLen, iv,
			&cryptor);
		if(crtn) {
			printCCError("CCCryptorCreate", crtn);
			return crtn;
		}
	}
	
	toMove = inTextLen;		/* total to go */
	outp = outBuf;
	outBytes = 0;			/* bytes actually produced in outBuf */
	
	while(toMove) {
		uint32 thisMoveIn;			/* input to CCryptUpdate() */
		
		thisMoveIn = genRand(1, toMove);
		logSize(("###ptext segment len %lu\n", (unsigned long)thisMoveIn)); 
		if(askOutSize) {
			thisOutLen = CCCryptorGetOutputLength(cryptor, thisMoveIn, false);
		}
		else {
			thisOutLen = outLen;
		}
		crtn = CCCryptorUpdate(cryptor, inp, thisMoveIn,
			outp, thisOutLen, &thisMoveOut);
		if(crtn) {
			printCCError("CCCryptorUpdate", crtn);
			goto errOut;
		}
		inp			+= thisMoveIn;
		toMove		-= thisMoveIn;
		outp		+= thisMoveOut;
		outLen   	-= thisMoveOut;
		outBytes	+= thisMoveOut;
	}
	
	if(doPadding) {
		/* Final is not needed if padding is disabled */
		if(askOutSize) {
			thisOutLen = CCCryptorGetOutputLength(cryptor, 0, true);
		}
		else {
			thisOutLen = outLen;
		}
		crtn = CCCryptorFinal(cryptor, outp, thisOutLen, &thisMoveOut);
	}
	else {
		thisMoveOut = 0;
		crtn = kCCSuccess;
	}
	
	if(crtn) {
		printCCError("CCCryptorFinal", crtn);
		goto errOut;
	}
	
	outBytes += thisMoveOut;
	*outText = outBuf;
	*outTextLen = outBytes;
	crtn = kCCSuccess;

	for(dex=0; dex<MARKER_LENGTH; dex++) {
		if(textMarker[dex] != MARKER_BYTE) {
			printf("***lib scribbled on our textMarker memory (op=%s)!\n",
				forEncrypt ? "encrypt" : "decrypt");
			crtn = (CCCryptorStatus)-1;
		}
	}
	if(ctxSize) {
		for(dex=0; dex<MARKER_LENGTH; dex++) {
			if(ctxMarker[dex] != MARKER_BYTE) {
				printf("***lib scribbled on our ctxMarker memory (op=%s)!\n",
					forEncrypt ? "encrypt" : "decrypt");
				crtn = (CCCryptorStatus)-1;
			}
		}
	}
	
errOut:
	if(crtn) {
		if(outBuf) {
			free(outBuf);
		}
	}
	if(cryptor) {
		CCCryptorRelease(cryptor);
	}
	return crtn;
}

static int doTest(const uint8_t *ptext,
	size_t ptextLen,
	CCAlgorithm encrAlg,			
	bool doCbc,
	bool doPadding,
	bool nullIV,			/* if CBC, use NULL IV */
	uint32 keySizeInBytes,
	bool stagedEncr,
	bool stagedDecr,
	bool inPlace,	
	size_t ctxSize,		
	bool askOutSize,
	bool quiet)
{
	uint8_t			keyBytes[MAX_KEY_SIZE];
	uint8_t			iv[MAX_BLOCK_SIZE];
	uint8_t			*ivPtrEncrypt;
	uint8_t			*ivPtrDecrypt;
	uint8_t			*ctext = NULL;		/* mallocd by doCCCrypt */
	size_t			ctextLen = 0;
	uint8_t			*rptext = NULL;		/* mallocd by doCCCrypt */
	size_t			rptextLen;
	CCCryptorStatus	crtn;
	int				rtn = 0;
	
	/* random key */
	appGetRandomBytes(keyBytes, keySizeInBytes);
	
	/* random IV if needed */
	if(doCbc) {
		if(nullIV) {
			memset(iv, 0, MAX_BLOCK_SIZE);
			
			/* flip a coin, give one side NULL, the other size zeroes */
			if(genRand(1,2) == 1) {
				ivPtrEncrypt = NULL;
				ivPtrDecrypt = iv;
			}
			else {
				ivPtrEncrypt = iv;
				ivPtrDecrypt = NULL;
			}
		}
		else {
			appGetRandomBytes(iv, MAX_BLOCK_SIZE);
			ivPtrEncrypt = iv;
			ivPtrDecrypt = iv;
		}
	}	
	else {
		ivPtrEncrypt = NULL;
		ivPtrDecrypt = NULL;
	}

	crtn = doCCCrypt(true, encrAlg, doCbc, doPadding,
		keyBytes, keySizeInBytes, ivPtrEncrypt,
		stagedEncr, inPlace, ctxSize, askOutSize,
		ptext, ptextLen,
		&ctext, &ctextLen);
	if(crtn) {
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	
	logSize(("###ctext len %lu\n", ctextLen)); 
	
	crtn = doCCCrypt(false, encrAlg, doCbc, doPadding,
		keyBytes, keySizeInBytes, ivPtrDecrypt,
		stagedDecr, inPlace, ctxSize, askOutSize,
		ctext, ctextLen,
		&rptext, &rptextLen);
	if(crtn) {
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}

	logSize(("###rptext len %lu\n", rptextLen)); 
	
	/* compare ptext, rptext */
	if(ptextLen != rptextLen) {
		printf("Ptext length mismatch: expect %lu, got %lu\n", ptextLen, rptextLen);
		rtn = testError(quiet);
		if(rtn) {
			goto abort;
		}
	}
	if(memcmp(ptext, rptext, ptextLen)) {
		printf("***data miscompare\n");
		rtn = testError(quiet);
	}
abort:
	if(ctext) {
		free(ctext);
	}
	if(rptext) {
		free(rptext);
	}
	return rtn;
}

bool isBitSet(unsigned bit, unsigned word) 
{
	if(bit > 31) {
		printf("We don't have that many bits\n");
		exit(1);
	}
	unsigned mask = 1 << bit;
	return (word & mask) ? true : false;
}

int main(int argc, char **argv)
{
	int					arg;
	char				*argp;
	unsigned			loop;
	uint8				*ptext;
	size_t				ptextLen;
	bool				stagedEncr = false;
	bool				stagedDecr = false;
	bool				doPadding;
	bool				doCbc = false;
	bool				nullIV;
	const char			*algStr;
	CCAlgorithm			encrAlg;	
	int					i;
	int					currAlg;		// ALG_xxx
	uint32				minKeySizeInBytes;
	uint32				maxKeySizeInBytes;
	uint32				keySizeInBytes = 0;
	int					rtn = 0;
	uint32				blockSize;		// for noPadding case
	size_t				ctxSize;		// always set per alg
	size_t				ctxSizeUsed;	// passed to doTest
	bool				askOutSize;		// inquire output size each op
	
	/*
	 * User-spec'd params
	 */
	bool		keySizeSpec = false;		// false: use rand key size
	SymAlg		minAlg = ALG_FIRST;
	SymAlg		maxAlg = ALG_LAST;
	unsigned	loops = LOOPS_DEF;
	bool		verbose = false;
	size_t		minPtextSize = MIN_DATA_SIZE;
	size_t		maxPtextSize = MAX_DATA_SIZE;
	bool		quiet = false;
	unsigned	pauseInterval = 0;
	bool		paddingSpec = false;		// true: user calls doPadding, const
	bool		cbcSpec = false;			// ditto for doCbc
	bool		stagedSpec = false;			// ditto for stagedEncr and stagedDecr
	bool		inPlace = false;			// en/decrypt in place for ECB
	bool		allocCtxSpec = false;		// use allocCtx
	bool		allocCtx = false;			// allocate context ourself
	
	for(arg=1; arg<argc; arg++) {
		argp = argv[arg];
		switch(argp[0]) {
			case 'a':
				if(argp[1] != '=') {
					usage(argv);
				}
				switch(argp[2]) {
					case 's':
						minAlg = maxAlg = ALG_ASC;
						break;
					case 'd':
						minAlg = maxAlg = ALG_DES;
						break;
					case '3':
						minAlg = maxAlg = ALG_3DES;
						break;
					case '2':
						minAlg = maxAlg = ALG_RC2;
						break;
					case '4':
						minAlg = maxAlg = ALG_RC4;
						break;
					case '5':
						minAlg = maxAlg = ALG_RC5;
						break;
					case 'a':
						minAlg = maxAlg = ALG_AES_128;
						break;
					case 'n':
						minAlg = maxAlg = ALG_AES_192;
						break;
					case 'A':
						minAlg = maxAlg = ALG_AES_256;
						break;
					case 'b':
						minAlg = maxAlg = ALG_BFISH;
						break;
					case 'c':
						minAlg = maxAlg = ALG_CAST;
						break;
					default:
						usage(argv);
				}
				if(maxAlg > ALG_LAST) {
					/* we left them in the switch but we can't use them */
					usage(argv);
				}
				break;
		    case 'l':
				loops = atoi(&argp[2]);
				break;
		    case 'n':
				minPtextSize = atoi(&argp[2]);
				break;
		    case 'm':
				maxPtextSize = atoi(&argp[2]);
				break;
		    case 'k':
		    	minKeySizeInBytes = maxKeySizeInBytes = atoi(&argp[2]);
		    	keySizeSpec = true;
				break;
			case 'x':
				allocCtxSpec = true;
				allocCtx = true;
				break;
			case 'X':
				allocCtxSpec = true;
				allocCtx = false;
				break;
		    case 'v':
		    	verbose = true;
				break;
		    case 'q':
		    	quiet = true;
				break;
		    case 'p':
		    	pauseInterval = atoi(&argp[2]);;
				break;
			case 'o':
				doPadding = false;
				paddingSpec = true;
				break;
			case 'e':
				doCbc = false;
				cbcSpec = true;
				break;
			case 'E':
				doCbc = true;
				cbcSpec = true;
				break;
		    case 'u':
		    	stagedEncr = false;
		    	stagedDecr = false;
				stagedSpec = true;
				break;
		    case 'U':
		    	stagedEncr = true;
		    	stagedDecr = true;
				stagedSpec = true;
				break;
		    case 'h':
		    default:
				usage(argv);
		}
	}
	ptext = (uint8 *)malloc(maxPtextSize);
	if(ptext == NULL) {
		printf("Insufficient heap space\n");
		exit(1);
	}
	/* ptext length set in test loop */
	
	printf("Starting ccSymTest; args: ");
	for(i=1; i<argc; i++) {
		printf("%s ", argv[i]);
	}
	printf("\n");
	
	if(pauseInterval) {
		fpurge(stdin);
		printf("Top of test; hit CR to proceed: ");
		getchar();
	}

	for(currAlg=minAlg; currAlg<=maxAlg; currAlg++) {
		switch(currAlg) {
			case ALG_DES:
				encrAlg = kCCAlgorithmDES;
				blockSize = kCCBlockSizeDES;
				minKeySizeInBytes = kCCKeySizeDES;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeDES;
				algStr = "DES";
				break;
			case ALG_3DES:
				encrAlg = kCCAlgorithm3DES;
				blockSize = kCCBlockSize3DES;
				minKeySizeInBytes = kCCKeySize3DES;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSize3DES;
				
				algStr = "3DES";
				break;
			case ALG_AES_128:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES128;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES128";
				break;
			case ALG_AES_192:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES192;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES192";
				break;
			case ALG_AES_256:
				encrAlg = kCCAlgorithmAES128;
				blockSize = kCCBlockSizeAES128;
				minKeySizeInBytes = kCCKeySizeAES256;
				maxKeySizeInBytes = minKeySizeInBytes;
				ctxSize = kCCContextSizeAES128;
				algStr = "AES256";
				break;
			case ALG_CAST:
				encrAlg = kCCAlgorithmCAST;
				blockSize = kCCBlockSizeCAST;
				minKeySizeInBytes = kCCKeySizeMinCAST;
				maxKeySizeInBytes = kCCKeySizeMaxCAST;
				ctxSize = kCCContextSizeCAST;
				algStr = "CAST";
				break;
			case ALG_RC4:
				encrAlg = kCCAlgorithmRC4;
				blockSize = 0;
				minKeySizeInBytes = kCCKeySizeMinRC4;
				maxKeySizeInBytes = kCCKeySizeMaxRC4;
				ctxSize = kCCContextSizeRC4;
				algStr = "RC4";
				break;
			default:
				printf("***BRRZAP!\n");
				exit(1);
		}
		if(!quiet || verbose) {
			printf("Testing alg %s\n", algStr);
		}
		for(loop=1; ; loop++) {
			ptextLen = genRand(minPtextSize, maxPtextSize);
			appGetRandomBytes(ptext, ptextLen);
			
			/* per-loop settings */
			if(!keySizeSpec) {
				if(minKeySizeInBytes == maxKeySizeInBytes) {
					keySizeInBytes = minKeySizeInBytes;
				}
				else {
					keySizeInBytes = genRand(minKeySizeInBytes, maxKeySizeInBytes);
				}
			}
			if(blockSize == 0) {
				/* stream cipher */
				doCbc = false;
				doPadding = false;
			}
			else {
				if(!cbcSpec) {
					doCbc = isBitSet(0, loop);
				}
				if(!paddingSpec) {
					doPadding = isBitSet(1, loop);
				}
			}
			if(!doPadding && (blockSize != 0)) {
				/* align plaintext */
				ptextLen = (ptextLen / blockSize) * blockSize;
				if(ptextLen == 0) {
					ptextLen = blockSize;
				}
			}
			if(!stagedSpec) {
				stagedEncr = isBitSet(2, loop);
				stagedDecr = isBitSet(3, loop);
			}
			if(doCbc) {
				nullIV = isBitSet(4, loop);
			}
			else {
				nullIV = false;
			}
			inPlace = isBitSet(5, loop);
			if(allocCtxSpec) {
				ctxSizeUsed = allocCtx ? ctxSize : 0;
			}
			else if(isBitSet(6, loop)) {
				ctxSizeUsed = ctxSize;
			}
			else {
				ctxSizeUsed = 0;
			}
			askOutSize = isBitSet(7, loop);
			if(!quiet) {
			   	if(verbose || ((loop % LOOP_NOTIFY) == 0)) {
					printf("..loop %3d ptextLen %lu keyLen %d cbc=%d padding=%d stagedEncr=%d "
							"stagedDecr=%d\n",
						loop, (unsigned long)ptextLen, (int)keySizeInBytes, 
						(int)doCbc, (int)doPadding,
					 	(int)stagedEncr, (int)stagedDecr);
					printf("           nullIV %d inPlace %d ctxSize %d askOutSize %d\n",
						(int)nullIV, (int)inPlace, (int)ctxSizeUsed, (int)askOutSize);
				}
			}
			
			if(doTest(ptext, ptextLen,
					encrAlg, doCbc, doPadding, nullIV,
					keySizeInBytes,
					stagedEncr,	stagedDecr, inPlace, ctxSizeUsed, askOutSize,
					quiet)) {
				rtn = 1;
				break;
			}
			if(pauseInterval && ((loop % pauseInterval) == 0)) {
				char c;
				fpurge(stdin);
				printf("Hit CR to proceed, q to abort: ");
				c = getchar();
				if(c == 'q') {
					goto testDone;
				}
			}
			if(loops && (loop == loops)) {
				break;
			}
		}	/* main loop */
		if(rtn) {
			break;
		}
		
	}	/* for algs */
	
testDone:
	if(pauseInterval) {
		fpurge(stdin);
		printf("ModuleDetach/Unload complete; hit CR to exit: ");
		getchar();
	}
	if((rtn == 0) && !quiet) {
		printf("%s test complete\n", argv[0]);
	}
	free(ptext);
	return rtn;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted LocalTests/testUtil/byteBuffer.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
 *  printByteBuffer.c
 *  byteutils
 *
 *  Created by Richard Murphy on 3/7/10.
 *  Copyright 2010 McKenzie-Murphy. All rights reserved.
 *
 */

#include "byteBuffer.h"

void printBytes(uint8_t *buff, size_t len, char *name)
{
	int i;
	printf("Dumping %d bytes from %s\n", (int) len, name);
	for(i=0; i<len; i++) {
		if(i > 0 && !(i%8)) putchar(' ');
		if(i > 0 && !(i%64)) putchar('\n');
		printf("%02x", buff[i]);
	}
	putchar('\n');
}

void printByteBuffer(byteBuffer bb, char *name)
{
    printBytes(bb->bytes, bb->len, name);
}


byteBuffer
mallocByteBuffer(size_t len)
{
	byteBuffer retval;
	if((retval = (byteBuffer) malloc(sizeof(byteBufferStruct) + len + 1)) == NULL) return NULL;
    retval->len = len;
    retval->bytes = (uint8_t *) (retval + 1) ; /* just past the byteBuffer in malloc'ed space */
    return retval;
}

/* utility function to convert hex character representation to their nibble (4 bit) values */
static uint8_t
nibbleFromChar(char c)
{
	if(c >= '0' && c <= '9') return c - '0';
	if(c >= 'a' && c <= 'f') return c - 'a' + 10;
	if(c >= 'A' && c <= 'F') return c - 'A' + 10;
	return 255;
}

/* Convert a string of characters representing a hex buffer into a series of bytes of that real value */
byteBuffer
hexStringToBytes(char *inhex)
{
	byteBuffer retval;
	uint8_t *p;
	int len, i;
	
	len = strlen(inhex) / 2;
	if((retval = mallocByteBuffer(len)) == NULL) return NULL;
    
	for(i=0, p = (uint8_t *) inhex; i<len; i++) {
		retval->bytes[i] = (nibbleFromChar(*p) << 4) | nibbleFromChar(*(p+1));
		p += 2;
	}
    retval->bytes[len] = 0;
	return retval;
}

byteBuffer
bytesToBytes(void *bytes, size_t len)
{
    byteBuffer retval = mallocByteBuffer(len);
    memcpy(retval->bytes, bytes, len);
    return retval;
}

int
bytesAreEqual(byteBuffer b1, byteBuffer b2)
{
    if(b1->len != b2->len) return 0;
    return (memcmp(b1->bytes, b2->bytes, b1->len) == 0);
}


static char byteMap[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
static int byteMapLen = sizeof(byteMap);

/* Utility function to convert nibbles (4 bit values) into a hex character representation */
static char
nibbleToChar(uint8_t nibble)
{
	if(nibble < byteMapLen) return byteMap[nibble];
	return '*';
}

/* Convert a buffer of binary values into a hex string representation */
char
*bytesToHexString(byteBuffer bb)
{
	char *retval;
	int i;
	
	retval = malloc(bb->len*2 + 1);
	for(i=0; i<bb->len; i++) {
		retval[i*2] = nibbleToChar(bb->bytes[i] >> 4);
		retval[i*2+1] = nibbleToChar(bb->bytes[i] & 0x0f);
	}
    retval[bb->len*2] = 0;
	return retval;
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































Deleted LocalTests/testUtil/byteBuffer.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
 *  printByteBuffer.h
 *  byteutils
 *
 */

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#ifndef _BYTEBUFFER_H_
#define _BYTEBUFFER_H_

typedef struct byte_buf {
    size_t  len;
    uint8_t  *bytes;
} byteBufferStruct, *byteBuffer;

void printByteBuffer(byteBuffer bb, char *name);

void printBytes(uint8_t *buff, size_t len, char *name);

byteBuffer
mallocByteBuffer(size_t len);

byteBuffer
hexStringToBytes(char *inhex);

byteBuffer
bytesToBytes(void *bytes, size_t len);

int
bytesAreEqual(byteBuffer b1, byteBuffer b2);

char
*bytesToHexString(byteBuffer bytes);

#endif _BYTEBUFFER_H_
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































Deleted LocalTests/utilLib/Makefile.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# name of executable to build
EXECUTABLE=libcsputils.a
# C++ source (with .cpp extension)
CPSOURCE= commonCpp.cpp nssAppUtils.cpp ssleayUtils.cpp
# C source (.c extension)
CSOURCE= common.c cspwrap.c fileIo.c bsafeUtils.c t_stdlib.c rijndael-alg-ref.c \
	rijndaelApi.c cputime.c

#
# project-specific libraries, e.g., -lstdc++
#
PROJ_LIBS= 
#
# Optional lib search paths
#
PROJ_LIBPATH=
#
# choose one for cc
#
VERBOSE=
#VERBOSE=-v

#
# Other files to remove at 'make clean' time
#
OTHER_TO_CLEAN=

#
# non-standard frameworks (e.g., -framework foo)
#
PROJ_FRAMEWORKS=

#
# project-specific includes, with leading -I
#
PROJ_INCLUDES= 

#
# Optional C flags (warnings, optimizations, etc.)
#
#PROJ_CFLAGS= -Os
PROJ_CFLAGS= 

#
# Optional link flags (using cc, not ld)
#
PROJ_LDFLAGS=

#
# Optional dependencies
#
PROJ_DEPENDS=

include ../Makefile.lib

# Special case for this object file...normally we ignore header dependencies, but
# this header is auto generated on a regular basis. 
$(OBJROOT)/commonCpp.o: commonCpp.cpp cssmErrorStrings.h
	$(CC) $(ALL_CFLAGS) -c -o $(OBJROOT)/commonCpp.o commonCpp.cpp
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































Deleted LocalTests/utilLib/boxes-ref.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
static const word8 Logtable[256] = {
  0,   0,  25,   1,  50,   2,  26, 198,  75, 199,  27, 104,  51, 238, 223,   3, 
100,   4, 224,  14,  52, 141, 129, 239,  76, 113,   8, 200, 248, 105,  28, 193, 
125, 194,  29, 181, 249, 185,  39, 106,  77, 228, 166, 114, 154, 201,   9, 120, 
101,  47, 138,   5,  33,  15, 225,  36,  18, 240, 130,  69,  53, 147, 218, 142, 
150, 143, 219, 189,  54, 208, 206, 148,  19,  92, 210, 241,  64,  70, 131,  56, 
102, 221, 253,  48, 191,   6, 139,  98, 179,  37, 226, 152,  34, 136, 145,  16, 
126, 110,  72, 195, 163, 182,  30,  66,  58, 107,  40,  84, 250, 133,  61, 186, 
 43, 121,  10,  21, 155, 159,  94, 202,  78, 212, 172, 229, 243, 115, 167,  87, 
175,  88, 168,  80, 244, 234, 214, 116,  79, 174, 233, 213, 231, 230, 173, 232, 
 44, 215, 117, 122, 235,  22,  11, 245,  89, 203,  95, 176, 156, 169,  81, 160, 
127,  12, 246, 111,  23, 196,  73, 236, 216,  67,  31,  45, 164, 118, 123, 183, 
204, 187,  62,  90, 251,  96, 177, 134,  59,  82, 161, 108, 170,  85,  41, 157, 
151, 178, 135, 144,  97, 190, 220, 252, 188, 149, 207, 205,  55,  63,  91, 209, 
 83,  57, 132,  60,  65, 162, 109,  71,  20,  42, 158,  93,  86, 242, 211, 171, 
 68,  17, 146, 217,  35,  32,  46, 137, 180, 124, 184,  38, 119, 153, 227, 165, 
103,  74, 237, 222, 197,  49, 254,  24,  13,  99, 140, 128, 192, 247, 112,   7, 
};

static const word8 Alogtable[256] = {
  1,   3,   5,  15,  17,  51,  85, 255,  26,  46, 114, 150, 161, 248,  19,  53, 
 95, 225,  56,  72, 216, 115, 149, 164, 247,   2,   6,  10,  30,  34, 102, 170, 
229,  52,  92, 228,  55,  89, 235,  38, 106, 190, 217, 112, 144, 171, 230,  49, 
 83, 245,   4,  12,  20,  60,  68, 204,  79, 209, 104, 184, 211, 110, 178, 205, 
 76, 212, 103, 169, 224,  59,  77, 215,  98, 166, 241,   8,  24,  40, 120, 136, 
131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206,  73, 219, 118, 154, 
181, 196,  87, 249,  16,  48,  80, 240,  11,  29,  39, 105, 187, 214,  97, 163, 
254,  25,  43, 125, 135, 146, 173, 236,  47, 113, 147, 174, 233,  32,  96, 160, 
251,  22,  58,  78, 210, 109, 183, 194,  93, 231,  50,  86, 250,  21,  63,  65, 
195,  94, 226,  61,  71, 201,  64, 192,  91, 237,  44, 116, 156, 191, 218, 117, 
159, 186, 213, 100, 172, 239,  42, 126, 130, 157, 188, 223, 122, 142, 137, 128, 
155, 182, 193,  88, 232,  35, 101, 175, 234,  37, 111, 177, 200,  67, 197,  84, 
252,  31,  33,  99, 165, 244,   7,   9,  27,  45, 119, 153, 176, 203,  70, 202, 
 69, 207,  74, 222, 121, 139, 134, 145, 168, 227,  62,  66, 198,  81, 243,  14, 
 18,  54,  90, 238,  41, 123, 141, 140, 143, 138, 133, 148, 167, 242,  13,  23, 
 57,  75, 221, 124, 132, 151, 162, 253,  28,  36, 108, 180, 199,  82, 246,   1, 
};

static const word8 S[256] = {
 99, 124, 119, 123, 242, 107, 111, 197,  48,   1, 103,  43, 254, 215, 171, 118, 
202, 130, 201, 125, 250,  89,  71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 
183, 253, 147,  38,  54,  63, 247, 204,  52, 165, 229, 241, 113, 216,  49,  21, 
  4, 199,  35, 195,  24, 150,   5, 154,   7,  18, 128, 226, 235,  39, 178, 117, 
  9, 131,  44,  26,  27, 110,  90, 160,  82,  59, 214, 179,  41, 227,  47, 132, 
 83, 209,   0, 237,  32, 252, 177,  91, 106, 203, 190,  57,  74,  76,  88, 207, 
208, 239, 170, 251,  67,  77,  51, 133,  69, 249,   2, 127,  80,  60, 159, 168, 
 81, 163,  64, 143, 146, 157,  56, 245, 188, 182, 218,  33,  16, 255, 243, 210, 
205,  12,  19, 236,  95, 151,  68,  23, 196, 167, 126,  61, 100,  93,  25, 115, 
 96, 129,  79, 220,  34,  42, 144, 136,  70, 238, 184,  20, 222,  94,  11, 219, 
224,  50,  58,  10,  73,   6,  36,  92, 194, 211, 172,  98, 145, 149, 228, 121, 
231, 200,  55, 109, 141, 213,  78, 169, 108,  86, 244, 234, 101, 122, 174,   8, 
186, 120,  37,  46,  28, 166, 180, 198, 232, 221, 116,  31,  75, 189, 139, 138, 
112,  62, 181, 102,  72,   3, 246,  14,  97,  53,  87, 185, 134, 193,  29, 158, 
225, 248, 152,  17, 105, 217, 142, 148, 155,  30, 135, 233, 206,  85,  40, 223, 
140, 161, 137,  13, 191, 230,  66, 104,  65, 153,  45,  15, 176,  84, 187,  22, 
};

static const word8 Si[256] = {
 82,   9, 106, 213,  48,  54, 165,  56, 191,  64, 163, 158, 129, 243, 215, 251, 
124, 227,  57, 130, 155,  47, 255, 135,  52, 142,  67,  68, 196, 222, 233, 203, 
 84, 123, 148,  50, 166, 194,  35,  61, 238,  76, 149,  11,  66, 250, 195,  78, 
  8,  46, 161, 102,  40, 217,  36, 178, 118,  91, 162,  73, 109, 139, 209,  37, 
114, 248, 246, 100, 134, 104, 152,  22, 212, 164,  92, 204,  93, 101, 182, 146, 
108, 112,  72,  80, 253, 237, 185, 218,  94,  21,  70,  87, 167, 141, 157, 132, 
144, 216, 171,   0, 140, 188, 211,  10, 247, 228,  88,   5, 184, 179,  69,   6, 
208,  44,  30, 143, 202,  63,  15,   2, 193, 175, 189,   3,   1,  19, 138, 107, 
 58, 145,  17,  65,  79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 
150, 172, 116,  34, 231, 173,  53, 133, 226, 249,  55, 232,  28, 117, 223, 110, 
 71, 241,  26, 113,  29,  41, 197, 137, 111, 183,  98,  14, 170,  24, 190,  27, 
252,  86,  62,  75, 198, 210, 121,  32, 154, 219, 192, 254, 120, 205,  90, 244, 
 31, 221, 168,  51, 136,   7, 199,  49, 177,  18,  16,  89,  39, 128, 236,  95, 
 96,  81, 127, 169,  25, 181,  74,  13,  45, 229, 122, 159, 147, 201, 156, 239, 
160, 224,  59,  77, 174,  42, 245, 176, 200, 235, 187,  60, 131,  83, 153,  97, 
 23,  43,   4, 126, 186, 119, 214,  38, 225, 105,  20,  99,  85,  33,  12, 125, 
};

static const word8 iG[4][4] = {
{ 0x0e, 0x09, 0x0d, 0x0b }, 
{ 0x0b, 0x0e, 0x09, 0x0d },
{ 0x0d, 0x0b, 0x0e, 0x09 }, 
{ 0x09, 0x0d, 0x0b, 0x0e } 
};

static const word32 rcon[30] = { 
  0x01,0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, };
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































Deleted LocalTests/utilLib/bsafeUtils.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
/*
 * bsafeUtils.c - common routines for CDSA/BSAFE compatibility testing
 */
 
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <security_bsafe/bsafe.h>
#include <security_bsafe/aglobal.h>
#include "bsafeUtils.h"
#include <Security/cssmerr.h>
#include "common.h"

/*
 * Convert between BSAFE ITEM and CSSM_DATA
 */
static inline void buItemToCssmData(
	const ITEM 		*item,
	CSSM_DATA_PTR	cdata)
{
	cdata->Data   = item->data;
	cdata->Length = item->len;
}

static inline void buCssmDataToItem(
	const CSSM_DATA		*cdata,
	ITEM 				*item)
{
	item->data = cdata->Data;
	item->len  = cdata->Length;
}

/*
 * BSafe's Chooser table - all we'll ever need.
 */
/*static*/ B_ALGORITHM_METHOD *BSAFE_ALGORITHM_CHOOSER[] = {
    // digests
    &AM_SHA,
    &AM_MD5,
	&AM_MD2,

    // organizational
    &AM_CBC_ENCRYPT,
    &AM_CBC_DECRYPT,
    &AM_ECB_ENCRYPT,
    &AM_ECB_DECRYPT,
    &AM_OFB_ENCRYPT,
    &AM_OFB_DECRYPT,

    // DES & variants
    &AM_DES_ENCRYPT,
    &AM_DES_DECRYPT,
    &AM_DESX_ENCRYPT,
    &AM_DESX_DECRYPT,
    &AM_DES_EDE_ENCRYPT,
    &AM_DES_EDE_DECRYPT,

    // RCn stuff
    &AM_RC2_CBC_ENCRYPT,
    &AM_RC2_CBC_DECRYPT,
    &AM_RC2_ENCRYPT,
    &AM_RC2_DECRYPT,
    &AM_RC4_ENCRYPT,
    &AM_RC4_DECRYPT,
    &AM_RC5_ENCRYPT,
    &AM_RC5_DECRYPT,
    &AM_RC5_CBC_ENCRYPT,
    &AM_RC5_CBC_DECRYPT,

    // RSA
    &AM_RSA_STRONG_KEY_GEN,
    &AM_RSA_KEY_GEN,
    &AM_RSA_CRT_ENCRYPT_BLIND,
    &AM_RSA_CRT_DECRYPT_BLIND,
    &AM_RSA_ENCRYPT,
    &AM_RSA_DECRYPT,

    // DSA
    &AM_DSA_PARAM_GEN,
    &AM_DSA_KEY_GEN,

    // signatures
    &AM_DSA_SIGN,
    &AM_DSA_VERIFY,

    // random number generation
    &AM_MD5_RANDOM,
    &AM_SHA_RANDOM,

    // sentinel
    (B_ALGORITHM_METHOD *)NULL_PTR
};

/* 
 * Convert a BSAFE return to a CSSM error and optionally print the error msg with 
 * the op in which the error occurred.
 */
static CSSM_RETURN buBsafeErrToCssm(
	int brtn, 
	const char *op)
{
	char *errStr = NULL;
	CSSM_RETURN crtn;
	
    switch (brtn) {
		case 0:
			return CSSM_OK;
		case BE_ALLOC:
			crtn = CSSMERR_CSSM_MEMORY_ERROR;
			errStr = "BE_ALLOC";
			break;
		case BE_SIGNATURE:
			crtn = CSSMERR_CSP_VERIFY_FAILED;
			errStr = "BE_SIGNATURE";
			break;
		case BE_OUTPUT_LEN:
			crtn = CSSMERR_CSP_OUTPUT_LENGTH_ERROR;
			errStr = "BE_OUTPUT_LEN";
			break;
		case BE_INPUT_LEN:
			crtn = CSSMERR_CSP_INPUT_LENGTH_ERROR;
			errStr = "BE_INPUT_LEN";
			break;
		case BE_EXPONENT_EVEN:
			crtn = CSSMERR_CSP_INVALID_KEY;
			errStr = "BE_EXPONENT_EVEN";
			break;
		case BE_EXPONENT_LEN:
			crtn = CSSMERR_CSP_INVALID_KEY;
			errStr = "BE_EXPONENT_LEN";
			break;
		case BE_EXPONENT_ONE:
			crtn = CSSMERR_CSP_INVALID_KEY;
			errStr = "BE_EXPONENT_ONE";
			break;
		case BE_DATA:
			crtn = CSSMERR_CSP_INVALID_DATA;
			errStr = "BE_DATA";
			break;
		case BE_INPUT_DATA:
			crtn = CSSMERR_CSP_INVALID_DATA;
			errStr = "BE_INPUT_DATA";
			break;
		case BE_WRONG_KEY_INFO:
			crtn = CSSMERR_CSP_INVALID_KEY;
			errStr = "BE_WRONG_KEY_INFO";
			break;
        default:
			//@@@ translate BSafe errors intelligently
 			crtn = CSSM_ERRCODE_INTERNAL_ERROR;
			errStr = "Other BSAFE error";
			break;
    }
	if(op != NULL) {
		printf("%s: BSAFE error %d (%s)\n", op, brtn, errStr);
	}
	return crtn;
}

/*
 * Non-thread-safe global random B_ALGORITHM_OBJ and a reusable init for it.
 */
static B_ALGORITHM_OBJ 	bsafeRng = NULL;
#define BSAFE_RANDSIZE	64

static B_ALGORITHM_OBJ buGetRng()
{
	int brtn;
	uint8 seed[BSAFE_RANDSIZE];
	
	if(bsafeRng != NULL) {
		return bsafeRng;
	}
	brtn = B_CreateAlgorithmObject(&bsafeRng);
	if(brtn) {
		buBsafeErrToCssm(brtn, "B_CreateAlgorithmObject(&bsafeRng)");
		return NULL;
	}
	brtn = B_SetAlgorithmInfo(bsafeRng, AI_X962Random_V0, NULL_PTR);
	if(brtn) {
		buBsafeErrToCssm(brtn, "B_SetAlgorithmInfo(bsafeRng)");
		return NULL;
	}
	brtn = B_RandomInit(bsafeRng, BSAFE_ALGORITHM_CHOOSER, NULL);
 	if(brtn) {
		buBsafeErrToCssm(brtn, "B_SetAlgorithmInfo(bsafeRng)");
		return NULL;
	}
	appGetRandomBytes(seed, BSAFE_RANDSIZE);
	brtn = B_RandomUpdate(bsafeRng, seed, BSAFE_RANDSIZE, NULL);
	if(brtn) {
		buBsafeErrToCssm(brtn, "B_RandomUpdate");
		return NULL;
	}
	return bsafeRng;
}

/*
 * Create a symmetric key.
 */
CSSM_RETURN  buGenSymKey(
	uint32			keySizeInBits,
	const CSSM_DATA	*keyData,
	BU_KEY			*key)			// RETURNED
{
	int				brtn;
	B_KEY_OBJ		bkey = NULL;
	ITEM			item;
	unsigned		keyBytes = (keySizeInBits + 7) / 8;
	
	if(keyBytes > keyData->Length) {
		/* note it's OK to give us too much key data */
		printf("***buGenSymKey: Insufficient keyData\n");
		return CSSM_ERRCODE_INTERNAL_ERROR;
	}

	/* create a BSAFE key */
	brtn = B_CreateKeyObject(&bkey);
	if(brtn) {
		return buBsafeErrToCssm(brtn, "B_CreateKeyObject");
	}
	
	/* assign data to the key */
	item.data = keyData->Data;
	item.len = keyBytes;
	brtn = B_SetKeyInfo(bkey, KI_Item, (POINTER)&item);
	if(brtn) {
		return buBsafeErrToCssm(brtn, "B_SetKeyInfo");
	}
	else {
		*key = bkey;
		return CSSM_OK;
	}
}

/*
 * Create asymmetric key pair.
 * FIXME - additional params (e.g. DSA params, RSA exponent)?
 */
CSSM_RETURN buGenKeyPair(
	uint32			keySizeInBits,
	CSSM_ALGORITHMS	keyAlg,			// CSSM_ALGID_{RSA,DSA}
	BU_KEY			*pubKey,		// RETURNED
	BU_KEY			*privKey)		// RETURNED
{
	int						brtn;
	B_KEY_OBJ				bPubkey = NULL;
	B_KEY_OBJ				bPrivkey = NULL;
	B_ALGORITHM_OBJ			keypairGen = NULL;
	char					*op = NULL;
	A_RSA_KEY_GEN_PARAMS	params;
	unsigned char 			exp[1] = { 3 };
    B_ALGORITHM_OBJ 		genDsaAlg = NULL;
    B_ALGORITHM_OBJ 		dsaResult = NULL;
	B_DSA_PARAM_GEN_PARAMS 	dsaParams;
	A_DSA_PARAMS 			*kParams = NULL;
	
	/* create algorithm object */
	brtn = B_CreateAlgorithmObject(&keypairGen);
	if(brtn) {
		return CSSMERR_CSSM_MEMORY_ERROR;
	}
	
	/* create two BSAFE keys */
	brtn = B_CreateKeyObject(&bPubkey);
	if(brtn) {
		op ="B_CreateKeyObject";
		goto abort;
	}
	brtn = B_CreateKeyObject(&bPrivkey);
	if(brtn) {
		op ="B_CreateKeyObject";
		goto abort;
	}
	switch(keyAlg) {
		case CSSM_ALGID_RSA:
		{
			/* set RSA-specific params */
			params.modulusBits = keySizeInBits;
			/* hack - parameterize? */
			params.publicExponent.data = exp;
			params.publicExponent.len = 1;
			brtn = B_SetAlgorithmInfo(keypairGen, AI_RSAKeyGen, 
				(POINTER)&params);
			if(brtn) {
				op ="B_SetAlgorithmInfo(AI_RSAKeyGen)";
			}
			break;
		}
		case CSSM_ALGID_DSA:	
		{
			/* jump through hoops generating parameters */
			brtn = B_CreateAlgorithmObject(&genDsaAlg);
			if(brtn) {
				op ="B_CreateAlgorithmObject";
				break;
			}
			dsaParams.primeBits = keySizeInBits;
        	brtn = B_SetAlgorithmInfo(genDsaAlg, AI_DSAParamGen, (POINTER)&dsaParams);
			if(brtn) {
				op = "B_SetAlgorithmInfo(AI_DSAParamGen)";
				break;
			}
			brtn = B_GenerateInit(genDsaAlg, BSAFE_ALGORITHM_CHOOSER, NULL);
			if(brtn) {
				op = "B_GenerateInit(AI_DSAParamGen)";
				break;
			}
        	brtn = B_CreateAlgorithmObject(&dsaResult);
			if(brtn) {
				op = "B_CreateAlgorithmObject";
				break;
			}
        	brtn = B_GenerateParameters(genDsaAlg, dsaResult, buGetRng(), NULL);
			if(brtn) {
				op = "B_GenerateParameters";
				break;
			}
			
			/* dsaResult now has the parameters, which we must extract and then
			 * apply to the keypairGen object. Cool, huh? */
			brtn = B_GetAlgorithmInfo((POINTER *)&kParams, dsaResult, AI_DSAKeyGen);
			if(brtn) {
				op = "B_GetAlgorithmInfo(AI_DSAKeyGen)";
				break;
			}
			brtn = B_SetAlgorithmInfo(keypairGen, AI_DSAKeyGen, (POINTER)kParams);
			if(brtn) {
				op ="B_SetAlgorithmInfo(AI_DSAKeyGen)";
			}
			break;
		}
		default:
			printf("buGenKeyPair: algorithm not supported\n");
			return CSSMERR_CSSM_FUNCTION_NOT_IMPLEMENTED;
	}
	if(brtn) {
		goto abort;
	}
	
	/* keypairGen all set to go. */
	brtn = B_GenerateInit(keypairGen, 
		BSAFE_ALGORITHM_CHOOSER,
		(A_SURRENDER_CTX *)NULL);
	if(brtn) {
		op = "B_GenerateInit";
		goto abort;
	}
	brtn = B_GenerateKeypair(keypairGen,
		bPubkey,
		bPrivkey,
		buGetRng(),
		NULL);
	if(brtn) {
		op = "B_GenerateInit";
	}
abort:
	B_DestroyAlgorithmObject(&keypairGen);
	B_DestroyAlgorithmObject(&genDsaAlg);
	B_DestroyAlgorithmObject(&dsaResult);
	if(brtn) {
		B_DestroyKeyObject(&bPubkey);
		B_DestroyKeyObject(&bPrivkey);
		return buBsafeErrToCssm(brtn, op);
	}
	else {
		*pubKey = bPubkey;
		*privKey = bPrivkey;
		return CSSM_OK;
	}
}

/*
 * Free a key created in buGenSymKey or buGenKeyPair
 */
CSSM_RETURN buFreeKey(
	BU_KEY			key)
{
	B_KEY_OBJ bkey = (B_KEY_OBJ)key;
	B_DestroyKeyObject(&bkey);
	return CSSM_OK;
}

/*
 * encrypt/decrypt
 */
CSSM_RETURN buEncryptDecrypt(
	BU_KEY				key,
	CSSM_BOOL			forEncrypt,
	CSSM_ALGORITHMS		encrAlg,
	CSSM_ENCRYPT_MODE	mode,				// CSSM_ALGMODE_CBC, etc.
	const CSSM_DATA		*iv,				//Êoptional per mode
	uint32				effectiveKeyBits,	// optional per key alg (actually just RC2)
											// for RSA, key size in bits
	uint32				rounds,				// optional, RC5 only
	const CSSM_DATA		*inData,
	CSSM_DATA_PTR		outData)			// mallocd and RETURNED
{
	B_ALGORITHM_OBJ		alg;
	int 				brtn;
	char				fbCipher = 1;
	uint32				blockSize = 0;
	unsigned			outBufLen;
	unsigned			bytesMoved;
	CSSM_RETURN			crtn;
	char				useIv;
	
	// these variables are used in the switch below and need to 
	// live until after setAlgorithm()
	ITEM	 			bsIv;
    B_BLK_CIPHER_W_FEEDBACK_PARAMS spec;
	A_RC5_PARAMS		rc5Params;
	A_RC2_PARAMS		rc2Params;
	
	brtn = B_CreateAlgorithmObject(&alg);
	if(brtn) {
		return buBsafeErrToCssm(brtn, "B_CreateAlgorithmObject");
	}
	
	/* per-alg setup */
	switch(encrAlg) {
		case CSSM_ALGID_RC4:
			/* the easy one */
			brtn = B_SetAlgorithmInfo(alg, AI_RC4, NULL);
			if(brtn) {
				crtn = buBsafeErrToCssm(brtn, "B_SetAlgorithmInfo");
				goto abort;
			}
			fbCipher = 0;
			break;
			
		case CSSM_ALGID_RSA:
			/* assume encrypt via publicm decrypt via private */
			if(forEncrypt) {
				brtn = B_SetAlgorithmInfo(alg, AI_PKCS_RSAPublic, NULL);
			}
			else {
				brtn = B_SetAlgorithmInfo(alg, AI_PKCS_RSAPrivate, NULL);
			}
			if(brtn) {
				crtn = buBsafeErrToCssm(brtn, "B_SetAlgorithmInfo(RSA)");
				goto abort;
			}
			blockSize = (effectiveKeyBits + 7) / 8;
			fbCipher = 0;
			break;
			
		/* common code using AI_FeebackCipher */
        case CSSM_ALGID_DES:
            spec.encryptionMethodName = (POINTER)"des";
			blockSize = 8;
            break;
        case CSSM_ALGID_DESX:
            spec.encryptionMethodName = (POINTER)"desx";
 			blockSize = 8;
			break;
        case CSSM_ALGID_3DES_3KEY_EDE:
            spec.encryptionMethodName = (POINTER)"des_ede";
			blockSize = 8;
            break;
        case CSSM_ALGID_RC5:
            spec.encryptionMethodName = (POINTER)"rc5";
			spec.encryptionParams = (POINTER)&rc5Params;
			rc5Params.version = 0x10;
			rc5Params.rounds = rounds;
			rc5Params.wordSizeInBits = 32;
			blockSize = 8;
            break;
        case CSSM_ALGID_RC2:
            spec.encryptionMethodName = (POINTER)"rc2";
			spec.encryptionParams = (POINTER)&rc2Params;
			rc2Params.effectiveKeyBits = effectiveKeyBits;
 			blockSize = 8;
           break;
		/* add other non-AI_FeebackCipher algorithms here */
		default:
			printf("buEncryptDecrypt: unknown algorithm\n");
			return CSSM_ERRCODE_INTERNAL_ERROR;
	}
	if(fbCipher) {
		useIv = 1;		// default, except for ECB
		switch(mode) {
			case CSSM_ALGMODE_CBCPadIV8:
				spec.feedbackMethodName = (POINTER)"cbc";
				spec.paddingMethodName = (POINTER)"pad";
				break;
			case CSSM_ALGMODE_CBC_IV8: 
				spec.feedbackMethodName = (POINTER)"cbc";
				spec.paddingMethodName = (POINTER)"nopad";
				break;
			case CSSM_ALGMODE_OFB_IV8: 
				spec.feedbackMethodName = (POINTER)"cbc";
				spec.paddingMethodName = (POINTER)"nopad";
				break;
			case CSSM_ALGMODE_ECB: 
				/* this does not seem to work yet - need info from 
				 * RSA. Specify block size as the feedbackParams (per manual)
				 * and get a memmove error trying to copy from address 8; specify
				 * an IV and get BSAFE error 524 (BE_INPUT_DATA) error on the
				 * EncryptInit.
				 */
				spec.feedbackMethodName = (POINTER)"ecb";
				spec.paddingMethodName = (POINTER)"nopad";
				//useIv = 0;
				//spec.feedbackParams = (POINTER)8;
				break;
			default:
				printf("buEncryptDecrypt: unknown mode\n");
				return CSSM_ERRCODE_INTERNAL_ERROR;
		}
		if(useIv && (iv != NULL)) {
			buCssmDataToItem(iv, &bsIv);
			spec.feedbackParams = (POINTER)&bsIv;
		}
		
		brtn = B_SetAlgorithmInfo(alg, AI_FeedbackCipher, (POINTER)&spec);
		if(brtn) {
			crtn = buBsafeErrToCssm(brtn, "B_SetAlgorithmInfo");
			goto abort;
		}
	}
	
	/*
	 * OK, one way or another we have an algorithm object. Set up
	 * output buffer.
	 */
	if(forEncrypt) {
		outBufLen = inData->Length + blockSize;
	}
	else {
		outBufLen = inData->Length;
	}
	outData->Length = 0;
	outData->Data = NULL;
	crtn = appSetupCssmData(outData, outBufLen);
	if(crtn) {
		goto abort;
	}
	if(forEncrypt) {
		brtn = B_EncryptInit(alg, 
			(B_KEY_OBJ)key,
			BSAFE_ALGORITHM_CHOOSER,
			(A_SURRENDER_CTX *)NULL);
		if(brtn) {
			crtn = buBsafeErrToCssm(brtn, "B_EncryptInit");
			goto abort;
		}
		brtn = B_EncryptUpdate(alg,
			outData->Data,
			&bytesMoved,
			outBufLen,
			inData->Data,
			inData->Length,
			buGetRng(),		// randAlg
			NULL);			// surrender
		if(brtn) {
			crtn = buBsafeErrToCssm(brtn, "B_EncryptInit");
			goto abort;
		}
		outData->Length = bytesMoved;
		brtn = B_EncryptFinal(alg,
			outData->Data + bytesMoved,
			&bytesMoved,
			outBufLen - outData->Length,
			buGetRng(),		// randAlg
			NULL);			// surrender
		if(brtn) {
			crtn = buBsafeErrToCssm(brtn, "B_EncryptFinal");
			goto abort;
		}
		outData->Length += bytesMoved;
		crtn = CSSM_OK;
	}
	else {
		brtn = B_DecryptInit(alg, 
			(B_KEY_OBJ)key,
			BSAFE_ALGORITHM_CHOOSER,
			(A_SURRENDER_CTX *)NULL);
		if(brtn) {
			crtn = buBsafeErrToCssm(brtn, "B_DecryptInit");
			goto abort;
		}
		brtn = B_DecryptUpdate(alg,
			outData->Data,
			&bytesMoved,
			outBufLen,
			inData->Data,
			inData->Length,
			NULL,			// randAlg
			NULL);			// surrender
		if(brtn) {
			crtn = buBsafeErrToCssm(brtn, "B_DecryptUpdate");
			goto abort;
		}
		outData->Length = bytesMoved;
		brtn = B_DecryptFinal(alg,
			outData->Data + bytesMoved,
			&bytesMoved,
			outBufLen - outData->Length,
			NULL,			// randAlg
			NULL);			// surrender
		if(brtn) {
			crtn = buBsafeErrToCssm(brtn, "B_DecryptFinal");
			goto abort;
		}
		outData->Length += bytesMoved;
		crtn = CSSM_OK;
	}
abort:
	B_DestroyAlgorithmObject(&alg);
	return crtn;
}

/* CSSM sig alg --> B_INFO_TYPE */
static CSSM_RETURN cssmSigAlgToInfoType(
	CSSM_ALGORITHMS cssmAlg,
	B_INFO_TYPE		*infoType)
{
	switch(cssmAlg) {
		case CSSM_ALGID_SHA1WithRSA:
			*infoType = AI_SHA1WithRSAEncryption;
			break;
		case CSSM_ALGID_MD5WithRSA:
			*infoType = AI_MD5WithRSAEncryption;
			break;
		case CSSM_ALGID_SHA1WithDSA:
			*infoType = AI_DSAWithSHA1;
			break;
		default:
			printf("cssmSigAlgToInfoType: unknown algorithm\n");
			return CSSMERR_CSSM_FUNCTION_NOT_IMPLEMENTED;
	}
	return CSSM_OK;
}

/*
 * Sign/verify
 */
CSSM_RETURN buSign(
	BU_KEY				key,
	CSSM_ALGORITHMS		sigAlg,
	const CSSM_DATA		*ptext,
	uint32				keySizeInBits,		// to set up sig
	CSSM_DATA_PTR		sig)				// mallocd and RETURNED
{
	B_ALGORITHM_OBJ		alg = NULL;
	int 				brtn;
	B_INFO_TYPE			infoType;
	CSSM_RETURN			crtn;
	unsigned			sigBytes;
	
	brtn = B_CreateAlgorithmObject(&alg);
	if(brtn) {
		return buBsafeErrToCssm(brtn, "B_CreateAlgorithmObject");
	}
	crtn = cssmSigAlgToInfoType(sigAlg, &infoType);
	if(crtn) {
		return crtn;
	}
	brtn = B_SetAlgorithmInfo(alg, infoType, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_SetAlgorithmInfo");
		goto abort;
	}
	brtn = B_SignInit(alg, (B_KEY_OBJ)key, BSAFE_ALGORITHM_CHOOSER, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_SignInit");
		goto abort;
	}
	brtn = B_SignUpdate(alg, ptext->Data, ptext->Length, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_SignUpdate");
		goto abort;
	}
	
	/* prepare for sig, size of key */
	sigBytes = (keySizeInBits + 7) / 8;
	sig->Data = (uint8 *)CSSM_MALLOC(sigBytes);
	sig->Length = sigBytes;
	
	brtn = B_SignFinal(alg, sig->Data, &sigBytes, sigBytes, buGetRng(), NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_SignFinal");
		goto abort;
	}
	sig->Length = sigBytes;
	crtn = CSSM_OK;
abort:
	B_DestroyAlgorithmObject(&alg);
	return crtn;
}

CSSM_RETURN buVerify(
	BU_KEY				key,
	CSSM_ALGORITHMS		sigAlg,
	const CSSM_DATA		*ptext,
	const CSSM_DATA		*sig)				// mallocd and RETURNED
{
	B_ALGORITHM_OBJ		alg = NULL;
	int 				brtn;
	B_INFO_TYPE			infoType;
	CSSM_RETURN			crtn;
	
	brtn = B_CreateAlgorithmObject(&alg);
	if(brtn) {
		return buBsafeErrToCssm(brtn, "B_CreateAlgorithmObject");
	}
	crtn = cssmSigAlgToInfoType(sigAlg, &infoType);
	if(crtn) {
		return crtn;
	}
	brtn = B_SetAlgorithmInfo(alg, infoType, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_SetAlgorithmInfo");
		goto abort;
	}
	brtn = B_VerifyInit(alg, (B_KEY_OBJ)key, BSAFE_ALGORITHM_CHOOSER, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_VerifyInit");
		goto abort;
	}
	brtn = B_VerifyUpdate(alg, ptext->Data, ptext->Length, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_VerifyUpdate");
		goto abort;
	}
	brtn = B_VerifyFinal(alg, sig->Data, sig->Length, buGetRng(), NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_VerifyFinal");
		goto abort;
	}
	crtn = CSSM_OK;
abort:
	B_DestroyAlgorithmObject(&alg);
	return crtn;
}

/* 
 * generate MAC either one update (updateSizes == NULL) or 
 * specified set of update sizes.
 */
#define MAX_MAC_SIZE	20

CSSM_RETURN buGenMac(
	BU_KEY				key,				// any key, any size
	CSSM_ALGORITHMS		macAlg,				// only CSSM_ALGID_SHA1HMAC for now
	const CSSM_DATA		*ptext,
	unsigned			*updateSizes,		// NULL --> random updates
											// else null-terminated list of sizes
	CSSM_DATA_PTR		mac)				// mallocd and RETURNED 
{
	B_ALGORITHM_OBJ		alg = NULL;
	int 				brtn;
	CSSM_RETURN			crtn;
	B_DIGEST_SPECIFIER	digestInfo;
	B_INFO_TYPE			infoType;
	unsigned			macBytes;
	
	brtn = B_CreateAlgorithmObject(&alg);
	if(brtn) {
		return buBsafeErrToCssm(brtn, "B_CreateAlgorithmObject");
	}
	switch(macAlg) {
		case CSSM_ALGID_SHA1HMAC:
		case CSSM_ALGID_SHA1HMAC_LEGACY:
			digestInfo.digestInfoType = AI_SHA1;
			infoType = AI_HMAC;
			break;
		default:
			printf("buGenMac: alg not supported\n");
			return CSSMERR_CSSM_FUNCTION_NOT_IMPLEMENTED;
	}
	digestInfo.digestInfoParams = NULL;
	brtn = B_SetAlgorithmInfo(alg, infoType, (POINTER)&digestInfo);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_SetAlgorithmInfo");
		goto abort;
	}
	brtn = B_DigestInit(alg, (B_KEY_OBJ)key, BSAFE_ALGORITHM_CHOOSER, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_DigestInit");
		goto abort;
	}
	if(updateSizes) {
		uint8 *currData = ptext->Data;
		while(*updateSizes) {
			brtn = B_DigestUpdate(alg, currData, *updateSizes, NULL);
			if(brtn) {
				crtn = buBsafeErrToCssm(brtn, "B_DigestUpdate");
				goto abort;
			}
			currData += *updateSizes;
			updateSizes++;
		}
	}
	else {
		/* one-shot */
		brtn = B_DigestUpdate(alg, ptext->Data, ptext->Length, NULL);
		if(brtn) {
			crtn = buBsafeErrToCssm(brtn, "B_DigestUpdate");
			goto abort;
		}
	}
	/* prepare for mac, magically gleaned max size */
	macBytes = MAX_MAC_SIZE;
	mac->Data = (uint8 *)CSSM_MALLOC(macBytes);
	mac->Length = macBytes;
	
	brtn = B_DigestFinal(alg, mac->Data, &macBytes, macBytes, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_DigestFinal");
		goto abort;
	}
	mac->Length = macBytes;
	crtn = CSSM_OK;
abort:
	B_DestroyAlgorithmObject(&alg);
	return crtn;

}

/* generate digest */
#define MAX_DIGEST_SIZE		20

CSSM_RETURN buGenDigest(
	CSSM_ALGORITHMS		macAlg,				// CSSM_ALGID_SHA1, etc. */
	const CSSM_DATA		*ptext,
	CSSM_DATA_PTR		digest)				// mallocd and RETURNED 
{
	B_ALGORITHM_OBJ		alg = NULL;
	int 				brtn;
	CSSM_RETURN			crtn;
	B_INFO_TYPE			infoType;
	unsigned			hashBytes;
	
	brtn = B_CreateAlgorithmObject(&alg);
	if(brtn) {
		return buBsafeErrToCssm(brtn, "B_CreateAlgorithmObject");
	}
	switch(macAlg) {
		case CSSM_ALGID_SHA1:
			infoType = AI_SHA1;
			break;
		case CSSM_ALGID_MD5:
			infoType = AI_MD5;
			break;
		case CSSM_ALGID_MD2:
			infoType = AI_MD2;
			break;
		default:
			printf("buGenDigest: alg not supported\n");
			return CSSMERR_CSSM_FUNCTION_NOT_IMPLEMENTED;
	}
	brtn = B_SetAlgorithmInfo(alg, infoType, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_SetAlgorithmInfo");
		goto abort;
	}
	brtn = B_DigestInit(alg, NULL, BSAFE_ALGORITHM_CHOOSER, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_DigestInit");
		goto abort;
	}
	brtn = B_DigestUpdate(alg, ptext->Data, ptext->Length, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_DigestUpdate");
		goto abort;
	}
	
	/* prepare for digest, magically gleaned max size */
	hashBytes = MAX_DIGEST_SIZE;
	digest->Data = (uint8 *)CSSM_MALLOC(hashBytes);
	digest->Length = hashBytes;
	
	brtn = B_DigestFinal(alg, digest->Data, &hashBytes, hashBytes, NULL);
	if(brtn) {
		crtn = buBsafeErrToCssm(brtn, "B_DigestFinal");
		goto abort;
	}
	digest->Length = hashBytes;
	crtn = CSSM_OK;
abort:
	B_DestroyAlgorithmObject(&alg);
	return crtn;

}

/*
 * Convert between BSAFE and CDSA private keys
 */
CSSM_RETURN buBsafePrivKeyToCdsa(
	CSSM_ALGORITHMS		keyAlg,
	uint32				keySizeInBits,
	BU_KEY				bsafePrivKey,
	CSSM_KEY_PTR		cdsaPrivKey)
{
	B_INFO_TYPE			infoType;
	ITEM				*keyBlob;
	int					brtn;
	CSSM_KEYBLOB_FORMAT	format;
	CSSM_KEYHEADER_PTR	hdr = &cdsaPrivKey->KeyHeader;
	
	/* what kind of info? */
	switch(keyAlg) {
		case CSSM_ALGID_RSA:
			infoType = KI_PKCS_RSAPrivateBER;
			format = CSSM_KEYBLOB_RAW_FORMAT_PKCS8;
			break;
		case CSSM_ALGID_DSA:
			infoType = KI_DSAPrivateBER;
			format = CSSM_KEYBLOB_RAW_FORMAT_FIPS186;
			break;
		default:
			printf("***buBsafePrivKeyToCdsa: bogus keyAlg\n");
			return CSSMERR_CSSM_FUNCTION_NOT_IMPLEMENTED;
	}
	
	/* get the blob */
	brtn = B_GetKeyInfo((POINTER *)&keyBlob,
		(B_KEY_OBJ)bsafePrivKey,
		infoType);
	if(brtn) {
		return buBsafeErrToCssm(brtn, "B_GetKeyInfo");
	}
	
	/* copy blob to CDSA key */
	cdsaPrivKey->KeyData.Data = (uint8 *)CSSM_MALLOC(keyBlob->len);
	cdsaPrivKey->KeyData.Length = keyBlob->len;
	memmove(cdsaPrivKey->KeyData.Data, keyBlob->data, keyBlob->len);
	
	/* set up CSSM key header */
	memset(hdr, 0, sizeof(CSSM_KEYHEADER));
	hdr->HeaderVersion = CSSM_KEYHEADER_VERSION;
	hdr->BlobType = CSSM_KEYBLOB_RAW;
	hdr->Format = format;
	hdr->AlgorithmId = keyAlg;
	hdr->KeyClass = CSSM_KEYCLASS_PRIVATE_KEY;
	hdr->LogicalKeySizeInBits = keySizeInBits;
	hdr->KeyAttr = CSSM_KEYATTR_EXTRACTABLE;
	hdr->KeyUsage = CSSM_KEYUSE_ANY;
	return CSSM_OK;
}

CSSM_RETURN buCdsaPrivKeyToBsafe(
	CSSM_KEY_PTR		cdsaPrivKey,
	BU_KEY				*bsafePrivKey)
{
	int 		brtn;
	B_KEY_OBJ	privKey = NULL;
	ITEM		keyBlob;
	B_INFO_TYPE	infoType;
	
	/* what kind of info? */
	switch(cdsaPrivKey->KeyHeader.AlgorithmId) {
		case CSSM_ALGID_RSA:
			infoType = KI_PKCS_RSAPrivateBER;
			break;
		case CSSM_ALGID_DSA:
			infoType = KI_DSAPrivateBER;
			break;
		default:
			printf("***buCdsaPrivKeyToCssm: bogus keyAlg\n");
			return CSSMERR_CSSM_FUNCTION_NOT_IMPLEMENTED;
	}
	
	/* create caller's key, assign blob to it */
	brtn = B_CreateKeyObject(&privKey);
	if(brtn) {
		return buBsafeErrToCssm(brtn, "B_CreateKeyObject");
	}
	buCssmDataToItem(&cdsaPrivKey->KeyData, &keyBlob);
	brtn = B_SetKeyInfo(privKey, infoType, (POINTER)&keyBlob);
	if(brtn) {
		return buBsafeErrToCssm(brtn, "B_SetKeyInfo");
	}
	*bsafePrivKey = privKey;
	return CSSM_OK;
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted LocalTests/utilLib/bsafeUtils.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
 * bsafeUtils.h - common routines for CDSA/BSAFE compatibility testing
 */

/*
 * Clients of this module do not need to know about or see anything from the 
 * BSAFE headers. 
 */
#ifndef	_BSAFE_UTILS_H_
#define _BSAFE_UTILS_H_
#include <Security/cssmtype.h>

#ifdef	__cplusplus
extern "C" {
#endif

/* Actually the same as a B_KEY_OBJ, but our callers don't need to know that */
typedef void *BU_KEY;

/*
 * Create a symmetric key.
 */
CSSM_RETURN  buGenSymKey(
	uint32			keySizeInBits,
	const CSSM_DATA	*keyData,
	BU_KEY			*key);			// RETURNED

/*
 * Create asymmetric key pair.
 * FIXME - additional params (e.g. DSA params, RSA exponent)?
 */
CSSM_RETURN buGenKeyPair(
	uint32			keySizeInBits,
	CSSM_ALGORITHMS	keyAlg,			// CSSM_ALGID_{RSA,DSA}
	BU_KEY			*pubKey,		// RETURNED
	BU_KEY			*privKey);		// RETURNED
	
/*
 * Free a key created in buGenSymKey or buGenKeyPair
 */
CSSM_RETURN buFreeKey(
	BU_KEY			key);

/*
 * encrypt/decrypt
 */
CSSM_RETURN buEncryptDecrypt(
	BU_KEY				key,
	CSSM_BOOL			forEncrypt,
	CSSM_ALGORITHMS		encrAlg,
	CSSM_ENCRYPT_MODE	mode,				// CSSM_ALGMODE_CBC, etc.
	const CSSM_DATA		*iv,				//Êoptional per mode
	uint32				effectiveKeyBits,	// optional per key alg (actually just RC2)
											// for RSA, key size in bits
	uint32				rounds,				// optional, RC5 only
	const CSSM_DATA		*inData,
	CSSM_DATA_PTR		outData);			// mallocd and RETURNED

/*
 * Sign/verify
 */
CSSM_RETURN buSign(
	BU_KEY				key,
	CSSM_ALGORITHMS		sigAlg,
	const CSSM_DATA		*ptext,
	uint32				keySizeInBits,		// to set up sig
	CSSM_DATA_PTR		sig);				// mallocd and RETURNED

CSSM_RETURN buVerify(
	BU_KEY				key,
	CSSM_ALGORITHMS		sigAlg,
	const CSSM_DATA		*ptext,
	const CSSM_DATA		*sig);				// mallocd and RETURNED

/* 
 * generate MAC either one update (updateSizes == NULL) or 
 * specified set of update sizes.
 */
CSSM_RETURN buGenMac(
	BU_KEY				key,				// any key, any size
	CSSM_ALGORITHMS		macAlg,				// only CSSM_ALGID_SHA1HMAC for now
	const CSSM_DATA		*ptext,
	unsigned			*updateSizes,		// NULL --> random updates
											// else null-terminated list of sizes
	CSSM_DATA_PTR		mac);				// mallocd and RETURNED 
	
/* generate digest */
CSSM_RETURN buGenDigest(
	CSSM_ALGORITHMS		macAlg,				// CSSM_ALGID_SHA1, etc. */
	const CSSM_DATA		*ptext,
	CSSM_DATA_PTR		digest);			// mallocd and RETURNED 
	
/*
 * Convert between BSAFE and CDSA private keys
 */
CSSM_RETURN buBsafePrivKeyToCdsa(
	CSSM_ALGORITHMS		keyAlg,
	uint32				keySizeInBits,
	BU_KEY				bsafePrivKey,
	CSSM_KEY_PTR		cdsaPrivKey);
CSSM_RETURN buCdsaPrivKeyToBsafe(
	CSSM_KEY_PTR		cdsaPrivKey,
	BU_KEY				*bsafePrivKey);

#ifdef	__cplusplus
}
#endif

#endif	/* _BSAFE_UTILS_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































Deleted LocalTests/utilLib/common.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/* Copyright 1997 Apple Computer, Inc.
 *
 * common.c - Common CSP test code
 *
 * Revision History
 * ----------------
 *   4 May 2000 Doug Mitchell
 *		Ported to X/CDSA2. 
 *   6 Jul 1998 Doug Mitchell at Apple
 *		Added clStartup().
 *  12 Aug 1997	Doug Mitchell at Apple
 *		Created.
 */
 
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <Security/cssm.h>
#include "common.h"
#include <Security/cssmapple.h>			/* apple, not intel */
#include <time.h>

static CSSM_VERSION vers = {2, 0};
//const static uint32 guidPrefix = 0xFADE;
const CSSM_GUID testGuid = { 0xFADE, 0, 0, { 1,2,3,4,5,6,7,0 }};

/*
 * We can't enable this until all of these are fixed and integrated:
 * 2890978 CSP
 * 2927474 CSPDL
 * 2928357 TP
 */
#define DETECT_MALLOC_ABUSE		1	

#if		DETECT_MALLOC_ABUSE

/* 
 * This set of allocator functions detects when we free something
 * which was mallocd by CDSA or a plugin using something other than
 * our callback malloc/realloc/calloc. With proper runtime support
 * (which is present in Jaguar 6C35), the reverse is also detected
 * by malloc (i.e., we malloc something and CDSA or a plugin frees
 * it).
 */
#define APP_MALLOC_MAGIC		'Util'

void * appMalloc (CSSM_SIZE size, void *allocRef) {
	void *ptr;

	/* scribble magic number in first four bytes */
	ptr = malloc(size + 4);
	*(uint32 *)ptr = APP_MALLOC_MAGIC;
	ptr = (char *)ptr + 4;

	return ptr;
}

void appFree (void *ptr, void *allocRef) {
	if(ptr == NULL) {
		return;
	}
	ptr = (char *)ptr - 4;
	if(*(uint32 *)ptr != APP_MALLOC_MAGIC) {
		printf("ERROR: appFree() freeing a block that we didn't allocate!\n");
		return;		// this free is not safe
	}
	*(uint32 *)ptr = 0;
	free(ptr);
}

/* Realloc - adjust both original pointer and size */
void * appRealloc (void *ptr, CSSM_SIZE size, void *allocRef) {
	if(ptr == NULL) {
		/* no ptr, no existing magic number */
		return appMalloc(size, allocRef);
	}
	ptr = (char *)ptr - 4;
	if(*(uint32 *)ptr != APP_MALLOC_MAGIC) {
		printf("ERROR: appRealloc() on a block that we didn't allocate!\n");
	}
	*(uint32 *)ptr = 0;
	ptr = realloc(ptr, size + 4);
	*(uint32 *)ptr = APP_MALLOC_MAGIC;
	ptr = (char *)ptr + 4;
	return ptr;
}

/* Have to do this manually */
void * appCalloc (uint32 num, CSSM_SIZE size, void *allocRef) {
	uint32 memSize = num * size;
	
	void *ptr = appMalloc(memSize, allocRef);
	memset(ptr, 0, memSize);
	return ptr;
}

#else	/* DETECT_MALLOC_ABUSE */
/*
 * Standard app-level memory functions required by CDSA.
 */
void * appMalloc (CSSM_SIZE size, void *allocRef) {
	return( malloc(size) );
}
void appFree (void *mem_ptr, void *allocRef) {
	free(mem_ptr);
 	return;
}
void * appRealloc (void *ptr, CSSM_SIZE size, void *allocRef) {
	return( realloc( ptr, size ) );
}
void * appCalloc (uint32 num, CSSM_SIZE size, void *allocRef) {
	return( calloc( num, size ) );
}
#endif	/* DETECT_MALLOC_ABUSE */

static CSSM_API_MEMORY_FUNCS memFuncs = {
	appMalloc,
	appFree,
	appRealloc,
 	appCalloc,
 	NULL
 };
 
/*
 * Init CSSM; returns CSSM_FALSE on error. Reusable.
 */
static CSSM_BOOL cssmInitd = CSSM_FALSE;

CSSM_BOOL cssmStartup()
{
	CSSM_RETURN  crtn;
    CSSM_PVC_MODE pvcPolicy = CSSM_PVC_NONE;
	
	if(cssmInitd) {
		return CSSM_TRUE;
	}  
	crtn = CSSM_Init (&vers, 
		CSSM_PRIVILEGE_SCOPE_NONE,
		&testGuid,
		CSSM_KEY_HIERARCHY_NONE,
		&pvcPolicy,
		NULL /* reserved */);
	if(crtn != CSSM_OK) 
	{
		printError("CSSM_Init", crtn);
		return CSSM_FALSE;
	}
	else {
		cssmInitd = CSSM_TRUE;
		return CSSM_TRUE;
	}
}

/*
 * Init CSSM and establish a session with the Apple CSP.
 */
CSSM_CSP_HANDLE cspStartup()
{
	return cspDlDbStartup(CSSM_TRUE, NULL);	
}

/* like cspStartup, but also returns DB handle. If incoming dbHandPtr
 * is NULL, no DB startup. */
CSSM_CSP_HANDLE cspDbStartup(
	CSSM_DB_HANDLE *dbHandPtr)
{
	return cspDlDbStartup(CSSM_TRUE, NULL);	
}

CSSM_CSP_HANDLE cspDlDbStartup(
	CSSM_BOOL bareCsp,			// true ==> CSP, false ==> CSP/DL
	CSSM_DB_HANDLE *dbHandPtr)	// optional - TO BE DELETED
{
	CSSM_CSP_HANDLE cspHand;
	CSSM_RETURN		crtn;
	const CSSM_GUID *guid;
	char *modName;
	
	if(dbHandPtr) {
		*dbHandPtr = 0;
	}
	if(cssmStartup() == CSSM_FALSE) {
		return 0;
	}
	if(bareCsp) {
		guid = &gGuidAppleCSP;
		modName = (char*) "AppleCSP";
	}
	else {
		guid = &gGuidAppleCSPDL;
		modName = (char *) "AppleCSPDL";
	}
	crtn = CSSM_ModuleLoad(guid,
		CSSM_KEY_HIERARCHY_NONE,
		NULL,			// eventHandler
		NULL);			// AppNotifyCallbackCtx
	if(crtn) {
		char outStr[100];
		sprintf(outStr, "CSSM_ModuleLoad(%s)", modName);
		printError(outStr, crtn);
		return 0;
	}
	crtn = CSSM_ModuleAttach (guid,
		&vers,
		&memFuncs,			// memFuncs
		0,					// SubserviceID
		CSSM_SERVICE_CSP,	
		0,					// AttachFlags
		CSSM_KEY_HIERARCHY_NONE,
		NULL,				// FunctionTable
		0,					// NumFuncTable
		NULL,				// reserved
		&cspHand);
	if(crtn) {
		char outStr[100];
		sprintf(outStr, "CSSM_ModuleAttach(%s)", modName);
		printError(outStr, crtn);
		return 0;
	}
	return cspHand;
}

/*
 * Detach and unload from a CSP.
 */
CSSM_RETURN cspShutdown(
	CSSM_CSP_HANDLE	cspHand,
	CSSM_BOOL bareCsp)			// true ==> CSP, false ==> CSP/DL
{
	CSSM_RETURN crtn;
	const CSSM_GUID *guid;
	char *modName;
	
	if(bareCsp) {
		guid = &gGuidAppleCSP;
		modName = (char *) "AppleCSP";
	}
	else {
		guid = &gGuidAppleCSPDL;
		modName = (char *) "AppleCSPDL";
	}
	crtn = CSSM_ModuleDetach(cspHand);
	if(crtn) {
		printf("Error detaching from %s\n", modName);
		printError("CSSM_ModuleDetach", crtn);
		return crtn;
	}
	crtn = CSSM_ModuleUnload(guid, NULL, NULL);
	if(crtn) {
		printf("Error unloading %s\n", modName);
		printError("CSSM_ModuleUnload", crtn);
	}
	return crtn;
}

/* Attach to DL side of CSPDL */
CSSM_DL_HANDLE dlStartup()
{
	CSSM_DL_HANDLE 	dlHand = 0;
	CSSM_RETURN		crtn;
	
	if(cssmStartup() == CSSM_FALSE) {
		return 0;
	}
	crtn = CSSM_ModuleLoad(&gGuidAppleCSPDL,
		CSSM_KEY_HIERARCHY_NONE,
		NULL,			// eventHandler
		NULL);			// AppNotifyCallbackCtx
	if(crtn) {
		printError("CSSM_ModuleLoad(Apple CSPDL)", crtn);
		return 0;
	}
	crtn = CSSM_ModuleAttach (&gGuidAppleCSPDL,
		&vers,
		&memFuncs,			// memFuncs
		0,					// SubserviceID
		CSSM_SERVICE_DL,	
		0,					// AttachFlags
		CSSM_KEY_HIERARCHY_NONE,
		NULL,				// FunctionTable
		0,					// NumFuncTable
		NULL,				// reserved
		&dlHand);
	if(crtn) {
		printError("CSSM_ModuleAttach(Apple CSPDL)", crtn);
		return 0;
	}
	return dlHand;
}

/*
 * Delete a DB.
 */
#define DELETE_WITH_AUTHENT		0
CSSM_RETURN dbDelete(
	CSSM_DL_HANDLE		dlHand,			// from dlStartup()
	const char 			*dbName)
{
	return CSSM_DL_DbDelete(dlHand, dbName, NULL, NULL);
}

/*
 * open a DB, ensure it's empty.
 */
CSSM_DB_HANDLE dbStartup(
	CSSM_DL_HANDLE		dlHand,			// from dlStartup()
	const char 			*dbName)
{
	CSSM_DB_HANDLE dbHand = 0;
	
	CSSM_RETURN crtn = dbCreateOpen(dlHand, dbName, 
		CSSM_TRUE,		// create
		CSSM_TRUE,		// delete
		NULL,			// pwd
		&dbHand);
	if(crtn == CSSM_OK) {
		return dbHand;
	}
	else {
		return 0;
	}
}

#if 0
/*
 * Attach to existing DB or create an empty new one.
 */
CSSM_DB_HANDLE dbStartupByName(CSSM_DL_HANDLE dlHand,
	char 		*dbName,
	CSSM_BOOL 	doCreate)
{
	CSSM_RETURN crtn;
	CSSM_DB_HANDLE				dbHand;
	
	/* try to open existing DB in either case */
	
	crtn = CSSM_DL_DbOpen(dlHand,
		dbName, 
		NULL,			// DbLocation
		CSSM_DB_ACCESS_READ | CSSM_DB_ACCESS_WRITE,
		NULL, 			// CSSM_ACCESS_CREDENTIALS *AccessCred
		NULL,			// void *OpenParameters
		&dbHand);
	if(dbHand != 0) {
		return dbHand;
	}
	if(!doCreate) {
		printf("***no such data base (%s)\n", dbName);
		printError("CSSM_DL_DbOpen", crtn);
		return 0;
	}
	/* have to create one */
	return dbStartup(dlHand, dbName);
}
#endif

/*
 * routines which convert various types to untyped byte arrays.
 */
void intToBytes(unsigned i, unsigned char *buf)
{
	*buf++ = (unsigned char)((i >> 24) & 0xff);
	*buf++ = (unsigned char)((i >> 16) & 0xff);
	*buf++ = (unsigned char)((i >> 8)  & 0xff);
	*buf   = (unsigned char)(i & 0xff);
}
void shortToBytes(unsigned short s, unsigned char *buf)
{
	*buf++ = (unsigned char)((s >> 8)  & 0xff);
	*buf   = (unsigned char)(s & 0xff);
}
unsigned bytesToInt(const unsigned char *buf) {
	unsigned result;
	result = (((unsigned)buf[0] << 24) & 0xff000000) |
		(((unsigned)buf[1] << 16) & 0x00ff0000) |
		(((unsigned)buf[2] << 8) & 0xff00) |
		(((unsigned)buf[3]) & 0xff);
	return result;
}
unsigned short bytesToShort(const unsigned char *buf) {
    	unsigned short result;
    	result = (((unsigned short)buf[0] << 8) & 0xff00) |
		 (((unsigned short)buf[1]) & 0xff);
    	return result;
}

/*
 * Given a context specified via a CSSM_CC_HANDLE, add a new
 * CSSM_CONTEXT_ATTRIBUTE to the context as specified by AttributeType,
 * AttributeLength, and an untyped pointer.
 *
 * This is currently used to add a second CSSM_KEY attribute when performing
 * ops with algorithm CSSM_ALGID_FEED and CSSM_ALGID_FEECFILE.
 */
CSSM_RETURN AddContextAttribute(CSSM_CC_HANDLE CCHandle,
	uint32 AttributeType,
	uint32 AttributeLength,
	ContextAttrType attrType,
	/* specify exactly one of these */
	const void *AttributePtr,
	uint32 attributeInt)
{
	CSSM_CONTEXT_ATTRIBUTE		newAttr;	
	CSSM_RETURN					crtn;
	
	newAttr.AttributeType     = AttributeType;
	newAttr.AttributeLength   = AttributeLength;
	if(attrType == CAT_Uint32) {
		newAttr.Attribute.Uint32  = attributeInt;
	}
	else {
		newAttr.Attribute.Data    = (CSSM_DATA_PTR)AttributePtr;
	}
	crtn = CSSM_UpdateContextAttributes(CCHandle, 1, &newAttr);
	if(crtn) {
		printError("CSSM_UpdateContextAttributes", crtn);
	}
	return crtn;
}

/*
 * Set up a CSSM data.
 */
CSSM_RETURN appSetupCssmData(
	CSSM_DATA_PTR	data,
	uint32			numBytes)
{
	if(data == NULL) {
		printf("Hey! appSetupCssmData with NULL Data!\n");
		return CSSMERR_CSSM_INTERNAL_ERROR;
	}
	data->Data = (uint8 *)CSSM_MALLOC(numBytes);
	if(data->Data == NULL) {
		return CSSMERR_CSSM_MEMORY_ERROR;
	}
	data->Length = numBytes;
	return CSSM_OK;
}

/*
 * Free the data referenced by a CSSM data, and optionally, the struct itself.
 */
void appFreeCssmData(CSSM_DATA_PTR data,
	CSSM_BOOL freeStruct)
{
	if(data == NULL) {
		return;
	}
	if(data->Length != 0) {
		CSSM_FREE(data->Data);
	}
	if(freeStruct) {
		CSSM_FREE(data);
	}
	else {
		data->Length = 0;
		data->Data = NULL;
	}
}

/*
 * Copy src to dst, mallocing dst.
 */
CSSM_RETURN appCopyCssmData(const CSSM_DATA *src, 
	CSSM_DATA_PTR dst)
{
	return appCopyData(src->Data, src->Length, dst);
}

/* copy raw data to a CSSM_DATA, mallocing dst. */
CSSM_RETURN  appCopyData(const void *src, 
	uint32 len,
	CSSM_DATA_PTR dst)
{
	dst->Length = 0;
	if(len == 0) {
		dst->Data = NULL;
		return CSSM_OK;
	}
	dst->Data = (uint8 *)CSSM_MALLOC(len);
	if(dst->Data == NULL) {
		return CSSM_ERRCODE_MEMORY_ERROR;
	}
	dst->Length = len;
	memcpy(dst->Data, src, len);
	return CSSM_OK;
}

CSSM_BOOL appCompareCssmData(const CSSM_DATA *d1,
	const CSSM_DATA *d2)
{	
	if(d1->Length != d2->Length) {
		return CSSM_FALSE;
	}
	if(memcmp(d1->Data, d2->Data, d1->Length)) {
		return CSSM_FALSE;
	}
	return CSSM_TRUE;	
}

/* min <= return <= max */
unsigned genRand(unsigned min, unsigned max)
{
	unsigned i;
	if(min == max) {
		return min;
	}
	appGetRandomBytes(&i, 4);
	return (min + (i % (max - min + 1)));
}	

void simpleGenData(CSSM_DATA_PTR dbuf, unsigned minBufSize, unsigned maxBufSize)
{
	unsigned len = genRand(minBufSize, maxBufSize);
	appGetRandomBytes(dbuf->Data, len);
	dbuf->Length = len;
}

#define MIN_OFFSET	0
#define MAX_OFFSET	99
#define MIN_ASCII	'a'
#define MAX_ASCII	'z'

/*
 * Calculate random data size, fill dataPool with that many random bytes.
 *
 * (10**minExp + MIN_OFFSET) <= size <= (10**maxExp + MAX_OFFSET)
 */
unsigned genData(unsigned char *dataPool,
	unsigned minExp,
	unsigned maxExp,
	dataType type)
{
	int 		exp;
	int 		offset;
	int 		size;
	char 		*cp;
	int 		i;
	char		ac;
	
	/*
	 * Calculate "random" size : (10 ** (random exponent)) + random offset
	 */
	exp = genRand(minExp, maxExp);
	offset = genRand(MIN_OFFSET, MAX_OFFSET);
	size = 1;
	while(exp--) {			// size = 10 ** exp
		size *= 10;
	}
	size += offset;
	switch(type) {
	    case DT_Zero:
			bzero(dataPool, size);
			break;
	    case DT_Increment:
			{
				int i;
				for(i=0; i<size; i++) {
					dataPool[i] = i;
				}
			}
			break;
	    case DT_ASCII:
	    	ac = MIN_ASCII;
			cp = (char *)dataPool;
	    	for(i=0; i<size; i++) {
				*cp++ = ac++;
				if(ac > MAX_ASCII) {
					ac = MIN_ASCII;
				}
			}
			break;
	    case DT_Random: 
			appGetRandomBytes(dataPool, size);
			break;
	}
	return size;
}

void dumpBuffer(
	const char *bufName,	// optional
	unsigned char *buf,
	unsigned len)
{
	unsigned i;
	
	if(bufName) {
		printf("%s\n", bufName);
	}
	printf("   ");
	for(i=0; i<len; i++) {
		printf("%02X ", buf[i]);
		if((i % 24) == 23) {
			printf("\n   ");
		}
	}
	printf("\n");
}

int testError(CSSM_BOOL quiet)
{
	char resp;
	
	if(quiet) {
		printf("\n***Test aborting.\n");
		exit(1);
	}
	fpurge(stdin);
	printf("a to abort, c to continue: ");
	resp = getchar();
	return (resp == 'a');
}

void testStartBanner(
	char *testName,
	int argc,
	char **argv)
{
	printf("Starting %s; args: ", testName);
	int i;
	for(i=1; i<argc; i++) {
		printf("%s ", argv[i]);
	}
	printf("\n");
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted LocalTests/utilLib/common.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
/* Copyright 1997 Apple Computer, Inc.
 *
 * common.h - Common CSP test code
 *
 * Revision History
 * ----------------
 *  12 Aug 1997	Doug Mitchell at Apple
 *		Created.
 */
 
#ifndef	_UTIL_LIB_COMMON_H_
#define _UTIL_LIB_COMMON_H_

#include <Security/cssm.h>

#ifdef	__cplusplus
extern "C" {
#endif

#undef COMMON_CSSM_MEMORY
#define COMMON_CSSM_MEMORY 0

#if		COMMON_CSSM_MEMORY
#define CSSM_MALLOC(size)			CSSM_Malloc(size)
#define CSSM_FREE(ptr)				CSSM_Free(ptr)
#define CSSM_CALLOC(num, size)		CSSM_Calloc(num, size)
#define CSSM_REALLOC(ptr, newSize)	CSSM_Realloc(ptr, newSize)
/* used in cspwrap when allocating memory on app's behalf */
#define appMalloc(size, allocRef)	CSSM_Malloc(size)

#else	/* !COMMON_CSSM_MEMORY */

void * appMalloc (CSSM_SIZE size, void *allocRef);
void appFree (void *mem_ptr, void *allocRef);
void * appRealloc (void *ptr, CSSM_SIZE size, void *allocRef);
void * appCalloc (uint32 num, CSSM_SIZE size, void *allocRef);

#define CSSM_MALLOC(size)			appMalloc(size, NULL)
#define CSSM_FREE(ptr)				appFree(ptr, NULL)
#define CSSM_CALLOC(num, size)		appCalloc(num, size, NULL)
#define CSSM_REALLOC(ptr, newSize)	appRealloc(ptr, newSize, NULL)

#endif	/* COMMON_CSSM_MEMORY */

/*
 * As of 23 March 1999, there is no longer a "default DB" available for
 * generating keys. This is the standard DB handle created when 
 * calling cspStartup().
 */
extern CSSM_DB_HANDLE commonDb;

/*
 * Init CSSM; returns CSSM_FALSE on error. Reusable.
 */
extern CSSM_BOOL cssmStartup();

/* various flavors of "start up the CSP with optional DB open" */
CSSM_CSP_HANDLE cspStartup();	// bare bones CSP
CSSM_CSP_HANDLE cspDbStartup(	// bare bones CSP, DB open
	CSSM_DB_HANDLE *dbHandPtr);	
CSSM_DL_HANDLE dlStartup();
CSSM_CSP_HANDLE cspDlDbStartup(	// one size fits all
	CSSM_BOOL bareCsp,			// true ==> CSP, false ==> CSP/DL
	CSSM_DB_HANDLE *dbHandPtr);	// optional
CSSM_RETURN cspShutdown(
	CSSM_CSP_HANDLE	cspHand,
	CSSM_BOOL bareCsp);			// true ==> CSP, false ==> CSP/DL
CSSM_RETURN dbDelete(
	CSSM_DL_HANDLE		dlHand,			// from dlStartup()
	const char 			*dbName);
CSSM_DB_HANDLE dbStartup(
	CSSM_DL_HANDLE		dlHand,			// from dlStartup()
	const char 			*dbName);
CSSM_RETURN dbCreateOpen(
	CSSM_DL_HANDLE		dlHand,			// from dlStartup()
	const char 			*dbName,
	CSSM_BOOL			doCreate,		// if false, must already exist	
	CSSM_BOOL			deleteExist,
	const char			*pwd,			// optional
	CSSM_DB_HANDLE		*dbHand);

extern void intToBytes(unsigned i, unsigned char *buf);
void shortToBytes(unsigned short s, unsigned char *buf);
unsigned bytesToInt(const unsigned char *buf);
unsigned short bytesToShort(const unsigned char *buf);

/* specify either 32-bit integer or a pointer as an added attribute value */
typedef enum {
	CAT_Uint32,
	CAT_Ptr
} ContextAttrType;

CSSM_RETURN AddContextAttribute(CSSM_CC_HANDLE CCHandle,
	uint32 AttributeType,
	uint32 AttributeLength,
	ContextAttrType attrType,
	/* specify exactly one of these */
	const void *AttributePtr,
	uint32 attributeInt);
void printError(const char *op, CSSM_RETURN err);
CSSM_RETURN appSetupCssmData(
	CSSM_DATA_PTR	data,
	uint32			numBytes);
void appFreeCssmData(CSSM_DATA_PTR data,
	CSSM_BOOL freeStruct);
CSSM_RETURN appCopyCssmData(const CSSM_DATA *src, 
	CSSM_DATA_PTR dst);
/* copy raw data to a CSSM_DATAm mallocing dst. */
CSSM_RETURN  appCopyData(const void *src, 
	uint32 len,
	CSSM_DATA_PTR dst);
	
/* returns CSSM_TRUE on success, else CSSM_FALSE */
CSSM_BOOL appCompareCssmData(const CSSM_DATA *d1,
	const CSSM_DATA *d2);
	
const char *cssmErrToStr(CSSM_RETURN err);

/*
 * Calculate random data size, fill dataPool with that many random bytes.
 */
typedef enum {
	DT_Random,
	DT_Increment,
	DT_Zero,
	DT_ASCII
} dataType;

unsigned genData(unsigned char *dataPool,
	unsigned minExp,
	unsigned maxExp,
	dataType type);
void simpleGenData(CSSM_DATA_PTR dbuf, unsigned minBufSize, unsigned maxBufSize);
unsigned genRand(unsigned min, unsigned max);
extern void	appGetRandomBytes(void *buf, unsigned len);

void dumpBuffer(
	const char *bufName,	// optional
	unsigned char *buf,
	unsigned len);

int testError(CSSM_BOOL quiet);

void testStartBanner(
	char *testName,
	int argc,
	char **argv);

#ifdef	__cplusplus
}

#endif
#endif	/* _UTIL_LIB_COMMON_H_*/


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































































































































































Deleted LocalTests/utilLib/commonCpp.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
//
// throw  C++-dependent stuff in here
//
#include <stdio.h>
#include <Security/cssm.h>
#include "common.h"
#include <Security/SecBasePriv.h>
#include <security_cdsa_client/keychainacl.h>
#include <security_cdsa_utilities/cssmacl.h>
#include <security_cdsa_client/aclclient.h>
#include <security_cdsa_utilities/cssmdata.h>
#include <security_cdsa_utilities/cssmalloc.h>
#include <security_utilities/devrandom.h>
#include <CoreFoundation/CFString.h>
#include "cssmErrorStrings.h"		/* generated error string table */

/*
 * Log CSSM error.
 */
void printError(const char *op, CSSM_RETURN err)
{
	cssmPerror(op, err);
}

const char *cssmErrToStr(CSSM_RETURN err)
{
	const ErrString *esp;
	
	for(esp=errStrings; esp->errStr!=NULL; esp++) {
		if(esp->errCode == err) {
			return esp->errStr;
		}
	}
	
	static char outbuf[512];
	sprintf(outbuf, "UNKNOWN ERROR CODE %d", (int)err);
	return outbuf;
}


/*
 * Open a DB, optionally:
 *
 *		-- ensuring it's empty
 *		-- creating it 
 *		-- Specifying optional password to avoid SecurityAgent UI.
 */
CSSM_RETURN dbCreateOpen(
	CSSM_DL_HANDLE		dlHand,			// from dlStartup()
	const char 			*dbName,
	CSSM_BOOL			doCreate,		// if false, must already exist	
	CSSM_BOOL			deleteExist,
	const char			*pwd,			// optional
	CSSM_DB_HANDLE		*dbHand)
{
	CSSM_RETURN		crtn;
	CSSM_DBINFO		dbInfo;
	
	if(deleteExist) {
		/* first delete possible existing DB, ignore error */
		crtn = dbDelete(dlHand, dbName);
		switch(crtn) {
			/* only allowed error is "no such file" */
			case CSSM_OK:
			case CSSMERR_DL_DATASTORE_DOESNOT_EXIST:
				break;
			default:
				printError("CSSM_DL_DbDelete", crtn);
				return crtn;
		}
		if(!doCreate) {
			printf("***Hey! dbCreateOpen with deleteExist and !doCreate\n");
			exit(1);
		}
	}
	else {
		/* 
		 * Try to open existing DB. This does not have a means
		 * to specify password (yet). 
		 */
		crtn = CSSM_DL_DbOpen(dlHand,
			dbName, 
			NULL,			// DbLocation
			CSSM_DB_ACCESS_READ | CSSM_DB_ACCESS_WRITE,
			NULL, 			// CSSM_ACCESS_CREDENTIALS *AccessCred
			NULL,			// void *OpenParameters
			dbHand);
		if(crtn == CSSM_OK) {
			return crtn;
		}
		if(!doCreate) {
			printError("CSSM_DL_DbOpen", crtn);
			printf("Error opening %s\n", dbName);
			return crtn;
		}
	}
	memset(&dbInfo, 0, sizeof(CSSM_DBINFO));
	
	/* now create it */
	if(pwd) {
		/*
		 * This glorious code copied from crlRefresh. I didn't pretend
		 * to understand it when I put it there either.
		 */
		Allocator &alloc = Allocator::standard();
		CssmClient::AclFactory::PasswordChangeCredentials 
			pCreds((StringData(pwd)), alloc);
		const AccessCredentials* aa = pCreds;
		TypedList subject(alloc, CSSM_ACL_SUBJECT_TYPE_ANY);
		AclEntryPrototype protoType(subject);
		AuthorizationGroup &authGroup = protoType.authorization();
		CSSM_ACL_AUTHORIZATION_TAG tag = CSSM_ACL_AUTHORIZATION_ANY;
		authGroup.NumberOfAuthTags = 1;
		authGroup.AuthTags = &tag;
	
		const ResourceControlContext rcc(protoType, 
			const_cast<AccessCredentials *>(aa));

		crtn = CSSM_DL_DbCreate(dlHand, 
			dbName,
			NULL,						// DbLocation
			&dbInfo,
			// &Security::KeychainCore::Schema::DBInfo,
			CSSM_DB_ACCESS_PRIVILEGED,
			&rcc,						// CredAndAclEntry
			NULL,						// OpenParameters
			dbHand);
	}
	else {
		crtn = CSSM_DL_DbCreate(dlHand, 
			dbName,
			NULL,						// DbLocation
			&dbInfo,
			// &Security::KeychainCore::Schema::DBInfo,
			CSSM_DB_ACCESS_PRIVILEGED,
			NULL,						// CredAndAclEntry
			NULL,						// OpenParameters
			dbHand);
	}
	if(crtn) {
		printError("CSSM_DL_DbCreate", crtn);
	}
	return crtn;
}

/*
 * *The* way for all tests to get random data.
 */
void appGetRandomBytes(void *buf, unsigned len)
{
	try {
		Security::DevRandomGenerator devRand(false);
		devRand.random(buf, len);
	}
	catch(...) {
		printf("***Hey! DevRandomGenerator threw an exception!\n");
		/* Yes, exit - I'd really like to catch one of these */
		exit(1);
	}
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































Deleted LocalTests/utilLib/cputime.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libc.h>
#include "cputime.h"

/* 
 * This returns the frequency of the TBR in cycles per second.
 */
static double GetTBRFreq(void) {
	mach_timebase_info_data_t tinfo;
	mach_timebase_info(&tinfo);
	
	double machRatio = (double)tinfo.numer / (double)tinfo.denom;
	return machRatio;
}

/*
 * Return TBR Frequency, getting it lazily once. May not be thread safe.
 */
static double TbrFreqLocal = 0.0;		// ration for NANOSECONDS
static double tbrFreq()
{
	if(TbrFreqLocal == 0.0) {
		TbrFreqLocal = GetTBRFreq();
		printf("machRatio %e\n", TbrFreqLocal);
	}
	return TbrFreqLocal;
}

// seconds
double CPUTimeDeltaSec(CPUTime from, CPUTime to)	
{
	CPUTime delta = to - from;
	return (double)delta * (tbrFreq() * (double)1e-9);
}

// milliseconds
double CPUTimeDeltaMs(CPUTime from, CPUTime to)
{
	CPUTime delta = to - from;
	return (double)delta * (tbrFreq() * (double)1e-6);
}

// microseconds
double CPUTimeDeltaUs(CPUTime from, CPUTime to)
{
	CPUTime delta = to - from;
	return (double)delta * (tbrFreq() * (double)1e-3);
}
	
/*
 * Calculate the average of an array of doubles. The lowest and highest values
 * are discarded if there are more than two samples. Typically used to get an
 * average of a set of values returned from CPUTimeDelta*().
 */
double CPUTimeAvg(
	const double *array,
	unsigned arraySize)
{
	double sum = 0;
	double lowest = array[0];
	double highest = array[0];
	
	unsigned dex;
	for(dex=0; dex<arraySize; dex++) {
		double curr = array[dex];
		sum += curr;
		if(curr < lowest) {
			lowest = curr;
		}
		if(curr > highest) {
			highest = curr;
		}
	}
	if(arraySize > 2) {
		sum -= lowest;
		sum -= highest;
		arraySize -= 2;
	}
	return sum / (double)arraySize;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































Deleted LocalTests/utilLib/cputime.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
 * Copyright (c) 2003 Apple Computer, Inc. All Rights Reserved.
 * 
 * The contents of this file constitute Original Code as defined in and are
 * subject to the Apple Public Source License Version 1.2 (the 'License').
 * You may not use this file except in compliance with the License. Please 
 * obtain a copy of the License at http://www.apple.com/publicsource and 
 * read it before using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER 
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, 
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. 
 * Please see the License for the specific language governing rights and 
 * limitations under the License.
 */

/*
 * cputime.h - high resolution timing module
 *
 * This module uses a highly machine-dependent mechanism to get timestamps
 * directly from CPU registers, without the overhead of a system call. The
 * timestamps are exported as type CPUTime and you should not concern yourself
 * with exactly what that is. 
 *
 * We provide routines to convert a difference between two CPUTimes as a double,
 * in seconds, milliseconds, and microseconds. Th
 *
 * The cost (time) of getting a timestamp (via CPUTimeRead()) generally takes
 * two or fewer times the resolution period, i.e., less than 80 ns on a 100 MHz
 * bus machine, often 40 ns.
 * 
 * The general usage of this module is as follows:
 *
 * {
 *		set up test scenario;
 *		CPUTime startTime = CPUTimeRead();
 *		...critical timed code here...
 *		CPUTime endTime = CPUTimeRead();
 * 		double elapsedMilliseconds = CPUTimeDeltaMs(startTime, endTime);
 * }
 *
 * It's crucial to place the CPUTimeDelta*() call OUTSIDE of the critical timed
 * area. It's really cheap to snag the timestamps, but it's not at all cheap
 * to convert the difference between two timestamps to a double. 
 */
 
#ifndef	_CPUTIME_H_
#define _CPUTIME_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <mach/mach_time.h>


typedef uint64_t CPUTime;

/*
 * Obtain machine-dependent, high resolution, cheap-to-read timestamp.
 */
#define CPUTimeRead() mach_absolute_time()

/*
 * Convert difference between two CPUTimes into various units.
 * Implemented as separate functions to preserve as much precision as possible
 * before required machine-dependent "divide by clock frequency".
 */
extern double CPUTimeDeltaSec(CPUTime from, CPUTime to);	// seconds
extern double CPUTimeDeltaMs(CPUTime from, CPUTime to);		// milliseconds
extern double CPUTimeDeltaUs(CPUTime from, CPUTime to);		// microseconds

/*
 * Calculate the average of an array of doubles. The lowest and highest values
 * are discarded if there are more than two samples. Typically used to get an
 * average of a set of values returned from CPUTimeDelta*().
 */
double CPUTimeAvg(
	const double *array,
	unsigned arraySize);

#ifdef __cplusplus
}
#endif

#endif	/* _CPUTIME_H_ */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































Deleted LocalTests/utilLib/cspdlTesting.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
 * cspdlTesting.h - workaround flags for testing CSPDL using CSP-oriented tests.
 */

#ifndef	_CSPDL_TESTING_H_
#define _CSPDL_TESTING_H_

#ifdef	__cplusplus
extern "C" {
#endif

/*
 * All generated keys must be reference keys.
 */
#define CSPDL_ALL_KEYS_ARE_REF		1

/*
 * 2nd/public key in two-key FEE ops must be raw. This is because the Security 
 * Server doesn't go in and deal with ref keys which are only found in a
 * Context.
 */
#define CSPDL_2ND_PUB_KEY_IS_RAW	1

/*
 * Ease off on restriction of ptext size == ctext size in case of symmetric 
 * en/decrypt with no padding. The sizes will be equal, but we can't ensure
 * that by mallocing exactly the right amount after because CSPDL doesn't
 * give an exact (proper) outputSize in this case (yet).
 */
#define CSPDL_NOPAD_ENFORCE_SIZE	1

/*
 * CSPDL can't do SHA1HMAC_LEGACY with bug-for-bug compatibility with 
 * BSAFE (sinceÊthe bug-for-bug feature involves doing actual HMAC updates
 * exactly as the app presents them).
 */
#define CSPDL_SHA1HMAC_LEGACY_ENABLE	0

/*
 * CSPDL does not support DSA GenerateAlgorithmParameters. Let the secure CSP
 * do it implicitly during key gen.
 */
#define CSPDL_DSA_GEN_PARAMS			0

/*
 * Can't generate keys with CSSM_KEYATTR_PRIVATE. Is this a bug or a feature?
 * Nobody pays any attention to this except the CSP, which rejects it. Shouldn't
 * either CSPDL or SS look at this and strip it off before sending the request
 * down to the CSP?
 */
#define CSPDL_KEYATTR_PRIVATE			0

/* 
 * ObtainPrivateKeyFromPublic key not implemented yet (if ever).
 */
#define CSPDL_OBTAIN_PRIV_FROM_PUB		0

/*** Workarounds for badattr test only ***/
 
/*
 * Munged header fields in a ref key should result in CSP_INVALID_KEY_REFERENCE,
 * but work fine.
 */
#define CSPDL_MUNGE_HEADER_CHECK		0

/* 
 * ALWAYS_SENSITIVE, NEVER_EXTRACTABLE are ignored, should result in 
 * CSP_INVALID_KEYATTR_MASK at key gen time.
 * FIXED per Radar 2879872.
 */
#define CSPDL_ALWAYS_SENSITIVE_CHECK	1
#define CSPDL_NEVER_EXTRACTABLE_CHECK	1

/*** end of badattr workarounds ***/

/* 
 * <rdar://problem/3732910> certtool can't generate keypair
 *
 * Until this is fixed - actually the underlying problem is in securityd - 
 * CSPDL can not generate a key pair without private and public both being 
 * PERMANENT.
 */
#define CSPDL_ALL_KEYS_ARE_PERMANENT	0


/***
 *** Other differences/bugs/oddities.
 ***/
 
/*
 * 1. SS wraps (encrypt) public keys when encoding them, thus the CSP has to allow
 *    wrapping of public keys. This may not be what we really want. See
 *    AppleCSP/AppleCSP/wrapKey.cpp for workaround per ALLOW_PUB_KEY_WRAP.
 */
 
#ifdef	__cplusplus
}
#endif

#endif	/* _CSPDL_TESTING_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































Deleted LocalTests/utilLib/cspwrap.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
/* Copyright 1997 Apple Computer, Inc.
 *
 * cspwrap.c - wrappers to simplify access to CDSA
 *
 * Revision History
 * ----------------
 *   3 May 2000 Doug Mitchell
 *		Ported to X/CDSA2.
 *  12 Aug 1997	Doug Mitchell at Apple
 *		Created.
 */
 
#include <Security/cssmapple.h>
#include <Security/cssm.h>
#include "cspwrap.h"
#include "common.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* MCF hack */
// #include <CarbonCore/MacTypes.h>
#include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacTypes.h>
/* end MCF */

#ifndef	NULL
#define NULL ((void *)0)
#endif	/* NULL */
#ifndef	MAX
#define MAX(a,b)	((a > b) ? a : b)
#define MIN(a,b)	((a < b) ? a : b)
#endif

#pragma mark --------- Key Generation ---------

/*
 * Key generation
 */
#define FEE_PRIV_DATA_SIZE	20
/*
 * Debug/test only. BsafeCSP only (long since disabled, in Puma).
 * This results in quicker but less secure RSA key generation.
 */
#define RSA_WEAK_KEYS		0

/*
 * Force bad data in KeyData prior to generating, deriving, or
 * wrapping key to ensure that the CSP ignores incoming
 * KeyData.
 */
static void setBadKeyData(
	CSSM_KEY_PTR key)
{
	key->KeyData.Data = (uint8 *)0xeaaaeaaa;	// bad ptr
	key->KeyData.Length = 1;	// no key can fit here
}

/*
 * Generate key pair of arbitrary algorithm. 
 * FEE keys will have random private data.
 */
CSSM_RETURN cspGenKeyPair(CSSM_CSP_HANDLE cspHand,
	uint32 algorithm,
	const char *keyLabel,
	unsigned keyLabelLen,
	uint32 keySize,					// in bits
	CSSM_KEY_PTR pubKey,			// mallocd by caller
	CSSM_BOOL pubIsRef,				// true - reference key, false - data
	uint32 pubKeyUsage,				// CSSM_KEYUSE_ENCRYPT, etc.
	CSSM_KEYBLOB_FORMAT pubFormat,	// Optional. Specify 0 or CSSM_KEYBLOB_RAW_FORMAT_NONE
									//   to get the default format. 
	CSSM_KEY_PTR privKey,			// mallocd by caller
	CSSM_BOOL privIsRef,			// true - reference key, false - data
	uint32 privKeyUsage,			// CSSM_KEYUSE_DECRYPT, etc.
	CSSM_KEYBLOB_FORMAT privFormat,	// optional 0 ==> default
	CSSM_BOOL genSeed)				// FEE only. True: we generate seed and CSP
									// will hash it. False: CSP generates random 
									// seed. 
{
	CSSM_RETURN				crtn;
	CSSM_CC_HANDLE 			ccHand;
	CSSM_DATA				privData = {0, NULL};		// mallocd for FEE
	CSSM_CRYPTO_DATA		privCData;
	CSSM_CRYPTO_DATA_PTR	privCDataPtr = NULL;
	CSSM_DATA				keyLabelData;
	uint32					pubAttr;
	uint32					privAttr;
	CSSM_RETURN 			ocrtn = CSSM_OK;
	
	/* pre-context-create algorithm-specific stuff */
	switch(algorithm) {
		case CSSM_ALGID_FEE:
			if(genSeed) {
				/* cook up random privData */
				privData.Data = (uint8 *)CSSM_MALLOC(FEE_PRIV_DATA_SIZE);
				privData.Length = FEE_PRIV_DATA_SIZE;
				appGetRandomBytes(privData.Data, FEE_PRIV_DATA_SIZE);
				privCData.Param = privData;
				privCData.Callback = NULL;
				privCDataPtr = &privCData;
			}
			/* else CSP generates random seed/key */
			
			if(keySize == CSP_KEY_SIZE_DEFAULT) {
				keySize = CSP_FEE_KEY_SIZE_DEFAULT;
			}
			break;
		case CSSM_ALGID_RSA:
			if(keySize == CSP_KEY_SIZE_DEFAULT) {
				keySize = CSP_RSA_KEY_SIZE_DEFAULT;
			}
			break;
		case CSSM_ALGID_DSA:
			if(keySize == CSP_KEY_SIZE_DEFAULT) {
				keySize = CSP_DSA_KEY_SIZE_DEFAULT;
			}
			break;
		default:
			printf("cspGenKeyPair: Unknown algorithm\n");
			/* but what the hey */
			privCDataPtr = NULL;
			break;
	}
	keyLabelData.Data        = (uint8 *)keyLabel,
	keyLabelData.Length      = keyLabelLen;
	memset(pubKey, 0, sizeof(CSSM_KEY));
	memset(privKey, 0, sizeof(CSSM_KEY));
	setBadKeyData(pubKey);
	setBadKeyData(privKey);
	
	crtn = CSSM_CSP_CreateKeyGenContext(cspHand,
		algorithm,
		keySize,
		privCDataPtr,			// Seed
		NULL,					// Salt
		NULL,					// StartDate
		NULL,					// EndDate
		NULL,					// Params
		&ccHand);
	if(crtn) {
		printError("CSSM_CSP_CreateKeyGenContext", crtn);
		ocrtn = crtn;
		goto abort;
	}
	/* cook up attribute bits */
	if(pubIsRef) {
		pubAttr = CSSM_KEYATTR_RETURN_REF | CSSM_KEYATTR_EXTRACTABLE;
	}
	else {
		pubAttr = CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE;
	}
	if(privIsRef) {
		privAttr = CSSM_KEYATTR_RETURN_REF | CSSM_KEYATTR_EXTRACTABLE;
	}
	else {
		privAttr = CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE;
	}

	/* post-context-create algorithm-specific stuff */
	switch(algorithm) {
		case CSSM_ALGID_RSA:
		
			#if	RSA_WEAK_KEYS
			{
				/* for testing, speed up key gen by using the
				* undocumented "CUSTOM" key gen mode. This
				* results in the CSP using AI_RsaKeyGen instead of
				* AI_RSAStrongKeyGen.
				*/
				crtn = AddContextAttribute(ccHand,
					CSSM_ATTRIBUTE_MODE,
					sizeof(uint32),		
					CAT_Uint32,
					NULL,
					CSSM_ALGMODE_CUSTOM);
				if(crtn) {
					printError("CSSM_UpdateContextAttributes", crtn);
					return crtn;
				}
			}
			#endif	// RSA_WEAK_KEYS
			break;
		 
		 case CSSM_ALGID_DSA:
			/* 
			 * extra step - generate params - this just adds some
			 * info to the context
			 */
			{
				CSSM_DATA dummy = {0, NULL};
				crtn = CSSM_GenerateAlgorithmParams(ccHand, 
					keySize, &dummy);
				if(crtn) {
					printError("CSSM_GenerateAlgorithmParams", crtn);
					return crtn;
				}
				appFreeCssmData(&dummy, CSSM_FALSE);
			}
			break;
		default:
			break;
	}
	
	/* optional format specifiers */
	if(!pubIsRef && (pubFormat != CSSM_KEYBLOB_RAW_FORMAT_NONE)) {
		crtn = AddContextAttribute(ccHand,
			CSSM_ATTRIBUTE_PUBLIC_KEY_FORMAT,
			sizeof(uint32),	
			CAT_Uint32,
			NULL,
			pubFormat);
		if(crtn) {
			printError("AddContextAttribute(CSSM_ATTRIBUTE_PUBLIC_KEY_FORMAT)", crtn);
			return crtn;
		}
	}
	if(!privIsRef && (privFormat != CSSM_KEYBLOB_RAW_FORMAT_NONE)) {
		crtn = AddContextAttribute(ccHand,
			CSSM_ATTRIBUTE_PRIVATE_KEY_FORMAT,
			sizeof(uint32),			// currently sizeof CSSM_DATA
			CAT_Uint32,
			NULL,
			privFormat);
		if(crtn) {
			printError("AddContextAttribute(CSSM_ATTRIBUTE_PRIVATE_KEY_FORMAT)", crtn);
			return crtn;
		}
	}
	crtn = CSSM_GenerateKeyPair(ccHand,
		pubKeyUsage,
		pubAttr,
		&keyLabelData,
		pubKey,
		privKeyUsage,
		privAttr,
		&keyLabelData,			// same labels
		NULL,					// CredAndAclEntry
		privKey);
	if(crtn) {
		printError("CSSM_GenerateKeyPair", crtn);
		ocrtn = crtn;
		goto abort;
	}
	/* basic checks...*/
	if(privIsRef) {
		if(privKey->KeyHeader.BlobType != CSSM_KEYBLOB_REFERENCE) {
			printf("privKey blob type: exp %u got %u\n",
				CSSM_KEYBLOB_REFERENCE, (unsigned)privKey->KeyHeader.BlobType);
			ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
			goto abort;
		}
	}
	else {
		switch(privKey->KeyHeader.BlobType) {
			case CSSM_KEYBLOB_RAW:
				break;
			default:
				printf("privKey blob type: exp raw, got %u\n",
					(unsigned)privKey->KeyHeader.BlobType);
				ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
				goto abort;
		}
	}
	if(pubIsRef) {
		if(pubKey->KeyHeader.BlobType != CSSM_KEYBLOB_REFERENCE) {
			printf("pubKey blob type: exp %u got %u\n",
				CSSM_KEYBLOB_REFERENCE, (unsigned)pubKey->KeyHeader.BlobType);
			ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
			goto abort;
		}
	}
	else {
		switch(pubKey->KeyHeader.BlobType) {
			case CSSM_KEYBLOB_RAW:
				break;
			default:
				printf("pubKey blob type: exp raw or raw_berder, got %u\n",
					(unsigned)pubKey->KeyHeader.BlobType);
				ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
				goto abort;
		}
	}
abort:
	if(ccHand != 0) {
		crtn = CSSM_DeleteContext(ccHand);
		if(crtn) {
			printError("CSSM_DeleteContext", crtn);
			ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
		}
	}
	if(privData.Data != NULL) {
		CSSM_FREE(privData.Data);
	}
	return ocrtn;
}

/*
 * Generate FEE key pair with optional primeType, curveType, and seed (password) data.
 */
CSSM_RETURN cspGenFEEKeyPair(CSSM_CSP_HANDLE cspHand,
	const char *keyLabel,
	unsigned keyLabelLen,
	uint32 keySize,					// in bits
	uint32 primeType,				// CSSM_FEE_PRIME_TYPE_MERSENNE, etc.
	uint32 curveType,				// CSSM_FEE_CURVE_TYPE_MONTGOMERY, etc.
	CSSM_KEY_PTR pubKey,			// mallocd by caller
	CSSM_BOOL pubIsRef,				// true - reference key, false - data
	uint32 pubKeyUsage,				// CSSM_KEYUSE_ENCRYPT, etc.
	CSSM_KEYBLOB_FORMAT pubFormat,	// Optional. Specify 0 or CSSM_KEYBLOB_RAW_FORMAT_NONE
									//   to get the default format. 
	CSSM_KEY_PTR privKey,			// mallocd by caller
	CSSM_BOOL privIsRef,			// true - reference key, false - data
	uint32 privKeyUsage,			// CSSM_KEYUSE_DECRYPT, etc.
	CSSM_KEYBLOB_FORMAT privFormat,	// optional 0 ==> default
	const CSSM_DATA *seedData)		// Present: CSP will hash this for private data.
									// NULL: CSP generates random seed. 
{
	CSSM_RETURN				crtn;
	CSSM_CC_HANDLE 			ccHand;
	CSSM_CRYPTO_DATA		privCData;
	CSSM_CRYPTO_DATA_PTR	privCDataPtr = NULL;
	CSSM_DATA				keyLabelData;
	uint32					pubAttr;
	uint32					privAttr;
	CSSM_RETURN 			ocrtn = CSSM_OK;
	
	/* pre-context-create algorithm-specific stuff */
	if(seedData) {
		privCData.Param = *((CSSM_DATA_PTR)seedData);
		privCData.Callback = NULL;
		privCDataPtr = &privCData;
	}
	/* else CSP generates random seed/key */
	
	if(keySize == CSP_KEY_SIZE_DEFAULT) {
		keySize = CSP_FEE_KEY_SIZE_DEFAULT;
	}

	keyLabelData.Data        = (uint8 *)keyLabel,
	keyLabelData.Length      = keyLabelLen;
	memset(pubKey, 0, sizeof(CSSM_KEY));
	memset(privKey, 0, sizeof(CSSM_KEY));
	setBadKeyData(pubKey);
	setBadKeyData(privKey);
	
	crtn = CSSM_CSP_CreateKeyGenContext(cspHand,
		CSSM_ALGID_FEE,
		keySize,
		privCDataPtr,			// Seed
		NULL,					// Salt
		NULL,					// StartDate
		NULL,					// EndDate
		NULL,					// Params
		&ccHand);
	if(crtn) {
		printError("CSSM_CSP_CreateKeyGenContext", crtn);
		ocrtn = crtn;
		goto abort;
	}
	/* cook up attribute bits */
	if(pubIsRef) {
		pubAttr = CSSM_KEYATTR_RETURN_REF | CSSM_KEYATTR_EXTRACTABLE;
	}
	else {
		pubAttr = CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE;
	}
	if(privIsRef) {
		privAttr = CSSM_KEYATTR_RETURN_REF | CSSM_KEYATTR_EXTRACTABLE;
	}
	else {
		privAttr = CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE;
	}

	/* optional post-context-create stuff */
	if(primeType != CSSM_FEE_PRIME_TYPE_DEFAULT) {
		crtn = AddContextAttribute(ccHand,
			CSSM_ATTRIBUTE_FEE_PRIME_TYPE,
			sizeof(uint32),		
			CAT_Uint32,
			NULL,
			primeType);
		if(crtn) {
			printError("AddContextAttribute(CSSM_ATTRIBUTE_FEE_PRIME_TYPE)", crtn);
			return crtn;
		}
	}
	if(curveType != CSSM_FEE_CURVE_TYPE_DEFAULT) {
		crtn = AddContextAttribute(ccHand,
			CSSM_ATTRIBUTE_FEE_CURVE_TYPE,
			sizeof(uint32),		
			CAT_Uint32,
			NULL,
			curveType);
		if(crtn) {
			printError("AddContextAttribute(CSSM_ATTRIBUTE_FEE_CURVE_TYPE)", crtn);
			return crtn;
		}
	}
	
	if(pubFormat != CSSM_KEYBLOB_RAW_FORMAT_NONE) {
		crtn = AddContextAttribute(ccHand,
			CSSM_ATTRIBUTE_PUBLIC_KEY_FORMAT,
			sizeof(uint32),		
			CAT_Uint32,
			NULL,
			pubFormat);
		if(crtn) {
			printError("AddContextAttribute(CSSM_ATTRIBUTE_PUBLIC_KEY_FORMAT)", crtn);
			return crtn;
		}
	}
	if(privFormat != CSSM_KEYBLOB_RAW_FORMAT_NONE) {
		crtn = AddContextAttribute(ccHand,
			CSSM_ATTRIBUTE_PRIVATE_KEY_FORMAT,
			sizeof(uint32),			// currently sizeof CSSM_DATA
			CAT_Uint32,
			NULL,
			pubFormat);
		if(crtn) {
			printError("AddContextAttribute(CSSM_ATTRIBUTE_PRIVATE_KEY_FORMAT)", crtn);
			return crtn;
		}
	}
	crtn = CSSM_GenerateKeyPair(ccHand,
		pubKeyUsage,
		pubAttr,
		&keyLabelData,
		pubKey,
		privKeyUsage,
		privAttr,
		&keyLabelData,			// same labels
		NULL,					// CredAndAclEntry
		privKey);
	if(crtn) {
		printError("CSSM_GenerateKeyPair", crtn);
		ocrtn = crtn;
		goto abort;
	}
	/* basic checks...*/
	if(privIsRef) {
		if(privKey->KeyHeader.BlobType != CSSM_KEYBLOB_REFERENCE) {
			printf("privKey blob type: exp %u got %u\n",
				CSSM_KEYBLOB_REFERENCE, (unsigned)privKey->KeyHeader.BlobType);
			ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
			goto abort;
		}
	}
	else {
		switch(privKey->KeyHeader.BlobType) {
			case CSSM_KEYBLOB_RAW:
				break;
			default:
				printf("privKey blob type: exp raw, got %u\n",
					(unsigned)privKey->KeyHeader.BlobType);
				ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
				goto abort;
		}
	}
	if(pubIsRef) {
		if(pubKey->KeyHeader.BlobType != CSSM_KEYBLOB_REFERENCE) {
			printf("pubKey blob type: exp %u got %u\n",
				CSSM_KEYBLOB_REFERENCE, (unsigned)pubKey->KeyHeader.BlobType);
			ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
			goto abort;
		}
	}
	else {
		switch(pubKey->KeyHeader.BlobType) {
			case CSSM_KEYBLOB_RAW:
				break;
			default:
				printf("pubKey blob type: exp raw or raw_berder, got %u\n",
					(unsigned)pubKey->KeyHeader.BlobType);
				ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
				goto abort;
		}
	}
abort:
	if(ccHand != 0) {
		crtn = CSSM_DeleteContext(ccHand);
		if(crtn) {
			printError("CSSM_DeleteContext", crtn);
			ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
		}
	}
	return ocrtn;
}

/*
 * Generate DSA key pair with optional generateAlgParams and optional
 * incoming parameters.
 */
CSSM_RETURN cspGenDSAKeyPair(CSSM_CSP_HANDLE cspHand,
	const char *keyLabel,
	unsigned keyLabelLen,
	uint32 keySize,					// in bits
	CSSM_KEY_PTR pubKey,			// mallocd by caller
	CSSM_BOOL pubIsRef,				// true - reference key, false - data
	uint32 pubKeyUsage,				// CSSM_KEYUSE_ENCRYPT, etc.
	CSSM_KEYBLOB_FORMAT pubFormat,	// Optional. Specify 0 or CSSM_KEYBLOB_RAW_FORMAT_NONE
									//   to get the default format. 
	CSSM_KEY_PTR privKey,			// mallocd by caller
	CSSM_BOOL privIsRef,			// true - reference key, false - data
	uint32 privKeyUsage,			// CSSM_KEYUSE_DECRYPT, etc.
	CSSM_KEYBLOB_FORMAT privFormat,	// Optional. Specify 0 or CSSM_KEYBLOB_RAW_FORMAT_NONE
									//   to get the default format. 
	CSSM_BOOL genParams,
	CSSM_DATA_PTR paramData)		// optional	
{
	CSSM_RETURN				crtn;
	CSSM_CC_HANDLE 			ccHand;
	CSSM_DATA				keyLabelData;
	uint32					pubAttr;
	uint32					privAttr;
	CSSM_RETURN 			ocrtn = CSSM_OK;
	
	if(keySize == CSP_KEY_SIZE_DEFAULT) {
		keySize = CSP_DSA_KEY_SIZE_DEFAULT;
	}
	keyLabelData.Data        = (uint8 *)keyLabel,
	keyLabelData.Length      = keyLabelLen;
	memset(pubKey, 0, sizeof(CSSM_KEY));
	memset(privKey, 0, sizeof(CSSM_KEY));
	setBadKeyData(pubKey);
	setBadKeyData(privKey);
	
	crtn = CSSM_CSP_CreateKeyGenContext(cspHand,
		CSSM_ALGID_DSA,
		keySize,
		NULL,					// Seed
		NULL,					// Salt
		NULL,					// StartDate
		NULL,					// EndDate
		paramData,
		&ccHand);
	if(crtn) {
		printError("CSSM_CSP_CreateKeyGenContext", crtn);
		ocrtn = crtn;
		goto abort;
	}
	
	/* cook up attribute bits */
	if(pubIsRef) {
		pubAttr = CSSM_KEYATTR_RETURN_REF | CSSM_KEYATTR_EXTRACTABLE;
	}
	else {
		pubAttr = CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE;
	}
	if(privIsRef) {
		privAttr = CSSM_KEYATTR_RETURN_REF | CSSM_KEYATTR_EXTRACTABLE;
	}
	else {
		privAttr = CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE;
	}

	if(genParams) {
		/* 
		 * extra step - generate params - this just adds some
		 * info to the context
		 */
		CSSM_DATA dummy = {0, NULL};
		crtn = CSSM_GenerateAlgorithmParams(ccHand, 
			keySize, &dummy);
		if(crtn) {
			printError("CSSM_GenerateAlgorithmParams", crtn);
			return crtn;
		}
		appFreeCssmData(&dummy, CSSM_FALSE);
	}
	
	/* optional format specifiers */
	if(!pubIsRef && (pubFormat != CSSM_KEYBLOB_RAW_FORMAT_NONE)) {
		crtn = AddContextAttribute(ccHand,
			CSSM_ATTRIBUTE_PUBLIC_KEY_FORMAT,
			sizeof(uint32),	
			CAT_Uint32,
			NULL,
			pubFormat);
		if(crtn) {
			printError("AddContextAttribute(CSSM_ATTRIBUTE_PUBLIC_KEY_FORMAT)", crtn);
			return crtn;
		}
	}
	if(!privIsRef && (privFormat != CSSM_KEYBLOB_RAW_FORMAT_NONE)) {
		crtn = AddContextAttribute(ccHand,
			CSSM_ATTRIBUTE_PRIVATE_KEY_FORMAT,
			sizeof(uint32),			// currently sizeof CSSM_DATA
			CAT_Uint32,
			NULL,
			privFormat);
		if(crtn) {
			printError("AddContextAttribute(CSSM_ATTRIBUTE_PRIVATE_KEY_FORMAT)", crtn);
			return crtn;
		}
	}

	crtn = CSSM_GenerateKeyPair(ccHand,
		pubKeyUsage,
		pubAttr,
		&keyLabelData,
		pubKey,
		privKeyUsage,
		privAttr,
		&keyLabelData,			// same labels
		NULL,					// CredAndAclEntry
		privKey);
	if(crtn) {
		printError("CSSM_GenerateKeyPair", crtn);
		ocrtn = crtn;
		goto abort;
	}
	/* basic checks...*/
	if(privIsRef) {
		if(privKey->KeyHeader.BlobType != CSSM_KEYBLOB_REFERENCE) {
			printf("privKey blob type: exp %u got %u\n",
				CSSM_KEYBLOB_REFERENCE, (unsigned)privKey->KeyHeader.BlobType);
			ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
			goto abort;
		}
	}
	else {
		switch(privKey->KeyHeader.BlobType) {
			case CSSM_KEYBLOB_RAW:
				break;
			default:
				printf("privKey blob type: exp raw, got %u\n",
					(unsigned)privKey->KeyHeader.BlobType);
				ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
				goto abort;
		}
	}
	if(pubIsRef) {
		if(pubKey->KeyHeader.BlobType != CSSM_KEYBLOB_REFERENCE) {
			printf("pubKey blob type: exp %u got %u\n",
				CSSM_KEYBLOB_REFERENCE, (unsigned)pubKey->KeyHeader.BlobType);
			ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
			goto abort;
		}
	}
	else {
		switch(pubKey->KeyHeader.BlobType) {
			case CSSM_KEYBLOB_RAW:
				break;
			default:
				printf("pubKey blob type: exp raw or raw_berder, got %u\n",
					(unsigned)pubKey->KeyHeader.BlobType);
				ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
				goto abort;
		}
	}
abort:
	if(ccHand != 0) {
		crtn = CSSM_DeleteContext(ccHand);
		if(crtn) {
			printError("CSSM_DeleteContext", crtn);
			ocrtn = CSSM_ERRCODE_INTERNAL_ERROR;
		}
	}
	return ocrtn;
}


uint32 cspDefaultKeySize(uint32 alg)
{
	uint32 keySizeInBits;
	switch(alg) {
		case CSSM_ALGID_DES:
			keySizeInBits = CSP_DES_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_3DES_3KEY:
		case CSSM_ALGID_DESX:
			keySizeInBits = CSP_DES3_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_RC2:
			keySizeInBits = CSP_RC2_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_RC4:
			keySizeInBits = CSP_RC4_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_RC5:
			keySizeInBits = CSP_RC5_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_ASC:
			keySizeInBits = CSP_ASC_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_BLOWFISH:
			keySizeInBits = CSP_BFISH_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_CAST:
			keySizeInBits = CSP_CAST_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_IDEA:
			keySizeInBits = CSP_IDEA_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_AES:
			keySizeInBits = CSP_AES_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_SHA1HMAC:
			keySizeInBits = CSP_HMAC_SHA_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_MD5HMAC:
			keySizeInBits = CSP_HMAC_MD5_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_FEE:
			keySizeInBits = CSP_FEE_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_RSA:
			keySizeInBits = CSP_RSA_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_DSA:
			keySizeInBits = CSP_DSA_KEY_SIZE_DEFAULT;
			break;
		case CSSM_ALGID_NONE:
			keySizeInBits = CSP_NULL_CRYPT_KEY_SIZE_DEF;
			break;
		default:
			printf("***cspDefaultKeySize: Unknown symmetric algorithm\n");
			keySizeInBits = 0;
			break;
	}
	return keySizeInBits;
}

/*
 * Create a random symmetric key.
 */
CSSM_KEY_PTR cspGenSymKey(CSSM_CSP_HANDLE cspHand,
		uint32 				alg,
		const char 			*keyLabel,
		unsigned 			keyLabelLen,
		uint32 				keyUsage,		// CSSM_KEYUSE_ENCRYPT, etc.
		uint32 				keySizeInBits,
		CSSM_BOOL			refKey)
{
	CSSM_KEY_PTR 		symKey = (CSSM_KEY_PTR)CSSM_MALLOC(sizeof(CSSM_KEY));
	CSSM_RETURN			crtn;
	CSSM_CC_HANDLE 		ccHand;
	uint32				keyAttr;
	CSSM_DATA			dummyLabel;
	
	if(symKey == NULL) {
		printf("Insufficient heap space\n");
		return NULL;
	}
	memset(symKey, 0, sizeof(CSSM_KEY));
	setBadKeyData(symKey);
	if(keySizeInBits == CSP_KEY_SIZE_DEFAULT) {
		keySizeInBits = cspDefaultKeySize(alg);
	}
	crtn = CSSM_CSP_CreateKeyGenContext(cspHand,
		alg,
		keySizeInBits,	// keySizeInBits
		NULL,			// Seed
		NULL,			// Salt
		NULL,			// StartDate
		NULL,			// EndDate
		NULL,			// Params
		&ccHand);
	if(crtn) {
		printError("CSSM_CSP_CreateKeyGenContext", crtn);
		goto errorOut;
	}
	if(refKey) {
		keyAttr = CSSM_KEYATTR_RETURN_REF | CSSM_KEYATTR_EXTRACTABLE;
	}
	else {
		keyAttr = CSSM_KEYATTR_RETURN_DATA | CSSM_KEYATTR_EXTRACTABLE;
	}
	dummyLabel.Length = keyLabelLen;
	dummyLabel.Data = (uint8 *)keyLabel;

	crtn = CSSM_GenerateKey(ccHand,
		keyUsage,
		keyAttr,
		&dummyLabel,
		NULL,			// ACL
		symKey);
	if(crtn) {
		printError("CSSM_GenerateKey", crtn);
		goto errorOut;
	}
	crtn = CSSM_DeleteContext(ccHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		goto errorOut;
	}
	return symKey;
errorOut:
	CSSM_FREE(symKey);
	return NULL;
}

/*
 * Derive symmetric key.
 * Note in the X CSP, we never return an IV. 
 */
CSSM_KEY_PTR cspDeriveKey(CSSM_CSP_HANDLE cspHand,
		uint32 				deriveAlg,		// CSSM_ALGID_PKCS5_PBKDF2, etc.
		uint32				keyAlg,			// CSSM_ALGID_RC5, etc.
		const char 			*keyLabel,
		unsigned 			keyLabelLen,
		uint32 				keyUsage,		// CSSM_KEYUSE_ENCRYPT, etc.
		uint32 				keySizeInBits,
		CSSM_BOOL			isRefKey,
		CSSM_DATA_PTR		password,		// in PKCS-5 lingo
		CSSM_DATA_PTR		salt,			// ditto
		uint32				iterationCnt,	// ditto
		CSSM_DATA_PTR		initVector)		// mallocd & RETURNED
{
	CSSM_KEY_PTR 				symKey = (CSSM_KEY_PTR)
									CSSM_MALLOC(sizeof(CSSM_KEY));
	CSSM_RETURN					crtn;
	CSSM_CC_HANDLE 				ccHand;
	uint32						keyAttr;
	CSSM_DATA					dummyLabel;
	CSSM_PKCS5_PBKDF2_PARAMS 	pbeParams;
	CSSM_DATA					pbeData;
	CSSM_ACCESS_CREDENTIALS		creds;
	
	if(symKey == NULL) {
		printf("Insufficient heap space\n");
		return NULL;
	}
	memset(symKey, 0, sizeof(CSSM_KEY));
	setBadKeyData(symKey);
	memset(&creds, 0, sizeof(CSSM_ACCESS_CREDENTIALS));
	if(keySizeInBits == CSP_KEY_SIZE_DEFAULT) {
		keySizeInBits = cspDefaultKeySize(keyAlg);
	}
	crtn = CSSM_CSP_CreateDeriveKeyContext(cspHand,
		deriveAlg,
		keyAlg,
		keySizeInBits,
		&creds,
		NULL,			// BaseKey
		iterationCnt,
		salt,
		NULL,			// seed
		&ccHand);
	if(crtn) {
		printError("CSSM_CSP_CreateDeriveKeyContext", crtn);
		goto errorOut;
	}
	keyAttr = CSSM_KEYATTR_EXTRACTABLE;
	if(isRefKey) {
		keyAttr |= (CSSM_KEYATTR_RETURN_REF | CSSM_KEYATTR_SENSITIVE);
	}
	else {
		keyAttr |= CSSM_KEYATTR_RETURN_DATA;
	}
	dummyLabel.Length = keyLabelLen;
	dummyLabel.Data = (uint8 *)keyLabel;
	
	/* passing in password is pretty strange....*/
	pbeParams.Passphrase = *password;
	pbeParams.PseudoRandomFunction = 
			CSSM_PKCS5_PBKDF2_PRF_HMAC_SHA1;
	pbeData.Data = (uint8 *)&pbeParams;
	pbeData.Length = sizeof(pbeParams);
	crtn = CSSM_DeriveKey(ccHand,
		&pbeData,
		keyUsage,
		keyAttr,
		&dummyLabel,
		NULL,			// cred and acl
		symKey);
	if(crtn) {
		printError("CSSM_DeriveKey", crtn);
		goto errorOut;
	}
	/* copy IV back to caller */
	/* Nope, not supported */
	#if 0
	if(pbeParams.InitVector.Data != NULL) {
		if(initVector->Data != NULL) {
			if(initVector->Length < pbeParams.InitVector.Length) {
				printf("***Insufficient InitVector\n");
				goto errorOut;
			}
		}
		else {
			initVector->Data = 
				(uint8 *)CSSM_MALLOC(pbeParams.InitVector.Length);
		}
		memmove(initVector->Data, pbeParams.InitVector.Data,
				pbeParams.InitVector.Length);
		initVector->Length = pbeParams.InitVector.Length;
		CSSM_FREE(pbeParams.InitVector.Data);
	}
	else {
		printf("***Warning: CSSM_DeriveKey, no InitVector\n");
	}
	#endif
	crtn = CSSM_DeleteContext(ccHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		goto errorOut;
	}
	return symKey;
errorOut:
	CSSM_FREE(symKey);
	return NULL;
}

/*
 * Cook up a symmetric key with specified key bits and other
 * params. Currently the CSPDL can only deal with reference keys except when
 * doing wrap/unwrap, so we manually cook up a raw key, then we null-unwrap it. 
 */
CSSM_RETURN cspGenSymKeyWithBits(
	CSSM_CSP_HANDLE		cspHand,
	CSSM_ALGORITHMS		keyAlg,
	CSSM_KEYUSE			keyUsage,
	const CSSM_DATA		*keyBits,
	unsigned			keySizeInBytes,
	CSSM_KEY_PTR		refKey)				// init'd and RETURNED
{
	CSSM_KEY			rawKey;
	CSSM_KEYHEADER_PTR	hdr = &rawKey.KeyHeader;
	CSSM_RETURN			crtn;
	
	/* set up a raw key the CSP will accept */
	memset(&rawKey, 0, sizeof(CSSM_KEY));
	hdr->HeaderVersion = CSSM_KEYHEADER_VERSION;
	hdr->BlobType = CSSM_KEYBLOB_RAW;
	hdr->Format = CSSM_KEYBLOB_RAW_FORMAT_OCTET_STRING;
	hdr->AlgorithmId = keyAlg;
	hdr->KeyClass = CSSM_KEYCLASS_SESSION_KEY;
	hdr->LogicalKeySizeInBits = keySizeInBytes * 8;
	hdr->KeyAttr = CSSM_KEYATTR_EXTRACTABLE;
	hdr->KeyUsage = keyUsage;
	appSetupCssmData(&rawKey.KeyData, keySizeInBytes);
	memmove(rawKey.KeyData.Data, keyBits->Data, keySizeInBytes);
	
	/* convert to a ref key */
	crtn = cspRawKeyToRef(cspHand, &rawKey, refKey);
	appFreeCssmData(&rawKey.KeyData, CSSM_FALSE);
	return crtn;
}

/*
 * Free a key. This frees a CSP's resources associated with the key if
 * the key is a reference key. It also frees key->KeyData. The CSSM_KEY
 * struct itself is not freed.
 * Note this has no effect on the CSP or DL cached keys unless the incoming
 * key is a reference key.
 */
CSSM_RETURN	cspFreeKey(CSSM_CSP_HANDLE cspHand,
	CSSM_KEY_PTR key)
{
	CSSM_RETURN crtn;
	crtn = CSSM_FreeKey(cspHand, 
		NULL,		// access cred
		key,
		CSSM_FALSE);	// delete - OK? maybe should parameterize?
	if(crtn) {
		printError("CSSM_FreeKey", crtn);
	}
	return crtn;
}

/* generate a random and reasonable key size in bits for specified CSSM algorithm */
uint32 randKeySizeBits(uint32 alg, 
	opType op)			// OT_Encrypt, etc.
{
	uint32 minSize;
	uint32 maxSize;
	uint32 size;
	
	switch(alg) {
		case CSSM_ALGID_DES:
			return CSP_DES_KEY_SIZE_DEFAULT;
		case CSSM_ALGID_3DES_3KEY:
		case CSSM_ALGID_DESX:
			return CSP_DES3_KEY_SIZE_DEFAULT;
		case CSSM_ALGID_ASC:
		case CSSM_ALGID_RC2:
		case CSSM_ALGID_RC4:
		case CSSM_ALGID_RC5:
			minSize = 5 * 8;
			maxSize = MAX_KEY_SIZE_RC245_BYTES * 8 ;	// somewhat arbitrary
			break;
		case CSSM_ALGID_BLOWFISH:
			minSize = 32;
			maxSize = 448;
			break;
		case CSSM_ALGID_CAST:
			minSize = 40;
			maxSize = 128;
			break;
		case CSSM_ALGID_IDEA:
			return CSP_IDEA_KEY_SIZE_DEFAULT;
		case CSSM_ALGID_RSA:
			minSize = CSP_RSA_KEY_SIZE_DEFAULT;
			maxSize = 1024;
			break;
		case CSSM_ALGID_DSA:
			/* signature only, no export restriction */
			minSize = 512;
			maxSize = 1024;
			break;
		case CSSM_ALGID_SHA1HMAC:
			minSize = 20 * 8;
			maxSize = 256 * 8;
			break;
		case CSSM_ALGID_MD5HMAC:
			minSize = 16 * 8;
			maxSize = 256 * 8;
			break;
		case CSSM_ALGID_FEE:
		case CSSM_ALGID_ECDSA:
		case CSSM_ALGID_SHA1WithECDSA:
			/* FEE, ECDSA require discrete sizes */
			size = genRand(1,3);
			switch(size) {
				case 1:
					return 31;
				case 2:
					if(alg == CSSM_ALGID_FEE) {
						return 127;
					}
					else {
						return 128;
					}
				case 3:
					return 161;
				case 5:
					return 192;
				default:
					printf("randKeySizeBits: internal error\n");
					return 0;
			}
		case CSSM_ALGID_AES:
			size = genRand(1, 3);
			switch(size) {
				case 1:
					return 128;
				case 2:
					return 192;
				case 3:
					return 256;
			}
		case CSSM_ALGID_NONE:
			return CSP_NULL_CRYPT_KEY_SIZE_DEF;
		default:
			printf("randKeySizeBits: unknown alg\n");
			return CSP_KEY_SIZE_DEFAULT;
	}
	size = genRand(minSize, maxSize);
	
	/* per-alg postprocessing.... */
	if(alg != CSSM_ALGID_RC2) {
		size &= ~0x7;
	}
	switch(alg) {
		case CSSM_ALGID_RSA:
			// new for X - strong keys */
			size &= ~(16 - 1);
			break;
		case CSSM_ALGID_DSA:
			/* size mod 64 == 0 */
			size &= ~(64 - 1);
			break;
		default:
			break;
	}
	return size;
}

#pragma mark --------- Encrypt/Decrypt ---------

/*
 * Encrypt/Decrypt
 */
/*
 * Common routine for encrypt/decrypt - cook up an appropriate context handle
 */
/*
 * When true, effectiveKeySizeInBits is passed down via the Params argument.
 * Otherwise, we add a customized context attribute.
 * Setting this true works with the stock Intel CSSM; this may well change.
 * Note this overloading prevent us from specifying RC5 rounds....
 */
#define EFFECTIVE_SIZE_VIA_PARAMS		0
CSSM_CC_HANDLE genCryptHandle(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEED, etc.
		uint32 mode,						// CSSM_ALGMODE_CBC, etc. - only for symmetric algs
		CSSM_PADDING padding,				// CSSM_PADDING_PKCS1, etc. 
		const CSSM_KEY *key0,
		const CSSM_KEY *key1,				// for CSSM_ALGID_FEED only - must be the 
											// public key
		const CSSM_DATA *iv,				// optional
		uint32 effectiveKeySizeInBits,		// 0 means skip this attribute
		uint32 rounds)						// ditto
{
	CSSM_CC_HANDLE cryptHand = 0;
	uint32 params;
	CSSM_RETURN crtn;
	CSSM_ACCESS_CREDENTIALS	creds;
	
	memset(&creds, 0, sizeof(CSSM_ACCESS_CREDENTIALS));
	#if	EFFECTIVE_SIZE_VIA_PARAMS
	params = effectiveKeySizeInBits;
	#else
	params = 0;
	#endif
	switch(algorithm) {
		case CSSM_ALGID_DES:
		case CSSM_ALGID_3DES_3KEY_EDE:
		case CSSM_ALGID_DESX:
		case CSSM_ALGID_ASC:
		case CSSM_ALGID_RC2:
		case CSSM_ALGID_RC4:
		case CSSM_ALGID_RC5:
		case CSSM_ALGID_AES:
		case CSSM_ALGID_BLOWFISH:
		case CSSM_ALGID_CAST:
		case CSSM_ALGID_IDEA:
		case CSSM_ALGID_NONE:		// used for wrapKey()
			crtn = CSSM_CSP_CreateSymmetricContext(cspHand,
				algorithm,
				mode,
				NULL,			// access cred
				key0,
				iv,				// InitVector
				padding,	
				NULL,			// Params
				&cryptHand);
			if(crtn) {
				printError("CSSM_CSP_CreateSymmetricContext", crtn);
				return 0;
			}
			break;
		case CSSM_ALGID_FEED:
		case CSSM_ALGID_FEEDEXP:
		case CSSM_ALGID_FEECFILE:
		case CSSM_ALGID_RSA:
			 crtn = CSSM_CSP_CreateAsymmetricContext(cspHand,
				algorithm,
				&creds,			// access
				key0,
				padding,
				&cryptHand);
			if(crtn) {
				printError("CSSM_CSP_CreateAsymmetricContext", crtn);
				return 0;
			}
			if(key1 != NULL) {
				/*
				 * FEED, some CFILE. Add (non-standard) second key attribute.
				 */
				crtn = AddContextAttribute(cryptHand,
						CSSM_ATTRIBUTE_PUBLIC_KEY,
						sizeof(CSSM_KEY),			// currently sizeof CSSM_DATA
						CAT_Ptr,
						key1,
						0);
				if(crtn) {
					printError("AddContextAttribute", crtn);
					return 0;
				}
			}
			if(mode != CSSM_ALGMODE_NONE) {
				/* special case, e.g., CSSM_ALGMODE_PUBLIC_KEY */
				crtn = AddContextAttribute(cryptHand,
						CSSM_ATTRIBUTE_MODE,
						sizeof(uint32),
						CAT_Uint32,
						NULL,
						mode);
				if(crtn) {
					printError("AddContextAttribute", crtn);
					return 0;
				}
			}
			break;
		default:
			printf("genCryptHandle: bogus algorithm\n");
			return 0;
	}
	#if		!EFFECTIVE_SIZE_VIA_PARAMS
	/* add optional EffectiveKeySizeInBits and rounds attributes */
	if(effectiveKeySizeInBits != 0) {
		CSSM_CONTEXT_ATTRIBUTE attr;
		attr.AttributeType = CSSM_ATTRIBUTE_EFFECTIVE_BITS;
		attr.AttributeLength = sizeof(uint32);
		attr.Attribute.Uint32 = effectiveKeySizeInBits;
		crtn = CSSM_UpdateContextAttributes(
			cryptHand,
			1,
			&attr);
		if(crtn) {
			printError("CSSM_UpdateContextAttributes", crtn);
			return crtn;
		}
	}
	#endif
	
	if(rounds != 0) {
		CSSM_CONTEXT_ATTRIBUTE attr;
		attr.AttributeType = CSSM_ATTRIBUTE_ROUNDS;
		attr.AttributeLength = sizeof(uint32);
		attr.Attribute.Uint32 = rounds;
		crtn = CSSM_UpdateContextAttributes(
			cryptHand,
			1,
			&attr);
		if(crtn) {
			printError("CSSM_UpdateContextAttributes", crtn);
			return crtn;
		}
	}

	return cryptHand;
}

CSSM_RETURN cspEncrypt(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEED, etc.
		uint32 mode,						// CSSM_ALGMODE_CBC, etc. - only for symmetric algs
		CSSM_PADDING padding,				// CSSM_PADDING_PKCS1, etc. 
		const CSSM_KEY *key,				// public or session key
		const CSSM_KEY *pubKey,				// for CSSM_ALGID_FEED, CSSM_ALGID_FEECFILE only
		uint32 effectiveKeySizeInBits,		// 0 means skip this attribute
		uint32 rounds,						// ditto
		const CSSM_DATA *iv,				// init vector, optional
		const CSSM_DATA *ptext,
		CSSM_DATA_PTR ctext,				// RETURNED
		CSSM_BOOL mallocCtext)				// if true, and ctext empty, malloc
											// by getting size from CSP
{
	CSSM_CC_HANDLE 	cryptHand;
	CSSM_RETURN		crtn;
	CSSM_SIZE		bytesEncrypted;
	CSSM_DATA		remData = {0, NULL};
	CSSM_RETURN		ocrtn = CSSM_OK;
	unsigned		origCtextLen;			// the amount we malloc, if any
	CSSM_RETURN		savedErr = CSSM_OK;
	CSSM_BOOL		restoreErr = CSSM_FALSE;
	
	cryptHand = genCryptHandle(cspHand, 
		algorithm, 
		mode, 
		padding,
		key, 
		pubKey, 
		iv, 
		effectiveKeySizeInBits,
		rounds);
	if(cryptHand == 0) {
		return CSSMERR_CSSM_INTERNAL_ERROR;
	}
	if(mallocCtext && (ctext->Length == 0)) {
		CSSM_QUERY_SIZE_DATA querySize;
		querySize.SizeInputBlock = ptext->Length;
		crtn = CSSM_QuerySize(cryptHand,
			CSSM_TRUE,						// encrypt
			1,
			&querySize);
		if(crtn) {
			printError("CSSM_QuerySize", crtn);
			ocrtn = crtn;
			goto abort;
		}
		if(querySize.SizeOutputBlock == 0) {
			/* CSP couldn't figure this out; skip our malloc */
			printf("***cspEncrypt: warning: cipherTextSize unknown; "
				"skipping malloc\n");
			origCtextLen = 0;
		}
		else {
			ctext->Data = (uint8 *)
				appMalloc(querySize.SizeOutputBlock, NULL);
			if(ctext->Data == NULL) {
				printf("Insufficient heap space\n");
				ocrtn = CSSM_ERRCODE_MEMORY_ERROR;
				goto abort;
			}
			ctext->Length = origCtextLen = querySize.SizeOutputBlock;
			memset(ctext->Data, 0, ctext->Length);
		}
	}
	else {
		origCtextLen = ctext->Length;
	}
	crtn = CSSM_EncryptData(cryptHand,
		ptext,
		1,
		ctext,
		1,
		&bytesEncrypted,
		&remData);
	if(crtn == CSSM_OK) {
		/*
		 * Deal with remData - its contents are included in bytesEncrypted.
		 */
		if((remData.Length != 0) && mallocCtext) {
			/* shouldn't happen - right? */
			if(bytesEncrypted > origCtextLen) {
				/* malloc and copy a new one */
				uint8 *newCdata = (uint8 *)appMalloc(bytesEncrypted, NULL);
				printf("**Warning: app malloced cipherBuf, but got nonzero "
					"remData!\n");
				if(newCdata == NULL) {
					printf("Insufficient heap space\n");
					ocrtn = CSSM_ERRCODE_MEMORY_ERROR;
					goto abort;
				}
				memmove(newCdata, ctext->Data, ctext->Length);
				memmove(newCdata+ctext->Length, remData.Data, remData.Length);
				CSSM_FREE(ctext->Data);
				ctext->Data = newCdata;
			}
			else {
				/* there's room left over */
				memmove(ctext->Data+ctext->Length, remData.Data, remData.Length);
			}
			ctext->Length = bytesEncrypted;
		}
		// NOTE: We return the proper length in ctext....
		ctext->Length = bytesEncrypted;
	}
	else {
		savedErr = crtn;
		restoreErr = CSSM_TRUE;
		printError("CSSM_EncryptData", crtn);
	}
abort:
	crtn = CSSM_DeleteContext(cryptHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	if(restoreErr) {
		ocrtn = savedErr;
	}
	return ocrtn;
}

#define PAD_IMPLIES_RAND_PTEXTSIZE	1
#define LOG_STAGED_OPS				0
#if		LOG_STAGED_OPS
#define soprintf(s)	printf s
#else
#define soprintf(s)
#endif

CSSM_RETURN cspStagedEncrypt(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEED, etc.
		uint32 mode,						// CSSM_ALGMODE_CBC, etc. - only for symmetric algs
		CSSM_PADDING padding,				// CSSM_PADDING_PKCS1, etc. 
		const CSSM_KEY *key,				// public or session key
		const CSSM_KEY *pubKey,				// for CSSM_ALGID_FEED, CSSM_ALGID_FEECFILE only
		uint32 effectiveKeySizeInBits,		// 0 means skip this attribute
		uint32 cipherBlockSize,				// ditto
		uint32 rounds,						// ditto
		const CSSM_DATA *iv,				// init vector, optional
		const CSSM_DATA *ptext,
		CSSM_DATA_PTR ctext,				// RETURNED, we malloc
		CSSM_BOOL multiUpdates)				// false:single update, true:multi updates
{
	CSSM_CC_HANDLE 	cryptHand;
	CSSM_RETURN		crtn;
	CSSM_SIZE		bytesEncrypted;			// per update
	CSSM_SIZE		bytesEncryptedTotal = 0;
	CSSM_RETURN		ocrtn = CSSM_OK;		// 'our' crtn
	unsigned		toMove;					// remaining
	unsigned		thisMove;				// bytes to encrypt on this update
	CSSM_DATA		thisPtext;				// running ptr into ptext
	CSSM_DATA		ctextWork;				// per update, mallocd by CSP
	CSSM_QUERY_SIZE_DATA querySize;
	uint8			*origCtext;				// initial ctext->Data
	unsigned		origCtextLen;			// amount we mallocd
	CSSM_BOOL		restoreErr = CSSM_FALSE;
	CSSM_RETURN		savedErr = CSSM_OK;
	
	
	cryptHand = genCryptHandle(cspHand, 
		algorithm, 
		mode, 
		padding,
		key, 
		pubKey, 
		iv,
		effectiveKeySizeInBits,
		rounds);
	if(cryptHand == 0) {
		return CSSMERR_CSP_INTERNAL_ERROR;
	}
	if(cipherBlockSize) {
		crtn = AddContextAttribute(cryptHand,
			CSSM_ATTRIBUTE_BLOCK_SIZE,
			sizeof(uint32),
			CAT_Uint32,
			NULL,
			cipherBlockSize);
		if(crtn) {
			printError("CSSM_UpdateContextAttributes", crtn);
			goto abort;
		}
	}
	
	/* obtain total required ciphertext size and block size */
	querySize.SizeInputBlock = ptext->Length;
	crtn = CSSM_QuerySize(cryptHand,
		CSSM_TRUE,						// encrypt
		1,
		&querySize);
	if(crtn) {
		printError("CSSM_QuerySize(1)", crtn);
		ocrtn = CSSMERR_CSP_INTERNAL_ERROR;
		goto abort;
	}
	if(querySize.SizeOutputBlock == 0) {
		/* CSP couldn't figure this out; skip our malloc - caller is taking its
		 * chances */
		printf("***cspStagedEncrypt: warning: cipherTextSize unknown; aborting\n");
		ocrtn = CSSMERR_CSP_INTERNAL_ERROR;
		goto abort;
	}
	else {
		origCtextLen = querySize.SizeOutputBlock;
		if(algorithm == CSSM_ALGID_ASC) {
			/* ASC is weird - the more chunks we do, the bigger the
			 * resulting ctext...*/
			origCtextLen *= 2;
		}
		ctext->Length = origCtextLen;
		ctext->Data   = origCtext = (uint8 *)appMalloc(origCtextLen, NULL);
		if(ctext->Data == NULL) {
			printf("Insufficient heap space\n");
			ocrtn = CSSMERR_CSP_MEMORY_ERROR;
			goto abort;
		}
		memset(ctext->Data, 0, ctext->Length);
	}

	crtn = CSSM_EncryptDataInit(cryptHand);
	if(crtn) {
		printError("CSSM_EncryptDataInit", crtn);
		ocrtn = crtn;
		goto abort;
	}
	
	toMove = ptext->Length;
	thisPtext.Data = ptext->Data;
	while(toMove) {
		if(multiUpdates) {
			thisMove = genRand(1, toMove);
		}
		else {
			/* just do one pass thru this loop */
			thisMove = toMove;
		}
		thisPtext.Length = thisMove;
		/* let CSP do the individual mallocs */
		ctextWork.Data = NULL;
		ctextWork.Length = 0;
		soprintf(("*** EncryptDataUpdate: ptextLen 0x%x\n", thisMove));
		crtn = CSSM_EncryptDataUpdate(cryptHand,
			&thisPtext,
			1,
			&ctextWork,
			1,
			&bytesEncrypted);
		if(crtn) {
			printError("CSSM_EncryptDataUpdate", crtn);
			ocrtn = crtn;
			goto abort;
		}
		// NOTE: We return the proper length in ctext....
		ctextWork.Length = bytesEncrypted;
		soprintf(("*** EncryptDataUpdate: ptextLen 0x%x  bytesEncrypted 0x%x\n",
			thisMove, bytesEncrypted));
		thisPtext.Data += thisMove;
		toMove         -= thisMove;
		if(bytesEncrypted > ctext->Length) {
			printf("cspStagedEncrypt: ctext overflow!\n");
			ocrtn = crtn;
			goto abort;
		}
		if(bytesEncrypted != 0) {
			memmove(ctext->Data, ctextWork.Data, bytesEncrypted);
			bytesEncryptedTotal += bytesEncrypted;
			ctext->Data         += bytesEncrypted;
			ctext->Length       -= bytesEncrypted;
		}
		if(ctextWork.Data != NULL) {
			CSSM_FREE(ctextWork.Data);
		}
	}
	/* OK, one more */
	ctextWork.Data = NULL;
	ctextWork.Length = 0;
	crtn = CSSM_EncryptDataFinal(cryptHand, &ctextWork);
	if(crtn) {
		printError("CSSM_EncryptDataFinal", crtn);
		savedErr = crtn;
		restoreErr = CSSM_TRUE;
		goto abort;
	}
	if(ctextWork.Length != 0) {
		bytesEncryptedTotal += ctextWork.Length;
		if(ctextWork.Length > ctext->Length) {
			printf("cspStagedEncrypt: ctext overflow (2)!\n");
			ocrtn = CSSMERR_CSP_INTERNAL_ERROR;
			goto abort;
		}
		memmove(ctext->Data, ctextWork.Data, ctextWork.Length);
	}
	if(ctextWork.Data) {
		/* this could have gotten mallocd and Length still be zero */
		CSSM_FREE(ctextWork.Data);
	}

	/* retweeze ctext */
	ctext->Data   = origCtext;
	ctext->Length = bytesEncryptedTotal;
abort:
	crtn = CSSM_DeleteContext(cryptHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	if(restoreErr) {
		/* give caller the error from the encrypt */
		ocrtn = savedErr;
	}
	return ocrtn;
}

CSSM_RETURN cspDecrypt(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEED, etc.
		uint32 mode,						// CSSM_ALGMODE_CBC, etc. - only for symmetric algs
		CSSM_PADDING padding,				// CSSM_PADDING_PKCS1, etc. 
		const CSSM_KEY *key,				// public or session key
		const CSSM_KEY *pubKey,				// for CSSM_ALGID_FEED, CSSM_ALGID_FEECFILE only
		uint32 effectiveKeySizeInBits,		// 0 means skip this attribute
		uint32 rounds,						// ditto
		const CSSM_DATA *iv,				// init vector, optional
		const CSSM_DATA *ctext,
		CSSM_DATA_PTR ptext,				// RETURNED
		CSSM_BOOL mallocPtext)				// if true and ptext->Length = 0,
											//   we'll malloc
{
	CSSM_CC_HANDLE 	cryptHand;
	CSSM_RETURN		crtn;
	CSSM_RETURN		ocrtn = CSSM_OK;
	CSSM_SIZE		bytesDecrypted;
	CSSM_DATA		remData = {0, NULL};
	unsigned		origPtextLen;			// the amount we malloc, if any

	cryptHand = genCryptHandle(cspHand, 
		algorithm, 
		mode, 
		padding,
		key, 
		pubKey, 
		iv,
		effectiveKeySizeInBits,
		rounds);
	if(cryptHand == 0) {
		return CSSMERR_CSP_INTERNAL_ERROR;
	}
	if(mallocPtext && (ptext->Length == 0)) {
		CSSM_QUERY_SIZE_DATA querySize;
		querySize.SizeInputBlock = ctext->Length;
		crtn = CSSM_QuerySize(cryptHand,
			CSSM_FALSE,						// encrypt
			1,
			&querySize);
		if(crtn) {
			printError("CSSM_QuerySize", crtn);
			ocrtn = crtn;
			goto abort;
		}
		if(querySize.SizeOutputBlock == 0) {
			/* CSP couldn't figure this one out; skip our malloc */
			printf("***cspDecrypt: warning: plainTextSize unknown; "
				"skipping malloc\n");
			origPtextLen = 0;
		}
		else {
			ptext->Data = 
				(uint8 *)appMalloc(querySize.SizeOutputBlock, NULL);
			if(ptext->Data == NULL) {
				printf("Insufficient heap space\n");
				ocrtn = CSSMERR_CSP_MEMORY_ERROR;
				goto abort;
			}
			ptext->Length = origPtextLen = querySize.SizeOutputBlock;
			memset(ptext->Data, 0, ptext->Length);
		}
	}
	else {
		origPtextLen = ptext->Length;
	}
	crtn = CSSM_DecryptData(cryptHand,
		ctext,
		1,
		ptext,
		1,
		&bytesDecrypted,
		&remData);
	if(crtn == CSSM_OK) {
		/*
		 * Deal with remData - its contents are included in bytesDecrypted.
		 */
		if((remData.Length != 0) && mallocPtext) {
			/* shouldn't happen - right? */
			if(bytesDecrypted > origPtextLen) {
				/* malloc and copy a new one */
				uint8 *newPdata = (uint8 *)appMalloc(bytesDecrypted, NULL);
				printf("**Warning: app malloced ClearBuf, but got nonzero "
					"remData!\n");
				if(newPdata == NULL) {
					printf("Insufficient heap space\n");
					ocrtn = CSSMERR_CSP_MEMORY_ERROR;
					goto abort;
				}
				memmove(newPdata, ptext->Data, ptext->Length);
				memmove(newPdata + ptext->Length,
					remData.Data, remData.Length);
				CSSM_FREE(ptext->Data);
				ptext->Data = newPdata;
			}
			else {
				/* there's room left over */
				memmove(ptext->Data + ptext->Length,
					remData.Data, remData.Length);
			}
			ptext->Length = bytesDecrypted;
		}
		// NOTE: We return the proper length in ptext....
		ptext->Length = bytesDecrypted;
		
		// FIXME - sometimes get mallocd RemData here, but never any valid data
		// there...side effect of CSPFullPluginSession's buffer handling logic;
		// but will we ever actually see valid data in RemData? So far we never
		// have....
		if(remData.Data != NULL) {
			appFree(remData.Data, NULL);
		}
	}
	else {
		printError("CSSM_DecryptData", crtn);
		ocrtn = crtn;
	}
abort:
	crtn = CSSM_DeleteContext(cryptHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	return ocrtn;
}

CSSM_RETURN cspStagedDecrypt(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEED, etc.
		uint32 mode,						// CSSM_ALGMODE_CBC, etc. - only for symmetric algs
		CSSM_PADDING padding,				// CSSM_PADDING_PKCS1, etc. 
		const CSSM_KEY *key,				// public or session key
		const CSSM_KEY *pubKey,				// for CSSM_ALGID_FEED, CSSM_ALGID_FEECFILE only
		uint32 effectiveKeySizeInBits,		// 0 means skip this attribute
		uint32 cipherBlockSize,				// ditto
		uint32 rounds,						// ditto
		const CSSM_DATA *iv,				// init vector, optional
		const CSSM_DATA *ctext,
		CSSM_DATA_PTR ptext,				// RETURNED, we malloc
		CSSM_BOOL multiUpdates)				// false:single update, true:multi updates
{
	CSSM_CC_HANDLE 	cryptHand;
	CSSM_RETURN		crtn;
	CSSM_SIZE		bytesDecrypted;			// per update
	CSSM_SIZE		bytesDecryptedTotal = 0;
	CSSM_RETURN		ocrtn = CSSM_OK;		// 'our' crtn
	unsigned		toMove;					// remaining
	unsigned		thisMove;				// bytes to encrypt on this update
	CSSM_DATA		thisCtext;				// running ptr into ptext
	CSSM_DATA		ptextWork;				// per update, mallocd by CSP
	CSSM_QUERY_SIZE_DATA querySize;
	uint8			*origPtext;				// initial ptext->Data
	unsigned		origPtextLen;			// amount we mallocd
	
	cryptHand = genCryptHandle(cspHand, 
		algorithm, 
		mode, 
		padding,
		key, 
		pubKey, 
		iv,
		effectiveKeySizeInBits,
		rounds);
	if(cryptHand == 0) {
		return CSSMERR_CSP_INTERNAL_ERROR;
	}
	if(cipherBlockSize) {
		crtn = AddContextAttribute(cryptHand,
			CSSM_ATTRIBUTE_BLOCK_SIZE,
			sizeof(uint32),
			CAT_Uint32,
			NULL,
			cipherBlockSize);
		if(crtn) {
			printError("CSSM_UpdateContextAttributes", crtn);
			goto abort;
		}
	}
	
	/* obtain total required ciphertext size and block size */
	querySize.SizeInputBlock = ctext->Length;
	crtn = CSSM_QuerySize(cryptHand,
		CSSM_FALSE,						// encrypt
		1,
		&querySize);
	if(crtn) {
		printError("CSSM_QuerySize(1)", crtn);
		ocrtn = crtn;
		goto abort;
	}
	
	/* required ptext size should be independent of number of chunks */
	if(querySize.SizeOutputBlock == 0) {
		printf("***warning: cspStagedDecrypt: plainTextSize unknown; aborting\n");
		ocrtn = CSSMERR_CSP_INTERNAL_ERROR;
		goto abort;
	}
	else {
		// until exit, ptext->Length indicates remaining bytes of usable data in
		// ptext->Data
		ptext->Length = origPtextLen = querySize.SizeOutputBlock;
		ptext->Data   = origPtext    = 
			(uint8 *)appMalloc(origPtextLen, NULL);
		if(ptext->Data == NULL) {
			printf("Insufficient heap space\n");
			ocrtn = CSSMERR_CSP_INTERNAL_ERROR;
			goto abort;
		}
		memset(ptext->Data, 0, ptext->Length);
	}
	
	crtn = CSSM_DecryptDataInit(cryptHand);
	if(crtn) {
		printError("CSSM_DecryptDataInit", crtn);
		ocrtn = crtn;
		goto abort;
	}
	toMove = ctext->Length;
	thisCtext.Data = ctext->Data;
	while(toMove) {
		if(multiUpdates) {
			thisMove = genRand(1, toMove);
		}
		else {
			/* just do one pass thru this loop */
			thisMove = toMove;
		}
		thisCtext.Length = thisMove;
		/* let CSP do the individual mallocs */
		ptextWork.Data = NULL;
		ptextWork.Length = 0;
		soprintf(("*** DecryptDataUpdate: ctextLen 0x%x\n", thisMove));
		crtn = CSSM_DecryptDataUpdate(cryptHand,
			&thisCtext,
			1,
			&ptextWork,
			1,
			&bytesDecrypted);
		if(crtn) {
			printError("CSSM_DecryptDataUpdate", crtn);
			ocrtn = crtn;
			goto abort;
		}
		//
		// NOTE: We return the proper length in ptext....
		ptextWork.Length = bytesDecrypted;
		thisCtext.Data += thisMove;
		toMove         -= thisMove;
		if(bytesDecrypted > ptext->Length) {
			printf("cspStagedDecrypt: ptext overflow!\n");
			ocrtn = CSSMERR_CSP_INTERNAL_ERROR;
			goto abort;
		}
		if(bytesDecrypted != 0) {
			memmove(ptext->Data, ptextWork.Data, bytesDecrypted);
			bytesDecryptedTotal += bytesDecrypted;
			ptext->Data         += bytesDecrypted;
			ptext->Length       -= bytesDecrypted;
		}
		if(ptextWork.Data != NULL) {
			CSSM_FREE(ptextWork.Data);
		}
	}
	/* OK, one more */
	ptextWork.Data = NULL;
	ptextWork.Length = 0;
	crtn = CSSM_DecryptDataFinal(cryptHand, &ptextWork);
	if(crtn) {
		printError("CSSM_DecryptDataFinal", crtn);
		ocrtn = crtn;
		goto abort;
	}
	if(ptextWork.Length != 0) {
		bytesDecryptedTotal += ptextWork.Length;
		if(ptextWork.Length > ptext->Length) {
			printf("cspStagedDecrypt: ptext overflow (2)!\n");
			ocrtn = CSSMERR_CSP_INTERNAL_ERROR;
			goto abort;
		}
		memmove(ptext->Data, ptextWork.Data, ptextWork.Length);
	}
	if(ptextWork.Data) {
		/* this could have gotten mallocd and Length still be zero */
		CSSM_FREE(ptextWork.Data);
	}
	
	/* retweeze ptext */
	ptext->Data   = origPtext;
	ptext->Length = bytesDecryptedTotal;
abort:
	crtn = CSSM_DeleteContext(cryptHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	return ocrtn;
}

#pragma mark --------- sign/verify/MAC ---------

/*
 * Signature routines
 * This all-in-one sign op has a special case for RSA keys. If the requested
 * alg is MD5 or SHA1, we'll do a manual digest op followed by raw RSA sign. 
 * Likewise, if it's CSSM_ALGID_DSA, we'll do manual SHA1 digest followed by 
 * raw DSA sign.
 */

CSSM_RETURN cspSign(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// private key
		const CSSM_DATA *text,
		CSSM_DATA_PTR sig)					// RETURNED
{
	CSSM_CC_HANDLE	sigHand;
	CSSM_RETURN		crtn;
	CSSM_RETURN		ocrtn = CSSM_OK;
	const CSSM_DATA	*ptext;
	CSSM_DATA		digest = {0, NULL};
	CSSM_ALGORITHMS	digestAlg = CSSM_ALGID_NONE;

	/* handle special cases for raw sign */
	switch(algorithm) {
		case CSSM_ALGID_SHA1:
			digestAlg = CSSM_ALGID_SHA1;
			algorithm = CSSM_ALGID_RSA;
			break;
		case CSSM_ALGID_MD5:
			digestAlg = CSSM_ALGID_MD5;
			algorithm = CSSM_ALGID_RSA;
			break;
		case CSSM_ALGID_DSA:
			digestAlg = CSSM_ALGID_SHA1;
			algorithm = CSSM_ALGID_DSA;
			break;
		default:
			break;
	}
	if(digestAlg != CSSM_ALGID_NONE) {
		crtn = cspDigest(cspHand,
			digestAlg,
			CSSM_FALSE,			// mallocDigest
			text,
			&digest);
		if(crtn) {
			return crtn;
		}	
		/* sign digest with raw RSA/DSA */
		ptext = &digest;
	}
	else {
		ptext = text;
	}
	crtn = CSSM_CSP_CreateSignatureContext(cspHand,
		algorithm,
		NULL,				// passPhrase
		key,
		&sigHand);
	if(crtn) {
		printError("CSSM_CSP_CreateSignatureContext (1)", crtn);
		return crtn;
	}
	crtn = CSSM_SignData(sigHand,
		ptext,
		1,
		digestAlg,
		sig);
	if(crtn) {
		printError("CSSM_SignData", crtn);
		ocrtn = crtn;
	}
	crtn = CSSM_DeleteContext(sigHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	if(digest.Data != NULL) {
		CSSM_FREE(digest.Data);
	}
	return ocrtn;
}

/*
 * Staged sign. Each update does a random number of bytes 'till through.
 */
CSSM_RETURN cspStagedSign(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// private key
		const CSSM_DATA *text,
		CSSM_BOOL multiUpdates,				// false:single update, true:multi updates
		CSSM_DATA_PTR sig)					// RETURNED
{
	CSSM_CC_HANDLE	sigHand;
	CSSM_RETURN		crtn;
	CSSM_RETURN		ocrtn = CSSM_OK;
	unsigned		thisMove;				// this update
	unsigned		toMove;					// total to go
	CSSM_DATA		thisText;				// actaully passed to update
	crtn = CSSM_CSP_CreateSignatureContext(cspHand,
		algorithm,
		NULL,				// passPhrase
		key,
		&sigHand);
	if(crtn) {
		printError("CSSM_CSP_CreateSignatureContext (1)", crtn);
		return crtn;
	}
	crtn = CSSM_SignDataInit(sigHand);
	if(crtn) {
		printError("CSSM_SignDataInit", crtn);
		ocrtn = crtn;
		goto abort;
	}
	toMove = text->Length;
	thisText.Data = text->Data;
	while(toMove) {
		if(multiUpdates) {
			thisMove = genRand(1, toMove);
		}
		else {
			thisMove = toMove;
		}
		thisText.Length = thisMove;
		crtn = CSSM_SignDataUpdate(sigHand,
			&thisText,
			1);
		if(crtn) {
			printError("CSSM_SignDataUpdate", crtn);
			ocrtn = crtn;
			goto abort;
		}
		thisText.Data += thisMove;
		toMove -= thisMove;
	}
	crtn = CSSM_SignDataFinal(sigHand, sig);
	if(crtn) {
		printError("CSSM_SignDataFinal", crtn);
		ocrtn = crtn;
		goto abort;
	}
abort:
	crtn = CSSM_DeleteContext(sigHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	return ocrtn;
}

/*
 * This all-in-one verify op has a special case for RSA keys. If the requested
 * alg is MD5 or SHA1, we'll do a manual digest op followed by raw RSA verify.
 * Likewise, if it's CSSM_ALGID_DSA, we'll do manual SHA1 digest followed by 
 * raw DSA sign.
 */ 
 
CSSM_RETURN cspSigVerify(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// public key
		const CSSM_DATA *text,
		const CSSM_DATA *sig,
		CSSM_RETURN expectResult)			// expected result is verify failure
											// CSSM_OK - expect success
{
	CSSM_CC_HANDLE	sigHand;
	CSSM_RETURN		ocrtn = CSSM_OK;
	CSSM_RETURN		crtn;
	const CSSM_DATA	*ptext;
	CSSM_DATA		digest = {0, NULL};
	CSSM_ALGORITHMS	digestAlg = CSSM_ALGID_NONE;
	
	/* handle special cases for raw sign */
	switch(algorithm) {
		case CSSM_ALGID_SHA1:
			digestAlg = CSSM_ALGID_SHA1;
			algorithm = CSSM_ALGID_RSA;
			break;
		case CSSM_ALGID_MD5:
			digestAlg = CSSM_ALGID_MD5;
			algorithm = CSSM_ALGID_RSA;
			break;
		case CSSM_ALGID_DSA:
			digestAlg = CSSM_ALGID_SHA1;
			algorithm = CSSM_ALGID_DSA;
			break;
		default:
			break;
	}
	if(digestAlg != CSSM_ALGID_NONE) {
		crtn = cspDigest(cspHand,
			digestAlg,
			CSSM_FALSE,			// mallocDigest
			text,
			&digest);
		if(crtn) {
			return crtn;
		}	
		/* sign digest with raw RSA/DSA */
		ptext = &digest;
	}
	else {
		ptext = text;
	}
	crtn = CSSM_CSP_CreateSignatureContext(cspHand,
		algorithm,
		NULL,				// passPhrase
		key,
		&sigHand);
	if(crtn) {
		printError("CSSM_CSP_CreateSignatureContext (3)", crtn);
		return crtn;
	}
	
	crtn = CSSM_VerifyData(sigHand,
		ptext,
		1,
		digestAlg,
		sig);
	if(crtn != expectResult) {
		if(!crtn) {
			printf("Unexpected good Sig Verify\n");
		}
		else {
			printError("CSSM_VerifyData", crtn);
		}
		ocrtn = CSSMERR_CSSM_INTERNAL_ERROR;
	}
	crtn = CSSM_DeleteContext(sigHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	if(digest.Data != NULL) {
		CSSM_FREE(digest.Data);
	}
	return ocrtn;
}

/*
 * Staged verify. Each update does a random number of bytes 'till through.
 */
CSSM_RETURN cspStagedSigVerify(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// private key
		const CSSM_DATA *text,
		const CSSM_DATA *sig,
		CSSM_BOOL multiUpdates,				// false:single update, true:multi updates
		CSSM_RETURN expectResult)			// expected result is verify failure
											// CSSM_TRUE - expect success
{
	CSSM_CC_HANDLE	sigHand;
	CSSM_RETURN		crtn;
	CSSM_RETURN		ocrtn = CSSM_OK;
	unsigned		thisMove;				// this update
	unsigned		toMove;					// total to go
	CSSM_DATA		thisText;				// actaully passed to update
	crtn = CSSM_CSP_CreateSignatureContext(cspHand,
		algorithm,
		NULL,				// passPhrase
		key,
		&sigHand);
	if(crtn) {
		printError("CSSM_CSP_CreateSignatureContext (4)", crtn);
		return crtn;
	}
	crtn = CSSM_VerifyDataInit(sigHand);
	if(crtn) {
		printError("CSSM_VerifyDataInit", crtn);
		ocrtn = crtn;
		goto abort;
	}
	toMove = text->Length;
	thisText.Data = text->Data;
	while(toMove) {
		if(multiUpdates) {
			thisMove = genRand(1, toMove);
		}
		else {
			thisMove = toMove;
		}
		thisText.Length = thisMove;
		crtn = CSSM_VerifyDataUpdate(sigHand,
			&thisText,
			1);
		if(crtn) {
			printError("CSSM_VerifyDataUpdate", crtn);
			ocrtn = crtn;
			goto abort;
		}
		thisText.Data += thisMove;
		toMove -= thisMove;
	}
	crtn = CSSM_VerifyDataFinal(sigHand, sig);
	if(crtn != expectResult) {
		if(crtn) {
			printError("CSSM_VerifyDataFinal", crtn);
		}
		else {
			printf("Unexpected good Staged Sig Verify\n");
		}
		ocrtn = CSSMERR_CSSM_INTERNAL_ERROR;
	}
abort:
	crtn = CSSM_DeleteContext(sigHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	return ocrtn;
}

/*
 * MAC routines
 */
CSSM_RETURN cspGenMac(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// session key
		const CSSM_DATA *text,
		CSSM_DATA_PTR mac)					// RETURNED
{
	CSSM_CC_HANDLE	macHand;
	CSSM_RETURN		crtn;
	CSSM_RETURN		ocrtn = CSSM_OK;
	crtn = CSSM_CSP_CreateMacContext(cspHand,
		algorithm,
		key,
		&macHand);
	if(crtn) {
		printError("CSSM_CSP_CreateMacContext (1)", crtn);
		return crtn;
	}
	crtn = CSSM_GenerateMac(macHand,
		text,
		1,
		mac);
	if(crtn) {
		printError("CSSM_GenerateMac", crtn);
		ocrtn = crtn;
	}
	crtn = CSSM_DeleteContext(macHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	return ocrtn;
}

/*
 * Staged generate mac. 
 */
CSSM_RETURN cspStagedGenMac(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// private key
		const CSSM_DATA *text,
		CSSM_BOOL mallocMac,				// if true and digest->Length = 0, we'll 
											//		malloc
		CSSM_BOOL multiUpdates,				// false:single update, true:multi updates
		CSSM_DATA_PTR mac)					// RETURNED
{
	CSSM_CC_HANDLE	macHand;
	CSSM_RETURN		crtn;
	CSSM_RETURN		ocrtn = CSSM_OK;
	unsigned		thisMove;				// this update
	unsigned		toMove;					// total to go
	CSSM_DATA		thisText;				// actaully passed to update
	
	crtn = CSSM_CSP_CreateMacContext(cspHand,
		algorithm,
		key,
		&macHand);
	if(crtn) {
		printError("CSSM_CSP_CreateMacContext (2)", crtn);
		return crtn;
	}

	if(mallocMac && (mac->Length == 0)) {
		/* malloc mac - ask CSP for size */
		CSSM_QUERY_SIZE_DATA	querySize = {0, 0};
		crtn = CSSM_QuerySize(macHand,
			CSSM_TRUE,						// encrypt
			1,
			&querySize);
		if(crtn) {
			printError("CSSM_QuerySize(mac)", crtn);
			ocrtn = crtn;
			goto abort;
		}
		if(querySize.SizeOutputBlock == 0) {
			printf("Unknown mac size\n");
			ocrtn = CSSMERR_CSSM_INTERNAL_ERROR;
			goto abort;
		}
		mac->Data = (uint8 *)appMalloc(querySize.SizeOutputBlock, NULL);
		if(mac->Data == NULL) {
			printf("malloc failure\n");
			ocrtn = CSSMERR_CSSM_MEMORY_ERROR;
			goto abort;
		}
		mac->Length = querySize.SizeOutputBlock;
	}

	crtn = CSSM_GenerateMacInit(macHand);
	if(crtn) {
		printError("CSSM_GenerateMacInit", crtn);
		ocrtn = crtn;
		goto abort;
	}
	toMove = text->Length;
	thisText.Data = text->Data;
	
	while(toMove) {
		if(multiUpdates) {
			thisMove = genRand(1, toMove);
		}
		else {
			thisMove = toMove;
		}
		thisText.Length = thisMove;
		crtn = CSSM_GenerateMacUpdate(macHand,
			&thisText,
			1);
		if(crtn) {
			printError("CSSM_GenerateMacUpdate", crtn);
			ocrtn = crtn;
			goto abort;
		}
		thisText.Data += thisMove;
		toMove -= thisMove;
	}
	crtn = CSSM_GenerateMacFinal(macHand, mac);
	if(crtn) {
		printError("CSSM_GenerateMacFinal", crtn);
		ocrtn = crtn;
		goto abort;
	}
abort:
	crtn = CSSM_DeleteContext(macHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	return ocrtn;
}

CSSM_RETURN cspMacVerify(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// public key
		const CSSM_DATA *text,
		const CSSM_DATA_PTR mac,
		CSSM_RETURN expectResult)			// expected result 
											// CSSM_OK - expect success
{
	CSSM_CC_HANDLE	macHand;
	CSSM_RETURN		ocrtn = CSSM_OK;
	CSSM_RETURN		crtn;
	crtn = CSSM_CSP_CreateMacContext(cspHand,
		algorithm,
		key,
		&macHand);
	if(crtn) {
		printError("CSSM_CSP_CreateMacContext (3)", crtn);
		return crtn;
	}
	crtn = CSSM_VerifyMac(macHand,
		text,
		1,
		mac);
	if(crtn != expectResult) {
		if(crtn) {
			printError("CSSM_VerifyMac", crtn);
		}
		else {
			printf("Unexpected good Mac Verify\n");
		}
		ocrtn = CSSMERR_CSSM_INTERNAL_ERROR;
	}
	crtn = CSSM_DeleteContext(macHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	return ocrtn;
}

/*
 * Staged mac verify. Each update does a random number of bytes 'till through.
 */
CSSM_RETURN cspStagedMacVerify(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// private key
		const CSSM_DATA *text,
		const CSSM_DATA_PTR mac,
		CSSM_BOOL multiUpdates,				// false:single update, true:multi updates
		CSSM_RETURN expectResult)			// expected result is verify failure
											// CSSM_OK - expect success
{
	CSSM_CC_HANDLE	macHand;
	CSSM_RETURN		crtn;
	CSSM_RETURN		ocrtn = CSSM_OK;
	unsigned		thisMove;				// this update
	unsigned		toMove;					// total to go
	CSSM_DATA		thisText;				// actaully passed to update

	crtn = CSSM_CSP_CreateMacContext(cspHand,
		algorithm,
		key,
		&macHand);
	if(crtn) {
		printError("CSSM_CSP_CreateMacContext (4)", crtn);
		return crtn;
	}
	crtn = CSSM_VerifyMacInit(macHand);
	if(crtn) {
		printError("CSSM_VerifyMacInit", crtn);
		ocrtn = crtn;
		goto abort;
	}
	toMove = text->Length;
	thisText.Data = text->Data;
	
	while(toMove) {
		if(multiUpdates) {
			thisMove = genRand(1, toMove);
		}
		else {
			thisMove = toMove;
		}
		thisText.Length = thisMove;
		crtn = CSSM_VerifyMacUpdate(macHand,
			&thisText,
			1);
		if(crtn) {
			printError("CSSM_VerifyMacUpdate", crtn);
			ocrtn = crtn;
			goto abort;
		}
		thisText.Data += thisMove;
		toMove -= thisMove;
	}
	crtn = CSSM_VerifyMacFinal(macHand, mac);
	if(crtn != expectResult) {
		if(crtn) {
			printError("CSSM_VerifyMacFinal", crtn);
		}
		else {
			printf("Unexpected good Staged Mac Verify\n");
		}
		ocrtn = CSSMERR_CSSM_INTERNAL_ERROR;
	}
abort:
	crtn = CSSM_DeleteContext(macHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	return ocrtn;
}

#pragma mark --------- Digest ---------

/*
 * Digest functions
 */
CSSM_RETURN cspDigest(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_MD5, etc.
		CSSM_BOOL mallocDigest,				// if true and digest->Length = 0, we'll malloc
		const CSSM_DATA *text,
		CSSM_DATA_PTR digest)
{
	CSSM_CC_HANDLE	digestHand;
	CSSM_RETURN		crtn;
	CSSM_RETURN		ocrtn = CSSM_OK;
	
	crtn = CSSM_CSP_CreateDigestContext(cspHand,
		algorithm,
		&digestHand);
	if(crtn) {
		printError("CSSM_CSP_CreateDIgestContext (1)", crtn);
		return crtn;
	}
	if(mallocDigest && (digest->Length == 0)) {
		/* malloc digest - ask CSP for size */
		CSSM_QUERY_SIZE_DATA	querySize = {0, 0};
		crtn = CSSM_QuerySize(digestHand,
			CSSM_FALSE,						// encrypt
			1,
			&querySize);
		if(crtn) {
			printError("CSSM_QuerySize(3)", crtn);
			ocrtn = crtn;
			goto abort;
		}
		if(querySize.SizeOutputBlock == 0) {
			printf("Unknown digest size\n");
			ocrtn = CSSMERR_CSSM_INTERNAL_ERROR;
			goto abort;
		}
		digest->Data = (uint8 *)appMalloc(querySize.SizeOutputBlock, NULL);
		if(digest->Data == NULL) {
			printf("malloc failure\n");
			ocrtn = CSSMERR_CSSM_MEMORY_ERROR;
			goto abort;
		}
		digest->Length = querySize.SizeOutputBlock;
	}
	crtn = CSSM_DigestData(digestHand,
		text,
		1,
		digest);
	if(crtn) {
		printError("CSSM_DigestData", crtn);
		ocrtn = crtn;
	}
abort:
	crtn = CSSM_DeleteContext(digestHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	return ocrtn;
}

CSSM_RETURN cspStagedDigest(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_MD5, etc.
		CSSM_BOOL mallocDigest,				// if true and digest->Length = 0, we'll 
											//		malloc
		CSSM_BOOL multiUpdates,				// false:single update, true:multi updates
		const CSSM_DATA *text,
		CSSM_DATA_PTR digest)
{
	CSSM_CC_HANDLE	digestHand;
	CSSM_RETURN		crtn;
	CSSM_RETURN		ocrtn = CSSM_OK;
	unsigned		thisMove;				// this update
	unsigned		toMove;					// total to go
	CSSM_DATA		thisText;				// actually passed to update
	
	crtn = CSSM_CSP_CreateDigestContext(cspHand,
		algorithm,
		&digestHand);
	if(crtn) {
		printError("CSSM_CSP_CreateDigestContext (2)", crtn);
		return crtn;
	}
	if(mallocDigest && (digest->Length == 0)) {
		/* malloc digest - ask CSP for size */
		CSSM_QUERY_SIZE_DATA	querySize = {0, 0};
		crtn = CSSM_QuerySize(digestHand,
			CSSM_FALSE,						// encrypt
			1,
			&querySize);
		if(crtn) {
			printError("CSSM_QuerySize(4)", crtn);
			ocrtn = crtn;
			goto abort;
		}
		if(querySize.SizeOutputBlock == 0) {
			printf("Unknown digest size\n");
			ocrtn = CSSMERR_CSSM_INTERNAL_ERROR;
			goto abort;
		}
		digest->Data = (uint8 *)appMalloc(querySize.SizeOutputBlock, NULL);
		if(digest->Data == NULL) {
			printf("malloc failure\n");
			ocrtn = CSSMERR_CSSM_MEMORY_ERROR;
			goto abort;
		}
		digest->Length = querySize.SizeOutputBlock;
	}
	crtn = CSSM_DigestDataInit(digestHand);
	if(crtn) {
		printError("CSSM_DigestDataInit", crtn);
		ocrtn = crtn;
		goto abort;
	}
	toMove = text->Length;
	thisText.Data = text->Data;
	while(toMove) {
		if(multiUpdates) {
			thisMove = genRand(1, toMove);
		}
		else {
			thisMove = toMove;
		}
		thisText.Length = thisMove;
		crtn = CSSM_DigestDataUpdate(digestHand,
			&thisText,
			1);
		if(crtn) {
			printError("CSSM_DigestDataUpdate", crtn);
			ocrtn = crtn;
			goto abort;
		}
		thisText.Data += thisMove;
		toMove -= thisMove;
	}
	crtn = CSSM_DigestDataFinal(digestHand, digest);
	if(crtn) {
		printError("CSSM_DigestDataFinal", crtn);
		ocrtn = crtn;
		goto abort;
	}
abort:
	crtn = CSSM_DeleteContext(digestHand);
	if(crtn) {
		printError("CSSM_DeleteContext", crtn);
		ocrtn = crtn;
	}
	return ocrtn;
}

#pragma mark --------- wrap/unwrap ---------

/* wrap key function. */
CSSM_RETURN cspWrapKey(CSSM_CSP_HANDLE cspHand,
	const CSSM_KEY			*unwrappedKey,	
	const CSSM_KEY			*wrappingKey,
	CSSM_ALGORITHMS			wrapAlg,
	CSSM_ENCRYPT_MODE		wrapMode,
	CSSM_KEYBLOB_FORMAT		wrapFormat,			// NONE, PKCS7, PKCS8
	CSSM_PADDING			wrapPad,
	CSSM_DATA_PTR			initVector,			// for some wrapping algs
	CSSM_DATA_PTR			descrData,			// optional 
	CSSM_KEY_PTR			wrappedKey)			// RETURNED
{
	CSSM_CC_HANDLE		ccHand;
	CSSM_RETURN			crtn;
	CSSM_ACCESS_CREDENTIALS	creds;
	
	memset(wrappedKey, 0, sizeof(CSSM_KEY));
	setBadKeyData(wrappedKey);
	memset(&creds, 0, sizeof(CSSM_ACCESS_CREDENTIALS));
	/* special case for NULL wrap - no wrapping key */
	if((wrappingKey == NULL) ||
	   (wrappingKey->KeyHeader.KeyClass == CSSM_KEYCLASS_SESSION_KEY)) {
		crtn = CSSM_CSP_CreateSymmetricContext(cspHand,
				wrapAlg,
				wrapMode,
				&creds,			// passPhrase,
				wrappingKey,
				initVector,
				wrapPad,		// Padding
				0,				// Params
				&ccHand);
	}
	else {
		crtn = CSSM_CSP_CreateAsymmetricContext(cspHand,
				wrapAlg,
				&creds,	
				wrappingKey,
				wrapPad,		// padding
				&ccHand);
		if(crtn) {
			printError("cspWrapKey/CreateContext", crtn);
			return crtn;
		}
		if(initVector) {
			/* manually add IV for CMS. The actual low-level encrypt doesn't
			 * use it (and must ignore it). */
			crtn = AddContextAttribute(ccHand,
				CSSM_ATTRIBUTE_INIT_VECTOR,
				sizeof(CSSM_DATA),
				CAT_Ptr,
				initVector,
				0);
			if(crtn) {
				printError("CSSM_UpdateContextAttributes", crtn);
				return crtn;
			}
		}
	}
	if(crtn) {
		printError("cspWrapKey/CreateContext", crtn);
		return crtn;
	}
	if(wrapFormat != CSSM_KEYBLOB_WRAPPED_FORMAT_NONE) {
		/* only add this attribute if it's not the default */
		CSSM_CONTEXT_ATTRIBUTE attr;
		attr.AttributeType = CSSM_ATTRIBUTE_WRAPPED_KEY_FORMAT;
		attr.AttributeLength = sizeof(uint32);
		attr.Attribute.Uint32 = wrapFormat;
		crtn = CSSM_UpdateContextAttributes(
			ccHand,
			1,
			&attr);
		if(crtn) {
			printError("CSSM_UpdateContextAttributes", crtn);
			return crtn;
		}
	}
	crtn = CSSM_WrapKey(ccHand,
		&creds,
		unwrappedKey,
		descrData,			// DescriptiveData
		wrappedKey);
	if(crtn != CSSM_OK) {
		printError("CSSM_WrapKey", crtn);
	}
	if(CSSM_DeleteContext(ccHand)) {
		printf("CSSM_DeleteContext failure\n");
	}
	return crtn;
}

/* unwrap key function. */
CSSM_RETURN cspUnwrapKey(CSSM_CSP_HANDLE cspHand,
	const CSSM_KEY			*wrappedKey,
	const CSSM_KEY			*unwrappingKey,
	CSSM_ALGORITHMS			unwrapAlg,
	CSSM_ENCRYPT_MODE		unwrapMode,
	CSSM_PADDING 			unwrapPad,
	CSSM_DATA_PTR			initVector,			// for some wrapping algs
	CSSM_KEY_PTR			unwrappedKey,		// RETURNED
	CSSM_DATA_PTR			descrData,			// required
	const char 				*keyLabel,
	unsigned 				keyLabelLen)
{
	CSSM_CC_HANDLE		ccHand;
	CSSM_RETURN			crtn;
	CSSM_DATA			labelData;
	uint32				keyAttr;
	CSSM_ACCESS_CREDENTIALS	creds;
	
	memset(unwrappedKey, 0, sizeof(CSSM_KEY));
	setBadKeyData(unwrappedKey);
	memset(&creds, 0, sizeof(CSSM_ACCESS_CREDENTIALS));
	if((unwrappingKey == NULL) ||
	   (unwrappingKey->KeyHeader.KeyClass == CSSM_KEYCLASS_SESSION_KEY)) {
		crtn = CSSM_CSP_CreateSymmetricContext(cspHand,
				unwrapAlg,
				unwrapMode,
				&creds,
				unwrappingKey,
				initVector,
				unwrapPad,
				0,				// Params
				&ccHand);
	}
	else {
		crtn = CSSM_CSP_CreateAsymmetricContext(cspHand,
				unwrapAlg,
				&creds,			// passPhrase,
				unwrappingKey,
				unwrapPad,		// Padding
				&ccHand);
		if(crtn) {
			printError("cspUnwrapKey/CreateContext", crtn);
			return crtn;
		}
		if(initVector) {
			/* manually add IV for CMS. The actual low-level encrypt doesn't
			 * use it (and must ignore it). */
			crtn = AddContextAttribute(ccHand,
				CSSM_ATTRIBUTE_INIT_VECTOR,
				sizeof(CSSM_DATA),
				CAT_Ptr,
				initVector,
				0);
			if(crtn) {
				printError("CSSM_UpdateContextAttributes", crtn);
				return crtn;
			}
		}
	}
	if(crtn) {
		printError("cspUnwrapKey/CreateContext", crtn);
		return crtn;
	}
	labelData.Data = (uint8 *)keyLabel;
	labelData.Length = keyLabelLen;
	
	/*
	 * New keyAttr - clear some old bits, make sure we ask for ref key
	 */
	keyAttr = wrappedKey->KeyHeader.KeyAttr;
	keyAttr &= ~(CSSM_KEYATTR_ALWAYS_SENSITIVE | CSSM_KEYATTR_NEVER_EXTRACTABLE);
	keyAttr |= CSSM_KEYATTR_RETURN_REF;
	crtn = CSSM_UnwrapKey(ccHand,
		NULL,				// PublicKey
		wrappedKey,
		wrappedKey->KeyHeader.KeyUsage,
		keyAttr,
		&labelData,
		NULL,				// CredAndAclEntry
		unwrappedKey,
		descrData);			// required
	if(crtn != CSSM_OK) {
		printError("CSSM_UnwrapKey", crtn);
	}
	if(CSSM_DeleteContext(ccHand)) {
		printf("CSSM_DeleteContext failure\n");
	}
	return crtn;
}

/*
 * Simple NULL wrap to convert a reference key to a raw key.
 */
CSSM_RETURN cspRefKeyToRaw(
	CSSM_CSP_HANDLE cspHand,
	const CSSM_KEY *refKey,
	CSSM_KEY_PTR rawKey)		// init'd and RETURNED
{
	CSSM_DATA descData = {0, 0};
	
	memset(rawKey, 0, sizeof(CSSM_KEY));
	return cspWrapKey(cspHand,
		refKey,
		NULL,					// unwrappingKey
		CSSM_ALGID_NONE,
		CSSM_ALGMODE_NONE,
		CSSM_KEYBLOB_WRAPPED_FORMAT_NONE,
		CSSM_PADDING_NONE,
		NULL,					// IV
		&descData,
		rawKey);
}

/* unwrap raw key --> ref */
CSSM_RETURN cspRawKeyToRef(
	CSSM_CSP_HANDLE cspHand,
	const CSSM_KEY *rawKey,
	CSSM_KEY_PTR refKey)				// init'd and RETURNED
{
	CSSM_DATA descData = {0, 0};

	memset(refKey, 0, sizeof(CSSM_KEY));
	return cspUnwrapKey(cspHand,
		rawKey,
		NULL,		// unwrappingKey
		CSSM_ALGID_NONE,
		CSSM_ALGMODE_NONE,
		CSSM_PADDING_NONE,
		NULL,		// init vector
		refKey,
		&descData,
		"noLabel",
		7);
}


#pragma mark --------- FEE key/curve support ---------

/*
 * Generate random key size, primeType, curveType for FEE key for specified op.
 *
 * First just enumerate the curves we know about, with ECDSA-INcapable first
 */
 
typedef struct {
	uint32	keySizeInBits;
	uint32 	primeType;				// CSSM_FEE_PRIME_TYPE_xxx
	uint32 	curveType;				// CSSM_FEE_CURVE_TYPE_xxx
} feeCurveParams;

#define FEE_PROTOTYPE_CURVES	0
#if 	FEE_PROTOTYPE_CURVES
/* obsolete as of 4/9/2001 */
static feeCurveParams feeCurves[] = {
	{	31,		CSSM_FEE_PRIME_TYPE_MERSENNE,	CSSM_FEE_CURVE_TYPE_MONTGOMERY },
	{	127,	CSSM_FEE_PRIME_TYPE_MERSENNE,	CSSM_FEE_CURVE_TYPE_MONTGOMERY },
	{	127,	CSSM_FEE_PRIME_TYPE_GENERAL,	CSSM_FEE_CURVE_TYPE_MONTGOMERY },
	#define NUM_NON_ECDSA_CURVES	3
	
	/* start of Weierstrass, IEEE P1363-capable curves */
	{	31,		CSSM_FEE_PRIME_TYPE_MERSENNE,	CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
	{	40,		CSSM_FEE_PRIME_TYPE_FEE,		CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
	{	127,	CSSM_FEE_PRIME_TYPE_MERSENNE,	CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
	{	160,	CSSM_FEE_PRIME_TYPE_FEE,		CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
	{	160,	CSSM_FEE_PRIME_TYPE_GENERAL,	CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
	{	192,	CSSM_FEE_PRIME_TYPE_FEE,		CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
};
#else	/* FEE_PROTOTYPE_CURVES */
static feeCurveParams feeCurves[] = {
	{	31,		CSSM_FEE_PRIME_TYPE_MERSENNE,	CSSM_FEE_CURVE_TYPE_MONTGOMERY },
	{	127,	CSSM_FEE_PRIME_TYPE_MERSENNE,	CSSM_FEE_CURVE_TYPE_MONTGOMERY },
	#define NUM_NON_ECDSA_CURVES	2
	
	/* start of Weierstrass, IEEE P1363-capable curves */
	{	31,		CSSM_FEE_PRIME_TYPE_MERSENNE,	CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
	{	128,	CSSM_FEE_PRIME_TYPE_FEE,		CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
	{	161,	CSSM_FEE_PRIME_TYPE_FEE,		CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
	{	161,	CSSM_FEE_PRIME_TYPE_GENERAL,	CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
	{	192,	CSSM_FEE_PRIME_TYPE_GENERAL,	CSSM_FEE_CURVE_TYPE_WEIERSTRASS },
};
#endif	/* FEE_PROTOTYPE_CURVES */
#define NUM_FEE_CURVES	(sizeof(feeCurves) / sizeof(feeCurveParams))

void randFeeKeyParams(
	CSSM_ALGORITHMS	alg,			// ALGID_FEED, CSSM_ALGID_FEE_MD5, etc.
	uint32			*keySizeInBits,	// RETURNED
	uint32 			*primeType,		// CSSM_FEE_PRIME_TYPE_xxx, RETURNED
	uint32 			*curveType)		// CSSM_FEE_CURVE_TYPE_xxx, RETURNED
{
	unsigned minParams;
	unsigned die;
	feeCurveParams *feeParams;
	
	switch(alg) {
		case CSSM_ALGID_SHA1WithECDSA:
			minParams = NUM_NON_ECDSA_CURVES;
			break;
		default:
			minParams = 0;
			break;
	}
	die = genRand(minParams, (NUM_FEE_CURVES - 1));
	feeParams = &feeCurves[die];
	*keySizeInBits = feeParams->keySizeInBits;
	*primeType = feeParams->primeType;
	*curveType = feeParams->curveType;
}

/*
 * Obtain strings for primeType and curveType.
 */
const char *primeTypeStr(uint32 primeType)
{
	const char *p;
	switch(primeType) {
		case CSSM_FEE_PRIME_TYPE_MERSENNE:
			p = "Mersenne";
			break;
		case CSSM_FEE_PRIME_TYPE_FEE:
			p = "FEE";
			break;
		case CSSM_FEE_PRIME_TYPE_GENERAL:
			p = "General";
			break;
		case CSSM_FEE_PRIME_TYPE_DEFAULT:
			p = "Default";
			break;
		default:
			p = "***UNKNOWN***";
			break;
	}
	return p;
}

const char *curveTypeStr(uint32 curveType)
{
	const char *c;
	switch(curveType) {
		case CSSM_FEE_CURVE_TYPE_DEFAULT:
			c = "Default";
			break;
		case CSSM_FEE_CURVE_TYPE_MONTGOMERY:
			c = "Montgomery";
			break;
		case CSSM_FEE_CURVE_TYPE_WEIERSTRASS:
			c = "Weierstrass";
			break;
		default:
			c = "***UNKNOWN***";
			break;
	}
	return c;
}

/*
 * Perform FEE Key exchange via CSSM_DeriveKey. 
 */
#if 0
/* Not implemented in OS X */
CSSM_RETURN cspFeeKeyExchange(CSSM_CSP_HANDLE cspHand,
	CSSM_KEY_PTR 	privKey,
	CSSM_KEY_PTR 	pubKey,
	CSSM_KEY_PTR 	derivedKey,		// mallocd by caller
	
	/* remaining fields apply to derivedKey */
	uint32 			keyAlg,
	const char 		*keyLabel,
	unsigned 		keyLabelLen,
	uint32 			keyUsage,		// CSSM_KEYUSE_ENCRYPT, etc.
	uint32 			keySizeInBits)
{
	CSSM_CC_HANDLE	dkHand;
	CSSM_RETURN 	crtn;
	CSSM_DATA		labelData;
	
	if(derivedKey == NULL) {
		printf("cspFeeKeyExchange: no derivedKey\n");
		return CSSMERR_CSSM_INTERNAL_ERROR;
	}
	if((pubKey == NULL) ||
	   (pubKey->KeyHeader.KeyClass != CSSM_KEYCLASS_PUBLIC_KEY) ||
	   (pubKey->KeyHeader.BlobType != CSSM_KEYBLOB_RAW)) {
	 	printf("cspFeeKeyExchange: bad pubKey\n");
	 	return CSSMERR_CSSM_INTERNAL_ERROR;
	}
	if((privKey == NULL) ||
	   (privKey->KeyHeader.KeyClass != CSSM_KEYCLASS_PRIVATE_KEY) ||
	   (privKey->KeyHeader.BlobType != CSSM_KEYBLOB_REFERENCE)) {
	 	printf("cspFeeKeyExchange: bad privKey\n");
	 	return CSSMERR_CSSM_INTERNAL_ERROR;
	}
	memset(derivedKey, 0, sizeof(CSSM_KEY));
	
	crtn = CSSM_CSP_CreateDeriveKeyContext(cspHand,
		CSSM_ALGID_FEE_KEYEXCH,			// AlgorithmID
		keyAlg,							// alg of the derived key
		keySizeInBits,
		NULL,							// access creds
		// FIXME
		0,								// IterationCount
		NULL,							// Salt
		NULL,							// Seed
		NULL);							// PassPhrase
	if(dkHand == 0) {
		printError("CSSM_CSP_CreateDeriveKeyContext");
		return CSSM_FAIL;
	} 
	labelData.Length = keyLabelLen;
	labelData.Data = (uint8 *)keyLabel;
	crtn = CSSM_DeriveKey(dkHand,
		privKey,
		&pubKey->KeyData,		// Param - pub key blob
		keyUsage,
		CSSM_KEYATTR_RETURN_REF | CSSM_KEYATTR_EXTRACTABLE |
				  CSSM_KEYATTR_SENSITIVE,
		&labelData,
		derivedKey);
	
	/* FIXME - save/restore error */
	CSSM_DeleteContext(dkHand);
	if(crtn) {
		printError("CSSM_DeriveKey");
	}
	return crtn;
}
#endif

#pragma mark --------- Key/DL/DB support ---------

/*
 * Add a DL/DB handle to a crypto context.
 */
CSSM_RETURN cspAddDlDbToContext(
	CSSM_CC_HANDLE ccHand,
	CSSM_DL_HANDLE dlHand,
	CSSM_DB_HANDLE dbHand)
{
	CSSM_DL_DB_HANDLE dlDb = { dlHand, dbHand };
	return AddContextAttribute(ccHand, 
		CSSM_ATTRIBUTE_DL_DB_HANDLE,
		sizeof(CSSM_ATTRIBUTE_DL_DB_HANDLE),
		CAT_Ptr,
		&dlDb,
		0);
}
	
/* 
 * Common routine to do a basic DB lookup by label and key type.
 * Query is aborted prior to exit.
 */
static CSSM_DB_UNIQUE_RECORD_PTR dlLookup(
	CSSM_DL_DB_HANDLE	dlDbHand,
	const CSSM_DATA		*keyLabel,
	CT_KeyType 			keyType,
	CSSM_HANDLE 		*resultHand,			// RETURNED
	CSSM_DATA_PTR		theData,				// RETURED
	CSSM_DB_RECORDTYPE	*recordType)			// RETURNED
{
	CSSM_QUERY						query;
	CSSM_SELECTION_PREDICATE		predicate;
	CSSM_DB_UNIQUE_RECORD_PTR		record = NULL;
	CSSM_RETURN						crtn;
	
	switch(keyType) {
		case CKT_Public:
			query.RecordType = *recordType = CSSM_DL_DB_RECORD_PUBLIC_KEY;
			break;
		case CKT_Private:
			query.RecordType = *recordType = CSSM_DL_DB_RECORD_PRIVATE_KEY;
			break;
		case CKT_Session:
			query.RecordType = *recordType = CSSM_DL_DB_RECORD_SYMMETRIC_KEY;
			break;
		default:
			printf("Hey bozo! Give me a valid key type!\n");
			return NULL;
	}
	query.Conjunctive = CSSM_DB_NONE;
	query.NumSelectionPredicates = 1;
	predicate.DbOperator = CSSM_DB_EQUAL;
	
	predicate.Attribute.Info.AttributeNameFormat = 
		CSSM_DB_ATTRIBUTE_NAME_AS_STRING;
	predicate.Attribute.Info.Label.AttributeName = (char *) "Label";
	predicate.Attribute.Info.AttributeFormat = CSSM_DB_ATTRIBUTE_FORMAT_BLOB;
	/* hope this cast is OK */
	predicate.Attribute.Value = (CSSM_DATA_PTR)keyLabel;
	query.SelectionPredicate = &predicate;
	
	query.QueryLimits.TimeLimit = 0;	// FIXME - meaningful?
	query.QueryLimits.SizeLimit = 1;	// FIXME - meaningful?
	query.QueryFlags = CSSM_QUERY_RETURN_DATA;	// FIXME - used?
	
	crtn = CSSM_DL_DataGetFirst(dlDbHand,
		&query,
		resultHand,
		NULL,
		theData,
		&record);
	/* abort only on success */
	if(crtn == CSSM_OK) {
		crtn = CSSM_DL_DataAbortQuery(dlDbHand, *resultHand);
		if(crtn) {
			printError("CSSM_DL_AbortQuery", crtn);
			return NULL;
		}
	}
	return record;
}

/*
 * Look up a key by label and type.
 */
CSSM_KEY_PTR cspLookUpKeyByLabel(
	CSSM_DL_HANDLE dlHand, 
	CSSM_DB_HANDLE dbHand, 
	const CSSM_DATA *labelData, 
	CT_KeyType keyType)
{
	CSSM_DB_UNIQUE_RECORD_PTR	record;
	CSSM_HANDLE					resultHand;
	CSSM_DATA					theData;
	CSSM_KEY_PTR				key;
	CSSM_DB_RECORDTYPE 			recordType;
	CSSM_DL_DB_HANDLE			dlDbHand;
	
	dlDbHand.DLHandle = dlHand;
	dlDbHand.DBHandle = dbHand;
	
	theData.Length = 0;
	theData.Data = NULL;
	
	record = dlLookup(dlDbHand,
		labelData,
		keyType,
		&resultHand,
		&theData,
		&recordType);
	if(record == NULL) {
		//printf("cspLookUpKeyByLabel: key not found\n");
		return NULL;
	}
	key = (CSSM_KEY_PTR)theData.Data;
	CSSM_DL_FreeUniqueRecord(dlDbHand, record);
	return key;
}

/*
 * Delete and free a key 
 */
CSSM_RETURN cspDeleteKey(
	CSSM_CSP_HANDLE		cspHand,		// for free
	CSSM_DL_HANDLE		dlHand,			// for delete
	CSSM_DB_HANDLE		dbHand,			// ditto
	const CSSM_DATA 	*labelData, 
	CSSM_KEY_PTR		key)
{
	CSSM_DB_UNIQUE_RECORD_PTR	record;
	CSSM_HANDLE					resultHand;
	CT_KeyType					keyType;
	CSSM_RETURN					crtn = CSSM_OK;
	CSSM_DB_RECORDTYPE 			recordType;
	CSSM_DL_DB_HANDLE			dlDbHand;
	
	if(key->KeyHeader.KeyAttr & CSSM_KEYATTR_PERMANENT) {
		/* first do a lookup based in this key's fields */
		switch(key->KeyHeader.KeyClass) {
			case CSSM_KEYCLASS_PUBLIC_KEY:
				keyType = CKT_Public;
				break;
			case CSSM_KEYCLASS_PRIVATE_KEY:
				keyType = CKT_Private;
				break;
			case CSSM_KEYCLASS_SESSION_KEY:
				keyType = CKT_Session;
				break;
			default:
				printf("Hey bozo! Give me a valid key type!\n");
				return -1;
		}

		dlDbHand.DLHandle = dlHand;
		dlDbHand.DBHandle = dbHand;
		
		record = dlLookup(dlDbHand,
			labelData,
			keyType,
			&resultHand,
			NULL,			// don't want actual data
			&recordType);
		if(record == NULL) {
			printf("cspDeleteKey: key not found in DL\n");
			return CSSMERR_DL_RECORD_NOT_FOUND;
		}
		
		/* OK, nuke it */
		crtn = CSSM_DL_DataDelete(dlDbHand, record);
		if(crtn) {
			printError("CSSM_DL_DataDelete", crtn);
		}
		CSSM_DL_FreeUniqueRecord(dlDbHand, record);
	}
		
	/* CSSM_FreeKey() should fail due to the delete, but it will
	 * still free KeyData....
	 * FIXME - we should be able to do this in this one single call - right?
	 */
	CSSM_FreeKey(cspHand, NULL, key, CSSM_FALSE);

	return crtn;
}

/*
 * Given any key in either blob or reference format,
 * obtain the associated SHA-1 hash. 
 */
CSSM_RETURN cspKeyHash(
	CSSM_CSP_HANDLE		cspHand,	
	const CSSM_KEY_PTR	key,			/* public key */
	CSSM_DATA_PTR		*hashData)		/* hash mallocd and RETURNED here */
{
	CSSM_CC_HANDLE		ccHand;
	CSSM_RETURN			crtn;
	CSSM_DATA_PTR		dp;
	
	*hashData = NULL;
	
	/* validate input params */
	if((key == NULL) ||
	   (hashData == NULL)) {
	   	printf("cspKeyHash: bogus args\n");
		return CSSMERR_CSSM_INTERNAL_ERROR;				
	}
	
	/* cook up a context for a passthrough op */
	crtn = CSSM_CSP_CreatePassThroughContext(cspHand,
	 	key,
		&ccHand);
	if(ccHand == 0) {
		printError("CSSM_CSP_CreatePassThroughContext", crtn);
		return crtn;
	}
	
	/* now it's up to the CSP */
	crtn = CSSM_CSP_PassThrough(ccHand,
		CSSM_APPLECSP_KEYDIGEST,
		NULL,
		(void **)&dp);
	if(crtn) {
		printError("CSSM_CSP_PassThrough(PUBKEYHASH)", crtn);
	}
	else {
		*hashData = dp;
		crtn = CSSM_OK;
	}
	CSSM_DeleteContext(ccHand);
	return crtn;
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted LocalTests/utilLib/cspwrap.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/* Copyright 1997 Apple Computer, Inc.
 *
 * cspwrap.h - wrappers to simplify access to CDSA
 *
 * Revision History
 * ----------------
 *   3 May 2000 Doug Mitchell
 *		Ported to X/CDSA2.
 *  12 Aug 1997	Doug Mitchell at Apple
 *		Created.
 */
 
#ifndef	_CSPWRAP_H_
#define _CSPWRAP_H_
#include <Security/cssm.h>

#ifdef	__cplusplus
extern "C" {
#endif

/* 
 * Bug/feature workaround flags
 */
 
/* 
 * Doing a WrapKey requires Access Creds, which should be 
 * optional. Looks like this is not a bug.
 */
#define WRAP_KEY_REQUIRES_CREDS	1

/*
 * encrypt/decrypt - cook up a context handle
 */
CSSM_CC_HANDLE genCryptHandle(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEED, etc.
		uint32 mode,						// CSSM_ALGMODE_CBC, etc. - only for symmetric algs
		CSSM_PADDING padding,				// CSSM_PADDING_PKCS1, etc. 
		const CSSM_KEY *key0,
		const CSSM_KEY *key1,				// for CSSM_ALGID_FEED only - must be the 
											// public key
		const CSSM_DATA *iv,				// optional
		uint32 effectiveKeySizeInBits,		// 0 means skip this attribute
		uint32 rounds);						// ditto
/*
 * Key generation
 */
/*
 * Specifying a keySize of CSP_KEY_SIZE_DEFAULT results in using the default
 * key size for the specified algorithm.
 */
#define CSP_KEY_SIZE_DEFAULT		0

/* symmetric key sizes in bits */
#define CSP_ASC_KEY_SIZE_DEFAULT	(16 * 8)
#define CSP_DES_KEY_SIZE_DEFAULT	(8 * 8)
#define CSP_DES3_KEY_SIZE_DEFAULT	(24 * 8)
#define CSP_RC2_KEY_SIZE_DEFAULT	(10 * 8)
#define CSP_RC4_KEY_SIZE_DEFAULT	(10 * 8)
#define CSP_RC5_KEY_SIZE_DEFAULT	(10 * 8)
#define CSP_AES_KEY_SIZE_DEFAULT	128
#define CSP_BFISH_KEY_SIZE_DEFAULT	128
#define CSP_CAST_KEY_SIZE_DEFAULT	128
#define CSP_IDEA_KEY_SIZE_DEFAULT	128				/* fixed */
#define CSP_HMAC_SHA_KEY_SIZE_DEFAULT	(20 * 8)
#define CSP_HMAC_MD5_KEY_SIZE_DEFAULT	(16 * 8)
#define CSP_NULL_CRYPT_KEY_SIZE_DEF	(16 * 8)

/* asymmetric key sizes in bits */
/* note: we now use AI_RSAStrongKeyGen for RSA key pair 
 * generate; this requires at least 512 bits and also that
 * the key size be a multiple of 16. */
#define CSP_FEE_KEY_SIZE_DEFAULT	128

#define CSP_RSA_KEY_SIZE_DEFAULT	1024		/* min for SHA512/RSA */
#define CSP_DSA_KEY_SIZE_DEFAULT	512

/*
 * Generate key pair of arbitrary algorithm. 
 */
extern CSSM_RETURN cspGenKeyPair(CSSM_CSP_HANDLE cspHand,	
	uint32 algorithm,
	const char *keyLabel,
	unsigned keyLabelLen,
	uint32 keySizeInBits,
	CSSM_KEY_PTR pubKey,			// mallocd by caller
	CSSM_BOOL pubIsRef,				// true - reference key, false - data
	uint32 pubKeyUsage,				// CSSM_KEYUSE_ENCRYPT, etc.
	CSSM_KEYBLOB_FORMAT pubFormat,	// Optional. Specify 0 or CSSM_KEYBLOB_RAW_FORMAT_NONE
									//   to get the default format. 
	CSSM_KEY_PTR privKey,			// mallocd by caller - always returned as ref
	CSSM_BOOL privIsRef,			// true - reference key, false - data
	uint32 privKeyUsage,			// CSSM_KEYUSE_DECRYPT, etc.
	CSSM_KEYBLOB_FORMAT privFormat,	// optional 0 ==> default
	CSSM_BOOL genSeed);				// FEE only. True: we generate seed and CSP
									//   will hash it. False: CSP generates random 
									//   seed. 

/*
 * Generate FEE key pair with optional primeType, curveType, and seed (password) data.
 */
extern CSSM_RETURN cspGenFEEKeyPair(CSSM_CSP_HANDLE cspHand,
	const char *keyLabel,
	unsigned keyLabelLen,
	uint32 keySize,					// in bits
	uint32 primeType,				// CSSM_FEE_PRIME_TYPE_MERSENNE, etc.
	uint32 curveType,				// CSSM_FEE_CURVE_TYPE_MONTGOMERY, etc.
	CSSM_KEY_PTR pubKey,			// mallocd by caller
	CSSM_BOOL pubIsRef,				// true - reference key, false - data
	uint32 pubKeyUsage,				// CSSM_KEYUSE_ENCRYPT, etc.
	CSSM_KEYBLOB_FORMAT pubFormat,	// Optional. Specify 0 or CSSM_KEYBLOB_RAW_FORMAT_NONE
									//   to get the default format. 
	CSSM_KEY_PTR privKey,			// mallocd by caller
	CSSM_BOOL privIsRef,			// true - reference key, false - data
	uint32 privKeyUsage,			// CSSM_KEYUSE_DECRYPT, etc.
	CSSM_KEYBLOB_FORMAT privFormat,	// optional 0 ==> default
	const CSSM_DATA *seedData);		// Present: CSP will hash this for private data.
									// NULL: CSP generates random seed. 

/*
 * Generate DSA key pair with optional generateAlgParams.
 */
extern CSSM_RETURN cspGenDSAKeyPair(CSSM_CSP_HANDLE cspHand,
	const char *keyLabel,
	unsigned keyLabelLen,
	uint32 keySize,					// in bits
	CSSM_KEY_PTR pubKey,			// mallocd by caller
	CSSM_BOOL pubIsRef,				// true - reference key, false - data
	uint32 pubKeyUsage,				// CSSM_KEYUSE_ENCRYPT, etc.
	CSSM_KEYBLOB_FORMAT pubFormat,	// Optional. Specify 0 or CSSM_KEYBLOB_RAW_FORMAT_NONE
									//   to get the default format. 
	CSSM_KEY_PTR privKey,			// mallocd by caller
	CSSM_BOOL privIsRef,			// true - reference key, false - data
	uint32 privKeyUsage,			// CSSM_KEYUSE_DECRYPT, etc.
	CSSM_KEYBLOB_FORMAT privFormat,	// Optional. Specify 0 or CSSM_KEYBLOB_RAW_FORMAT_NONE
									//   to get the default format. 
	CSSM_BOOL genParams,
	CSSM_DATA_PTR paramData);		// optional

/*
 * Create a symmetric key.
 */
extern CSSM_KEY_PTR cspGenSymKey(CSSM_CSP_HANDLE cspHand,
		uint32 				alg,
		const char 			*keyLabel,
		unsigned 			keyLabelLen,
		uint32 				keyUsage,		// CSSM_KEYUSE_ENCRYPT, etc.
		uint32 				keySizeInBits,
		CSSM_BOOL			refKey); // true - reference key, false - data

/*
 * Derive symmetric key using PBE.
 */
CSSM_KEY_PTR cspDeriveKey(CSSM_CSP_HANDLE cspHand,
		uint32 				deriveAlg,		// CSSM_ALGID_MD5_PBE, etc.
		uint32				keyAlg,			// CSSM_ALGID_RC5, etc.
		const char 			*keyLabel,
		unsigned 			keyLabelLen,
		uint32 				keyUsage,		// CSSM_KEYUSE_ENCRYPT, etc.
		uint32 				keySizeInBits,
		CSSM_BOOL			isRefKey,
		CSSM_DATA_PTR		password,		// in PKCS-5 lingo
		CSSM_DATA_PTR		salt,			// ditto
		uint32				iterationCnt,	// ditto
		CSSM_DATA_PTR		initVector);	// mallocd & RETURNED

/*
 * Encrypt/Decrypt - these work for both symmetric and asymmetric algorithms.
 */
CSSM_RETURN cspEncrypt(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEED, etc.
		uint32 mode,						// CSSM_ALGMODE_CBC, etc. - only for 
											//    symmetric algs
		CSSM_PADDING padding,				// CSSM_PADDING_PKCS1, etc. 
		const CSSM_KEY *key,				// public or session key
		const CSSM_KEY *pubKey,				// for CSSM_ALGID_{FEED,FEECFILE} only
		uint32 effectiveKeySizeInBits,		// 0 means skip this attribute
		uint32 rounds,						// ditto
		const CSSM_DATA *iv,				// init vector, optional
		const CSSM_DATA *ptext,
		CSSM_DATA_PTR ctext,				// RETURNED
		CSSM_BOOL mallocCtext);
		
CSSM_RETURN cspStagedEncrypt(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEED, etc.
		uint32 mode,						// CSSM_ALGMODE_CBC, etc. - only for 
											//    symmetric algs
		CSSM_PADDING padding,				// CSSM_PADDING_PKCS1, etc. 
		const CSSM_KEY *key,				// public or session key
		const CSSM_KEY *pubKey,				// for CSSM_ALGID_{FEED,FEECFILE} only
		uint32 effectiveKeySizeInBits,		// 0 means skip this attribute
		uint32 cipherBlockSize,				// ditto, block size in bytes
		uint32 rounds,						// ditto
		const CSSM_DATA *iv,				// init vector, optional
		const CSSM_DATA *ptext,
		CSSM_DATA_PTR ctext,				// RETURNED, we malloc
		CSSM_BOOL multiUpdates);			// false:single update, true:multi updates
		
CSSM_RETURN cspDecrypt(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEED, etc.
		uint32 mode,						// CSSM_ALGMODE_CBC, etc. - only for 
											//    symmetric algs
		CSSM_PADDING padding,				// CSSM_PADDING_PKCS1, etc. 
		const CSSM_KEY *key,				// private or session key
		const CSSM_KEY *pubKey,				// for CSSM_ALGID_{FEED,FEECFILE} only
		uint32 effectiveKeySizeInBits,		// 0 means skip this attribute
		uint32 rounds,						// ditto
		const CSSM_DATA *iv,				// init vector, optional
		const CSSM_DATA *ctext,
		CSSM_DATA_PTR ptext,				// RETURNED
		CSSM_BOOL mallocPtext);
		
CSSM_RETURN cspStagedDecrypt(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEED, etc.
		uint32 mode,						// CSSM_ALGMODE_CBC, etc. - only for 
											//    symmetric algs
		CSSM_PADDING padding,				// CSSM_PADDING_PKCS1, etc. 
		const CSSM_KEY *key,				// private or session key
		const CSSM_KEY *pubKey,				// for CSSM_ALGID_{FEED,FEECFILE} only
		uint32 effectiveKeySizeInBits,		// 0 means skip this attribute
		uint32 cipherBlockSize,				// ditto, block size in bytes
		uint32 rounds,						// ditto
		const CSSM_DATA *iv,				// init vector, optional
		const CSSM_DATA *ctext,
		CSSM_DATA_PTR ptext,				// RETURNED, we malloc
		CSSM_BOOL multiUpdates);			// false:single update, true:multi updates

/*
 * Signature routines
 */
CSSM_RETURN cspSign(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// private key
		const CSSM_DATA *text,
		CSSM_DATA_PTR sig);					// RETURNED
CSSM_RETURN cspStagedSign(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// private key
		const CSSM_DATA *text,
		CSSM_BOOL multiUpdates,				// false:single update, true:multi updates
		CSSM_DATA_PTR sig);					// RETURNED
CSSM_RETURN cspSigVerify(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// public key
		const CSSM_DATA *text,
		const CSSM_DATA *sig,
		CSSM_RETURN expectResult);			// expected result is verify failure
											// CSSM_OK - expect success
CSSM_RETURN cspStagedSigVerify(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// private key
		const CSSM_DATA *text,
		const CSSM_DATA *sig,
		CSSM_BOOL multiUpdates,				// false:single update, true:multi updates
		CSSM_RETURN expectResult);			// expected result is verify failure
											// CSSM_OK - expect success

/*
 * MAC routines
 */
CSSM_RETURN cspGenMac(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_DES, etc.
		CSSM_KEY_PTR key,					// session key
		const CSSM_DATA *text,
		CSSM_DATA_PTR mac);					// RETURNED
CSSM_RETURN cspStagedGenMac(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_FEE_MD5, etc.
		CSSM_KEY_PTR key,					// private key
		const CSSM_DATA *text,
		CSSM_BOOL mallocMac,				// if true and digest->Length = 0, we'll 
											//		malloc
		CSSM_BOOL multiUpdates,				// false:single update, true:multi updates
		CSSM_DATA_PTR mac);					// RETURNED
CSSM_RETURN cspMacVerify(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					
		CSSM_KEY_PTR key,					// public key
		const CSSM_DATA *text,
		const CSSM_DATA_PTR mac,
		CSSM_RETURN expectResult);		
CSSM_RETURN cspStagedMacVerify(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					
		CSSM_KEY_PTR key,					// private key
		const CSSM_DATA *text,
		const CSSM_DATA_PTR mac,
		CSSM_BOOL multiUpdates,				// false:single update, true:multi updates
		CSSM_RETURN expectResult);			

/*
 * Digest functions
 */
CSSM_RETURN cspDigest(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_MD5, etc.
		CSSM_BOOL mallocDigest,				// if true and digest->Length = 0, we'll malloc
		const CSSM_DATA *text,
		CSSM_DATA_PTR digest);
CSSM_RETURN cspStagedDigest(CSSM_CSP_HANDLE cspHand,
		uint32 algorithm,					// CSSM_ALGID_MD5, etc.
		CSSM_BOOL mallocDigest,				// if true and digest->Length = 0, we'll malloc
		CSSM_BOOL multiUpdates,				// false:single update, true:multi updates
		const CSSM_DATA *text,
		CSSM_DATA_PTR digest);
CSSM_RETURN	cspFreeKey(CSSM_CSP_HANDLE cspHand,
	CSSM_KEY_PTR key);

/*
 * Perform FEE Key exchange via CSSM_DeriveKey. 
 */
CSSM_RETURN cspFeeKeyExchange(CSSM_CSP_HANDLE cspHand,
	CSSM_KEY_PTR 	privKey,
	CSSM_KEY_PTR 	pubKey,
	CSSM_KEY_PTR 	derivedKey,		// mallocd by caller
	
	/* remaining fields apply to derivedKey */
	uint32 			keyAlg,
	const char 		*keyLabel,
	unsigned 		keyLabelLen,
	uint32 			keyUsage,		// CSSM_KEYUSE_ENCRYPT, etc.
	uint32 			keySizeInBits);

/* 
 * wrap/unwrap key functions. 
 */
CSSM_RETURN cspWrapKey(CSSM_CSP_HANDLE cspHand,
	const CSSM_KEY			*unwrappedKey,	
	const CSSM_KEY			*wrappingKey,
	CSSM_ALGORITHMS			wrapAlg,
	CSSM_ENCRYPT_MODE		wrapMode,
	CSSM_KEYBLOB_FORMAT		wrapFormat,			// NONE, PKCS7, PKCS8
	CSSM_PADDING			wrapPad,
	CSSM_DATA_PTR			initVector,			// for some wrapping algs
	CSSM_DATA_PTR			descrData,			// optional 
	CSSM_KEY_PTR			wrappedKey);		// RETURNED
CSSM_RETURN cspUnwrapKey(CSSM_CSP_HANDLE cspHand,
	const CSSM_KEY			*wrappedKey,
	const CSSM_KEY			*unwrappingKey,
	CSSM_ALGORITHMS			unwrapAlg,
	CSSM_ENCRYPT_MODE		unwrapMode,
	CSSM_PADDING 			unwrapPad,
	CSSM_DATA_PTR			initVector,			// for some wrapping algs
	CSSM_KEY_PTR			unwrappedKey,		// RETURNED
	CSSM_DATA_PTR			descrData,			// required
	const char 				*keyLabel,
	unsigned 				keyLabelLen);

/* generate a random and reasonable key size in bits for specified CSSM algorithm */
typedef enum {
	OT_Sign,
	OT_Encrypt,
	OT_KeyExch
} opType;

#define MAX_KEY_SIZE_RC245_BYTES		64	/* max bytes, RC2, RC4, RC5 */

uint32 randKeySizeBits(uint32 alg, opType op);
uint32 cspDefaultKeySize(uint32 alg);

/*
 * Generate random key size, primeType, curveType for FEE key for specified op.
 */
void randFeeKeyParams(
	CSSM_ALGORITHMS	alg,			// ALGID_FEED, CSSM_ALGID_FEE_MD5, etc.
	uint32			*keySizeInBits,	// RETURNED
	uint32 			*primeType,		// CSSM_FEE_PRIME_TYPE_xxx, RETURNED
	uint32 			*curveType);	// CSSM_FEE_CURVE_TYPE_xxx, RETURNED

/*
 * Obtain strings for primeType and curveType.
 */
const char *primeTypeStr(uint32 primeType);
const char *curveTypeStr(uint32 curveType);

/*
 * Given any key in either blob or reference format,
 * obtain the associated SHA-1 hash. 
 */
CSSM_RETURN cspKeyHash(
	CSSM_CSP_HANDLE		cspHand,	
	const CSSM_KEY_PTR	key,			/* public key */
	CSSM_DATA_PTR		*hashData);		/* hash mallocd and RETURNED here */

/* wrap ref key --> raw key */
CSSM_RETURN cspRefKeyToRaw(
	CSSM_CSP_HANDLE cspHand,
	const CSSM_KEY *refKey,
	CSSM_KEY_PTR rawKey);				// init'd and RETURNED

/* unwrap raw key --> ref */
CSSM_RETURN cspRawKeyToRef(
	CSSM_CSP_HANDLE cspHand,
	const CSSM_KEY *rawKey,
	CSSM_KEY_PTR refKey);				// init'd and RETURNED

/*
 * Cook up a symmetric key with specified key bits and other
 * params. Currently the CSPDL can only deal with reference keys except when
 * doing wrap/unwrap, so we manually cook up a raw key, then we null-unwrap it. 
 */
CSSM_RETURN cspGenSymKeyWithBits(
	CSSM_CSP_HANDLE		cspHand,
	CSSM_ALGORITHMS		keyAlg,
	CSSM_KEYUSE			keyUsage,
	const CSSM_DATA		*keyBits,
	unsigned			keySizeInBytes,
	CSSM_KEY_PTR		refKey);			// init'd and RETURNED

/*
 * Add a DL/DB handle to a crypto context.
 */
CSSM_RETURN cspAddDlDbToContext(
	CSSM_CC_HANDLE ccHand,
	CSSM_DL_HANDLE dlHand,
	CSSM_DB_HANDLE dbHand);

/*
 * Look up a key by label and type.
 */
typedef enum {
	CKT_Public = 1,
	CKT_Private = 2,
	CKT_Session = 3
	/* any others? */
} CT_KeyType;

CSSM_KEY_PTR cspLookUpKeyByLabel(
	CSSM_DL_HANDLE dlHand, 
	CSSM_DB_HANDLE dbHand, 
	const CSSM_DATA *labelData, 
	CT_KeyType keyType);

/*
 * Delete and free a key 
 */
CSSM_RETURN cspDeleteKey(
	CSSM_CSP_HANDLE		cspHand,		// for free
	CSSM_DL_HANDLE		dlHand,			// for delete
	CSSM_DB_HANDLE		dbHand,			// ditto
	const CSSM_DATA 	*labelData, 
	CSSM_KEY_PTR		key);

// temp hack
#define	CSSM_ALGID_FEECFILE		(CSSM_ALGID_VENDOR_DEFINED + 102)

#ifdef	__cplusplus
}
#endif
#endif	/* _CSPWRAP_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted LocalTests/utilLib/cssmErrorStrings.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
/*
 * This file autogenerated by genErrorStrings. Do not edit. 
 */

#include <Security/Security.h>

typedef struct {
	CSSM_RETURN errCode;
	const char *errStr;
} ErrString;

static const ErrString errStrings[] = {
	{ CSSM_OK,"CSSM_OK"},
	/* Error codes from cssmerr.h */
	{ CSSMERR_CSSM_INVALID_ADDIN_HANDLE,"CSSMERR_CSSM_INVALID_ADDIN_HANDLE"},
	{ CSSMERR_CSSM_NOT_INITIALIZED,"CSSMERR_CSSM_NOT_INITIALIZED"},
	{ CSSMERR_CSSM_INVALID_HANDLE_USAGE,"CSSMERR_CSSM_INVALID_HANDLE_USAGE"},
	{ CSSMERR_CSSM_PVC_REFERENT_NOT_FOUND,"CSSMERR_CSSM_PVC_REFERENT_NOT_FOUND"},
	{ CSSMERR_CSSM_FUNCTION_INTEGRITY_FAIL,"CSSMERR_CSSM_FUNCTION_INTEGRITY_FAIL"},
	{ CSSMERR_CSSM_INTERNAL_ERROR,"CSSMERR_CSSM_INTERNAL_ERROR"},
	{ CSSMERR_CSSM_MEMORY_ERROR,"CSSMERR_CSSM_MEMORY_ERROR"},
	{ CSSMERR_CSSM_MDS_ERROR,"CSSMERR_CSSM_MDS_ERROR"},
	{ CSSMERR_CSSM_INVALID_POINTER,"CSSMERR_CSSM_INVALID_POINTER"},
	{ CSSMERR_CSSM_INVALID_INPUT_POINTER,"CSSMERR_CSSM_INVALID_INPUT_POINTER"},
	{ CSSMERR_CSSM_INVALID_OUTPUT_POINTER,"CSSMERR_CSSM_INVALID_OUTPUT_POINTER"},
	{ CSSMERR_CSSM_FUNCTION_NOT_IMPLEMENTED,"CSSMERR_CSSM_FUNCTION_NOT_IMPLEMENTED"},
	{ CSSMERR_CSSM_SELF_CHECK_FAILED,"CSSMERR_CSSM_SELF_CHECK_FAILED"},
	{ CSSMERR_CSSM_OS_ACCESS_DENIED,"CSSMERR_CSSM_OS_ACCESS_DENIED"},
	{ CSSMERR_CSSM_FUNCTION_FAILED,"CSSMERR_CSSM_FUNCTION_FAILED"},
	{ CSSMERR_CSSM_MODULE_MANIFEST_VERIFY_FAILED,"CSSMERR_CSSM_MODULE_MANIFEST_VERIFY_FAILED"},
	{ CSSMERR_CSSM_INVALID_GUID,"CSSMERR_CSSM_INVALID_GUID"},
	{ CSSMERR_CSSM_INVALID_CONTEXT_HANDLE,"CSSMERR_CSSM_INVALID_CONTEXT_HANDLE"},
	{ CSSMERR_CSSM_INCOMPATIBLE_VERSION,"CSSMERR_CSSM_INCOMPATIBLE_VERSION"},
	{ CSSMERR_CSSM_PRIVILEGE_NOT_GRANTED,"CSSMERR_CSSM_PRIVILEGE_NOT_GRANTED"},
	{ CSSMERR_CSSM_SCOPE_NOT_SUPPORTED,"CSSMERR_CSSM_SCOPE_NOT_SUPPORTED"},
	{ CSSMERR_CSSM_PVC_ALREADY_CONFIGURED,"CSSMERR_CSSM_PVC_ALREADY_CONFIGURED"},
	{ CSSMERR_CSSM_INVALID_PVC,"CSSMERR_CSSM_INVALID_PVC"},
	{ CSSMERR_CSSM_EMM_LOAD_FAILED,"CSSMERR_CSSM_EMM_LOAD_FAILED"},
	{ CSSMERR_CSSM_EMM_UNLOAD_FAILED,"CSSMERR_CSSM_EMM_UNLOAD_FAILED"},
	{ CSSMERR_CSSM_ADDIN_LOAD_FAILED,"CSSMERR_CSSM_ADDIN_LOAD_FAILED"},
	{ CSSMERR_CSSM_INVALID_KEY_HIERARCHY,"CSSMERR_CSSM_INVALID_KEY_HIERARCHY"},
	{ CSSMERR_CSSM_ADDIN_UNLOAD_FAILED,"CSSMERR_CSSM_ADDIN_UNLOAD_FAILED"},
	{ CSSMERR_CSSM_LIB_REF_NOT_FOUND,"CSSMERR_CSSM_LIB_REF_NOT_FOUND"},
	{ CSSMERR_CSSM_INVALID_ADDIN_FUNCTION_TABLE,"CSSMERR_CSSM_INVALID_ADDIN_FUNCTION_TABLE"},
	{ CSSMERR_CSSM_EMM_AUTHENTICATE_FAILED,"CSSMERR_CSSM_EMM_AUTHENTICATE_FAILED"},
	{ CSSMERR_CSSM_ADDIN_AUTHENTICATE_FAILED,"CSSMERR_CSSM_ADDIN_AUTHENTICATE_FAILED"},
	{ CSSMERR_CSSM_INVALID_SERVICE_MASK,"CSSMERR_CSSM_INVALID_SERVICE_MASK"},
	{ CSSMERR_CSSM_MODULE_NOT_LOADED,"CSSMERR_CSSM_MODULE_NOT_LOADED"},
	{ CSSMERR_CSSM_INVALID_SUBSERVICEID,"CSSMERR_CSSM_INVALID_SUBSERVICEID"},
	{ CSSMERR_CSSM_BUFFER_TOO_SMALL,"CSSMERR_CSSM_BUFFER_TOO_SMALL"},
	{ CSSMERR_CSSM_INVALID_ATTRIBUTE,"CSSMERR_CSSM_INVALID_ATTRIBUTE"},
	{ CSSMERR_CSSM_ATTRIBUTE_NOT_IN_CONTEXT,"CSSMERR_CSSM_ATTRIBUTE_NOT_IN_CONTEXT"},
	{ CSSMERR_CSSM_MODULE_MANAGER_INITIALIZE_FAIL,"CSSMERR_CSSM_MODULE_MANAGER_INITIALIZE_FAIL"},
	{ CSSMERR_CSSM_MODULE_MANAGER_NOT_FOUND,"CSSMERR_CSSM_MODULE_MANAGER_NOT_FOUND"},
	{ CSSMERR_CSSM_EVENT_NOTIFICATION_CALLBACK_NOT_FOUND,"CSSMERR_CSSM_EVENT_NOTIFICATION_CALLBACK_NOT_FOUND"},
	{ CSSMERR_CSP_INTERNAL_ERROR,"CSSMERR_CSP_INTERNAL_ERROR"},
	{ CSSMERR_CSP_MEMORY_ERROR,"CSSMERR_CSP_MEMORY_ERROR"},
	{ CSSMERR_CSP_MDS_ERROR,"CSSMERR_CSP_MDS_ERROR"},
	{ CSSMERR_CSP_INVALID_POINTER,"CSSMERR_CSP_INVALID_POINTER"},
	{ CSSMERR_CSP_INVALID_INPUT_POINTER,"CSSMERR_CSP_INVALID_INPUT_POINTER"},
	{ CSSMERR_CSP_INVALID_OUTPUT_POINTER,"CSSMERR_CSP_INVALID_OUTPUT_POINTER"},
	{ CSSMERR_CSP_FUNCTION_NOT_IMPLEMENTED,"CSSMERR_CSP_FUNCTION_NOT_IMPLEMENTED"},
	{ CSSMERR_CSP_SELF_CHECK_FAILED,"CSSMERR_CSP_SELF_CHECK_FAILED"},
	{ CSSMERR_CSP_OS_ACCESS_DENIED,"CSSMERR_CSP_OS_ACCESS_DENIED"},
	{ CSSMERR_CSP_FUNCTION_FAILED,"CSSMERR_CSP_FUNCTION_FAILED"},
	{ CSSMERR_CSP_OPERATION_AUTH_DENIED,"CSSMERR_CSP_OPERATION_AUTH_DENIED"},
	{ CSSMERR_CSP_OBJECT_USE_AUTH_DENIED,"CSSMERR_CSP_OBJECT_USE_AUTH_DENIED"},
	{ CSSMERR_CSP_OBJECT_MANIP_AUTH_DENIED,"CSSMERR_CSP_OBJECT_MANIP_AUTH_DENIED"},
	{ CSSMERR_CSP_OBJECT_ACL_NOT_SUPPORTED,"CSSMERR_CSP_OBJECT_ACL_NOT_SUPPORTED"},
	{ CSSMERR_CSP_OBJECT_ACL_REQUIRED,"CSSMERR_CSP_OBJECT_ACL_REQUIRED"},
	{ CSSMERR_CSP_INVALID_ACCESS_CREDENTIALS,"CSSMERR_CSP_INVALID_ACCESS_CREDENTIALS"},
	{ CSSMERR_CSP_INVALID_ACL_BASE_CERTS,"CSSMERR_CSP_INVALID_ACL_BASE_CERTS"},
	{ CSSMERR_CSP_ACL_BASE_CERTS_NOT_SUPPORTED,"CSSMERR_CSP_ACL_BASE_CERTS_NOT_SUPPORTED"},
	{ CSSMERR_CSP_INVALID_SAMPLE_VALUE,"CSSMERR_CSP_INVALID_SAMPLE_VALUE"},
	{ CSSMERR_CSP_SAMPLE_VALUE_NOT_SUPPORTED,"CSSMERR_CSP_SAMPLE_VALUE_NOT_SUPPORTED"},
	{ CSSMERR_CSP_INVALID_ACL_SUBJECT_VALUE,"CSSMERR_CSP_INVALID_ACL_SUBJECT_VALUE"},
	{ CSSMERR_CSP_ACL_SUBJECT_TYPE_NOT_SUPPORTED,"CSSMERR_CSP_ACL_SUBJECT_TYPE_NOT_SUPPORTED"},
	{ CSSMERR_CSP_INVALID_ACL_CHALLENGE_CALLBACK,"CSSMERR_CSP_INVALID_ACL_CHALLENGE_CALLBACK"},
	{ CSSMERR_CSP_ACL_CHALLENGE_CALLBACK_FAILED,"CSSMERR_CSP_ACL_CHALLENGE_CALLBACK_FAILED"},
	{ CSSMERR_CSP_INVALID_ACL_ENTRY_TAG,"CSSMERR_CSP_INVALID_ACL_ENTRY_TAG"},
	{ CSSMERR_CSP_ACL_ENTRY_TAG_NOT_FOUND,"CSSMERR_CSP_ACL_ENTRY_TAG_NOT_FOUND"},
	{ CSSMERR_CSP_INVALID_ACL_EDIT_MODE,"CSSMERR_CSP_INVALID_ACL_EDIT_MODE"},
	{ CSSMERR_CSP_ACL_CHANGE_FAILED,"CSSMERR_CSP_ACL_CHANGE_FAILED"},
	{ CSSMERR_CSP_INVALID_NEW_ACL_ENTRY,"CSSMERR_CSP_INVALID_NEW_ACL_ENTRY"},
	{ CSSMERR_CSP_INVALID_NEW_ACL_OWNER,"CSSMERR_CSP_INVALID_NEW_ACL_OWNER"},
	{ CSSMERR_CSP_ACL_DELETE_FAILED,"CSSMERR_CSP_ACL_DELETE_FAILED"},
	{ CSSMERR_CSP_ACL_REPLACE_FAILED,"CSSMERR_CSP_ACL_REPLACE_FAILED"},
	{ CSSMERR_CSP_ACL_ADD_FAILED,"CSSMERR_CSP_ACL_ADD_FAILED"},
	{ CSSMERR_CSP_INVALID_CONTEXT_HANDLE,"CSSMERR_CSP_INVALID_CONTEXT_HANDLE"},
	{ CSSMERR_CSP_PRIVILEGE_NOT_GRANTED,"CSSMERR_CSP_PRIVILEGE_NOT_GRANTED"},
	{ CSSMERR_CSP_INVALID_DATA,"CSSMERR_CSP_INVALID_DATA"},
	{ CSSMERR_CSP_INVALID_PASSTHROUGH_ID,"CSSMERR_CSP_INVALID_PASSTHROUGH_ID"},
	{ CSSMERR_CSP_INVALID_CRYPTO_DATA,"CSSMERR_CSP_INVALID_CRYPTO_DATA"},
	{ CSSMERR_CSP_INPUT_LENGTH_ERROR,"CSSMERR_CSP_INPUT_LENGTH_ERROR"},
	{ CSSMERR_CSP_OUTPUT_LENGTH_ERROR,"CSSMERR_CSP_OUTPUT_LENGTH_ERROR"},
	{ CSSMERR_CSP_PRIVILEGE_NOT_SUPPORTED,"CSSMERR_CSP_PRIVILEGE_NOT_SUPPORTED"},
	{ CSSMERR_CSP_DEVICE_ERROR,"CSSMERR_CSP_DEVICE_ERROR"},
	{ CSSMERR_CSP_DEVICE_MEMORY_ERROR,"CSSMERR_CSP_DEVICE_MEMORY_ERROR"},
	{ CSSMERR_CSP_ATTACH_HANDLE_BUSY,"CSSMERR_CSP_ATTACH_HANDLE_BUSY"},
	{ CSSMERR_CSP_NOT_LOGGED_IN,"CSSMERR_CSP_NOT_LOGGED_IN"},
	{ CSSMERR_CSP_INVALID_KEY,"CSSMERR_CSP_INVALID_KEY"},
	{ CSSMERR_CSP_INVALID_KEY_REFERENCE,"CSSMERR_CSP_INVALID_KEY_REFERENCE"},
	{ CSSMERR_CSP_INVALID_KEY_CLASS,"CSSMERR_CSP_INVALID_KEY_CLASS"},
	{ CSSMERR_CSP_ALGID_MISMATCH,"CSSMERR_CSP_ALGID_MISMATCH"},
	{ CSSMERR_CSP_KEY_USAGE_INCORRECT,"CSSMERR_CSP_KEY_USAGE_INCORRECT"},
	{ CSSMERR_CSP_KEY_BLOB_TYPE_INCORRECT,"CSSMERR_CSP_KEY_BLOB_TYPE_INCORRECT"},
	{ CSSMERR_CSP_KEY_HEADER_INCONSISTENT,"CSSMERR_CSP_KEY_HEADER_INCONSISTENT"},
	{ CSSMERR_CSP_UNSUPPORTED_KEY_FORMAT,"CSSMERR_CSP_UNSUPPORTED_KEY_FORMAT"},
	{ CSSMERR_CSP_UNSUPPORTED_KEY_SIZE,"CSSMERR_CSP_UNSUPPORTED_KEY_SIZE"},
	{ CSSMERR_CSP_INVALID_KEY_POINTER,"CSSMERR_CSP_INVALID_KEY_POINTER"},
	{ CSSMERR_CSP_INVALID_KEYUSAGE_MASK,"CSSMERR_CSP_INVALID_KEYUSAGE_MASK"},
	{ CSSMERR_CSP_UNSUPPORTED_KEYUSAGE_MASK,"CSSMERR_CSP_UNSUPPORTED_KEYUSAGE_MASK"},
	{ CSSMERR_CSP_INVALID_KEYATTR_MASK,"CSSMERR_CSP_INVALID_KEYATTR_MASK"},
	{ CSSMERR_CSP_UNSUPPORTED_KEYATTR_MASK,"CSSMERR_CSP_UNSUPPORTED_KEYATTR_MASK"},
	{ CSSMERR_CSP_INVALID_KEY_LABEL,"CSSMERR_CSP_INVALID_KEY_LABEL"},
	{ CSSMERR_CSP_UNSUPPORTED_KEY_LABEL,"CSSMERR_CSP_UNSUPPORTED_KEY_LABEL"},
	{ CSSMERR_CSP_INVALID_KEY_FORMAT,"CSSMERR_CSP_INVALID_KEY_FORMAT"},
	{ CSSMERR_CSP_INVALID_DATA_COUNT,"CSSMERR_CSP_INVALID_DATA_COUNT"},
	{ CSSMERR_CSP_VECTOR_OF_BUFS_UNSUPPORTED,"CSSMERR_CSP_VECTOR_OF_BUFS_UNSUPPORTED"},
	{ CSSMERR_CSP_INVALID_INPUT_VECTOR,"CSSMERR_CSP_INVALID_INPUT_VECTOR"},
	{ CSSMERR_CSP_INVALID_OUTPUT_VECTOR,"CSSMERR_CSP_INVALID_OUTPUT_VECTOR"},
	{ CSSMERR_CSP_INVALID_CONTEXT,"CSSMERR_CSP_INVALID_CONTEXT"},
	{ CSSMERR_CSP_INVALID_ALGORITHM,"CSSMERR_CSP_INVALID_ALGORITHM"},
	{ CSSMERR_CSP_INVALID_ATTR_KEY,"CSSMERR_CSP_INVALID_ATTR_KEY"},
	{ CSSMERR_CSP_MISSING_ATTR_KEY,"CSSMERR_CSP_MISSING_ATTR_KEY"},
	{ CSSMERR_CSP_INVALID_ATTR_INIT_VECTOR,"CSSMERR_CSP_INVALID_ATTR_INIT_VECTOR"},
	{ CSSMERR_CSP_MISSING_ATTR_INIT_VECTOR,"CSSMERR_CSP_MISSING_ATTR_INIT_VECTOR"},
	{ CSSMERR_CSP_INVALID_ATTR_SALT,"CSSMERR_CSP_INVALID_ATTR_SALT"},
	{ CSSMERR_CSP_MISSING_ATTR_SALT,"CSSMERR_CSP_MISSING_ATTR_SALT"},
	{ CSSMERR_CSP_INVALID_ATTR_PADDING,"CSSMERR_CSP_INVALID_ATTR_PADDING"},
	{ CSSMERR_CSP_MISSING_ATTR_PADDING,"CSSMERR_CSP_MISSING_ATTR_PADDING"},
	{ CSSMERR_CSP_INVALID_ATTR_RANDOM,"CSSMERR_CSP_INVALID_ATTR_RANDOM"},
	{ CSSMERR_CSP_MISSING_ATTR_RANDOM,"CSSMERR_CSP_MISSING_ATTR_RANDOM"},
	{ CSSMERR_CSP_INVALID_ATTR_SEED,"CSSMERR_CSP_INVALID_ATTR_SEED"},
	{ CSSMERR_CSP_MISSING_ATTR_SEED,"CSSMERR_CSP_MISSING_ATTR_SEED"},
	{ CSSMERR_CSP_INVALID_ATTR_PASSPHRASE,"CSSMERR_CSP_INVALID_ATTR_PASSPHRASE"},
	{ CSSMERR_CSP_MISSING_ATTR_PASSPHRASE,"CSSMERR_CSP_MISSING_ATTR_PASSPHRASE"},
	{ CSSMERR_CSP_INVALID_ATTR_KEY_LENGTH,"CSSMERR_CSP_INVALID_ATTR_KEY_LENGTH"},
	{ CSSMERR_CSP_MISSING_ATTR_KEY_LENGTH,"CSSMERR_CSP_MISSING_ATTR_KEY_LENGTH"},
	{ CSSMERR_CSP_INVALID_ATTR_BLOCK_SIZE,"CSSMERR_CSP_INVALID_ATTR_BLOCK_SIZE"},
	{ CSSMERR_CSP_MISSING_ATTR_BLOCK_SIZE,"CSSMERR_CSP_MISSING_ATTR_BLOCK_SIZE"},
	{ CSSMERR_CSP_INVALID_ATTR_OUTPUT_SIZE,"CSSMERR_CSP_INVALID_ATTR_OUTPUT_SIZE"},
	{ CSSMERR_CSP_MISSING_ATTR_OUTPUT_SIZE,"CSSMERR_CSP_MISSING_ATTR_OUTPUT_SIZE"},
	{ CSSMERR_CSP_INVALID_ATTR_ROUNDS,"CSSMERR_CSP_INVALID_ATTR_ROUNDS"},
	{ CSSMERR_CSP_MISSING_ATTR_ROUNDS,"CSSMERR_CSP_MISSING_ATTR_ROUNDS"},
	{ CSSMERR_CSP_INVALID_ATTR_ALG_PARAMS,"CSSMERR_CSP_INVALID_ATTR_ALG_PARAMS"},
	{ CSSMERR_CSP_MISSING_ATTR_ALG_PARAMS,"CSSMERR_CSP_MISSING_ATTR_ALG_PARAMS"},
	{ CSSMERR_CSP_INVALID_ATTR_LABEL,"CSSMERR_CSP_INVALID_ATTR_LABEL"},
	{ CSSMERR_CSP_MISSING_ATTR_LABEL,"CSSMERR_CSP_MISSING_ATTR_LABEL"},
	{ CSSMERR_CSP_INVALID_ATTR_KEY_TYPE,"CSSMERR_CSP_INVALID_ATTR_KEY_TYPE"},
	{ CSSMERR_CSP_MISSING_ATTR_KEY_TYPE,"CSSMERR_CSP_MISSING_ATTR_KEY_TYPE"},
	{ CSSMERR_CSP_INVALID_ATTR_MODE,"CSSMERR_CSP_INVALID_ATTR_MODE"},
	{ CSSMERR_CSP_MISSING_ATTR_MODE,"CSSMERR_CSP_MISSING_ATTR_MODE"},
	{ CSSMERR_CSP_INVALID_ATTR_EFFECTIVE_BITS,"CSSMERR_CSP_INVALID_ATTR_EFFECTIVE_BITS"},
	{ CSSMERR_CSP_MISSING_ATTR_EFFECTIVE_BITS,"CSSMERR_CSP_MISSING_ATTR_EFFECTIVE_BITS"},
	{ CSSMERR_CSP_INVALID_ATTR_START_DATE,"CSSMERR_CSP_INVALID_ATTR_START_DATE"},
	{ CSSMERR_CSP_MISSING_ATTR_START_DATE,"CSSMERR_CSP_MISSING_ATTR_START_DATE"},
	{ CSSMERR_CSP_INVALID_ATTR_END_DATE,"CSSMERR_CSP_INVALID_ATTR_END_DATE"},
	{ CSSMERR_CSP_MISSING_ATTR_END_DATE,"CSSMERR_CSP_MISSING_ATTR_END_DATE"},
	{ CSSMERR_CSP_INVALID_ATTR_VERSION,"CSSMERR_CSP_INVALID_ATTR_VERSION"},
	{ CSSMERR_CSP_MISSING_ATTR_VERSION,"CSSMERR_CSP_MISSING_ATTR_VERSION"},
	{ CSSMERR_CSP_INVALID_ATTR_PRIME,"CSSMERR_CSP_INVALID_ATTR_PRIME"},
	{ CSSMERR_CSP_MISSING_ATTR_PRIME,"CSSMERR_CSP_MISSING_ATTR_PRIME"},
	{ CSSMERR_CSP_INVALID_ATTR_BASE,"CSSMERR_CSP_INVALID_ATTR_BASE"},
	{ CSSMERR_CSP_MISSING_ATTR_BASE,"CSSMERR_CSP_MISSING_ATTR_BASE"},
	{ CSSMERR_CSP_INVALID_ATTR_SUBPRIME,"CSSMERR_CSP_INVALID_ATTR_SUBPRIME"},
	{ CSSMERR_CSP_MISSING_ATTR_SUBPRIME,"CSSMERR_CSP_MISSING_ATTR_SUBPRIME"},
	{ CSSMERR_CSP_INVALID_ATTR_ITERATION_COUNT,"CSSMERR_CSP_INVALID_ATTR_ITERATION_COUNT"},
	{ CSSMERR_CSP_MISSING_ATTR_ITERATION_COUNT,"CSSMERR_CSP_MISSING_ATTR_ITERATION_COUNT"},
	{ CSSMERR_CSP_INVALID_ATTR_DL_DB_HANDLE,"CSSMERR_CSP_INVALID_ATTR_DL_DB_HANDLE"},
	{ CSSMERR_CSP_MISSING_ATTR_DL_DB_HANDLE,"CSSMERR_CSP_MISSING_ATTR_DL_DB_HANDLE"},
	{ CSSMERR_CSP_INVALID_ATTR_ACCESS_CREDENTIALS,"CSSMERR_CSP_INVALID_ATTR_ACCESS_CREDENTIALS"},
	{ CSSMERR_CSP_MISSING_ATTR_ACCESS_CREDENTIALS,"CSSMERR_CSP_MISSING_ATTR_ACCESS_CREDENTIALS"},
	{ CSSMERR_CSP_INVALID_ATTR_PUBLIC_KEY_FORMAT,"CSSMERR_CSP_INVALID_ATTR_PUBLIC_KEY_FORMAT"},
	{ CSSMERR_CSP_MISSING_ATTR_PUBLIC_KEY_FORMAT,"CSSMERR_CSP_MISSING_ATTR_PUBLIC_KEY_FORMAT"},
	{ CSSMERR_CSP_INVALID_ATTR_PRIVATE_KEY_FORMAT,"CSSMERR_CSP_INVALID_ATTR_PRIVATE_KEY_FORMAT"},
	{ CSSMERR_CSP_MISSING_ATTR_PRIVATE_KEY_FORMAT,"CSSMERR_CSP_MISSING_ATTR_PRIVATE_KEY_FORMAT"},
	{ CSSMERR_CSP_INVALID_ATTR_SYMMETRIC_KEY_FORMAT,"CSSMERR_CSP_INVALID_ATTR_SYMMETRIC_KEY_FORMAT"},
	{ CSSMERR_CSP_MISSING_ATTR_SYMMETRIC_KEY_FORMAT,"CSSMERR_CSP_MISSING_ATTR_SYMMETRIC_KEY_FORMAT"},
	{ CSSMERR_CSP_INVALID_ATTR_WRAPPED_KEY_FORMAT,"CSSMERR_CSP_INVALID_ATTR_WRAPPED_KEY_FORMAT"},
	{ CSSMERR_CSP_MISSING_ATTR_WRAPPED_KEY_FORMAT,"CSSMERR_CSP_MISSING_ATTR_WRAPPED_KEY_FORMAT"},
	{ CSSMERR_CSP_STAGED_OPERATION_IN_PROGRESS,"CSSMERR_CSP_STAGED_OPERATION_IN_PROGRESS"},
	{ CSSMERR_CSP_STAGED_OPERATION_NOT_STARTED,"CSSMERR_CSP_STAGED_OPERATION_NOT_STARTED"},
	{ CSSMERR_CSP_VERIFY_FAILED,"CSSMERR_CSP_VERIFY_FAILED"},
	{ CSSMERR_CSP_INVALID_SIGNATURE,"CSSMERR_CSP_INVALID_SIGNATURE"},
	{ CSSMERR_CSP_QUERY_SIZE_UNKNOWN,"CSSMERR_CSP_QUERY_SIZE_UNKNOWN"},
	{ CSSMERR_CSP_BLOCK_SIZE_MISMATCH,"CSSMERR_CSP_BLOCK_SIZE_MISMATCH"},
	{ CSSMERR_CSP_PRIVATE_KEY_NOT_FOUND,"CSSMERR_CSP_PRIVATE_KEY_NOT_FOUND"},
	{ CSSMERR_CSP_PUBLIC_KEY_INCONSISTENT,"CSSMERR_CSP_PUBLIC_KEY_INCONSISTENT"},
	{ CSSMERR_CSP_DEVICE_VERIFY_FAILED,"CSSMERR_CSP_DEVICE_VERIFY_FAILED"},
	{ CSSMERR_CSP_INVALID_LOGIN_NAME,"CSSMERR_CSP_INVALID_LOGIN_NAME"},
	{ CSSMERR_CSP_ALREADY_LOGGED_IN,"CSSMERR_CSP_ALREADY_LOGGED_IN"},
	{ CSSMERR_CSP_PRIVATE_KEY_ALREADY_EXISTS,"CSSMERR_CSP_PRIVATE_KEY_ALREADY_EXISTS"},
	{ CSSMERR_CSP_KEY_LABEL_ALREADY_EXISTS,"CSSMERR_CSP_KEY_LABEL_ALREADY_EXISTS"},
	{ CSSMERR_CSP_INVALID_DIGEST_ALGORITHM,"CSSMERR_CSP_INVALID_DIGEST_ALGORITHM"},
	{ CSSMERR_CSP_CRYPTO_DATA_CALLBACK_FAILED,"CSSMERR_CSP_CRYPTO_DATA_CALLBACK_FAILED"},
	{ CSSMERR_TP_INTERNAL_ERROR,"CSSMERR_TP_INTERNAL_ERROR"},
	{ CSSMERR_TP_MEMORY_ERROR,"CSSMERR_TP_MEMORY_ERROR"},
	{ CSSMERR_TP_MDS_ERROR,"CSSMERR_TP_MDS_ERROR"},
	{ CSSMERR_TP_INVALID_POINTER,"CSSMERR_TP_INVALID_POINTER"},
	{ CSSMERR_TP_INVALID_INPUT_POINTER,"CSSMERR_TP_INVALID_INPUT_POINTER"},
	{ CSSMERR_TP_INVALID_OUTPUT_POINTER,"CSSMERR_TP_INVALID_OUTPUT_POINTER"},
	{ CSSMERR_TP_FUNCTION_NOT_IMPLEMENTED,"CSSMERR_TP_FUNCTION_NOT_IMPLEMENTED"},
	{ CSSMERR_TP_SELF_CHECK_FAILED,"CSSMERR_TP_SELF_CHECK_FAILED"},
	{ CSSMERR_TP_OS_ACCESS_DENIED,"CSSMERR_TP_OS_ACCESS_DENIED"},
	{ CSSMERR_TP_FUNCTION_FAILED,"CSSMERR_TP_FUNCTION_FAILED"},
	{ CSSMERR_TP_INVALID_CONTEXT_HANDLE,"CSSMERR_TP_INVALID_CONTEXT_HANDLE"},
	{ CSSMERR_TP_INVALID_DATA,"CSSMERR_TP_INVALID_DATA"},
	{ CSSMERR_TP_INVALID_DB_LIST,"CSSMERR_TP_INVALID_DB_LIST"},
	{ CSSMERR_TP_INVALID_CERTGROUP_POINTER,"CSSMERR_TP_INVALID_CERTGROUP_POINTER"},
	{ CSSMERR_TP_INVALID_CERT_POINTER,"CSSMERR_TP_INVALID_CERT_POINTER"},
	{ CSSMERR_TP_INVALID_CRL_POINTER,"CSSMERR_TP_INVALID_CRL_POINTER"},
	{ CSSMERR_TP_INVALID_FIELD_POINTER,"CSSMERR_TP_INVALID_FIELD_POINTER"},
	{ CSSMERR_TP_INVALID_NETWORK_ADDR,"CSSMERR_TP_INVALID_NETWORK_ADDR"},
	{ CSSMERR_TP_CRL_ALREADY_SIGNED,"CSSMERR_TP_CRL_ALREADY_SIGNED"},
	{ CSSMERR_TP_INVALID_NUMBER_OF_FIELDS,"CSSMERR_TP_INVALID_NUMBER_OF_FIELDS"},
	{ CSSMERR_TP_VERIFICATION_FAILURE,"CSSMERR_TP_VERIFICATION_FAILURE"},
	{ CSSMERR_TP_INVALID_DB_HANDLE,"CSSMERR_TP_INVALID_DB_HANDLE"},
	{ CSSMERR_TP_UNKNOWN_FORMAT,"CSSMERR_TP_UNKNOWN_FORMAT"},
	{ CSSMERR_TP_UNKNOWN_TAG,"CSSMERR_TP_UNKNOWN_TAG"},
	{ CSSMERR_TP_INVALID_PASSTHROUGH_ID,"CSSMERR_TP_INVALID_PASSTHROUGH_ID"},
	{ CSSMERR_TP_INVALID_CSP_HANDLE,"CSSMERR_TP_INVALID_CSP_HANDLE"},
	{ CSSMERR_TP_INVALID_DL_HANDLE,"CSSMERR_TP_INVALID_DL_HANDLE"},
	{ CSSMERR_TP_INVALID_CL_HANDLE,"CSSMERR_TP_INVALID_CL_HANDLE"},
	{ CSSMERR_TP_INVALID_DB_LIST_POINTER,"CSSMERR_TP_INVALID_DB_LIST_POINTER"},
	{ CSSMERR_TP_INVALID_CALLERAUTH_CONTEXT_POINTER,"CSSMERR_TP_INVALID_CALLERAUTH_CONTEXT_POINTER"},
	{ CSSMERR_TP_INVALID_IDENTIFIER_POINTER,"CSSMERR_TP_INVALID_IDENTIFIER_POINTER"},
	{ CSSMERR_TP_INVALID_KEYCACHE_HANDLE,"CSSMERR_TP_INVALID_KEYCACHE_HANDLE"},
	{ CSSMERR_TP_INVALID_CERTGROUP,"CSSMERR_TP_INVALID_CERTGROUP"},
	{ CSSMERR_TP_INVALID_CRLGROUP,"CSSMERR_TP_INVALID_CRLGROUP"},
	{ CSSMERR_TP_INVALID_CRLGROUP_POINTER,"CSSMERR_TP_INVALID_CRLGROUP_POINTER"},
	{ CSSMERR_TP_AUTHENTICATION_FAILED,"CSSMERR_TP_AUTHENTICATION_FAILED"},
	{ CSSMERR_TP_CERTGROUP_INCOMPLETE,"CSSMERR_TP_CERTGROUP_INCOMPLETE"},
	{ CSSMERR_TP_CERTIFICATE_CANT_OPERATE,"CSSMERR_TP_CERTIFICATE_CANT_OPERATE"},
	{ CSSMERR_TP_CERT_EXPIRED,"CSSMERR_TP_CERT_EXPIRED"},
	{ CSSMERR_TP_CERT_NOT_VALID_YET,"CSSMERR_TP_CERT_NOT_VALID_YET"},
	{ CSSMERR_TP_CERT_REVOKED,"CSSMERR_TP_CERT_REVOKED"},
	{ CSSMERR_TP_CERT_SUSPENDED,"CSSMERR_TP_CERT_SUSPENDED"},
	{ CSSMERR_TP_INSUFFICIENT_CREDENTIALS,"CSSMERR_TP_INSUFFICIENT_CREDENTIALS"},
	{ CSSMERR_TP_INVALID_ACTION,"CSSMERR_TP_INVALID_ACTION"},
	{ CSSMERR_TP_INVALID_ACTION_DATA,"CSSMERR_TP_INVALID_ACTION_DATA"},
	{ CSSMERR_TP_INVALID_ANCHOR_CERT,"CSSMERR_TP_INVALID_ANCHOR_CERT"},
	{ CSSMERR_TP_INVALID_AUTHORITY,"CSSMERR_TP_INVALID_AUTHORITY"},
	{ CSSMERR_TP_VERIFY_ACTION_FAILED,"CSSMERR_TP_VERIFY_ACTION_FAILED"},
	{ CSSMERR_TP_INVALID_CERTIFICATE,"CSSMERR_TP_INVALID_CERTIFICATE"},
	{ CSSMERR_TP_INVALID_CERT_AUTHORITY,"CSSMERR_TP_INVALID_CERT_AUTHORITY"},
	{ CSSMERR_TP_INVALID_CRL_AUTHORITY,"CSSMERR_TP_INVALID_CRL_AUTHORITY"},
	{ CSSMERR_TP_INVALID_CRL_ENCODING,"CSSMERR_TP_INVALID_CRL_ENCODING"},
	{ CSSMERR_TP_INVALID_CRL_TYPE,"CSSMERR_TP_INVALID_CRL_TYPE"},
	{ CSSMERR_TP_INVALID_CRL,"CSSMERR_TP_INVALID_CRL"},
	{ CSSMERR_TP_INVALID_FORM_TYPE,"CSSMERR_TP_INVALID_FORM_TYPE"},
	{ CSSMERR_TP_INVALID_ID,"CSSMERR_TP_INVALID_ID"},
	{ CSSMERR_TP_INVALID_IDENTIFIER,"CSSMERR_TP_INVALID_IDENTIFIER"},
	{ CSSMERR_TP_INVALID_INDEX,"CSSMERR_TP_INVALID_INDEX"},
	{ CSSMERR_TP_INVALID_NAME,"CSSMERR_TP_INVALID_NAME"},
	{ CSSMERR_TP_INVALID_POLICY_IDENTIFIERS,"CSSMERR_TP_INVALID_POLICY_IDENTIFIERS"},
	{ CSSMERR_TP_INVALID_TIMESTRING,"CSSMERR_TP_INVALID_TIMESTRING"},
	{ CSSMERR_TP_INVALID_REASON,"CSSMERR_TP_INVALID_REASON"},
	{ CSSMERR_TP_INVALID_REQUEST_INPUTS,"CSSMERR_TP_INVALID_REQUEST_INPUTS"},
	{ CSSMERR_TP_INVALID_RESPONSE_VECTOR,"CSSMERR_TP_INVALID_RESPONSE_VECTOR"},
	{ CSSMERR_TP_INVALID_SIGNATURE,"CSSMERR_TP_INVALID_SIGNATURE"},
	{ CSSMERR_TP_INVALID_STOP_ON_POLICY,"CSSMERR_TP_INVALID_STOP_ON_POLICY"},
	{ CSSMERR_TP_INVALID_CALLBACK,"CSSMERR_TP_INVALID_CALLBACK"},
	{ CSSMERR_TP_INVALID_TUPLE,"CSSMERR_TP_INVALID_TUPLE"},
	{ CSSMERR_TP_NOT_SIGNER,"CSSMERR_TP_NOT_SIGNER"},
	{ CSSMERR_TP_NOT_TRUSTED,"CSSMERR_TP_NOT_TRUSTED"},
	{ CSSMERR_TP_NO_DEFAULT_AUTHORITY,"CSSMERR_TP_NO_DEFAULT_AUTHORITY"},
	{ CSSMERR_TP_REJECTED_FORM,"CSSMERR_TP_REJECTED_FORM"},
	{ CSSMERR_TP_REQUEST_LOST,"CSSMERR_TP_REQUEST_LOST"},
	{ CSSMERR_TP_REQUEST_REJECTED,"CSSMERR_TP_REQUEST_REJECTED"},
	{ CSSMERR_TP_UNSUPPORTED_ADDR_TYPE,"CSSMERR_TP_UNSUPPORTED_ADDR_TYPE"},
	{ CSSMERR_TP_UNSUPPORTED_SERVICE,"CSSMERR_TP_UNSUPPORTED_SERVICE"},
	{ CSSMERR_TP_INVALID_TUPLEGROUP_POINTER,"CSSMERR_TP_INVALID_TUPLEGROUP_POINTER"},
	{ CSSMERR_TP_INVALID_TUPLEGROUP,"CSSMERR_TP_INVALID_TUPLEGROUP"},
	{ CSSMERR_AC_INTERNAL_ERROR,"CSSMERR_AC_INTERNAL_ERROR"},
	{ CSSMERR_AC_MEMORY_ERROR,"CSSMERR_AC_MEMORY_ERROR"},
	{ CSSMERR_AC_MDS_ERROR,"CSSMERR_AC_MDS_ERROR"},
	{ CSSMERR_AC_INVALID_POINTER,"CSSMERR_AC_INVALID_POINTER"},
	{ CSSMERR_AC_INVALID_INPUT_POINTER,"CSSMERR_AC_INVALID_INPUT_POINTER"},
	{ CSSMERR_AC_INVALID_OUTPUT_POINTER,"CSSMERR_AC_INVALID_OUTPUT_POINTER"},
	{ CSSMERR_AC_FUNCTION_NOT_IMPLEMENTED,"CSSMERR_AC_FUNCTION_NOT_IMPLEMENTED"},
	{ CSSMERR_AC_SELF_CHECK_FAILED,"CSSMERR_AC_SELF_CHECK_FAILED"},
	{ CSSMERR_AC_OS_ACCESS_DENIED,"CSSMERR_AC_OS_ACCESS_DENIED"},
	{ CSSMERR_AC_FUNCTION_FAILED,"CSSMERR_AC_FUNCTION_FAILED"},
	{ CSSMERR_AC_INVALID_CONTEXT_HANDLE,"CSSMERR_AC_INVALID_CONTEXT_HANDLE"},
	{ CSSMERR_AC_INVALID_DATA,"CSSMERR_AC_INVALID_DATA"},
	{ CSSMERR_AC_INVALID_DB_LIST,"CSSMERR_AC_INVALID_DB_LIST"},
	{ CSSMERR_AC_INVALID_PASSTHROUGH_ID,"CSSMERR_AC_INVALID_PASSTHROUGH_ID"},
	{ CSSMERR_AC_INVALID_DL_HANDLE,"CSSMERR_AC_INVALID_DL_HANDLE"},
	{ CSSMERR_AC_INVALID_CL_HANDLE,"CSSMERR_AC_INVALID_CL_HANDLE"},
	{ CSSMERR_AC_INVALID_TP_HANDLE,"CSSMERR_AC_INVALID_TP_HANDLE"},
	{ CSSMERR_AC_INVALID_DB_HANDLE,"CSSMERR_AC_INVALID_DB_HANDLE"},
	{ CSSMERR_AC_INVALID_DB_LIST_POINTER,"CSSMERR_AC_INVALID_DB_LIST_POINTER"},
	{ CSSMERR_AC_INVALID_BASE_ACLS,"CSSMERR_AC_INVALID_BASE_ACLS"},
	{ CSSMERR_AC_INVALID_TUPLE_CREDENTIALS,"CSSMERR_AC_INVALID_TUPLE_CREDENTIALS"},
	{ CSSMERR_AC_INVALID_ENCODING,"CSSMERR_AC_INVALID_ENCODING"},
	{ CSSMERR_AC_INVALID_VALIDITY_PERIOD,"CSSMERR_AC_INVALID_VALIDITY_PERIOD"},
	{ CSSMERR_AC_INVALID_REQUESTOR,"CSSMERR_AC_INVALID_REQUESTOR"},
	{ CSSMERR_AC_INVALID_REQUEST_DESCRIPTOR,"CSSMERR_AC_INVALID_REQUEST_DESCRIPTOR"},
	{ CSSMERR_CL_INTERNAL_ERROR,"CSSMERR_CL_INTERNAL_ERROR"},
	{ CSSMERR_CL_MEMORY_ERROR,"CSSMERR_CL_MEMORY_ERROR"},
	{ CSSMERR_CL_MDS_ERROR,"CSSMERR_CL_MDS_ERROR"},
	{ CSSMERR_CL_INVALID_POINTER,"CSSMERR_CL_INVALID_POINTER"},
	{ CSSMERR_CL_INVALID_INPUT_POINTER,"CSSMERR_CL_INVALID_INPUT_POINTER"},
	{ CSSMERR_CL_INVALID_OUTPUT_POINTER,"CSSMERR_CL_INVALID_OUTPUT_POINTER"},
	{ CSSMERR_CL_FUNCTION_NOT_IMPLEMENTED,"CSSMERR_CL_FUNCTION_NOT_IMPLEMENTED"},
	{ CSSMERR_CL_SELF_CHECK_FAILED,"CSSMERR_CL_SELF_CHECK_FAILED"},
	{ CSSMERR_CL_OS_ACCESS_DENIED,"CSSMERR_CL_OS_ACCESS_DENIED"},
	{ CSSMERR_CL_FUNCTION_FAILED,"CSSMERR_CL_FUNCTION_FAILED"},
	{ CSSMERR_CL_INVALID_CONTEXT_HANDLE,"CSSMERR_CL_INVALID_CONTEXT_HANDLE"},
	{ CSSMERR_CL_INVALID_CERTGROUP_POINTER,"CSSMERR_CL_INVALID_CERTGROUP_POINTER"},
	{ CSSMERR_CL_INVALID_CERT_POINTER,"CSSMERR_CL_INVALID_CERT_POINTER"},
	{ CSSMERR_CL_INVALID_CRL_POINTER,"CSSMERR_CL_INVALID_CRL_POINTER"},
	{ CSSMERR_CL_INVALID_FIELD_POINTER,"CSSMERR_CL_INVALID_FIELD_POINTER"},
	{ CSSMERR_CL_INVALID_DATA,"CSSMERR_CL_INVALID_DATA"},
	{ CSSMERR_CL_CRL_ALREADY_SIGNED,"CSSMERR_CL_CRL_ALREADY_SIGNED"},
	{ CSSMERR_CL_INVALID_NUMBER_OF_FIELDS,"CSSMERR_CL_INVALID_NUMBER_OF_FIELDS"},
	{ CSSMERR_CL_VERIFICATION_FAILURE,"CSSMERR_CL_VERIFICATION_FAILURE"},
	{ CSSMERR_CL_UNKNOWN_FORMAT,"CSSMERR_CL_UNKNOWN_FORMAT"},
	{ CSSMERR_CL_UNKNOWN_TAG,"CSSMERR_CL_UNKNOWN_TAG"},
	{ CSSMERR_CL_INVALID_PASSTHROUGH_ID,"CSSMERR_CL_INVALID_PASSTHROUGH_ID"},
	{ CSSMERR_CL_INVALID_BUNDLE_POINTER,"CSSMERR_CL_INVALID_BUNDLE_POINTER"},
	{ CSSMERR_CL_INVALID_CACHE_HANDLE,"CSSMERR_CL_INVALID_CACHE_HANDLE"},
	{ CSSMERR_CL_INVALID_RESULTS_HANDLE,"CSSMERR_CL_INVALID_RESULTS_HANDLE"},
	{ CSSMERR_CL_INVALID_BUNDLE_INFO,"CSSMERR_CL_INVALID_BUNDLE_INFO"},
	{ CSSMERR_CL_INVALID_CRL_INDEX,"CSSMERR_CL_INVALID_CRL_INDEX"},
	{ CSSMERR_CL_INVALID_SCOPE,"CSSMERR_CL_INVALID_SCOPE"},
	{ CSSMERR_CL_NO_FIELD_VALUES,"CSSMERR_CL_NO_FIELD_VALUES"},
	{ CSSMERR_CL_SCOPE_NOT_SUPPORTED,"CSSMERR_CL_SCOPE_NOT_SUPPORTED"},
	{ CSSMERR_DL_INTERNAL_ERROR,"CSSMERR_DL_INTERNAL_ERROR"},
	{ CSSMERR_DL_MEMORY_ERROR,"CSSMERR_DL_MEMORY_ERROR"},
	{ CSSMERR_DL_MDS_ERROR,"CSSMERR_DL_MDS_ERROR"},
	{ CSSMERR_DL_INVALID_POINTER,"CSSMERR_DL_INVALID_POINTER"},
	{ CSSMERR_DL_INVALID_INPUT_POINTER,"CSSMERR_DL_INVALID_INPUT_POINTER"},
	{ CSSMERR_DL_INVALID_OUTPUT_POINTER,"CSSMERR_DL_INVALID_OUTPUT_POINTER"},
	{ CSSMERR_DL_FUNCTION_NOT_IMPLEMENTED,"CSSMERR_DL_FUNCTION_NOT_IMPLEMENTED"},
	{ CSSMERR_DL_SELF_CHECK_FAILED,"CSSMERR_DL_SELF_CHECK_FAILED"},
	{ CSSMERR_DL_OS_ACCESS_DENIED,"CSSMERR_DL_OS_ACCESS_DENIED"},
	{ CSSMERR_DL_FUNCTION_FAILED,"CSSMERR_DL_FUNCTION_FAILED"},
	{ CSSMERR_DL_INVALID_CSP_HANDLE,"CSSMERR_DL_INVALID_CSP_HANDLE"},
	{ CSSMERR_DL_INVALID_DL_HANDLE,"CSSMERR_DL_INVALID_DL_HANDLE"},
	{ CSSMERR_DL_INVALID_CL_HANDLE,"CSSMERR_DL_INVALID_CL_HANDLE"},
	{ CSSMERR_DL_INVALID_DB_LIST_POINTER,"CSSMERR_DL_INVALID_DB_LIST_POINTER"},
	{ CSSMERR_DL_OPERATION_AUTH_DENIED,"CSSMERR_DL_OPERATION_AUTH_DENIED"},
	{ CSSMERR_DL_OBJECT_USE_AUTH_DENIED,"CSSMERR_DL_OBJECT_USE_AUTH_DENIED"},
	{ CSSMERR_DL_OBJECT_MANIP_AUTH_DENIED,"CSSMERR_DL_OBJECT_MANIP_AUTH_DENIED"},
	{ CSSMERR_DL_OBJECT_ACL_NOT_SUPPORTED,"CSSMERR_DL_OBJECT_ACL_NOT_SUPPORTED"},
	{ CSSMERR_DL_OBJECT_ACL_REQUIRED,"CSSMERR_DL_OBJECT_ACL_REQUIRED"},
	{ CSSMERR_DL_INVALID_ACCESS_CREDENTIALS,"CSSMERR_DL_INVALID_ACCESS_CREDENTIALS"},
	{ CSSMERR_DL_INVALID_ACL_BASE_CERTS,"CSSMERR_DL_INVALID_ACL_BASE_CERTS"},
	{ CSSMERR_DL_ACL_BASE_CERTS_NOT_SUPPORTED,"CSSMERR_DL_ACL_BASE_CERTS_NOT_SUPPORTED"},
	{ CSSMERR_DL_INVALID_SAMPLE_VALUE,"CSSMERR_DL_INVALID_SAMPLE_VALUE"},
	{ CSSMERR_DL_SAMPLE_VALUE_NOT_SUPPORTED,"CSSMERR_DL_SAMPLE_VALUE_NOT_SUPPORTED"},
	{ CSSMERR_DL_INVALID_ACL_SUBJECT_VALUE,"CSSMERR_DL_INVALID_ACL_SUBJECT_VALUE"},
	{ CSSMERR_DL_ACL_SUBJECT_TYPE_NOT_SUPPORTED,"CSSMERR_DL_ACL_SUBJECT_TYPE_NOT_SUPPORTED"},
	{ CSSMERR_DL_INVALID_ACL_CHALLENGE_CALLBACK,"CSSMERR_DL_INVALID_ACL_CHALLENGE_CALLBACK"},
	{ CSSMERR_DL_ACL_CHALLENGE_CALLBACK_FAILED,"CSSMERR_DL_ACL_CHALLENGE_CALLBACK_FAILED"},
	{ CSSMERR_DL_INVALID_ACL_ENTRY_TAG,"CSSMERR_DL_INVALID_ACL_ENTRY_TAG"},
	{ CSSMERR_DL_ACL_ENTRY_TAG_NOT_FOUND,"CSSMERR_DL_ACL_ENTRY_TAG_NOT_FOUND"},
	{ CSSMERR_DL_INVALID_ACL_EDIT_MODE,"CSSMERR_DL_INVALID_ACL_EDIT_MODE"},
	{ CSSMERR_DL_ACL_CHANGE_FAILED,"CSSMERR_DL_ACL_CHANGE_FAILED"},
	{ CSSMERR_DL_INVALID_NEW_ACL_ENTRY,"CSSMERR_DL_INVALID_NEW_ACL_ENTRY"},
	{ CSSMERR_DL_INVALID_NEW_ACL_OWNER,"CSSMERR_DL_INVALID_NEW_ACL_OWNER"},
	{ CSSMERR_DL_ACL_DELETE_FAILED,"CSSMERR_DL_ACL_DELETE_FAILED"},
	{ CSSMERR_DL_ACL_REPLACE_FAILED,"CSSMERR_DL_ACL_REPLACE_FAILED"},
	{ CSSMERR_DL_ACL_ADD_FAILED,"CSSMERR_DL_ACL_ADD_FAILED"},
	{ CSSMERR_DL_INVALID_DB_HANDLE,"CSSMERR_DL_INVALID_DB_HANDLE"},
	{ CSSMERR_DL_INVALID_PASSTHROUGH_ID,"CSSMERR_DL_INVALID_PASSTHROUGH_ID"},
	{ CSSMERR_DL_INVALID_NETWORK_ADDR,"CSSMERR_DL_INVALID_NETWORK_ADDR"},
	{ CSSMERR_DL_DATABASE_CORRUPT,"CSSMERR_DL_DATABASE_CORRUPT"},
	{ CSSMERR_DL_INVALID_RECORD_INDEX,"CSSMERR_DL_INVALID_RECORD_INDEX"},
	{ CSSMERR_DL_INVALID_RECORDTYPE,"CSSMERR_DL_INVALID_RECORDTYPE"},
	{ CSSMERR_DL_INVALID_FIELD_NAME,"CSSMERR_DL_INVALID_FIELD_NAME"},
	{ CSSMERR_DL_UNSUPPORTED_FIELD_FORMAT,"CSSMERR_DL_UNSUPPORTED_FIELD_FORMAT"},
	{ CSSMERR_DL_UNSUPPORTED_INDEX_INFO,"CSSMERR_DL_UNSUPPORTED_INDEX_INFO"},
	{ CSSMERR_DL_UNSUPPORTED_LOCALITY,"CSSMERR_DL_UNSUPPORTED_LOCALITY"},
	{ CSSMERR_DL_UNSUPPORTED_NUM_ATTRIBUTES,"CSSMERR_DL_UNSUPPORTED_NUM_ATTRIBUTES"},
	{ CSSMERR_DL_UNSUPPORTED_NUM_INDEXES,"CSSMERR_DL_UNSUPPORTED_NUM_INDEXES"},
	{ CSSMERR_DL_UNSUPPORTED_NUM_RECORDTYPES,"CSSMERR_DL_UNSUPPORTED_NUM_RECORDTYPES"},
	{ CSSMERR_DL_UNSUPPORTED_RECORDTYPE,"CSSMERR_DL_UNSUPPORTED_RECORDTYPE"},
	{ CSSMERR_DL_FIELD_SPECIFIED_MULTIPLE,"CSSMERR_DL_FIELD_SPECIFIED_MULTIPLE"},
	{ CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT,"CSSMERR_DL_INCOMPATIBLE_FIELD_FORMAT"},
	{ CSSMERR_DL_INVALID_PARSING_MODULE,"CSSMERR_DL_INVALID_PARSING_MODULE"},
	{ CSSMERR_DL_INVALID_DB_NAME,"CSSMERR_DL_INVALID_DB_NAME"},
	{ CSSMERR_DL_DATASTORE_DOESNOT_EXIST,"CSSMERR_DL_DATASTORE_DOESNOT_EXIST"},
	{ CSSMERR_DL_DATASTORE_ALREADY_EXISTS,"CSSMERR_DL_DATASTORE_ALREADY_EXISTS"},
	{ CSSMERR_DL_DB_LOCKED,"CSSMERR_DL_DB_LOCKED"},
	{ CSSMERR_DL_DATASTORE_IS_OPEN,"CSSMERR_DL_DATASTORE_IS_OPEN"},
	{ CSSMERR_DL_RECORD_NOT_FOUND,"CSSMERR_DL_RECORD_NOT_FOUND"},
	{ CSSMERR_DL_MISSING_VALUE,"CSSMERR_DL_MISSING_VALUE"},
	{ CSSMERR_DL_UNSUPPORTED_QUERY,"CSSMERR_DL_UNSUPPORTED_QUERY"},
	{ CSSMERR_DL_UNSUPPORTED_QUERY_LIMITS,"CSSMERR_DL_UNSUPPORTED_QUERY_LIMITS"},
	{ CSSMERR_DL_UNSUPPORTED_NUM_SELECTION_PREDS,"CSSMERR_DL_UNSUPPORTED_NUM_SELECTION_PREDS"},
	{ CSSMERR_DL_UNSUPPORTED_OPERATOR,"CSSMERR_DL_UNSUPPORTED_OPERATOR"},
	{ CSSMERR_DL_INVALID_RESULTS_HANDLE,"CSSMERR_DL_INVALID_RESULTS_HANDLE"},
	{ CSSMERR_DL_INVALID_DB_LOCATION,"CSSMERR_DL_INVALID_DB_LOCATION"},
	{ CSSMERR_DL_INVALID_ACCESS_REQUEST,"CSSMERR_DL_INVALID_ACCESS_REQUEST"},
	{ CSSMERR_DL_INVALID_INDEX_INFO,"CSSMERR_DL_INVALID_INDEX_INFO"},
	{ CSSMERR_DL_INVALID_SELECTION_TAG,"CSSMERR_DL_INVALID_SELECTION_TAG"},
	{ CSSMERR_DL_INVALID_NEW_OWNER,"CSSMERR_DL_INVALID_NEW_OWNER"},
	{ CSSMERR_DL_INVALID_RECORD_UID,"CSSMERR_DL_INVALID_RECORD_UID"},
	{ CSSMERR_DL_INVALID_UNIQUE_INDEX_DATA,"CSSMERR_DL_INVALID_UNIQUE_INDEX_DATA"},
	{ CSSMERR_DL_INVALID_MODIFY_MODE,"CSSMERR_DL_INVALID_MODIFY_MODE"},
	{ CSSMERR_DL_INVALID_OPEN_PARAMETERS,"CSSMERR_DL_INVALID_OPEN_PARAMETERS"},
	{ CSSMERR_DL_RECORD_MODIFIED,"CSSMERR_DL_RECORD_MODIFIED"},
	{ CSSMERR_DL_ENDOFDATA,"CSSMERR_DL_ENDOFDATA"},
	{ CSSMERR_DL_INVALID_QUERY,"CSSMERR_DL_INVALID_QUERY"},
	{ CSSMERR_DL_INVALID_VALUE,"CSSMERR_DL_INVALID_VALUE"},
	{ CSSMERR_DL_MULTIPLE_VALUES_UNSUPPORTED,"CSSMERR_DL_MULTIPLE_VALUES_UNSUPPORTED"},
	{ CSSMERR_DL_STALE_UNIQUE_RECORD,"CSSMERR_DL_STALE_UNIQUE_RECORD"},
	/* Error codes from cssmapple.h */
	{ CSSMERR_CSSM_NO_USER_INTERACTION,"CSSMERR_CSSM_NO_USER_INTERACTION"},
	{ CSSMERR_AC_NO_USER_INTERACTION,"CSSMERR_AC_NO_USER_INTERACTION"},
	{ CSSMERR_CSP_NO_USER_INTERACTION,"CSSMERR_CSP_NO_USER_INTERACTION"},
	{ CSSMERR_CL_NO_USER_INTERACTION,"CSSMERR_CL_NO_USER_INTERACTION"},
	{ CSSMERR_DL_NO_USER_INTERACTION,"CSSMERR_DL_NO_USER_INTERACTION"},
	{ CSSMERR_TP_NO_USER_INTERACTION,"CSSMERR_TP_NO_USER_INTERACTION"},
	{ CSSMERR_CSSM_USER_CANCELED,"CSSMERR_CSSM_USER_CANCELED"},
	{ CSSMERR_AC_USER_CANCELED,"CSSMERR_AC_USER_CANCELED"},
	{ CSSMERR_CSP_USER_CANCELED,"CSSMERR_CSP_USER_CANCELED"},
	{ CSSMERR_CL_USER_CANCELED,"CSSMERR_CL_USER_CANCELED"},
	{ CSSMERR_DL_USER_CANCELED,"CSSMERR_DL_USER_CANCELED"},
	{ CSSMERR_TP_USER_CANCELED,"CSSMERR_TP_USER_CANCELED"},
	{ CSSMERR_CSSM_SERVICE_NOT_AVAILABLE,"CSSMERR_CSSM_SERVICE_NOT_AVAILABLE"},
	{ CSSMERR_AC_SERVICE_NOT_AVAILABLE,"CSSMERR_AC_SERVICE_NOT_AVAILABLE"},
	{ CSSMERR_CSP_SERVICE_NOT_AVAILABLE,"CSSMERR_CSP_SERVICE_NOT_AVAILABLE"},
	{ CSSMERR_CL_SERVICE_NOT_AVAILABLE,"CSSMERR_CL_SERVICE_NOT_AVAILABLE"},
	{ CSSMERR_DL_SERVICE_NOT_AVAILABLE,"CSSMERR_DL_SERVICE_NOT_AVAILABLE"},
	{ CSSMERR_TP_SERVICE_NOT_AVAILABLE,"CSSMERR_TP_SERVICE_NOT_AVAILABLE"},
	{ CSSMERR_CSSM_INSUFFICIENT_CLIENT_IDENTIFICATION,"CSSMERR_CSSM_INSUFFICIENT_CLIENT_IDENTIFICATION"},
	{ CSSMERR_AC_INSUFFICIENT_CLIENT_IDENTIFICATION,"CSSMERR_AC_INSUFFICIENT_CLIENT_IDENTIFICATION"},
	{ CSSMERR_CSP_INSUFFICIENT_CLIENT_IDENTIFICATION,"CSSMERR_CSP_INSUFFICIENT_CLIENT_IDENTIFICATION"},
	{ CSSMERR_CL_INSUFFICIENT_CLIENT_IDENTIFICATION,"CSSMERR_CL_INSUFFICIENT_CLIENT_IDENTIFICATION"},
	{ CSSMERR_DL_INSUFFICIENT_CLIENT_IDENTIFICATION,"CSSMERR_DL_INSUFFICIENT_CLIENT_IDENTIFICATION"},
	{ CSSMERR_TP_INSUFFICIENT_CLIENT_IDENTIFICATION,"CSSMERR_TP_INSUFFICIENT_CLIENT_IDENTIFICATION"},
	{ CSSMERR_CSSM_DEVICE_RESET,"CSSMERR_CSSM_DEVICE_RESET"},
	{ CSSMERR_AC_DEVICE_RESET,"CSSMERR_AC_DEVICE_RESET"},
	{ CSSMERR_CSP_DEVICE_RESET,"CSSMERR_CSP_DEVICE_RESET"},
	{ CSSMERR_CL_DEVICE_RESET,"CSSMERR_CL_DEVICE_RESET"},
	{ CSSMERR_DL_DEVICE_RESET,"CSSMERR_DL_DEVICE_RESET"},
	{ CSSMERR_TP_DEVICE_RESET,"CSSMERR_TP_DEVICE_RESET"},
	{ CSSMERR_CSSM_DEVICE_FAILED,"CSSMERR_CSSM_DEVICE_FAILED"},
	{ CSSMERR_AC_DEVICE_FAILED,"CSSMERR_AC_DEVICE_FAILED"},
	{ CSSMERR_CSP_DEVICE_FAILED,"CSSMERR_CSP_DEVICE_FAILED"},
	{ CSSMERR_CL_DEVICE_FAILED,"CSSMERR_CL_DEVICE_FAILED"},
	{ CSSMERR_DL_DEVICE_FAILED,"CSSMERR_DL_DEVICE_FAILED"},
	{ CSSMERR_TP_DEVICE_FAILED,"CSSMERR_TP_DEVICE_FAILED"},
	{ CSSMERR_CSP_APPLE_ADD_APPLICATION_ACL_SUBJECT,"CSSMERR_CSP_APPLE_ADD_APPLICATION_ACL_SUBJECT"},
	{ CSSMERR_CSP_APPLE_PUBLIC_KEY_INCOMPLETE,"CSSMERR_CSP_APPLE_PUBLIC_KEY_INCOMPLETE"},
	{ CSSMERR_CSP_APPLE_SIGNATURE_MISMATCH,"CSSMERR_CSP_APPLE_SIGNATURE_MISMATCH"},
	{ CSSMERR_CSP_APPLE_INVALID_KEY_START_DATE,"CSSMERR_CSP_APPLE_INVALID_KEY_START_DATE"},
	{ CSSMERR_CSP_APPLE_INVALID_KEY_END_DATE,"CSSMERR_CSP_APPLE_INVALID_KEY_END_DATE"},
	{ CSSMERR_CSPDL_APPLE_DL_CONVERSION_ERROR,"CSSMERR_CSPDL_APPLE_DL_CONVERSION_ERROR"},
	{ CSSMERR_CSP_APPLE_SSLv2_ROLLBACK,"CSSMERR_CSP_APPLE_SSLv2_ROLLBACK"},
	{ CSSMERR_APPLEDL_INVALID_OPEN_PARAMETERS,"CSSMERR_APPLEDL_INVALID_OPEN_PARAMETERS"},
	{ CSSMERR_APPLEDL_DISK_FULL,"CSSMERR_APPLEDL_DISK_FULL"},
	{ CSSMERR_APPLEDL_QUOTA_EXCEEDED,"CSSMERR_APPLEDL_QUOTA_EXCEEDED"},
	{ CSSMERR_APPLEDL_FILE_TOO_BIG,"CSSMERR_APPLEDL_FILE_TOO_BIG"},
	{ CSSMERR_APPLEDL_INVALID_DATABASE_BLOB,"CSSMERR_APPLEDL_INVALID_DATABASE_BLOB"},
	{ CSSMERR_APPLEDL_INVALID_KEY_BLOB,"CSSMERR_APPLEDL_INVALID_KEY_BLOB"},
	{ CSSMERR_APPLEDL_INCOMPATIBLE_DATABASE_BLOB,"CSSMERR_APPLEDL_INCOMPATIBLE_DATABASE_BLOB"},
	{ CSSMERR_APPLEDL_INCOMPATIBLE_KEY_BLOB,"CSSMERR_APPLEDL_INCOMPATIBLE_KEY_BLOB"},
	{ CSSMERR_APPLETP_HOSTNAME_MISMATCH,"CSSMERR_APPLETP_HOSTNAME_MISMATCH"},
	{ CSSMERR_APPLETP_UNKNOWN_CRITICAL_EXTEN,"CSSMERR_APPLETP_UNKNOWN_CRITICAL_EXTEN"},
	{ CSSMERR_APPLETP_NO_BASIC_CONSTRAINTS,"CSSMERR_APPLETP_NO_BASIC_CONSTRAINTS"},
	{ CSSMERR_APPLETP_INVALID_CA,"CSSMERR_APPLETP_INVALID_CA"},
	{ CSSMERR_APPLETP_INVALID_AUTHORITY_ID,"CSSMERR_APPLETP_INVALID_AUTHORITY_ID"},
	{ CSSMERR_APPLETP_INVALID_SUBJECT_ID,"CSSMERR_APPLETP_INVALID_SUBJECT_ID"},
	{ CSSMERR_APPLETP_INVALID_KEY_USAGE,"CSSMERR_APPLETP_INVALID_KEY_USAGE"},
	{ CSSMERR_APPLETP_INVALID_EXTENDED_KEY_USAGE,"CSSMERR_APPLETP_INVALID_EXTENDED_KEY_USAGE"},
	{ CSSMERR_APPLETP_INVALID_ID_LINKAGE,"CSSMERR_APPLETP_INVALID_ID_LINKAGE"},
	{ CSSMERR_APPLETP_PATH_LEN_CONSTRAINT,"CSSMERR_APPLETP_PATH_LEN_CONSTRAINT"},
	{ CSSMERR_APPLETP_INVALID_ROOT,"CSSMERR_APPLETP_INVALID_ROOT"},
	{ CSSMERR_APPLETP_CRL_EXPIRED,"CSSMERR_APPLETP_CRL_EXPIRED"},
	{ CSSMERR_APPLETP_CRL_NOT_VALID_YET,"CSSMERR_APPLETP_CRL_NOT_VALID_YET"},
	{ CSSMERR_APPLETP_CRL_NOT_FOUND,"CSSMERR_APPLETP_CRL_NOT_FOUND"},
	{ CSSMERR_APPLETP_CRL_SERVER_DOWN,"CSSMERR_APPLETP_CRL_SERVER_DOWN"},
	{ CSSMERR_APPLETP_CRL_BAD_URI,"CSSMERR_APPLETP_CRL_BAD_URI"},
	{ CSSMERR_APPLETP_UNKNOWN_CERT_EXTEN,"CSSMERR_APPLETP_UNKNOWN_CERT_EXTEN"},
	{ CSSMERR_APPLETP_UNKNOWN_CRL_EXTEN,"CSSMERR_APPLETP_UNKNOWN_CRL_EXTEN"},
	{ CSSMERR_APPLETP_CRL_NOT_TRUSTED,"CSSMERR_APPLETP_CRL_NOT_TRUSTED"},
	{ CSSMERR_APPLETP_CRL_INVALID_ANCHOR_CERT,"CSSMERR_APPLETP_CRL_INVALID_ANCHOR_CERT"},
	{ CSSMERR_APPLETP_CRL_POLICY_FAIL,"CSSMERR_APPLETP_CRL_POLICY_FAIL"},
	{ CSSMERR_APPLETP_IDP_FAIL,"CSSMERR_APPLETP_IDP_FAIL"},
	{ CSSMERR_APPLETP_CERT_NOT_FOUND_FROM_ISSUER,"CSSMERR_APPLETP_CERT_NOT_FOUND_FROM_ISSUER"},
	{ CSSMERR_APPLETP_BAD_CERT_FROM_ISSUER,"CSSMERR_APPLETP_BAD_CERT_FROM_ISSUER"},
	{ CSSMERR_APPLETP_SMIME_EMAIL_ADDRS_NOT_FOUND,"CSSMERR_APPLETP_SMIME_EMAIL_ADDRS_NOT_FOUND"},
	{ CSSMERR_APPLETP_SMIME_BAD_EXT_KEY_USE,"CSSMERR_APPLETP_SMIME_BAD_EXT_KEY_USE"},
	{ CSSMERR_APPLETP_SMIME_BAD_KEY_USE,"CSSMERR_APPLETP_SMIME_BAD_KEY_USE"},
	{ CSSMERR_APPLETP_SMIME_KEYUSAGE_NOT_CRITICAL,"CSSMERR_APPLETP_SMIME_KEYUSAGE_NOT_CRITICAL"},
	{ CSSMERR_APPLETP_SMIME_NO_EMAIL_ADDRS,"CSSMERR_APPLETP_SMIME_NO_EMAIL_ADDRS"},
	{ CSSMERR_APPLETP_SMIME_SUBJ_ALT_NAME_NOT_CRIT,"CSSMERR_APPLETP_SMIME_SUBJ_ALT_NAME_NOT_CRIT"},
	{ CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE,"CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE"},
	{ CSSMERR_APPLETP_OCSP_BAD_RESPONSE,"CSSMERR_APPLETP_OCSP_BAD_RESPONSE"},
	{ CSSMERR_APPLETP_OCSP_BAD_REQUEST,"CSSMERR_APPLETP_OCSP_BAD_REQUEST"},
	{ CSSMERR_APPLETP_OCSP_UNAVAILABLE,"CSSMERR_APPLETP_OCSP_UNAVAILABLE"},
	{ CSSMERR_APPLETP_OCSP_STATUS_UNRECOGNIZED,"CSSMERR_APPLETP_OCSP_STATUS_UNRECOGNIZED"},
	{ CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK,"CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK"},
	{ CSSMERR_APPLETP_NETWORK_FAILURE,"CSSMERR_APPLETP_NETWORK_FAILURE"},
	{ CSSMERR_APPLETP_OCSP_NOT_TRUSTED,"CSSMERR_APPLETP_OCSP_NOT_TRUSTED"},
	{ CSSMERR_APPLETP_OCSP_INVALID_ANCHOR_CERT,"CSSMERR_APPLETP_OCSP_INVALID_ANCHOR_CERT"},
	{ CSSMERR_APPLETP_OCSP_SIG_ERROR,"CSSMERR_APPLETP_OCSP_SIG_ERROR"},
	{ CSSMERR_APPLETP_OCSP_NO_SIGNER,"CSSMERR_APPLETP_OCSP_NO_SIGNER"},
	{ CSSMERR_APPLETP_OCSP_RESP_MALFORMED_REQ,"CSSMERR_APPLETP_OCSP_RESP_MALFORMED_REQ"},
	{ CSSMERR_APPLETP_OCSP_RESP_INTERNAL_ERR,"CSSMERR_APPLETP_OCSP_RESP_INTERNAL_ERR"},
	{ CSSMERR_APPLETP_OCSP_RESP_TRY_LATER,"CSSMERR_APPLETP_OCSP_RESP_TRY_LATER"},
	{ CSSMERR_APPLETP_OCSP_RESP_SIG_REQUIRED,"CSSMERR_APPLETP_OCSP_RESP_SIG_REQUIRED"},
	{ CSSMERR_APPLETP_OCSP_RESP_UNAUTHORIZED,"CSSMERR_APPLETP_OCSP_RESP_UNAUTHORIZED"},
	{ CSSMERR_APPLETP_OCSP_NONCE_MISMATCH,"CSSMERR_APPLETP_OCSP_NONCE_MISMATCH"},
	{ CSSMERR_APPLETP_CS_BAD_CERT_CHAIN_LENGTH,"CSSMERR_APPLETP_CS_BAD_CERT_CHAIN_LENGTH"},
	{ CSSMERR_APPLETP_CS_NO_BASIC_CONSTRAINTS,"CSSMERR_APPLETP_CS_NO_BASIC_CONSTRAINTS"},
	{ CSSMERR_APPLETP_CS_BAD_PATH_LENGTH,"CSSMERR_APPLETP_CS_BAD_PATH_LENGTH"},
	{ CSSMERR_APPLETP_CS_NO_EXTENDED_KEY_USAGE,"CSSMERR_APPLETP_CS_NO_EXTENDED_KEY_USAGE"},
	{ CSSMERR_APPLETP_CODE_SIGN_DEVELOPMENT,"CSSMERR_APPLETP_CODE_SIGN_DEVELOPMENT"},
	{ CSSMERR_APPLETP_RS_BAD_CERT_CHAIN_LENGTH,"CSSMERR_APPLETP_RS_BAD_CERT_CHAIN_LENGTH"},
	{ CSSMERR_APPLETP_RS_BAD_EXTENDED_KEY_USAGE,"CSSMERR_APPLETP_RS_BAD_EXTENDED_KEY_USAGE"},
	{ CSSMERR_APPLETP_TRUST_SETTING_DENY,"CSSMERR_APPLETP_TRUST_SETTING_DENY"},
	{ CSSMERR_APPLETP_INVALID_EMPTY_SUBJECT,"CSSMERR_APPLETP_INVALID_EMPTY_SUBJECT"},
	{ CSSMERR_APPLETP_UNKNOWN_QUAL_CERT_STATEMENT,"CSSMERR_APPLETP_UNKNOWN_QUAL_CERT_STATEMENT"},
	{ CSSMERR_APPLE_DOTMAC_REQ_QUEUED,"CSSMERR_APPLE_DOTMAC_REQ_QUEUED"},
	{ CSSMERR_APPLE_DOTMAC_REQ_REDIRECT,"CSSMERR_APPLE_DOTMAC_REQ_REDIRECT"},
	{ CSSMERR_APPLE_DOTMAC_REQ_SERVER_ERR,"CSSMERR_APPLE_DOTMAC_REQ_SERVER_ERR"},
	{ CSSMERR_APPLE_DOTMAC_REQ_SERVER_PARAM,"CSSMERR_APPLE_DOTMAC_REQ_SERVER_PARAM"},
	{ CSSMERR_APPLE_DOTMAC_REQ_SERVER_AUTH,"CSSMERR_APPLE_DOTMAC_REQ_SERVER_AUTH"},
	{ CSSMERR_APPLE_DOTMAC_REQ_SERVER_UNIMPL,"CSSMERR_APPLE_DOTMAC_REQ_SERVER_UNIMPL"},
	{ CSSMERR_APPLE_DOTMAC_REQ_SERVER_NOT_AVAIL,"CSSMERR_APPLE_DOTMAC_REQ_SERVER_NOT_AVAIL"},
	{ CSSMERR_APPLE_DOTMAC_REQ_SERVER_ALREADY_EXIST,"CSSMERR_APPLE_DOTMAC_REQ_SERVER_ALREADY_EXIST"},
	{ CSSMERR_APPLE_DOTMAC_REQ_SERVER_SERVICE_ERROR,"CSSMERR_APPLE_DOTMAC_REQ_SERVER_SERVICE_ERROR"},
	{ CSSMERR_APPLE_DOTMAC_REQ_IS_PENDING,"CSSMERR_APPLE_DOTMAC_REQ_IS_PENDING"},
	{ CSSMERR_APPLE_DOTMAC_NO_REQ_PENDING,"CSSMERR_APPLE_DOTMAC_NO_REQ_PENDING"},
	{0, NULL}
};
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted LocalTests/utilLib/fileIo.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "fileIo.h"

int cspWriteFile(
	const char			*fileName,
	const unsigned char	*bytes,
	unsigned			numBytes)
{
	int		rtn;
	int 	fd;
	
	fd = open(fileName, O_RDWR | O_CREAT | O_TRUNC, 0600);
	if(fd <= 0) {
		return errno;
	}
	rtn = lseek(fd, 0, SEEK_SET);
	if(rtn < 0) {
		return errno;
	}
	rtn = write(fd, bytes, (size_t)numBytes);
	if(rtn != (int)numBytes) {
		if(rtn >= 0) {
			printf("writeFile: short write\n");
		}
		rtn = EIO;
	}
	else {
		rtn = 0;
	}
	close(fd);
	return rtn;
}
	
/*
 * Read entire file. 
 */
int cspReadFile(
	const char		*fileName,
	unsigned char	**bytes,		// mallocd and returned
	unsigned		*numBytes)		// returned
{
	int ourRtn = 0;
	int fd;
	char *buf;
	char *thisBuf;
	struct stat	sb;
	unsigned size;
	size_t toMove;
	ssize_t thisMoved;
	int irtn;
	off_t lrtn = 0;
	
	*numBytes = 0;
	*bytes = NULL;
	fd = open(fileName, O_RDONLY, 0);
	if(fd <= 0) {
		perror("open");
		return errno;
	}
	irtn = fstat(fd, &sb);
	if(irtn) {
		ourRtn = errno;
		if(ourRtn == 0) {
			fprintf(stderr, "***Bogus zero error on fstat\n");
			ourRtn = -1;
		}
		else {
			perror("fstat");
		}
		goto errOut;
	}
	size = sb.st_size;
	buf = thisBuf = (char *)malloc(size);
	if(buf == NULL) {
		ourRtn = ENOMEM;
		goto errOut;
	}
	lrtn = lseek(fd, 0, SEEK_SET);
	if(lrtn < 0) {
		ourRtn = errno;
		if(ourRtn == 0) {
			fprintf(stderr, "***Bogus zero error on lseek\n");
			ourRtn = -1;
		}
		else {
			perror("lseek");
		}
		goto errOut;
	}
	toMove = size;
	
	/*
	 * On ppc this read ALWAYS returns the entire file. On i386, not so. 
	 */
	do {
		thisMoved = read(fd, thisBuf, toMove);
		if(thisMoved == 0) {
			/* reading empty file: done */
			break;
		}
		else if(thisMoved < 0) {
			ourRtn = errno;
			perror("read");
			break;
		}
		size_t uThisMoved = (size_t)thisMoved;
		if(uThisMoved != toMove) {
			fprintf(stderr, "===Short read: asked for %ld, got %lu\n", 
				toMove, uThisMoved);
		}
		toMove  -= thisMoved;
		thisBuf += thisMoved;
	} while(toMove);
	
	if(ourRtn == 0) {
		*bytes = (unsigned char *)buf;
		*numBytes = size;
	}
errOut:
	close(fd);
	return ourRtn;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































Deleted LocalTests/utilLib/fileIo.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * Read entire file. 
 */
#ifdef __cplusplus
extern "C" {
#endif

int cspReadFile(
	const char			*fileName,
	unsigned char		**bytes,		// mallocd and returned
	unsigned			*numBytes);		// returned

int cspWriteFile(
	const char			*fileName,
	const unsigned char	*bytes,
	unsigned			numBytes);

#ifdef __cplusplus
}
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































Deleted LocalTests/utilLib/nssAppUtils.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 * Copyright (c) 2003 Apple Computer, Inc. All Rights Reserved.
 * 
 * The contents of this file constitute Original Code as defined in and are
 * subject to the Apple Public Source License Version 1.2 (the 'License').
 * You may not use this file except in compliance with the License. Please 
 * obtain a copy of the License at http://www.apple.com/publicsource and 
 * read it before using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER 
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, 
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. 
 * Please see the License for the specific language governing rights and 
 * limitations under the License.
 */
/*
 * nssAppUtils.cpp
 */
 
#include "nssAppUtils.h"
#include "common.h"
#include "cspwrap.h"
#include <Security/SecAsn1Coder.h>
#include <Security/osKeyTemplates.h>	
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>

/*
 * Create pubKeyPartial as copy of pubKey without the DSA params.
 * Returned partial key is RAW. Incoming key can be raw or ref.
 */
CSSM_RETURN extractDsaPartial(
	CSSM_CSP_HANDLE cspHand,
	const CSSM_KEY *pubKey, 
	CSSM_KEY_PTR pubKeyPartial)
{
	const CSSM_KEY *thePubKey = pubKey;
	CSSM_KEY rawPubKey;
	CSSM_RETURN crtn;
	
	if(pubKey->KeyHeader.BlobType == CSSM_KEYBLOB_REFERENCE) {
		/* first get this in raw form */
		crtn = cspRefKeyToRaw(cspHand, pubKey, &rawPubKey);
		if(crtn) {
			return crtn;
		}
		thePubKey = &rawPubKey;
	}
	
	/* decode raw public key */
	NSS_DSAPublicKeyX509 nssPub;
	SecAsn1CoderRef coder;
	
	OSStatus ortn = SecAsn1CoderCreate(&coder);
	if(ortn) {
		cssmPerror("SecAsn1CoderCreate", ortn);
		return ortn;
	}
	memset(&nssPub, 0, sizeof(nssPub));
	if(SecAsn1DecodeData(coder, &thePubKey->KeyData, kSecAsn1DSAPublicKeyX509Template,
			&nssPub)) {
		printf("***Error decoding DSA public key. Aborting.\n");
		return 1;
	}
	
	/* zero out the params and reencode */
	nssPub.dsaAlg.params = NULL;
	CSSM_DATA newKey = {0, NULL};
	if(SecAsn1EncodeItem(coder, &nssPub, kSecAsn1DSAPublicKeyX509Template,
			&newKey)) {
		printf("***Error reencoding DSA pub key\n");
		return 1;
	}
	
	/* copy - newKey is in coder space */
	*pubKeyPartial = *thePubKey;
	appCopyCssmData(&newKey, &pubKeyPartial->KeyData);

	if(pubKey->KeyHeader.BlobType == CSSM_KEYBLOB_REFERENCE) {
		/* free the KeyData mallocd by cspRefKeyToRaw */
		CSSM_FREE(thePubKey->KeyData.Data);
		pubKeyPartial->KeyHeader.BlobType = CSSM_KEYBLOB_RAW;
	}
	pubKeyPartial->KeyHeader.KeyAttr |= CSSM_KEYATTR_PARTIAL;
	SecAsn1CoderRelease(coder);
	return CSSM_OK;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































Deleted LocalTests/utilLib/nssAppUtils.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
 * Copyright (c) 2003 Apple Computer, Inc. All Rights Reserved.
 * 
 * The contents of this file constitute Original Code as defined in and are
 * subject to the Apple Public Source License Version 1.2 (the 'License').
 * You may not use this file except in compliance with the License. Please 
 * obtain a copy of the License at http://www.apple.com/publicsource and 
 * read it before using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER 
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, 
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. 
 * Please see the License for the specific language governing rights and 
 * limitations under the License.
 */
/*
 * nssAppUtils.h
 */
 
#ifndef	_NSS_APP_UTILS_H_
#define _NSS_APP_UTILS_H_

#include <Security/cssmtype.h>

#ifdef __cplusplus
extern "C" {
#endif

CSSM_RETURN extractDsaPartial(
	CSSM_CSP_HANDLE cspHand,
	const CSSM_KEY *pubKey, 
	CSSM_KEY_PTR pubKeyPartial);

#ifdef __cplusplus
}
#endif

#endif	/* _NSS_APP_UTILS_H_ */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































Deleted LocalTests/utilLib/rijndael-alg-ref.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/* rijndael-alg-ref.c   v2.0   August '99
 * Reference ANSI C code
 * authors: Paulo Barreto
 *          Vincent Rijmen
 */

#include <stdio.h>
#include <stdlib.h>

#include "rijndael-alg-ref.h"

#define SC	((BC - 4) >> 1)

#include "boxes-ref.h"

static const word8 shifts[3][4][2] = {
 { { 0, 0 },
   { 1, 3 },
   { 2, 2 },
   { 3, 1 }
 },
 { { 0, 0 },
   { 1, 5 },
   { 2, 4 },
   { 3, 3 }
 },
 { { 0, 0 },
   { 1, 7 },
   { 3, 5 },
   { 4, 4 }
 }
}; 


static word8 mul(word8 a, word8 b) {
   /* multiply two elements of GF(2^m)
    * needed for MixColumn and InvMixColumn
    */
	if (a && b) return Alogtable[(Logtable[a] + Logtable[b])%255];
	else return 0;
}

static void KeyAddition(word8 a[4][MAXBC], word8 rk[4][MAXBC], word8 BC) {
	/* Exor corresponding text input and round key input bytes
	 */
	int i, j;
	
	for(i = 0; i < 4; i++)
   		for(j = 0; j < BC; j++) a[i][j] ^= rk[i][j];
}

static void ShiftRow(word8 a[4][MAXBC], word8 d, word8 BC) {
	/* Row 0 remains unchanged
	 * The other three rows are shifted a variable amount
	 */
	word8 tmp[MAXBC];
	int i, j;
	
	for(i = 1; i < 4; i++) {
		for(j = 0; j < BC; j++) tmp[j] = a[i][(j + shifts[SC][i][d]) % BC];
		for(j = 0; j < BC; j++) a[i][j] = tmp[j];
	}
}

static void Substitution(word8 a[4][MAXBC], const word8 box[256], word8 BC) {
	/* Replace every byte of the input by the byte at that place
	 * in the nonlinear S-box
	 */
	int i, j;
	
	for(i = 0; i < 4; i++)
		for(j = 0; j < BC; j++) a[i][j] = box[a[i][j]] ;
}
   
static void MixColumn(word8 a[4][MAXBC], word8 BC) {
        /* Mix the four bytes of every column in a linear way
	 */
	word8 b[4][MAXBC];
	int i, j;
		
	for(j = 0; j < BC; j++)
		for(i = 0; i < 4; i++)
			b[i][j] = mul(2,a[i][j])
				^ mul(3,a[(i + 1) % 4][j])
				^ a[(i + 2) % 4][j]
				^ a[(i + 3) % 4][j];
	for(i = 0; i < 4; i++)
		for(j = 0; j < BC; j++) a[i][j] = b[i][j];
}

static void InvMixColumn(word8 a[4][MAXBC], word8 BC) {
        /* Mix the four bytes of every column in a linear way
	 * This is the opposite operation of Mixcolumn
	 */
	word8 b[4][MAXBC];
	int i, j;
	
	for(j = 0; j < BC; j++)
	for(i = 0; i < 4; i++)             
		b[i][j] = mul(0xe,a[i][j])
			^ mul(0xb,a[(i + 1) % 4][j])                 
			^ mul(0xd,a[(i + 2) % 4][j])
			^ mul(0x9,a[(i + 3) % 4][j]);                        
	for(i = 0; i < 4; i++)
		for(j = 0; j < BC; j++) a[i][j] = b[i][j];
}

int _rijndaelKeySched (word8 k[4][MAXKC], int keyBits, int blockBits, word8 W[MAXROUNDS+1][4][MAXBC]) {
	/* Calculate the necessary round keys
	 * The number of calculations depends on keyBits and blockBits
	 */
	int KC, BC, ROUNDS;
	int i, j, t, rconpointer = 0;
	word8 tk[4][MAXKC];   

	switch (keyBits) {
	case 128: KC = 4; break;
	case 192: KC = 6; break;
	case 256: KC = 8; break;
	default : return (-1);
	}

	switch (blockBits) {
	case 128: BC = 4; break;
	case 192: BC = 6; break;
	case 256: BC = 8; break;
	default : return (-2);
	}

	switch (keyBits >= blockBits ? keyBits : blockBits) {
	case 128: ROUNDS = 10; break;
	case 192: ROUNDS = 12; break;
	case 256: ROUNDS = 14; break;
	default : return (-3); /* this cannot happen */
	}

	
	for(j = 0; j < KC; j++)
		for(i = 0; i < 4; i++)
			tk[i][j] = k[i][j];
	t = 0;
	/* copy values into round key array */
	for(j = 0; (j < KC) && (t < (ROUNDS+1)*BC); j++, t++)
		for(i = 0; i < 4; i++) W[t / BC][i][t % BC] = tk[i][j];
		
	while (t < (ROUNDS+1)*BC) { /* while not enough round key material calculated */
		/* calculate new values */
		for(i = 0; i < 4; i++)
			tk[i][0] ^= S[tk[(i+1)%4][KC-1]];
		tk[0][0] ^= rcon[rconpointer++];

		if (KC != 8)
			for(j = 1; j < KC; j++)
				for(i = 0; i < 4; i++) tk[i][j] ^= tk[i][j-1];
		else {
			for(j = 1; j < KC/2; j++)
				for(i = 0; i < 4; i++) tk[i][j] ^= tk[i][j-1];
			for(i = 0; i < 4; i++) tk[i][KC/2] ^= S[tk[i][KC/2 - 1]];
			for(j = KC/2 + 1; j < KC; j++)
				for(i = 0; i < 4; i++) tk[i][j] ^= tk[i][j-1];
	}
	/* copy values into round key array */
	for(j = 0; (j < KC) && (t < (ROUNDS+1)*BC); j++, t++)
		for(i = 0; i < 4; i++) W[t / BC][i][t % BC] = tk[i][j];
	}		

	return 0;
}
      
int _rijndaelEncrypt (word8 a[4][MAXBC], int keyBits, int blockBits, word8 rk[MAXROUNDS+1][4][MAXBC])
{
	/* Encryption of one block. 
	 */
	int r, BC, ROUNDS;

	switch (blockBits) {
	case 128: BC = 4; break;
	case 192: BC = 6; break;
	case 256: BC = 8; break;
	default : return (-2);
	}

	switch (keyBits >= blockBits ? keyBits : blockBits) {
	case 128: ROUNDS = 10; break;
	case 192: ROUNDS = 12; break;
	case 256: ROUNDS = 14; break;
	default : return (-3); /* this cannot happen */
	}

	/* begin with a key addition
	 */
	KeyAddition(a,rk[0],BC); 

        /* ROUNDS-1 ordinary rounds
	 */
	for(r = 1; r < ROUNDS; r++) {
		Substitution(a,S,BC);
		ShiftRow(a,0,BC);
		MixColumn(a,BC);
		KeyAddition(a,rk[r],BC);
	}
	
	/* Last round is special: there is no MixColumn
	 */
	Substitution(a,S,BC);
	ShiftRow(a,0,BC);
	KeyAddition(a,rk[ROUNDS],BC);

	return 0;
}   


#ifndef	__APPLE__

int rijndaelEncryptRound (word8 a[4][MAXBC], int keyBits, int blockBits, 
		word8 rk[MAXROUNDS+1][4][MAXBC], int rounds)
/* Encrypt only a certain number of rounds.
 * Only used in the Intermediate Value Known Answer Test.
 */
{
	int r, BC, ROUNDS;

	switch (blockBits) {
	case 128: BC = 4; break;
	case 192: BC = 6; break;
	case 256: BC = 8; break;
	default : return (-2);
	}

	switch (keyBits >= blockBits ? keyBits : blockBits) {
	case 128: ROUNDS = 10; break;
	case 192: ROUNDS = 12; break;
	case 256: ROUNDS = 14; break;
	default : return (-3); /* this cannot happen */
	}

	/* make number of rounds sane */
	if (rounds > ROUNDS) rounds = ROUNDS;

	/* begin with a key addition
	 */
	KeyAddition(a,rk[0],BC);
        
	/* at most ROUNDS-1 ordinary rounds
	 */
	for(r = 1; (r <= rounds) && (r < ROUNDS); r++) {
		Substitution(a,S,BC);
		ShiftRow(a,0,BC);
		MixColumn(a,BC);
		KeyAddition(a,rk[r],BC);
	}
	
	/* if necessary, do the last, special, round: 
	 */
	if (rounds == ROUNDS) {
		Substitution(a,S,BC);
		ShiftRow(a,0,BC);
		KeyAddition(a,rk[ROUNDS],BC);
	}

	return 0;
}   
#endif	/* __APPLE__ */

int _rijndaelDecrypt (word8 a[4][MAXBC], int keyBits, int blockBits, word8 rk[MAXROUNDS+1][4][MAXBC])
{
	int r, BC, ROUNDS;
	
	switch (blockBits) {
	case 128: BC = 4; break;
	case 192: BC = 6; break;
	case 256: BC = 8; break;
	default : return (-2);
	}

	switch (keyBits >= blockBits ? keyBits : blockBits) {
	case 128: ROUNDS = 10; break;
	case 192: ROUNDS = 12; break;
	case 256: ROUNDS = 14; break;
	default : return (-3); /* this cannot happen */
	}

	/* To decrypt: apply the inverse operations of the encrypt routine,
	 *             in opposite order
	 * 
	 * (KeyAddition is an involution: it 's equal to its inverse)
	 * (the inverse of Substitution with table S is Substitution with the inverse table of S)
	 * (the inverse of Shiftrow is Shiftrow over a suitable distance)
	 */

        /* First the special round:
	 *   without InvMixColumn
	 *   with extra KeyAddition
	 */
	KeyAddition(a,rk[ROUNDS],BC);
	Substitution(a,Si,BC);
	ShiftRow(a,1,BC);              
	
	/* ROUNDS-1 ordinary rounds
	 */
	for(r = ROUNDS-1; r > 0; r--) {
		KeyAddition(a,rk[r],BC);
		InvMixColumn(a,BC);      
		Substitution(a,Si,BC);
		ShiftRow(a,1,BC);                
	}
	
	/* End with the extra key addition
	 */
	
	KeyAddition(a,rk[0],BC);    

	return 0;
}

#ifndef	__APPLE__

int rijndaelDecryptRound (word8 a[4][MAXBC], int keyBits, int blockBits, 
	word8 rk[MAXROUNDS+1][4][MAXBC], int rounds)
/* Decrypt only a certain number of rounds.
 * Only used in the Intermediate Value Known Answer Test.
 * Operations rearranged such that the intermediate values
 * of decryption correspond with the intermediate values
 * of encryption.
 */
{
	int r, BC, ROUNDS;
	
	switch (blockBits) {
	case 128: BC = 4; break;
	case 192: BC = 6; break;
	case 256: BC = 8; break;
	default : return (-2);
	}

	switch (keyBits >= blockBits ? keyBits : blockBits) {
	case 128: ROUNDS = 10; break;
	case 192: ROUNDS = 12; break;
	case 256: ROUNDS = 14; break;
	default : return (-3); /* this cannot happen */
	}


	/* make number of rounds sane */
	if (rounds > ROUNDS) rounds = ROUNDS;

        /* First the special round:
	 *   without InvMixColumn
	 *   with extra KeyAddition
	 */
	KeyAddition(a,rk[ROUNDS],BC);
	Substitution(a,Si,BC);
	ShiftRow(a,1,BC);              
	
	/* ROUNDS-1 ordinary rounds
	 */
	for(r = ROUNDS-1; r > rounds; r--) {
		KeyAddition(a,rk[r],BC);
		InvMixColumn(a,BC);      
		Substitution(a,Si,BC);
		ShiftRow(a,1,BC);                
	}
	
	if (rounds == 0) {
		/* End with the extra key addition
		 */	
		KeyAddition(a,rk[0],BC);
	}    

	return 0;
}

#endif	/* __APPLE__ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































































































































































































































































































































































































































































































Deleted LocalTests/utilLib/rijndael-alg-ref.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* rijndael-alg-ref.h   v2.0   August '99
 * Reference ANSI C code
 * authors: Paulo Barreto
 *          Vincent Rijmen
 */
#ifndef __RIJNDAEL_ALG_H
#define __RIJNDAEL_ALG_H

#ifdef	__APPLE__
#define MIN_AES_KEY_BITS		128
#define MID_AES_KEY_BITS		192
#define MAX_AES_KEY_BITS		256
#define MAX_AES_KEY_BYTES		(MAX_AES_KEY_BITS / 8)

#define MIN_AES_BLOCK_BITS		128
#define MID_AES_BLOCK_BITS		192
#define MAX_AES_BLOCK_BITS		256
#define MIN_AES_BLOCK_BYTES		(MIN_AES_BLOCK_BITS / 8)

#endif
#define MAXBC				(MAX_AES_BLOCK_BITS/32)
#define MAXKC				(MAX_AES_KEY_BITS/32)
#define MAXROUNDS			14

#ifdef	__cplusplus
extern "C" {
#endif

typedef unsigned char		word8;	
typedef unsigned short		word16;	
typedef unsigned long		word32;


int _rijndaelKeySched (word8 k[4][MAXKC], int keyBits, int blockBits, 
		word8 rk[MAXROUNDS+1][4][MAXBC]);
int _rijndaelEncrypt (word8 a[4][MAXBC], int keyBits, int blockBits, 
		word8 rk[MAXROUNDS+1][4][MAXBC]);
#ifndef	__APPLE__
int rijndaelEncryptRound (word8 a[4][MAXBC], int keyBits, int blockBits, 
		word8 rk[MAXROUNDS+1][4][MAXBC], int rounds);
#endif
int _rijndaelDecrypt (word8 a[4][MAXBC], int keyBits, int blockBits, 
		word8 rk[MAXROUNDS+1][4][MAXBC]);
#ifndef	__APPLE__
int rijndaelDecryptRound (word8 a[4][MAXBC], int keyBits, int blockBits, 
		word8 rk[MAXROUNDS+1][4][MAXBC], int rounds);
#endif

#ifdef	__cplusplus
}
#endif

#endif /* __RIJNDAEL_ALG_H */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































Deleted LocalTests/utilLib/rijndaelApi.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/* 
 * rijndaelApi.c  -  AES API layer
 *
 * Based on rijndael-api-ref.h v2.0 written by Paulo Barreto
 * and Vincent Rijmen
 */
#include <stdlib.h>
#include <string.h>

#include "rijndael-alg-ref.h"
#include "rijndaelApi.h"

#define CBC_DEBUG		0
#if 	CBC_DEBUG
static void dumpChainBuf(cipherInstance *cipher, char *op)
{
	int t,j;
	int columns = cipher->blockLen / 32;

	printf("chainBuf %s: ", op);
	for (j = 0; j < columns; j++) {
		for(t = 0; t < 4; t++) {
			printf("%02x ", cipher->chainBlock[t][j]);
		}
	}
	printf("\n");
}
#else
#define dumpChainBuf(c, o)
#endif

int _makeKey(	keyInstance *key, 
	BYTE direction, 
	int keyLen, 		// in BITS
	int blockLen,		// in BITS
	BYTE *keyMaterial)
{
	word8 k[4][MAXKC];
	unsigned keyBytes;
	unsigned  i;

	if (key == NULL) {
		return BAD_KEY_INSTANCE;
	}
	if(keyMaterial == NULL) {
		return BAD_KEY_MAT;
	}
	if ((direction == DIR_ENCRYPT) || (direction == DIR_DECRYPT)) {
		key->direction = direction;
	} else {
		return BAD_KEY_DIR;
	}

	if ((keyLen == 128) || (keyLen == 192) || (keyLen == 256)) { 
		key->keyLen = keyLen;
	} else {
		return BAD_KEY_MAT;
	}
	key->blockLen = blockLen;

	/* initialize key schedule: */ 
	keyBytes = keyLen / 8;
 	for(i = 0; i < keyBytes; i++) {
		k[i % 4][i / 4] = keyMaterial[i]; 
	}	
	_rijndaelKeySched (k, key->keyLen, key->blockLen, key->keySched);	
	memset(k, 0, 4 * MAXKC);
	return TRUE;
}

int _cipherInit(	cipherInstance *cipher, 
	BYTE mode, 
	int blockLen,		// in BITS
	BYTE *IV)
{
	int t, j;
	int columns = blockLen / 32;
	
	/* MODE_CFB1 not supported */
	if ((mode == MODE_ECB) || (mode == MODE_CBC)) {
		cipher->mode = mode;
	} else {
		return BAD_CIPHER_MODE;
	}
	cipher->blockLen = blockLen;
	
	if (IV != NULL) {
		/* Save IV in rectangular block format */
		for (j = 0; j < columns; j++) {
			for(t = 0; t < 4; t++) {
				/* parse initial value into rectangular array */
				cipher->chainBlock[t][j] = IV[t+4*j];
			}
		}
	}
	dumpChainBuf(cipher, "init  ");	
	return TRUE;
}


int _blockEncrypt(cipherInstance *cipher,
	keyInstance *key, BYTE *input, int inputLen, BYTE *outBuffer)
{
	int i, j, t, numBlocks;
	unsigned blockSizeBytes;
	int columns;
	
	/* check parameter consistency: */
	if (key == NULL ||
		key->direction != DIR_ENCRYPT ||
		(key->keyLen != 128 && key->keyLen != 192 && key->keyLen != 256)) {
		return BAD_KEY_MAT;
	}
	if (cipher == NULL ||
		(cipher->mode != MODE_ECB && cipher->mode != MODE_CBC) ||
		(cipher->blockLen != 128 && cipher->blockLen != 192 && cipher->blockLen != 256)) {
			return BAD_CIPHER_STATE;
	}

	numBlocks = inputLen/cipher->blockLen;
	blockSizeBytes = cipher->blockLen / 8;
	columns = cipher->blockLen / 32;
	
	switch (cipher->mode) {
	case MODE_ECB: 
		for (i = 0; i < numBlocks; i++) {
			for (j = 0; j < columns; j++) {
				for(t = 0; t < 4; t++)
				/* parse input stream into rectangular array */
					cipher->chainBlock[t][j] = input[4*j+t];
			}
			_rijndaelEncrypt (cipher->chainBlock, key->keyLen, cipher->blockLen, key->keySched);
			for (j = 0; j < columns; j++) {
				/* parse rectangular array into output ciphertext bytes */
				for(t = 0; t < 4; t++)
					outBuffer[4*j+t] = (BYTE) cipher->chainBlock[t][j];
			}
			input += blockSizeBytes;
			outBuffer += blockSizeBytes;
			dumpChainBuf(cipher, "encr ECB");
		}
		break;
		
	case MODE_CBC:
		for (i = 0; i < numBlocks; i++) {
			for (j = 0; j < columns; j++) {
				for(t = 0; t < 4; t++)
				/* parse input stream into rectangular array and exor with 
				   IV or the previous ciphertext */
					cipher->chainBlock[t][j] ^= input[4*j+t];
			}
			_rijndaelEncrypt (cipher->chainBlock, key->keyLen, cipher->blockLen, key->keySched);
			for (j = 0; j < columns; j++) {
				/* parse rectangular array into output ciphertext bytes */
				for(t = 0; t < 4; t++)
					outBuffer[4*j+t] = (BYTE) cipher->chainBlock[t][j];
			}
			/* Hey! This code was broken for multi-block ops! */
			input += blockSizeBytes;
			outBuffer += blockSizeBytes;
			dumpChainBuf(cipher, "encr CBC");
		}
		break;
	
	default: return BAD_CIPHER_STATE;
	}
	
	return numBlocks*cipher->blockLen;
}

int _blockDecrypt(cipherInstance *cipher,
	keyInstance *key, BYTE *input, int inputLen, BYTE *outBuffer)
{
	int i, j, t, numBlocks;
	word8 block[4][MAXBC];		// working memory: encrypt/decrypt in place here
	unsigned blockSizeBytes;
	word8 cblock[4][MAXBC];		// saved ciphertext
	int columns;

	if (cipher == NULL ||
		key == NULL ||
		key->direction == DIR_ENCRYPT ||
		cipher->blockLen != key->blockLen) {
		return BAD_CIPHER_STATE;
	}

	/* check parameter consistency: */
	if (key == NULL ||
		key->direction != DIR_DECRYPT ||
		(key->keyLen != 128 && key->keyLen != 192 && key->keyLen != 256)) {
		return BAD_KEY_MAT;
	}
	if (cipher == NULL ||
		(cipher->mode != MODE_ECB && cipher->mode != MODE_CBC) ||
		(cipher->blockLen != 128 && cipher->blockLen != 192 && cipher->blockLen != 256)) {
		return BAD_CIPHER_STATE;
	}
	
	numBlocks = inputLen/cipher->blockLen;
	blockSizeBytes = cipher->blockLen / 8;
	columns = cipher->blockLen / 32;
	
	switch (cipher->mode) {
	case MODE_ECB: 
		for (i = 0; i < numBlocks; i++) {
			for (j = 0; j < columns; j++) {
				for(t = 0; t < 4; t++)
				/* parse input stream into rectangular array */
					block[t][j] = input[4*j+t];
			}
			_rijndaelDecrypt (block, key->keyLen, cipher->blockLen, key->keySched);
			for (j = 0; j < columns; j++) {
				/* parse rectangular array into output ciphertext bytes */
				for(t = 0; t < 4; t++)
					outBuffer[4*j+t] = (BYTE) block[t][j];
			}
			input += blockSizeBytes;
			outBuffer += blockSizeBytes;
			dumpChainBuf(cipher, "decr ECB");
		}
		break;
		
	case MODE_CBC:
		for (i = 0; i < numBlocks; i++) {
			for (j = 0; j < columns; j++) {
				for(t = 0; t < 4; t++)
				/* parse input stream into rectangular array */
					block[t][j] = input[4*j+t];
			}
			
			/* save a copoy of incoming ciphertext for later chain; decrypt */
			memmove(cblock, block, 4*MAXBC);
			_rijndaelDecrypt (block, key->keyLen, cipher->blockLen, key->keySched);
			
			/* 
			 * exor with last ciphertext --> plaintext out
			 * save this ciphertext in lastBlock
			 * FIXME - we can optimize this by avoiding the copy into 
			 * lastBlock on all but last time thru...
			 */
			for (j = 0; j < columns; j++) {
				for(t = 0; t < 4; t++) {
					outBuffer[4*j+t] = (block[t][j] ^ cipher->chainBlock[t][j]);
				}
			}
			memmove(cipher->chainBlock, cblock, 4 * MAXBC);
			input += blockSizeBytes;
			outBuffer += blockSizeBytes;
			dumpChainBuf(cipher, "decr CBC");
		}
		break;
	
	default: return BAD_CIPHER_STATE;
	}
	memset(block, 0, 4 * MAXBC);
	memset(cblock, 0, 4 * MAXBC);
	return numBlocks*cipher->blockLen;
}

/*
 * Apple addenda 3/28/2001: simplified single-block encrypt/decrypt.
 * Used when chaining and padding is done in elsewhere. 
 */
#define AES_CONSISTENCY_CHECK		1

int _rijndaelBlockEncrypt(
	cipherInstance *cipher,
	keyInstance *key, 
	BYTE *input, 
	BYTE *outBuffer)
{
	int j, t;
	unsigned blockSizeBytes;
	int columns;
	
	#if		AES_CONSISTENCY_CHECK
	/* check parameter consistency: */
	if (key == NULL ||
		key->direction != DIR_ENCRYPT ||
		(key->keyLen != 128 && key->keyLen != 192 && key->keyLen != 256)) {
		return BAD_KEY_MAT;
	}
	if (cipher == NULL ||
		(cipher->mode != MODE_ECB && cipher->mode != MODE_CBC) ||
		(cipher->blockLen != 128 && cipher->blockLen != 192 && cipher->blockLen != 256)) {
			return BAD_CIPHER_STATE;
	}
	#endif	/* AES_CONSISTENCY_CHECK */
	
	blockSizeBytes = cipher->blockLen >> 3;	/* was / 8; should just save in cipher */
	columns = cipher->blockLen >> 5;		/* was / 32; ditto */
	
	for (j = 0; j < columns; j++) {
		for(t = 0; t < 4; t++)
		/* parse input stream into rectangular array */
			cipher->chainBlock[t][j] = input[4*j+t];
	}
	_rijndaelEncrypt (cipher->chainBlock, key->keyLen, cipher->blockLen, 
		key->keySched);
	for (j = 0; j < columns; j++) {
		/* parse rectangular array into output ciphertext bytes */
		for(t = 0; t < 4; t++)
			outBuffer[4*j+t] = (BYTE) cipher->chainBlock[t][j];
	}
	return cipher->blockLen;
}

int _rijndaelBlockDecrypt(
	cipherInstance *cipher,
	keyInstance *key, 
	BYTE *input, 
	BYTE *outBuffer)
{
	int j, t;
	word8 block[4][MAXBC];		// working memory: encrypt/decrypt in place here
	unsigned blockSizeBytes;
	int columns;

	#if		AES_CONSISTENCY_CHECK
	if (cipher == NULL ||
		key == NULL ||
		key->direction == DIR_ENCRYPT ||
		cipher->blockLen != key->blockLen) {
		return BAD_CIPHER_STATE;
	}

	/* check parameter consistency: */
	if (key == NULL ||
		key->direction != DIR_DECRYPT ||
		(key->keyLen != 128 && key->keyLen != 192 && key->keyLen != 256)) {
		return BAD_KEY_MAT;
	}
	if (cipher == NULL ||
		(cipher->mode != MODE_ECB && cipher->mode != MODE_CBC) ||
		(cipher->blockLen != 128 && cipher->blockLen != 192 && cipher->blockLen != 256)) {
		return BAD_CIPHER_STATE;
	}
	#endif		/* AES_CONSISTENCY_CHECK */
	
	blockSizeBytes = cipher->blockLen >> 3;	/* was / 8; should just save in cipher */
	columns = cipher->blockLen >> 5;		/* was / 32; ditto */
	
	for (j = 0; j < columns; j++) {
		for(t = 0; t < 4; t++)
		/* parse input stream into rectangular array */
			block[t][j] = input[4*j+t];
	}
	_rijndaelDecrypt (block, key->keyLen, cipher->blockLen, key->keySched);
	for (j = 0; j < columns; j++) {
		/* parse rectangular array into output ciphertext bytes */
		for(t = 0; t < 4; t++)
			outBuffer[4*j+t] = (BYTE) block[t][j];
	}
			
	return cipher->blockLen;
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































































































































































































































































































































































































































































Deleted LocalTests/utilLib/rijndaelApi.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* 
 * rijndaelApi.h  -  AES API layer
 *
 * Based on rijndael-api-ref.h v2.0 written by Paulo Barreto
 * and Vincent Rijmen
 */

#ifndef	_RIJNDAEL_API_REF_H_
#define _RIJNDAEL_API_REF_H_

#include <stdio.h>
#include "rijndael-alg-ref.h"

#ifdef	__cplusplus
extern "C" {
#endif

#define     DIR_ENCRYPT     0    /*  Are we encrpyting?  */
#define     DIR_DECRYPT     1    /*  Are we decrpyting?  */
#define     MODE_ECB        1    /*  Are we ciphering in ECB mode?   */
#define     MODE_CBC        2    /*  Are we ciphering in CBC mode?   */

#define     TRUE            1
#define     FALSE           0

/*  Error Codes  */
#define     BAD_KEY_DIR        -1  /*  Key direction is invalid, e.g.,
									   unknown value */
#define     BAD_KEY_MAT        -2  /*  Key material not of correct 
									   length */
#define     BAD_KEY_INSTANCE   -3  /*  Key passed is not valid  */
#define     BAD_CIPHER_MODE    -4  /*  Params struct passed to 
									   cipherInit invalid */
#define     BAD_CIPHER_STATE   -5  /*  Cipher in wrong state (e.g., not 
									   initialized) */
#define     BAD_CIPHER_INSTANCE   -7 

#define     MAX_AES_KEY_SIZE	(MAX_AES_KEY_BITS / 8)
#define 	MAX_AES_BLOCK_SIZE	(MAX_AES_BLOCK_BITS / 8)
#define     MAX_AES_IV_SIZE		MAX_AES_BLOCK_SIZE
	
typedef    unsigned char    BYTE;

/*  The structure for key information */
typedef struct {
      BYTE  direction;	/* Key used for encrypting or decrypting? */
      int   keyLen;		/* Length of the key in bits */
      int   blockLen;   /* Length of block in bits */
      word8 keySched[MAXROUNDS+1][4][MAXBC];	/* key schedule		*/
      } keyInstance;

/*  The structure for cipher information */
typedef struct {
      BYTE  mode;           /* MODE_ECB, MODE_CBC, or MODE_CFB1 */
	  word8 chainBlock[4][MAXBC];      
	  int   blockLen;    	/* block length in bits */
      } cipherInstance;


int _makeKey(
	keyInstance *key, 
	BYTE direction, 
	int keyLen, 		// in BITS
	int blockLen,		// in BITS
	BYTE *keyMaterial);

int _cipherInit(
	cipherInstance *cipher, 
	BYTE mode, 
	int blockLen,		// in BITS
	BYTE *IV);

int _blockEncrypt(
	cipherInstance *cipher, 
	keyInstance *key, 
	BYTE *input, 
	int inputLen, 		// in BITS
	BYTE *outBuffer);

int _blockDecrypt(
	cipherInstance *cipher, 
	keyInstance *key, 
	BYTE *input,
	int inputLen, 		// in BITS
	BYTE *outBuffer);

/*
 * Apple addenda 3/28/2001: simplified single-block encrypt/decrypt.
 * Used when chaining and padding is done in elsewhere. 
 */
int _rijndaelBlockEncrypt(
	cipherInstance *cipher,
	keyInstance *key, 
	BYTE *input, 
	BYTE *outBuffer);
int _rijndaelBlockDecrypt(
	cipherInstance *cipher,
	keyInstance *key, 
	BYTE *input, 
	BYTE *outBuffer);
	
#ifdef	__cplusplus
}
#endif	// cplusplus

#endif	// RIJNDAEL_API_REF


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































Deleted LocalTests/utilLib/ssleayUtils.cpp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
 * ssleayUtils.c - common routines for CDSA/openssl compatibility testing
 */
 
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <openssl/blowfish.h>
#include <openssl/cast.h>
#include <openssl/evp.h>
#include "ssleayUtils.h"
#include <Security/cssmerr.h>
#include "common.h"

/*
 * Caller sees EAY_KEY, we see a pointer to this.
 */
typedef struct {
	CSSM_ALGORITHMS alg;
	union {
		BF_KEY				bf;		// blowfish
		CAST_KEY			cast;
	} key;
} EayKeyPriv;

/*
 * Create a symmetric key.
 */
CSSM_RETURN  eayGenSymKey(
	CSSM_ALGORITHMS alg,
	CSSM_BOOL		forEncr,
	const CSSM_DATA	*keyData,
	EAY_KEY			*key)			// RETURNED
{
	EayKeyPriv *ekp = (EayKeyPriv *)malloc(sizeof(EayKeyPriv));
	memset(ekp, 0, sizeof(*ekp));
	switch(alg) {
		case CSSM_ALGID_BLOWFISH:
			BF_set_key(&ekp->key.bf, keyData->Length, keyData->Data);
			break;
		case CSSM_ALGID_CAST:		// cast128 only
			CAST_set_key(&ekp->key.cast, keyData->Length, keyData->Data);
			break;
		default:
			printf("***eayGenSymKey: bad alg\n");
			return -1;
	}
	ekp->alg = alg;
	*key = (EAY_KEY)ekp;
	return CSSM_OK;
}

/*
 * Free a key created in eayGenSymKey
 */
CSSM_RETURN eayFreeKey(
	EAY_KEY			key)
{
	memset(key, 0, sizeof(EayKeyPriv));
	free(key);
	return CSSM_OK;
}

/*
 * encrypt/decrypt
 */
CSSM_RETURN eayEncryptDecrypt(
	EAY_KEY				key,
	CSSM_BOOL			forEncrypt,
	CSSM_ALGORITHMS		encrAlg,
	CSSM_ENCRYPT_MODE	mode,				// CSSM_ALGMODE_CBC ONLY!
	const CSSM_DATA		*iv,				//Êoptional per mode
	const CSSM_DATA		*inData,
	CSSM_DATA_PTR		outData)			// CSSM_MALLOCd and RETURNED
{
	EayKeyPriv *ekp = (EayKeyPriv *)key;
	if((mode != CSSM_ALGMODE_CBC_IV8) && (mode != CSSM_ALGMODE_ECB)) {
		printf("***eayEncryptDecrypt only does CBC_IV8, ECB\n");
		return -1;
	}
	
	bool cbc = (mode == CSSM_ALGMODE_ECB) ? false : true;
	
	outData->Data = (uint8 *)CSSM_MALLOC(inData->Length);
	outData->Length = inData->Length;
	
	/* BF_cbc_encrypt actually writes to IV */
	CSSM_DATA ivc = {0, NULL};
	if(cbc) {
		ivc.Data = (uint8 *)malloc(iv->Length);
		ivc.Length = iv->Length;
		memmove(ivc.Data, iv->Data, ivc.Length);
	}
	switch(encrAlg) {
		case CSSM_ALGID_BLOWFISH:
			if(cbc) {
				BF_cbc_encrypt(inData->Data,
					outData->Data,
					inData->Length,
					&ekp->key.bf,
					ivc.Data,
					forEncrypt ? BF_ENCRYPT : BF_DECRYPT);
			}
			else {
				CSSM_DATA intext = *inData;
				CSSM_DATA outtext = *outData;
				while(intext.Length) {
					BF_ecb_encrypt(intext.Data,
						outtext.Data,
						&ekp->key.bf,
						forEncrypt ? BF_ENCRYPT : BF_DECRYPT);
					intext.Data   += 8;
					outtext.Data  += 8;
					intext.Length -= 8;
				}
			}
			break;
		case CSSM_ALGID_CAST:		// cast128 only
			CAST_cbc_encrypt(inData->Data,
				outData->Data,
				inData->Length,
				&ekp->key.cast,
				ivc.Data,
				forEncrypt ? CAST_ENCRYPT : CAST_DECRYPT);
			break;
		default:
			printf("***eayEncryptDecrypt: bad alg\n");
			return -1;
	}
	if(ivc.Data) {
		free(ivc.Data);
	}
	return CSSM_OK;
}

/*** EVP-based encrypt/decrypt ***/

int evpEncryptDecrypt(
	CSSM_ALGORITHMS		alg,				// AES 128 only for now 
	CSSM_BOOL			forEncr,
	const CSSM_DATA		*keyData,			// may be larger than the key size we use
	unsigned			keyLengthInBits,
	CSSM_ENCRYPT_MODE	mode,				// CSSM_ALGMODE_CBC_IV8, ECB, always padding
	const CSSM_DATA		*iv,				// optional per mode
	const CSSM_DATA		*inData,
	CSSM_DATA_PTR		outData)			// CSSM_MALLOCd and RETURNED
{
	EVP_CIPHER_CTX ctx;
	const EVP_CIPHER *cipher;
	unsigned blockSize;
	unsigned outLen = inData->Length;
	bool noPad = false;
	
	switch(alg) {
		case CSSM_ALGID_AES:
			switch(mode) {
				case CSSM_ALGMODE_CBCPadIV8:
					switch(keyLengthInBits) {
						case 128:
							cipher = EVP_aes_128_cbc();
							break;
						case 192:
							cipher = EVP_aes_192_cbc();
							break;
						case 256:
							cipher = EVP_aes_256_cbc();
							break;
						default:
							printf("***Bad AES key length (%u)\n", keyLengthInBits);
							return -1;
					}
					break;
				case CSSM_ALGMODE_ECB:
					switch(keyLengthInBits) {
						case 128:
							cipher = EVP_aes_128_ecb();
							break;
						case 192:
							cipher = EVP_aes_192_ecb();
							break;
						case 256:
							cipher = EVP_aes_256_ecb();
							break;
						default:
							printf("***Bad AES key length (%u)\n", keyLengthInBits);
							return -1;
					}
					noPad = true;
					break;
				default:
					printf("***evpEncryptDecrypt only does CBC and ECB for now\n");
					return -1;
			}
			blockSize = 16;
			break;
		case CSSM_ALGID_DES:
			switch(mode) {
				case CSSM_ALGMODE_CBCPadIV8:
					cipher = EVP_des_cbc();
					break;
				case CSSM_ALGMODE_ECB:
					cipher = EVP_des_ecb();
					noPad = true;
					break;
				default:
					printf("***evpEncryptDecrypt only does CBC and ECB for now\n");
					return -1;
			}
			blockSize = 8;
			break;
		default:
			printf("***evpEncryptDecrypt only does DES and AES 128 for now\n");
			return -1;
	}
	outLen += blockSize;
	unsigned char *outp = (uint8 *)CSSM_MALLOC(outLen);
	int outl = outLen;
	outData->Data = outp;
	
	if(forEncr) {
		int rtn = EVP_EncryptInit(&ctx, cipher, keyData->Data, iv ? iv->Data : NULL);
		if(!rtn) {
			printf("EVP_EncryptInit error\n");
			return -1;
		}
		if(noPad) {
			EVP_CIPHER_CTX_set_padding(&ctx, 0);
		}
		if(!EVP_EncryptUpdate(&ctx, outp, &outl, inData->Data, inData->Length)) {
			printf("EVP_EncryptUpdate error\n");
			return -1;
		}
	}
	else {
		int rtn = EVP_DecryptInit(&ctx, cipher, keyData->Data, iv ? iv->Data : NULL);
		if(!rtn) {
			printf("EVP_DecryptInit error\n");
			return -1;
		}
		if(noPad) {
			EVP_CIPHER_CTX_set_padding(&ctx, 0);
		}
		
		if(!EVP_DecryptUpdate(&ctx, outp, &outl, inData->Data, inData->Length)) {
			printf("EVP_DecryptUpdate error\n");
			return -1;
		}
	}
	outData->Length = outl;
	outp += outl;
	outl = outLen - outl;
	if(forEncr) {
		if(!EVP_EncryptFinal(&ctx, outp, &outl)) {
			printf("EVP_EncryptFinal error\n");
			return -1;
		}
	}
	else {
		if(!EVP_DecryptFinal(&ctx, outp, &outl)) {
			printf("EVP_DecryptFinal error\n");
			return -1;
		}
	}
	outData->Length += outl;
	return 0;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































































































































































































































































































































































Deleted LocalTests/utilLib/ssleayUtils.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
 * ssleayUtils.h - common routines for CDSA/openssl compatibility testing
 */

/*
 * Clients of this module do not need to know about or see anything from the 
 * libcrypt headers. 
 */
#ifndef	_SSLEAY_UTILS_H_
#define _SSLEAY_UTILS_H_
#include <Security/cssmtype.h>

typedef void *EAY_KEY;

/*
 * Create a symmetric key.
 */
CSSM_RETURN  eayGenSymKey(
	CSSM_ALGORITHMS alg,
	CSSM_BOOL		forEncr,
	const CSSM_DATA	*keyData,
	EAY_KEY			*key);			// RETURNED

/*
 * Free a key created in eayGenSymKey
 */
CSSM_RETURN eayFreeKey(
	EAY_KEY			key);

/*
 * encrypt/decrypt
 */
CSSM_RETURN eayEncryptDecrypt(
	EAY_KEY				key,
	CSSM_BOOL			forEncrypt,
	CSSM_ALGORITHMS		encrAlg,
	CSSM_ENCRYPT_MODE	mode,				// CSSM_ALGMODE_CBC ONLY!
	const CSSM_DATA		*iv,				//Êoptional per mode
	const CSSM_DATA		*inData,
	CSSM_DATA_PTR		outData);			// mallocd and RETURNED

/*** EVP-based encrypt/decrypt ***/

int evpEncryptDecrypt(
	CSSM_ALGORITHMS		alg,				// AES 128 only for now 
	CSSM_BOOL			forEncr,
	const CSSM_DATA		*keyData,			// may be larger than the key size we use
	unsigned			keyLengthInBits,
	CSSM_ENCRYPT_MODE	mode,				// CSSM_ALGMODE_CBC_IV8, ECB, always padding
	const CSSM_DATA		*iv,				// optional per mode
	const CSSM_DATA		*inData,
	CSSM_DATA_PTR		outData);			// CSSM_MALLOCd and RETURNED

#endif	/* _EAY_UTILS_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































Deleted LocalTests/utilLib/t_stdlib.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <security_bsafe/bsafe.h>

void T_free(POINTER block)
{
    if (block != NULL_PTR) {
		free(block);
    }
}

POINTER T_malloc(unsigned int len)
{
    return (POINTER) malloc(len ? len : 1);
}

/* these are not needed - they are in system.c in security_bsafe */
#if 0
int T_memcmp(POINTER firstBlock, POINTER secondBlock, unsigned int len)
{
    if (len == 0) {
		return 0;
    }
    return memcmp(firstBlock, secondBlock, len);
}

void T_memcpy(POINTER output, POINTER input, unsigned int len)
{
    if (len != 0) {
		memcpy(output, input, len);
    }
}

void T_memmove(POINTER output, POINTER input, unsigned int len)
{
    if (len != 0) {
		memmove(output, input, len);
    }
}

void T_memset(POINTER output, int value, unsigned int len)
{
    if (len != 0) {
		memset(output, value, len);
    }
}
#endif

POINTER T_realloc(POINTER block, unsigned int len)
{
    if (block == NULL_PTR)
		return (POINTER) malloc(len ? len : 1);
	
	return (POINTER)realloc(block, len);
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































Deleted Source/AESedp/AES.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
#include "AESAssembly.h"

// Generate object code iff this implementation is requested.
#if defined UseAESedp


/*	This module must not be compiled with -fstrict-aliasing.

	We are forced to do some aliasing in this module, because we must conform
	to an external API but need to do four-byte word manipulations for
	efficiency.  For example, chainBuf in the aes_cc_ctx structure is an array
	of char, but we operate in units of four-byte words (or bigger).
*/


#if defined UseAESedp_GeneralC


static void XorBlock(AESData *a, const AESData *b, const AESData *c)
{
	a->w[0] = b->w[0] ^ c->w[0];
	a->w[1] = b->w[1] ^ c->w[1];
	a->w[2] = b->w[2] ^ c->w[2];
	a->w[3] = b->w[3] ^ c->w[3];
}


/*	The code inside this preprocessor conditional clause is retained as an
	illustration of how the assembly implementation works.  For the most part,
	the code here implements AES in the same way the accompanying Intel
	assembly code does.

	While the assembly implementation performs well on an Intel processor, the
	code GCC generates for this C code is not particularly fast.

	Key expansion differs somewhat from the assembly implementation.  AES
	presents an Inverse Cipher for decryption that is not immediately suitable
	to table implementation.  AES also offers an Equivalent Inverse Cipher
	which is suitable for table implementation.  In the Equivalent Inverse
	Cipher, the InvMixColumn operation is switched with an XOR with the key.
	Fortunately, InvMixColumn distributes over XOR (it is a linear combination
	of its operands in a Galois field the AES defines, and the XOR is an
	addition in the field), so the swap can be made by applying InvMixColumn to
	the blocks of the key that will be used in the swapped operations.

	In the C code, InvMixColumn is applied in a separate step after expanded
	the key, in a for-loop inside the aes_cc_set_key routine.  In the assembly
	code, InvMixColumn is integrated into the key expansion code.
*/


#include "Data.c"	// Include tables with precalculated AES functions.


/*	This implements the InvMixColumn operation of the AES algorithm.  It is
	needed as a separate function during key expansion for decryption.
*/
static Word InvMixColumn(Word w)
{
	union { Word w; Byte b[4]; } b = { w };
	Byte 
		s0 = b.b[0],
		s1 = b.b[1],
		s2 = b.b[2],
		s3 = b.b[3];

	return
		  AESInvMixColumnTable[0][s0]
		^ AESInvMixColumnTable[1][s1]
		^ AESInvMixColumnTable[2][s2]
		^ AESInvMixColumnTable[3][s3];
}


// Expand the user's cipher key according to the AES key schedule.
static void AESExpandKey(Word *ExpandedKey, const AESKey *Key, long Nk)
{
	const Word (*T)[256] = AESSubBytesWordTable;
	const Byte *R = AESRcon;

	Word * const E = ExpandedKey;

	switch (Nk)
	{
		default:
		case 4:
		{
			const int Nr = 10;

			// The first words are just copies of the key.
			Word
				e0 = E[0] = Key->w[0],
				e1 = E[1] = Key->w[1],
				e2 = E[2] = Key->w[2],
				e3 = E[3] = Key->w[3];

			for (int i = Nk; i < Nb * (Nr + 1); i += Nk)
			{
				Word temp;
				{
					Byte * const b = (Byte *) &e3;

					Byte b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
					temp = T[0][b1] ^ T[1][b2] ^ T[2][b3] ^ T[3][b0];
				}
				temp ^= *++R;
				E[i+0] = e0 ^= temp;
				E[i+1] = e1 ^= e0;
				E[i+2] = e2 ^= e1;
				E[i+3] = e3 ^= e2;
			}
			break;
		}
		case 6:
		{
			const int Nr = 12;

			// The first words are just copies of the key.
			for (int i = 0; i < Nk; ++i)
				E[i] = Key->w[i];

			Word temp = E[Nk-1];
			for (int i = Nk; 1; i += Nk)
			{
				{
					Byte * const b = (Byte *) &temp;

					Byte b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
					temp = T[0][b1] ^ T[1][b2] ^ T[2][b3] ^ T[3][b0];
					temp ^= *++R;
				}
				E[i+0] = temp ^= E[i+0-Nk];
				E[i+1] = temp ^= E[i+1-Nk];
				E[i+2] = temp ^= E[i+2-Nk];
				E[i+3] = temp ^= E[i+3-Nk];

				if (Nb * Nr <= i)
					break;

				E[i+4] = temp ^= E[i+4-Nk];
				E[i+5] = temp ^= E[i+5-Nk];
			}
			break;
		}
		case 8:
		{
			const int Nr = 14;

			// The first words are just copies of the key.
			for (int i = 0; i < Nk; ++i)
				E[i] = Key->w[i];

			Word temp = E[Nk-1];
			for (int i = Nk; 1; i += Nk)
			{
				{
					Byte * const b = (Byte *) &temp;

					Byte b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
					temp = T[0][b1] ^ T[1][b2] ^ T[2][b3] ^ T[3][b0];
					temp ^= *++R;
				}
				E[i+0] = temp ^= E[i+0-Nk];
				E[i+1] = temp ^= E[i+1-Nk];
				E[i+2] = temp ^= E[i+2-Nk];
				E[i+3] = temp ^= E[i+3-Nk];

				if (Nb * Nr <= i)
					break;

				{
					Byte * const b = (Byte *) &temp;

					Byte b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
					temp = T[0][b0] ^ T[1][b1] ^ T[2][b2] ^ T[3][b3];
				}
				E[i+4] = temp ^= E[i+4-Nk];
				E[i+5] = temp ^= E[i+5-Nk];
				E[i+6] = temp ^= E[i+6-Nk];
				E[i+7] = temp ^= E[i+7-Nk];
			}
			break;
		}
	}
}


// This is the main encryption routine.
static void AESEncryptWithExpandedKey(Byte *Ciphertext, const Byte *Plaintext,
	const AESData *ExpandedKey, long Nr)
{
	AESData State;

	XorBlock(&State, (const AESData *) Plaintext, &ExpandedKey[0]);

	{
		const Word (*T)[256] = AESEncryptTable;

		for (int round = 1; round < Nr; ++round)
		{
			const AESData *Key = &ExpandedKey[round];

			const union { Word w; Byte b[4]; }
				w0 = { State.w[0] },
				w1 = { State.w[1] },
				w2 = { State.w[2] },
				w3 = { State.w[3] };

			State.w[0] = Key->w[0]
				^ T[0][w0.b[0]] ^ T[1][w1.b[1]] ^ T[2][w2.b[2]] ^ T[3][w3.b[3]];
			State.w[1] = Key->w[1]
				^ T[0][w1.b[0]] ^ T[1][w2.b[1]] ^ T[2][w3.b[2]] ^ T[3][w0.b[3]];
			State.w[2] = Key->w[2]
				^ T[0][w2.b[0]] ^ T[1][w3.b[1]] ^ T[2][w0.b[2]] ^ T[3][w1.b[3]];
			State.w[3] = Key->w[3]
				^ T[0][w3.b[0]] ^ T[1][w0.b[1]] ^ T[2][w1.b[2]] ^ T[3][w2.b[3]];
		}
	}

	{
		const Word (*T)[256] = AESSubBytesWordTable;

		const AESData *Key = &ExpandedKey[Nr];

		const union { Word w; Byte b[4]; }
			w0 = { State.w[0] },
			w1 = { State.w[1] },
			w2 = { State.w[2] },
			w3 = { State.w[3] };

		State.w[0] = Key->w[0]
			^ T[0][w0.b[0]] ^ T[1][w1.b[1]] ^ T[2][w2.b[2]] ^ T[3][w3.b[3]];
		State.w[1] = Key->w[1]
			^ T[0][w1.b[0]] ^ T[1][w2.b[1]] ^ T[2][w3.b[2]] ^ T[3][w0.b[3]];
		State.w[2] = Key->w[2]
			^ T[0][w2.b[0]] ^ T[1][w3.b[1]] ^ T[2][w0.b[2]] ^ T[3][w1.b[3]];
		State.w[3] = Key->w[3]
			^ T[0][w3.b[0]] ^ T[1][w0.b[1]] ^ T[2][w1.b[2]] ^ T[3][w2.b[3]];
	}

	* (AESData *) Ciphertext = State;
}


// This is the main decryption routine.
static void AESDecryptWithExpandedKey(Byte *Plaintext, const Byte *Ciphertext,
	const AESData *ExpandedKey, long Nr)
{
	AESData State;
	
	XorBlock(&State, (const AESData *) Ciphertext, &ExpandedKey[Nr]);

	{
		const Word (*T)[256] = AESDecryptTable;

		for (int round = Nr-1; 0 < round; --round)
		{
			const AESData *Key = &ExpandedKey[round];

			const union { Word w; Byte b[4]; }
				w0 = { State.w[0] },
				w1 = { State.w[1] },
				w2 = { State.w[2] },
				w3 = { State.w[3] };

			State.w[0] = Key->w[0]
				^ T[0][w0.b[0]] ^ T[1][w3.b[1]] ^ T[2][w2.b[2]] ^ T[3][w1.b[3]];
			State.w[1] = Key->w[1]
				^ T[0][w1.b[0]] ^ T[1][w0.b[1]] ^ T[2][w3.b[2]] ^ T[3][w2.b[3]];
			State.w[2] = Key->w[2]
				^ T[0][w2.b[0]] ^ T[1][w1.b[1]] ^ T[2][w0.b[2]] ^ T[3][w3.b[3]];
			State.w[3] = Key->w[3]
				^ T[0][w3.b[0]] ^ T[1][w2.b[1]] ^ T[2][w1.b[2]] ^ T[3][w0.b[3]];
		}
	}

	{
		const Word (*T)[256] = AESInvSubBytesWordTable;

		const AESData *Key = &ExpandedKey[0];

		const union { Word w; Byte b[4]; }
			w0 = { State.w[0] },
			w1 = { State.w[1] },
			w2 = { State.w[2] },
			w3 = { State.w[3] };

		State.w[0] = Key->w[0]
			^ T[0][w0.b[0]] ^ T[1][w3.b[1]] ^ T[2][w2.b[2]] ^ T[3][w1.b[3]];
		State.w[1] = Key->w[1]
			^ T[0][w1.b[0]] ^ T[1][w0.b[1]] ^ T[2][w3.b[2]] ^ T[3][w2.b[3]];
		State.w[2] = Key->w[2]
			^ T[0][w2.b[0]] ^ T[1][w1.b[1]] ^ T[2][w0.b[2]] ^ T[3][w3.b[3]];
		State.w[3] = Key->w[3]
			^ T[0][w3.b[0]] ^ T[1][w2.b[1]] ^ T[2][w1.b[2]] ^ T[3][w0.b[3]];
	}

	* (AESData *) Plaintext = State;
}


#else	// defined UseAESedp_GeneralC

	// Declare routines implemented elsewhere.
	void AESExpandKeyForEncryption(Word *ExpandedKey, const AESKey *Key,
		long Nk);
	void AESExpandKeyForDecryption(Word *ExpandedKey, const AESKey *Key,
		long Nk);
	void AESEncryptWithExpandedKey(Byte *OutputText, const Byte *InputText,
		const AESData *ExpandedKey, long Nr);
	void AESDecryptWithExpandedKey(Byte *OutputText, const Byte *InputText,
		const AESData *ExpandedKey, long Nr);
	void AESEncryptCBC(void *Output, const void *Input,
		void *ChainBuffer, void *Key, long Blocks, long Rounds);
	void AESDecryptCBC(void *Output, const void *Input,
		void *ChainBuffer, void *Key, long Blocks, long Rounds);

#endif	// defined UseAESedp_GeneralC


/*	Expand a key and store the expansion in the cryptor context.

	CommonCrypto calls this routine.
*/
int aes_cc_set_key(
		aes_cc_ctx *Context,	// Cryptor context.
		const void *Key,		// Key.
		aes_32t KeyLength,		// Number of bytes in key.
		int ForEncryption		// True for encryption, false for decryption.
	)
{
	// Test for invalid key length.
	if (KeyLength != 16 && KeyLength != 24 && KeyLength != 32)
		return -1;

	// Set Nk to number of four-byte words in key.
	const int Nk = KeyLength / 4;

	// Remember the number of rounds.
	Context->encrypt.rn = Nk + 6;

	#if defined UseAESedp_GeneralC

		AESExpandKey(Context->encrypt.ks, Key, Nk);

		if (!ForEncryption)
		{

			/*	Change the expanded key so we can swap the InvMixColumns and
				XorBlock operations during decryption.
			*/
			Word *E = Context->encrypt.ks;
			int Nr = Context->encrypt.rn;
			for (int i = Nb; i < Nr * Nb; ++i)
				E[i] = InvMixColumn(E[i]);
		}

	#else	// defined UseAESedp_GeneralC

		if (ForEncryption)
			AESExpandKeyForEncryption(Context->encrypt.ks, Key, Nk);
		else
			AESExpandKeyForDecryption(Context->encrypt.ks, Key, Nk);

	#endif	// defined UseAESedp_GeneralC

	// Indicate there is no initial value stored.
	Context->encrypt.cbcEnable = 0;

	return 0;
}


#include <string.h>	// For memcpy.


/*	Store an initial value (or lack thereof) in the cryptor context.

	CommonCrypto calls this routine.
*/
void aes_cc_set_iv(aes_cc_ctx *Context, int ForEncryption, const void *IV)
{
	if (IV == 0)
		// Indicate there is no initial value stored.
		Context->encrypt.cbcEnable = 0;
	else
	{
		// Indicate there is an initial value stored.
		Context->encrypt.cbcEnable = 1;
		memcpy(Context->encrypt.chainBuf, IV, sizeof Context->encrypt.chainBuf);
	}
}


/*	Encrypt blocks of data.

	CommonCrypto calls this routine.
*/
void aes_cc_encrypt(
		aes_cc_ctx *Context,	// Cryptor context.
		const void *Input,		// Input.
		aes_32t Blocks,			// Number of 16-byte blocks to process.
		void *Output			// Output.
	)
{
	// Alias to more convenient pointers for referring to blocks.
	const AESData *I = Input;
	      AESData *O = Output;

	// If we have an initial value, use Cipher Block Chaining (CBC) mode.
	if (Context->encrypt.cbcEnable)
	{
		#if defined UseAESedp_GeneralC
			// Get chain value.
			AESData State = * (AESData *) Context->encrypt.chainBuf;

			// Chain and encrypt.
			while (Blocks--)
			{
				XorBlock(&State, &State, I++);
				AESEncryptWithExpandedKey(State.b, State.b,
					(const void *) Context->encrypt.ks,
					Context->encrypt.rn);
				*O++ = State;
			}

			// Save updated chain value.
			* (AESData *) Context->encrypt.chainBuf = State;
		#else	// defined UseAESedp_GeneralC
			AESEncryptCBC(O, I, Context->encrypt.chainBuf,
				Context->encrypt.ks, Blocks, Context->encrypt.rn);
		#endif	// defined UseAESedp_GeneralC
	}

	// If we have no initial value, use Electronic Code Book (ECB) mode.
	else
	{
		aes_32t i;
		for (i = 0; i < Blocks; ++i)
			AESEncryptWithExpandedKey(O[i].b, I[i].b,
				(const void *) Context->encrypt.ks, Context->encrypt.rn);
	}
}


/*	Alternate interface to encryption, same as aes_cc_encrypt, except that if
	InitialValue is non-null, it points to an initial value which is used for
	CBC mode, regardless of the cbcEnable flag and the initial/chain value in
	the context structure.  The updated chain value is written to written to
	the context structure.
*/
aes_rval aes_encrypt_cbc(
	const unsigned char *Input,
	const unsigned char *InitialValue,
	unsigned int Blocks,
	unsigned char *Output,
	aes_encrypt_ctx *Context)
{
	// Alias to more convenient pointers for referring to blocks.
	const AESData *I = (const AESData *) Input;
	      AESData *O = (      AESData *) Output;

	// If we have an initial value, use Cipher Block Chaining (CBC) mode.
	if (Context->cbcEnable || InitialValue)
	{
		#if defined UseAESedp_GeneralC
			// Get chain value.
			AESData State = InitialValue
				? * (const AESData *) InitialValue
				: * (const AESData *) Context->chainBuf;

			// Chain and encrypt.
			while (Blocks--)
			{
				XorBlock(&State, &State, I++);
				AESEncryptWithExpandedKey(State.b, State.b,
					(const void *) Context->ks,
					Context->rn);
				*O++ = State;
			}

			// Save updated chain value.
			* (AESData *) Context->chainBuf = State;
		#else	// defined UseAESedp_GeneralC
			AESEncryptCBC(O, I, Context->chainBuf,
				Context->ks, Blocks, Context->rn);
		#endif	// defined UseAESedp_GeneralC
	}

	// If we have no initial value, use Electronic Code Book (ECB) mode.
	else
	{
		aes_32t i;
		for (i = 0; i < Blocks; ++i)
			AESEncryptWithExpandedKey(O[i].b, I[i].b,
				(const void *) Context->ks, Context->rn);
	}
}


/*	Decrypt blocks of data.

	CommonCrypto calls this routine.
*/
void aes_cc_decrypt(
		aes_cc_ctx *Context,	// Cryptor context.
		const void *Input,		// Input.
		aes_32t Blocks,			// Number of 16-byte blocks to process.
		void *Output			// Output.
	)
{
	// Alias to more convenient pointers for referring to blocks.
	const AESData *I = Input;
	      AESData *O = Output;

	// If we have an initial value, use Cipher Block Chaining (CBC) mode.
	if (Context->encrypt.cbcEnable)
	{
		#if defined UseAESedp_GeneralC
			// Get chain value.
			AESData NextChainValue = * (AESData *) Context->encrypt.chainBuf;

			// Decrypt and chain.
			while (Blocks--)
			{
				AESData ChainValue = NextChainValue, State;
				NextChainValue = *I++;
				AESDecryptWithExpandedKey(State.b, NextChainValue.b,
					(const void *) Context->encrypt.ks, Context->encrypt.rn);
				XorBlock(O++, &State, &ChainValue);
			}

			// Save updated chain value.
			* (AESData *) Context->encrypt.chainBuf = NextChainValue;
		#else	// defined UseAESedp_GeneralC
			AESDecryptCBC(O, I, Context->encrypt.chainBuf,
				Context->encrypt.ks, Blocks, Context->encrypt.rn);
		#endif	// defined UseAESedp_GeneralC
	}

	// If we have no initial value, use Electronic Code Book (ECB) mode.
	else
	{
		aes_32t i;
		for (i = 0; i < Blocks; ++i)
			AESDecryptWithExpandedKey(O[i].b, I[i].b,
				(const void *) Context->encrypt.ks, Context->encrypt.rn);
	}
}


/*	Alternate interface to decryption, same as aes_cc_decrypt, except that if
	InitialValue is non-null, it points to an initial value which is used for
	CBC mode, regardless of the cbcEnable flag and the initial/chain value in
	the context structure.  The updated chain value is written to written to
	the context structure.
*/
aes_rval aes_decrypt_cbc(
	const unsigned char *Input,
	const unsigned char *InitialValue,
	unsigned int Blocks,
	unsigned char *Output,
	aes_decrypt_ctx *Context)
{
	// Alias to more convenient pointers for referring to blocks.
	const AESData *I = (const AESData *) Input;
	      AESData *O = (      AESData *) Output;

	// If we have an initial value, use Cipher Block Chaining (CBC) mode.
	if (Context->cbcEnable || InitialValue)
	{
		#if defined UseAESedp_GeneralC
			// Get chain value.
			AESData NextChainValue = InitialValue
				? * (const AESData *) InitialValue
				: * (const AESData *) Context->chainBuf;

			// Decrypt and chain.
			while (Blocks--)
			{
				AESData ChainValue = NextChainValue, State;
				NextChainValue = *I++;
				AESDecryptWithExpandedKey(State.b, NextChainValue.b,
					(const void *) Context->ks, Context->rn);
				XorBlock(O++, &State, &ChainValue);
			}

			// Save updated chain value.
			* (AESData *) Context->chainBuf = NextChainValue;
		#else	// defined UseAESedp_GeneralC
			AESDecryptCBC(O, I, Context->chainBuf,
				Context->ks, Blocks, Context->rn);
		#endif	// defined UseAESedp_GeneralC
	}

	// If we have no initial value, use Electronic Code Book (ECB) mode.
	else
	{
		aes_32t i;
		for (i = 0; i < Blocks; ++i)
			AESDecryptWithExpandedKey(O[i].b, I[i].b,
				(const void *) Context->ks, Context->rn);
	}
}



#endif	// defined UseAESedp
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/AESedp/AESAssembly.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#if !defined AES_h
#define AES_h


// Include aesopt.h to get the UseAESedp symbol.  We use nothing else from it.
#include <CommonCrypto/aesopt.h>


// Generate object code iff UseAESedp is defined.
#if defined UseAESedp


// Select which implementation to use.
#if 1
	#define	UseAESedp_IntelAssembly
#else
	#define	UseAESedp_GeneralC
#endif


/*	MaxNb is the maximum value of Nb, the number of four-byte words in one data
	block.
*/
#define	MaxNb	4

/*	Nb is the number of four-byte words in one data block.  AES fixes Nb at 4,
	although Rijndael allows up to 8.
*/
#define	Nb		4

/*	MaxNk is the maximum value of Nk, the number of four-byte words in a key.
	AES and Rijndael allow up to 8.
*/
#define	MaxNk	8

/*	Nk is not defined here because different key sizes are supported
	dynamically.
*/

/*	MaxRcon is the maximum number of round constants that might be needed.
	The number needed is (Nb*(Nr+1)-1) / Nk + 1.  For AES, Nr is Nk + 6.  (For
	Rijndael, Nr is max(Nk, Nb) + 6.)  For AES, we have:

		(Nb*(Nr+1)-1) / Nk + 1.
		(Nb*(Nk+6+1)-1) / Nk + 1.
		(Nb*Nk + Nb*7 - 1) / Nk + 1.
		Nb + (Nb*7-1)/Nk + 1.

	Clearly this is greatest when Nk is smallest.  Nk is at least 4.  In AES,
	Nb is 4, so we have 4 + 27/4 + 1 = 11.

	(In Rijndael, the maximum is 30, occurring when Nb is 8 and Nk is 4.)
*/
#define	MaxRcon	11


#if !__ASSEMBLER__

	#include <stdint.h>

	typedef uint8_t Byte;
	typedef uint32_t Word;
	typedef union { Byte b[MaxNb*4]; Word w[MaxNb]; } AESData;
	typedef union { Byte b[MaxNk*4]; Word w[MaxNk]; } AESKey ;

#endif


#endif	// defined UseAESedp


#endif	// !defined AES_h
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































Deleted Source/AESedp/Data.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
// This file was generated by MakeData.c.


#include "AESAssembly.h"


// Round constants.
const Byte AESRcon[] =
{
	0,	// Not used, included for indexing simplicity.
	0x01,
	0x02,
	0x04,
	0x08,
	0x10,
	0x20,
	0x40,
	0x80,
	0x1b,
	0x36,
};


// Tables for InvMixColumn.
const Word AESInvMixColumnTable[4][256] =
{
	{
		0x00000000,
		0x0b0d090e,
		0x161a121c,
		0x1d171b12,
		0x2c342438,
		0x27392d36,
		0x3a2e3624,
		0x31233f2a,
		0x58684870,
		0x5365417e,
		0x4e725a6c,
		0x457f5362,
		0x745c6c48,
		0x7f516546,
		0x62467e54,
		0x694b775a,
		0xb0d090e0,
		0xbbdd99ee,
		0xa6ca82fc,
		0xadc78bf2,
		0x9ce4b4d8,
		0x97e9bdd6,
		0x8afea6c4,
		0x81f3afca,
		0xe8b8d890,
		0xe3b5d19e,
		0xfea2ca8c,
		0xf5afc382,
		0xc48cfca8,
		0xcf81f5a6,
		0xd296eeb4,
		0xd99be7ba,
		0x7bbb3bdb,
		0x70b632d5,
		0x6da129c7,
		0x66ac20c9,
		0x578f1fe3,
		0x5c8216ed,
		0x41950dff,
		0x4a9804f1,
		0x23d373ab,
		0x28de7aa5,
		0x35c961b7,
		0x3ec468b9,
		0x0fe75793,
		0x04ea5e9d,
		0x19fd458f,
		0x12f04c81,
		0xcb6bab3b,
		0xc066a235,
		0xdd71b927,
		0xd67cb029,
		0xe75f8f03,
		0xec52860d,
		0xf1459d1f,
		0xfa489411,
		0x9303e34b,
		0x980eea45,
		0x8519f157,
		0x8e14f859,
		0xbf37c773,
		0xb43ace7d,
		0xa92dd56f,
		0xa220dc61,
		0xf66d76ad,
		0xfd607fa3,
		0xe07764b1,
		0xeb7a6dbf,
		0xda595295,
		0xd1545b9b,
		0xcc434089,
		0xc74e4987,
		0xae053edd,
		0xa50837d3,
		0xb81f2cc1,
		0xb31225cf,
		0x82311ae5,
		0x893c13eb,
		0x942b08f9,
		0x9f2601f7,
		0x46bde64d,
		0x4db0ef43,
		0x50a7f451,
		0x5baafd5f,
		0x6a89c275,
		0x6184cb7b,
		0x7c93d069,
		0x779ed967,
		0x1ed5ae3d,
		0x15d8a733,
		0x08cfbc21,
		0x03c2b52f,
		0x32e18a05,
		0x39ec830b,
		0x24fb9819,
		0x2ff69117,
		0x8dd64d76,
		0x86db4478,
		0x9bcc5f6a,
		0x90c15664,
		0xa1e2694e,
		0xaaef6040,
		0xb7f87b52,
		0xbcf5725c,
		0xd5be0506,
		0xdeb30c08,
		0xc3a4171a,
		0xc8a91e14,
		0xf98a213e,
		0xf2872830,
		0xef903322,
		0xe49d3a2c,
		0x3d06dd96,
		0x360bd498,
		0x2b1ccf8a,
		0x2011c684,
		0x1132f9ae,
		0x1a3ff0a0,
		0x0728ebb2,
		0x0c25e2bc,
		0x656e95e6,
		0x6e639ce8,
		0x737487fa,
		0x78798ef4,
		0x495ab1de,
		0x4257b8d0,
		0x5f40a3c2,
		0x544daacc,
		0xf7daec41,
		0xfcd7e54f,
		0xe1c0fe5d,
		0xeacdf753,
		0xdbeec879,
		0xd0e3c177,
		0xcdf4da65,
		0xc6f9d36b,
		0xafb2a431,
		0xa4bfad3f,
		0xb9a8b62d,
		0xb2a5bf23,
		0x83868009,
		0x888b8907,
		0x959c9215,
		0x9e919b1b,
		0x470a7ca1,
		0x4c0775af,
		0x51106ebd,
		0x5a1d67b3,
		0x6b3e5899,
		0x60335197,
		0x7d244a85,
		0x7629438b,
		0x1f6234d1,
		0x146f3ddf,
		0x097826cd,
		0x02752fc3,
		0x335610e9,
		0x385b19e7,
		0x254c02f5,
		0x2e410bfb,
		0x8c61d79a,
		0x876cde94,
		0x9a7bc586,
		0x9176cc88,
		0xa055f3a2,
		0xab58faac,
		0xb64fe1be,
		0xbd42e8b0,
		0xd4099fea,
		0xdf0496e4,
		0xc2138df6,
		0xc91e84f8,
		0xf83dbbd2,
		0xf330b2dc,
		0xee27a9ce,
		0xe52aa0c0,
		0x3cb1477a,
		0x37bc4e74,
		0x2aab5566,
		0x21a65c68,
		0x10856342,
		0x1b886a4c,
		0x069f715e,
		0x0d927850,
		0x64d90f0a,
		0x6fd40604,
		0x72c31d16,
		0x79ce1418,
		0x48ed2b32,
		0x43e0223c,
		0x5ef7392e,
		0x55fa3020,
		0x01b79aec,
		0x0aba93e2,
		0x17ad88f0,
		0x1ca081fe,
		0x2d83bed4,
		0x268eb7da,
		0x3b99acc8,
		0x3094a5c6,
		0x59dfd29c,
		0x52d2db92,
		0x4fc5c080,
		0x44c8c98e,
		0x75ebf6a4,
		0x7ee6ffaa,
		0x63f1e4b8,
		0x68fcedb6,
		0xb1670a0c,
		0xba6a0302,
		0xa77d1810,
		0xac70111e,
		0x9d532e34,
		0x965e273a,
		0x8b493c28,
		0x80443526,
		0xe90f427c,
		0xe2024b72,
		0xff155060,
		0xf418596e,
		0xc53b6644,
		0xce366f4a,
		0xd3217458,
		0xd82c7d56,
		0x7a0ca137,
		0x7101a839,
		0x6c16b32b,
		0x671bba25,
		0x5638850f,
		0x5d358c01,
		0x40229713,
		0x4b2f9e1d,
		0x2264e947,
		0x2969e049,
		0x347efb5b,
		0x3f73f255,
		0x0e50cd7f,
		0x055dc471,
		0x184adf63,
		0x1347d66d,
		0xcadc31d7,
		0xc1d138d9,
		0xdcc623cb,
		0xd7cb2ac5,
		0xe6e815ef,
		0xede51ce1,
		0xf0f207f3,
		0xfbff0efd,
		0x92b479a7,
		0x99b970a9,
		0x84ae6bbb,
		0x8fa362b5,
		0xbe805d9f,
		0xb58d5491,
		0xa89a4f83,
		0xa397468d,
	},
	{
		0x00000000,
		0x0d090e0b,
		0x1a121c16,
		0x171b121d,
		0x3424382c,
		0x392d3627,
		0x2e36243a,
		0x233f2a31,
		0x68487058,
		0x65417e53,
		0x725a6c4e,
		0x7f536245,
		0x5c6c4874,
		0x5165467f,
		0x467e5462,
		0x4b775a69,
		0xd090e0b0,
		0xdd99eebb,
		0xca82fca6,
		0xc78bf2ad,
		0xe4b4d89c,
		0xe9bdd697,
		0xfea6c48a,
		0xf3afca81,
		0xb8d890e8,
		0xb5d19ee3,
		0xa2ca8cfe,
		0xafc382f5,
		0x8cfca8c4,
		0x81f5a6cf,
		0x96eeb4d2,
		0x9be7bad9,
		0xbb3bdb7b,
		0xb632d570,
		0xa129c76d,
		0xac20c966,
		0x8f1fe357,
		0x8216ed5c,
		0x950dff41,
		0x9804f14a,
		0xd373ab23,
		0xde7aa528,
		0xc961b735,
		0xc468b93e,
		0xe757930f,
		0xea5e9d04,
		0xfd458f19,
		0xf04c8112,
		0x6bab3bcb,
		0x66a235c0,
		0x71b927dd,
		0x7cb029d6,
		0x5f8f03e7,
		0x52860dec,
		0x459d1ff1,
		0x489411fa,
		0x03e34b93,
		0x0eea4598,
		0x19f15785,
		0x14f8598e,
		0x37c773bf,
		0x3ace7db4,
		0x2dd56fa9,
		0x20dc61a2,
		0x6d76adf6,
		0x607fa3fd,
		0x7764b1e0,
		0x7a6dbfeb,
		0x595295da,
		0x545b9bd1,
		0x434089cc,
		0x4e4987c7,
		0x053eddae,
		0x0837d3a5,
		0x1f2cc1b8,
		0x1225cfb3,
		0x311ae582,
		0x3c13eb89,
		0x2b08f994,
		0x2601f79f,
		0xbde64d46,
		0xb0ef434d,
		0xa7f45150,
		0xaafd5f5b,
		0x89c2756a,
		0x84cb7b61,
		0x93d0697c,
		0x9ed96777,
		0xd5ae3d1e,
		0xd8a73315,
		0xcfbc2108,
		0xc2b52f03,
		0xe18a0532,
		0xec830b39,
		0xfb981924,
		0xf691172f,
		0xd64d768d,
		0xdb447886,
		0xcc5f6a9b,
		0xc1566490,
		0xe2694ea1,
		0xef6040aa,
		0xf87b52b7,
		0xf5725cbc,
		0xbe0506d5,
		0xb30c08de,
		0xa4171ac3,
		0xa91e14c8,
		0x8a213ef9,
		0x872830f2,
		0x903322ef,
		0x9d3a2ce4,
		0x06dd963d,
		0x0bd49836,
		0x1ccf8a2b,
		0x11c68420,
		0x32f9ae11,
		0x3ff0a01a,
		0x28ebb207,
		0x25e2bc0c,
		0x6e95e665,
		0x639ce86e,
		0x7487fa73,
		0x798ef478,
		0x5ab1de49,
		0x57b8d042,
		0x40a3c25f,
		0x4daacc54,
		0xdaec41f7,
		0xd7e54ffc,
		0xc0fe5de1,
		0xcdf753ea,
		0xeec879db,
		0xe3c177d0,
		0xf4da65cd,
		0xf9d36bc6,
		0xb2a431af,
		0xbfad3fa4,
		0xa8b62db9,
		0xa5bf23b2,
		0x86800983,
		0x8b890788,
		0x9c921595,
		0x919b1b9e,
		0x0a7ca147,
		0x0775af4c,
		0x106ebd51,
		0x1d67b35a,
		0x3e58996b,
		0x33519760,
		0x244a857d,
		0x29438b76,
		0x6234d11f,
		0x6f3ddf14,
		0x7826cd09,
		0x752fc302,
		0x5610e933,
		0x5b19e738,
		0x4c02f525,
		0x410bfb2e,
		0x61d79a8c,
		0x6cde9487,
		0x7bc5869a,
		0x76cc8891,
		0x55f3a2a0,
		0x58faacab,
		0x4fe1beb6,
		0x42e8b0bd,
		0x099fead4,
		0x0496e4df,
		0x138df6c2,
		0x1e84f8c9,
		0x3dbbd2f8,
		0x30b2dcf3,
		0x27a9ceee,
		0x2aa0c0e5,
		0xb1477a3c,
		0xbc4e7437,
		0xab55662a,
		0xa65c6821,
		0x85634210,
		0x886a4c1b,
		0x9f715e06,
		0x9278500d,
		0xd90f0a64,
		0xd406046f,
		0xc31d1672,
		0xce141879,
		0xed2b3248,
		0xe0223c43,
		0xf7392e5e,
		0xfa302055,
		0xb79aec01,
		0xba93e20a,
		0xad88f017,
		0xa081fe1c,
		0x83bed42d,
		0x8eb7da26,
		0x99acc83b,
		0x94a5c630,
		0xdfd29c59,
		0xd2db9252,
		0xc5c0804f,
		0xc8c98e44,
		0xebf6a475,
		0xe6ffaa7e,
		0xf1e4b863,
		0xfcedb668,
		0x670a0cb1,
		0x6a0302ba,
		0x7d1810a7,
		0x70111eac,
		0x532e349d,
		0x5e273a96,
		0x493c288b,
		0x44352680,
		0x0f427ce9,
		0x024b72e2,
		0x155060ff,
		0x18596ef4,
		0x3b6644c5,
		0x366f4ace,
		0x217458d3,
		0x2c7d56d8,
		0x0ca1377a,
		0x01a83971,
		0x16b32b6c,
		0x1bba2567,
		0x38850f56,
		0x358c015d,
		0x22971340,
		0x2f9e1d4b,
		0x64e94722,
		0x69e04929,
		0x7efb5b34,
		0x73f2553f,
		0x50cd7f0e,
		0x5dc47105,
		0x4adf6318,
		0x47d66d13,
		0xdc31d7ca,
		0xd138d9c1,
		0xc623cbdc,
		0xcb2ac5d7,
		0xe815efe6,
		0xe51ce1ed,
		0xf207f3f0,
		0xff0efdfb,
		0xb479a792,
		0xb970a999,
		0xae6bbb84,
		0xa362b58f,
		0x805d9fbe,
		0x8d5491b5,
		0x9a4f83a8,
		0x97468da3,
	},
	{
		0x00000000,
		0x090e0b0d,
		0x121c161a,
		0x1b121d17,
		0x24382c34,
		0x2d362739,
		0x36243a2e,
		0x3f2a3123,
		0x48705868,
		0x417e5365,
		0x5a6c4e72,
		0x5362457f,
		0x6c48745c,
		0x65467f51,
		0x7e546246,
		0x775a694b,
		0x90e0b0d0,
		0x99eebbdd,
		0x82fca6ca,
		0x8bf2adc7,
		0xb4d89ce4,
		0xbdd697e9,
		0xa6c48afe,
		0xafca81f3,
		0xd890e8b8,
		0xd19ee3b5,
		0xca8cfea2,
		0xc382f5af,
		0xfca8c48c,
		0xf5a6cf81,
		0xeeb4d296,
		0xe7bad99b,
		0x3bdb7bbb,
		0x32d570b6,
		0x29c76da1,
		0x20c966ac,
		0x1fe3578f,
		0x16ed5c82,
		0x0dff4195,
		0x04f14a98,
		0x73ab23d3,
		0x7aa528de,
		0x61b735c9,
		0x68b93ec4,
		0x57930fe7,
		0x5e9d04ea,
		0x458f19fd,
		0x4c8112f0,
		0xab3bcb6b,
		0xa235c066,
		0xb927dd71,
		0xb029d67c,
		0x8f03e75f,
		0x860dec52,
		0x9d1ff145,
		0x9411fa48,
		0xe34b9303,
		0xea45980e,
		0xf1578519,
		0xf8598e14,
		0xc773bf37,
		0xce7db43a,
		0xd56fa92d,
		0xdc61a220,
		0x76adf66d,
		0x7fa3fd60,
		0x64b1e077,
		0x6dbfeb7a,
		0x5295da59,
		0x5b9bd154,
		0x4089cc43,
		0x4987c74e,
		0x3eddae05,
		0x37d3a508,
		0x2cc1b81f,
		0x25cfb312,
		0x1ae58231,
		0x13eb893c,
		0x08f9942b,
		0x01f79f26,
		0xe64d46bd,
		0xef434db0,
		0xf45150a7,
		0xfd5f5baa,
		0xc2756a89,
		0xcb7b6184,
		0xd0697c93,
		0xd967779e,
		0xae3d1ed5,
		0xa73315d8,
		0xbc2108cf,
		0xb52f03c2,
		0x8a0532e1,
		0x830b39ec,
		0x981924fb,
		0x91172ff6,
		0x4d768dd6,
		0x447886db,
		0x5f6a9bcc,
		0x566490c1,
		0x694ea1e2,
		0x6040aaef,
		0x7b52b7f8,
		0x725cbcf5,
		0x0506d5be,
		0x0c08deb3,
		0x171ac3a4,
		0x1e14c8a9,
		0x213ef98a,
		0x2830f287,
		0x3322ef90,
		0x3a2ce49d,
		0xdd963d06,
		0xd498360b,
		0xcf8a2b1c,
		0xc6842011,
		0xf9ae1132,
		0xf0a01a3f,
		0xebb20728,
		0xe2bc0c25,
		0x95e6656e,
		0x9ce86e63,
		0x87fa7374,
		0x8ef47879,
		0xb1de495a,
		0xb8d04257,
		0xa3c25f40,
		0xaacc544d,
		0xec41f7da,
		0xe54ffcd7,
		0xfe5de1c0,
		0xf753eacd,
		0xc879dbee,
		0xc177d0e3,
		0xda65cdf4,
		0xd36bc6f9,
		0xa431afb2,
		0xad3fa4bf,
		0xb62db9a8,
		0xbf23b2a5,
		0x80098386,
		0x8907888b,
		0x9215959c,
		0x9b1b9e91,
		0x7ca1470a,
		0x75af4c07,
		0x6ebd5110,
		0x67b35a1d,
		0x58996b3e,
		0x51976033,
		0x4a857d24,
		0x438b7629,
		0x34d11f62,
		0x3ddf146f,
		0x26cd0978,
		0x2fc30275,
		0x10e93356,
		0x19e7385b,
		0x02f5254c,
		0x0bfb2e41,
		0xd79a8c61,
		0xde94876c,
		0xc5869a7b,
		0xcc889176,
		0xf3a2a055,
		0xfaacab58,
		0xe1beb64f,
		0xe8b0bd42,
		0x9fead409,
		0x96e4df04,
		0x8df6c213,
		0x84f8c91e,
		0xbbd2f83d,
		0xb2dcf330,
		0xa9ceee27,
		0xa0c0e52a,
		0x477a3cb1,
		0x4e7437bc,
		0x55662aab,
		0x5c6821a6,
		0x63421085,
		0x6a4c1b88,
		0x715e069f,
		0x78500d92,
		0x0f0a64d9,
		0x06046fd4,
		0x1d1672c3,
		0x141879ce,
		0x2b3248ed,
		0x223c43e0,
		0x392e5ef7,
		0x302055fa,
		0x9aec01b7,
		0x93e20aba,
		0x88f017ad,
		0x81fe1ca0,
		0xbed42d83,
		0xb7da268e,
		0xacc83b99,
		0xa5c63094,
		0xd29c59df,
		0xdb9252d2,
		0xc0804fc5,
		0xc98e44c8,
		0xf6a475eb,
		0xffaa7ee6,
		0xe4b863f1,
		0xedb668fc,
		0x0a0cb167,
		0x0302ba6a,
		0x1810a77d,
		0x111eac70,
		0x2e349d53,
		0x273a965e,
		0x3c288b49,
		0x35268044,
		0x427ce90f,
		0x4b72e202,
		0x5060ff15,
		0x596ef418,
		0x6644c53b,
		0x6f4ace36,
		0x7458d321,
		0x7d56d82c,
		0xa1377a0c,
		0xa8397101,
		0xb32b6c16,
		0xba25671b,
		0x850f5638,
		0x8c015d35,
		0x97134022,
		0x9e1d4b2f,
		0xe9472264,
		0xe0492969,
		0xfb5b347e,
		0xf2553f73,
		0xcd7f0e50,
		0xc471055d,
		0xdf63184a,
		0xd66d1347,
		0x31d7cadc,
		0x38d9c1d1,
		0x23cbdcc6,
		0x2ac5d7cb,
		0x15efe6e8,
		0x1ce1ede5,
		0x07f3f0f2,
		0x0efdfbff,
		0x79a792b4,
		0x70a999b9,
		0x6bbb84ae,
		0x62b58fa3,
		0x5d9fbe80,
		0x5491b58d,
		0x4f83a89a,
		0x468da397,
	},
	{
		0x00000000,
		0x0e0b0d09,
		0x1c161a12,
		0x121d171b,
		0x382c3424,
		0x3627392d,
		0x243a2e36,
		0x2a31233f,
		0x70586848,
		0x7e536541,
		0x6c4e725a,
		0x62457f53,
		0x48745c6c,
		0x467f5165,
		0x5462467e,
		0x5a694b77,
		0xe0b0d090,
		0xeebbdd99,
		0xfca6ca82,
		0xf2adc78b,
		0xd89ce4b4,
		0xd697e9bd,
		0xc48afea6,
		0xca81f3af,
		0x90e8b8d8,
		0x9ee3b5d1,
		0x8cfea2ca,
		0x82f5afc3,
		0xa8c48cfc,
		0xa6cf81f5,
		0xb4d296ee,
		0xbad99be7,
		0xdb7bbb3b,
		0xd570b632,
		0xc76da129,
		0xc966ac20,
		0xe3578f1f,
		0xed5c8216,
		0xff41950d,
		0xf14a9804,
		0xab23d373,
		0xa528de7a,
		0xb735c961,
		0xb93ec468,
		0x930fe757,
		0x9d04ea5e,
		0x8f19fd45,
		0x8112f04c,
		0x3bcb6bab,
		0x35c066a2,
		0x27dd71b9,
		0x29d67cb0,
		0x03e75f8f,
		0x0dec5286,
		0x1ff1459d,
		0x11fa4894,
		0x4b9303e3,
		0x45980eea,
		0x578519f1,
		0x598e14f8,
		0x73bf37c7,
		0x7db43ace,
		0x6fa92dd5,
		0x61a220dc,
		0xadf66d76,
		0xa3fd607f,
		0xb1e07764,
		0xbfeb7a6d,
		0x95da5952,
		0x9bd1545b,
		0x89cc4340,
		0x87c74e49,
		0xddae053e,
		0xd3a50837,
		0xc1b81f2c,
		0xcfb31225,
		0xe582311a,
		0xeb893c13,
		0xf9942b08,
		0xf79f2601,
		0x4d46bde6,
		0x434db0ef,
		0x5150a7f4,
		0x5f5baafd,
		0x756a89c2,
		0x7b6184cb,
		0x697c93d0,
		0x67779ed9,
		0x3d1ed5ae,
		0x3315d8a7,
		0x2108cfbc,
		0x2f03c2b5,
		0x0532e18a,
		0x0b39ec83,
		0x1924fb98,
		0x172ff691,
		0x768dd64d,
		0x7886db44,
		0x6a9bcc5f,
		0x6490c156,
		0x4ea1e269,
		0x40aaef60,
		0x52b7f87b,
		0x5cbcf572,
		0x06d5be05,
		0x08deb30c,
		0x1ac3a417,
		0x14c8a91e,
		0x3ef98a21,
		0x30f28728,
		0x22ef9033,
		0x2ce49d3a,
		0x963d06dd,
		0x98360bd4,
		0x8a2b1ccf,
		0x842011c6,
		0xae1132f9,
		0xa01a3ff0,
		0xb20728eb,
		0xbc0c25e2,
		0xe6656e95,
		0xe86e639c,
		0xfa737487,
		0xf478798e,
		0xde495ab1,
		0xd04257b8,
		0xc25f40a3,
		0xcc544daa,
		0x41f7daec,
		0x4ffcd7e5,
		0x5de1c0fe,
		0x53eacdf7,
		0x79dbeec8,
		0x77d0e3c1,
		0x65cdf4da,
		0x6bc6f9d3,
		0x31afb2a4,
		0x3fa4bfad,
		0x2db9a8b6,
		0x23b2a5bf,
		0x09838680,
		0x07888b89,
		0x15959c92,
		0x1b9e919b,
		0xa1470a7c,
		0xaf4c0775,
		0xbd51106e,
		0xb35a1d67,
		0x996b3e58,
		0x97603351,
		0x857d244a,
		0x8b762943,
		0xd11f6234,
		0xdf146f3d,
		0xcd097826,
		0xc302752f,
		0xe9335610,
		0xe7385b19,
		0xf5254c02,
		0xfb2e410b,
		0x9a8c61d7,
		0x94876cde,
		0x869a7bc5,
		0x889176cc,
		0xa2a055f3,
		0xacab58fa,
		0xbeb64fe1,
		0xb0bd42e8,
		0xead4099f,
		0xe4df0496,
		0xf6c2138d,
		0xf8c91e84,
		0xd2f83dbb,
		0xdcf330b2,
		0xceee27a9,
		0xc0e52aa0,
		0x7a3cb147,
		0x7437bc4e,
		0x662aab55,
		0x6821a65c,
		0x42108563,
		0x4c1b886a,
		0x5e069f71,
		0x500d9278,
		0x0a64d90f,
		0x046fd406,
		0x1672c31d,
		0x1879ce14,
		0x3248ed2b,
		0x3c43e022,
		0x2e5ef739,
		0x2055fa30,
		0xec01b79a,
		0xe20aba93,
		0xf017ad88,
		0xfe1ca081,
		0xd42d83be,
		0xda268eb7,
		0xc83b99ac,
		0xc63094a5,
		0x9c59dfd2,
		0x9252d2db,
		0x804fc5c0,
		0x8e44c8c9,
		0xa475ebf6,
		0xaa7ee6ff,
		0xb863f1e4,
		0xb668fced,
		0x0cb1670a,
		0x02ba6a03,
		0x10a77d18,
		0x1eac7011,
		0x349d532e,
		0x3a965e27,
		0x288b493c,
		0x26804435,
		0x7ce90f42,
		0x72e2024b,
		0x60ff1550,
		0x6ef41859,
		0x44c53b66,
		0x4ace366f,
		0x58d32174,
		0x56d82c7d,
		0x377a0ca1,
		0x397101a8,
		0x2b6c16b3,
		0x25671bba,
		0x0f563885,
		0x015d358c,
		0x13402297,
		0x1d4b2f9e,
		0x472264e9,
		0x492969e0,
		0x5b347efb,
		0x553f73f2,
		0x7f0e50cd,
		0x71055dc4,
		0x63184adf,
		0x6d1347d6,
		0xd7cadc31,
		0xd9c1d138,
		0xcbdcc623,
		0xc5d7cb2a,
		0xefe6e815,
		0xe1ede51c,
		0xf3f0f207,
		0xfdfbff0e,
		0xa792b479,
		0xa999b970,
		0xbb84ae6b,
		0xb58fa362,
		0x9fbe805d,
		0x91b58d54,
		0x83a89a4f,
		0x8da39746,
	},
};


// Tables for main encryption iterations.
const Word AESEncryptTable[4][256] =
{
	{
		0xa56363c6,
		0x847c7cf8,
		0x997777ee,
		0x8d7b7bf6,
		0x0df2f2ff,
		0xbd6b6bd6,
		0xb16f6fde,
		0x54c5c591,
		0x50303060,
		0x03010102,
		0xa96767ce,
		0x7d2b2b56,
		0x19fefee7,
		0x62d7d7b5,
		0xe6abab4d,
		0x9a7676ec,
		0x45caca8f,
		0x9d82821f,
		0x40c9c989,
		0x877d7dfa,
		0x15fafaef,
		0xeb5959b2,
		0xc947478e,
		0x0bf0f0fb,
		0xecadad41,
		0x67d4d4b3,
		0xfda2a25f,
		0xeaafaf45,
		0xbf9c9c23,
		0xf7a4a453,
		0x967272e4,
		0x5bc0c09b,
		0xc2b7b775,
		0x1cfdfde1,
		0xae93933d,
		0x6a26264c,
		0x5a36366c,
		0x413f3f7e,
		0x02f7f7f5,
		0x4fcccc83,
		0x5c343468,
		0xf4a5a551,
		0x34e5e5d1,
		0x08f1f1f9,
		0x937171e2,
		0x73d8d8ab,
		0x53313162,
		0x3f15152a,
		0x0c040408,
		0x52c7c795,
		0x65232346,
		0x5ec3c39d,
		0x28181830,
		0xa1969637,
		0x0f05050a,
		0xb59a9a2f,
		0x0907070e,
		0x36121224,
		0x9b80801b,
		0x3de2e2df,
		0x26ebebcd,
		0x6927274e,
		0xcdb2b27f,
		0x9f7575ea,
		0x1b090912,
		0x9e83831d,
		0x742c2c58,
		0x2e1a1a34,
		0x2d1b1b36,
		0xb26e6edc,
		0xee5a5ab4,
		0xfba0a05b,
		0xf65252a4,
		0x4d3b3b76,
		0x61d6d6b7,
		0xceb3b37d,
		0x7b292952,
		0x3ee3e3dd,
		0x712f2f5e,
		0x97848413,
		0xf55353a6,
		0x68d1d1b9,
		0x00000000,
		0x2cededc1,
		0x60202040,
		0x1ffcfce3,
		0xc8b1b179,
		0xed5b5bb6,
		0xbe6a6ad4,
		0x46cbcb8d,
		0xd9bebe67,
		0x4b393972,
		0xde4a4a94,
		0xd44c4c98,
		0xe85858b0,
		0x4acfcf85,
		0x6bd0d0bb,
		0x2aefefc5,
		0xe5aaaa4f,
		0x16fbfbed,
		0xc5434386,
		0xd74d4d9a,
		0x55333366,
		0x94858511,
		0xcf45458a,
		0x10f9f9e9,
		0x06020204,
		0x817f7ffe,
		0xf05050a0,
		0x443c3c78,
		0xba9f9f25,
		0xe3a8a84b,
		0xf35151a2,
		0xfea3a35d,
		0xc0404080,
		0x8a8f8f05,
		0xad92923f,
		0xbc9d9d21,
		0x48383870,
		0x04f5f5f1,
		0xdfbcbc63,
		0xc1b6b677,
		0x75dadaaf,
		0x63212142,
		0x30101020,
		0x1affffe5,
		0x0ef3f3fd,
		0x6dd2d2bf,
		0x4ccdcd81,
		0x140c0c18,
		0x35131326,
		0x2fececc3,
		0xe15f5fbe,
		0xa2979735,
		0xcc444488,
		0x3917172e,
		0x57c4c493,
		0xf2a7a755,
		0x827e7efc,
		0x473d3d7a,
		0xac6464c8,
		0xe75d5dba,
		0x2b191932,
		0x957373e6,
		0xa06060c0,
		0x98818119,
		0xd14f4f9e,
		0x7fdcdca3,
		0x66222244,
		0x7e2a2a54,
		0xab90903b,
		0x8388880b,
		0xca46468c,
		0x29eeeec7,
		0xd3b8b86b,
		0x3c141428,
		0x79dedea7,
		0xe25e5ebc,
		0x1d0b0b16,
		0x76dbdbad,
		0x3be0e0db,
		0x56323264,
		0x4e3a3a74,
		0x1e0a0a14,
		0xdb494992,
		0x0a06060c,
		0x6c242448,
		0xe45c5cb8,
		0x5dc2c29f,
		0x6ed3d3bd,
		0xefacac43,
		0xa66262c4,
		0xa8919139,
		0xa4959531,
		0x37e4e4d3,
		0x8b7979f2,
		0x32e7e7d5,
		0x43c8c88b,
		0x5937376e,
		0xb76d6dda,
		0x8c8d8d01,
		0x64d5d5b1,
		0xd24e4e9c,
		0xe0a9a949,
		0xb46c6cd8,
		0xfa5656ac,
		0x07f4f4f3,
		0x25eaeacf,
		0xaf6565ca,
		0x8e7a7af4,
		0xe9aeae47,
		0x18080810,
		0xd5baba6f,
		0x887878f0,
		0x6f25254a,
		0x722e2e5c,
		0x241c1c38,
		0xf1a6a657,
		0xc7b4b473,
		0x51c6c697,
		0x23e8e8cb,
		0x7cdddda1,
		0x9c7474e8,
		0x211f1f3e,
		0xdd4b4b96,
		0xdcbdbd61,
		0x868b8b0d,
		0x858a8a0f,
		0x907070e0,
		0x423e3e7c,
		0xc4b5b571,
		0xaa6666cc,
		0xd8484890,
		0x05030306,
		0x01f6f6f7,
		0x120e0e1c,
		0xa36161c2,
		0x5f35356a,
		0xf95757ae,
		0xd0b9b969,
		0x91868617,
		0x58c1c199,
		0x271d1d3a,
		0xb99e9e27,
		0x38e1e1d9,
		0x13f8f8eb,
		0xb398982b,
		0x33111122,
		0xbb6969d2,
		0x70d9d9a9,
		0x898e8e07,
		0xa7949433,
		0xb69b9b2d,
		0x221e1e3c,
		0x92878715,
		0x20e9e9c9,
		0x49cece87,
		0xff5555aa,
		0x78282850,
		0x7adfdfa5,
		0x8f8c8c03,
		0xf8a1a159,
		0x80898909,
		0x170d0d1a,
		0xdabfbf65,
		0x31e6e6d7,
		0xc6424284,
		0xb86868d0,
		0xc3414182,
		0xb0999929,
		0x772d2d5a,
		0x110f0f1e,
		0xcbb0b07b,
		0xfc5454a8,
		0xd6bbbb6d,
		0x3a16162c,
	},
	{
		0x6363c6a5,
		0x7c7cf884,
		0x7777ee99,
		0x7b7bf68d,
		0xf2f2ff0d,
		0x6b6bd6bd,
		0x6f6fdeb1,
		0xc5c59154,
		0x30306050,
		0x01010203,
		0x6767cea9,
		0x2b2b567d,
		0xfefee719,
		0xd7d7b562,
		0xabab4de6,
		0x7676ec9a,
		0xcaca8f45,
		0x82821f9d,
		0xc9c98940,
		0x7d7dfa87,
		0xfafaef15,
		0x5959b2eb,
		0x47478ec9,
		0xf0f0fb0b,
		0xadad41ec,
		0xd4d4b367,
		0xa2a25ffd,
		0xafaf45ea,
		0x9c9c23bf,
		0xa4a453f7,
		0x7272e496,
		0xc0c09b5b,
		0xb7b775c2,
		0xfdfde11c,
		0x93933dae,
		0x26264c6a,
		0x36366c5a,
		0x3f3f7e41,
		0xf7f7f502,
		0xcccc834f,
		0x3434685c,
		0xa5a551f4,
		0xe5e5d134,
		0xf1f1f908,
		0x7171e293,
		0xd8d8ab73,
		0x31316253,
		0x15152a3f,
		0x0404080c,
		0xc7c79552,
		0x23234665,
		0xc3c39d5e,
		0x18183028,
		0x969637a1,
		0x05050a0f,
		0x9a9a2fb5,
		0x07070e09,
		0x12122436,
		0x80801b9b,
		0xe2e2df3d,
		0xebebcd26,
		0x27274e69,
		0xb2b27fcd,
		0x7575ea9f,
		0x0909121b,
		0x83831d9e,
		0x2c2c5874,
		0x1a1a342e,
		0x1b1b362d,
		0x6e6edcb2,
		0x5a5ab4ee,
		0xa0a05bfb,
		0x5252a4f6,
		0x3b3b764d,
		0xd6d6b761,
		0xb3b37dce,
		0x2929527b,
		0xe3e3dd3e,
		0x2f2f5e71,
		0x84841397,
		0x5353a6f5,
		0xd1d1b968,
		0x00000000,
		0xededc12c,
		0x20204060,
		0xfcfce31f,
		0xb1b179c8,
		0x5b5bb6ed,
		0x6a6ad4be,
		0xcbcb8d46,
		0xbebe67d9,
		0x3939724b,
		0x4a4a94de,
		0x4c4c98d4,
		0x5858b0e8,
		0xcfcf854a,
		0xd0d0bb6b,
		0xefefc52a,
		0xaaaa4fe5,
		0xfbfbed16,
		0x434386c5,
		0x4d4d9ad7,
		0x33336655,
		0x85851194,
		0x45458acf,
		0xf9f9e910,
		0x02020406,
		0x7f7ffe81,
		0x5050a0f0,
		0x3c3c7844,
		0x9f9f25ba,
		0xa8a84be3,
		0x5151a2f3,
		0xa3a35dfe,
		0x404080c0,
		0x8f8f058a,
		0x92923fad,
		0x9d9d21bc,
		0x38387048,
		0xf5f5f104,
		0xbcbc63df,
		0xb6b677c1,
		0xdadaaf75,
		0x21214263,
		0x10102030,
		0xffffe51a,
		0xf3f3fd0e,
		0xd2d2bf6d,
		0xcdcd814c,
		0x0c0c1814,
		0x13132635,
		0xececc32f,
		0x5f5fbee1,
		0x979735a2,
		0x444488cc,
		0x17172e39,
		0xc4c49357,
		0xa7a755f2,
		0x7e7efc82,
		0x3d3d7a47,
		0x6464c8ac,
		0x5d5dbae7,
		0x1919322b,
		0x7373e695,
		0x6060c0a0,
		0x81811998,
		0x4f4f9ed1,
		0xdcdca37f,
		0x22224466,
		0x2a2a547e,
		0x90903bab,
		0x88880b83,
		0x46468cca,
		0xeeeec729,
		0xb8b86bd3,
		0x1414283c,
		0xdedea779,
		0x5e5ebce2,
		0x0b0b161d,
		0xdbdbad76,
		0xe0e0db3b,
		0x32326456,
		0x3a3a744e,
		0x0a0a141e,
		0x494992db,
		0x06060c0a,
		0x2424486c,
		0x5c5cb8e4,
		0xc2c29f5d,
		0xd3d3bd6e,
		0xacac43ef,
		0x6262c4a6,
		0x919139a8,
		0x959531a4,
		0xe4e4d337,
		0x7979f28b,
		0xe7e7d532,
		0xc8c88b43,
		0x37376e59,
		0x6d6ddab7,
		0x8d8d018c,
		0xd5d5b164,
		0x4e4e9cd2,
		0xa9a949e0,
		0x6c6cd8b4,
		0x5656acfa,
		0xf4f4f307,
		0xeaeacf25,
		0x6565caaf,
		0x7a7af48e,
		0xaeae47e9,
		0x08081018,
		0xbaba6fd5,
		0x7878f088,
		0x25254a6f,
		0x2e2e5c72,
		0x1c1c3824,
		0xa6a657f1,
		0xb4b473c7,
		0xc6c69751,
		0xe8e8cb23,
		0xdddda17c,
		0x7474e89c,
		0x1f1f3e21,
		0x4b4b96dd,
		0xbdbd61dc,
		0x8b8b0d86,
		0x8a8a0f85,
		0x7070e090,
		0x3e3e7c42,
		0xb5b571c4,
		0x6666ccaa,
		0x484890d8,
		0x03030605,
		0xf6f6f701,
		0x0e0e1c12,
		0x6161c2a3,
		0x35356a5f,
		0x5757aef9,
		0xb9b969d0,
		0x86861791,
		0xc1c19958,
		0x1d1d3a27,
		0x9e9e27b9,
		0xe1e1d938,
		0xf8f8eb13,
		0x98982bb3,
		0x11112233,
		0x6969d2bb,
		0xd9d9a970,
		0x8e8e0789,
		0x949433a7,
		0x9b9b2db6,
		0x1e1e3c22,
		0x87871592,
		0xe9e9c920,
		0xcece8749,
		0x5555aaff,
		0x28285078,
		0xdfdfa57a,
		0x8c8c038f,
		0xa1a159f8,
		0x89890980,
		0x0d0d1a17,
		0xbfbf65da,
		0xe6e6d731,
		0x424284c6,
		0x6868d0b8,
		0x414182c3,
		0x999929b0,
		0x2d2d5a77,
		0x0f0f1e11,
		0xb0b07bcb,
		0x5454a8fc,
		0xbbbb6dd6,
		0x16162c3a,
	},
	{
		0x63c6a563,
		0x7cf8847c,
		0x77ee9977,
		0x7bf68d7b,
		0xf2ff0df2,
		0x6bd6bd6b,
		0x6fdeb16f,
		0xc59154c5,
		0x30605030,
		0x01020301,
		0x67cea967,
		0x2b567d2b,
		0xfee719fe,
		0xd7b562d7,
		0xab4de6ab,
		0x76ec9a76,
		0xca8f45ca,
		0x821f9d82,
		0xc98940c9,
		0x7dfa877d,
		0xfaef15fa,
		0x59b2eb59,
		0x478ec947,
		0xf0fb0bf0,
		0xad41ecad,
		0xd4b367d4,
		0xa25ffda2,
		0xaf45eaaf,
		0x9c23bf9c,
		0xa453f7a4,
		0x72e49672,
		0xc09b5bc0,
		0xb775c2b7,
		0xfde11cfd,
		0x933dae93,
		0x264c6a26,
		0x366c5a36,
		0x3f7e413f,
		0xf7f502f7,
		0xcc834fcc,
		0x34685c34,
		0xa551f4a5,
		0xe5d134e5,
		0xf1f908f1,
		0x71e29371,
		0xd8ab73d8,
		0x31625331,
		0x152a3f15,
		0x04080c04,
		0xc79552c7,
		0x23466523,
		0xc39d5ec3,
		0x18302818,
		0x9637a196,
		0x050a0f05,
		0x9a2fb59a,
		0x070e0907,
		0x12243612,
		0x801b9b80,
		0xe2df3de2,
		0xebcd26eb,
		0x274e6927,
		0xb27fcdb2,
		0x75ea9f75,
		0x09121b09,
		0x831d9e83,
		0x2c58742c,
		0x1a342e1a,
		0x1b362d1b,
		0x6edcb26e,
		0x5ab4ee5a,
		0xa05bfba0,
		0x52a4f652,
		0x3b764d3b,
		0xd6b761d6,
		0xb37dceb3,
		0x29527b29,
		0xe3dd3ee3,
		0x2f5e712f,
		0x84139784,
		0x53a6f553,
		0xd1b968d1,
		0x00000000,
		0xedc12ced,
		0x20406020,
		0xfce31ffc,
		0xb179c8b1,
		0x5bb6ed5b,
		0x6ad4be6a,
		0xcb8d46cb,
		0xbe67d9be,
		0x39724b39,
		0x4a94de4a,
		0x4c98d44c,
		0x58b0e858,
		0xcf854acf,
		0xd0bb6bd0,
		0xefc52aef,
		0xaa4fe5aa,
		0xfbed16fb,
		0x4386c543,
		0x4d9ad74d,
		0x33665533,
		0x85119485,
		0x458acf45,
		0xf9e910f9,
		0x02040602,
		0x7ffe817f,
		0x50a0f050,
		0x3c78443c,
		0x9f25ba9f,
		0xa84be3a8,
		0x51a2f351,
		0xa35dfea3,
		0x4080c040,
		0x8f058a8f,
		0x923fad92,
		0x9d21bc9d,
		0x38704838,
		0xf5f104f5,
		0xbc63dfbc,
		0xb677c1b6,
		0xdaaf75da,
		0x21426321,
		0x10203010,
		0xffe51aff,
		0xf3fd0ef3,
		0xd2bf6dd2,
		0xcd814ccd,
		0x0c18140c,
		0x13263513,
		0xecc32fec,
		0x5fbee15f,
		0x9735a297,
		0x4488cc44,
		0x172e3917,
		0xc49357c4,
		0xa755f2a7,
		0x7efc827e,
		0x3d7a473d,
		0x64c8ac64,
		0x5dbae75d,
		0x19322b19,
		0x73e69573,
		0x60c0a060,
		0x81199881,
		0x4f9ed14f,
		0xdca37fdc,
		0x22446622,
		0x2a547e2a,
		0x903bab90,
		0x880b8388,
		0x468cca46,
		0xeec729ee,
		0xb86bd3b8,
		0x14283c14,
		0xdea779de,
		0x5ebce25e,
		0x0b161d0b,
		0xdbad76db,
		0xe0db3be0,
		0x32645632,
		0x3a744e3a,
		0x0a141e0a,
		0x4992db49,
		0x060c0a06,
		0x24486c24,
		0x5cb8e45c,
		0xc29f5dc2,
		0xd3bd6ed3,
		0xac43efac,
		0x62c4a662,
		0x9139a891,
		0x9531a495,
		0xe4d337e4,
		0x79f28b79,
		0xe7d532e7,
		0xc88b43c8,
		0x376e5937,
		0x6ddab76d,
		0x8d018c8d,
		0xd5b164d5,
		0x4e9cd24e,
		0xa949e0a9,
		0x6cd8b46c,
		0x56acfa56,
		0xf4f307f4,
		0xeacf25ea,
		0x65caaf65,
		0x7af48e7a,
		0xae47e9ae,
		0x08101808,
		0xba6fd5ba,
		0x78f08878,
		0x254a6f25,
		0x2e5c722e,
		0x1c38241c,
		0xa657f1a6,
		0xb473c7b4,
		0xc69751c6,
		0xe8cb23e8,
		0xdda17cdd,
		0x74e89c74,
		0x1f3e211f,
		0x4b96dd4b,
		0xbd61dcbd,
		0x8b0d868b,
		0x8a0f858a,
		0x70e09070,
		0x3e7c423e,
		0xb571c4b5,
		0x66ccaa66,
		0x4890d848,
		0x03060503,
		0xf6f701f6,
		0x0e1c120e,
		0x61c2a361,
		0x356a5f35,
		0x57aef957,
		0xb969d0b9,
		0x86179186,
		0xc19958c1,
		0x1d3a271d,
		0x9e27b99e,
		0xe1d938e1,
		0xf8eb13f8,
		0x982bb398,
		0x11223311,
		0x69d2bb69,
		0xd9a970d9,
		0x8e07898e,
		0x9433a794,
		0x9b2db69b,
		0x1e3c221e,
		0x87159287,
		0xe9c920e9,
		0xce8749ce,
		0x55aaff55,
		0x28507828,
		0xdfa57adf,
		0x8c038f8c,
		0xa159f8a1,
		0x89098089,
		0x0d1a170d,
		0xbf65dabf,
		0xe6d731e6,
		0x4284c642,
		0x68d0b868,
		0x4182c341,
		0x9929b099,
		0x2d5a772d,
		0x0f1e110f,
		0xb07bcbb0,
		0x54a8fc54,
		0xbb6dd6bb,
		0x162c3a16,
	},
	{
		0xc6a56363,
		0xf8847c7c,
		0xee997777,
		0xf68d7b7b,
		0xff0df2f2,
		0xd6bd6b6b,
		0xdeb16f6f,
		0x9154c5c5,
		0x60503030,
		0x02030101,
		0xcea96767,
		0x567d2b2b,
		0xe719fefe,
		0xb562d7d7,
		0x4de6abab,
		0xec9a7676,
		0x8f45caca,
		0x1f9d8282,
		0x8940c9c9,
		0xfa877d7d,
		0xef15fafa,
		0xb2eb5959,
		0x8ec94747,
		0xfb0bf0f0,
		0x41ecadad,
		0xb367d4d4,
		0x5ffda2a2,
		0x45eaafaf,
		0x23bf9c9c,
		0x53f7a4a4,
		0xe4967272,
		0x9b5bc0c0,
		0x75c2b7b7,
		0xe11cfdfd,
		0x3dae9393,
		0x4c6a2626,
		0x6c5a3636,
		0x7e413f3f,
		0xf502f7f7,
		0x834fcccc,
		0x685c3434,
		0x51f4a5a5,
		0xd134e5e5,
		0xf908f1f1,
		0xe2937171,
		0xab73d8d8,
		0x62533131,
		0x2a3f1515,
		0x080c0404,
		0x9552c7c7,
		0x46652323,
		0x9d5ec3c3,
		0x30281818,
		0x37a19696,
		0x0a0f0505,
		0x2fb59a9a,
		0x0e090707,
		0x24361212,
		0x1b9b8080,
		0xdf3de2e2,
		0xcd26ebeb,
		0x4e692727,
		0x7fcdb2b2,
		0xea9f7575,
		0x121b0909,
		0x1d9e8383,
		0x58742c2c,
		0x342e1a1a,
		0x362d1b1b,
		0xdcb26e6e,
		0xb4ee5a5a,
		0x5bfba0a0,
		0xa4f65252,
		0x764d3b3b,
		0xb761d6d6,
		0x7dceb3b3,
		0x527b2929,
		0xdd3ee3e3,
		0x5e712f2f,
		0x13978484,
		0xa6f55353,
		0xb968d1d1,
		0x00000000,
		0xc12ceded,
		0x40602020,
		0xe31ffcfc,
		0x79c8b1b1,
		0xb6ed5b5b,
		0xd4be6a6a,
		0x8d46cbcb,
		0x67d9bebe,
		0x724b3939,
		0x94de4a4a,
		0x98d44c4c,
		0xb0e85858,
		0x854acfcf,
		0xbb6bd0d0,
		0xc52aefef,
		0x4fe5aaaa,
		0xed16fbfb,
		0x86c54343,
		0x9ad74d4d,
		0x66553333,
		0x11948585,
		0x8acf4545,
		0xe910f9f9,
		0x04060202,
		0xfe817f7f,
		0xa0f05050,
		0x78443c3c,
		0x25ba9f9f,
		0x4be3a8a8,
		0xa2f35151,
		0x5dfea3a3,
		0x80c04040,
		0x058a8f8f,
		0x3fad9292,
		0x21bc9d9d,
		0x70483838,
		0xf104f5f5,
		0x63dfbcbc,
		0x77c1b6b6,
		0xaf75dada,
		0x42632121,
		0x20301010,
		0xe51affff,
		0xfd0ef3f3,
		0xbf6dd2d2,
		0x814ccdcd,
		0x18140c0c,
		0x26351313,
		0xc32fecec,
		0xbee15f5f,
		0x35a29797,
		0x88cc4444,
		0x2e391717,
		0x9357c4c4,
		0x55f2a7a7,
		0xfc827e7e,
		0x7a473d3d,
		0xc8ac6464,
		0xbae75d5d,
		0x322b1919,
		0xe6957373,
		0xc0a06060,
		0x19988181,
		0x9ed14f4f,
		0xa37fdcdc,
		0x44662222,
		0x547e2a2a,
		0x3bab9090,
		0x0b838888,
		0x8cca4646,
		0xc729eeee,
		0x6bd3b8b8,
		0x283c1414,
		0xa779dede,
		0xbce25e5e,
		0x161d0b0b,
		0xad76dbdb,
		0xdb3be0e0,
		0x64563232,
		0x744e3a3a,
		0x141e0a0a,
		0x92db4949,
		0x0c0a0606,
		0x486c2424,
		0xb8e45c5c,
		0x9f5dc2c2,
		0xbd6ed3d3,
		0x43efacac,
		0xc4a66262,
		0x39a89191,
		0x31a49595,
		0xd337e4e4,
		0xf28b7979,
		0xd532e7e7,
		0x8b43c8c8,
		0x6e593737,
		0xdab76d6d,
		0x018c8d8d,
		0xb164d5d5,
		0x9cd24e4e,
		0x49e0a9a9,
		0xd8b46c6c,
		0xacfa5656,
		0xf307f4f4,
		0xcf25eaea,
		0xcaaf6565,
		0xf48e7a7a,
		0x47e9aeae,
		0x10180808,
		0x6fd5baba,
		0xf0887878,
		0x4a6f2525,
		0x5c722e2e,
		0x38241c1c,
		0x57f1a6a6,
		0x73c7b4b4,
		0x9751c6c6,
		0xcb23e8e8,
		0xa17cdddd,
		0xe89c7474,
		0x3e211f1f,
		0x96dd4b4b,
		0x61dcbdbd,
		0x0d868b8b,
		0x0f858a8a,
		0xe0907070,
		0x7c423e3e,
		0x71c4b5b5,
		0xccaa6666,
		0x90d84848,
		0x06050303,
		0xf701f6f6,
		0x1c120e0e,
		0xc2a36161,
		0x6a5f3535,
		0xaef95757,
		0x69d0b9b9,
		0x17918686,
		0x9958c1c1,
		0x3a271d1d,
		0x27b99e9e,
		0xd938e1e1,
		0xeb13f8f8,
		0x2bb39898,
		0x22331111,
		0xd2bb6969,
		0xa970d9d9,
		0x07898e8e,
		0x33a79494,
		0x2db69b9b,
		0x3c221e1e,
		0x15928787,
		0xc920e9e9,
		0x8749cece,
		0xaaff5555,
		0x50782828,
		0xa57adfdf,
		0x038f8c8c,
		0x59f8a1a1,
		0x09808989,
		0x1a170d0d,
		0x65dabfbf,
		0xd731e6e6,
		0x84c64242,
		0xd0b86868,
		0x82c34141,
		0x29b09999,
		0x5a772d2d,
		0x1e110f0f,
		0x7bcbb0b0,
		0xa8fc5454,
		0x6dd6bbbb,
		0x2c3a1616,
	},
};


// Tables for main decryption iterations.
const Word AESDecryptTable[4][256] =
{
	{
		0x50a7f451,
		0x5365417e,
		0xc3a4171a,
		0x965e273a,
		0xcb6bab3b,
		0xf1459d1f,
		0xab58faac,
		0x9303e34b,
		0x55fa3020,
		0xf66d76ad,
		0x9176cc88,
		0x254c02f5,
		0xfcd7e54f,
		0xd7cb2ac5,
		0x80443526,
		0x8fa362b5,
		0x495ab1de,
		0x671bba25,
		0x980eea45,
		0xe1c0fe5d,
		0x02752fc3,
		0x12f04c81,
		0xa397468d,
		0xc6f9d36b,
		0xe75f8f03,
		0x959c9215,
		0xeb7a6dbf,
		0xda595295,
		0x2d83bed4,
		0xd3217458,
		0x2969e049,
		0x44c8c98e,
		0x6a89c275,
		0x78798ef4,
		0x6b3e5899,
		0xdd71b927,
		0xb64fe1be,
		0x17ad88f0,
		0x66ac20c9,
		0xb43ace7d,
		0x184adf63,
		0x82311ae5,
		0x60335197,
		0x457f5362,
		0xe07764b1,
		0x84ae6bbb,
		0x1ca081fe,
		0x942b08f9,
		0x58684870,
		0x19fd458f,
		0x876cde94,
		0xb7f87b52,
		0x23d373ab,
		0xe2024b72,
		0x578f1fe3,
		0x2aab5566,
		0x0728ebb2,
		0x03c2b52f,
		0x9a7bc586,
		0xa50837d3,
		0xf2872830,
		0xb2a5bf23,
		0xba6a0302,
		0x5c8216ed,
		0x2b1ccf8a,
		0x92b479a7,
		0xf0f207f3,
		0xa1e2694e,
		0xcdf4da65,
		0xd5be0506,
		0x1f6234d1,
		0x8afea6c4,
		0x9d532e34,
		0xa055f3a2,
		0x32e18a05,
		0x75ebf6a4,
		0x39ec830b,
		0xaaef6040,
		0x069f715e,
		0x51106ebd,
		0xf98a213e,
		0x3d06dd96,
		0xae053edd,
		0x46bde64d,
		0xb58d5491,
		0x055dc471,
		0x6fd40604,
		0xff155060,
		0x24fb9819,
		0x97e9bdd6,
		0xcc434089,
		0x779ed967,
		0xbd42e8b0,
		0x888b8907,
		0x385b19e7,
		0xdbeec879,
		0x470a7ca1,
		0xe90f427c,
		0xc91e84f8,
		0x00000000,
		0x83868009,
		0x48ed2b32,
		0xac70111e,
		0x4e725a6c,
		0xfbff0efd,
		0x5638850f,
		0x1ed5ae3d,
		0x27392d36,
		0x64d90f0a,
		0x21a65c68,
		0xd1545b9b,
		0x3a2e3624,
		0xb1670a0c,
		0x0fe75793,
		0xd296eeb4,
		0x9e919b1b,
		0x4fc5c080,
		0xa220dc61,
		0x694b775a,
		0x161a121c,
		0x0aba93e2,
		0xe52aa0c0,
		0x43e0223c,
		0x1d171b12,
		0x0b0d090e,
		0xadc78bf2,
		0xb9a8b62d,
		0xc8a91e14,
		0x8519f157,
		0x4c0775af,
		0xbbdd99ee,
		0xfd607fa3,
		0x9f2601f7,
		0xbcf5725c,
		0xc53b6644,
		0x347efb5b,
		0x7629438b,
		0xdcc623cb,
		0x68fcedb6,
		0x63f1e4b8,
		0xcadc31d7,
		0x10856342,
		0x40229713,
		0x2011c684,
		0x7d244a85,
		0xf83dbbd2,
		0x1132f9ae,
		0x6da129c7,
		0x4b2f9e1d,
		0xf330b2dc,
		0xec52860d,
		0xd0e3c177,
		0x6c16b32b,
		0x99b970a9,
		0xfa489411,
		0x2264e947,
		0xc48cfca8,
		0x1a3ff0a0,
		0xd82c7d56,
		0xef903322,
		0xc74e4987,
		0xc1d138d9,
		0xfea2ca8c,
		0x360bd498,
		0xcf81f5a6,
		0x28de7aa5,
		0x268eb7da,
		0xa4bfad3f,
		0xe49d3a2c,
		0x0d927850,
		0x9bcc5f6a,
		0x62467e54,
		0xc2138df6,
		0xe8b8d890,
		0x5ef7392e,
		0xf5afc382,
		0xbe805d9f,
		0x7c93d069,
		0xa92dd56f,
		0xb31225cf,
		0x3b99acc8,
		0xa77d1810,
		0x6e639ce8,
		0x7bbb3bdb,
		0x097826cd,
		0xf418596e,
		0x01b79aec,
		0xa89a4f83,
		0x656e95e6,
		0x7ee6ffaa,
		0x08cfbc21,
		0xe6e815ef,
		0xd99be7ba,
		0xce366f4a,
		0xd4099fea,
		0xd67cb029,
		0xafb2a431,
		0x31233f2a,
		0x3094a5c6,
		0xc066a235,
		0x37bc4e74,
		0xa6ca82fc,
		0xb0d090e0,
		0x15d8a733,
		0x4a9804f1,
		0xf7daec41,
		0x0e50cd7f,
		0x2ff69117,
		0x8dd64d76,
		0x4db0ef43,
		0x544daacc,
		0xdf0496e4,
		0xe3b5d19e,
		0x1b886a4c,
		0xb81f2cc1,
		0x7f516546,
		0x04ea5e9d,
		0x5d358c01,
		0x737487fa,
		0x2e410bfb,
		0x5a1d67b3,
		0x52d2db92,
		0x335610e9,
		0x1347d66d,
		0x8c61d79a,
		0x7a0ca137,
		0x8e14f859,
		0x893c13eb,
		0xee27a9ce,
		0x35c961b7,
		0xede51ce1,
		0x3cb1477a,
		0x59dfd29c,
		0x3f73f255,
		0x79ce1418,
		0xbf37c773,
		0xeacdf753,
		0x5baafd5f,
		0x146f3ddf,
		0x86db4478,
		0x81f3afca,
		0x3ec468b9,
		0x2c342438,
		0x5f40a3c2,
		0x72c31d16,
		0x0c25e2bc,
		0x8b493c28,
		0x41950dff,
		0x7101a839,
		0xdeb30c08,
		0x9ce4b4d8,
		0x90c15664,
		0x6184cb7b,
		0x70b632d5,
		0x745c6c48,
		0x4257b8d0,
	},
	{
		0xa7f45150,
		0x65417e53,
		0xa4171ac3,
		0x5e273a96,
		0x6bab3bcb,
		0x459d1ff1,
		0x58faacab,
		0x03e34b93,
		0xfa302055,
		0x6d76adf6,
		0x76cc8891,
		0x4c02f525,
		0xd7e54ffc,
		0xcb2ac5d7,
		0x44352680,
		0xa362b58f,
		0x5ab1de49,
		0x1bba2567,
		0x0eea4598,
		0xc0fe5de1,
		0x752fc302,
		0xf04c8112,
		0x97468da3,
		0xf9d36bc6,
		0x5f8f03e7,
		0x9c921595,
		0x7a6dbfeb,
		0x595295da,
		0x83bed42d,
		0x217458d3,
		0x69e04929,
		0xc8c98e44,
		0x89c2756a,
		0x798ef478,
		0x3e58996b,
		0x71b927dd,
		0x4fe1beb6,
		0xad88f017,
		0xac20c966,
		0x3ace7db4,
		0x4adf6318,
		0x311ae582,
		0x33519760,
		0x7f536245,
		0x7764b1e0,
		0xae6bbb84,
		0xa081fe1c,
		0x2b08f994,
		0x68487058,
		0xfd458f19,
		0x6cde9487,
		0xf87b52b7,
		0xd373ab23,
		0x024b72e2,
		0x8f1fe357,
		0xab55662a,
		0x28ebb207,
		0xc2b52f03,
		0x7bc5869a,
		0x0837d3a5,
		0x872830f2,
		0xa5bf23b2,
		0x6a0302ba,
		0x8216ed5c,
		0x1ccf8a2b,
		0xb479a792,
		0xf207f3f0,
		0xe2694ea1,
		0xf4da65cd,
		0xbe0506d5,
		0x6234d11f,
		0xfea6c48a,
		0x532e349d,
		0x55f3a2a0,
		0xe18a0532,
		0xebf6a475,
		0xec830b39,
		0xef6040aa,
		0x9f715e06,
		0x106ebd51,
		0x8a213ef9,
		0x06dd963d,
		0x053eddae,
		0xbde64d46,
		0x8d5491b5,
		0x5dc47105,
		0xd406046f,
		0x155060ff,
		0xfb981924,
		0xe9bdd697,
		0x434089cc,
		0x9ed96777,
		0x42e8b0bd,
		0x8b890788,
		0x5b19e738,
		0xeec879db,
		0x0a7ca147,
		0x0f427ce9,
		0x1e84f8c9,
		0x00000000,
		0x86800983,
		0xed2b3248,
		0x70111eac,
		0x725a6c4e,
		0xff0efdfb,
		0x38850f56,
		0xd5ae3d1e,
		0x392d3627,
		0xd90f0a64,
		0xa65c6821,
		0x545b9bd1,
		0x2e36243a,
		0x670a0cb1,
		0xe757930f,
		0x96eeb4d2,
		0x919b1b9e,
		0xc5c0804f,
		0x20dc61a2,
		0x4b775a69,
		0x1a121c16,
		0xba93e20a,
		0x2aa0c0e5,
		0xe0223c43,
		0x171b121d,
		0x0d090e0b,
		0xc78bf2ad,
		0xa8b62db9,
		0xa91e14c8,
		0x19f15785,
		0x0775af4c,
		0xdd99eebb,
		0x607fa3fd,
		0x2601f79f,
		0xf5725cbc,
		0x3b6644c5,
		0x7efb5b34,
		0x29438b76,
		0xc623cbdc,
		0xfcedb668,
		0xf1e4b863,
		0xdc31d7ca,
		0x85634210,
		0x22971340,
		0x11c68420,
		0x244a857d,
		0x3dbbd2f8,
		0x32f9ae11,
		0xa129c76d,
		0x2f9e1d4b,
		0x30b2dcf3,
		0x52860dec,
		0xe3c177d0,
		0x16b32b6c,
		0xb970a999,
		0x489411fa,
		0x64e94722,
		0x8cfca8c4,
		0x3ff0a01a,
		0x2c7d56d8,
		0x903322ef,
		0x4e4987c7,
		0xd138d9c1,
		0xa2ca8cfe,
		0x0bd49836,
		0x81f5a6cf,
		0xde7aa528,
		0x8eb7da26,
		0xbfad3fa4,
		0x9d3a2ce4,
		0x9278500d,
		0xcc5f6a9b,
		0x467e5462,
		0x138df6c2,
		0xb8d890e8,
		0xf7392e5e,
		0xafc382f5,
		0x805d9fbe,
		0x93d0697c,
		0x2dd56fa9,
		0x1225cfb3,
		0x99acc83b,
		0x7d1810a7,
		0x639ce86e,
		0xbb3bdb7b,
		0x7826cd09,
		0x18596ef4,
		0xb79aec01,
		0x9a4f83a8,
		0x6e95e665,
		0xe6ffaa7e,
		0xcfbc2108,
		0xe815efe6,
		0x9be7bad9,
		0x366f4ace,
		0x099fead4,
		0x7cb029d6,
		0xb2a431af,
		0x233f2a31,
		0x94a5c630,
		0x66a235c0,
		0xbc4e7437,
		0xca82fca6,
		0xd090e0b0,
		0xd8a73315,
		0x9804f14a,
		0xdaec41f7,
		0x50cd7f0e,
		0xf691172f,
		0xd64d768d,
		0xb0ef434d,
		0x4daacc54,
		0x0496e4df,
		0xb5d19ee3,
		0x886a4c1b,
		0x1f2cc1b8,
		0x5165467f,
		0xea5e9d04,
		0x358c015d,
		0x7487fa73,
		0x410bfb2e,
		0x1d67b35a,
		0xd2db9252,
		0x5610e933,
		0x47d66d13,
		0x61d79a8c,
		0x0ca1377a,
		0x14f8598e,
		0x3c13eb89,
		0x27a9ceee,
		0xc961b735,
		0xe51ce1ed,
		0xb1477a3c,
		0xdfd29c59,
		0x73f2553f,
		0xce141879,
		0x37c773bf,
		0xcdf753ea,
		0xaafd5f5b,
		0x6f3ddf14,
		0xdb447886,
		0xf3afca81,
		0xc468b93e,
		0x3424382c,
		0x40a3c25f,
		0xc31d1672,
		0x25e2bc0c,
		0x493c288b,
		0x950dff41,
		0x01a83971,
		0xb30c08de,
		0xe4b4d89c,
		0xc1566490,
		0x84cb7b61,
		0xb632d570,
		0x5c6c4874,
		0x57b8d042,
	},
	{
		0xf45150a7,
		0x417e5365,
		0x171ac3a4,
		0x273a965e,
		0xab3bcb6b,
		0x9d1ff145,
		0xfaacab58,
		0xe34b9303,
		0x302055fa,
		0x76adf66d,
		0xcc889176,
		0x02f5254c,
		0xe54ffcd7,
		0x2ac5d7cb,
		0x35268044,
		0x62b58fa3,
		0xb1de495a,
		0xba25671b,
		0xea45980e,
		0xfe5de1c0,
		0x2fc30275,
		0x4c8112f0,
		0x468da397,
		0xd36bc6f9,
		0x8f03e75f,
		0x9215959c,
		0x6dbfeb7a,
		0x5295da59,
		0xbed42d83,
		0x7458d321,
		0xe0492969,
		0xc98e44c8,
		0xc2756a89,
		0x8ef47879,
		0x58996b3e,
		0xb927dd71,
		0xe1beb64f,
		0x88f017ad,
		0x20c966ac,
		0xce7db43a,
		0xdf63184a,
		0x1ae58231,
		0x51976033,
		0x5362457f,
		0x64b1e077,
		0x6bbb84ae,
		0x81fe1ca0,
		0x08f9942b,
		0x48705868,
		0x458f19fd,
		0xde94876c,
		0x7b52b7f8,
		0x73ab23d3,
		0x4b72e202,
		0x1fe3578f,
		0x55662aab,
		0xebb20728,
		0xb52f03c2,
		0xc5869a7b,
		0x37d3a508,
		0x2830f287,
		0xbf23b2a5,
		0x0302ba6a,
		0x16ed5c82,
		0xcf8a2b1c,
		0x79a792b4,
		0x07f3f0f2,
		0x694ea1e2,
		0xda65cdf4,
		0x0506d5be,
		0x34d11f62,
		0xa6c48afe,
		0x2e349d53,
		0xf3a2a055,
		0x8a0532e1,
		0xf6a475eb,
		0x830b39ec,
		0x6040aaef,
		0x715e069f,
		0x6ebd5110,
		0x213ef98a,
		0xdd963d06,
		0x3eddae05,
		0xe64d46bd,
		0x5491b58d,
		0xc471055d,
		0x06046fd4,
		0x5060ff15,
		0x981924fb,
		0xbdd697e9,
		0x4089cc43,
		0xd967779e,
		0xe8b0bd42,
		0x8907888b,
		0x19e7385b,
		0xc879dbee,
		0x7ca1470a,
		0x427ce90f,
		0x84f8c91e,
		0x00000000,
		0x80098386,
		0x2b3248ed,
		0x111eac70,
		0x5a6c4e72,
		0x0efdfbff,
		0x850f5638,
		0xae3d1ed5,
		0x2d362739,
		0x0f0a64d9,
		0x5c6821a6,
		0x5b9bd154,
		0x36243a2e,
		0x0a0cb167,
		0x57930fe7,
		0xeeb4d296,
		0x9b1b9e91,
		0xc0804fc5,
		0xdc61a220,
		0x775a694b,
		0x121c161a,
		0x93e20aba,
		0xa0c0e52a,
		0x223c43e0,
		0x1b121d17,
		0x090e0b0d,
		0x8bf2adc7,
		0xb62db9a8,
		0x1e14c8a9,
		0xf1578519,
		0x75af4c07,
		0x99eebbdd,
		0x7fa3fd60,
		0x01f79f26,
		0x725cbcf5,
		0x6644c53b,
		0xfb5b347e,
		0x438b7629,
		0x23cbdcc6,
		0xedb668fc,
		0xe4b863f1,
		0x31d7cadc,
		0x63421085,
		0x97134022,
		0xc6842011,
		0x4a857d24,
		0xbbd2f83d,
		0xf9ae1132,
		0x29c76da1,
		0x9e1d4b2f,
		0xb2dcf330,
		0x860dec52,
		0xc177d0e3,
		0xb32b6c16,
		0x70a999b9,
		0x9411fa48,
		0xe9472264,
		0xfca8c48c,
		0xf0a01a3f,
		0x7d56d82c,
		0x3322ef90,
		0x4987c74e,
		0x38d9c1d1,
		0xca8cfea2,
		0xd498360b,
		0xf5a6cf81,
		0x7aa528de,
		0xb7da268e,
		0xad3fa4bf,
		0x3a2ce49d,
		0x78500d92,
		0x5f6a9bcc,
		0x7e546246,
		0x8df6c213,
		0xd890e8b8,
		0x392e5ef7,
		0xc382f5af,
		0x5d9fbe80,
		0xd0697c93,
		0xd56fa92d,
		0x25cfb312,
		0xacc83b99,
		0x1810a77d,
		0x9ce86e63,
		0x3bdb7bbb,
		0x26cd0978,
		0x596ef418,
		0x9aec01b7,
		0x4f83a89a,
		0x95e6656e,
		0xffaa7ee6,
		0xbc2108cf,
		0x15efe6e8,
		0xe7bad99b,
		0x6f4ace36,
		0x9fead409,
		0xb029d67c,
		0xa431afb2,
		0x3f2a3123,
		0xa5c63094,
		0xa235c066,
		0x4e7437bc,
		0x82fca6ca,
		0x90e0b0d0,
		0xa73315d8,
		0x04f14a98,
		0xec41f7da,
		0xcd7f0e50,
		0x91172ff6,
		0x4d768dd6,
		0xef434db0,
		0xaacc544d,
		0x96e4df04,
		0xd19ee3b5,
		0x6a4c1b88,
		0x2cc1b81f,
		0x65467f51,
		0x5e9d04ea,
		0x8c015d35,
		0x87fa7374,
		0x0bfb2e41,
		0x67b35a1d,
		0xdb9252d2,
		0x10e93356,
		0xd66d1347,
		0xd79a8c61,
		0xa1377a0c,
		0xf8598e14,
		0x13eb893c,
		0xa9ceee27,
		0x61b735c9,
		0x1ce1ede5,
		0x477a3cb1,
		0xd29c59df,
		0xf2553f73,
		0x141879ce,
		0xc773bf37,
		0xf753eacd,
		0xfd5f5baa,
		0x3ddf146f,
		0x447886db,
		0xafca81f3,
		0x68b93ec4,
		0x24382c34,
		0xa3c25f40,
		0x1d1672c3,
		0xe2bc0c25,
		0x3c288b49,
		0x0dff4195,
		0xa8397101,
		0x0c08deb3,
		0xb4d89ce4,
		0x566490c1,
		0xcb7b6184,
		0x32d570b6,
		0x6c48745c,
		0xb8d04257,
	},
	{
		0x5150a7f4,
		0x7e536541,
		0x1ac3a417,
		0x3a965e27,
		0x3bcb6bab,
		0x1ff1459d,
		0xacab58fa,
		0x4b9303e3,
		0x2055fa30,
		0xadf66d76,
		0x889176cc,
		0xf5254c02,
		0x4ffcd7e5,
		0xc5d7cb2a,
		0x26804435,
		0xb58fa362,
		0xde495ab1,
		0x25671bba,
		0x45980eea,
		0x5de1c0fe,
		0xc302752f,
		0x8112f04c,
		0x8da39746,
		0x6bc6f9d3,
		0x03e75f8f,
		0x15959c92,
		0xbfeb7a6d,
		0x95da5952,
		0xd42d83be,
		0x58d32174,
		0x492969e0,
		0x8e44c8c9,
		0x756a89c2,
		0xf478798e,
		0x996b3e58,
		0x27dd71b9,
		0xbeb64fe1,
		0xf017ad88,
		0xc966ac20,
		0x7db43ace,
		0x63184adf,
		0xe582311a,
		0x97603351,
		0x62457f53,
		0xb1e07764,
		0xbb84ae6b,
		0xfe1ca081,
		0xf9942b08,
		0x70586848,
		0x8f19fd45,
		0x94876cde,
		0x52b7f87b,
		0xab23d373,
		0x72e2024b,
		0xe3578f1f,
		0x662aab55,
		0xb20728eb,
		0x2f03c2b5,
		0x869a7bc5,
		0xd3a50837,
		0x30f28728,
		0x23b2a5bf,
		0x02ba6a03,
		0xed5c8216,
		0x8a2b1ccf,
		0xa792b479,
		0xf3f0f207,
		0x4ea1e269,
		0x65cdf4da,
		0x06d5be05,
		0xd11f6234,
		0xc48afea6,
		0x349d532e,
		0xa2a055f3,
		0x0532e18a,
		0xa475ebf6,
		0x0b39ec83,
		0x40aaef60,
		0x5e069f71,
		0xbd51106e,
		0x3ef98a21,
		0x963d06dd,
		0xddae053e,
		0x4d46bde6,
		0x91b58d54,
		0x71055dc4,
		0x046fd406,
		0x60ff1550,
		0x1924fb98,
		0xd697e9bd,
		0x89cc4340,
		0x67779ed9,
		0xb0bd42e8,
		0x07888b89,
		0xe7385b19,
		0x79dbeec8,
		0xa1470a7c,
		0x7ce90f42,
		0xf8c91e84,
		0x00000000,
		0x09838680,
		0x3248ed2b,
		0x1eac7011,
		0x6c4e725a,
		0xfdfbff0e,
		0x0f563885,
		0x3d1ed5ae,
		0x3627392d,
		0x0a64d90f,
		0x6821a65c,
		0x9bd1545b,
		0x243a2e36,
		0x0cb1670a,
		0x930fe757,
		0xb4d296ee,
		0x1b9e919b,
		0x804fc5c0,
		0x61a220dc,
		0x5a694b77,
		0x1c161a12,
		0xe20aba93,
		0xc0e52aa0,
		0x3c43e022,
		0x121d171b,
		0x0e0b0d09,
		0xf2adc78b,
		0x2db9a8b6,
		0x14c8a91e,
		0x578519f1,
		0xaf4c0775,
		0xeebbdd99,
		0xa3fd607f,
		0xf79f2601,
		0x5cbcf572,
		0x44c53b66,
		0x5b347efb,
		0x8b762943,
		0xcbdcc623,
		0xb668fced,
		0xb863f1e4,
		0xd7cadc31,
		0x42108563,
		0x13402297,
		0x842011c6,
		0x857d244a,
		0xd2f83dbb,
		0xae1132f9,
		0xc76da129,
		0x1d4b2f9e,
		0xdcf330b2,
		0x0dec5286,
		0x77d0e3c1,
		0x2b6c16b3,
		0xa999b970,
		0x11fa4894,
		0x472264e9,
		0xa8c48cfc,
		0xa01a3ff0,
		0x56d82c7d,
		0x22ef9033,
		0x87c74e49,
		0xd9c1d138,
		0x8cfea2ca,
		0x98360bd4,
		0xa6cf81f5,
		0xa528de7a,
		0xda268eb7,
		0x3fa4bfad,
		0x2ce49d3a,
		0x500d9278,
		0x6a9bcc5f,
		0x5462467e,
		0xf6c2138d,
		0x90e8b8d8,
		0x2e5ef739,
		0x82f5afc3,
		0x9fbe805d,
		0x697c93d0,
		0x6fa92dd5,
		0xcfb31225,
		0xc83b99ac,
		0x10a77d18,
		0xe86e639c,
		0xdb7bbb3b,
		0xcd097826,
		0x6ef41859,
		0xec01b79a,
		0x83a89a4f,
		0xe6656e95,
		0xaa7ee6ff,
		0x2108cfbc,
		0xefe6e815,
		0xbad99be7,
		0x4ace366f,
		0xead4099f,
		0x29d67cb0,
		0x31afb2a4,
		0x2a31233f,
		0xc63094a5,
		0x35c066a2,
		0x7437bc4e,
		0xfca6ca82,
		0xe0b0d090,
		0x3315d8a7,
		0xf14a9804,
		0x41f7daec,
		0x7f0e50cd,
		0x172ff691,
		0x768dd64d,
		0x434db0ef,
		0xcc544daa,
		0xe4df0496,
		0x9ee3b5d1,
		0x4c1b886a,
		0xc1b81f2c,
		0x467f5165,
		0x9d04ea5e,
		0x015d358c,
		0xfa737487,
		0xfb2e410b,
		0xb35a1d67,
		0x9252d2db,
		0xe9335610,
		0x6d1347d6,
		0x9a8c61d7,
		0x377a0ca1,
		0x598e14f8,
		0xeb893c13,
		0xceee27a9,
		0xb735c961,
		0xe1ede51c,
		0x7a3cb147,
		0x9c59dfd2,
		0x553f73f2,
		0x1879ce14,
		0x73bf37c7,
		0x53eacdf7,
		0x5f5baafd,
		0xdf146f3d,
		0x7886db44,
		0xca81f3af,
		0xb93ec468,
		0x382c3424,
		0xc25f40a3,
		0x1672c31d,
		0xbc0c25e2,
		0x288b493c,
		0xff41950d,
		0x397101a8,
		0x08deb30c,
		0xd89ce4b4,
		0x6490c156,
		0x7b6184cb,
		0xd570b632,
		0x48745c6c,
		0xd04257b8,
	},
};


// SubBytes embedded in words tables.
const Word AESSubBytesWordTable[4][256] =
{
	{
		0x00000063,
		0x0000007c,
		0x00000077,
		0x0000007b,
		0x000000f2,
		0x0000006b,
		0x0000006f,
		0x000000c5,
		0x00000030,
		0x00000001,
		0x00000067,
		0x0000002b,
		0x000000fe,
		0x000000d7,
		0x000000ab,
		0x00000076,
		0x000000ca,
		0x00000082,
		0x000000c9,
		0x0000007d,
		0x000000fa,
		0x00000059,
		0x00000047,
		0x000000f0,
		0x000000ad,
		0x000000d4,
		0x000000a2,
		0x000000af,
		0x0000009c,
		0x000000a4,
		0x00000072,
		0x000000c0,
		0x000000b7,
		0x000000fd,
		0x00000093,
		0x00000026,
		0x00000036,
		0x0000003f,
		0x000000f7,
		0x000000cc,
		0x00000034,
		0x000000a5,
		0x000000e5,
		0x000000f1,
		0x00000071,
		0x000000d8,
		0x00000031,
		0x00000015,
		0x00000004,
		0x000000c7,
		0x00000023,
		0x000000c3,
		0x00000018,
		0x00000096,
		0x00000005,
		0x0000009a,
		0x00000007,
		0x00000012,
		0x00000080,
		0x000000e2,
		0x000000eb,
		0x00000027,
		0x000000b2,
		0x00000075,
		0x00000009,
		0x00000083,
		0x0000002c,
		0x0000001a,
		0x0000001b,
		0x0000006e,
		0x0000005a,
		0x000000a0,
		0x00000052,
		0x0000003b,
		0x000000d6,
		0x000000b3,
		0x00000029,
		0x000000e3,
		0x0000002f,
		0x00000084,
		0x00000053,
		0x000000d1,
		0x00000000,
		0x000000ed,
		0x00000020,
		0x000000fc,
		0x000000b1,
		0x0000005b,
		0x0000006a,
		0x000000cb,
		0x000000be,
		0x00000039,
		0x0000004a,
		0x0000004c,
		0x00000058,
		0x000000cf,
		0x000000d0,
		0x000000ef,
		0x000000aa,
		0x000000fb,
		0x00000043,
		0x0000004d,
		0x00000033,
		0x00000085,
		0x00000045,
		0x000000f9,
		0x00000002,
		0x0000007f,
		0x00000050,
		0x0000003c,
		0x0000009f,
		0x000000a8,
		0x00000051,
		0x000000a3,
		0x00000040,
		0x0000008f,
		0x00000092,
		0x0000009d,
		0x00000038,
		0x000000f5,
		0x000000bc,
		0x000000b6,
		0x000000da,
		0x00000021,
		0x00000010,
		0x000000ff,
		0x000000f3,
		0x000000d2,
		0x000000cd,
		0x0000000c,
		0x00000013,
		0x000000ec,
		0x0000005f,
		0x00000097,
		0x00000044,
		0x00000017,
		0x000000c4,
		0x000000a7,
		0x0000007e,
		0x0000003d,
		0x00000064,
		0x0000005d,
		0x00000019,
		0x00000073,
		0x00000060,
		0x00000081,
		0x0000004f,
		0x000000dc,
		0x00000022,
		0x0000002a,
		0x00000090,
		0x00000088,
		0x00000046,
		0x000000ee,
		0x000000b8,
		0x00000014,
		0x000000de,
		0x0000005e,
		0x0000000b,
		0x000000db,
		0x000000e0,
		0x00000032,
		0x0000003a,
		0x0000000a,
		0x00000049,
		0x00000006,
		0x00000024,
		0x0000005c,
		0x000000c2,
		0x000000d3,
		0x000000ac,
		0x00000062,
		0x00000091,
		0x00000095,
		0x000000e4,
		0x00000079,
		0x000000e7,
		0x000000c8,
		0x00000037,
		0x0000006d,
		0x0000008d,
		0x000000d5,
		0x0000004e,
		0x000000a9,
		0x0000006c,
		0x00000056,
		0x000000f4,
		0x000000ea,
		0x00000065,
		0x0000007a,
		0x000000ae,
		0x00000008,
		0x000000ba,
		0x00000078,
		0x00000025,
		0x0000002e,
		0x0000001c,
		0x000000a6,
		0x000000b4,
		0x000000c6,
		0x000000e8,
		0x000000dd,
		0x00000074,
		0x0000001f,
		0x0000004b,
		0x000000bd,
		0x0000008b,
		0x0000008a,
		0x00000070,
		0x0000003e,
		0x000000b5,
		0x00000066,
		0x00000048,
		0x00000003,
		0x000000f6,
		0x0000000e,
		0x00000061,
		0x00000035,
		0x00000057,
		0x000000b9,
		0x00000086,
		0x000000c1,
		0x0000001d,
		0x0000009e,
		0x000000e1,
		0x000000f8,
		0x00000098,
		0x00000011,
		0x00000069,
		0x000000d9,
		0x0000008e,
		0x00000094,
		0x0000009b,
		0x0000001e,
		0x00000087,
		0x000000e9,
		0x000000ce,
		0x00000055,
		0x00000028,
		0x000000df,
		0x0000008c,
		0x000000a1,
		0x00000089,
		0x0000000d,
		0x000000bf,
		0x000000e6,
		0x00000042,
		0x00000068,
		0x00000041,
		0x00000099,
		0x0000002d,
		0x0000000f,
		0x000000b0,
		0x00000054,
		0x000000bb,
		0x00000016,
	},
	{
		0x00006300,
		0x00007c00,
		0x00007700,
		0x00007b00,
		0x0000f200,
		0x00006b00,
		0x00006f00,
		0x0000c500,
		0x00003000,
		0x00000100,
		0x00006700,
		0x00002b00,
		0x0000fe00,
		0x0000d700,
		0x0000ab00,
		0x00007600,
		0x0000ca00,
		0x00008200,
		0x0000c900,
		0x00007d00,
		0x0000fa00,
		0x00005900,
		0x00004700,
		0x0000f000,
		0x0000ad00,
		0x0000d400,
		0x0000a200,
		0x0000af00,
		0x00009c00,
		0x0000a400,
		0x00007200,
		0x0000c000,
		0x0000b700,
		0x0000fd00,
		0x00009300,
		0x00002600,
		0x00003600,
		0x00003f00,
		0x0000f700,
		0x0000cc00,
		0x00003400,
		0x0000a500,
		0x0000e500,
		0x0000f100,
		0x00007100,
		0x0000d800,
		0x00003100,
		0x00001500,
		0x00000400,
		0x0000c700,
		0x00002300,
		0x0000c300,
		0x00001800,
		0x00009600,
		0x00000500,
		0x00009a00,
		0x00000700,
		0x00001200,
		0x00008000,
		0x0000e200,
		0x0000eb00,
		0x00002700,
		0x0000b200,
		0x00007500,
		0x00000900,
		0x00008300,
		0x00002c00,
		0x00001a00,
		0x00001b00,
		0x00006e00,
		0x00005a00,
		0x0000a000,
		0x00005200,
		0x00003b00,
		0x0000d600,
		0x0000b300,
		0x00002900,
		0x0000e300,
		0x00002f00,
		0x00008400,
		0x00005300,
		0x0000d100,
		0x00000000,
		0x0000ed00,
		0x00002000,
		0x0000fc00,
		0x0000b100,
		0x00005b00,
		0x00006a00,
		0x0000cb00,
		0x0000be00,
		0x00003900,
		0x00004a00,
		0x00004c00,
		0x00005800,
		0x0000cf00,
		0x0000d000,
		0x0000ef00,
		0x0000aa00,
		0x0000fb00,
		0x00004300,
		0x00004d00,
		0x00003300,
		0x00008500,
		0x00004500,
		0x0000f900,
		0x00000200,
		0x00007f00,
		0x00005000,
		0x00003c00,
		0x00009f00,
		0x0000a800,
		0x00005100,
		0x0000a300,
		0x00004000,
		0x00008f00,
		0x00009200,
		0x00009d00,
		0x00003800,
		0x0000f500,
		0x0000bc00,
		0x0000b600,
		0x0000da00,
		0x00002100,
		0x00001000,
		0x0000ff00,
		0x0000f300,
		0x0000d200,
		0x0000cd00,
		0x00000c00,
		0x00001300,
		0x0000ec00,
		0x00005f00,
		0x00009700,
		0x00004400,
		0x00001700,
		0x0000c400,
		0x0000a700,
		0x00007e00,
		0x00003d00,
		0x00006400,
		0x00005d00,
		0x00001900,
		0x00007300,
		0x00006000,
		0x00008100,
		0x00004f00,
		0x0000dc00,
		0x00002200,
		0x00002a00,
		0x00009000,
		0x00008800,
		0x00004600,
		0x0000ee00,
		0x0000b800,
		0x00001400,
		0x0000de00,
		0x00005e00,
		0x00000b00,
		0x0000db00,
		0x0000e000,
		0x00003200,
		0x00003a00,
		0x00000a00,
		0x00004900,
		0x00000600,
		0x00002400,
		0x00005c00,
		0x0000c200,
		0x0000d300,
		0x0000ac00,
		0x00006200,
		0x00009100,
		0x00009500,
		0x0000e400,
		0x00007900,
		0x0000e700,
		0x0000c800,
		0x00003700,
		0x00006d00,
		0x00008d00,
		0x0000d500,
		0x00004e00,
		0x0000a900,
		0x00006c00,
		0x00005600,
		0x0000f400,
		0x0000ea00,
		0x00006500,
		0x00007a00,
		0x0000ae00,
		0x00000800,
		0x0000ba00,
		0x00007800,
		0x00002500,
		0x00002e00,
		0x00001c00,
		0x0000a600,
		0x0000b400,
		0x0000c600,
		0x0000e800,
		0x0000dd00,
		0x00007400,
		0x00001f00,
		0x00004b00,
		0x0000bd00,
		0x00008b00,
		0x00008a00,
		0x00007000,
		0x00003e00,
		0x0000b500,
		0x00006600,
		0x00004800,
		0x00000300,
		0x0000f600,
		0x00000e00,
		0x00006100,
		0x00003500,
		0x00005700,
		0x0000b900,
		0x00008600,
		0x0000c100,
		0x00001d00,
		0x00009e00,
		0x0000e100,
		0x0000f800,
		0x00009800,
		0x00001100,
		0x00006900,
		0x0000d900,
		0x00008e00,
		0x00009400,
		0x00009b00,
		0x00001e00,
		0x00008700,
		0x0000e900,
		0x0000ce00,
		0x00005500,
		0x00002800,
		0x0000df00,
		0x00008c00,
		0x0000a100,
		0x00008900,
		0x00000d00,
		0x0000bf00,
		0x0000e600,
		0x00004200,
		0x00006800,
		0x00004100,
		0x00009900,
		0x00002d00,
		0x00000f00,
		0x0000b000,
		0x00005400,
		0x0000bb00,
		0x00001600,
	},
	{
		0x00630000,
		0x007c0000,
		0x00770000,
		0x007b0000,
		0x00f20000,
		0x006b0000,
		0x006f0000,
		0x00c50000,
		0x00300000,
		0x00010000,
		0x00670000,
		0x002b0000,
		0x00fe0000,
		0x00d70000,
		0x00ab0000,
		0x00760000,
		0x00ca0000,
		0x00820000,
		0x00c90000,
		0x007d0000,
		0x00fa0000,
		0x00590000,
		0x00470000,
		0x00f00000,
		0x00ad0000,
		0x00d40000,
		0x00a20000,
		0x00af0000,
		0x009c0000,
		0x00a40000,
		0x00720000,
		0x00c00000,
		0x00b70000,
		0x00fd0000,
		0x00930000,
		0x00260000,
		0x00360000,
		0x003f0000,
		0x00f70000,
		0x00cc0000,
		0x00340000,
		0x00a50000,
		0x00e50000,
		0x00f10000,
		0x00710000,
		0x00d80000,
		0x00310000,
		0x00150000,
		0x00040000,
		0x00c70000,
		0x00230000,
		0x00c30000,
		0x00180000,
		0x00960000,
		0x00050000,
		0x009a0000,
		0x00070000,
		0x00120000,
		0x00800000,
		0x00e20000,
		0x00eb0000,
		0x00270000,
		0x00b20000,
		0x00750000,
		0x00090000,
		0x00830000,
		0x002c0000,
		0x001a0000,
		0x001b0000,
		0x006e0000,
		0x005a0000,
		0x00a00000,
		0x00520000,
		0x003b0000,
		0x00d60000,
		0x00b30000,
		0x00290000,
		0x00e30000,
		0x002f0000,
		0x00840000,
		0x00530000,
		0x00d10000,
		0x00000000,
		0x00ed0000,
		0x00200000,
		0x00fc0000,
		0x00b10000,
		0x005b0000,
		0x006a0000,
		0x00cb0000,
		0x00be0000,
		0x00390000,
		0x004a0000,
		0x004c0000,
		0x00580000,
		0x00cf0000,
		0x00d00000,
		0x00ef0000,
		0x00aa0000,
		0x00fb0000,
		0x00430000,
		0x004d0000,
		0x00330000,
		0x00850000,
		0x00450000,
		0x00f90000,
		0x00020000,
		0x007f0000,
		0x00500000,
		0x003c0000,
		0x009f0000,
		0x00a80000,
		0x00510000,
		0x00a30000,
		0x00400000,
		0x008f0000,
		0x00920000,
		0x009d0000,
		0x00380000,
		0x00f50000,
		0x00bc0000,
		0x00b60000,
		0x00da0000,
		0x00210000,
		0x00100000,
		0x00ff0000,
		0x00f30000,
		0x00d20000,
		0x00cd0000,
		0x000c0000,
		0x00130000,
		0x00ec0000,
		0x005f0000,
		0x00970000,
		0x00440000,
		0x00170000,
		0x00c40000,
		0x00a70000,
		0x007e0000,
		0x003d0000,
		0x00640000,
		0x005d0000,
		0x00190000,
		0x00730000,
		0x00600000,
		0x00810000,
		0x004f0000,
		0x00dc0000,
		0x00220000,
		0x002a0000,
		0x00900000,
		0x00880000,
		0x00460000,
		0x00ee0000,
		0x00b80000,
		0x00140000,
		0x00de0000,
		0x005e0000,
		0x000b0000,
		0x00db0000,
		0x00e00000,
		0x00320000,
		0x003a0000,
		0x000a0000,
		0x00490000,
		0x00060000,
		0x00240000,
		0x005c0000,
		0x00c20000,
		0x00d30000,
		0x00ac0000,
		0x00620000,
		0x00910000,
		0x00950000,
		0x00e40000,
		0x00790000,
		0x00e70000,
		0x00c80000,
		0x00370000,
		0x006d0000,
		0x008d0000,
		0x00d50000,
		0x004e0000,
		0x00a90000,
		0x006c0000,
		0x00560000,
		0x00f40000,
		0x00ea0000,
		0x00650000,
		0x007a0000,
		0x00ae0000,
		0x00080000,
		0x00ba0000,
		0x00780000,
		0x00250000,
		0x002e0000,
		0x001c0000,
		0x00a60000,
		0x00b40000,
		0x00c60000,
		0x00e80000,
		0x00dd0000,
		0x00740000,
		0x001f0000,
		0x004b0000,
		0x00bd0000,
		0x008b0000,
		0x008a0000,
		0x00700000,
		0x003e0000,
		0x00b50000,
		0x00660000,
		0x00480000,
		0x00030000,
		0x00f60000,
		0x000e0000,
		0x00610000,
		0x00350000,
		0x00570000,
		0x00b90000,
		0x00860000,
		0x00c10000,
		0x001d0000,
		0x009e0000,
		0x00e10000,
		0x00f80000,
		0x00980000,
		0x00110000,
		0x00690000,
		0x00d90000,
		0x008e0000,
		0x00940000,
		0x009b0000,
		0x001e0000,
		0x00870000,
		0x00e90000,
		0x00ce0000,
		0x00550000,
		0x00280000,
		0x00df0000,
		0x008c0000,
		0x00a10000,
		0x00890000,
		0x000d0000,
		0x00bf0000,
		0x00e60000,
		0x00420000,
		0x00680000,
		0x00410000,
		0x00990000,
		0x002d0000,
		0x000f0000,
		0x00b00000,
		0x00540000,
		0x00bb0000,
		0x00160000,
	},
	{
		0x63000000,
		0x7c000000,
		0x77000000,
		0x7b000000,
		0xf2000000,
		0x6b000000,
		0x6f000000,
		0xc5000000,
		0x30000000,
		0x01000000,
		0x67000000,
		0x2b000000,
		0xfe000000,
		0xd7000000,
		0xab000000,
		0x76000000,
		0xca000000,
		0x82000000,
		0xc9000000,
		0x7d000000,
		0xfa000000,
		0x59000000,
		0x47000000,
		0xf0000000,
		0xad000000,
		0xd4000000,
		0xa2000000,
		0xaf000000,
		0x9c000000,
		0xa4000000,
		0x72000000,
		0xc0000000,
		0xb7000000,
		0xfd000000,
		0x93000000,
		0x26000000,
		0x36000000,
		0x3f000000,
		0xf7000000,
		0xcc000000,
		0x34000000,
		0xa5000000,
		0xe5000000,
		0xf1000000,
		0x71000000,
		0xd8000000,
		0x31000000,
		0x15000000,
		0x04000000,
		0xc7000000,
		0x23000000,
		0xc3000000,
		0x18000000,
		0x96000000,
		0x05000000,
		0x9a000000,
		0x07000000,
		0x12000000,
		0x80000000,
		0xe2000000,
		0xeb000000,
		0x27000000,
		0xb2000000,
		0x75000000,
		0x09000000,
		0x83000000,
		0x2c000000,
		0x1a000000,
		0x1b000000,
		0x6e000000,
		0x5a000000,
		0xa0000000,
		0x52000000,
		0x3b000000,
		0xd6000000,
		0xb3000000,
		0x29000000,
		0xe3000000,
		0x2f000000,
		0x84000000,
		0x53000000,
		0xd1000000,
		0x00000000,
		0xed000000,
		0x20000000,
		0xfc000000,
		0xb1000000,
		0x5b000000,
		0x6a000000,
		0xcb000000,
		0xbe000000,
		0x39000000,
		0x4a000000,
		0x4c000000,
		0x58000000,
		0xcf000000,
		0xd0000000,
		0xef000000,
		0xaa000000,
		0xfb000000,
		0x43000000,
		0x4d000000,
		0x33000000,
		0x85000000,
		0x45000000,
		0xf9000000,
		0x02000000,
		0x7f000000,
		0x50000000,
		0x3c000000,
		0x9f000000,
		0xa8000000,
		0x51000000,
		0xa3000000,
		0x40000000,
		0x8f000000,
		0x92000000,
		0x9d000000,
		0x38000000,
		0xf5000000,
		0xbc000000,
		0xb6000000,
		0xda000000,
		0x21000000,
		0x10000000,
		0xff000000,
		0xf3000000,
		0xd2000000,
		0xcd000000,
		0x0c000000,
		0x13000000,
		0xec000000,
		0x5f000000,
		0x97000000,
		0x44000000,
		0x17000000,
		0xc4000000,
		0xa7000000,
		0x7e000000,
		0x3d000000,
		0x64000000,
		0x5d000000,
		0x19000000,
		0x73000000,
		0x60000000,
		0x81000000,
		0x4f000000,
		0xdc000000,
		0x22000000,
		0x2a000000,
		0x90000000,
		0x88000000,
		0x46000000,
		0xee000000,
		0xb8000000,
		0x14000000,
		0xde000000,
		0x5e000000,
		0x0b000000,
		0xdb000000,
		0xe0000000,
		0x32000000,
		0x3a000000,
		0x0a000000,
		0x49000000,
		0x06000000,
		0x24000000,
		0x5c000000,
		0xc2000000,
		0xd3000000,
		0xac000000,
		0x62000000,
		0x91000000,
		0x95000000,
		0xe4000000,
		0x79000000,
		0xe7000000,
		0xc8000000,
		0x37000000,
		0x6d000000,
		0x8d000000,
		0xd5000000,
		0x4e000000,
		0xa9000000,
		0x6c000000,
		0x56000000,
		0xf4000000,
		0xea000000,
		0x65000000,
		0x7a000000,
		0xae000000,
		0x08000000,
		0xba000000,
		0x78000000,
		0x25000000,
		0x2e000000,
		0x1c000000,
		0xa6000000,
		0xb4000000,
		0xc6000000,
		0xe8000000,
		0xdd000000,
		0x74000000,
		0x1f000000,
		0x4b000000,
		0xbd000000,
		0x8b000000,
		0x8a000000,
		0x70000000,
		0x3e000000,
		0xb5000000,
		0x66000000,
		0x48000000,
		0x03000000,
		0xf6000000,
		0x0e000000,
		0x61000000,
		0x35000000,
		0x57000000,
		0xb9000000,
		0x86000000,
		0xc1000000,
		0x1d000000,
		0x9e000000,
		0xe1000000,
		0xf8000000,
		0x98000000,
		0x11000000,
		0x69000000,
		0xd9000000,
		0x8e000000,
		0x94000000,
		0x9b000000,
		0x1e000000,
		0x87000000,
		0xe9000000,
		0xce000000,
		0x55000000,
		0x28000000,
		0xdf000000,
		0x8c000000,
		0xa1000000,
		0x89000000,
		0x0d000000,
		0xbf000000,
		0xe6000000,
		0x42000000,
		0x68000000,
		0x41000000,
		0x99000000,
		0x2d000000,
		0x0f000000,
		0xb0000000,
		0x54000000,
		0xbb000000,
		0x16000000,
	},
};


// InvSubBytes embedded in words tables.
const Word AESInvSubBytesWordTable[4][256] =
{
	{
		0x00000052,
		0x00000009,
		0x0000006a,
		0x000000d5,
		0x00000030,
		0x00000036,
		0x000000a5,
		0x00000038,
		0x000000bf,
		0x00000040,
		0x000000a3,
		0x0000009e,
		0x00000081,
		0x000000f3,
		0x000000d7,
		0x000000fb,
		0x0000007c,
		0x000000e3,
		0x00000039,
		0x00000082,
		0x0000009b,
		0x0000002f,
		0x000000ff,
		0x00000087,
		0x00000034,
		0x0000008e,
		0x00000043,
		0x00000044,
		0x000000c4,
		0x000000de,
		0x000000e9,
		0x000000cb,
		0x00000054,
		0x0000007b,
		0x00000094,
		0x00000032,
		0x000000a6,
		0x000000c2,
		0x00000023,
		0x0000003d,
		0x000000ee,
		0x0000004c,
		0x00000095,
		0x0000000b,
		0x00000042,
		0x000000fa,
		0x000000c3,
		0x0000004e,
		0x00000008,
		0x0000002e,
		0x000000a1,
		0x00000066,
		0x00000028,
		0x000000d9,
		0x00000024,
		0x000000b2,
		0x00000076,
		0x0000005b,
		0x000000a2,
		0x00000049,
		0x0000006d,
		0x0000008b,
		0x000000d1,
		0x00000025,
		0x00000072,
		0x000000f8,
		0x000000f6,
		0x00000064,
		0x00000086,
		0x00000068,
		0x00000098,
		0x00000016,
		0x000000d4,
		0x000000a4,
		0x0000005c,
		0x000000cc,
		0x0000005d,
		0x00000065,
		0x000000b6,
		0x00000092,
		0x0000006c,
		0x00000070,
		0x00000048,
		0x00000050,
		0x000000fd,
		0x000000ed,
		0x000000b9,
		0x000000da,
		0x0000005e,
		0x00000015,
		0x00000046,
		0x00000057,
		0x000000a7,
		0x0000008d,
		0x0000009d,
		0x00000084,
		0x00000090,
		0x000000d8,
		0x000000ab,
		0x00000000,
		0x0000008c,
		0x000000bc,
		0x000000d3,
		0x0000000a,
		0x000000f7,
		0x000000e4,
		0x00000058,
		0x00000005,
		0x000000b8,
		0x000000b3,
		0x00000045,
		0x00000006,
		0x000000d0,
		0x0000002c,
		0x0000001e,
		0x0000008f,
		0x000000ca,
		0x0000003f,
		0x0000000f,
		0x00000002,
		0x000000c1,
		0x000000af,
		0x000000bd,
		0x00000003,
		0x00000001,
		0x00000013,
		0x0000008a,
		0x0000006b,
		0x0000003a,
		0x00000091,
		0x00000011,
		0x00000041,
		0x0000004f,
		0x00000067,
		0x000000dc,
		0x000000ea,
		0x00000097,
		0x000000f2,
		0x000000cf,
		0x000000ce,
		0x000000f0,
		0x000000b4,
		0x000000e6,
		0x00000073,
		0x00000096,
		0x000000ac,
		0x00000074,
		0x00000022,
		0x000000e7,
		0x000000ad,
		0x00000035,
		0x00000085,
		0x000000e2,
		0x000000f9,
		0x00000037,
		0x000000e8,
		0x0000001c,
		0x00000075,
		0x000000df,
		0x0000006e,
		0x00000047,
		0x000000f1,
		0x0000001a,
		0x00000071,
		0x0000001d,
		0x00000029,
		0x000000c5,
		0x00000089,
		0x0000006f,
		0x000000b7,
		0x00000062,
		0x0000000e,
		0x000000aa,
		0x00000018,
		0x000000be,
		0x0000001b,
		0x000000fc,
		0x00000056,
		0x0000003e,
		0x0000004b,
		0x000000c6,
		0x000000d2,
		0x00000079,
		0x00000020,
		0x0000009a,
		0x000000db,
		0x000000c0,
		0x000000fe,
		0x00000078,
		0x000000cd,
		0x0000005a,
		0x000000f4,
		0x0000001f,
		0x000000dd,
		0x000000a8,
		0x00000033,
		0x00000088,
		0x00000007,
		0x000000c7,
		0x00000031,
		0x000000b1,
		0x00000012,
		0x00000010,
		0x00000059,
		0x00000027,
		0x00000080,
		0x000000ec,
		0x0000005f,
		0x00000060,
		0x00000051,
		0x0000007f,
		0x000000a9,
		0x00000019,
		0x000000b5,
		0x0000004a,
		0x0000000d,
		0x0000002d,
		0x000000e5,
		0x0000007a,
		0x0000009f,
		0x00000093,
		0x000000c9,
		0x0000009c,
		0x000000ef,
		0x000000a0,
		0x000000e0,
		0x0000003b,
		0x0000004d,
		0x000000ae,
		0x0000002a,
		0x000000f5,
		0x000000b0,
		0x000000c8,
		0x000000eb,
		0x000000bb,
		0x0000003c,
		0x00000083,
		0x00000053,
		0x00000099,
		0x00000061,
		0x00000017,
		0x0000002b,
		0x00000004,
		0x0000007e,
		0x000000ba,
		0x00000077,
		0x000000d6,
		0x00000026,
		0x000000e1,
		0x00000069,
		0x00000014,
		0x00000063,
		0x00000055,
		0x00000021,
		0x0000000c,
		0x0000007d,
	},
	{
		0x00005200,
		0x00000900,
		0x00006a00,
		0x0000d500,
		0x00003000,
		0x00003600,
		0x0000a500,
		0x00003800,
		0x0000bf00,
		0x00004000,
		0x0000a300,
		0x00009e00,
		0x00008100,
		0x0000f300,
		0x0000d700,
		0x0000fb00,
		0x00007c00,
		0x0000e300,
		0x00003900,
		0x00008200,
		0x00009b00,
		0x00002f00,
		0x0000ff00,
		0x00008700,
		0x00003400,
		0x00008e00,
		0x00004300,
		0x00004400,
		0x0000c400,
		0x0000de00,
		0x0000e900,
		0x0000cb00,
		0x00005400,
		0x00007b00,
		0x00009400,
		0x00003200,
		0x0000a600,
		0x0000c200,
		0x00002300,
		0x00003d00,
		0x0000ee00,
		0x00004c00,
		0x00009500,
		0x00000b00,
		0x00004200,
		0x0000fa00,
		0x0000c300,
		0x00004e00,
		0x00000800,
		0x00002e00,
		0x0000a100,
		0x00006600,
		0x00002800,
		0x0000d900,
		0x00002400,
		0x0000b200,
		0x00007600,
		0x00005b00,
		0x0000a200,
		0x00004900,
		0x00006d00,
		0x00008b00,
		0x0000d100,
		0x00002500,
		0x00007200,
		0x0000f800,
		0x0000f600,
		0x00006400,
		0x00008600,
		0x00006800,
		0x00009800,
		0x00001600,
		0x0000d400,
		0x0000a400,
		0x00005c00,
		0x0000cc00,
		0x00005d00,
		0x00006500,
		0x0000b600,
		0x00009200,
		0x00006c00,
		0x00007000,
		0x00004800,
		0x00005000,
		0x0000fd00,
		0x0000ed00,
		0x0000b900,
		0x0000da00,
		0x00005e00,
		0x00001500,
		0x00004600,
		0x00005700,
		0x0000a700,
		0x00008d00,
		0x00009d00,
		0x00008400,
		0x00009000,
		0x0000d800,
		0x0000ab00,
		0x00000000,
		0x00008c00,
		0x0000bc00,
		0x0000d300,
		0x00000a00,
		0x0000f700,
		0x0000e400,
		0x00005800,
		0x00000500,
		0x0000b800,
		0x0000b300,
		0x00004500,
		0x00000600,
		0x0000d000,
		0x00002c00,
		0x00001e00,
		0x00008f00,
		0x0000ca00,
		0x00003f00,
		0x00000f00,
		0x00000200,
		0x0000c100,
		0x0000af00,
		0x0000bd00,
		0x00000300,
		0x00000100,
		0x00001300,
		0x00008a00,
		0x00006b00,
		0x00003a00,
		0x00009100,
		0x00001100,
		0x00004100,
		0x00004f00,
		0x00006700,
		0x0000dc00,
		0x0000ea00,
		0x00009700,
		0x0000f200,
		0x0000cf00,
		0x0000ce00,
		0x0000f000,
		0x0000b400,
		0x0000e600,
		0x00007300,
		0x00009600,
		0x0000ac00,
		0x00007400,
		0x00002200,
		0x0000e700,
		0x0000ad00,
		0x00003500,
		0x00008500,
		0x0000e200,
		0x0000f900,
		0x00003700,
		0x0000e800,
		0x00001c00,
		0x00007500,
		0x0000df00,
		0x00006e00,
		0x00004700,
		0x0000f100,
		0x00001a00,
		0x00007100,
		0x00001d00,
		0x00002900,
		0x0000c500,
		0x00008900,
		0x00006f00,
		0x0000b700,
		0x00006200,
		0x00000e00,
		0x0000aa00,
		0x00001800,
		0x0000be00,
		0x00001b00,
		0x0000fc00,
		0x00005600,
		0x00003e00,
		0x00004b00,
		0x0000c600,
		0x0000d200,
		0x00007900,
		0x00002000,
		0x00009a00,
		0x0000db00,
		0x0000c000,
		0x0000fe00,
		0x00007800,
		0x0000cd00,
		0x00005a00,
		0x0000f400,
		0x00001f00,
		0x0000dd00,
		0x0000a800,
		0x00003300,
		0x00008800,
		0x00000700,
		0x0000c700,
		0x00003100,
		0x0000b100,
		0x00001200,
		0x00001000,
		0x00005900,
		0x00002700,
		0x00008000,
		0x0000ec00,
		0x00005f00,
		0x00006000,
		0x00005100,
		0x00007f00,
		0x0000a900,
		0x00001900,
		0x0000b500,
		0x00004a00,
		0x00000d00,
		0x00002d00,
		0x0000e500,
		0x00007a00,
		0x00009f00,
		0x00009300,
		0x0000c900,
		0x00009c00,
		0x0000ef00,
		0x0000a000,
		0x0000e000,
		0x00003b00,
		0x00004d00,
		0x0000ae00,
		0x00002a00,
		0x0000f500,
		0x0000b000,
		0x0000c800,
		0x0000eb00,
		0x0000bb00,
		0x00003c00,
		0x00008300,
		0x00005300,
		0x00009900,
		0x00006100,
		0x00001700,
		0x00002b00,
		0x00000400,
		0x00007e00,
		0x0000ba00,
		0x00007700,
		0x0000d600,
		0x00002600,
		0x0000e100,
		0x00006900,
		0x00001400,
		0x00006300,
		0x00005500,
		0x00002100,
		0x00000c00,
		0x00007d00,
	},
	{
		0x00520000,
		0x00090000,
		0x006a0000,
		0x00d50000,
		0x00300000,
		0x00360000,
		0x00a50000,
		0x00380000,
		0x00bf0000,
		0x00400000,
		0x00a30000,
		0x009e0000,
		0x00810000,
		0x00f30000,
		0x00d70000,
		0x00fb0000,
		0x007c0000,
		0x00e30000,
		0x00390000,
		0x00820000,
		0x009b0000,
		0x002f0000,
		0x00ff0000,
		0x00870000,
		0x00340000,
		0x008e0000,
		0x00430000,
		0x00440000,
		0x00c40000,
		0x00de0000,
		0x00e90000,
		0x00cb0000,
		0x00540000,
		0x007b0000,
		0x00940000,
		0x00320000,
		0x00a60000,
		0x00c20000,
		0x00230000,
		0x003d0000,
		0x00ee0000,
		0x004c0000,
		0x00950000,
		0x000b0000,
		0x00420000,
		0x00fa0000,
		0x00c30000,
		0x004e0000,
		0x00080000,
		0x002e0000,
		0x00a10000,
		0x00660000,
		0x00280000,
		0x00d90000,
		0x00240000,
		0x00b20000,
		0x00760000,
		0x005b0000,
		0x00a20000,
		0x00490000,
		0x006d0000,
		0x008b0000,
		0x00d10000,
		0x00250000,
		0x00720000,
		0x00f80000,
		0x00f60000,
		0x00640000,
		0x00860000,
		0x00680000,
		0x00980000,
		0x00160000,
		0x00d40000,
		0x00a40000,
		0x005c0000,
		0x00cc0000,
		0x005d0000,
		0x00650000,
		0x00b60000,
		0x00920000,
		0x006c0000,
		0x00700000,
		0x00480000,
		0x00500000,
		0x00fd0000,
		0x00ed0000,
		0x00b90000,
		0x00da0000,
		0x005e0000,
		0x00150000,
		0x00460000,
		0x00570000,
		0x00a70000,
		0x008d0000,
		0x009d0000,
		0x00840000,
		0x00900000,
		0x00d80000,
		0x00ab0000,
		0x00000000,
		0x008c0000,
		0x00bc0000,
		0x00d30000,
		0x000a0000,
		0x00f70000,
		0x00e40000,
		0x00580000,
		0x00050000,
		0x00b80000,
		0x00b30000,
		0x00450000,
		0x00060000,
		0x00d00000,
		0x002c0000,
		0x001e0000,
		0x008f0000,
		0x00ca0000,
		0x003f0000,
		0x000f0000,
		0x00020000,
		0x00c10000,
		0x00af0000,
		0x00bd0000,
		0x00030000,
		0x00010000,
		0x00130000,
		0x008a0000,
		0x006b0000,
		0x003a0000,
		0x00910000,
		0x00110000,
		0x00410000,
		0x004f0000,
		0x00670000,
		0x00dc0000,
		0x00ea0000,
		0x00970000,
		0x00f20000,
		0x00cf0000,
		0x00ce0000,
		0x00f00000,
		0x00b40000,
		0x00e60000,
		0x00730000,
		0x00960000,
		0x00ac0000,
		0x00740000,
		0x00220000,
		0x00e70000,
		0x00ad0000,
		0x00350000,
		0x00850000,
		0x00e20000,
		0x00f90000,
		0x00370000,
		0x00e80000,
		0x001c0000,
		0x00750000,
		0x00df0000,
		0x006e0000,
		0x00470000,
		0x00f10000,
		0x001a0000,
		0x00710000,
		0x001d0000,
		0x00290000,
		0x00c50000,
		0x00890000,
		0x006f0000,
		0x00b70000,
		0x00620000,
		0x000e0000,
		0x00aa0000,
		0x00180000,
		0x00be0000,
		0x001b0000,
		0x00fc0000,
		0x00560000,
		0x003e0000,
		0x004b0000,
		0x00c60000,
		0x00d20000,
		0x00790000,
		0x00200000,
		0x009a0000,
		0x00db0000,
		0x00c00000,
		0x00fe0000,
		0x00780000,
		0x00cd0000,
		0x005a0000,
		0x00f40000,
		0x001f0000,
		0x00dd0000,
		0x00a80000,
		0x00330000,
		0x00880000,
		0x00070000,
		0x00c70000,
		0x00310000,
		0x00b10000,
		0x00120000,
		0x00100000,
		0x00590000,
		0x00270000,
		0x00800000,
		0x00ec0000,
		0x005f0000,
		0x00600000,
		0x00510000,
		0x007f0000,
		0x00a90000,
		0x00190000,
		0x00b50000,
		0x004a0000,
		0x000d0000,
		0x002d0000,
		0x00e50000,
		0x007a0000,
		0x009f0000,
		0x00930000,
		0x00c90000,
		0x009c0000,
		0x00ef0000,
		0x00a00000,
		0x00e00000,
		0x003b0000,
		0x004d0000,
		0x00ae0000,
		0x002a0000,
		0x00f50000,
		0x00b00000,
		0x00c80000,
		0x00eb0000,
		0x00bb0000,
		0x003c0000,
		0x00830000,
		0x00530000,
		0x00990000,
		0x00610000,
		0x00170000,
		0x002b0000,
		0x00040000,
		0x007e0000,
		0x00ba0000,
		0x00770000,
		0x00d60000,
		0x00260000,
		0x00e10000,
		0x00690000,
		0x00140000,
		0x00630000,
		0x00550000,
		0x00210000,
		0x000c0000,
		0x007d0000,
	},
	{
		0x52000000,
		0x09000000,
		0x6a000000,
		0xd5000000,
		0x30000000,
		0x36000000,
		0xa5000000,
		0x38000000,
		0xbf000000,
		0x40000000,
		0xa3000000,
		0x9e000000,
		0x81000000,
		0xf3000000,
		0xd7000000,
		0xfb000000,
		0x7c000000,
		0xe3000000,
		0x39000000,
		0x82000000,
		0x9b000000,
		0x2f000000,
		0xff000000,
		0x87000000,
		0x34000000,
		0x8e000000,
		0x43000000,
		0x44000000,
		0xc4000000,
		0xde000000,
		0xe9000000,
		0xcb000000,
		0x54000000,
		0x7b000000,
		0x94000000,
		0x32000000,
		0xa6000000,
		0xc2000000,
		0x23000000,
		0x3d000000,
		0xee000000,
		0x4c000000,
		0x95000000,
		0x0b000000,
		0x42000000,
		0xfa000000,
		0xc3000000,
		0x4e000000,
		0x08000000,
		0x2e000000,
		0xa1000000,
		0x66000000,
		0x28000000,
		0xd9000000,
		0x24000000,
		0xb2000000,
		0x76000000,
		0x5b000000,
		0xa2000000,
		0x49000000,
		0x6d000000,
		0x8b000000,
		0xd1000000,
		0x25000000,
		0x72000000,
		0xf8000000,
		0xf6000000,
		0x64000000,
		0x86000000,
		0x68000000,
		0x98000000,
		0x16000000,
		0xd4000000,
		0xa4000000,
		0x5c000000,
		0xcc000000,
		0x5d000000,
		0x65000000,
		0xb6000000,
		0x92000000,
		0x6c000000,
		0x70000000,
		0x48000000,
		0x50000000,
		0xfd000000,
		0xed000000,
		0xb9000000,
		0xda000000,
		0x5e000000,
		0x15000000,
		0x46000000,
		0x57000000,
		0xa7000000,
		0x8d000000,
		0x9d000000,
		0x84000000,
		0x90000000,
		0xd8000000,
		0xab000000,
		0x00000000,
		0x8c000000,
		0xbc000000,
		0xd3000000,
		0x0a000000,
		0xf7000000,
		0xe4000000,
		0x58000000,
		0x05000000,
		0xb8000000,
		0xb3000000,
		0x45000000,
		0x06000000,
		0xd0000000,
		0x2c000000,
		0x1e000000,
		0x8f000000,
		0xca000000,
		0x3f000000,
		0x0f000000,
		0x02000000,
		0xc1000000,
		0xaf000000,
		0xbd000000,
		0x03000000,
		0x01000000,
		0x13000000,
		0x8a000000,
		0x6b000000,
		0x3a000000,
		0x91000000,
		0x11000000,
		0x41000000,
		0x4f000000,
		0x67000000,
		0xdc000000,
		0xea000000,
		0x97000000,
		0xf2000000,
		0xcf000000,
		0xce000000,
		0xf0000000,
		0xb4000000,
		0xe6000000,
		0x73000000,
		0x96000000,
		0xac000000,
		0x74000000,
		0x22000000,
		0xe7000000,
		0xad000000,
		0x35000000,
		0x85000000,
		0xe2000000,
		0xf9000000,
		0x37000000,
		0xe8000000,
		0x1c000000,
		0x75000000,
		0xdf000000,
		0x6e000000,
		0x47000000,
		0xf1000000,
		0x1a000000,
		0x71000000,
		0x1d000000,
		0x29000000,
		0xc5000000,
		0x89000000,
		0x6f000000,
		0xb7000000,
		0x62000000,
		0x0e000000,
		0xaa000000,
		0x18000000,
		0xbe000000,
		0x1b000000,
		0xfc000000,
		0x56000000,
		0x3e000000,
		0x4b000000,
		0xc6000000,
		0xd2000000,
		0x79000000,
		0x20000000,
		0x9a000000,
		0xdb000000,
		0xc0000000,
		0xfe000000,
		0x78000000,
		0xcd000000,
		0x5a000000,
		0xf4000000,
		0x1f000000,
		0xdd000000,
		0xa8000000,
		0x33000000,
		0x88000000,
		0x07000000,
		0xc7000000,
		0x31000000,
		0xb1000000,
		0x12000000,
		0x10000000,
		0x59000000,
		0x27000000,
		0x80000000,
		0xec000000,
		0x5f000000,
		0x60000000,
		0x51000000,
		0x7f000000,
		0xa9000000,
		0x19000000,
		0xb5000000,
		0x4a000000,
		0x0d000000,
		0x2d000000,
		0xe5000000,
		0x7a000000,
		0x9f000000,
		0x93000000,
		0xc9000000,
		0x9c000000,
		0xef000000,
		0xa0000000,
		0xe0000000,
		0x3b000000,
		0x4d000000,
		0xae000000,
		0x2a000000,
		0xf5000000,
		0xb0000000,
		0xc8000000,
		0xeb000000,
		0xbb000000,
		0x3c000000,
		0x83000000,
		0x53000000,
		0x99000000,
		0x61000000,
		0x17000000,
		0x2b000000,
		0x04000000,
		0x7e000000,
		0xba000000,
		0x77000000,
		0xd6000000,
		0x26000000,
		0xe1000000,
		0x69000000,
		0x14000000,
		0x63000000,
		0x55000000,
		0x21000000,
		0x0c000000,
		0x7d000000,
	},
};
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/AESedp/Intel/AES.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#include "../AESAssembly.h"


// Generate object code only if this implementation has been requested.
#if defined UseAESedp_IntelAssembly


/*	AES.s -- Core AES routines for Intel processors.

	Written by Eric Postpischil, December 13, 2007.
*/


/*	We build these AES routines as a single module because the routines refer
	to labels in Data.s and it is easier and faster to refer to them as local
	labels.

	A local label can be referred to with position-independent assembler
	expressions such as "label-base(register)", where <base> is a local label
	whose address has been loaded into <register>.  (On i386, this is typically
	done with the idiom of a call to the next instrution and a pop of that
	return address into a register.)  Without local labels, the references must
	be done using spaces for addresses "lazy symbols" that are filled in by the
	dynamic loader and loaded by the code that wants the address.

	So the various routines in other files are assembled here via #include
	directives.
*/
#include "Data.s"


#define	TableSize	(256*4)
	/*	Each of the arrays defined in Data.s except for the round constants
		in _AESRcon is composed of four tables of 256 entries of four bytes
		each.  TableSize is the number of bytes in one of those four tables.
	*/


/*	Define a macro to select a value based on architecture.  This reduces
	some of the architecture conditionalization later in the source.
*/
#if defined __i386__
	#define	Arch(i386, x86_64)	i386
#elif defined __x86_64__
	#define	Arch(i386, x86_64)	x86_64
#endif


// Define an instruction for moving pointers.
#define	movp	Arch(movd, movd)
	// Latter argument should be "movq", but the assembler uses "movd".


/*	Rename the general registers.  This makes it easier to keep track of them
	and provides names for the "whole register" that are uniform between i386
	and x86_64.
*/
#if defined __i386__
	#define	r0	%eax	// Available for any use.
	#define	r1	%ecx	// Available for any use, some special purposes (loop).
	#define	r2	%edx	// Available for any use.
	#define	r3	%ebx	// Must be preserved by called routine.
	#define	r4	%esp	// Stack pointer.
	#define	r5	%ebp	// Frame pointer, must preserve, no bare indirect.
	#define	r6	%esi	// Must be preserved by called routine.
	#define	r7	%edi	// Must be preserved by called routine.
#elif defined __x86_64__
	#define	r0	%rax	// Available for any use.
	#define	r1	%rcx	// Available for any use.
	#define	r2	%rdx	// Available for any use.
	#define	r3	%rbx	// Must be preserved by called routine.
	#define	r4	%rsp	// Stack pointer.
	#define	r5	%rbp	// Frame pointer.  Must be preserved by called routine.
	#define	r6	%rsi	// Available for any use.
	#define	r7	%rdi	// Available for any use.
	#define	r8	%r8		// Available for any use.
	#define	r9	%r9		// Available for any use.
	#define	r10	%r10	// Available for any use.
	#define	r11	%r11	// Available for any use.
	#define	r12	%r12	// Must be preserved by called routine.
	#define	r13	%r13	// Must be preserved by called routine.
	#define	r14	%r14	// Must be preserved by called routine.
	#define	r15	%r15	// Must be preserved by called routine.
#else
	#error "Unknown architecture."
#endif

// Define names for parts of registers.

#define	r0d		%eax	// Low 32 bits of r0.
#define	r1d		%ecx	// Low 32 bits of r1.
#define	r2d		%edx	// Low 32 bits of r2.
#define	r3d		%ebx	// Low 32 bits of r3.
#define	r5d		%ebp	// Low 32 bits of r5.
#define	r6d		%esi	// Low 32 bits of r6.
#define	r7d		%edi	// Low 32 bits of r7.
#define	r8d		%r8d	// Low 32 bits of r8.
#define	r9d		%r9d	// Low 32 bits of r9.
#define	r11d	%r11d	// Low 32 bits of r11.

#define	r0l		%al		// Low byte of r0.
#define	r1l		%cl		// Low byte of r1.
#define	r2l		%dl		// Low byte of r2.
#define	r3l		%bl		// Low byte of r3.
#define	r5l		%bpl	// Low byte of r5.

#define	r0h		%ah		// Second lowest byte of r0.
#define	r1h		%ch		// Second lowest byte of r1.
#define	r2h		%dh		// Second lowest byte of r2.
#define	r3h		%bh		// Second lowest byte of r3.


	.text


// Define encryption routine, _AESEncryptWithExpandedKey
#define	Select	0
#include "EncryptDecrypt.s"
#undef	Select


// Define decryption routine, _AESDecryptWithExpandedKey
#define	Select	1
#include "EncryptDecrypt.s"
#undef	Select


// Define key expansion routine for encryption, _AESExpandKeyForEncryption.
#include "ExpandKeyForEncryption.s"


// Define key expansion for decryption routine, _AESExpandKeyForDecryption.
#include "ExpandKeyForDecryption.s"


#endif	// defined UseAESedp_IntelAssembly
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































Deleted Source/AESedp/Intel/Data.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
// This file was generated by MakeData.c.


	.const


// Round constants.
	.globl	_OLDAESRcon
	.private_extern	_OLDAESRcon
_OLDAESRcon:
	.byte	0	// Not used, included for indexing simplicity.
	.byte	0x01
	.byte	0x02
	.byte	0x04
	.byte	0x08
	.byte	0x10
	.byte	0x20
	.byte	0x40
	.byte	0x80
	.byte	0x1b
	.byte	0x36


// Tables for InvMixColumn.
	.globl	_OLDAESInvMixColumnTable
	.private_extern	_OLDAESInvMixColumnTable
	.align	2
_OLDAESInvMixColumnTable:
	// Table 0.
	.long	0x00000000
	.long	0x0b0d090e
	.long	0x161a121c
	.long	0x1d171b12
	.long	0x2c342438
	.long	0x27392d36
	.long	0x3a2e3624
	.long	0x31233f2a
	.long	0x58684870
	.long	0x5365417e
	.long	0x4e725a6c
	.long	0x457f5362
	.long	0x745c6c48
	.long	0x7f516546
	.long	0x62467e54
	.long	0x694b775a
	.long	0xb0d090e0
	.long	0xbbdd99ee
	.long	0xa6ca82fc
	.long	0xadc78bf2
	.long	0x9ce4b4d8
	.long	0x97e9bdd6
	.long	0x8afea6c4
	.long	0x81f3afca
	.long	0xe8b8d890
	.long	0xe3b5d19e
	.long	0xfea2ca8c
	.long	0xf5afc382
	.long	0xc48cfca8
	.long	0xcf81f5a6
	.long	0xd296eeb4
	.long	0xd99be7ba
	.long	0x7bbb3bdb
	.long	0x70b632d5
	.long	0x6da129c7
	.long	0x66ac20c9
	.long	0x578f1fe3
	.long	0x5c8216ed
	.long	0x41950dff
	.long	0x4a9804f1
	.long	0x23d373ab
	.long	0x28de7aa5
	.long	0x35c961b7
	.long	0x3ec468b9
	.long	0x0fe75793
	.long	0x04ea5e9d
	.long	0x19fd458f
	.long	0x12f04c81
	.long	0xcb6bab3b
	.long	0xc066a235
	.long	0xdd71b927
	.long	0xd67cb029
	.long	0xe75f8f03
	.long	0xec52860d
	.long	0xf1459d1f
	.long	0xfa489411
	.long	0x9303e34b
	.long	0x980eea45
	.long	0x8519f157
	.long	0x8e14f859
	.long	0xbf37c773
	.long	0xb43ace7d
	.long	0xa92dd56f
	.long	0xa220dc61
	.long	0xf66d76ad
	.long	0xfd607fa3
	.long	0xe07764b1
	.long	0xeb7a6dbf
	.long	0xda595295
	.long	0xd1545b9b
	.long	0xcc434089
	.long	0xc74e4987
	.long	0xae053edd
	.long	0xa50837d3
	.long	0xb81f2cc1
	.long	0xb31225cf
	.long	0x82311ae5
	.long	0x893c13eb
	.long	0x942b08f9
	.long	0x9f2601f7
	.long	0x46bde64d
	.long	0x4db0ef43
	.long	0x50a7f451
	.long	0x5baafd5f
	.long	0x6a89c275
	.long	0x6184cb7b
	.long	0x7c93d069
	.long	0x779ed967
	.long	0x1ed5ae3d
	.long	0x15d8a733
	.long	0x08cfbc21
	.long	0x03c2b52f
	.long	0x32e18a05
	.long	0x39ec830b
	.long	0x24fb9819
	.long	0x2ff69117
	.long	0x8dd64d76
	.long	0x86db4478
	.long	0x9bcc5f6a
	.long	0x90c15664
	.long	0xa1e2694e
	.long	0xaaef6040
	.long	0xb7f87b52
	.long	0xbcf5725c
	.long	0xd5be0506
	.long	0xdeb30c08
	.long	0xc3a4171a
	.long	0xc8a91e14
	.long	0xf98a213e
	.long	0xf2872830
	.long	0xef903322
	.long	0xe49d3a2c
	.long	0x3d06dd96
	.long	0x360bd498
	.long	0x2b1ccf8a
	.long	0x2011c684
	.long	0x1132f9ae
	.long	0x1a3ff0a0
	.long	0x0728ebb2
	.long	0x0c25e2bc
	.long	0x656e95e6
	.long	0x6e639ce8
	.long	0x737487fa
	.long	0x78798ef4
	.long	0x495ab1de
	.long	0x4257b8d0
	.long	0x5f40a3c2
	.long	0x544daacc
	.long	0xf7daec41
	.long	0xfcd7e54f
	.long	0xe1c0fe5d
	.long	0xeacdf753
	.long	0xdbeec879
	.long	0xd0e3c177
	.long	0xcdf4da65
	.long	0xc6f9d36b
	.long	0xafb2a431
	.long	0xa4bfad3f
	.long	0xb9a8b62d
	.long	0xb2a5bf23
	.long	0x83868009
	.long	0x888b8907
	.long	0x959c9215
	.long	0x9e919b1b
	.long	0x470a7ca1
	.long	0x4c0775af
	.long	0x51106ebd
	.long	0x5a1d67b3
	.long	0x6b3e5899
	.long	0x60335197
	.long	0x7d244a85
	.long	0x7629438b
	.long	0x1f6234d1
	.long	0x146f3ddf
	.long	0x097826cd
	.long	0x02752fc3
	.long	0x335610e9
	.long	0x385b19e7
	.long	0x254c02f5
	.long	0x2e410bfb
	.long	0x8c61d79a
	.long	0x876cde94
	.long	0x9a7bc586
	.long	0x9176cc88
	.long	0xa055f3a2
	.long	0xab58faac
	.long	0xb64fe1be
	.long	0xbd42e8b0
	.long	0xd4099fea
	.long	0xdf0496e4
	.long	0xc2138df6
	.long	0xc91e84f8
	.long	0xf83dbbd2
	.long	0xf330b2dc
	.long	0xee27a9ce
	.long	0xe52aa0c0
	.long	0x3cb1477a
	.long	0x37bc4e74
	.long	0x2aab5566
	.long	0x21a65c68
	.long	0x10856342
	.long	0x1b886a4c
	.long	0x069f715e
	.long	0x0d927850
	.long	0x64d90f0a
	.long	0x6fd40604
	.long	0x72c31d16
	.long	0x79ce1418
	.long	0x48ed2b32
	.long	0x43e0223c
	.long	0x5ef7392e
	.long	0x55fa3020
	.long	0x01b79aec
	.long	0x0aba93e2
	.long	0x17ad88f0
	.long	0x1ca081fe
	.long	0x2d83bed4
	.long	0x268eb7da
	.long	0x3b99acc8
	.long	0x3094a5c6
	.long	0x59dfd29c
	.long	0x52d2db92
	.long	0x4fc5c080
	.long	0x44c8c98e
	.long	0x75ebf6a4
	.long	0x7ee6ffaa
	.long	0x63f1e4b8
	.long	0x68fcedb6
	.long	0xb1670a0c
	.long	0xba6a0302
	.long	0xa77d1810
	.long	0xac70111e
	.long	0x9d532e34
	.long	0x965e273a
	.long	0x8b493c28
	.long	0x80443526
	.long	0xe90f427c
	.long	0xe2024b72
	.long	0xff155060
	.long	0xf418596e
	.long	0xc53b6644
	.long	0xce366f4a
	.long	0xd3217458
	.long	0xd82c7d56
	.long	0x7a0ca137
	.long	0x7101a839
	.long	0x6c16b32b
	.long	0x671bba25
	.long	0x5638850f
	.long	0x5d358c01
	.long	0x40229713
	.long	0x4b2f9e1d
	.long	0x2264e947
	.long	0x2969e049
	.long	0x347efb5b
	.long	0x3f73f255
	.long	0x0e50cd7f
	.long	0x055dc471
	.long	0x184adf63
	.long	0x1347d66d
	.long	0xcadc31d7
	.long	0xc1d138d9
	.long	0xdcc623cb
	.long	0xd7cb2ac5
	.long	0xe6e815ef
	.long	0xede51ce1
	.long	0xf0f207f3
	.long	0xfbff0efd
	.long	0x92b479a7
	.long	0x99b970a9
	.long	0x84ae6bbb
	.long	0x8fa362b5
	.long	0xbe805d9f
	.long	0xb58d5491
	.long	0xa89a4f83
	.long	0xa397468d
	// Table 1.
	.long	0x00000000
	.long	0x0d090e0b
	.long	0x1a121c16
	.long	0x171b121d
	.long	0x3424382c
	.long	0x392d3627
	.long	0x2e36243a
	.long	0x233f2a31
	.long	0x68487058
	.long	0x65417e53
	.long	0x725a6c4e
	.long	0x7f536245
	.long	0x5c6c4874
	.long	0x5165467f
	.long	0x467e5462
	.long	0x4b775a69
	.long	0xd090e0b0
	.long	0xdd99eebb
	.long	0xca82fca6
	.long	0xc78bf2ad
	.long	0xe4b4d89c
	.long	0xe9bdd697
	.long	0xfea6c48a
	.long	0xf3afca81
	.long	0xb8d890e8
	.long	0xb5d19ee3
	.long	0xa2ca8cfe
	.long	0xafc382f5
	.long	0x8cfca8c4
	.long	0x81f5a6cf
	.long	0x96eeb4d2
	.long	0x9be7bad9
	.long	0xbb3bdb7b
	.long	0xb632d570
	.long	0xa129c76d
	.long	0xac20c966
	.long	0x8f1fe357
	.long	0x8216ed5c
	.long	0x950dff41
	.long	0x9804f14a
	.long	0xd373ab23
	.long	0xde7aa528
	.long	0xc961b735
	.long	0xc468b93e
	.long	0xe757930f
	.long	0xea5e9d04
	.long	0xfd458f19
	.long	0xf04c8112
	.long	0x6bab3bcb
	.long	0x66a235c0
	.long	0x71b927dd
	.long	0x7cb029d6
	.long	0x5f8f03e7
	.long	0x52860dec
	.long	0x459d1ff1
	.long	0x489411fa
	.long	0x03e34b93
	.long	0x0eea4598
	.long	0x19f15785
	.long	0x14f8598e
	.long	0x37c773bf
	.long	0x3ace7db4
	.long	0x2dd56fa9
	.long	0x20dc61a2
	.long	0x6d76adf6
	.long	0x607fa3fd
	.long	0x7764b1e0
	.long	0x7a6dbfeb
	.long	0x595295da
	.long	0x545b9bd1
	.long	0x434089cc
	.long	0x4e4987c7
	.long	0x053eddae
	.long	0x0837d3a5
	.long	0x1f2cc1b8
	.long	0x1225cfb3
	.long	0x311ae582
	.long	0x3c13eb89
	.long	0x2b08f994
	.long	0x2601f79f
	.long	0xbde64d46
	.long	0xb0ef434d
	.long	0xa7f45150
	.long	0xaafd5f5b
	.long	0x89c2756a
	.long	0x84cb7b61
	.long	0x93d0697c
	.long	0x9ed96777
	.long	0xd5ae3d1e
	.long	0xd8a73315
	.long	0xcfbc2108
	.long	0xc2b52f03
	.long	0xe18a0532
	.long	0xec830b39
	.long	0xfb981924
	.long	0xf691172f
	.long	0xd64d768d
	.long	0xdb447886
	.long	0xcc5f6a9b
	.long	0xc1566490
	.long	0xe2694ea1
	.long	0xef6040aa
	.long	0xf87b52b7
	.long	0xf5725cbc
	.long	0xbe0506d5
	.long	0xb30c08de
	.long	0xa4171ac3
	.long	0xa91e14c8
	.long	0x8a213ef9
	.long	0x872830f2
	.long	0x903322ef
	.long	0x9d3a2ce4
	.long	0x06dd963d
	.long	0x0bd49836
	.long	0x1ccf8a2b
	.long	0x11c68420
	.long	0x32f9ae11
	.long	0x3ff0a01a
	.long	0x28ebb207
	.long	0x25e2bc0c
	.long	0x6e95e665
	.long	0x639ce86e
	.long	0x7487fa73
	.long	0x798ef478
	.long	0x5ab1de49
	.long	0x57b8d042
	.long	0x40a3c25f
	.long	0x4daacc54
	.long	0xdaec41f7
	.long	0xd7e54ffc
	.long	0xc0fe5de1
	.long	0xcdf753ea
	.long	0xeec879db
	.long	0xe3c177d0
	.long	0xf4da65cd
	.long	0xf9d36bc6
	.long	0xb2a431af
	.long	0xbfad3fa4
	.long	0xa8b62db9
	.long	0xa5bf23b2
	.long	0x86800983
	.long	0x8b890788
	.long	0x9c921595
	.long	0x919b1b9e
	.long	0x0a7ca147
	.long	0x0775af4c
	.long	0x106ebd51
	.long	0x1d67b35a
	.long	0x3e58996b
	.long	0x33519760
	.long	0x244a857d
	.long	0x29438b76
	.long	0x6234d11f
	.long	0x6f3ddf14
	.long	0x7826cd09
	.long	0x752fc302
	.long	0x5610e933
	.long	0x5b19e738
	.long	0x4c02f525
	.long	0x410bfb2e
	.long	0x61d79a8c
	.long	0x6cde9487
	.long	0x7bc5869a
	.long	0x76cc8891
	.long	0x55f3a2a0
	.long	0x58faacab
	.long	0x4fe1beb6
	.long	0x42e8b0bd
	.long	0x099fead4
	.long	0x0496e4df
	.long	0x138df6c2
	.long	0x1e84f8c9
	.long	0x3dbbd2f8
	.long	0x30b2dcf3
	.long	0x27a9ceee
	.long	0x2aa0c0e5
	.long	0xb1477a3c
	.long	0xbc4e7437
	.long	0xab55662a
	.long	0xa65c6821
	.long	0x85634210
	.long	0x886a4c1b
	.long	0x9f715e06
	.long	0x9278500d
	.long	0xd90f0a64
	.long	0xd406046f
	.long	0xc31d1672
	.long	0xce141879
	.long	0xed2b3248
	.long	0xe0223c43
	.long	0xf7392e5e
	.long	0xfa302055
	.long	0xb79aec01
	.long	0xba93e20a
	.long	0xad88f017
	.long	0xa081fe1c
	.long	0x83bed42d
	.long	0x8eb7da26
	.long	0x99acc83b
	.long	0x94a5c630
	.long	0xdfd29c59
	.long	0xd2db9252
	.long	0xc5c0804f
	.long	0xc8c98e44
	.long	0xebf6a475
	.long	0xe6ffaa7e
	.long	0xf1e4b863
	.long	0xfcedb668
	.long	0x670a0cb1
	.long	0x6a0302ba
	.long	0x7d1810a7
	.long	0x70111eac
	.long	0x532e349d
	.long	0x5e273a96
	.long	0x493c288b
	.long	0x44352680
	.long	0x0f427ce9
	.long	0x024b72e2
	.long	0x155060ff
	.long	0x18596ef4
	.long	0x3b6644c5
	.long	0x366f4ace
	.long	0x217458d3
	.long	0x2c7d56d8
	.long	0x0ca1377a
	.long	0x01a83971
	.long	0x16b32b6c
	.long	0x1bba2567
	.long	0x38850f56
	.long	0x358c015d
	.long	0x22971340
	.long	0x2f9e1d4b
	.long	0x64e94722
	.long	0x69e04929
	.long	0x7efb5b34
	.long	0x73f2553f
	.long	0x50cd7f0e
	.long	0x5dc47105
	.long	0x4adf6318
	.long	0x47d66d13
	.long	0xdc31d7ca
	.long	0xd138d9c1
	.long	0xc623cbdc
	.long	0xcb2ac5d7
	.long	0xe815efe6
	.long	0xe51ce1ed
	.long	0xf207f3f0
	.long	0xff0efdfb
	.long	0xb479a792
	.long	0xb970a999
	.long	0xae6bbb84
	.long	0xa362b58f
	.long	0x805d9fbe
	.long	0x8d5491b5
	.long	0x9a4f83a8
	.long	0x97468da3
	// Table 2.
	.long	0x00000000
	.long	0x090e0b0d
	.long	0x121c161a
	.long	0x1b121d17
	.long	0x24382c34
	.long	0x2d362739
	.long	0x36243a2e
	.long	0x3f2a3123
	.long	0x48705868
	.long	0x417e5365
	.long	0x5a6c4e72
	.long	0x5362457f
	.long	0x6c48745c
	.long	0x65467f51
	.long	0x7e546246
	.long	0x775a694b
	.long	0x90e0b0d0
	.long	0x99eebbdd
	.long	0x82fca6ca
	.long	0x8bf2adc7
	.long	0xb4d89ce4
	.long	0xbdd697e9
	.long	0xa6c48afe
	.long	0xafca81f3
	.long	0xd890e8b8
	.long	0xd19ee3b5
	.long	0xca8cfea2
	.long	0xc382f5af
	.long	0xfca8c48c
	.long	0xf5a6cf81
	.long	0xeeb4d296
	.long	0xe7bad99b
	.long	0x3bdb7bbb
	.long	0x32d570b6
	.long	0x29c76da1
	.long	0x20c966ac
	.long	0x1fe3578f
	.long	0x16ed5c82
	.long	0x0dff4195
	.long	0x04f14a98
	.long	0x73ab23d3
	.long	0x7aa528de
	.long	0x61b735c9
	.long	0x68b93ec4
	.long	0x57930fe7
	.long	0x5e9d04ea
	.long	0x458f19fd
	.long	0x4c8112f0
	.long	0xab3bcb6b
	.long	0xa235c066
	.long	0xb927dd71
	.long	0xb029d67c
	.long	0x8f03e75f
	.long	0x860dec52
	.long	0x9d1ff145
	.long	0x9411fa48
	.long	0xe34b9303
	.long	0xea45980e
	.long	0xf1578519
	.long	0xf8598e14
	.long	0xc773bf37
	.long	0xce7db43a
	.long	0xd56fa92d
	.long	0xdc61a220
	.long	0x76adf66d
	.long	0x7fa3fd60
	.long	0x64b1e077
	.long	0x6dbfeb7a
	.long	0x5295da59
	.long	0x5b9bd154
	.long	0x4089cc43
	.long	0x4987c74e
	.long	0x3eddae05
	.long	0x37d3a508
	.long	0x2cc1b81f
	.long	0x25cfb312
	.long	0x1ae58231
	.long	0x13eb893c
	.long	0x08f9942b
	.long	0x01f79f26
	.long	0xe64d46bd
	.long	0xef434db0
	.long	0xf45150a7
	.long	0xfd5f5baa
	.long	0xc2756a89
	.long	0xcb7b6184
	.long	0xd0697c93
	.long	0xd967779e
	.long	0xae3d1ed5
	.long	0xa73315d8
	.long	0xbc2108cf
	.long	0xb52f03c2
	.long	0x8a0532e1
	.long	0x830b39ec
	.long	0x981924fb
	.long	0x91172ff6
	.long	0x4d768dd6
	.long	0x447886db
	.long	0x5f6a9bcc
	.long	0x566490c1
	.long	0x694ea1e2
	.long	0x6040aaef
	.long	0x7b52b7f8
	.long	0x725cbcf5
	.long	0x0506d5be
	.long	0x0c08deb3
	.long	0x171ac3a4
	.long	0x1e14c8a9
	.long	0x213ef98a
	.long	0x2830f287
	.long	0x3322ef90
	.long	0x3a2ce49d
	.long	0xdd963d06
	.long	0xd498360b
	.long	0xcf8a2b1c
	.long	0xc6842011
	.long	0xf9ae1132
	.long	0xf0a01a3f
	.long	0xebb20728
	.long	0xe2bc0c25
	.long	0x95e6656e
	.long	0x9ce86e63
	.long	0x87fa7374
	.long	0x8ef47879
	.long	0xb1de495a
	.long	0xb8d04257
	.long	0xa3c25f40
	.long	0xaacc544d
	.long	0xec41f7da
	.long	0xe54ffcd7
	.long	0xfe5de1c0
	.long	0xf753eacd
	.long	0xc879dbee
	.long	0xc177d0e3
	.long	0xda65cdf4
	.long	0xd36bc6f9
	.long	0xa431afb2
	.long	0xad3fa4bf
	.long	0xb62db9a8
	.long	0xbf23b2a5
	.long	0x80098386
	.long	0x8907888b
	.long	0x9215959c
	.long	0x9b1b9e91
	.long	0x7ca1470a
	.long	0x75af4c07
	.long	0x6ebd5110
	.long	0x67b35a1d
	.long	0x58996b3e
	.long	0x51976033
	.long	0x4a857d24
	.long	0x438b7629
	.long	0x34d11f62
	.long	0x3ddf146f
	.long	0x26cd0978
	.long	0x2fc30275
	.long	0x10e93356
	.long	0x19e7385b
	.long	0x02f5254c
	.long	0x0bfb2e41
	.long	0xd79a8c61
	.long	0xde94876c
	.long	0xc5869a7b
	.long	0xcc889176
	.long	0xf3a2a055
	.long	0xfaacab58
	.long	0xe1beb64f
	.long	0xe8b0bd42
	.long	0x9fead409
	.long	0x96e4df04
	.long	0x8df6c213
	.long	0x84f8c91e
	.long	0xbbd2f83d
	.long	0xb2dcf330
	.long	0xa9ceee27
	.long	0xa0c0e52a
	.long	0x477a3cb1
	.long	0x4e7437bc
	.long	0x55662aab
	.long	0x5c6821a6
	.long	0x63421085
	.long	0x6a4c1b88
	.long	0x715e069f
	.long	0x78500d92
	.long	0x0f0a64d9
	.long	0x06046fd4
	.long	0x1d1672c3
	.long	0x141879ce
	.long	0x2b3248ed
	.long	0x223c43e0
	.long	0x392e5ef7
	.long	0x302055fa
	.long	0x9aec01b7
	.long	0x93e20aba
	.long	0x88f017ad
	.long	0x81fe1ca0
	.long	0xbed42d83
	.long	0xb7da268e
	.long	0xacc83b99
	.long	0xa5c63094
	.long	0xd29c59df
	.long	0xdb9252d2
	.long	0xc0804fc5
	.long	0xc98e44c8
	.long	0xf6a475eb
	.long	0xffaa7ee6
	.long	0xe4b863f1
	.long	0xedb668fc
	.long	0x0a0cb167
	.long	0x0302ba6a
	.long	0x1810a77d
	.long	0x111eac70
	.long	0x2e349d53
	.long	0x273a965e
	.long	0x3c288b49
	.long	0x35268044
	.long	0x427ce90f
	.long	0x4b72e202
	.long	0x5060ff15
	.long	0x596ef418
	.long	0x6644c53b
	.long	0x6f4ace36
	.long	0x7458d321
	.long	0x7d56d82c
	.long	0xa1377a0c
	.long	0xa8397101
	.long	0xb32b6c16
	.long	0xba25671b
	.long	0x850f5638
	.long	0x8c015d35
	.long	0x97134022
	.long	0x9e1d4b2f
	.long	0xe9472264
	.long	0xe0492969
	.long	0xfb5b347e
	.long	0xf2553f73
	.long	0xcd7f0e50
	.long	0xc471055d
	.long	0xdf63184a
	.long	0xd66d1347
	.long	0x31d7cadc
	.long	0x38d9c1d1
	.long	0x23cbdcc6
	.long	0x2ac5d7cb
	.long	0x15efe6e8
	.long	0x1ce1ede5
	.long	0x07f3f0f2
	.long	0x0efdfbff
	.long	0x79a792b4
	.long	0x70a999b9
	.long	0x6bbb84ae
	.long	0x62b58fa3
	.long	0x5d9fbe80
	.long	0x5491b58d
	.long	0x4f83a89a
	.long	0x468da397
	// Table 3.
	.long	0x00000000
	.long	0x0e0b0d09
	.long	0x1c161a12
	.long	0x121d171b
	.long	0x382c3424
	.long	0x3627392d
	.long	0x243a2e36
	.long	0x2a31233f
	.long	0x70586848
	.long	0x7e536541
	.long	0x6c4e725a
	.long	0x62457f53
	.long	0x48745c6c
	.long	0x467f5165
	.long	0x5462467e
	.long	0x5a694b77
	.long	0xe0b0d090
	.long	0xeebbdd99
	.long	0xfca6ca82
	.long	0xf2adc78b
	.long	0xd89ce4b4
	.long	0xd697e9bd
	.long	0xc48afea6
	.long	0xca81f3af
	.long	0x90e8b8d8
	.long	0x9ee3b5d1
	.long	0x8cfea2ca
	.long	0x82f5afc3
	.long	0xa8c48cfc
	.long	0xa6cf81f5
	.long	0xb4d296ee
	.long	0xbad99be7
	.long	0xdb7bbb3b
	.long	0xd570b632
	.long	0xc76da129
	.long	0xc966ac20
	.long	0xe3578f1f
	.long	0xed5c8216
	.long	0xff41950d
	.long	0xf14a9804
	.long	0xab23d373
	.long	0xa528de7a
	.long	0xb735c961
	.long	0xb93ec468
	.long	0x930fe757
	.long	0x9d04ea5e
	.long	0x8f19fd45
	.long	0x8112f04c
	.long	0x3bcb6bab
	.long	0x35c066a2
	.long	0x27dd71b9
	.long	0x29d67cb0
	.long	0x03e75f8f
	.long	0x0dec5286
	.long	0x1ff1459d
	.long	0x11fa4894
	.long	0x4b9303e3
	.long	0x45980eea
	.long	0x578519f1
	.long	0x598e14f8
	.long	0x73bf37c7
	.long	0x7db43ace
	.long	0x6fa92dd5
	.long	0x61a220dc
	.long	0xadf66d76
	.long	0xa3fd607f
	.long	0xb1e07764
	.long	0xbfeb7a6d
	.long	0x95da5952
	.long	0x9bd1545b
	.long	0x89cc4340
	.long	0x87c74e49
	.long	0xddae053e
	.long	0xd3a50837
	.long	0xc1b81f2c
	.long	0xcfb31225
	.long	0xe582311a
	.long	0xeb893c13
	.long	0xf9942b08
	.long	0xf79f2601
	.long	0x4d46bde6
	.long	0x434db0ef
	.long	0x5150a7f4
	.long	0x5f5baafd
	.long	0x756a89c2
	.long	0x7b6184cb
	.long	0x697c93d0
	.long	0x67779ed9
	.long	0x3d1ed5ae
	.long	0x3315d8a7
	.long	0x2108cfbc
	.long	0x2f03c2b5
	.long	0x0532e18a
	.long	0x0b39ec83
	.long	0x1924fb98
	.long	0x172ff691
	.long	0x768dd64d
	.long	0x7886db44
	.long	0x6a9bcc5f
	.long	0x6490c156
	.long	0x4ea1e269
	.long	0x40aaef60
	.long	0x52b7f87b
	.long	0x5cbcf572
	.long	0x06d5be05
	.long	0x08deb30c
	.long	0x1ac3a417
	.long	0x14c8a91e
	.long	0x3ef98a21
	.long	0x30f28728
	.long	0x22ef9033
	.long	0x2ce49d3a
	.long	0x963d06dd
	.long	0x98360bd4
	.long	0x8a2b1ccf
	.long	0x842011c6
	.long	0xae1132f9
	.long	0xa01a3ff0
	.long	0xb20728eb
	.long	0xbc0c25e2
	.long	0xe6656e95
	.long	0xe86e639c
	.long	0xfa737487
	.long	0xf478798e
	.long	0xde495ab1
	.long	0xd04257b8
	.long	0xc25f40a3
	.long	0xcc544daa
	.long	0x41f7daec
	.long	0x4ffcd7e5
	.long	0x5de1c0fe
	.long	0x53eacdf7
	.long	0x79dbeec8
	.long	0x77d0e3c1
	.long	0x65cdf4da
	.long	0x6bc6f9d3
	.long	0x31afb2a4
	.long	0x3fa4bfad
	.long	0x2db9a8b6
	.long	0x23b2a5bf
	.long	0x09838680
	.long	0x07888b89
	.long	0x15959c92
	.long	0x1b9e919b
	.long	0xa1470a7c
	.long	0xaf4c0775
	.long	0xbd51106e
	.long	0xb35a1d67
	.long	0x996b3e58
	.long	0x97603351
	.long	0x857d244a
	.long	0x8b762943
	.long	0xd11f6234
	.long	0xdf146f3d
	.long	0xcd097826
	.long	0xc302752f
	.long	0xe9335610
	.long	0xe7385b19
	.long	0xf5254c02
	.long	0xfb2e410b
	.long	0x9a8c61d7
	.long	0x94876cde
	.long	0x869a7bc5
	.long	0x889176cc
	.long	0xa2a055f3
	.long	0xacab58fa
	.long	0xbeb64fe1
	.long	0xb0bd42e8
	.long	0xead4099f
	.long	0xe4df0496
	.long	0xf6c2138d
	.long	0xf8c91e84
	.long	0xd2f83dbb
	.long	0xdcf330b2
	.long	0xceee27a9
	.long	0xc0e52aa0
	.long	0x7a3cb147
	.long	0x7437bc4e
	.long	0x662aab55
	.long	0x6821a65c
	.long	0x42108563
	.long	0x4c1b886a
	.long	0x5e069f71
	.long	0x500d9278
	.long	0x0a64d90f
	.long	0x046fd406
	.long	0x1672c31d
	.long	0x1879ce14
	.long	0x3248ed2b
	.long	0x3c43e022
	.long	0x2e5ef739
	.long	0x2055fa30
	.long	0xec01b79a
	.long	0xe20aba93
	.long	0xf017ad88
	.long	0xfe1ca081
	.long	0xd42d83be
	.long	0xda268eb7
	.long	0xc83b99ac
	.long	0xc63094a5
	.long	0x9c59dfd2
	.long	0x9252d2db
	.long	0x804fc5c0
	.long	0x8e44c8c9
	.long	0xa475ebf6
	.long	0xaa7ee6ff
	.long	0xb863f1e4
	.long	0xb668fced
	.long	0x0cb1670a
	.long	0x02ba6a03
	.long	0x10a77d18
	.long	0x1eac7011
	.long	0x349d532e
	.long	0x3a965e27
	.long	0x288b493c
	.long	0x26804435
	.long	0x7ce90f42
	.long	0x72e2024b
	.long	0x60ff1550
	.long	0x6ef41859
	.long	0x44c53b66
	.long	0x4ace366f
	.long	0x58d32174
	.long	0x56d82c7d
	.long	0x377a0ca1
	.long	0x397101a8
	.long	0x2b6c16b3
	.long	0x25671bba
	.long	0x0f563885
	.long	0x015d358c
	.long	0x13402297
	.long	0x1d4b2f9e
	.long	0x472264e9
	.long	0x492969e0
	.long	0x5b347efb
	.long	0x553f73f2
	.long	0x7f0e50cd
	.long	0x71055dc4
	.long	0x63184adf
	.long	0x6d1347d6
	.long	0xd7cadc31
	.long	0xd9c1d138
	.long	0xcbdcc623
	.long	0xc5d7cb2a
	.long	0xefe6e815
	.long	0xe1ede51c
	.long	0xf3f0f207
	.long	0xfdfbff0e
	.long	0xa792b479
	.long	0xa999b970
	.long	0xbb84ae6b
	.long	0xb58fa362
	.long	0x9fbe805d
	.long	0x91b58d54
	.long	0x83a89a4f
	.long	0x8da39746


// Tables for main encryption iterations.
	.globl	_OLDAESEncryptTable
	.private_extern	_OLDAESEncryptTable
	.align	2
_OLDAESEncryptTable:
	// Table 0.
	.long	0xa56363c6
	.long	0x847c7cf8
	.long	0x997777ee
	.long	0x8d7b7bf6
	.long	0x0df2f2ff
	.long	0xbd6b6bd6
	.long	0xb16f6fde
	.long	0x54c5c591
	.long	0x50303060
	.long	0x03010102
	.long	0xa96767ce
	.long	0x7d2b2b56
	.long	0x19fefee7
	.long	0x62d7d7b5
	.long	0xe6abab4d
	.long	0x9a7676ec
	.long	0x45caca8f
	.long	0x9d82821f
	.long	0x40c9c989
	.long	0x877d7dfa
	.long	0x15fafaef
	.long	0xeb5959b2
	.long	0xc947478e
	.long	0x0bf0f0fb
	.long	0xecadad41
	.long	0x67d4d4b3
	.long	0xfda2a25f
	.long	0xeaafaf45
	.long	0xbf9c9c23
	.long	0xf7a4a453
	.long	0x967272e4
	.long	0x5bc0c09b
	.long	0xc2b7b775
	.long	0x1cfdfde1
	.long	0xae93933d
	.long	0x6a26264c
	.long	0x5a36366c
	.long	0x413f3f7e
	.long	0x02f7f7f5
	.long	0x4fcccc83
	.long	0x5c343468
	.long	0xf4a5a551
	.long	0x34e5e5d1
	.long	0x08f1f1f9
	.long	0x937171e2
	.long	0x73d8d8ab
	.long	0x53313162
	.long	0x3f15152a
	.long	0x0c040408
	.long	0x52c7c795
	.long	0x65232346
	.long	0x5ec3c39d
	.long	0x28181830
	.long	0xa1969637
	.long	0x0f05050a
	.long	0xb59a9a2f
	.long	0x0907070e
	.long	0x36121224
	.long	0x9b80801b
	.long	0x3de2e2df
	.long	0x26ebebcd
	.long	0x6927274e
	.long	0xcdb2b27f
	.long	0x9f7575ea
	.long	0x1b090912
	.long	0x9e83831d
	.long	0x742c2c58
	.long	0x2e1a1a34
	.long	0x2d1b1b36
	.long	0xb26e6edc
	.long	0xee5a5ab4
	.long	0xfba0a05b
	.long	0xf65252a4
	.long	0x4d3b3b76
	.long	0x61d6d6b7
	.long	0xceb3b37d
	.long	0x7b292952
	.long	0x3ee3e3dd
	.long	0x712f2f5e
	.long	0x97848413
	.long	0xf55353a6
	.long	0x68d1d1b9
	.long	0x00000000
	.long	0x2cededc1
	.long	0x60202040
	.long	0x1ffcfce3
	.long	0xc8b1b179
	.long	0xed5b5bb6
	.long	0xbe6a6ad4
	.long	0x46cbcb8d
	.long	0xd9bebe67
	.long	0x4b393972
	.long	0xde4a4a94
	.long	0xd44c4c98
	.long	0xe85858b0
	.long	0x4acfcf85
	.long	0x6bd0d0bb
	.long	0x2aefefc5
	.long	0xe5aaaa4f
	.long	0x16fbfbed
	.long	0xc5434386
	.long	0xd74d4d9a
	.long	0x55333366
	.long	0x94858511
	.long	0xcf45458a
	.long	0x10f9f9e9
	.long	0x06020204
	.long	0x817f7ffe
	.long	0xf05050a0
	.long	0x443c3c78
	.long	0xba9f9f25
	.long	0xe3a8a84b
	.long	0xf35151a2
	.long	0xfea3a35d
	.long	0xc0404080
	.long	0x8a8f8f05
	.long	0xad92923f
	.long	0xbc9d9d21
	.long	0x48383870
	.long	0x04f5f5f1
	.long	0xdfbcbc63
	.long	0xc1b6b677
	.long	0x75dadaaf
	.long	0x63212142
	.long	0x30101020
	.long	0x1affffe5
	.long	0x0ef3f3fd
	.long	0x6dd2d2bf
	.long	0x4ccdcd81
	.long	0x140c0c18
	.long	0x35131326
	.long	0x2fececc3
	.long	0xe15f5fbe
	.long	0xa2979735
	.long	0xcc444488
	.long	0x3917172e
	.long	0x57c4c493
	.long	0xf2a7a755
	.long	0x827e7efc
	.long	0x473d3d7a
	.long	0xac6464c8
	.long	0xe75d5dba
	.long	0x2b191932
	.long	0x957373e6
	.long	0xa06060c0
	.long	0x98818119
	.long	0xd14f4f9e
	.long	0x7fdcdca3
	.long	0x66222244
	.long	0x7e2a2a54
	.long	0xab90903b
	.long	0x8388880b
	.long	0xca46468c
	.long	0x29eeeec7
	.long	0xd3b8b86b
	.long	0x3c141428
	.long	0x79dedea7
	.long	0xe25e5ebc
	.long	0x1d0b0b16
	.long	0x76dbdbad
	.long	0x3be0e0db
	.long	0x56323264
	.long	0x4e3a3a74
	.long	0x1e0a0a14
	.long	0xdb494992
	.long	0x0a06060c
	.long	0x6c242448
	.long	0xe45c5cb8
	.long	0x5dc2c29f
	.long	0x6ed3d3bd
	.long	0xefacac43
	.long	0xa66262c4
	.long	0xa8919139
	.long	0xa4959531
	.long	0x37e4e4d3
	.long	0x8b7979f2
	.long	0x32e7e7d5
	.long	0x43c8c88b
	.long	0x5937376e
	.long	0xb76d6dda
	.long	0x8c8d8d01
	.long	0x64d5d5b1
	.long	0xd24e4e9c
	.long	0xe0a9a949
	.long	0xb46c6cd8
	.long	0xfa5656ac
	.long	0x07f4f4f3
	.long	0x25eaeacf
	.long	0xaf6565ca
	.long	0x8e7a7af4
	.long	0xe9aeae47
	.long	0x18080810
	.long	0xd5baba6f
	.long	0x887878f0
	.long	0x6f25254a
	.long	0x722e2e5c
	.long	0x241c1c38
	.long	0xf1a6a657
	.long	0xc7b4b473
	.long	0x51c6c697
	.long	0x23e8e8cb
	.long	0x7cdddda1
	.long	0x9c7474e8
	.long	0x211f1f3e
	.long	0xdd4b4b96
	.long	0xdcbdbd61
	.long	0x868b8b0d
	.long	0x858a8a0f
	.long	0x907070e0
	.long	0x423e3e7c
	.long	0xc4b5b571
	.long	0xaa6666cc
	.long	0xd8484890
	.long	0x05030306
	.long	0x01f6f6f7
	.long	0x120e0e1c
	.long	0xa36161c2
	.long	0x5f35356a
	.long	0xf95757ae
	.long	0xd0b9b969
	.long	0x91868617
	.long	0x58c1c199
	.long	0x271d1d3a
	.long	0xb99e9e27
	.long	0x38e1e1d9
	.long	0x13f8f8eb
	.long	0xb398982b
	.long	0x33111122
	.long	0xbb6969d2
	.long	0x70d9d9a9
	.long	0x898e8e07
	.long	0xa7949433
	.long	0xb69b9b2d
	.long	0x221e1e3c
	.long	0x92878715
	.long	0x20e9e9c9
	.long	0x49cece87
	.long	0xff5555aa
	.long	0x78282850
	.long	0x7adfdfa5
	.long	0x8f8c8c03
	.long	0xf8a1a159
	.long	0x80898909
	.long	0x170d0d1a
	.long	0xdabfbf65
	.long	0x31e6e6d7
	.long	0xc6424284
	.long	0xb86868d0
	.long	0xc3414182
	.long	0xb0999929
	.long	0x772d2d5a
	.long	0x110f0f1e
	.long	0xcbb0b07b
	.long	0xfc5454a8
	.long	0xd6bbbb6d
	.long	0x3a16162c
	// Table 1.
	.long	0x6363c6a5
	.long	0x7c7cf884
	.long	0x7777ee99
	.long	0x7b7bf68d
	.long	0xf2f2ff0d
	.long	0x6b6bd6bd
	.long	0x6f6fdeb1
	.long	0xc5c59154
	.long	0x30306050
	.long	0x01010203
	.long	0x6767cea9
	.long	0x2b2b567d
	.long	0xfefee719
	.long	0xd7d7b562
	.long	0xabab4de6
	.long	0x7676ec9a
	.long	0xcaca8f45
	.long	0x82821f9d
	.long	0xc9c98940
	.long	0x7d7dfa87
	.long	0xfafaef15
	.long	0x5959b2eb
	.long	0x47478ec9
	.long	0xf0f0fb0b
	.long	0xadad41ec
	.long	0xd4d4b367
	.long	0xa2a25ffd
	.long	0xafaf45ea
	.long	0x9c9c23bf
	.long	0xa4a453f7
	.long	0x7272e496
	.long	0xc0c09b5b
	.long	0xb7b775c2
	.long	0xfdfde11c
	.long	0x93933dae
	.long	0x26264c6a
	.long	0x36366c5a
	.long	0x3f3f7e41
	.long	0xf7f7f502
	.long	0xcccc834f
	.long	0x3434685c
	.long	0xa5a551f4
	.long	0xe5e5d134
	.long	0xf1f1f908
	.long	0x7171e293
	.long	0xd8d8ab73
	.long	0x31316253
	.long	0x15152a3f
	.long	0x0404080c
	.long	0xc7c79552
	.long	0x23234665
	.long	0xc3c39d5e
	.long	0x18183028
	.long	0x969637a1
	.long	0x05050a0f
	.long	0x9a9a2fb5
	.long	0x07070e09
	.long	0x12122436
	.long	0x80801b9b
	.long	0xe2e2df3d
	.long	0xebebcd26
	.long	0x27274e69
	.long	0xb2b27fcd
	.long	0x7575ea9f
	.long	0x0909121b
	.long	0x83831d9e
	.long	0x2c2c5874
	.long	0x1a1a342e
	.long	0x1b1b362d
	.long	0x6e6edcb2
	.long	0x5a5ab4ee
	.long	0xa0a05bfb
	.long	0x5252a4f6
	.long	0x3b3b764d
	.long	0xd6d6b761
	.long	0xb3b37dce
	.long	0x2929527b
	.long	0xe3e3dd3e
	.long	0x2f2f5e71
	.long	0x84841397
	.long	0x5353a6f5
	.long	0xd1d1b968
	.long	0x00000000
	.long	0xededc12c
	.long	0x20204060
	.long	0xfcfce31f
	.long	0xb1b179c8
	.long	0x5b5bb6ed
	.long	0x6a6ad4be
	.long	0xcbcb8d46
	.long	0xbebe67d9
	.long	0x3939724b
	.long	0x4a4a94de
	.long	0x4c4c98d4
	.long	0x5858b0e8
	.long	0xcfcf854a
	.long	0xd0d0bb6b
	.long	0xefefc52a
	.long	0xaaaa4fe5
	.long	0xfbfbed16
	.long	0x434386c5
	.long	0x4d4d9ad7
	.long	0x33336655
	.long	0x85851194
	.long	0x45458acf
	.long	0xf9f9e910
	.long	0x02020406
	.long	0x7f7ffe81
	.long	0x5050a0f0
	.long	0x3c3c7844
	.long	0x9f9f25ba
	.long	0xa8a84be3
	.long	0x5151a2f3
	.long	0xa3a35dfe
	.long	0x404080c0
	.long	0x8f8f058a
	.long	0x92923fad
	.long	0x9d9d21bc
	.long	0x38387048
	.long	0xf5f5f104
	.long	0xbcbc63df
	.long	0xb6b677c1
	.long	0xdadaaf75
	.long	0x21214263
	.long	0x10102030
	.long	0xffffe51a
	.long	0xf3f3fd0e
	.long	0xd2d2bf6d
	.long	0xcdcd814c
	.long	0x0c0c1814
	.long	0x13132635
	.long	0xececc32f
	.long	0x5f5fbee1
	.long	0x979735a2
	.long	0x444488cc
	.long	0x17172e39
	.long	0xc4c49357
	.long	0xa7a755f2
	.long	0x7e7efc82
	.long	0x3d3d7a47
	.long	0x6464c8ac
	.long	0x5d5dbae7
	.long	0x1919322b
	.long	0x7373e695
	.long	0x6060c0a0
	.long	0x81811998
	.long	0x4f4f9ed1
	.long	0xdcdca37f
	.long	0x22224466
	.long	0x2a2a547e
	.long	0x90903bab
	.long	0x88880b83
	.long	0x46468cca
	.long	0xeeeec729
	.long	0xb8b86bd3
	.long	0x1414283c
	.long	0xdedea779
	.long	0x5e5ebce2
	.long	0x0b0b161d
	.long	0xdbdbad76
	.long	0xe0e0db3b
	.long	0x32326456
	.long	0x3a3a744e
	.long	0x0a0a141e
	.long	0x494992db
	.long	0x06060c0a
	.long	0x2424486c
	.long	0x5c5cb8e4
	.long	0xc2c29f5d
	.long	0xd3d3bd6e
	.long	0xacac43ef
	.long	0x6262c4a6
	.long	0x919139a8
	.long	0x959531a4
	.long	0xe4e4d337
	.long	0x7979f28b
	.long	0xe7e7d532
	.long	0xc8c88b43
	.long	0x37376e59
	.long	0x6d6ddab7
	.long	0x8d8d018c
	.long	0xd5d5b164
	.long	0x4e4e9cd2
	.long	0xa9a949e0
	.long	0x6c6cd8b4
	.long	0x5656acfa
	.long	0xf4f4f307
	.long	0xeaeacf25
	.long	0x6565caaf
	.long	0x7a7af48e
	.long	0xaeae47e9
	.long	0x08081018
	.long	0xbaba6fd5
	.long	0x7878f088
	.long	0x25254a6f
	.long	0x2e2e5c72
	.long	0x1c1c3824
	.long	0xa6a657f1
	.long	0xb4b473c7
	.long	0xc6c69751
	.long	0xe8e8cb23
	.long	0xdddda17c
	.long	0x7474e89c
	.long	0x1f1f3e21
	.long	0x4b4b96dd
	.long	0xbdbd61dc
	.long	0x8b8b0d86
	.long	0x8a8a0f85
	.long	0x7070e090
	.long	0x3e3e7c42
	.long	0xb5b571c4
	.long	0x6666ccaa
	.long	0x484890d8
	.long	0x03030605
	.long	0xf6f6f701
	.long	0x0e0e1c12
	.long	0x6161c2a3
	.long	0x35356a5f
	.long	0x5757aef9
	.long	0xb9b969d0
	.long	0x86861791
	.long	0xc1c19958
	.long	0x1d1d3a27
	.long	0x9e9e27b9
	.long	0xe1e1d938
	.long	0xf8f8eb13
	.long	0x98982bb3
	.long	0x11112233
	.long	0x6969d2bb
	.long	0xd9d9a970
	.long	0x8e8e0789
	.long	0x949433a7
	.long	0x9b9b2db6
	.long	0x1e1e3c22
	.long	0x87871592
	.long	0xe9e9c920
	.long	0xcece8749
	.long	0x5555aaff
	.long	0x28285078
	.long	0xdfdfa57a
	.long	0x8c8c038f
	.long	0xa1a159f8
	.long	0x89890980
	.long	0x0d0d1a17
	.long	0xbfbf65da
	.long	0xe6e6d731
	.long	0x424284c6
	.long	0x6868d0b8
	.long	0x414182c3
	.long	0x999929b0
	.long	0x2d2d5a77
	.long	0x0f0f1e11
	.long	0xb0b07bcb
	.long	0x5454a8fc
	.long	0xbbbb6dd6
	.long	0x16162c3a
	// Table 2.
	.long	0x63c6a563
	.long	0x7cf8847c
	.long	0x77ee9977
	.long	0x7bf68d7b
	.long	0xf2ff0df2
	.long	0x6bd6bd6b
	.long	0x6fdeb16f
	.long	0xc59154c5
	.long	0x30605030
	.long	0x01020301
	.long	0x67cea967
	.long	0x2b567d2b
	.long	0xfee719fe
	.long	0xd7b562d7
	.long	0xab4de6ab
	.long	0x76ec9a76
	.long	0xca8f45ca
	.long	0x821f9d82
	.long	0xc98940c9
	.long	0x7dfa877d
	.long	0xfaef15fa
	.long	0x59b2eb59
	.long	0x478ec947
	.long	0xf0fb0bf0
	.long	0xad41ecad
	.long	0xd4b367d4
	.long	0xa25ffda2
	.long	0xaf45eaaf
	.long	0x9c23bf9c
	.long	0xa453f7a4
	.long	0x72e49672
	.long	0xc09b5bc0
	.long	0xb775c2b7
	.long	0xfde11cfd
	.long	0x933dae93
	.long	0x264c6a26
	.long	0x366c5a36
	.long	0x3f7e413f
	.long	0xf7f502f7
	.long	0xcc834fcc
	.long	0x34685c34
	.long	0xa551f4a5
	.long	0xe5d134e5
	.long	0xf1f908f1
	.long	0x71e29371
	.long	0xd8ab73d8
	.long	0x31625331
	.long	0x152a3f15
	.long	0x04080c04
	.long	0xc79552c7
	.long	0x23466523
	.long	0xc39d5ec3
	.long	0x18302818
	.long	0x9637a196
	.long	0x050a0f05
	.long	0x9a2fb59a
	.long	0x070e0907
	.long	0x12243612
	.long	0x801b9b80
	.long	0xe2df3de2
	.long	0xebcd26eb
	.long	0x274e6927
	.long	0xb27fcdb2
	.long	0x75ea9f75
	.long	0x09121b09
	.long	0x831d9e83
	.long	0x2c58742c
	.long	0x1a342e1a
	.long	0x1b362d1b
	.long	0x6edcb26e
	.long	0x5ab4ee5a
	.long	0xa05bfba0
	.long	0x52a4f652
	.long	0x3b764d3b
	.long	0xd6b761d6
	.long	0xb37dceb3
	.long	0x29527b29
	.long	0xe3dd3ee3
	.long	0x2f5e712f
	.long	0x84139784
	.long	0x53a6f553
	.long	0xd1b968d1
	.long	0x00000000
	.long	0xedc12ced
	.long	0x20406020
	.long	0xfce31ffc
	.long	0xb179c8b1
	.long	0x5bb6ed5b
	.long	0x6ad4be6a
	.long	0xcb8d46cb
	.long	0xbe67d9be
	.long	0x39724b39
	.long	0x4a94de4a
	.long	0x4c98d44c
	.long	0x58b0e858
	.long	0xcf854acf
	.long	0xd0bb6bd0
	.long	0xefc52aef
	.long	0xaa4fe5aa
	.long	0xfbed16fb
	.long	0x4386c543
	.long	0x4d9ad74d
	.long	0x33665533
	.long	0x85119485
	.long	0x458acf45
	.long	0xf9e910f9
	.long	0x02040602
	.long	0x7ffe817f
	.long	0x50a0f050
	.long	0x3c78443c
	.long	0x9f25ba9f
	.long	0xa84be3a8
	.long	0x51a2f351
	.long	0xa35dfea3
	.long	0x4080c040
	.long	0x8f058a8f
	.long	0x923fad92
	.long	0x9d21bc9d
	.long	0x38704838
	.long	0xf5f104f5
	.long	0xbc63dfbc
	.long	0xb677c1b6
	.long	0xdaaf75da
	.long	0x21426321
	.long	0x10203010
	.long	0xffe51aff
	.long	0xf3fd0ef3
	.long	0xd2bf6dd2
	.long	0xcd814ccd
	.long	0x0c18140c
	.long	0x13263513
	.long	0xecc32fec
	.long	0x5fbee15f
	.long	0x9735a297
	.long	0x4488cc44
	.long	0x172e3917
	.long	0xc49357c4
	.long	0xa755f2a7
	.long	0x7efc827e
	.long	0x3d7a473d
	.long	0x64c8ac64
	.long	0x5dbae75d
	.long	0x19322b19
	.long	0x73e69573
	.long	0x60c0a060
	.long	0x81199881
	.long	0x4f9ed14f
	.long	0xdca37fdc
	.long	0x22446622
	.long	0x2a547e2a
	.long	0x903bab90
	.long	0x880b8388
	.long	0x468cca46
	.long	0xeec729ee
	.long	0xb86bd3b8
	.long	0x14283c14
	.long	0xdea779de
	.long	0x5ebce25e
	.long	0x0b161d0b
	.long	0xdbad76db
	.long	0xe0db3be0
	.long	0x32645632
	.long	0x3a744e3a
	.long	0x0a141e0a
	.long	0x4992db49
	.long	0x060c0a06
	.long	0x24486c24
	.long	0x5cb8e45c
	.long	0xc29f5dc2
	.long	0xd3bd6ed3
	.long	0xac43efac
	.long	0x62c4a662
	.long	0x9139a891
	.long	0x9531a495
	.long	0xe4d337e4
	.long	0x79f28b79
	.long	0xe7d532e7
	.long	0xc88b43c8
	.long	0x376e5937
	.long	0x6ddab76d
	.long	0x8d018c8d
	.long	0xd5b164d5
	.long	0x4e9cd24e
	.long	0xa949e0a9
	.long	0x6cd8b46c
	.long	0x56acfa56
	.long	0xf4f307f4
	.long	0xeacf25ea
	.long	0x65caaf65
	.long	0x7af48e7a
	.long	0xae47e9ae
	.long	0x08101808
	.long	0xba6fd5ba
	.long	0x78f08878
	.long	0x254a6f25
	.long	0x2e5c722e
	.long	0x1c38241c
	.long	0xa657f1a6
	.long	0xb473c7b4
	.long	0xc69751c6
	.long	0xe8cb23e8
	.long	0xdda17cdd
	.long	0x74e89c74
	.long	0x1f3e211f
	.long	0x4b96dd4b
	.long	0xbd61dcbd
	.long	0x8b0d868b
	.long	0x8a0f858a
	.long	0x70e09070
	.long	0x3e7c423e
	.long	0xb571c4b5
	.long	0x66ccaa66
	.long	0x4890d848
	.long	0x03060503
	.long	0xf6f701f6
	.long	0x0e1c120e
	.long	0x61c2a361
	.long	0x356a5f35
	.long	0x57aef957
	.long	0xb969d0b9
	.long	0x86179186
	.long	0xc19958c1
	.long	0x1d3a271d
	.long	0x9e27b99e
	.long	0xe1d938e1
	.long	0xf8eb13f8
	.long	0x982bb398
	.long	0x11223311
	.long	0x69d2bb69
	.long	0xd9a970d9
	.long	0x8e07898e
	.long	0x9433a794
	.long	0x9b2db69b
	.long	0x1e3c221e
	.long	0x87159287
	.long	0xe9c920e9
	.long	0xce8749ce
	.long	0x55aaff55
	.long	0x28507828
	.long	0xdfa57adf
	.long	0x8c038f8c
	.long	0xa159f8a1
	.long	0x89098089
	.long	0x0d1a170d
	.long	0xbf65dabf
	.long	0xe6d731e6
	.long	0x4284c642
	.long	0x68d0b868
	.long	0x4182c341
	.long	0x9929b099
	.long	0x2d5a772d
	.long	0x0f1e110f
	.long	0xb07bcbb0
	.long	0x54a8fc54
	.long	0xbb6dd6bb
	.long	0x162c3a16
	// Table 3.
	.long	0xc6a56363
	.long	0xf8847c7c
	.long	0xee997777
	.long	0xf68d7b7b
	.long	0xff0df2f2
	.long	0xd6bd6b6b
	.long	0xdeb16f6f
	.long	0x9154c5c5
	.long	0x60503030
	.long	0x02030101
	.long	0xcea96767
	.long	0x567d2b2b
	.long	0xe719fefe
	.long	0xb562d7d7
	.long	0x4de6abab
	.long	0xec9a7676
	.long	0x8f45caca
	.long	0x1f9d8282
	.long	0x8940c9c9
	.long	0xfa877d7d
	.long	0xef15fafa
	.long	0xb2eb5959
	.long	0x8ec94747
	.long	0xfb0bf0f0
	.long	0x41ecadad
	.long	0xb367d4d4
	.long	0x5ffda2a2
	.long	0x45eaafaf
	.long	0x23bf9c9c
	.long	0x53f7a4a4
	.long	0xe4967272
	.long	0x9b5bc0c0
	.long	0x75c2b7b7
	.long	0xe11cfdfd
	.long	0x3dae9393
	.long	0x4c6a2626
	.long	0x6c5a3636
	.long	0x7e413f3f
	.long	0xf502f7f7
	.long	0x834fcccc
	.long	0x685c3434
	.long	0x51f4a5a5
	.long	0xd134e5e5
	.long	0xf908f1f1
	.long	0xe2937171
	.long	0xab73d8d8
	.long	0x62533131
	.long	0x2a3f1515
	.long	0x080c0404
	.long	0x9552c7c7
	.long	0x46652323
	.long	0x9d5ec3c3
	.long	0x30281818
	.long	0x37a19696
	.long	0x0a0f0505
	.long	0x2fb59a9a
	.long	0x0e090707
	.long	0x24361212
	.long	0x1b9b8080
	.long	0xdf3de2e2
	.long	0xcd26ebeb
	.long	0x4e692727
	.long	0x7fcdb2b2
	.long	0xea9f7575
	.long	0x121b0909
	.long	0x1d9e8383
	.long	0x58742c2c
	.long	0x342e1a1a
	.long	0x362d1b1b
	.long	0xdcb26e6e
	.long	0xb4ee5a5a
	.long	0x5bfba0a0
	.long	0xa4f65252
	.long	0x764d3b3b
	.long	0xb761d6d6
	.long	0x7dceb3b3
	.long	0x527b2929
	.long	0xdd3ee3e3
	.long	0x5e712f2f
	.long	0x13978484
	.long	0xa6f55353
	.long	0xb968d1d1
	.long	0x00000000
	.long	0xc12ceded
	.long	0x40602020
	.long	0xe31ffcfc
	.long	0x79c8b1b1
	.long	0xb6ed5b5b
	.long	0xd4be6a6a
	.long	0x8d46cbcb
	.long	0x67d9bebe
	.long	0x724b3939
	.long	0x94de4a4a
	.long	0x98d44c4c
	.long	0xb0e85858
	.long	0x854acfcf
	.long	0xbb6bd0d0
	.long	0xc52aefef
	.long	0x4fe5aaaa
	.long	0xed16fbfb
	.long	0x86c54343
	.long	0x9ad74d4d
	.long	0x66553333
	.long	0x11948585
	.long	0x8acf4545
	.long	0xe910f9f9
	.long	0x04060202
	.long	0xfe817f7f
	.long	0xa0f05050
	.long	0x78443c3c
	.long	0x25ba9f9f
	.long	0x4be3a8a8
	.long	0xa2f35151
	.long	0x5dfea3a3
	.long	0x80c04040
	.long	0x058a8f8f
	.long	0x3fad9292
	.long	0x21bc9d9d
	.long	0x70483838
	.long	0xf104f5f5
	.long	0x63dfbcbc
	.long	0x77c1b6b6
	.long	0xaf75dada
	.long	0x42632121
	.long	0x20301010
	.long	0xe51affff
	.long	0xfd0ef3f3
	.long	0xbf6dd2d2
	.long	0x814ccdcd
	.long	0x18140c0c
	.long	0x26351313
	.long	0xc32fecec
	.long	0xbee15f5f
	.long	0x35a29797
	.long	0x88cc4444
	.long	0x2e391717
	.long	0x9357c4c4
	.long	0x55f2a7a7
	.long	0xfc827e7e
	.long	0x7a473d3d
	.long	0xc8ac6464
	.long	0xbae75d5d
	.long	0x322b1919
	.long	0xe6957373
	.long	0xc0a06060
	.long	0x19988181
	.long	0x9ed14f4f
	.long	0xa37fdcdc
	.long	0x44662222
	.long	0x547e2a2a
	.long	0x3bab9090
	.long	0x0b838888
	.long	0x8cca4646
	.long	0xc729eeee
	.long	0x6bd3b8b8
	.long	0x283c1414
	.long	0xa779dede
	.long	0xbce25e5e
	.long	0x161d0b0b
	.long	0xad76dbdb
	.long	0xdb3be0e0
	.long	0x64563232
	.long	0x744e3a3a
	.long	0x141e0a0a
	.long	0x92db4949
	.long	0x0c0a0606
	.long	0x486c2424
	.long	0xb8e45c5c
	.long	0x9f5dc2c2
	.long	0xbd6ed3d3
	.long	0x43efacac
	.long	0xc4a66262
	.long	0x39a89191
	.long	0x31a49595
	.long	0xd337e4e4
	.long	0xf28b7979
	.long	0xd532e7e7
	.long	0x8b43c8c8
	.long	0x6e593737
	.long	0xdab76d6d
	.long	0x018c8d8d
	.long	0xb164d5d5
	.long	0x9cd24e4e
	.long	0x49e0a9a9
	.long	0xd8b46c6c
	.long	0xacfa5656
	.long	0xf307f4f4
	.long	0xcf25eaea
	.long	0xcaaf6565
	.long	0xf48e7a7a
	.long	0x47e9aeae
	.long	0x10180808
	.long	0x6fd5baba
	.long	0xf0887878
	.long	0x4a6f2525
	.long	0x5c722e2e
	.long	0x38241c1c
	.long	0x57f1a6a6
	.long	0x73c7b4b4
	.long	0x9751c6c6
	.long	0xcb23e8e8
	.long	0xa17cdddd
	.long	0xe89c7474
	.long	0x3e211f1f
	.long	0x96dd4b4b
	.long	0x61dcbdbd
	.long	0x0d868b8b
	.long	0x0f858a8a
	.long	0xe0907070
	.long	0x7c423e3e
	.long	0x71c4b5b5
	.long	0xccaa6666
	.long	0x90d84848
	.long	0x06050303
	.long	0xf701f6f6
	.long	0x1c120e0e
	.long	0xc2a36161
	.long	0x6a5f3535
	.long	0xaef95757
	.long	0x69d0b9b9
	.long	0x17918686
	.long	0x9958c1c1
	.long	0x3a271d1d
	.long	0x27b99e9e
	.long	0xd938e1e1
	.long	0xeb13f8f8
	.long	0x2bb39898
	.long	0x22331111
	.long	0xd2bb6969
	.long	0xa970d9d9
	.long	0x07898e8e
	.long	0x33a79494
	.long	0x2db69b9b
	.long	0x3c221e1e
	.long	0x15928787
	.long	0xc920e9e9
	.long	0x8749cece
	.long	0xaaff5555
	.long	0x50782828
	.long	0xa57adfdf
	.long	0x038f8c8c
	.long	0x59f8a1a1
	.long	0x09808989
	.long	0x1a170d0d
	.long	0x65dabfbf
	.long	0xd731e6e6
	.long	0x84c64242
	.long	0xd0b86868
	.long	0x82c34141
	.long	0x29b09999
	.long	0x5a772d2d
	.long	0x1e110f0f
	.long	0x7bcbb0b0
	.long	0xa8fc5454
	.long	0x6dd6bbbb
	.long	0x2c3a1616


// Tables for main decryption iterations.
	.globl	_OLDAESDecryptTable
	.private_extern	_OLDAESDecryptTable
	.align	2
_OLDAESDecryptTable:
	// Table 0.
	.long	0x50a7f451
	.long	0x5365417e
	.long	0xc3a4171a
	.long	0x965e273a
	.long	0xcb6bab3b
	.long	0xf1459d1f
	.long	0xab58faac
	.long	0x9303e34b
	.long	0x55fa3020
	.long	0xf66d76ad
	.long	0x9176cc88
	.long	0x254c02f5
	.long	0xfcd7e54f
	.long	0xd7cb2ac5
	.long	0x80443526
	.long	0x8fa362b5
	.long	0x495ab1de
	.long	0x671bba25
	.long	0x980eea45
	.long	0xe1c0fe5d
	.long	0x02752fc3
	.long	0x12f04c81
	.long	0xa397468d
	.long	0xc6f9d36b
	.long	0xe75f8f03
	.long	0x959c9215
	.long	0xeb7a6dbf
	.long	0xda595295
	.long	0x2d83bed4
	.long	0xd3217458
	.long	0x2969e049
	.long	0x44c8c98e
	.long	0x6a89c275
	.long	0x78798ef4
	.long	0x6b3e5899
	.long	0xdd71b927
	.long	0xb64fe1be
	.long	0x17ad88f0
	.long	0x66ac20c9
	.long	0xb43ace7d
	.long	0x184adf63
	.long	0x82311ae5
	.long	0x60335197
	.long	0x457f5362
	.long	0xe07764b1
	.long	0x84ae6bbb
	.long	0x1ca081fe
	.long	0x942b08f9
	.long	0x58684870
	.long	0x19fd458f
	.long	0x876cde94
	.long	0xb7f87b52
	.long	0x23d373ab
	.long	0xe2024b72
	.long	0x578f1fe3
	.long	0x2aab5566
	.long	0x0728ebb2
	.long	0x03c2b52f
	.long	0x9a7bc586
	.long	0xa50837d3
	.long	0xf2872830
	.long	0xb2a5bf23
	.long	0xba6a0302
	.long	0x5c8216ed
	.long	0x2b1ccf8a
	.long	0x92b479a7
	.long	0xf0f207f3
	.long	0xa1e2694e
	.long	0xcdf4da65
	.long	0xd5be0506
	.long	0x1f6234d1
	.long	0x8afea6c4
	.long	0x9d532e34
	.long	0xa055f3a2
	.long	0x32e18a05
	.long	0x75ebf6a4
	.long	0x39ec830b
	.long	0xaaef6040
	.long	0x069f715e
	.long	0x51106ebd
	.long	0xf98a213e
	.long	0x3d06dd96
	.long	0xae053edd
	.long	0x46bde64d
	.long	0xb58d5491
	.long	0x055dc471
	.long	0x6fd40604
	.long	0xff155060
	.long	0x24fb9819
	.long	0x97e9bdd6
	.long	0xcc434089
	.long	0x779ed967
	.long	0xbd42e8b0
	.long	0x888b8907
	.long	0x385b19e7
	.long	0xdbeec879
	.long	0x470a7ca1
	.long	0xe90f427c
	.long	0xc91e84f8
	.long	0x00000000
	.long	0x83868009
	.long	0x48ed2b32
	.long	0xac70111e
	.long	0x4e725a6c
	.long	0xfbff0efd
	.long	0x5638850f
	.long	0x1ed5ae3d
	.long	0x27392d36
	.long	0x64d90f0a
	.long	0x21a65c68
	.long	0xd1545b9b
	.long	0x3a2e3624
	.long	0xb1670a0c
	.long	0x0fe75793
	.long	0xd296eeb4
	.long	0x9e919b1b
	.long	0x4fc5c080
	.long	0xa220dc61
	.long	0x694b775a
	.long	0x161a121c
	.long	0x0aba93e2
	.long	0xe52aa0c0
	.long	0x43e0223c
	.long	0x1d171b12
	.long	0x0b0d090e
	.long	0xadc78bf2
	.long	0xb9a8b62d
	.long	0xc8a91e14
	.long	0x8519f157
	.long	0x4c0775af
	.long	0xbbdd99ee
	.long	0xfd607fa3
	.long	0x9f2601f7
	.long	0xbcf5725c
	.long	0xc53b6644
	.long	0x347efb5b
	.long	0x7629438b
	.long	0xdcc623cb
	.long	0x68fcedb6
	.long	0x63f1e4b8
	.long	0xcadc31d7
	.long	0x10856342
	.long	0x40229713
	.long	0x2011c684
	.long	0x7d244a85
	.long	0xf83dbbd2
	.long	0x1132f9ae
	.long	0x6da129c7
	.long	0x4b2f9e1d
	.long	0xf330b2dc
	.long	0xec52860d
	.long	0xd0e3c177
	.long	0x6c16b32b
	.long	0x99b970a9
	.long	0xfa489411
	.long	0x2264e947
	.long	0xc48cfca8
	.long	0x1a3ff0a0
	.long	0xd82c7d56
	.long	0xef903322
	.long	0xc74e4987
	.long	0xc1d138d9
	.long	0xfea2ca8c
	.long	0x360bd498
	.long	0xcf81f5a6
	.long	0x28de7aa5
	.long	0x268eb7da
	.long	0xa4bfad3f
	.long	0xe49d3a2c
	.long	0x0d927850
	.long	0x9bcc5f6a
	.long	0x62467e54
	.long	0xc2138df6
	.long	0xe8b8d890
	.long	0x5ef7392e
	.long	0xf5afc382
	.long	0xbe805d9f
	.long	0x7c93d069
	.long	0xa92dd56f
	.long	0xb31225cf
	.long	0x3b99acc8
	.long	0xa77d1810
	.long	0x6e639ce8
	.long	0x7bbb3bdb
	.long	0x097826cd
	.long	0xf418596e
	.long	0x01b79aec
	.long	0xa89a4f83
	.long	0x656e95e6
	.long	0x7ee6ffaa
	.long	0x08cfbc21
	.long	0xe6e815ef
	.long	0xd99be7ba
	.long	0xce366f4a
	.long	0xd4099fea
	.long	0xd67cb029
	.long	0xafb2a431
	.long	0x31233f2a
	.long	0x3094a5c6
	.long	0xc066a235
	.long	0x37bc4e74
	.long	0xa6ca82fc
	.long	0xb0d090e0
	.long	0x15d8a733
	.long	0x4a9804f1
	.long	0xf7daec41
	.long	0x0e50cd7f
	.long	0x2ff69117
	.long	0x8dd64d76
	.long	0x4db0ef43
	.long	0x544daacc
	.long	0xdf0496e4
	.long	0xe3b5d19e
	.long	0x1b886a4c
	.long	0xb81f2cc1
	.long	0x7f516546
	.long	0x04ea5e9d
	.long	0x5d358c01
	.long	0x737487fa
	.long	0x2e410bfb
	.long	0x5a1d67b3
	.long	0x52d2db92
	.long	0x335610e9
	.long	0x1347d66d
	.long	0x8c61d79a
	.long	0x7a0ca137
	.long	0x8e14f859
	.long	0x893c13eb
	.long	0xee27a9ce
	.long	0x35c961b7
	.long	0xede51ce1
	.long	0x3cb1477a
	.long	0x59dfd29c
	.long	0x3f73f255
	.long	0x79ce1418
	.long	0xbf37c773
	.long	0xeacdf753
	.long	0x5baafd5f
	.long	0x146f3ddf
	.long	0x86db4478
	.long	0x81f3afca
	.long	0x3ec468b9
	.long	0x2c342438
	.long	0x5f40a3c2
	.long	0x72c31d16
	.long	0x0c25e2bc
	.long	0x8b493c28
	.long	0x41950dff
	.long	0x7101a839
	.long	0xdeb30c08
	.long	0x9ce4b4d8
	.long	0x90c15664
	.long	0x6184cb7b
	.long	0x70b632d5
	.long	0x745c6c48
	.long	0x4257b8d0
	// Table 1.
	.long	0xa7f45150
	.long	0x65417e53
	.long	0xa4171ac3
	.long	0x5e273a96
	.long	0x6bab3bcb
	.long	0x459d1ff1
	.long	0x58faacab
	.long	0x03e34b93
	.long	0xfa302055
	.long	0x6d76adf6
	.long	0x76cc8891
	.long	0x4c02f525
	.long	0xd7e54ffc
	.long	0xcb2ac5d7
	.long	0x44352680
	.long	0xa362b58f
	.long	0x5ab1de49
	.long	0x1bba2567
	.long	0x0eea4598
	.long	0xc0fe5de1
	.long	0x752fc302
	.long	0xf04c8112
	.long	0x97468da3
	.long	0xf9d36bc6
	.long	0x5f8f03e7
	.long	0x9c921595
	.long	0x7a6dbfeb
	.long	0x595295da
	.long	0x83bed42d
	.long	0x217458d3
	.long	0x69e04929
	.long	0xc8c98e44
	.long	0x89c2756a
	.long	0x798ef478
	.long	0x3e58996b
	.long	0x71b927dd
	.long	0x4fe1beb6
	.long	0xad88f017
	.long	0xac20c966
	.long	0x3ace7db4
	.long	0x4adf6318
	.long	0x311ae582
	.long	0x33519760
	.long	0x7f536245
	.long	0x7764b1e0
	.long	0xae6bbb84
	.long	0xa081fe1c
	.long	0x2b08f994
	.long	0x68487058
	.long	0xfd458f19
	.long	0x6cde9487
	.long	0xf87b52b7
	.long	0xd373ab23
	.long	0x024b72e2
	.long	0x8f1fe357
	.long	0xab55662a
	.long	0x28ebb207
	.long	0xc2b52f03
	.long	0x7bc5869a
	.long	0x0837d3a5
	.long	0x872830f2
	.long	0xa5bf23b2
	.long	0x6a0302ba
	.long	0x8216ed5c
	.long	0x1ccf8a2b
	.long	0xb479a792
	.long	0xf207f3f0
	.long	0xe2694ea1
	.long	0xf4da65cd
	.long	0xbe0506d5
	.long	0x6234d11f
	.long	0xfea6c48a
	.long	0x532e349d
	.long	0x55f3a2a0
	.long	0xe18a0532
	.long	0xebf6a475
	.long	0xec830b39
	.long	0xef6040aa
	.long	0x9f715e06
	.long	0x106ebd51
	.long	0x8a213ef9
	.long	0x06dd963d
	.long	0x053eddae
	.long	0xbde64d46
	.long	0x8d5491b5
	.long	0x5dc47105
	.long	0xd406046f
	.long	0x155060ff
	.long	0xfb981924
	.long	0xe9bdd697
	.long	0x434089cc
	.long	0x9ed96777
	.long	0x42e8b0bd
	.long	0x8b890788
	.long	0x5b19e738
	.long	0xeec879db
	.long	0x0a7ca147
	.long	0x0f427ce9
	.long	0x1e84f8c9
	.long	0x00000000
	.long	0x86800983
	.long	0xed2b3248
	.long	0x70111eac
	.long	0x725a6c4e
	.long	0xff0efdfb
	.long	0x38850f56
	.long	0xd5ae3d1e
	.long	0x392d3627
	.long	0xd90f0a64
	.long	0xa65c6821
	.long	0x545b9bd1
	.long	0x2e36243a
	.long	0x670a0cb1
	.long	0xe757930f
	.long	0x96eeb4d2
	.long	0x919b1b9e
	.long	0xc5c0804f
	.long	0x20dc61a2
	.long	0x4b775a69
	.long	0x1a121c16
	.long	0xba93e20a
	.long	0x2aa0c0e5
	.long	0xe0223c43
	.long	0x171b121d
	.long	0x0d090e0b
	.long	0xc78bf2ad
	.long	0xa8b62db9
	.long	0xa91e14c8
	.long	0x19f15785
	.long	0x0775af4c
	.long	0xdd99eebb
	.long	0x607fa3fd
	.long	0x2601f79f
	.long	0xf5725cbc
	.long	0x3b6644c5
	.long	0x7efb5b34
	.long	0x29438b76
	.long	0xc623cbdc
	.long	0xfcedb668
	.long	0xf1e4b863
	.long	0xdc31d7ca
	.long	0x85634210
	.long	0x22971340
	.long	0x11c68420
	.long	0x244a857d
	.long	0x3dbbd2f8
	.long	0x32f9ae11
	.long	0xa129c76d
	.long	0x2f9e1d4b
	.long	0x30b2dcf3
	.long	0x52860dec
	.long	0xe3c177d0
	.long	0x16b32b6c
	.long	0xb970a999
	.long	0x489411fa
	.long	0x64e94722
	.long	0x8cfca8c4
	.long	0x3ff0a01a
	.long	0x2c7d56d8
	.long	0x903322ef
	.long	0x4e4987c7
	.long	0xd138d9c1
	.long	0xa2ca8cfe
	.long	0x0bd49836
	.long	0x81f5a6cf
	.long	0xde7aa528
	.long	0x8eb7da26
	.long	0xbfad3fa4
	.long	0x9d3a2ce4
	.long	0x9278500d
	.long	0xcc5f6a9b
	.long	0x467e5462
	.long	0x138df6c2
	.long	0xb8d890e8
	.long	0xf7392e5e
	.long	0xafc382f5
	.long	0x805d9fbe
	.long	0x93d0697c
	.long	0x2dd56fa9
	.long	0x1225cfb3
	.long	0x99acc83b
	.long	0x7d1810a7
	.long	0x639ce86e
	.long	0xbb3bdb7b
	.long	0x7826cd09
	.long	0x18596ef4
	.long	0xb79aec01
	.long	0x9a4f83a8
	.long	0x6e95e665
	.long	0xe6ffaa7e
	.long	0xcfbc2108
	.long	0xe815efe6
	.long	0x9be7bad9
	.long	0x366f4ace
	.long	0x099fead4
	.long	0x7cb029d6
	.long	0xb2a431af
	.long	0x233f2a31
	.long	0x94a5c630
	.long	0x66a235c0
	.long	0xbc4e7437
	.long	0xca82fca6
	.long	0xd090e0b0
	.long	0xd8a73315
	.long	0x9804f14a
	.long	0xdaec41f7
	.long	0x50cd7f0e
	.long	0xf691172f
	.long	0xd64d768d
	.long	0xb0ef434d
	.long	0x4daacc54
	.long	0x0496e4df
	.long	0xb5d19ee3
	.long	0x886a4c1b
	.long	0x1f2cc1b8
	.long	0x5165467f
	.long	0xea5e9d04
	.long	0x358c015d
	.long	0x7487fa73
	.long	0x410bfb2e
	.long	0x1d67b35a
	.long	0xd2db9252
	.long	0x5610e933
	.long	0x47d66d13
	.long	0x61d79a8c
	.long	0x0ca1377a
	.long	0x14f8598e
	.long	0x3c13eb89
	.long	0x27a9ceee
	.long	0xc961b735
	.long	0xe51ce1ed
	.long	0xb1477a3c
	.long	0xdfd29c59
	.long	0x73f2553f
	.long	0xce141879
	.long	0x37c773bf
	.long	0xcdf753ea
	.long	0xaafd5f5b
	.long	0x6f3ddf14
	.long	0xdb447886
	.long	0xf3afca81
	.long	0xc468b93e
	.long	0x3424382c
	.long	0x40a3c25f
	.long	0xc31d1672
	.long	0x25e2bc0c
	.long	0x493c288b
	.long	0x950dff41
	.long	0x01a83971
	.long	0xb30c08de
	.long	0xe4b4d89c
	.long	0xc1566490
	.long	0x84cb7b61
	.long	0xb632d570
	.long	0x5c6c4874
	.long	0x57b8d042
	// Table 2.
	.long	0xf45150a7
	.long	0x417e5365
	.long	0x171ac3a4
	.long	0x273a965e
	.long	0xab3bcb6b
	.long	0x9d1ff145
	.long	0xfaacab58
	.long	0xe34b9303
	.long	0x302055fa
	.long	0x76adf66d
	.long	0xcc889176
	.long	0x02f5254c
	.long	0xe54ffcd7
	.long	0x2ac5d7cb
	.long	0x35268044
	.long	0x62b58fa3
	.long	0xb1de495a
	.long	0xba25671b
	.long	0xea45980e
	.long	0xfe5de1c0
	.long	0x2fc30275
	.long	0x4c8112f0
	.long	0x468da397
	.long	0xd36bc6f9
	.long	0x8f03e75f
	.long	0x9215959c
	.long	0x6dbfeb7a
	.long	0x5295da59
	.long	0xbed42d83
	.long	0x7458d321
	.long	0xe0492969
	.long	0xc98e44c8
	.long	0xc2756a89
	.long	0x8ef47879
	.long	0x58996b3e
	.long	0xb927dd71
	.long	0xe1beb64f
	.long	0x88f017ad
	.long	0x20c966ac
	.long	0xce7db43a
	.long	0xdf63184a
	.long	0x1ae58231
	.long	0x51976033
	.long	0x5362457f
	.long	0x64b1e077
	.long	0x6bbb84ae
	.long	0x81fe1ca0
	.long	0x08f9942b
	.long	0x48705868
	.long	0x458f19fd
	.long	0xde94876c
	.long	0x7b52b7f8
	.long	0x73ab23d3
	.long	0x4b72e202
	.long	0x1fe3578f
	.long	0x55662aab
	.long	0xebb20728
	.long	0xb52f03c2
	.long	0xc5869a7b
	.long	0x37d3a508
	.long	0x2830f287
	.long	0xbf23b2a5
	.long	0x0302ba6a
	.long	0x16ed5c82
	.long	0xcf8a2b1c
	.long	0x79a792b4
	.long	0x07f3f0f2
	.long	0x694ea1e2
	.long	0xda65cdf4
	.long	0x0506d5be
	.long	0x34d11f62
	.long	0xa6c48afe
	.long	0x2e349d53
	.long	0xf3a2a055
	.long	0x8a0532e1
	.long	0xf6a475eb
	.long	0x830b39ec
	.long	0x6040aaef
	.long	0x715e069f
	.long	0x6ebd5110
	.long	0x213ef98a
	.long	0xdd963d06
	.long	0x3eddae05
	.long	0xe64d46bd
	.long	0x5491b58d
	.long	0xc471055d
	.long	0x06046fd4
	.long	0x5060ff15
	.long	0x981924fb
	.long	0xbdd697e9
	.long	0x4089cc43
	.long	0xd967779e
	.long	0xe8b0bd42
	.long	0x8907888b
	.long	0x19e7385b
	.long	0xc879dbee
	.long	0x7ca1470a
	.long	0x427ce90f
	.long	0x84f8c91e
	.long	0x00000000
	.long	0x80098386
	.long	0x2b3248ed
	.long	0x111eac70
	.long	0x5a6c4e72
	.long	0x0efdfbff
	.long	0x850f5638
	.long	0xae3d1ed5
	.long	0x2d362739
	.long	0x0f0a64d9
	.long	0x5c6821a6
	.long	0x5b9bd154
	.long	0x36243a2e
	.long	0x0a0cb167
	.long	0x57930fe7
	.long	0xeeb4d296
	.long	0x9b1b9e91
	.long	0xc0804fc5
	.long	0xdc61a220
	.long	0x775a694b
	.long	0x121c161a
	.long	0x93e20aba
	.long	0xa0c0e52a
	.long	0x223c43e0
	.long	0x1b121d17
	.long	0x090e0b0d
	.long	0x8bf2adc7
	.long	0xb62db9a8
	.long	0x1e14c8a9
	.long	0xf1578519
	.long	0x75af4c07
	.long	0x99eebbdd
	.long	0x7fa3fd60
	.long	0x01f79f26
	.long	0x725cbcf5
	.long	0x6644c53b
	.long	0xfb5b347e
	.long	0x438b7629
	.long	0x23cbdcc6
	.long	0xedb668fc
	.long	0xe4b863f1
	.long	0x31d7cadc
	.long	0x63421085
	.long	0x97134022
	.long	0xc6842011
	.long	0x4a857d24
	.long	0xbbd2f83d
	.long	0xf9ae1132
	.long	0x29c76da1
	.long	0x9e1d4b2f
	.long	0xb2dcf330
	.long	0x860dec52
	.long	0xc177d0e3
	.long	0xb32b6c16
	.long	0x70a999b9
	.long	0x9411fa48
	.long	0xe9472264
	.long	0xfca8c48c
	.long	0xf0a01a3f
	.long	0x7d56d82c
	.long	0x3322ef90
	.long	0x4987c74e
	.long	0x38d9c1d1
	.long	0xca8cfea2
	.long	0xd498360b
	.long	0xf5a6cf81
	.long	0x7aa528de
	.long	0xb7da268e
	.long	0xad3fa4bf
	.long	0x3a2ce49d
	.long	0x78500d92
	.long	0x5f6a9bcc
	.long	0x7e546246
	.long	0x8df6c213
	.long	0xd890e8b8
	.long	0x392e5ef7
	.long	0xc382f5af
	.long	0x5d9fbe80
	.long	0xd0697c93
	.long	0xd56fa92d
	.long	0x25cfb312
	.long	0xacc83b99
	.long	0x1810a77d
	.long	0x9ce86e63
	.long	0x3bdb7bbb
	.long	0x26cd0978
	.long	0x596ef418
	.long	0x9aec01b7
	.long	0x4f83a89a
	.long	0x95e6656e
	.long	0xffaa7ee6
	.long	0xbc2108cf
	.long	0x15efe6e8
	.long	0xe7bad99b
	.long	0x6f4ace36
	.long	0x9fead409
	.long	0xb029d67c
	.long	0xa431afb2
	.long	0x3f2a3123
	.long	0xa5c63094
	.long	0xa235c066
	.long	0x4e7437bc
	.long	0x82fca6ca
	.long	0x90e0b0d0
	.long	0xa73315d8
	.long	0x04f14a98
	.long	0xec41f7da
	.long	0xcd7f0e50
	.long	0x91172ff6
	.long	0x4d768dd6
	.long	0xef434db0
	.long	0xaacc544d
	.long	0x96e4df04
	.long	0xd19ee3b5
	.long	0x6a4c1b88
	.long	0x2cc1b81f
	.long	0x65467f51
	.long	0x5e9d04ea
	.long	0x8c015d35
	.long	0x87fa7374
	.long	0x0bfb2e41
	.long	0x67b35a1d
	.long	0xdb9252d2
	.long	0x10e93356
	.long	0xd66d1347
	.long	0xd79a8c61
	.long	0xa1377a0c
	.long	0xf8598e14
	.long	0x13eb893c
	.long	0xa9ceee27
	.long	0x61b735c9
	.long	0x1ce1ede5
	.long	0x477a3cb1
	.long	0xd29c59df
	.long	0xf2553f73
	.long	0x141879ce
	.long	0xc773bf37
	.long	0xf753eacd
	.long	0xfd5f5baa
	.long	0x3ddf146f
	.long	0x447886db
	.long	0xafca81f3
	.long	0x68b93ec4
	.long	0x24382c34
	.long	0xa3c25f40
	.long	0x1d1672c3
	.long	0xe2bc0c25
	.long	0x3c288b49
	.long	0x0dff4195
	.long	0xa8397101
	.long	0x0c08deb3
	.long	0xb4d89ce4
	.long	0x566490c1
	.long	0xcb7b6184
	.long	0x32d570b6
	.long	0x6c48745c
	.long	0xb8d04257
	// Table 3.
	.long	0x5150a7f4
	.long	0x7e536541
	.long	0x1ac3a417
	.long	0x3a965e27
	.long	0x3bcb6bab
	.long	0x1ff1459d
	.long	0xacab58fa
	.long	0x4b9303e3
	.long	0x2055fa30
	.long	0xadf66d76
	.long	0x889176cc
	.long	0xf5254c02
	.long	0x4ffcd7e5
	.long	0xc5d7cb2a
	.long	0x26804435
	.long	0xb58fa362
	.long	0xde495ab1
	.long	0x25671bba
	.long	0x45980eea
	.long	0x5de1c0fe
	.long	0xc302752f
	.long	0x8112f04c
	.long	0x8da39746
	.long	0x6bc6f9d3
	.long	0x03e75f8f
	.long	0x15959c92
	.long	0xbfeb7a6d
	.long	0x95da5952
	.long	0xd42d83be
	.long	0x58d32174
	.long	0x492969e0
	.long	0x8e44c8c9
	.long	0x756a89c2
	.long	0xf478798e
	.long	0x996b3e58
	.long	0x27dd71b9
	.long	0xbeb64fe1
	.long	0xf017ad88
	.long	0xc966ac20
	.long	0x7db43ace
	.long	0x63184adf
	.long	0xe582311a
	.long	0x97603351
	.long	0x62457f53
	.long	0xb1e07764
	.long	0xbb84ae6b
	.long	0xfe1ca081
	.long	0xf9942b08
	.long	0x70586848
	.long	0x8f19fd45
	.long	0x94876cde
	.long	0x52b7f87b
	.long	0xab23d373
	.long	0x72e2024b
	.long	0xe3578f1f
	.long	0x662aab55
	.long	0xb20728eb
	.long	0x2f03c2b5
	.long	0x869a7bc5
	.long	0xd3a50837
	.long	0x30f28728
	.long	0x23b2a5bf
	.long	0x02ba6a03
	.long	0xed5c8216
	.long	0x8a2b1ccf
	.long	0xa792b479
	.long	0xf3f0f207
	.long	0x4ea1e269
	.long	0x65cdf4da
	.long	0x06d5be05
	.long	0xd11f6234
	.long	0xc48afea6
	.long	0x349d532e
	.long	0xa2a055f3
	.long	0x0532e18a
	.long	0xa475ebf6
	.long	0x0b39ec83
	.long	0x40aaef60
	.long	0x5e069f71
	.long	0xbd51106e
	.long	0x3ef98a21
	.long	0x963d06dd
	.long	0xddae053e
	.long	0x4d46bde6
	.long	0x91b58d54
	.long	0x71055dc4
	.long	0x046fd406
	.long	0x60ff1550
	.long	0x1924fb98
	.long	0xd697e9bd
	.long	0x89cc4340
	.long	0x67779ed9
	.long	0xb0bd42e8
	.long	0x07888b89
	.long	0xe7385b19
	.long	0x79dbeec8
	.long	0xa1470a7c
	.long	0x7ce90f42
	.long	0xf8c91e84
	.long	0x00000000
	.long	0x09838680
	.long	0x3248ed2b
	.long	0x1eac7011
	.long	0x6c4e725a
	.long	0xfdfbff0e
	.long	0x0f563885
	.long	0x3d1ed5ae
	.long	0x3627392d
	.long	0x0a64d90f
	.long	0x6821a65c
	.long	0x9bd1545b
	.long	0x243a2e36
	.long	0x0cb1670a
	.long	0x930fe757
	.long	0xb4d296ee
	.long	0x1b9e919b
	.long	0x804fc5c0
	.long	0x61a220dc
	.long	0x5a694b77
	.long	0x1c161a12
	.long	0xe20aba93
	.long	0xc0e52aa0
	.long	0x3c43e022
	.long	0x121d171b
	.long	0x0e0b0d09
	.long	0xf2adc78b
	.long	0x2db9a8b6
	.long	0x14c8a91e
	.long	0x578519f1
	.long	0xaf4c0775
	.long	0xeebbdd99
	.long	0xa3fd607f
	.long	0xf79f2601
	.long	0x5cbcf572
	.long	0x44c53b66
	.long	0x5b347efb
	.long	0x8b762943
	.long	0xcbdcc623
	.long	0xb668fced
	.long	0xb863f1e4
	.long	0xd7cadc31
	.long	0x42108563
	.long	0x13402297
	.long	0x842011c6
	.long	0x857d244a
	.long	0xd2f83dbb
	.long	0xae1132f9
	.long	0xc76da129
	.long	0x1d4b2f9e
	.long	0xdcf330b2
	.long	0x0dec5286
	.long	0x77d0e3c1
	.long	0x2b6c16b3
	.long	0xa999b970
	.long	0x11fa4894
	.long	0x472264e9
	.long	0xa8c48cfc
	.long	0xa01a3ff0
	.long	0x56d82c7d
	.long	0x22ef9033
	.long	0x87c74e49
	.long	0xd9c1d138
	.long	0x8cfea2ca
	.long	0x98360bd4
	.long	0xa6cf81f5
	.long	0xa528de7a
	.long	0xda268eb7
	.long	0x3fa4bfad
	.long	0x2ce49d3a
	.long	0x500d9278
	.long	0x6a9bcc5f
	.long	0x5462467e
	.long	0xf6c2138d
	.long	0x90e8b8d8
	.long	0x2e5ef739
	.long	0x82f5afc3
	.long	0x9fbe805d
	.long	0x697c93d0
	.long	0x6fa92dd5
	.long	0xcfb31225
	.long	0xc83b99ac
	.long	0x10a77d18
	.long	0xe86e639c
	.long	0xdb7bbb3b
	.long	0xcd097826
	.long	0x6ef41859
	.long	0xec01b79a
	.long	0x83a89a4f
	.long	0xe6656e95
	.long	0xaa7ee6ff
	.long	0x2108cfbc
	.long	0xefe6e815
	.long	0xbad99be7
	.long	0x4ace366f
	.long	0xead4099f
	.long	0x29d67cb0
	.long	0x31afb2a4
	.long	0x2a31233f
	.long	0xc63094a5
	.long	0x35c066a2
	.long	0x7437bc4e
	.long	0xfca6ca82
	.long	0xe0b0d090
	.long	0x3315d8a7
	.long	0xf14a9804
	.long	0x41f7daec
	.long	0x7f0e50cd
	.long	0x172ff691
	.long	0x768dd64d
	.long	0x434db0ef
	.long	0xcc544daa
	.long	0xe4df0496
	.long	0x9ee3b5d1
	.long	0x4c1b886a
	.long	0xc1b81f2c
	.long	0x467f5165
	.long	0x9d04ea5e
	.long	0x015d358c
	.long	0xfa737487
	.long	0xfb2e410b
	.long	0xb35a1d67
	.long	0x9252d2db
	.long	0xe9335610
	.long	0x6d1347d6
	.long	0x9a8c61d7
	.long	0x377a0ca1
	.long	0x598e14f8
	.long	0xeb893c13
	.long	0xceee27a9
	.long	0xb735c961
	.long	0xe1ede51c
	.long	0x7a3cb147
	.long	0x9c59dfd2
	.long	0x553f73f2
	.long	0x1879ce14
	.long	0x73bf37c7
	.long	0x53eacdf7
	.long	0x5f5baafd
	.long	0xdf146f3d
	.long	0x7886db44
	.long	0xca81f3af
	.long	0xb93ec468
	.long	0x382c3424
	.long	0xc25f40a3
	.long	0x1672c31d
	.long	0xbc0c25e2
	.long	0x288b493c
	.long	0xff41950d
	.long	0x397101a8
	.long	0x08deb30c
	.long	0xd89ce4b4
	.long	0x6490c156
	.long	0x7b6184cb
	.long	0xd570b632
	.long	0x48745c6c
	.long	0xd04257b8


// SubBytes embedded in words tables.
	.globl	_OLDAESSubBytesWordTable
	.private_extern	_OLDAESSubBytesWordTable
	.align	2
_OLDAESSubBytesWordTable:
	// Table 0.
	.long	0x00000063
	.long	0x0000007c
	.long	0x00000077
	.long	0x0000007b
	.long	0x000000f2
	.long	0x0000006b
	.long	0x0000006f
	.long	0x000000c5
	.long	0x00000030
	.long	0x00000001
	.long	0x00000067
	.long	0x0000002b
	.long	0x000000fe
	.long	0x000000d7
	.long	0x000000ab
	.long	0x00000076
	.long	0x000000ca
	.long	0x00000082
	.long	0x000000c9
	.long	0x0000007d
	.long	0x000000fa
	.long	0x00000059
	.long	0x00000047
	.long	0x000000f0
	.long	0x000000ad
	.long	0x000000d4
	.long	0x000000a2
	.long	0x000000af
	.long	0x0000009c
	.long	0x000000a4
	.long	0x00000072
	.long	0x000000c0
	.long	0x000000b7
	.long	0x000000fd
	.long	0x00000093
	.long	0x00000026
	.long	0x00000036
	.long	0x0000003f
	.long	0x000000f7
	.long	0x000000cc
	.long	0x00000034
	.long	0x000000a5
	.long	0x000000e5
	.long	0x000000f1
	.long	0x00000071
	.long	0x000000d8
	.long	0x00000031
	.long	0x00000015
	.long	0x00000004
	.long	0x000000c7
	.long	0x00000023
	.long	0x000000c3
	.long	0x00000018
	.long	0x00000096
	.long	0x00000005
	.long	0x0000009a
	.long	0x00000007
	.long	0x00000012
	.long	0x00000080
	.long	0x000000e2
	.long	0x000000eb
	.long	0x00000027
	.long	0x000000b2
	.long	0x00000075
	.long	0x00000009
	.long	0x00000083
	.long	0x0000002c
	.long	0x0000001a
	.long	0x0000001b
	.long	0x0000006e
	.long	0x0000005a
	.long	0x000000a0
	.long	0x00000052
	.long	0x0000003b
	.long	0x000000d6
	.long	0x000000b3
	.long	0x00000029
	.long	0x000000e3
	.long	0x0000002f
	.long	0x00000084
	.long	0x00000053
	.long	0x000000d1
	.long	0x00000000
	.long	0x000000ed
	.long	0x00000020
	.long	0x000000fc
	.long	0x000000b1
	.long	0x0000005b
	.long	0x0000006a
	.long	0x000000cb
	.long	0x000000be
	.long	0x00000039
	.long	0x0000004a
	.long	0x0000004c
	.long	0x00000058
	.long	0x000000cf
	.long	0x000000d0
	.long	0x000000ef
	.long	0x000000aa
	.long	0x000000fb
	.long	0x00000043
	.long	0x0000004d
	.long	0x00000033
	.long	0x00000085
	.long	0x00000045
	.long	0x000000f9
	.long	0x00000002
	.long	0x0000007f
	.long	0x00000050
	.long	0x0000003c
	.long	0x0000009f
	.long	0x000000a8
	.long	0x00000051
	.long	0x000000a3
	.long	0x00000040
	.long	0x0000008f
	.long	0x00000092
	.long	0x0000009d
	.long	0x00000038
	.long	0x000000f5
	.long	0x000000bc
	.long	0x000000b6
	.long	0x000000da
	.long	0x00000021
	.long	0x00000010
	.long	0x000000ff
	.long	0x000000f3
	.long	0x000000d2
	.long	0x000000cd
	.long	0x0000000c
	.long	0x00000013
	.long	0x000000ec
	.long	0x0000005f
	.long	0x00000097
	.long	0x00000044
	.long	0x00000017
	.long	0x000000c4
	.long	0x000000a7
	.long	0x0000007e
	.long	0x0000003d
	.long	0x00000064
	.long	0x0000005d
	.long	0x00000019
	.long	0x00000073
	.long	0x00000060
	.long	0x00000081
	.long	0x0000004f
	.long	0x000000dc
	.long	0x00000022
	.long	0x0000002a
	.long	0x00000090
	.long	0x00000088
	.long	0x00000046
	.long	0x000000ee
	.long	0x000000b8
	.long	0x00000014
	.long	0x000000de
	.long	0x0000005e
	.long	0x0000000b
	.long	0x000000db
	.long	0x000000e0
	.long	0x00000032
	.long	0x0000003a
	.long	0x0000000a
	.long	0x00000049
	.long	0x00000006
	.long	0x00000024
	.long	0x0000005c
	.long	0x000000c2
	.long	0x000000d3
	.long	0x000000ac
	.long	0x00000062
	.long	0x00000091
	.long	0x00000095
	.long	0x000000e4
	.long	0x00000079
	.long	0x000000e7
	.long	0x000000c8
	.long	0x00000037
	.long	0x0000006d
	.long	0x0000008d
	.long	0x000000d5
	.long	0x0000004e
	.long	0x000000a9
	.long	0x0000006c
	.long	0x00000056
	.long	0x000000f4
	.long	0x000000ea
	.long	0x00000065
	.long	0x0000007a
	.long	0x000000ae
	.long	0x00000008
	.long	0x000000ba
	.long	0x00000078
	.long	0x00000025
	.long	0x0000002e
	.long	0x0000001c
	.long	0x000000a6
	.long	0x000000b4
	.long	0x000000c6
	.long	0x000000e8
	.long	0x000000dd
	.long	0x00000074
	.long	0x0000001f
	.long	0x0000004b
	.long	0x000000bd
	.long	0x0000008b
	.long	0x0000008a
	.long	0x00000070
	.long	0x0000003e
	.long	0x000000b5
	.long	0x00000066
	.long	0x00000048
	.long	0x00000003
	.long	0x000000f6
	.long	0x0000000e
	.long	0x00000061
	.long	0x00000035
	.long	0x00000057
	.long	0x000000b9
	.long	0x00000086
	.long	0x000000c1
	.long	0x0000001d
	.long	0x0000009e
	.long	0x000000e1
	.long	0x000000f8
	.long	0x00000098
	.long	0x00000011
	.long	0x00000069
	.long	0x000000d9
	.long	0x0000008e
	.long	0x00000094
	.long	0x0000009b
	.long	0x0000001e
	.long	0x00000087
	.long	0x000000e9
	.long	0x000000ce
	.long	0x00000055
	.long	0x00000028
	.long	0x000000df
	.long	0x0000008c
	.long	0x000000a1
	.long	0x00000089
	.long	0x0000000d
	.long	0x000000bf
	.long	0x000000e6
	.long	0x00000042
	.long	0x00000068
	.long	0x00000041
	.long	0x00000099
	.long	0x0000002d
	.long	0x0000000f
	.long	0x000000b0
	.long	0x00000054
	.long	0x000000bb
	.long	0x00000016
	// Table 1.
	.long	0x00006300
	.long	0x00007c00
	.long	0x00007700
	.long	0x00007b00
	.long	0x0000f200
	.long	0x00006b00
	.long	0x00006f00
	.long	0x0000c500
	.long	0x00003000
	.long	0x00000100
	.long	0x00006700
	.long	0x00002b00
	.long	0x0000fe00
	.long	0x0000d700
	.long	0x0000ab00
	.long	0x00007600
	.long	0x0000ca00
	.long	0x00008200
	.long	0x0000c900
	.long	0x00007d00
	.long	0x0000fa00
	.long	0x00005900
	.long	0x00004700
	.long	0x0000f000
	.long	0x0000ad00
	.long	0x0000d400
	.long	0x0000a200
	.long	0x0000af00
	.long	0x00009c00
	.long	0x0000a400
	.long	0x00007200
	.long	0x0000c000
	.long	0x0000b700
	.long	0x0000fd00
	.long	0x00009300
	.long	0x00002600
	.long	0x00003600
	.long	0x00003f00
	.long	0x0000f700
	.long	0x0000cc00
	.long	0x00003400
	.long	0x0000a500
	.long	0x0000e500
	.long	0x0000f100
	.long	0x00007100
	.long	0x0000d800
	.long	0x00003100
	.long	0x00001500
	.long	0x00000400
	.long	0x0000c700
	.long	0x00002300
	.long	0x0000c300
	.long	0x00001800
	.long	0x00009600
	.long	0x00000500
	.long	0x00009a00
	.long	0x00000700
	.long	0x00001200
	.long	0x00008000
	.long	0x0000e200
	.long	0x0000eb00
	.long	0x00002700
	.long	0x0000b200
	.long	0x00007500
	.long	0x00000900
	.long	0x00008300
	.long	0x00002c00
	.long	0x00001a00
	.long	0x00001b00
	.long	0x00006e00
	.long	0x00005a00
	.long	0x0000a000
	.long	0x00005200
	.long	0x00003b00
	.long	0x0000d600
	.long	0x0000b300
	.long	0x00002900
	.long	0x0000e300
	.long	0x00002f00
	.long	0x00008400
	.long	0x00005300
	.long	0x0000d100
	.long	0x00000000
	.long	0x0000ed00
	.long	0x00002000
	.long	0x0000fc00
	.long	0x0000b100
	.long	0x00005b00
	.long	0x00006a00
	.long	0x0000cb00
	.long	0x0000be00
	.long	0x00003900
	.long	0x00004a00
	.long	0x00004c00
	.long	0x00005800
	.long	0x0000cf00
	.long	0x0000d000
	.long	0x0000ef00
	.long	0x0000aa00
	.long	0x0000fb00
	.long	0x00004300
	.long	0x00004d00
	.long	0x00003300
	.long	0x00008500
	.long	0x00004500
	.long	0x0000f900
	.long	0x00000200
	.long	0x00007f00
	.long	0x00005000
	.long	0x00003c00
	.long	0x00009f00
	.long	0x0000a800
	.long	0x00005100
	.long	0x0000a300
	.long	0x00004000
	.long	0x00008f00
	.long	0x00009200
	.long	0x00009d00
	.long	0x00003800
	.long	0x0000f500
	.long	0x0000bc00
	.long	0x0000b600
	.long	0x0000da00
	.long	0x00002100
	.long	0x00001000
	.long	0x0000ff00
	.long	0x0000f300
	.long	0x0000d200
	.long	0x0000cd00
	.long	0x00000c00
	.long	0x00001300
	.long	0x0000ec00
	.long	0x00005f00
	.long	0x00009700
	.long	0x00004400
	.long	0x00001700
	.long	0x0000c400
	.long	0x0000a700
	.long	0x00007e00
	.long	0x00003d00
	.long	0x00006400
	.long	0x00005d00
	.long	0x00001900
	.long	0x00007300
	.long	0x00006000
	.long	0x00008100
	.long	0x00004f00
	.long	0x0000dc00
	.long	0x00002200
	.long	0x00002a00
	.long	0x00009000
	.long	0x00008800
	.long	0x00004600
	.long	0x0000ee00
	.long	0x0000b800
	.long	0x00001400
	.long	0x0000de00
	.long	0x00005e00
	.long	0x00000b00
	.long	0x0000db00
	.long	0x0000e000
	.long	0x00003200
	.long	0x00003a00
	.long	0x00000a00
	.long	0x00004900
	.long	0x00000600
	.long	0x00002400
	.long	0x00005c00
	.long	0x0000c200
	.long	0x0000d300
	.long	0x0000ac00
	.long	0x00006200
	.long	0x00009100
	.long	0x00009500
	.long	0x0000e400
	.long	0x00007900
	.long	0x0000e700
	.long	0x0000c800
	.long	0x00003700
	.long	0x00006d00
	.long	0x00008d00
	.long	0x0000d500
	.long	0x00004e00
	.long	0x0000a900
	.long	0x00006c00
	.long	0x00005600
	.long	0x0000f400
	.long	0x0000ea00
	.long	0x00006500
	.long	0x00007a00
	.long	0x0000ae00
	.long	0x00000800
	.long	0x0000ba00
	.long	0x00007800
	.long	0x00002500
	.long	0x00002e00
	.long	0x00001c00
	.long	0x0000a600
	.long	0x0000b400
	.long	0x0000c600
	.long	0x0000e800
	.long	0x0000dd00
	.long	0x00007400
	.long	0x00001f00
	.long	0x00004b00
	.long	0x0000bd00
	.long	0x00008b00
	.long	0x00008a00
	.long	0x00007000
	.long	0x00003e00
	.long	0x0000b500
	.long	0x00006600
	.long	0x00004800
	.long	0x00000300
	.long	0x0000f600
	.long	0x00000e00
	.long	0x00006100
	.long	0x00003500
	.long	0x00005700
	.long	0x0000b900
	.long	0x00008600
	.long	0x0000c100
	.long	0x00001d00
	.long	0x00009e00
	.long	0x0000e100
	.long	0x0000f800
	.long	0x00009800
	.long	0x00001100
	.long	0x00006900
	.long	0x0000d900
	.long	0x00008e00
	.long	0x00009400
	.long	0x00009b00
	.long	0x00001e00
	.long	0x00008700
	.long	0x0000e900
	.long	0x0000ce00
	.long	0x00005500
	.long	0x00002800
	.long	0x0000df00
	.long	0x00008c00
	.long	0x0000a100
	.long	0x00008900
	.long	0x00000d00
	.long	0x0000bf00
	.long	0x0000e600
	.long	0x00004200
	.long	0x00006800
	.long	0x00004100
	.long	0x00009900
	.long	0x00002d00
	.long	0x00000f00
	.long	0x0000b000
	.long	0x00005400
	.long	0x0000bb00
	.long	0x00001600
	// Table 2.
	.long	0x00630000
	.long	0x007c0000
	.long	0x00770000
	.long	0x007b0000
	.long	0x00f20000
	.long	0x006b0000
	.long	0x006f0000
	.long	0x00c50000
	.long	0x00300000
	.long	0x00010000
	.long	0x00670000
	.long	0x002b0000
	.long	0x00fe0000
	.long	0x00d70000
	.long	0x00ab0000
	.long	0x00760000
	.long	0x00ca0000
	.long	0x00820000
	.long	0x00c90000
	.long	0x007d0000
	.long	0x00fa0000
	.long	0x00590000
	.long	0x00470000
	.long	0x00f00000
	.long	0x00ad0000
	.long	0x00d40000
	.long	0x00a20000
	.long	0x00af0000
	.long	0x009c0000
	.long	0x00a40000
	.long	0x00720000
	.long	0x00c00000
	.long	0x00b70000
	.long	0x00fd0000
	.long	0x00930000
	.long	0x00260000
	.long	0x00360000
	.long	0x003f0000
	.long	0x00f70000
	.long	0x00cc0000
	.long	0x00340000
	.long	0x00a50000
	.long	0x00e50000
	.long	0x00f10000
	.long	0x00710000
	.long	0x00d80000
	.long	0x00310000
	.long	0x00150000
	.long	0x00040000
	.long	0x00c70000
	.long	0x00230000
	.long	0x00c30000
	.long	0x00180000
	.long	0x00960000
	.long	0x00050000
	.long	0x009a0000
	.long	0x00070000
	.long	0x00120000
	.long	0x00800000
	.long	0x00e20000
	.long	0x00eb0000
	.long	0x00270000
	.long	0x00b20000
	.long	0x00750000
	.long	0x00090000
	.long	0x00830000
	.long	0x002c0000
	.long	0x001a0000
	.long	0x001b0000
	.long	0x006e0000
	.long	0x005a0000
	.long	0x00a00000
	.long	0x00520000
	.long	0x003b0000
	.long	0x00d60000
	.long	0x00b30000
	.long	0x00290000
	.long	0x00e30000
	.long	0x002f0000
	.long	0x00840000
	.long	0x00530000
	.long	0x00d10000
	.long	0x00000000
	.long	0x00ed0000
	.long	0x00200000
	.long	0x00fc0000
	.long	0x00b10000
	.long	0x005b0000
	.long	0x006a0000
	.long	0x00cb0000
	.long	0x00be0000
	.long	0x00390000
	.long	0x004a0000
	.long	0x004c0000
	.long	0x00580000
	.long	0x00cf0000
	.long	0x00d00000
	.long	0x00ef0000
	.long	0x00aa0000
	.long	0x00fb0000
	.long	0x00430000
	.long	0x004d0000
	.long	0x00330000
	.long	0x00850000
	.long	0x00450000
	.long	0x00f90000
	.long	0x00020000
	.long	0x007f0000
	.long	0x00500000
	.long	0x003c0000
	.long	0x009f0000
	.long	0x00a80000
	.long	0x00510000
	.long	0x00a30000
	.long	0x00400000
	.long	0x008f0000
	.long	0x00920000
	.long	0x009d0000
	.long	0x00380000
	.long	0x00f50000
	.long	0x00bc0000
	.long	0x00b60000
	.long	0x00da0000
	.long	0x00210000
	.long	0x00100000
	.long	0x00ff0000
	.long	0x00f30000
	.long	0x00d20000
	.long	0x00cd0000
	.long	0x000c0000
	.long	0x00130000
	.long	0x00ec0000
	.long	0x005f0000
	.long	0x00970000
	.long	0x00440000
	.long	0x00170000
	.long	0x00c40000
	.long	0x00a70000
	.long	0x007e0000
	.long	0x003d0000
	.long	0x00640000
	.long	0x005d0000
	.long	0x00190000
	.long	0x00730000
	.long	0x00600000
	.long	0x00810000
	.long	0x004f0000
	.long	0x00dc0000
	.long	0x00220000
	.long	0x002a0000
	.long	0x00900000
	.long	0x00880000
	.long	0x00460000
	.long	0x00ee0000
	.long	0x00b80000
	.long	0x00140000
	.long	0x00de0000
	.long	0x005e0000
	.long	0x000b0000
	.long	0x00db0000
	.long	0x00e00000
	.long	0x00320000
	.long	0x003a0000
	.long	0x000a0000
	.long	0x00490000
	.long	0x00060000
	.long	0x00240000
	.long	0x005c0000
	.long	0x00c20000
	.long	0x00d30000
	.long	0x00ac0000
	.long	0x00620000
	.long	0x00910000
	.long	0x00950000
	.long	0x00e40000
	.long	0x00790000
	.long	0x00e70000
	.long	0x00c80000
	.long	0x00370000
	.long	0x006d0000
	.long	0x008d0000
	.long	0x00d50000
	.long	0x004e0000
	.long	0x00a90000
	.long	0x006c0000
	.long	0x00560000
	.long	0x00f40000
	.long	0x00ea0000
	.long	0x00650000
	.long	0x007a0000
	.long	0x00ae0000
	.long	0x00080000
	.long	0x00ba0000
	.long	0x00780000
	.long	0x00250000
	.long	0x002e0000
	.long	0x001c0000
	.long	0x00a60000
	.long	0x00b40000
	.long	0x00c60000
	.long	0x00e80000
	.long	0x00dd0000
	.long	0x00740000
	.long	0x001f0000
	.long	0x004b0000
	.long	0x00bd0000
	.long	0x008b0000
	.long	0x008a0000
	.long	0x00700000
	.long	0x003e0000
	.long	0x00b50000
	.long	0x00660000
	.long	0x00480000
	.long	0x00030000
	.long	0x00f60000
	.long	0x000e0000
	.long	0x00610000
	.long	0x00350000
	.long	0x00570000
	.long	0x00b90000
	.long	0x00860000
	.long	0x00c10000
	.long	0x001d0000
	.long	0x009e0000
	.long	0x00e10000
	.long	0x00f80000
	.long	0x00980000
	.long	0x00110000
	.long	0x00690000
	.long	0x00d90000
	.long	0x008e0000
	.long	0x00940000
	.long	0x009b0000
	.long	0x001e0000
	.long	0x00870000
	.long	0x00e90000
	.long	0x00ce0000
	.long	0x00550000
	.long	0x00280000
	.long	0x00df0000
	.long	0x008c0000
	.long	0x00a10000
	.long	0x00890000
	.long	0x000d0000
	.long	0x00bf0000
	.long	0x00e60000
	.long	0x00420000
	.long	0x00680000
	.long	0x00410000
	.long	0x00990000
	.long	0x002d0000
	.long	0x000f0000
	.long	0x00b00000
	.long	0x00540000
	.long	0x00bb0000
	.long	0x00160000
	// Table 3.
	.long	0x63000000
	.long	0x7c000000
	.long	0x77000000
	.long	0x7b000000
	.long	0xf2000000
	.long	0x6b000000
	.long	0x6f000000
	.long	0xc5000000
	.long	0x30000000
	.long	0x01000000
	.long	0x67000000
	.long	0x2b000000
	.long	0xfe000000
	.long	0xd7000000
	.long	0xab000000
	.long	0x76000000
	.long	0xca000000
	.long	0x82000000
	.long	0xc9000000
	.long	0x7d000000
	.long	0xfa000000
	.long	0x59000000
	.long	0x47000000
	.long	0xf0000000
	.long	0xad000000
	.long	0xd4000000
	.long	0xa2000000
	.long	0xaf000000
	.long	0x9c000000
	.long	0xa4000000
	.long	0x72000000
	.long	0xc0000000
	.long	0xb7000000
	.long	0xfd000000
	.long	0x93000000
	.long	0x26000000
	.long	0x36000000
	.long	0x3f000000
	.long	0xf7000000
	.long	0xcc000000
	.long	0x34000000
	.long	0xa5000000
	.long	0xe5000000
	.long	0xf1000000
	.long	0x71000000
	.long	0xd8000000
	.long	0x31000000
	.long	0x15000000
	.long	0x04000000
	.long	0xc7000000
	.long	0x23000000
	.long	0xc3000000
	.long	0x18000000
	.long	0x96000000
	.long	0x05000000
	.long	0x9a000000
	.long	0x07000000
	.long	0x12000000
	.long	0x80000000
	.long	0xe2000000
	.long	0xeb000000
	.long	0x27000000
	.long	0xb2000000
	.long	0x75000000
	.long	0x09000000
	.long	0x83000000
	.long	0x2c000000
	.long	0x1a000000
	.long	0x1b000000
	.long	0x6e000000
	.long	0x5a000000
	.long	0xa0000000
	.long	0x52000000
	.long	0x3b000000
	.long	0xd6000000
	.long	0xb3000000
	.long	0x29000000
	.long	0xe3000000
	.long	0x2f000000
	.long	0x84000000
	.long	0x53000000
	.long	0xd1000000
	.long	0x00000000
	.long	0xed000000
	.long	0x20000000
	.long	0xfc000000
	.long	0xb1000000
	.long	0x5b000000
	.long	0x6a000000
	.long	0xcb000000
	.long	0xbe000000
	.long	0x39000000
	.long	0x4a000000
	.long	0x4c000000
	.long	0x58000000
	.long	0xcf000000
	.long	0xd0000000
	.long	0xef000000
	.long	0xaa000000
	.long	0xfb000000
	.long	0x43000000
	.long	0x4d000000
	.long	0x33000000
	.long	0x85000000
	.long	0x45000000
	.long	0xf9000000
	.long	0x02000000
	.long	0x7f000000
	.long	0x50000000
	.long	0x3c000000
	.long	0x9f000000
	.long	0xa8000000
	.long	0x51000000
	.long	0xa3000000
	.long	0x40000000
	.long	0x8f000000
	.long	0x92000000
	.long	0x9d000000
	.long	0x38000000
	.long	0xf5000000
	.long	0xbc000000
	.long	0xb6000000
	.long	0xda000000
	.long	0x21000000
	.long	0x10000000
	.long	0xff000000
	.long	0xf3000000
	.long	0xd2000000
	.long	0xcd000000
	.long	0x0c000000
	.long	0x13000000
	.long	0xec000000
	.long	0x5f000000
	.long	0x97000000
	.long	0x44000000
	.long	0x17000000
	.long	0xc4000000
	.long	0xa7000000
	.long	0x7e000000
	.long	0x3d000000
	.long	0x64000000
	.long	0x5d000000
	.long	0x19000000
	.long	0x73000000
	.long	0x60000000
	.long	0x81000000
	.long	0x4f000000
	.long	0xdc000000
	.long	0x22000000
	.long	0x2a000000
	.long	0x90000000
	.long	0x88000000
	.long	0x46000000
	.long	0xee000000
	.long	0xb8000000
	.long	0x14000000
	.long	0xde000000
	.long	0x5e000000
	.long	0x0b000000
	.long	0xdb000000
	.long	0xe0000000
	.long	0x32000000
	.long	0x3a000000
	.long	0x0a000000
	.long	0x49000000
	.long	0x06000000
	.long	0x24000000
	.long	0x5c000000
	.long	0xc2000000
	.long	0xd3000000
	.long	0xac000000
	.long	0x62000000
	.long	0x91000000
	.long	0x95000000
	.long	0xe4000000
	.long	0x79000000
	.long	0xe7000000
	.long	0xc8000000
	.long	0x37000000
	.long	0x6d000000
	.long	0x8d000000
	.long	0xd5000000
	.long	0x4e000000
	.long	0xa9000000
	.long	0x6c000000
	.long	0x56000000
	.long	0xf4000000
	.long	0xea000000
	.long	0x65000000
	.long	0x7a000000
	.long	0xae000000
	.long	0x08000000
	.long	0xba000000
	.long	0x78000000
	.long	0x25000000
	.long	0x2e000000
	.long	0x1c000000
	.long	0xa6000000
	.long	0xb4000000
	.long	0xc6000000
	.long	0xe8000000
	.long	0xdd000000
	.long	0x74000000
	.long	0x1f000000
	.long	0x4b000000
	.long	0xbd000000
	.long	0x8b000000
	.long	0x8a000000
	.long	0x70000000
	.long	0x3e000000
	.long	0xb5000000
	.long	0x66000000
	.long	0x48000000
	.long	0x03000000
	.long	0xf6000000
	.long	0x0e000000
	.long	0x61000000
	.long	0x35000000
	.long	0x57000000
	.long	0xb9000000
	.long	0x86000000
	.long	0xc1000000
	.long	0x1d000000
	.long	0x9e000000
	.long	0xe1000000
	.long	0xf8000000
	.long	0x98000000
	.long	0x11000000
	.long	0x69000000
	.long	0xd9000000
	.long	0x8e000000
	.long	0x94000000
	.long	0x9b000000
	.long	0x1e000000
	.long	0x87000000
	.long	0xe9000000
	.long	0xce000000
	.long	0x55000000
	.long	0x28000000
	.long	0xdf000000
	.long	0x8c000000
	.long	0xa1000000
	.long	0x89000000
	.long	0x0d000000
	.long	0xbf000000
	.long	0xe6000000
	.long	0x42000000
	.long	0x68000000
	.long	0x41000000
	.long	0x99000000
	.long	0x2d000000
	.long	0x0f000000
	.long	0xb0000000
	.long	0x54000000
	.long	0xbb000000
	.long	0x16000000


// InvSubBytes embedded in words tables.
	.globl	_OLDAESInvSubBytesWordTable
	.private_extern	_OLDAESInvSubBytesWordTable
	.align	2
_OLDAESInvSubBytesWordTable:
	// Table 0.
	.long	0x00000052
	.long	0x00000009
	.long	0x0000006a
	.long	0x000000d5
	.long	0x00000030
	.long	0x00000036
	.long	0x000000a5
	.long	0x00000038
	.long	0x000000bf
	.long	0x00000040
	.long	0x000000a3
	.long	0x0000009e
	.long	0x00000081
	.long	0x000000f3
	.long	0x000000d7
	.long	0x000000fb
	.long	0x0000007c
	.long	0x000000e3
	.long	0x00000039
	.long	0x00000082
	.long	0x0000009b
	.long	0x0000002f
	.long	0x000000ff
	.long	0x00000087
	.long	0x00000034
	.long	0x0000008e
	.long	0x00000043
	.long	0x00000044
	.long	0x000000c4
	.long	0x000000de
	.long	0x000000e9
	.long	0x000000cb
	.long	0x00000054
	.long	0x0000007b
	.long	0x00000094
	.long	0x00000032
	.long	0x000000a6
	.long	0x000000c2
	.long	0x00000023
	.long	0x0000003d
	.long	0x000000ee
	.long	0x0000004c
	.long	0x00000095
	.long	0x0000000b
	.long	0x00000042
	.long	0x000000fa
	.long	0x000000c3
	.long	0x0000004e
	.long	0x00000008
	.long	0x0000002e
	.long	0x000000a1
	.long	0x00000066
	.long	0x00000028
	.long	0x000000d9
	.long	0x00000024
	.long	0x000000b2
	.long	0x00000076
	.long	0x0000005b
	.long	0x000000a2
	.long	0x00000049
	.long	0x0000006d
	.long	0x0000008b
	.long	0x000000d1
	.long	0x00000025
	.long	0x00000072
	.long	0x000000f8
	.long	0x000000f6
	.long	0x00000064
	.long	0x00000086
	.long	0x00000068
	.long	0x00000098
	.long	0x00000016
	.long	0x000000d4
	.long	0x000000a4
	.long	0x0000005c
	.long	0x000000cc
	.long	0x0000005d
	.long	0x00000065
	.long	0x000000b6
	.long	0x00000092
	.long	0x0000006c
	.long	0x00000070
	.long	0x00000048
	.long	0x00000050
	.long	0x000000fd
	.long	0x000000ed
	.long	0x000000b9
	.long	0x000000da
	.long	0x0000005e
	.long	0x00000015
	.long	0x00000046
	.long	0x00000057
	.long	0x000000a7
	.long	0x0000008d
	.long	0x0000009d
	.long	0x00000084
	.long	0x00000090
	.long	0x000000d8
	.long	0x000000ab
	.long	0x00000000
	.long	0x0000008c
	.long	0x000000bc
	.long	0x000000d3
	.long	0x0000000a
	.long	0x000000f7
	.long	0x000000e4
	.long	0x00000058
	.long	0x00000005
	.long	0x000000b8
	.long	0x000000b3
	.long	0x00000045
	.long	0x00000006
	.long	0x000000d0
	.long	0x0000002c
	.long	0x0000001e
	.long	0x0000008f
	.long	0x000000ca
	.long	0x0000003f
	.long	0x0000000f
	.long	0x00000002
	.long	0x000000c1
	.long	0x000000af
	.long	0x000000bd
	.long	0x00000003
	.long	0x00000001
	.long	0x00000013
	.long	0x0000008a
	.long	0x0000006b
	.long	0x0000003a
	.long	0x00000091
	.long	0x00000011
	.long	0x00000041
	.long	0x0000004f
	.long	0x00000067
	.long	0x000000dc
	.long	0x000000ea
	.long	0x00000097
	.long	0x000000f2
	.long	0x000000cf
	.long	0x000000ce
	.long	0x000000f0
	.long	0x000000b4
	.long	0x000000e6
	.long	0x00000073
	.long	0x00000096
	.long	0x000000ac
	.long	0x00000074
	.long	0x00000022
	.long	0x000000e7
	.long	0x000000ad
	.long	0x00000035
	.long	0x00000085
	.long	0x000000e2
	.long	0x000000f9
	.long	0x00000037
	.long	0x000000e8
	.long	0x0000001c
	.long	0x00000075
	.long	0x000000df
	.long	0x0000006e
	.long	0x00000047
	.long	0x000000f1
	.long	0x0000001a
	.long	0x00000071
	.long	0x0000001d
	.long	0x00000029
	.long	0x000000c5
	.long	0x00000089
	.long	0x0000006f
	.long	0x000000b7
	.long	0x00000062
	.long	0x0000000e
	.long	0x000000aa
	.long	0x00000018
	.long	0x000000be
	.long	0x0000001b
	.long	0x000000fc
	.long	0x00000056
	.long	0x0000003e
	.long	0x0000004b
	.long	0x000000c6
	.long	0x000000d2
	.long	0x00000079
	.long	0x00000020
	.long	0x0000009a
	.long	0x000000db
	.long	0x000000c0
	.long	0x000000fe
	.long	0x00000078
	.long	0x000000cd
	.long	0x0000005a
	.long	0x000000f4
	.long	0x0000001f
	.long	0x000000dd
	.long	0x000000a8
	.long	0x00000033
	.long	0x00000088
	.long	0x00000007
	.long	0x000000c7
	.long	0x00000031
	.long	0x000000b1
	.long	0x00000012
	.long	0x00000010
	.long	0x00000059
	.long	0x00000027
	.long	0x00000080
	.long	0x000000ec
	.long	0x0000005f
	.long	0x00000060
	.long	0x00000051
	.long	0x0000007f
	.long	0x000000a9
	.long	0x00000019
	.long	0x000000b5
	.long	0x0000004a
	.long	0x0000000d
	.long	0x0000002d
	.long	0x000000e5
	.long	0x0000007a
	.long	0x0000009f
	.long	0x00000093
	.long	0x000000c9
	.long	0x0000009c
	.long	0x000000ef
	.long	0x000000a0
	.long	0x000000e0
	.long	0x0000003b
	.long	0x0000004d
	.long	0x000000ae
	.long	0x0000002a
	.long	0x000000f5
	.long	0x000000b0
	.long	0x000000c8
	.long	0x000000eb
	.long	0x000000bb
	.long	0x0000003c
	.long	0x00000083
	.long	0x00000053
	.long	0x00000099
	.long	0x00000061
	.long	0x00000017
	.long	0x0000002b
	.long	0x00000004
	.long	0x0000007e
	.long	0x000000ba
	.long	0x00000077
	.long	0x000000d6
	.long	0x00000026
	.long	0x000000e1
	.long	0x00000069
	.long	0x00000014
	.long	0x00000063
	.long	0x00000055
	.long	0x00000021
	.long	0x0000000c
	.long	0x0000007d
	// Table 1.
	.long	0x00005200
	.long	0x00000900
	.long	0x00006a00
	.long	0x0000d500
	.long	0x00003000
	.long	0x00003600
	.long	0x0000a500
	.long	0x00003800
	.long	0x0000bf00
	.long	0x00004000
	.long	0x0000a300
	.long	0x00009e00
	.long	0x00008100
	.long	0x0000f300
	.long	0x0000d700
	.long	0x0000fb00
	.long	0x00007c00
	.long	0x0000e300
	.long	0x00003900
	.long	0x00008200
	.long	0x00009b00
	.long	0x00002f00
	.long	0x0000ff00
	.long	0x00008700
	.long	0x00003400
	.long	0x00008e00
	.long	0x00004300
	.long	0x00004400
	.long	0x0000c400
	.long	0x0000de00
	.long	0x0000e900
	.long	0x0000cb00
	.long	0x00005400
	.long	0x00007b00
	.long	0x00009400
	.long	0x00003200
	.long	0x0000a600
	.long	0x0000c200
	.long	0x00002300
	.long	0x00003d00
	.long	0x0000ee00
	.long	0x00004c00
	.long	0x00009500
	.long	0x00000b00
	.long	0x00004200
	.long	0x0000fa00
	.long	0x0000c300
	.long	0x00004e00
	.long	0x00000800
	.long	0x00002e00
	.long	0x0000a100
	.long	0x00006600
	.long	0x00002800
	.long	0x0000d900
	.long	0x00002400
	.long	0x0000b200
	.long	0x00007600
	.long	0x00005b00
	.long	0x0000a200
	.long	0x00004900
	.long	0x00006d00
	.long	0x00008b00
	.long	0x0000d100
	.long	0x00002500
	.long	0x00007200
	.long	0x0000f800
	.long	0x0000f600
	.long	0x00006400
	.long	0x00008600
	.long	0x00006800
	.long	0x00009800
	.long	0x00001600
	.long	0x0000d400
	.long	0x0000a400
	.long	0x00005c00
	.long	0x0000cc00
	.long	0x00005d00
	.long	0x00006500
	.long	0x0000b600
	.long	0x00009200
	.long	0x00006c00
	.long	0x00007000
	.long	0x00004800
	.long	0x00005000
	.long	0x0000fd00
	.long	0x0000ed00
	.long	0x0000b900
	.long	0x0000da00
	.long	0x00005e00
	.long	0x00001500
	.long	0x00004600
	.long	0x00005700
	.long	0x0000a700
	.long	0x00008d00
	.long	0x00009d00
	.long	0x00008400
	.long	0x00009000
	.long	0x0000d800
	.long	0x0000ab00
	.long	0x00000000
	.long	0x00008c00
	.long	0x0000bc00
	.long	0x0000d300
	.long	0x00000a00
	.long	0x0000f700
	.long	0x0000e400
	.long	0x00005800
	.long	0x00000500
	.long	0x0000b800
	.long	0x0000b300
	.long	0x00004500
	.long	0x00000600
	.long	0x0000d000
	.long	0x00002c00
	.long	0x00001e00
	.long	0x00008f00
	.long	0x0000ca00
	.long	0x00003f00
	.long	0x00000f00
	.long	0x00000200
	.long	0x0000c100
	.long	0x0000af00
	.long	0x0000bd00
	.long	0x00000300
	.long	0x00000100
	.long	0x00001300
	.long	0x00008a00
	.long	0x00006b00
	.long	0x00003a00
	.long	0x00009100
	.long	0x00001100
	.long	0x00004100
	.long	0x00004f00
	.long	0x00006700
	.long	0x0000dc00
	.long	0x0000ea00
	.long	0x00009700
	.long	0x0000f200
	.long	0x0000cf00
	.long	0x0000ce00
	.long	0x0000f000
	.long	0x0000b400
	.long	0x0000e600
	.long	0x00007300
	.long	0x00009600
	.long	0x0000ac00
	.long	0x00007400
	.long	0x00002200
	.long	0x0000e700
	.long	0x0000ad00
	.long	0x00003500
	.long	0x00008500
	.long	0x0000e200
	.long	0x0000f900
	.long	0x00003700
	.long	0x0000e800
	.long	0x00001c00
	.long	0x00007500
	.long	0x0000df00
	.long	0x00006e00
	.long	0x00004700
	.long	0x0000f100
	.long	0x00001a00
	.long	0x00007100
	.long	0x00001d00
	.long	0x00002900
	.long	0x0000c500
	.long	0x00008900
	.long	0x00006f00
	.long	0x0000b700
	.long	0x00006200
	.long	0x00000e00
	.long	0x0000aa00
	.long	0x00001800
	.long	0x0000be00
	.long	0x00001b00
	.long	0x0000fc00
	.long	0x00005600
	.long	0x00003e00
	.long	0x00004b00
	.long	0x0000c600
	.long	0x0000d200
	.long	0x00007900
	.long	0x00002000
	.long	0x00009a00
	.long	0x0000db00
	.long	0x0000c000
	.long	0x0000fe00
	.long	0x00007800
	.long	0x0000cd00
	.long	0x00005a00
	.long	0x0000f400
	.long	0x00001f00
	.long	0x0000dd00
	.long	0x0000a800
	.long	0x00003300
	.long	0x00008800
	.long	0x00000700
	.long	0x0000c700
	.long	0x00003100
	.long	0x0000b100
	.long	0x00001200
	.long	0x00001000
	.long	0x00005900
	.long	0x00002700
	.long	0x00008000
	.long	0x0000ec00
	.long	0x00005f00
	.long	0x00006000
	.long	0x00005100
	.long	0x00007f00
	.long	0x0000a900
	.long	0x00001900
	.long	0x0000b500
	.long	0x00004a00
	.long	0x00000d00
	.long	0x00002d00
	.long	0x0000e500
	.long	0x00007a00
	.long	0x00009f00
	.long	0x00009300
	.long	0x0000c900
	.long	0x00009c00
	.long	0x0000ef00
	.long	0x0000a000
	.long	0x0000e000
	.long	0x00003b00
	.long	0x00004d00
	.long	0x0000ae00
	.long	0x00002a00
	.long	0x0000f500
	.long	0x0000b000
	.long	0x0000c800
	.long	0x0000eb00
	.long	0x0000bb00
	.long	0x00003c00
	.long	0x00008300
	.long	0x00005300
	.long	0x00009900
	.long	0x00006100
	.long	0x00001700
	.long	0x00002b00
	.long	0x00000400
	.long	0x00007e00
	.long	0x0000ba00
	.long	0x00007700
	.long	0x0000d600
	.long	0x00002600
	.long	0x0000e100
	.long	0x00006900
	.long	0x00001400
	.long	0x00006300
	.long	0x00005500
	.long	0x00002100
	.long	0x00000c00
	.long	0x00007d00
	// Table 2.
	.long	0x00520000
	.long	0x00090000
	.long	0x006a0000
	.long	0x00d50000
	.long	0x00300000
	.long	0x00360000
	.long	0x00a50000
	.long	0x00380000
	.long	0x00bf0000
	.long	0x00400000
	.long	0x00a30000
	.long	0x009e0000
	.long	0x00810000
	.long	0x00f30000
	.long	0x00d70000
	.long	0x00fb0000
	.long	0x007c0000
	.long	0x00e30000
	.long	0x00390000
	.long	0x00820000
	.long	0x009b0000
	.long	0x002f0000
	.long	0x00ff0000
	.long	0x00870000
	.long	0x00340000
	.long	0x008e0000
	.long	0x00430000
	.long	0x00440000
	.long	0x00c40000
	.long	0x00de0000
	.long	0x00e90000
	.long	0x00cb0000
	.long	0x00540000
	.long	0x007b0000
	.long	0x00940000
	.long	0x00320000
	.long	0x00a60000
	.long	0x00c20000
	.long	0x00230000
	.long	0x003d0000
	.long	0x00ee0000
	.long	0x004c0000
	.long	0x00950000
	.long	0x000b0000
	.long	0x00420000
	.long	0x00fa0000
	.long	0x00c30000
	.long	0x004e0000
	.long	0x00080000
	.long	0x002e0000
	.long	0x00a10000
	.long	0x00660000
	.long	0x00280000
	.long	0x00d90000
	.long	0x00240000
	.long	0x00b20000
	.long	0x00760000
	.long	0x005b0000
	.long	0x00a20000
	.long	0x00490000
	.long	0x006d0000
	.long	0x008b0000
	.long	0x00d10000
	.long	0x00250000
	.long	0x00720000
	.long	0x00f80000
	.long	0x00f60000
	.long	0x00640000
	.long	0x00860000
	.long	0x00680000
	.long	0x00980000
	.long	0x00160000
	.long	0x00d40000
	.long	0x00a40000
	.long	0x005c0000
	.long	0x00cc0000
	.long	0x005d0000
	.long	0x00650000
	.long	0x00b60000
	.long	0x00920000
	.long	0x006c0000
	.long	0x00700000
	.long	0x00480000
	.long	0x00500000
	.long	0x00fd0000
	.long	0x00ed0000
	.long	0x00b90000
	.long	0x00da0000
	.long	0x005e0000
	.long	0x00150000
	.long	0x00460000
	.long	0x00570000
	.long	0x00a70000
	.long	0x008d0000
	.long	0x009d0000
	.long	0x00840000
	.long	0x00900000
	.long	0x00d80000
	.long	0x00ab0000
	.long	0x00000000
	.long	0x008c0000
	.long	0x00bc0000
	.long	0x00d30000
	.long	0x000a0000
	.long	0x00f70000
	.long	0x00e40000
	.long	0x00580000
	.long	0x00050000
	.long	0x00b80000
	.long	0x00b30000
	.long	0x00450000
	.long	0x00060000
	.long	0x00d00000
	.long	0x002c0000
	.long	0x001e0000
	.long	0x008f0000
	.long	0x00ca0000
	.long	0x003f0000
	.long	0x000f0000
	.long	0x00020000
	.long	0x00c10000
	.long	0x00af0000
	.long	0x00bd0000
	.long	0x00030000
	.long	0x00010000
	.long	0x00130000
	.long	0x008a0000
	.long	0x006b0000
	.long	0x003a0000
	.long	0x00910000
	.long	0x00110000
	.long	0x00410000
	.long	0x004f0000
	.long	0x00670000
	.long	0x00dc0000
	.long	0x00ea0000
	.long	0x00970000
	.long	0x00f20000
	.long	0x00cf0000
	.long	0x00ce0000
	.long	0x00f00000
	.long	0x00b40000
	.long	0x00e60000
	.long	0x00730000
	.long	0x00960000
	.long	0x00ac0000
	.long	0x00740000
	.long	0x00220000
	.long	0x00e70000
	.long	0x00ad0000
	.long	0x00350000
	.long	0x00850000
	.long	0x00e20000
	.long	0x00f90000
	.long	0x00370000
	.long	0x00e80000
	.long	0x001c0000
	.long	0x00750000
	.long	0x00df0000
	.long	0x006e0000
	.long	0x00470000
	.long	0x00f10000
	.long	0x001a0000
	.long	0x00710000
	.long	0x001d0000
	.long	0x00290000
	.long	0x00c50000
	.long	0x00890000
	.long	0x006f0000
	.long	0x00b70000
	.long	0x00620000
	.long	0x000e0000
	.long	0x00aa0000
	.long	0x00180000
	.long	0x00be0000
	.long	0x001b0000
	.long	0x00fc0000
	.long	0x00560000
	.long	0x003e0000
	.long	0x004b0000
	.long	0x00c60000
	.long	0x00d20000
	.long	0x00790000
	.long	0x00200000
	.long	0x009a0000
	.long	0x00db0000
	.long	0x00c00000
	.long	0x00fe0000
	.long	0x00780000
	.long	0x00cd0000
	.long	0x005a0000
	.long	0x00f40000
	.long	0x001f0000
	.long	0x00dd0000
	.long	0x00a80000
	.long	0x00330000
	.long	0x00880000
	.long	0x00070000
	.long	0x00c70000
	.long	0x00310000
	.long	0x00b10000
	.long	0x00120000
	.long	0x00100000
	.long	0x00590000
	.long	0x00270000
	.long	0x00800000
	.long	0x00ec0000
	.long	0x005f0000
	.long	0x00600000
	.long	0x00510000
	.long	0x007f0000
	.long	0x00a90000
	.long	0x00190000
	.long	0x00b50000
	.long	0x004a0000
	.long	0x000d0000
	.long	0x002d0000
	.long	0x00e50000
	.long	0x007a0000
	.long	0x009f0000
	.long	0x00930000
	.long	0x00c90000
	.long	0x009c0000
	.long	0x00ef0000
	.long	0x00a00000
	.long	0x00e00000
	.long	0x003b0000
	.long	0x004d0000
	.long	0x00ae0000
	.long	0x002a0000
	.long	0x00f50000
	.long	0x00b00000
	.long	0x00c80000
	.long	0x00eb0000
	.long	0x00bb0000
	.long	0x003c0000
	.long	0x00830000
	.long	0x00530000
	.long	0x00990000
	.long	0x00610000
	.long	0x00170000
	.long	0x002b0000
	.long	0x00040000
	.long	0x007e0000
	.long	0x00ba0000
	.long	0x00770000
	.long	0x00d60000
	.long	0x00260000
	.long	0x00e10000
	.long	0x00690000
	.long	0x00140000
	.long	0x00630000
	.long	0x00550000
	.long	0x00210000
	.long	0x000c0000
	.long	0x007d0000
	// Table 3.
	.long	0x52000000
	.long	0x09000000
	.long	0x6a000000
	.long	0xd5000000
	.long	0x30000000
	.long	0x36000000
	.long	0xa5000000
	.long	0x38000000
	.long	0xbf000000
	.long	0x40000000
	.long	0xa3000000
	.long	0x9e000000
	.long	0x81000000
	.long	0xf3000000
	.long	0xd7000000
	.long	0xfb000000
	.long	0x7c000000
	.long	0xe3000000
	.long	0x39000000
	.long	0x82000000
	.long	0x9b000000
	.long	0x2f000000
	.long	0xff000000
	.long	0x87000000
	.long	0x34000000
	.long	0x8e000000
	.long	0x43000000
	.long	0x44000000
	.long	0xc4000000
	.long	0xde000000
	.long	0xe9000000
	.long	0xcb000000
	.long	0x54000000
	.long	0x7b000000
	.long	0x94000000
	.long	0x32000000
	.long	0xa6000000
	.long	0xc2000000
	.long	0x23000000
	.long	0x3d000000
	.long	0xee000000
	.long	0x4c000000
	.long	0x95000000
	.long	0x0b000000
	.long	0x42000000
	.long	0xfa000000
	.long	0xc3000000
	.long	0x4e000000
	.long	0x08000000
	.long	0x2e000000
	.long	0xa1000000
	.long	0x66000000
	.long	0x28000000
	.long	0xd9000000
	.long	0x24000000
	.long	0xb2000000
	.long	0x76000000
	.long	0x5b000000
	.long	0xa2000000
	.long	0x49000000
	.long	0x6d000000
	.long	0x8b000000
	.long	0xd1000000
	.long	0x25000000
	.long	0x72000000
	.long	0xf8000000
	.long	0xf6000000
	.long	0x64000000
	.long	0x86000000
	.long	0x68000000
	.long	0x98000000
	.long	0x16000000
	.long	0xd4000000
	.long	0xa4000000
	.long	0x5c000000
	.long	0xcc000000
	.long	0x5d000000
	.long	0x65000000
	.long	0xb6000000
	.long	0x92000000
	.long	0x6c000000
	.long	0x70000000
	.long	0x48000000
	.long	0x50000000
	.long	0xfd000000
	.long	0xed000000
	.long	0xb9000000
	.long	0xda000000
	.long	0x5e000000
	.long	0x15000000
	.long	0x46000000
	.long	0x57000000
	.long	0xa7000000
	.long	0x8d000000
	.long	0x9d000000
	.long	0x84000000
	.long	0x90000000
	.long	0xd8000000
	.long	0xab000000
	.long	0x00000000
	.long	0x8c000000
	.long	0xbc000000
	.long	0xd3000000
	.long	0x0a000000
	.long	0xf7000000
	.long	0xe4000000
	.long	0x58000000
	.long	0x05000000
	.long	0xb8000000
	.long	0xb3000000
	.long	0x45000000
	.long	0x06000000
	.long	0xd0000000
	.long	0x2c000000
	.long	0x1e000000
	.long	0x8f000000
	.long	0xca000000
	.long	0x3f000000
	.long	0x0f000000
	.long	0x02000000
	.long	0xc1000000
	.long	0xaf000000
	.long	0xbd000000
	.long	0x03000000
	.long	0x01000000
	.long	0x13000000
	.long	0x8a000000
	.long	0x6b000000
	.long	0x3a000000
	.long	0x91000000
	.long	0x11000000
	.long	0x41000000
	.long	0x4f000000
	.long	0x67000000
	.long	0xdc000000
	.long	0xea000000
	.long	0x97000000
	.long	0xf2000000
	.long	0xcf000000
	.long	0xce000000
	.long	0xf0000000
	.long	0xb4000000
	.long	0xe6000000
	.long	0x73000000
	.long	0x96000000
	.long	0xac000000
	.long	0x74000000
	.long	0x22000000
	.long	0xe7000000
	.long	0xad000000
	.long	0x35000000
	.long	0x85000000
	.long	0xe2000000
	.long	0xf9000000
	.long	0x37000000
	.long	0xe8000000
	.long	0x1c000000
	.long	0x75000000
	.long	0xdf000000
	.long	0x6e000000
	.long	0x47000000
	.long	0xf1000000
	.long	0x1a000000
	.long	0x71000000
	.long	0x1d000000
	.long	0x29000000
	.long	0xc5000000
	.long	0x89000000
	.long	0x6f000000
	.long	0xb7000000
	.long	0x62000000
	.long	0x0e000000
	.long	0xaa000000
	.long	0x18000000
	.long	0xbe000000
	.long	0x1b000000
	.long	0xfc000000
	.long	0x56000000
	.long	0x3e000000
	.long	0x4b000000
	.long	0xc6000000
	.long	0xd2000000
	.long	0x79000000
	.long	0x20000000
	.long	0x9a000000
	.long	0xdb000000
	.long	0xc0000000
	.long	0xfe000000
	.long	0x78000000
	.long	0xcd000000
	.long	0x5a000000
	.long	0xf4000000
	.long	0x1f000000
	.long	0xdd000000
	.long	0xa8000000
	.long	0x33000000
	.long	0x88000000
	.long	0x07000000
	.long	0xc7000000
	.long	0x31000000
	.long	0xb1000000
	.long	0x12000000
	.long	0x10000000
	.long	0x59000000
	.long	0x27000000
	.long	0x80000000
	.long	0xec000000
	.long	0x5f000000
	.long	0x60000000
	.long	0x51000000
	.long	0x7f000000
	.long	0xa9000000
	.long	0x19000000
	.long	0xb5000000
	.long	0x4a000000
	.long	0x0d000000
	.long	0x2d000000
	.long	0xe5000000
	.long	0x7a000000
	.long	0x9f000000
	.long	0x93000000
	.long	0xc9000000
	.long	0x9c000000
	.long	0xef000000
	.long	0xa0000000
	.long	0xe0000000
	.long	0x3b000000
	.long	0x4d000000
	.long	0xae000000
	.long	0x2a000000
	.long	0xf5000000
	.long	0xb0000000
	.long	0xc8000000
	.long	0xeb000000
	.long	0xbb000000
	.long	0x3c000000
	.long	0x83000000
	.long	0x53000000
	.long	0x99000000
	.long	0x61000000
	.long	0x17000000
	.long	0x2b000000
	.long	0x04000000
	.long	0x7e000000
	.long	0xba000000
	.long	0x77000000
	.long	0xd6000000
	.long	0x26000000
	.long	0xe1000000
	.long	0x69000000
	.long	0x14000000
	.long	0x63000000
	.long	0x55000000
	.long	0x21000000
	.long	0x0c000000
	.long	0x7d000000
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/AESedp/Intel/DecryptCBC.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#include "../AESAssembly.h"


// Generate object code only if this implementation has been requested.
#if defined UseAESedp_IntelAssembly


/*	AESDecryptCBC.s -- Decrypt blocks with AES in Cipher Block Chaining mode.

	Written by Eric Postpischil, January 24, 2008.
*/


/*	Define a macro to select a value based on architecture.  This reduces
	some of the architecture conditionalization later in the source.
*/
#if defined __i386__
	#define	Arch(i386, x86_64)	i386
#elif defined __x86_64__
	#define	Arch(i386, x86_64)	x86_64
#endif


/*	Rename the general registers.  This makes it easier to keep track of them
	and provides names for the "whole register" that are uniform between i386
	and x86_64.
*/
#if defined __i386__
	#define	r0	%eax	// Available for any use.
	#define	r1	%ecx	// Available for any use, some special purposes (loop).
	#define	r2	%edx	// Available for any use.
	#define	r3	%ebx	// Must be preserved by called routine.
	#define	r4	%esp	// Stack pointer.
	#define	r5	%ebp	// Frame pointer, must preserve, no bare indirect.
	#define	r6	%esi	// Must be preserved by called routine.
	#define	r7	%edi	// Must be preserved by called routine.
#elif defined __x86_64__
	#define	r0	%rax	// Available for any use.
	#define	r1	%rcx	// Available for any use.
	#define	r2	%rdx	// Available for any use.
	#define	r3	%rbx	// Must be preserved by called routine.
	#define	r4	%rsp	// Stack pointer.
	#define	r5	%rbp	// Frame pointer.  Must be preserved by called routine.
	#define	r6	%rsi	// Available for any use.
	#define	r7	%rdi	// Available for any use.
	#define	r8	%r8		// Available for any use.
	#define	r9	%r9		// Available for any use.
	#define	r10	%r10	// Available for any use.
	#define	r11	%r11	// Available for any use.
	#define	r12	%r12	// Must be preserved by called routine.
	#define	r13	%r13	// Must be preserved by called routine.
	#define	r14	%r14	// Must be preserved by called routine.
	#define	r15	%r15	// Must be preserved by called routine.
#else
	#error "Unknown architecture."
#endif


/*	Routine:

		_AESDecryptCBC.

	Function:

		This routine uses _AESDecryptWithExpandedKey to decrypt blocks in
		Cipher Block Chaining mode, which requires chaining the AES state
		from block to block.  In CBC mode, each output block is (after the
		underlying decryption) XORed with the previous input block.  On the
		first iteration, the previous input block is supplied from a chain
		buffer.

	Input:

		void *O				// Output
		const void *I		// Input
		void *ChainBuffer	// Chain buffer / initial value.
		void *Key			// Expanded Key.
		long Blocks			// Number of 16-byte blocks to process.
		long Rounds			// Number of rounds.

	Output:

		Decrypted text is written to *O.

		The final input block is written to *ChainBuffer.
*/
	.globl _AESDecryptCBC
	.private_extern	_AESDecryptCBC
_AESDecryptCBC:

	// Push new stack frame.
	push	r5

	// Save registers.
	push	r3
	#if defined __i386__
		push	r6
		push	r7
		#define	RegisterSaveSize	(3*4)
	#elif defined __x86_64__
		push	r12
		push	r13
		push	r14
		push	r15
		#define	RegisterSaveSize	(5*8)
	#endif

/*	B is the number of bytes from the top of stack just before the instruction
	that called this routine to the top of stack after we push the frame
	pointer and other registers.  It provides information needed to align our
	stack frame.
*/
#define	B	(RegisterSaveSize + 2*Arch(4, 8))

/*	Allocate space on the stack for 16 bytes for the AES state, 16 bytes to
	save the chain value, and, on i386, 16 bytes for four four-byte arguments,
	and padding needed to produce 16-byte alignment.
*/
#define	LocalsSize	((16*2 + Arch(16, 0) + B + 15 & -16) - B)
#define	StackFrame	(LocalsSize + B)

/*	LocalState is the offset from the stack pointer to where we store the AES
 	state.
*/
#define	LocalState	Arch(16, 0)
#define	SavedChain	Arch(32, 16)	// Offset to saved chain value.

	#if 0 < LocalsSize
		sub		$LocalsSize, r4	// Allocate space on stack.
	#endif

// Non-volatile registers.
#define	I			r3
#define	O			r5
#define	Blocks		Arch(r6, r12)
#define	ChainBuffer	Arch(r7, r13)
#define	Rounds		Arch(Not used, r14)
#define	Key			Arch(Not used, r15)

// Volatile registers.
#define	t0			r0
#define	v0			%xmm0
#define	vState0		%xmm4

// Arguments passed to us.
#if defined __i386__
	// Define location of argument i.
	#define	Argument(i)	StackFrame+4*(i)(r4)
#endif
#define	ArgO			Arch(Argument(0), r7)
#define	ArgI			Arch(Argument(1), r6)
#define	ArgChainBuffer	Arch(Argument(2), r2)
#define	ArgKey			Arch(Argument(3), r1)
#define	ArgBlocks		Arch(Argument(4), r8)
#define	ArgRounds		Arch(Argument(5), r9)

	/*	Get some arguments.  We need to move these from the stack (on i386)
		or volatile registers (on x86_64) to non-volatile registers where we
		can use them and keep them during calls to a subroutine.
	*/
	mov		ArgO, O
	mov		ArgI, I
	mov		ArgChainBuffer, ChainBuffer
	mov		ArgBlocks, Blocks

	// Convert Blocks from number of blocks to displacement in bytes.
	imul	$16, Blocks
	je		done	// Leave if we were given zero blocks.

	// Save last input block to write to ChainBuffer later.
	movupd	-16(I, Blocks), v0
	movapd	v0, SavedChain(r4)

	#if defined __i386__

		// Put arguments we will pass on stack.
		mov		ArgRounds, t0
		mov		t0,    3*4(r4)

		mov		ArgKey, t0
		mov		t0,    2*4(r4)

		lea		LocalState(r4), t0
		mov		t0,    0*4(r4)

	#else

		// Put arguments we will pass into non-volatile registers.
		mov		ArgRounds, Rounds
		mov		ArgKey,    Key

	#endif

	add		$-16, Blocks

	jle		2f			// Skip main loop if there was only one block.

// Main loop.
1:
	#if defined __i386__

		// Pass address of current input block.
		lea		(I, Blocks), t0
		mov		t0, 1*4(r4)

	#else

		// Pass arguments to subroutine.
		#define	PassedRounds	r1
		#define	PassedKey		r2
		#define	PassedInput		r6
		#define	PassedOutput	r7
		mov		Rounds,         PassedRounds
		mov		Key,            PassedKey
		lea		(I, Blocks),    PassedInput
		lea		LocalState(r4), PassedOutput

	#endif

	// Decrypt state.
	call	_AESDecryptWithExpandedKey

	// XOR decrypted block with previous chain value.
	movapd	LocalState(r4), vState0
	movupd	-16(I, Blocks), v0
	pxor	v0, vState0

	// Write to output.
	movupd	vState0, 0*4(O, Blocks)

	add		$-16, Blocks

	jg		1b
2:

/*	First block is separate because it gets chain value from ChainBuffer
	rather than from the input stream.
*/
	#if defined __i386__

		// Pass address of current input block.
		lea		(I, Blocks), t0
		mov		t0, 1*4(r4)

	#else

		// Pass arguments to subroutine.
		#define	PassedRounds	r1
		#define	PassedKey		r2
		#define	PassedInput		r6
		#define	PassedOutput	r7
		mov		Rounds,         PassedRounds
		mov		Key,            PassedKey
		lea		(I, Blocks),    PassedInput
		lea		LocalState(r4), PassedOutput

	#endif

	// Decrypt state.
	call	_AESDecryptWithExpandedKey

	// XOR decrypted block with previous chain value.
	movapd	LocalState(r4), vState0
	movupd	(ChainBuffer), v0
	pxor	v0, vState0

	// Write to output.
	movupd	vState0, 0*4(O, Blocks)

	// Save state for chaining in future calls.
	movapd	SavedChain(r4), v0
	movupd	v0, (ChainBuffer)

done:
	// Pop stack and restore registers.
	#if 0 < LocalsSize
		add		$LocalsSize, r4
	#endif
	#if defined __i386__
		pop		r7
		pop		r6
	#elif defined __x86_64__
		pop		r15
		pop		r14
		pop		r13
		pop		r12
	#endif
	pop		r3
	pop		r5

	ret


#endif	// defined UseAESedp_IntelAssembly
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































































































































































Deleted Source/AESedp/Intel/EncryptCBC.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#include "../AESAssembly.h"


// Generate object code only if this implementation has been requested.
#if defined UseAESedp_IntelAssembly


/*	AESEncryptCBC.s -- Encrypt blocks with AES in Cipher Block Chaining mode.

	Written by Eric Postpischil, January 24, 2008.
*/


/*	Define a macro to select a value based on architecture.  This reduces
	some of the architecture conditionalization later in the source.
*/
#if defined __i386__
	#define	Arch(i386, x86_64)	i386
#elif defined __x86_64__
	#define	Arch(i386, x86_64)	x86_64
#endif


/*	Rename the general registers.  This makes it easier to keep track of them
	and provides names for the "whole register" that are uniform between i386
	and x86_64.
*/
#if defined __i386__
	#define	r0	%eax	// Available for any use.
	#define	r1	%ecx	// Available for any use, some special purposes (loop).
	#define	r2	%edx	// Available for any use.
	#define	r3	%ebx	// Must be preserved by called routine.
	#define	r4	%esp	// Stack pointer.
	#define	r5	%ebp	// Frame pointer, must preserve, no bare indirect.
	#define	r6	%esi	// Must be preserved by called routine.
	#define	r7	%edi	// Must be preserved by called routine.
#elif defined __x86_64__
	#define	r0	%rax	// Available for any use.
	#define	r1	%rcx	// Available for any use.
	#define	r2	%rdx	// Available for any use.
	#define	r3	%rbx	// Must be preserved by called routine.
	#define	r4	%rsp	// Stack pointer.
	#define	r5	%rbp	// Frame pointer.  Must be preserved by called routine.
	#define	r6	%rsi	// Available for any use.
	#define	r7	%rdi	// Available for any use.
	#define	r8	%r8		// Available for any use.
	#define	r9	%r9		// Available for any use.
	#define	r10	%r10	// Available for any use.
	#define	r11	%r11	// Available for any use.
	#define	r12	%r12	// Must be preserved by called routine.
	#define	r13	%r13	// Must be preserved by called routine.
	#define	r14	%r14	// Must be preserved by called routine.
	#define	r15	%r15	// Must be preserved by called routine.
#else
	#error "Unknown architecture."
#endif


/*	Routine:

		_AESEncryptCBC.

	Function:

		This routine uses _AESEncryptWithExpandedKey to encrypt blocks in
		Cipher Block Chaining mode, which requires chaining the AES state
		from block to block.  In CBC mode, an initial block is XORed with the
		first input block, and then each output block is XORed with the next
		input block.

	Input:

		void *O				// Output
		const void *I		// Input
		void *ChainBuffer	// Chain buffer / initial value.
		void *Key			// Expanded Key.
		long Blocks			// Number of 16-byte blocks to process.
		long Rounds			// Number of rounds.

	Output:

		Encrypted text is written to *O.

		The final output block is written to *ChainBuffer.
*/
	.globl _AESEncryptCBC
	.private_extern	_AESEncryptCBC
_AESEncryptCBC:

	// Push new stack frame.
	push	r5

	// Save registers.
	push	r3
	#if defined __i386__
		push	r6
		push	r7
		#define	RegisterSaveSize	(3*4)
	#elif defined __x86_64__
		push	r12
		push	r13
		push	r14
		push	r15
		#define	RegisterSaveSize	(5*8)
	#endif

/*	B is the number of bytes from the top of stack just before the instruction
	that called this routine to the top of stack after we push the frame
	pointer and other registers.  It provides information needed to align our
	stack frame.
*/
#define	B	(RegisterSaveSize + 2*Arch(4, 8))

/*	Allocate space on the stack for 16 bytes for the AES state and, on i386,
	16 bytes for four four-byte arguments, and padding needed to produce
	16-byte alignment.
*/
#define	LocalsSize	((16 + Arch(16, 0) + B + 15 & -16) - B)
#define	StackFrame	(LocalsSize + B)

/*	LocalState is the offset from the stack pointer to where we store the AES
 	state.
*/
#define	LocalState	Arch(16, 0)

	#if 0 < LocalsSize
		sub		$LocalsSize, r4	// Allocate space on stack.
	#endif

// Non-volatile registers.
#define	I			r3
#define	O			r5
#define	Blocks		Arch(r6, r12)
#define	ChainBuffer	Arch(r7, r13)
#define	Rounds		Arch(Not used, r14)
#define	Key			Arch(Not used, r15)

// Volatile registers.
#define	t0			r0
#define	v0			%xmm0
#define	v1			%xmm1
#define	v2			%xmm2
#define	v3			%xmm3
#define	vState0		%xmm4
#define	vState1		%xmm5
#define	vState2		%xmm6
#define	vState3		%xmm7

// Arguments passed to us.
#if defined __i386__
	// Define location of argument i.
	#define	Argument(i)	StackFrame+4*(i)(r4)
#endif
#define	ArgO			Arch(Argument(0), r7)
#define	ArgI			Arch(Argument(1), r6)
#define	ArgChainBuffer	Arch(Argument(2), r2)
#define	ArgKey			Arch(Argument(3), r1)
#define	ArgBlocks		Arch(Argument(4), r8)
#define	ArgRounds		Arch(Argument(5), r9)

	/*	Get some arguments.  We need to move these from the stack (on i386)
		or volatile registers (on x86_64) to non-volatile registers where we
		can use them and keep them during calls to a subroutine.
	*/
	mov		ArgO, O
	mov		ArgI, I
	mov		ArgChainBuffer, ChainBuffer
	mov		ArgBlocks, Blocks

	// Read the initial value from the chain buffer.
	movd	0*4(ChainBuffer), vState0
	movd	1*4(ChainBuffer), vState1
	movd	2*4(ChainBuffer), vState2
	movd	3*4(ChainBuffer), vState3

	/*	Convert Blocks from number of blocks to displacement in bytes from
		end of input to current input location.  (We will increment it from
		iteration to iteration.  When it reaches zero, we are done.)
	*/
	imul	$-16, Blocks
	je		done	// Leave if we were given zero blocks.

	// Adjust input and output pointers to use ends as base addresses.
	sub		Blocks, I
	sub		Blocks, O

	#if defined __i386__

		// Put arguments we will pass on stack.
		mov		ArgRounds, t0
		mov		t0,    3*4(r4)

		mov		ArgKey, t0
		mov		t0,    2*4(r4)

		lea		LocalState(r4), t0
		mov		t0,    1*4(r4)
		mov		t0,    0*4(r4)

	#else

		// Put arguments we will pass into non-volatile registers.
		mov		ArgRounds, Rounds
		mov		ArgKey,    Key

	#endif

1:
	// Read next input block.
	movd	0*4(I, Blocks), v0
	movd	1*4(I, Blocks), v1
	movd	2*4(I, Blocks), v2
	movd	3*4(I, Blocks), v3

	// Chain block with state.
	pxor	v0, vState0
	pxor	v1, vState1
	pxor	v2, vState2
	pxor	v3, vState3

	// Store state for passing to encryption routine.
	movd	vState0, 0*4+LocalState(r4)
	movd	vState1, 1*4+LocalState(r4)
	movd	vState2, 2*4+LocalState(r4)
	movd	vState3, 3*4+LocalState(r4)

	#if defined __x86_64__

		// Pass arguments to subroutine.
		#define	PassedRounds	r1
		#define	PassedKey		r2
		#define	PassedInput		r6
		#define	PassedOutput	r7
		mov		Rounds,         PassedRounds
		mov		Key,            PassedKey
		lea		LocalState(r4), PassedInput
		lea		(O, Blocks),    PassedOutput

	#endif

	// Encrypt state.
	call	_AESEncryptWithExpandedKey

	#if defined __i386__

		// Get encrypted state.
		movd	0*4+LocalState(r4), vState0
		movd	1*4+LocalState(r4), vState1
		movd	2*4+LocalState(r4), vState2
		movd	3*4+LocalState(r4), vState3

		// Write to output.
		movd	vState0, 0*4(O, Blocks)
		movd	vState1, 1*4(O, Blocks)
		movd	vState2, 2*4(O, Blocks)
		movd	vState3, 3*4(O, Blocks)

	#else

		// Get output for chaining.
		movd	0*4(O, Blocks), vState0
		movd	1*4(O, Blocks), vState1
		movd	2*4(O, Blocks), vState2
		movd	3*4(O, Blocks), vState3

	#endif

	add		$16, Blocks

	jl		1b

	// Save state for chaining in future calls.
	movd	vState0, 0*4(ChainBuffer)
	movd	vState1, 1*4(ChainBuffer)
	movd	vState2, 2*4(ChainBuffer)
	movd	vState3, 3*4(ChainBuffer)

done:
	// Pop stack and restore registers.
	#if 0 < LocalsSize
		add		$LocalsSize, r4
	#endif
	#if defined __i386__
		pop		r7
		pop		r6
	#elif defined __x86_64__
		pop		r15
		pop		r14
		pop		r13
		pop		r12
	#endif
	pop		r3
	pop		r5

	ret


#endif	// defined UseAESedp_IntelAssembly
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































































































































































































































































































































































































































Deleted Source/AESedp/Intel/EncryptDecrypt.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/*	This file defines _AESEncryptWithExpandedKey or _AESDecryptWithExpandedKey,
	according to the value of the Select preprocessor symbol.  This file is
	designed to be included in another assembly file using the preprocessor
	#include directive, to benefit from some assembly-time calculations.

	These two routines are nearly identical.  They differ only in the tables
	they use, the direction they iterate through the key, and the permutation
	performed on part of the state.

	Written by Eric Postpischil, January 2008.
*/


#if Select == 0
	#define	Name		_AESEncryptWithExpandedKey	// Routine name.
	#define	MTable		_OLDAESEncryptTable			// Main table.
	#define	FTable		_OLDAESSubBytesWordTable		// Final table.
	#define	P0			S0							// State permutation.
	#define	P1			S1
	#define	P2			S2
	#define	P3			S3
	#define	Increment	+16							// ExpandedKey increment.
#elif Select == 1
	#define	Name		_AESDecryptWithExpandedKey	// Routine name.
	#define	MTable		_OLDAESDecryptTable			// Main table.
	#define	FTable		_OLDAESInvSubBytesWordTable	// Final table.
	#define	P0			S2							// State permutation.
	#define	P1			S3
	#define	P2			S0
	#define	P3			S1
	#define	Increment	-16							// ExpandedKey increment.
#endif	// Select


/*	Routine:

		_AESEncryptWithExpandedKey (if Select is 0) or
		_AESDecryptWithExpandedKey (if Select is 1).

	Function:

		Perform the AES cipher or its inverse as defined in Federal Information
		Processing Standards Publication 197 (FIPS-197), November 26, 2001.

		The inverse cipher here is the "Equivalent Inverse Cipher" in FIPS-197.

	Input:

		Constant data:
				
			For encryption:

				The following names must be locally defined so the assembler
				can calculate certain offsets.

				static const Word _OLDAESEncryptTable[4][256].

					_OLDAESEncryptTable[i] contains the tables T[i] defined in AES
					Proposal: Rijndael, version 2, 03/09/99, by Joan Daemen and
					Vincent Rijmen, section 5.2.1, page 18.  These tables
					combine the SubBytes and MixColumns operations.

				static const Word _OLDAESSubBytesWordTable[256].

					_OLDAESSubBytesWordTable[i][j] = SubBytes(j) << 8*i, where
					SubBytes is defined in FIPS-197.  _OLDAESSubBytesWordTable
					differs from _OLDAESEncryptTable in that it does not include
					the MixColumn operation.  It is used in performing the last
					round, which differs fromm the previous rounds in that it
					does not include the MixColumn operation.

			For decryption:

				static const Word _OLDAESDecryptTable[4][256].

					The analog of _OLDAESEncryptTable for decryption.

				static const Word _OLDAESSubBytesWordTable[256].

					_OLDAESInvSubBytesWordTable[i][j] = InvSubBytes(j) << 8*i,
					where InvSubBytes is defined in FIPS-197.
					_OLDAESInvSubBytesWordTable differs from _OLDAESDecryptTable in
					that it does not include the InvMixColumn operation.  It is
					used in performing the last round, which differs fromm the
					previous rounds in that it does not include the
					InvMixColumn operation.

		Arguments:

			Byte *OutputText.

				Address of output, 16 bytes.  Best if four-byte aligned.

			const Byte *InputText.

				Address of input, 16 bytes.  Best if four-byte aligned.

			const Byte *ExpandedKey.

				Address of expanded key, which has 4 * (Nr+1) bytes.  Best if
				four-byte aligned.

			int Nr

				Number of rounds.

	Output:

		Encrypted or decrypted data is written to *OutputText.
*/
	.globl Name
	.private_extern	Name
Name:

	// Push new stack frame.
	push	r5

	// Save registers and set RegisterSave size to the number of bytes used.
	push	r3
	#if defined __i386__
		push	r6
		push	r7
		#define	RegisterSaveSize	(3*4)
	#elif defined __x86_64__
		#define	RegisterSaveSize	(1*8)
	#endif

#define	LocalsSize	Arch(4, 0)	// Number of bytes used for local variables.

	#if 0 < LocalsSize
		sub		$LocalsSize, r4	// Allocate space on stack.
	#endif

// Number of bytes from the stack pointer to the return address.
#define	StackFrame	(LocalsSize+RegisterSaveSize)

#if defined __i386__

	// Define location of argument i (presuming 4-byte arguments).
	#define	Argument(i)	StackFrame+8+4*(i)(%esp)

	#define	ArgOutputText	Argument(0)
	#define	ArgInputText	Argument(1)
	#define	ArgExpandedKey	Argument(2)
	#define	ArgNr			Argument(3)

#elif defined __x86_64__

	// Arguments.
	#define	OutputText		r7	// Needed near end of routine.
	#define	InputText		r6	// Used early then overwritten for other use.
	#define	ArgExpandedKey	r2
	#define	ArgNr			r1
		/*	The arguments passed in r1 and r2 overlaps registers we need for
		 	other work, so they must be moved early in the routine.
		*/

#endif

#define	BaseP		Arch(r7, r9)	// Base pointer for addressing global data.
#define	ExpandedKey	Arch(t0, r10)	// Address of expanded key.

/*	The Work registers defined below are used to hold parts of the AES state
	while we dissect or assemble it.  They must be assigned to the A, B, C, and
	D registers so that we can access the bytes in %al, %ah, and so on.
*/
#define	Work0d	r0d
#define	Work0l	r0l
#define	Work0h	r0h
#define	Work1d	r3d
#define	Work1l	r3l
#define	Work1h	r3h
#define	Work2d	r1d
#define	Work2l	r1l
#define	Work2h	r1h
#define	Work3d	r2d
#define	Work3l	r2l
#define	Work3h	r2h

#define	t0		r5
#define	t0d		r5d		// Low 32 bits of t0.
#define	t0l		r5l		// Low byte of t0.

#define	t1		r6

/*	S0, S1, S2, and S3 are where we assemble the new AES state when computing
	a regular round.  S1, S2, and S3 are assigned to the Work registers, but
	S0 needs to go somewhere else because Work0 holds part of the old state.
*/
#define	S0		Arch(t1, r8d)
#define	S1		Work1d
#define	S2		Work2d
#define	S3		Work3d

/*	These XMM registers are used as holding space, because it is faster to
	spill to these registers than to the stack.  (On x86_64, we do not need
	to spill, because there are additional general registers available.
	However, using more general registers requires saving them to the stack
	and restoring them.  I timed it, and no time was saved.)
*/
#define	vS1		%xmm1
#define	vS2		%xmm2
#define	vS3		%xmm3
#if defined __i386__
	#define	vExpandedKey	%xmm4
	#define	vIncrement		%xmm5
#endif

	// Get argument.
	mov	ArgExpandedKey, ExpandedKey

// Store sentinel value of ExpandedKey on stack on i386, a register on x86_64.
#define	ExpandedKeyEnd	Arch((r4), r11)

	/*	Convert ArgNr from rounds to number of bytes to move through expanded
		key to get to (but not beyond) last 16-byte block.
	*/
	mov		ArgNr, r0
	shl		$4, r0

	#if Select == 0
		// For encryption, prepare to iterate forward through expanded key.
		add		ExpandedKey, r0
		mov		r0, ExpandedKeyEnd
	#else
		// For decryption, prepare to iterate backward through expanded key.
		mov		ExpandedKey, ExpandedKeyEnd
		add		r0, ExpandedKey
	#endif

	// Initialize State from input text.
	#if defined __i386__
		mov		ArgInputText, BaseP
		#define	InputText	BaseP
	#endif
	mov		0*4(InputText), Work0d
	mov		1*4(InputText), S1
	mov		2*4(InputText), S2
	mov		3*4(InputText), S3
#undef	InputText	// Register is reused after this for other purposes.

	// Add round key and save results.
	xor		0*4(ExpandedKey), Work0d	// S0 is in dissection register.
	xor		1*4(ExpandedKey), S1
	movd	S1, vS1						// Save S1 to S3 in vector registers.
	xor		2*4(ExpandedKey), S2
	movd	S2, vS2
	xor		3*4(ExpandedKey), S3
	movd	S3, vS3

	add		$Increment, ExpandedKey		 // Advance to next round key.

	#if defined __i386__
		// Save expanded key address and increment in vector registers.
		mov		$Increment, t1
		movp	ExpandedKey, vExpandedKey
		movp	t1, vIncrement
	#endif

	// Set up relative addressing.
	#if defined __i386__

		// Get address of 0 in BaseP.
			call	0f				// Push program counter onto stack.
		0:
			pop		BaseP			// Get program counter.

		// Define macros to help address data.
#define	LookupM(table, index)	MTable-0b+(table)*TableSize(BaseP, index, 4)
#define LookupF(table, index)	FTable-0b+(table)*TableSize(BaseP, index, 4)

	#elif defined __x86_64__

		lea	MTable(%rip), BaseP

		// Define macros to help address data.
		#define	LookupM(table, index)	(table)*TableSize(BaseP, index, 4)
		#define	LookupF(table, index)	(table)*TableSize(BaseP, index, 4)

/*	With these definitions of LookupM and LookupF, BaseP must be loaded with
	the address of the table at the point where it is used.  So we need an
	instruction to change BaseP after we are done with MTable and before we
	start using FTable.  I would prefer to use something like:

		.set	FMinusM, FTable - MTable
		#define LookupF(table, index)	\
			FMinusM+(table)*TableSize(BaseP, index, 4)

	Then BaseP would not need to change.  However, this fails due to an
	assembler/linker bug, <rdar://problem/5683882>.
*/

	#endif

	// Get round key.
	mov		0*4(ExpandedKey), S0
	mov		1*4(ExpandedKey), S1
	mov		2*4(ExpandedKey), S2
	mov		3*4(ExpandedKey), S3

1:
	/*	Word 0 of the current state must be in Work0 now, and the next round
		key must be in S0 to S3.
	*/

	// Process previous S0.
	movzx	Work0l, t0
	xor		LookupM(0, t0), S0
	movzx	Work0h, t0d
	xor		LookupM(1, t0), P3
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupM(2, t0), S2
	movzx	Work0h, t0d
	xor		LookupM(3, t0), P1

	// Process previous S1.
	movd	vS1, Work0d
	movzx	Work0l, t0d
	xor		LookupM(0, t0), S1
	movzx	Work0h, t0d
	xor		LookupM(1, t0), P0
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupM(2, t0), S3
	movzx	Work0h, t0d
	xor		LookupM(3, t0), P2

	// Process previous S2.
	movd	vS2, Work0d
	movzx	Work0l, t0d
	xor		LookupM(0, t0), S2
	movzx	Work0h, t0d
	xor		LookupM(1, t0), P1
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupM(2, t0), S0
	movzx	Work0h, t0d
	xor		LookupM(3, t0), P3

	// Process previous S3.
	movd	vS3, Work0d
	movzx	Work0l, t0d
	xor		LookupM(0, t0), S3
	movzx	Work0h, t0d
	xor		LookupM(1, t0), P2
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupM(2, t0), S1
	movzx	Work0h, t0d
	xor		LookupM(3, t0), P0

	#if defined __i386__
		paddd	vIncrement, vExpandedKey
		movp	vExpandedKey, ExpandedKey
	#else
		add		$Increment, ExpandedKey
	#endif

	// Save state for next iteration and load next round key.
	mov		S0, Work0d
	mov		0*4(ExpandedKey), S0
	movd	S1, vS1
	mov		1*4(ExpandedKey), S1
	movd	S2, vS2
	mov		2*4(ExpandedKey), S2
	movd	S3, vS3
	mov		3*4(ExpandedKey), S3

	cmp		ExpandedKeyEnd, ExpandedKey
	jne		1b

	/*	Word 0 of the current state must be in Work0 now, and the next round
		key must be in S0 to S3.
	*/

	// Work around assembler bug.  See comments above about Radar 5683882.
	#if defined __x86_64__
		lea	FTable(%rip), BaseP
	#endif

	// Process previous S0.
	movzx	Work0l, t0
	xor		LookupF(0, t0), S0
	movzx	Work0h, t0d
	xor		LookupF(1, t0), P3
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupF(2, t0), S2
	movzx	Work0h, t0d
	xor		LookupF(3, t0), P1

	// Process previous S1.
	movd	vS1, Work0d
	movzx	Work0l, t0d
	xor		LookupF(0, t0), S1
	movzx	Work0h, t0d
	xor		LookupF(1, t0), P0
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupF(2, t0), S3
	movzx	Work0h, t0d
	xor		LookupF(3, t0), P2

	// Process previous S2.
	movd	vS2, Work0d
	movzx	Work0l, t0d
	xor		LookupF(0, t0), S2
	movzx	Work0h, t0d
	xor		LookupF(1, t0), P1
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupF(2, t0), S0
	movzx	Work0h, t0d
	xor		LookupF(3, t0), P3

	// Process previous S3.
	movd	vS3, Work0d
	movzx	Work0l, t0d
	xor		LookupF(0, t0), S3
	movzx	Work0h, t0d
	xor		LookupF(1, t0), P2
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupF(2, t0), S1
	movzx	Work0h, t0d
	xor		LookupF(3, t0), P0

	#if defined __i386__	// Architecture.
		// Get OutputText address.
		#define	OutputText	BaseP
		mov		ArgOutputText, OutputText
	#endif	// Architecture.

	// Write output.
	mov		S0, 0*4(OutputText)
	mov		S1, 1*4(OutputText)
	mov		S2, 2*4(OutputText)
	mov		S3, 3*4(OutputText)

	// Pop stack and restore registers.
	#if 0 < LocalsSize
		add		$LocalsSize, r4
	#endif
	#if defined __i386__
		pop		r7
		pop		r6
	#elif defined __x86_64__
	#endif
	pop		r3
	pop		r5

	ret


#undef	ArgExpandedKey
#undef	ArgInputText
#undef	ArgNr
#undef	ArgOutputText
#undef	Argument
#undef	BaseP
#undef	ExpandedKey
#undef	ExpandedKeyEnd
#undef	FTable
#undef	InputText
#undef	LocalsSize
#undef	LookupM
#undef	LookupF
#undef	MTable
#undef	OutputText
#undef	RegisterSaveSize
#undef	S0
#undef	S1
#undef	S2
#undef	S3
#undef	StackFrame
#undef	Work0d
#undef	Work0h
#undef	Work0l
#undef	Work1d
#undef	Work1h
#undef	Work1l
#undef	Work2d
#undef	Work2h
#undef	Work2l
#undef	Work3d
#undef	Work3h
#undef	Work3l
#undef	t0
#undef	t0d
#undef	t0l
#undef	t1
#undef	vExpandedKey
#undef	vS1
#undef	vS2
#undef	vS3

#undef	Name
#undef	MTable
#undef	FTable
#undef	P0
#undef	P1
#undef	P2
#undef	P3
#undef	Increment
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/AESedp/Intel/ExpandKeyForDecryption.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
/*	This file defines _AESExpandKeyForDecryption.  It is designed to be
	included in another assembly file with the preprocessor #include directive,
	to benefit from some assembly-time calculations.

	Written by Eric Postpischil, January 2008.

	The comments here do not say much about the algorithm; the code just
	follows the FIPS-197 specification.  I recommend reading the specification
	before working with this code or examining the C code in the parent
	directory that illustrates key expansion.

	One complication is that this routine both expands the key and applies
	InvMixColumn to most of the words in the expanded key.  This modifies the
	key for use with the Equivalent Inverse Cipher.

	During key expansion, there are sequences of four or six words that are
	produced like this:

		E[i+0] = E[i+0-Nk] ^ f(E[i-1]), where f is some function.
		E[i+1] = E[i+1-Nk] ^ E[i+0].
		E[i+2] = E[i+2-Nk] ^ E[i+1].
		E[i+3] = E[i+3-Nk] ^ E[i+2].

	When Nk is four or eight, the sequence stops there.  When it is six, it
	goes on for two more words.  Let I be the InvMixColumn function.  for the
	Equivalent Inverse Cipher, we want to store I(E[i+0]), I(E[i+1]),
	I(E[i+2]), I(E[i+3]) (and two more when Nk is six).  However, we do not
	need to calculate I four times.  In AES' finite field, I is a linear
	combination of the four bytes of its input.  The ^ operation on the bits
	that represent field elements is an addition in the Galois field.  So
	I(a ^ b) = I(a) ^ I(b).  Then we have:

		I(E[i+0]) = I(E[i+0-Nk] ^ f(E[i-1])) = I(E[i+0-Nk]) ^ I(f(E[i-1])).
		I(E[i+1]) = I(E[i+1-Nk]) ^ I(E[i+0]).
		I(E[i+2]) = I(E[i+2-Nk]) ^ I(E[i+1]).
		I(E[i+3]) = I(E[i+3-Nk]) ^ I(E[i+2]).

	To compute this, we compute I(f(E[i-1])) and XOR it with the previously
	stored E[i+0-Nk])) to get I(E[i+0])).  Then we XOR that with the previously
	stored E[i+1-Nk])) to get I(E[i+1])), and so on.

	Note that to compute I(f(E[i-1])), we need to have E[i-1].  So we have to
	compute the pre-InvMixColumn words of the expanded key; it is not
	sufficient to have the post-InvMixColumn words.
*/


/*	Routine:

		_AESExpandKeyForDecryption.

	Function:

		Expand the user's cipher key into the key schedule, as defined in
		Federal Information Processing Standards Publication 197 (FIPS-197),
		November 26, 2001.

		For decryption, the key is modified as shown in Figure 15 in FIPS-197,
		to support the Equivalent Inverse Cipher.

	Input:

		Constant data:

			The following names must be locally defined so the assembler
			can calculate certain offsets.

			static const Word _OLDAESSubBytesWordTable[4][256].

				_OLDAESSubBytesWordTable[i][j] = SubBytes(j) << 8*i, where
				SubBytes is defined in FIPS-197.  _OLDAESSubBytesWordTable
				differs from _OLDAESEncryptTable in that it does not include
				the MixColumn operation.  It is used in performing the last
				round, which differs fromm the previous rounds in that it
				does not include the MixColumn operation.

			static const Word _AESSInvMixColumnTable[4][256].

				_OLDAESInvMixColumnTable[i][j] contains the contribution of byte
				j to element i of the InvMixColumn operation.

				The four bytes of the word _OLDAESInvMixColumnTable[0][j] are:

					{0xe}*{j}, {0x9}*{j}, {0xd}*{j}, {0xb}*{j},

				listed in increasing address order, where multiplication is
				performed in the Galois field.  {j} designates the element of
				the Galois field represented by j.  _AESInvMixColumn[i][j] has
				the same bytes, rotated right in the order shown above.

			static const Byte _OLDAESRcon[].

				Round constants, beginning with OLDAESRcon[1] for the first round
				(OLDAESRcon[0] is padding.)
	
		Arguments:

			Word *ExpandedKey

				Address of output.

			const AESKey *Key

				Address of user's cipher key.

			long Nk

				Number of four-byte words in user's cipher key.

	Output:

		The expanded key is written to *ExpandedKey.
*/

#define	dr		r0d				// Dissection register.
#define	drl		r0l				// Low 8 bits of dissection register.
#define	drh		r0h				// Second-lowest 8 bits of dissection register.

#define	t0		r1
#define	t0d		r1d				// Low 32 bits of t0.

#define	STable	r2				// Address of SubBytes table.  Overlaps Nk.
#define	ITable	r3				// Address of InvMixColumn table.
#define	offset	r5				// Address offset and loop sentinel.

#define	R		r6				// Address of round constant.
#define	K		r6				// User key pointer, second x86_64 argument.
	// R and K overlap.

#define	E		r7				// Expanded key pointer, first x86_64 argument.

#define	ve0		%xmm0
#define	ve1		%xmm1
#define	ve2		%xmm2
#define	ve3		%xmm3
#define	ve4		%xmm4
#define	ve5		%xmm5
#define	vt1		%xmm6
#define	vt0		%xmm7

#define	LookupS(table, index)	(table)*TableSize(STable, index, 4)
#define	LookupI(table, index)	(table)*TableSize(ITable, index, 4)


/*	InvMixColumn puts InvMixColumn(dr) into vt0.  This is a non-standard
	subroutine.  It does not conform to the ABI.  It is an integral part of
	_ExpandKeyForDecryption and shares register use with it.
*/
InvMixColumn:
	movzx	drl, t0
	movd	LookupI(0, t0), vt0		// Look up byte 0 in table 0.
	movzx	drh, t0d
	movd	LookupI(1, t0), vt1		// Look up byte 1 in table 1.
	pxor	vt1, vt0
	shr		$16, dr
	movzx	drl, t0d
	movd	LookupI(2, t0), vt1		// Look up byte 2 in table 2.
	pxor	vt1, vt0
	movzx	drh, t0d
	movd	LookupI(3, t0), vt1		// Look up byte 3 in table 3.
	pxor	vt1, vt0
	ret


	// SubWordRotWord adds (XORs) SubWord(RotWord(dr)) to vt0.
	.macro	SubWordRotWord
		movzx	drl, t0
		movd	LookupS(3, t0), vt1		// Look up byte 0 in table 3.
		pxor	vt1, vt0
		movzx	drh, t0d
		movd	LookupS(0, t0), vt1		// Look up byte 1 in table 0.
		pxor	vt1, vt0
		shr		$$16, dr
		movzx	drl, t0d
		movd	LookupS(1, t0), vt1		// Look up byte 2 in table 1.
		pxor	vt1, vt0
		movzx	drh, t0d
		movd	LookupS(2, t0), vt1		// Look up byte 3 in table 2.
		pxor	vt1, vt0
	.endmacro


	// SubWord puts SubWord(dr) into vt0.
	.macro	SubWord
		movzx	drl, t0
		movd	LookupS(0, t0), vt0		// Look up byte 0 in table 0.
		movzx	drh, t0d
		movd	LookupS(1, t0), vt1		// Look up byte 1 in table 1.
		pxor	vt1,vt0
		shr		$$16, dr
		movzx	drl, t0d
		movd	LookupS(2, t0), vt1		// Look up byte 2 in table 2.
		pxor	vt1,vt0
		movzx	drh, t0d
		movd	LookupS(3, t0), vt1		// Look up byte 3 in table 3.
		pxor	vt1,vt0
	.endmacro


	.globl _AESExpandKeyForDecryption
	.private_extern	_AESExpandKeyForDecryption
_AESExpandKeyForDecryption:

	// Push new stack frame.
	push	r5

	// Save registers.
	push	r3
	#if defined __i386__
		push	r6
		push	r7
		#define	RegisterSaveSize	(3*4)
	#elif defined __x86_64__
		#define	RegisterSaveSize	(1*8)
		// Add pushes of r12 to r15 if used.
	#endif

#define	LocalsSize	0
#define	StackFrame	(LocalsSize+RegisterSaveSize)
	// Locals plus the registers we pushed after the new stack frame.

/*	Define stack offset to storage space for local data.  This is in the red
	zone.  We point far enough down to allow space for eight four-byte words
	plus a return address (4 or 8 bytes on i386 or x86_64) for our internal
	subroutine calls.
*/
#define	Local	(-8*4-8)

#if defined __i386__

	// Define location of argument i.
	#define	Argument(i)	StackFrame+8+4*(i)(r4)

	// Load arguments.
	mov		Argument(0), E
	mov		Argument(1), K
	#define	Nk	Argument(2)

#elif defined __x86_64__

	#define	Nk		r2			// Number of words in key.  Overlaps STable.

#endif

	cmp		$6,	 Nk

	#if 0 < LocalsSize
		sub		$LocalsSize, r4	// Allocate space on stack.
	#endif

	// First words of expanded key are copied from user key.
	movd	0*4(K), ve0
	movd	1*4(K), ve1
	movd	2*4(K), ve2
	movd	3*4(K), ve3
	je		DKeyHas6Words
	jg		DKeyHas8Words
	// Fall through to DKeyHas4Words.

DKeyHas4Words:

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__
		// Get address of 0 in R.
			call	0f			// Push program counter onto stack.
		0:
			pop		STable		// Get program counter.

		lea		_OLDAESRcon-0b(STable), R
		lea		_OLDAESInvMixColumnTable-0b(STable), ITable
		lea		_OLDAESSubBytesWordTable-0b(STable), STable

	#elif defined __x86_64__

		lea		_OLDAESRcon(%rip), R
		lea		_OLDAESInvMixColumnTable(%rip), ITable
		lea		_OLDAESSubBytesWordTable(%rip), STable

	#endif

	/*	With a four-word key, there are ten rounds (eleven 16-byte key blocks),
		nine of which have InvMixColumn applied.
	*/
	mov		$-9*4*4, offset
	sub		offset, E

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E, offset)
	movd	ve1, 1*4(E, offset)
	movd	ve2, 2*4(E, offset)
	movd	ve3, 3*4(E, offset)

/*	Here is the first iteration of the key expansion.  It is separate from the
	main loop below because we need to apply InvMixColumn to each of the
	outputs, in ve0 through ve3.  In the main loop, the technique described at
	the top of this file is used to compute the proper outputs while using
	InvMixColumn only once.
*/
	add		$1, R					// Advance pointer.
	movd	ve3, dr					// Put previous word into work register.
	movzx	(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	pxor	ve0, ve1
	pxor	ve1, ve2
	pxor	ve2, ve3

	add		$4*4, offset

	/*	Apply InvMixColumn to each word.  The transformed values are stored in
		the expanded key.  The original values are retained in registers for
		further computation.
	*/
	movd	ve0, dr
	call	InvMixColumn
	movd	vt0, 0*4(E, offset)

	movd	ve1, dr
	call	InvMixColumn
	movd	vt0, 1*4(E, offset)

	movd	ve2, dr
	call	InvMixColumn
	movd	vt0, 2*4(E, offset)

	movd	ve3, dr
	call	InvMixColumn
	movd	vt0, 3*4(E, offset)

//	Here is the main loop.
1:
	add		$1, R					// Advance pointer.
	movd	ve3, dr					// Put previous word into work register.
	movzx	(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	pxor	ve0, ve1
	pxor	ve1, ve2
	pxor	ve2, ve3
		/*	Dr. Brian Gladman uses a technique with a single XOR here instead
			of the previous four.  There is some periodic behavior in the key
			expansion, and Gladman maintains E[4*i+3] for the latest four
			values of i.  XORing the value in vt0 with one of these yields its
			replacement.  However, using this technique requires additional
			instructions before the loop (to initialize the values) and after
			it (to extract the final values to be stored) and either some way
			to rotate or index four values in the loop or a four-fold unrolling
			of the loop to provide the indexing.  Experiment suggests the
			former is not worthwhile.  Unrolling the loop might give a small
			gain, at the cost of increased use of instruction cache, increased
			instructions loads the first time the routine is executed, and
			increased code complexity, so I decided against it.
		*/

	// Apply InvMixColumn to the difference.
	movd	vt0, dr
	call	InvMixColumn

	add		$4*4, offset

	// Chain the transformed difference to previously transformed outputs.
	movd	(0-4)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 0*4(E, offset)

	movd	(1-4)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 1*4(E, offset)

	movd	(2-4)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 2*4(E, offset)

	movd	(3-4)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 3*4(E, offset)

	jl		1b

// Here is the final iteration, which does not perform InvMixColumn.

	movd	ve3, dr					// Put previous word into work register.
	movzx	1(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	movd	ve0, 4*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 5*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 6*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 7*4(E, offset)

	// Pop stack and restore registers.
	#if 0 < LocalsSize
		add		$LocalsSize, r4
	#endif
	#if defined __i386__
		// Add pops of r15 to r12 if used.
		pop		r7
		pop		r6
	#elif defined __x86_64__
	#endif
	pop		r3
	pop		r5

	ret


DKeyHas6Words:
	movd	4*4(K), ve4
	movd	5*4(K), ve5

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__
		// Get address of 0 in R.
			call	0f			// Push program counter onto stack.
		0:
			pop		STable		// Get program counter.

		lea		_OLDAESRcon-0b(STable), R
		lea		_OLDAESInvMixColumnTable-0b(STable), ITable
		lea		_OLDAESSubBytesWordTable-0b(STable), STable

	#elif defined __x86_64__

		lea		_OLDAESRcon(%rip), R
		lea		_OLDAESInvMixColumnTable(%rip), ITable
		lea		_OLDAESSubBytesWordTable(%rip), STable

	#endif

	/*	With a six-word key, there are twelve rounds (thirteen 16-byte key
		blocks), eleven of which have InvMixColumn applied.  The key expansion
		proceeds in iterations of six four-byte words, so the termination
		condition is a bit complicated.  We set offset to the negative of 10
		four four-byte words, and the loop branch does another iteration if
		offset is less than or equal to zero, meaning the number of iterations
		performed so far is less than or equal to 10.  Thus, after ten
		iterations, it branches again.  After the eleventh iteration, it
		stops.  Code after the end of the loop computes the twelfth key block,
		which does not have InvMixColumn applied.
	*/
	mov		$-10*4*4, offset
	sub		offset, E

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E, offset)
	movd	ve1, 1*4(E, offset)
	movd	ve2, 2*4(E, offset)
	movd	ve3, 3*4(E, offset)

	/*	The first four words are stored untransformed.  After that, words in
		the expanded key are transformed by InvMixColumn.
	*/
	movd	ve4, dr
	call	InvMixColumn
	movd	vt0, 4*4(E, offset)

	movd	ve5, dr
	call	InvMixColumn
	movd	vt0, 5*4(E, offset)

/*	Here is the first iteration of the key expansion.  It is separate from the
	main loop below because we need to apply InvMixColumn to each of the
	outputs, in ve0 through ve5.  In the main loop, the technique described at
	the top of this file is used to compute the proper outputs while using
	InvMixColumn only once.
*/
	add		$1, R					// Advance pointer.
	movd	ve5, dr					// Put previous word into work register.
	movzx	(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	pxor	ve0, ve1
	pxor	ve1, ve2
	pxor	ve2, ve3
	pxor	ve3, ve4
	pxor	ve4, ve5

	add		$6*4, offset

	/*	Apply InvMixColumn to each word.  The transformed values are stored in
		the expanded key.  The original values are retained in registers for
		further computation.
	*/
	movd	ve0, dr
	call	InvMixColumn
	movd	vt0, 0*4(E, offset)

	movd	ve1, dr
	call	InvMixColumn
	movd	vt0, 1*4(E, offset)

	movd	ve2, dr
	call	InvMixColumn
	movd	vt0, 2*4(E, offset)

	movd	ve3, dr
	call	InvMixColumn
	movd	vt0, 3*4(E, offset)

	movd	(4-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 4*4(E, offset)

	movd	(5-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 5*4(E, offset)

//	Here is the main loop.
1:
	add		$1, R					// Advance pointer.
	movd	ve5, dr					// Put previous word into work register.
	movzx	(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	pxor	ve0, ve1
	pxor	ve1, ve2
	pxor	ve2, ve3
	pxor	ve3, ve4
	pxor	ve4, ve5

	// Apply InvMixColumn to the difference.
	movd	vt0, dr
	call	InvMixColumn

	add		$6*4, offset

	// Chain the transformed difference to previously transformed outputs.
	movd	(0-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 0*4(E, offset)

	movd	(1-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 1*4(E, offset)

	movd	(2-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 2*4(E, offset)

	movd	(3-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 3*4(E, offset)

	movd	(4-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 4*4(E, offset)

	movd	(5-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 5*4(E, offset)

	jle		1b

// Here is the final iteration, which does not perform InvMixColumn.

	movd	ve5, dr					// Put previous word into work register.
	movzx	1(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	movd	ve0, 6*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 7*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 8*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 9*4(E, offset)

	// Pop stack and restore registers.
	#if 0 < LocalsSize
		add		$LocalsSize, r4
	#endif
	#if defined __i386__
		// Add pops of r15 to r12 if used.
		pop		r7
		pop		r6
	#elif defined __x86_64__
	#endif
	pop		r3
	pop		r5

	ret


DKeyHas8Words:

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E)
	movd	ve1, 1*4(E)
	movd	ve2, 2*4(E)
	movd	ve3, 3*4(E)
	movd	4*4(K), ve0
	movd	5*4(K), ve1
	movd	6*4(K), ve2
	movd	7*4(K), ve3

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__
		// Get address of 0 in R.
			call	0f			// Push program counter onto stack.
		0:
			pop		STable		// Get program counter.

		lea		_OLDAESRcon-0b(STable), R
		lea		_OLDAESInvMixColumnTable-0b(STable), ITable
		lea		_OLDAESSubBytesWordTable-0b(STable), STable

	#elif defined __x86_64__

		lea		_OLDAESRcon(%rip), R
		lea		_OLDAESInvMixColumnTable(%rip), ITable
		lea		_OLDAESSubBytesWordTable(%rip), STable

	#endif

	/*	With an eight-word key, there are fourteen rounds (fifteen 16-byte key
		blocks), thirteen of which have InvMixColumn applied.
	*/
	mov		$-12*4*4, offset
	sub		offset, E

	// Save untransformed values in stack area.
	movd	ve0, 4*4+Local(r4)
	movd	ve1, 5*4+Local(r4)
	movd	ve2, 6*4+Local(r4)
	movd	ve3, 7*4+Local(r4)

	/*	Apply InvMixColumn to words 4 through 7.  The transformed values are
		stored in the expanded key.  The original values are saved in the stack
		area for further computation.
	*/
	movd	ve0, dr
	call	InvMixColumn
	movd	vt0, 4*4(E, offset)

	movd	ve1, dr
	call	InvMixColumn
	movd	vt0, 5*4(E, offset)

	movd	ve2, dr
	call	InvMixColumn
	movd	vt0, 6*4(E, offset)

	movd	ve3, dr
	call	InvMixColumn
	movd	vt0, 7*4(E, offset)

/*	Here is the first iteration of the key expansion.  It is separate from the
	main loop below because we need to apply InvMixColumn to each of the
	outputs, in ve0 through ve3.  In the main loop, the technique described at
	the top of this file is used to compute the proper outputs while using
	InvMixColumn only once.
*/
	add		$1, R					// Advance pointer.
	movd	ve3, dr					// Put previous word into work register.
	movzx	(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord

	add		$8*4, offset

	movd	(0-8)*4(E, offset), ve0		// Get old word.
	pxor	vt0, ve0
	movd	ve0, 0*4+Local(r4)			// Save on stack.
	movd	ve0, dr
	call	InvMixColumn
	movd	vt0, 0*4(E, offset)			// Write to expanded key.

	/*	 Chain to successive words and apply InvMixColumn to each word.  The
		 transformed values are stored in the expanded key.  The original
		 values are retained in local data for further computation.
	*/
	movd	(1-8)*4(E, offset), ve1		// Get old word.
	pxor	ve0, ve1					// Chain.
	movd	ve1, 1*4+Local(r4)			// Save on stack.
	movd	ve1, dr
	call	InvMixColumn
	movd	vt0, 1*4(E, offset)			// Write to expanded key.

	movd	(2-8)*4(E, offset), ve2		// Get old word.
	pxor	ve1, ve2					// Chain.
	movd	ve2, 2*4+Local(r4)			// Save on stack.
	movd	ve2, dr
	call	InvMixColumn
	movd	vt0, 2*4(E, offset)			// Write to expanded key.

	movd	(3-8)*4(E, offset), ve3		// Get old word.
	pxor	ve2, ve3					// Chain.
	movd	ve3, 3*4+Local(r4)			// Save on stack.
	movd	ve3, dr
	call	InvMixColumn
	movd	vt0, 3*4(E, offset)			// Write to expanded key.

	movd	ve3, dr						// Put previous word into work register.
	SubWord

	movd	4*4+Local(r4), ve0			// Get old word.
	pxor	vt0, ve0					// Chain.
	movd	ve0, 4*4+Local(r4)			// Save on stack.

	movd	5*4+Local(r4), ve1			// Get old word.
	pxor	ve0, ve1					// Chain.
	movd	ve1, 5*4+Local(r4)			// Save on stack.

	movd	6*4+Local(r4), ve2			// Get old word.
	pxor	ve1, ve2					// Chain.
	movd	ve2, 6*4+Local(r4)			// Save on stack.

	movd	7*4+Local(r4), ve3			// Get old word.
	pxor	ve2, ve3					// Chain.
	movd	ve3, 7*4+Local(r4)			// Save on stack.

	movd	vt0, dr						// Move change to work register.
	call	InvMixColumn

	movd	(4-8)*4(E, offset), vt1		// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, 4*4(E, offset)			// Write new word to expanded key.

	movd	(5-8)*4(E, offset), vt1		// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, 5*4(E, offset)			// Write new word to expanded key.

	movd	(6-8)*4(E, offset), vt1		// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, 6*4(E, offset)			// Write new word to expanded key.

	movd	(7-8)*4(E, offset), vt1		// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, 7*4(E, offset)			// Write new word to expanded key.

//	Here is the main loop.
1:
	add		$1, R						// Advance pointer.
	movd	ve3, dr						// Put previous word into work register.
	movzx	(R), t0d					// Get round constant.
	movd	t0d, vt0

	SubWordRotWord

	movd	0*4+Local(r4), ve0			// Get old word.
	pxor	vt0, ve0
	movd	ve0, 0*4+Local(r4)			// Save on stack.

	// Chain to successive words.
	movd	1*4+Local(r4), ve1			// Get old word.
	pxor	ve0, ve1					// Chain.
	movd	ve1, 1*4+Local(r4)			// Save on stack.

	movd	2*4+Local(r4), ve2			// Get old word.
	pxor	ve1, ve2					// Chain.
	movd	ve2, 2*4+Local(r4)			// Save on stack.

	movd	3*4+Local(r4), ve3			// Get old word.
	pxor	ve2, ve3					// Chain.
	movd	ve3, 3*4+Local(r4)			// Save on stack.

	movd	vt0, dr						// Move change to work register.
	call	InvMixColumn

	movd	0*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (0+8)*4(E, offset)		// Write new word to expanded key.

	movd	1*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (1+8)*4(E, offset)		// Write new word to expanded key.

	movd	2*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (2+8)*4(E, offset)		// Write new word to expanded key.

	movd	3*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (3+8)*4(E, offset)		// Write new word to expanded key.

	movd	ve3, dr						// Put previous word into work register.
	SubWord

	movd	4*4+Local(r4), ve0			// Get old word.
	pxor	vt0, ve0					// Chain.
	movd	ve0, 4*4+Local(r4)			// Save on stack.

	movd	5*4+Local(r4), ve1			// Get old word.
	pxor	ve0, ve1					// Chain.
	movd	ve1, 5*4+Local(r4)			// Save on stack.

	movd	6*4+Local(r4), ve2			// Get old word.
	pxor	ve1, ve2					// Chain.
	movd	ve2, 6*4+Local(r4)			// Save on stack.

	movd	7*4+Local(r4), ve3			// Get old word.
	pxor	ve2, ve3					// Chain.
	movd	ve3, 7*4+Local(r4)			// Save on stack.

	movd	vt0, dr						// Move change to work register.
	call	InvMixColumn

	movd	4*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (4+8)*4(E, offset)		// Write new word to expanded key.

	movd	5*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (5+8)*4(E, offset)		// Write new word to expanded key.

	movd	6*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (6+8)*4(E, offset)		// Write new word to expanded key.

	movd	7*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (7+8)*4(E, offset)		// Write new word to expanded key.

	add		$8*4, offset

	jl		1b

	movd	ve3, dr						// Put previous word into work register.
	movzx	1(R), t0d					// Get round constant.
	movd	t0d, vt0

	SubWordRotWord

	movd	0*4+Local(r4), ve0			// Get old word.
	pxor	vt0, ve0					// Chain.
	movd	ve0, (0+8)*4(E, offset)

	// Chain to successive words.
	movd	1*4+Local(r4), ve1			// Get old word.
	pxor	ve0, ve1					// Chain.
	movd	ve1, (1+8)*4(E, offset)

	movd	2*4+Local(r4), ve2			// Get old word.
	pxor	ve1, ve2					// Chain.
	movd	ve2, (2+8)*4(E, offset)

	movd	3*4+Local(r4), ve3			// Get old word.
	pxor	ve2, ve3					// Chain.
	movd	ve3, (3+8)*4(E, offset)

	// Pop stack and restore registers.
	#if 0 < LocalsSize
		add		$LocalsSize, r4
	#endif
	#if defined __i386__
		// Add pops of r15 to r12 if used.
		pop		r7
		pop		r6
	#elif defined __x86_64__
	#endif
	pop		r3
	pop		r5

	ret


#undef	Address
#undef	Argument
#undef	E
#undef	ITable
#undef	K
#undef	LocalsSize
#undef	LookupI
#undef	LookupS
#undef	Nk
#undef	R
#undef	RegisterSaveSize
#undef	STable
#undef	StackFrame
#undef	dr
#undef	drh
#undef	drl
#undef	offset
#undef	t0
#undef	t0d
#undef	ve0
#undef	ve1
#undef	ve2
#undef	ve3
#undef	ve4
#undef	ve5
#undef	vt0
#undef	vt1
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/AESedp/Intel/ExpandKeyForEncryption.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*	This file defines _AESExpandKeyForEncryption.  It is designed to be
	included in another assembly file with the preprocessor #include directive,
	to benefit from some assembly-time calculations.

	Written by Eric Postpischil, January 2008.

	The comments here do not say much about the algorithm; the code just
	follows the FIPS-197 specification.  I recommend reading the specification
	before working with this code or examining the C code in the parent
	directory that illustrates key expansion.
*/


/*	Routine:

		_AESExpandKeyForEncryption.

	Function:

		Expand the user's cipher key into the key schedule, as defined in
		Federal Information Processing Standards Publication 197 (FIPS-197),
		November 26, 2001.

	Input:

		Constant data:

			The following names must be locally defined so the assembler
			can calculate certain offsets.

			static const Word _OLDAESSubBytesWordTable[4][256].

				_OLDAESSubBytesWordTable[i][j] = SubBytes(j) << 8*i, where
				SubBytes is defined in FIPS-197.  _OLDAESSubBytesWordTable
				differs from _OLDAESEncryptTable in that it does not include
				the MixColumn operation.  It is used in performing the last
				round, which differs fromm the previous rounds in that it
				does not include the MixColumn operation.

			static const Byte _OLDAESRcon[].

				Round constants, beginning with OLDAESRcon[1] for the first round
				(OLDAESRcon[0] is padding.)
	
		Arguments:

			Word *ExpandedKey

				Address of output.

			const AESKey *Key

				Address of user's cipher key.

			long Nk

				Number of four-byte words in user's cipher key.

	Output:

		The expanded key is written to *ExpandedKey.
*/
	.globl _AESExpandKeyForEncryption
	.private_extern	_AESExpandKeyForEncryption
_AESExpandKeyForEncryption:

#define	dr		r0d				// Dissection register.
#define	drl		r0l				// Low 8 bits of dissection register.
#define	drh		r0h				// Second-lowest 8 bits of dissection register.

#define	t0		r1
#define	t0d		r1d				// Low 32 bits of t0.

#define	offset	r5				// Address offset and loop sentinel.

#define	R		r6				// Address of round constant.
#define	K		r6				// User key pointer, second x86_64 argument.
	// R and K overlap.

#define	E		r7				// Expanded key pointer, first x86_64 argument.

#define	ve0		%xmm0
#define	ve1		%xmm1
#define	ve2		%xmm2
#define	ve3		%xmm3
#define	vt3		%xmm4
#define	vt2		%xmm5
#define	vt1		%xmm6
#define	vt0		%xmm7

#define	LookupS(table, index)	(table)*TableSize(STable, index, 4)

	// Push new stack frame.
	push	r5

	// Save registers.
	#if defined __i386__
		push	r6
		push	r7
		#define	RegisterSaveSize	(2*4)
	#elif defined __x86_64__
		#define	RegisterSaveSize	(0*8)
		// Add pushes of r12 to r15 if used.
	#endif

#define	LocalsSize	0
#define	StackFrame	(LocalsSize+RegisterSaveSize)
	// Locals plus the registers we pushed after the new stack frame.

#if defined __i386__

	// Define location of argument i.
	#define	Argument(i)	StackFrame+8+4*(i)(r4)

	// Load arguments.
	mov		Argument(0), E
	mov		Argument(1), K
	#define	Nk	Argument(2)

#elif defined __x86_64__

	#define	Nk		r2			// Number of words in key.  Overlaps STable.

#endif

	cmp		$6,	 Nk
// Stop using r2 for Nk and start using it for STable.
#undef	Nk
#define	STable	r2

	#if 0 < LocalsSize
		sub		$LocalsSize, r4	// Allocate space on stack.
	#endif

	// First words of expanded key are copied from user key.
	movd	0*4(K), ve0
	movd	1*4(K), ve1
	movd	2*4(K), ve2
	movd	3*4(K), ve3
	je		EKeyHas6Words
	jg		EKeyHas8Words
	// Fall through to EKeyHas4Words.

EKeyHas4Words:

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__
		// Get address of 0 in R.
			call	0f			// Push program counter onto stack.
		0:
			pop		STable		// Get program counter.

		lea		_OLDAESRcon-0b(STable), R
		lea		_OLDAESSubBytesWordTable-0b(STable), STable

	#elif defined __x86_64__

		lea		_OLDAESRcon(%rip), R
		lea		_OLDAESSubBytesWordTable(%rip), STable

	#endif

	// With a four-word key, there are ten rounds (eleven 16-byte key blocks).
	mov		$-10*4*4, offset
	sub		offset, E

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E, offset)
	movd	ve1, 1*4(E, offset)
	movd	ve2, 2*4(E, offset)
	movd	ve3, 3*4(E, offset)

1:
	add		$1, R				// Advance pointer.
	movd	ve3, dr				// Put previous word into dissection register.
	movzx	(R), t0d			// Get round constant.
	movd	t0d, vt3
	pxor	vt3, ve0			// XOR with word from four words back.

	// Perform SubWord(RotWord(dr)).
	movzx	drl, t0
	movd	LookupS(3, t0), vt0		// Look up byte 0 in table 3.
	movzx	drh, t0d
	movd	LookupS(0, t0), vt1		// Look up byte 1 in table 0.
	shr		$16, dr
	movzx	drl, t0d
	movd	LookupS(1, t0), vt2		// Look up byte 2 in table 1.
	movzx	drh, t0d
	movd	LookupS(2, t0), vt3		// Look up byte 3 in table 2.
	pxor	vt1, vt0
	pxor	vt3, vt2
	pxor	vt0, ve0
	pxor	vt2, ve0

	add		$4*4, offset

	// Chain to successive words.
	movd	ve0, 0*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 1*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 2*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 3*4(E, offset)

	jne		1b

	// Pop stack and restore registers.
	#if 0 < LocalsSize
		add		$LocalsSize, r4
	#endif
	#if defined __i386__
		// Add pops of r15 to r12 if used.
		pop		r7
		pop		r6
	#elif defined __x86_64
	#endif
	pop		r5

	ret


// Reset definitions for next case.
#undef	vt3
#undef	vt2
#define	ve4	%xmm4
#define	ve5	%xmm5


EKeyHas6Words:
	movd	4*4(K), ve4
	movd	5*4(K), ve5

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__
		// Get address of 0 in R.
			call	0f			// Push program counter onto stack.
		0:
			pop		STable		// Get program counter.

		lea		_OLDAESRcon-0b(STable), R
		lea		_OLDAESSubBytesWordTable-0b(STable), STable

	#elif defined __x86_64__

		lea		_OLDAESRcon(%rip), R
		lea		_OLDAESSubBytesWordTable(%rip), STable

	#endif

	/*	With a six-word key, there are twelve rounds (thirteen 16-byte key
		blocks).
	*/
	mov		$-12*4*4, offset
	sub		offset, E

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E, offset)
	movd	ve1, 1*4(E, offset)
	movd	ve2, 2*4(E, offset)
	movd	ve3, 3*4(E, offset)
	movd	ve4, 4*4(E, offset)
	movd	ve5, 5*4(E, offset)

/*	Jump into loop body.  The key expansion processes six four-byte words per
	iteration.  52 are needed in the key.  So only four are needed in the last
	iteration.
*/
	jmp		2f		
1:
	// Continue chaining to successive words.
	pxor	ve3, ve4
	movd	ve4, 4*4(E, offset)
	pxor	ve4, ve5
	movd	ve5, 5*4(E, offset)
2:
	add		$1, R				// Advance pointer.
	movd	ve5, dr				// Put previous word into dissection register.
	movzx	(R), t0				// Get round constant.
	movd	t0d, vt1
	pxor	vt1, ve0			// XOR with word from six words back.

	// Perform SubWord(RotWord(dr)).
	movzx	drl, t0d
	movd	LookupS(3, t0), vt0		// Look up byte 0 in table 3.
	movzx	drh, t0d
	movd	LookupS(0, t0), vt1		// Look up byte 1 in table 0.
	shr		$16, dr
	movzx	drl, t0d
	pxor	vt1, vt0
	pxor	vt0, ve0
	movd	LookupS(1, t0), vt0		// Look up byte 2 in table 1.
	movzx	drh, t0d
	movd	LookupS(2, t0), vt1		// Look up byte 3 in table 2.
	pxor	vt1, vt0
	pxor	vt0, ve0

	add		$6*4, offset

	// Chain to successive words.
	movd	ve0, 0*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 1*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 2*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 3*4(E, offset)

	jne		1b

	// Pop stack and restore registers.
	#if 0 < LocalsSize
		add		$LocalsSize, r4
	#endif
	#if defined __i386__
		// Add pops of r15 to r12 if used.
		pop		r7
		pop		r6
	#elif defined __x86_64
	#endif
	pop		r5

	ret


// Reset definitions for next case.
#undef	ve4
#undef	ve5
#define	vt3	%xmm4
#define	vt2	%xmm5


EKeyHas8Words:

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E)
	movd	ve1, 1*4(E)
	movd	ve2, 2*4(E)
	movd	ve3, 3*4(E)
	movd	4*4(K), ve0
	movd	5*4(K), ve1
	movd	6*4(K), ve2
	movd	7*4(K), ve3

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__
		// Get address of 0 in R.
			call	0f			// Push program counter onto stack.
		0:
			pop		STable		// Get program counter.

		lea		_OLDAESRcon-0b(STable), R
		lea		_OLDAESSubBytesWordTable-0b(STable), STable

	#elif defined __x86_64__

		lea		_OLDAESRcon(%rip), R
		lea		_OLDAESSubBytesWordTable(%rip), STable

	#endif

	/*	With an eight-word key, there are fourteen rounds (fifteen 16-byte key
	 	blocks).
	*/
	mov		$-14*4*4, offset
	sub		offset, E

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 4*4(E, offset)
	movd	ve1, 5*4(E, offset)
	movd	ve2, 6*4(E, offset)
	movd	ve3, 7*4(E, offset)

/*	Jump into loop body.  The key expansion processes eight four-byte words per
	iteration.  60 are needed in the key.  So only four are needed in the last
	iteration.
*/
	jmp		2f		
1:
	movd	ve3, dr				// Put previous word into dissection register.

	/*	Get word from eight words back (it is four words back from where E
	 	currently points, and we use it to prepare the value to be stored
		four words beyond where E currently points).
	*/
	movd	-4*4(E, offset), ve0

	// Perform SubWord(dr).
	movzx	drl, t0
	movd	LookupS(0, t0), vt0		// Look up byte 0 in table 0.
	movzx	drh, t0d
	movd	LookupS(1, t0), vt1		// Look up byte 1 in table 1.
	shr		$16, dr
	movzx	drl, t0d
	movd	LookupS(2, t0), vt2		// Look up byte 2 in table 2.
	movzx	drh, t0d
	movd	LookupS(3, t0), vt3		// Look up byte 3 in table 3.
	pxor	vt1, vt0
	pxor	vt3, vt2
	pxor	vt0, ve0
	pxor	vt2, ve0

	movd	-3*4(E, offset), ve1	// Get words from eight words back.
	movd	-2*4(E, offset), ve2
	movd	-1*4(E, offset), ve3

	// Chain to successive words.
	movd	ve0, 4*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 5*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 6*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 7*4(E, offset)

2:
	add		$1, R				// Advance pointer.
	movd	ve3, dr				// Put previous word into dissection register.
	movzx	(R), t0d			// Get round constant.
	movd	t0d, vt1
	movd	0*4(E, offset), ve0	// Get word from eight words back.
	pxor	vt1, ve0

	// Perform SubWord(RotWord(dr)).
	movzx	drl, t0
	movd	LookupS(3, t0), vt0		// Look up byte 0 in table 3.
	movzx	drh, t0d
	movd	LookupS(0, t0), vt1		// Look up byte 1 in table 0.
	shr		$16, dr
	movzx	drl, t0d
	movd	LookupS(1, t0), vt2		// Look up byte 2 in table 1.
	movzx	drh, t0d
	movd	LookupS(2, t0), vt3		// Look up byte 3 in table 2.
	pxor	vt1, vt0
	pxor	vt3, vt2
	pxor	vt0, ve0
	pxor	vt2, ve0

	movd	1*4(E, offset), ve1
	movd	2*4(E, offset), ve2
	movd	3*4(E, offset), ve3

	add		$8*4, offset

	// Chain to successive words.
	movd	ve0, 0*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 1*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 2*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 3*4(E, offset)

	jne		1b

	// Pop stack and restore registers.
	#if 0 < LocalsSize
		add		$LocalsSize, r4
	#endif
	#if defined __i386__
		// Add pops of r15 to r12 if used.
		pop		r7
		pop		r6
	#elif defined __x86_64
	#endif
	pop		r5

	ret


#undef	Address
#undef	Argument
#undef	E
#undef	LocalsSize
#undef	LookupS
#undef	R
#undef	RegisterSaveSize
#undef	STable
#undef	StackFrame
#undef	dr
#undef	drh
#undef	drl
#undef	offset
#undef	t0
#undef	t0d
#undef	ve0
#undef	ve1
#undef	ve2
#undef	ve3
#undef	vt0
#undef	vt1
#undef	vt2
#undef	vt3
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/AESedp/Intel/ReadMe.txt.

1
2
3
4
This directory contains implementations of core AES routines (the actual
encryption, decryption, and key expansion) for the i386 (IA-32) and x86_64
(EMT64) architectures.  These routines are intended to be called by routines
in the parent directory.
<
<
<
<








Deleted Source/AESedp/MakeData.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define	UseAESedp	// Tell AES.h to define things for AESedp.
#include "AES.h"


/*	In comments below, {n} designates the Galois field element represented by
	the byte n.  See notes about Galois field multiplication in ReadMe.txt.

	So 3+5 is addition of ordinary integers, and 3+5 == 8, while {3}+{5} is
	addition in the field, and {3} + {5} = {3 XOR 5} = {6}.)
*/


// Define constants for languages.
typedef enum { C, IntelAssembly } Language;


/*	LogBase3[i] will contain the base-three logarithm of i in the 256-element
	Galois field defined by AES.  That is, {3}**LogBase3[i] == {3}**i.
*/
static Byte LogBase3[256];

/*	AntilogBase3[i] will contain {3}**i in the 256-element Galois field defined
	by AES.  It contains extra elements so that the antilog of a+b can be found
	by looking up a+b directly, without having to reduce modulo the period, for
	0 <= a, b < 255.

	(254 is the greatest value we encounter.  Each a or b we use is the
	base-three logarithm of some element.  As a primitive root, the powers of
	three cycle through all non-zero elements of the field, of which there are
	255, so the exponents cover 0 to 254 before the powers repeat.)
*/
static Byte AntilogBase3[254+254+1];


static void InitializeLogTables(void)
{
	// log({1}) is zero, so start {p} (power) at {1} and l (logarithm) at 0.
	Byte p = 1;
	int l = 0;
	do
	{
		// Record table entries.
		LogBase3[p] = l;
		AntilogBase3[l] = p;

		/*	Observe that {2}*{p} is {p << 1 ^ (a & 0x80 ? 0x1b : 0)}, per notes
			in ReadMe.txt.  We produce {3}*{p}:

				{3}*{p}
					= {1}*{p} + {2}*{p}
					= {1}*{p} + {p << 1 ^ (a & 0x80 ? 0x1b : 0)}
					= {p ^ p << 1 ^ (p & 0x80 ? 0x1b : 0)}.
		*/
		p ^= p << 1 ^ (p & 0x80 ? 0x1b : 0);
		++l;

	} while (p != 1);	// Stop when we have gone around completely.

	/*	The antilogarithms are periodic with a period of 255, and we want to
		look up elements as high as 254+254 (the largest that a sum of two
		logarithms could be), so we replicate the table beyond the first
		period.
	*/
	for (l = 255; l < 254+254; ++l)
		AntilogBase3[l] = AntilogBase3[l-255];
}


/*	MultiplyByte(Byte b, Byte c) returns {b}*{c}.  It requires tables that must
	be initialized before this routine is used.
*/
static Byte MultiplyByte(Byte b, Byte c)
{
	// Calculate product by adding logarithms, but avoid logarithms of zero.
	return b == 0 || c == 0 ? 0 : AntilogBase3[LogBase3[b] + LogBase3[c]];
}


// Return {0} if {b} is {0} and the multiplicative inverse of {b} otherwise.
static Byte InverseByte(Byte b)
{
	return b == 0 ? 0 : AntilogBase3[255 - LogBase3[b]];
}


// Perform AES' SubBytes operation on a single byte.
static Byte SubByte(Byte b)
{
	unsigned int r = InverseByte(b);

	// Duplicate r as a proxy for a rotate operation.
	r = r | r<<8;

	// Apply the standard's affine transformation.
	return r ^ r>>4 ^ r>>5 ^ r>>6 ^ r>>7 ^ 0x63;
}


// Define and populate tables for the SubBytes and InvSubBytes operations.
static Byte SubBytesTable[256];
static Byte InvSubBytesTable[256];


static void InitializeSubBytesTable(void)
{
	for (int i = 0; i < 256; ++i)
		SubBytesTable[i] = SubByte((Byte) i);
}


static void InitializeInvSubBytesTable(void)
{
	for (int i = 0; i < 256; ++i)
		InvSubBytesTable[SubByte((Byte) i)] = i;
}


/*	Print tables for SubBytes function providing the output byte embedded in
	various places in a word, so that the table entries can be used with
	fewer byte manipulations.
*/
static void PrintSubBytesWordTable(Language language)
{
	switch (language)
	{
		case C:
			printf("\n\n"
				"// SubBytes embedded in words tables.\n"
				"const Word AESSubBytesWordTable[4][256] =\n"
				"{\n");
			for (int j = 0; j < 4; ++j)
			{
				printf("\t{\n");
				for (int i = 0; i < 256; ++i)
					printf("\t\t0x%08x,\n", SubBytesTable[i] << j*8);
				printf("\t},\n");
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// SubBytes embedded in words tables.\n"
				"\t.globl\t_AESSubBytesWordTable\n"
				"\t.private_extern\t_AESSubBytesWordTable\n"
				"\t.align\t2\n"
				"_AESSubBytesWordTable:\n");
			for (int j = 0; j < 4; ++j)
			{
				printf("\t// Table %d.\n", j);
				for (int i = 0; i < 256; ++i)
					printf("\t.long\t0x%08x\n", SubBytesTable[i] << j*8);
			}
			break;
	}
}


/*	Print tables for InvSubBytes function providing the output byte embedded in
	various places in a word, so that the table entries can be used with
	fewer byte manipulations.
*/
static void PrintInvSubBytesWordTable(Language language)
{
	switch (language)
	{
		case C:
			printf("\n\n"
				"// InvSubBytes embedded in words tables.\n"
				"const Word AESInvSubBytesWordTable[4][256] =\n"
				"{\n");
			for (int j = 0; j < 4; ++j)
			{
				printf("\t{\n");
				for (int i = 0; i < 256; ++i)
					printf("\t\t0x%08x,\n", InvSubBytesTable[i] << j*8);
				printf("\t},\n");
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// InvSubBytes embedded in words tables.\n"
				"\t.globl\t_AESInvSubBytesWordTable\n"
				"\t.private_extern\t_AESInvSubBytesWordTable\n"
				"\t.align\t2\n"
				"_AESInvSubBytesWordTable:\n");
			for (int j = 0; j < 4; ++j)
			{
				printf("\t// Table %d.\n", j);
				for (int i = 0; i < 256; ++i)
					printf("\t.long\t0x%08x\n", InvSubBytesTable[i] << j*8);
			}
			break;
	}
}


// Print the round constants.
static void PrintRcon(Language language)
{
	union { Byte c[4]; Word w; } t = { { 1, 0, 0, 0 } };

	switch (language)
	{
		case C:
			printf("\n\n"
				"// Round constants.\n"
				"const Byte AESRcon[] =\n"
				"{\n"
				"\t0,\t// Not used, included for indexing simplicity.\n");
			for (int i = 1; i < MaxRcon; ++i)
			{
				printf("\t0x%02x,\n", t.w);
				t.c[0] = MultiplyByte(0x2, t.c[0]);
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// Round constants.\n"
				"\t.globl\t_AESRcon\n"
				"\t.private_extern\t_AESRcon\n"
				"_AESRcon:\n"
				"\t.byte\t0\t// Not used, included for indexing simplicity.\n");
			for (int i = 1; i < MaxRcon; ++i)
			{
				printf("\t.byte\t0x%02x\n", t.w);
				t.c[0] = MultiplyByte(0x2, t.c[0]);
			}
			break;
	}
}


// Print tables for the InvMixColumn operation.
static void PrintInvMixColumnTable(Language language)
{
	Word T[4][256];

	for (int i = 0; i < 256; ++i)
	{
		union { Byte b[4]; Word w; } c;

		Byte s9 = MultiplyByte(0x9, i);
		Byte sb = MultiplyByte(0xb, i);
		Byte sd = MultiplyByte(0xd, i);
		Byte se = MultiplyByte(0xe, i);

		c.b[0] = se;
		c.b[1] = s9;
		c.b[2] = sd;
		c.b[3] = sb;
		T[0][i] = c.w;

		c.b[0] = sb;
		c.b[1] = se;
		c.b[2] = s9;
		c.b[3] = sd;
		T[1][i] = c.w;

		c.b[0] = sd;
		c.b[1] = sb;
		c.b[2] = se;
		c.b[3] = s9;
		T[2][i] = c.w;

		c.b[0] = s9;
		c.b[1] = sd;
		c.b[2] = sb;
		c.b[3] = se;
		T[3][i] = c.w;
	}

	switch (language)
	{
		case C:
			printf("\n\n"
				"// Tables for InvMixColumn.\n"
				"const Word AESInvMixColumnTable[4][256] =\n"
				"{\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t{\n");
				for (int j = 0; j < 256; ++j)
					printf("\t\t0x%08x,\n", T[i][j]);
				printf("\t},\n");
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// Tables for InvMixColumn.\n"
				"\t.globl\t_AESInvMixColumnTable\n"
				"\t.private_extern\t_AESInvMixColumnTable\n"
				"\t.align\t2\n"
				"_AESInvMixColumnTable:\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t// Table %d.\n", i);
				for (int j = 0; j < 256; ++j)
					printf("\t.long\t0x%08x\n", T[i][j]);
			}
			break;
	}
}


/*	Print the tables defined AES Proposal: Rijndael, amended, 9/04/2003,
	section 5.2.1.  These combine the MixColumn and SubBytes operations.
*/
static void PrintEncryptTable(Language language)
{
	Word T[4][256];

	for (int i = 0; i < 256; ++i)
	{
		union { Byte b[4]; Word w; } c;

		Byte s1 = SubBytesTable[i];
		Byte s2 = MultiplyByte(0x2, s1);
		Byte s3 = s1 ^ s2;

		c.b[0] = s2;
		c.b[1] = s1;
		c.b[2] = s1;
		c.b[3] = s3;
		T[0][i] = c.w;

		c.b[0] = s3;
		c.b[1] = s2;
		//c.b[2] = s1;
		c.b[3] = s1;
		T[1][i] = c.w;

		c.b[0] = s1;
		c.b[1] = s3;
		c.b[2] = s2;
		//c.b[3] = s1;
		T[2][i] = c.w;

		//c.b[0] = s1;
		c.b[1] = s1;
		c.b[2] = s3;
		c.b[3] = s2;
		T[3][i] = c.w;
	}

	switch (language)
	{
		case C:
			printf("\n\n"
				"// Tables for main encryption iterations.\n"
				"const Word AESEncryptTable[4][256] =\n"
				"{\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t{\n");
				for (int j = 0; j < 256; ++j)
					printf("\t\t0x%08x,\n", T[i][j]);
				printf("\t},\n");
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// Tables for main encryption iterations.\n"
				"\t.globl\t_AESEncryptTable\n"
				"\t.private_extern\t_AESEncryptTable\n"
				"\t.align\t2\n"
				"_AESEncryptTable:\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t// Table %d.\n", i);
				for (int j = 0; j < 256; ++j)
					printf("\t.long\t0x%08x\n", T[i][j]);
			}
			break;
	}
}


/*	Print the inverse tables.  These correspond to the tables above, but for
	decyrption.  These combine the InvSubBytes and InvMixColumn operations.
*/
static void PrintDecryptTable(Language language)
{
	Word T[4][256];

	for (int i = 0; i < 256; ++i)
	{
		union { Byte b[4]; Word w; } c;

		Byte si = InvSubBytesTable[i];

		Byte s9 = MultiplyByte(0x9, si);
		Byte sb = MultiplyByte(0xb, si);
		Byte sd = MultiplyByte(0xd, si);
		Byte se = MultiplyByte(0xe, si);

		c.b[0] = se;
		c.b[1] = s9;
		c.b[2] = sd;
		c.b[3] = sb;
		T[0][i] = c.w;

		c.b[0] = sb;
		c.b[1] = se;
		c.b[2] = s9;
		c.b[3] = sd;
		T[1][i] = c.w;

		c.b[0] = sd;
		c.b[1] = sb;
		c.b[2] = se;
		c.b[3] = s9;
		T[2][i] = c.w;

		c.b[0] = s9;
		c.b[1] = sd;
		c.b[2] = sb;
		c.b[3] = se;
		T[3][i] = c.w;
	}

	switch (language)
	{
		case C:
			printf("\n\n"
				"// Tables for main decryption iterations.\n"
				"const Word AESDecryptTable[4][256] =\n"
				"{\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t{\n");
				for (int j = 0; j < 256; ++j)
					printf("\t\t0x%08x,\n", T[i][j]);
				printf("\t},\n");
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// Tables for main decryption iterations.\n"
				"\t.globl\t_AESDecryptTable\n"
				"\t.private_extern\t_AESDecryptTable\n"
				"\t.align\t2\n"
				"_AESDecryptTable:\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t// Table %d.\n", i);
				for (int j = 0; j < 256; ++j)
					printf("\t.long\t0x%08x\n", T[i][j]);
			}
			break;
	}
}


static void Usage(const char *ProgramName)
{
	fprintf(stderr,
		"%s:  This program must have exactly one argument, \"C\" to generate\n"
		"C or \"Intel\" to generate GCC i386/x86_64 assembly.\n", ProgramName);
	exit(EXIT_FAILURE);
}


int main(int argc, char *argv[])
{
	if (argc != 2)
		Usage(argv[0]);

	Language language;

	// Figure out which language to generate, C or Intel assembly.
	if (0 == strcmp(argv[1], "C"))
		language = C;
	else if (0 == strcmp(argv[1], "Intel"))
		language = IntelAssembly;
	else
		Usage(argv[0]);

	printf("// This file was generated by " __FILE__ ".\n");

	if (language == C)
		printf("\n\n#include \"AES.h\"\n");

	if (language == IntelAssembly)
		printf("\n\n\t.const\n");

	InitializeLogTables();
	InitializeSubBytesTable();
	InitializeInvSubBytesTable();

	PrintRcon(language);
	PrintInvMixColumnTable(language);
	PrintEncryptTable(language);
	PrintDecryptTable(language);
	PrintSubBytesWordTable(language);
	PrintInvSubBytesWordTable(language);

	return 0;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/AESedp/ReadMe.txt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
This directory contains an implementation of AES intended to plug into the
CommonCrypto interface.  This main directory contains a C implementation which
is not particularly fast but which works and illustrates the techniques used.
The Intel subdirectory contains routines providing a fast implementation for
the i386 (IA-32) and x86_64 (EMT64) architectures.  The Intel routines replace
certain routines in AES.c when UseAESedp_IntelAssembly is defined in AES.h and
UseAESedp_GeneralC is not defined.

Below is a summary of some of the arithmetic used in AES.  This is not an
introduction to AES, just a note about why we use bitwise XOR for "addition" of
AES elements and various expressions for "multiplication."

AES defines a 256-element Galois field over the integers modulo 2 modulo the
polynomial p(x) = x**8 + x**4 + x**3 + x + 1.  This means:

	Only the residues modulo 2 of the coefficients are relevant, so each
	coefficient is effectively either 0 or 1.  1+1 yields zero.

	Only the residues modulo p(x) of the polynomials are relevant, so each
	polynomial is effectively a degree-seven or less polynomial.  (Any result,
	say from multiplication, that yields a polynomial with a term x**8 or
	greater is reduced by dividing it by p(x).)

	Each element of the field is a polynomial with eight coefficients (for
	each power of x from x**7 to x**0), and each coefficients is a single bit.
	So we can represent an element in an eight-bit byte.

	XORing two bytes is the same as adding two polynomials.

	To multiply a polynomial by x, shift the byte left one bit.  If the x**8
	bit is on, then subtract p(x), which is represented by 0x11b.  (No more
	than one subtraction is needed, because the x**8 coefficient is at most
	one.)  Equivalently:

		unsigned char MultiplyByX(unsigned char b)
		{ return b << 1 ^ (b & 0x80 ? 0x1b : 0); }

	Two polynomials can be multiplied by using the above operations to
	multiply by powers of x and add appropriate powers.

AES defines another field with polynomials whose coefficients are elements in
the previous Galois field.  This larger field has a characteristic polynomial
of x**4 + 1.  This means:

	Elements in this field have four coefficients, each of which can be
	represented by a byte.

	Elements are added by adding their coefficients, which are adding by XORing
	their byte representations.  So an XOR of two four-byte words containing
	the representations of two elements is the sum of the two elements.

	Because the characteristic polynomial is x**4 + 1 and b == -b in this
	field, multiplying a polynomial by x effectively rotates the four bytes
	that represent it left one byte.
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































Deleted Source/AESedp/makefile.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
default:
	@echo This makefile builds Data.c and Intel/Data.s, which contain constant
	@echo data for the AES implementation.  These files do not normally need to
	@echo be rebuilt, so they are checked into the source code repository.  They
	@echo should be changed only when the implementation changes and needs
	@echo data in a different format.
	@echo
	@echo To rebuild the files, execute "make all".

.PHONY:	all clean
Targets = Data.c Intel/Data.s
all:	$(Targets)

CFLAGS += -O3 -std=c99 -Wmost -Werror

.INTERMEDIATE:	MakeData
MakeData:	MakeData.c

# Do not leave bad output files if the build fails.
.DELETE_ON_ERROR:	$(Targets)

Data.c:	MakeData
	./$< >$@ C

Intel/Data.s:	MakeData
	./$< >$@ Intel

clean:
	-rm $(Targets)
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































Added Source/API/CommonBigNum.c.























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_BIGNUM_FUNCTIONS
#include "CommonBigNum.h"
#include "CommonBigNumPriv.h"
#include "CommonRandomSPI.h"
#include "ccMemory.h"
#include "ccErrors.h"
#include "ccdebug.h"
#include <corecrypto/ccz.h>
#include <corecrypto/ccn.h> /* For ccn_sizeof(). */
#include <corecrypto/cc_priv.h> /* For CC_LOAD32_BE. */


static void *
cc_alloc(void *ctx CC_UNUSED, size_t size) {
    return malloc(size);
}

static void
cc_free(void *ctx CC_UNUSED, size_t oldsize, void *p) {
    cc_zero(oldsize, p);
    free(p);
}

static void *
cc_realloc(void *ctx CC_UNUSED, size_t oldsize,
                 void *p, size_t newsize) {
    void *r = malloc(newsize);
    memcpy(r, p, oldsize);
    cc_zero(oldsize, p);
    free(p);
    return r;
}

struct ccz_class ccz_c = {
	.ctx = 0,
	.ccz_alloc = cc_alloc,
	.ccz_realloc = cc_realloc,
	.ccz_free = cc_free
};

CCBigNumRef
CCCreateBigNum(CCStatus *status)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = malloc(ccz_size(&ccz_c));
    if (status)
        *status = r ? kCCSuccess : kCCMemoryFailure;
    if (r)
        ccz_init(&ccz_c, r);
    if(!r) printf("Bad Create\n");
    return (CCBigNumRef)r;
}

CCStatus
CCBigNumClear(CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = (ccz *)bn;
    ccz_zero(r);
    return kCCSuccess;
}

void
CCBigNumFree(CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = (ccz *)bn;
    ccz_free(r);
    free(r);
}

CCBigNumRef
CCBigNumCopy(CCStatus *status, const CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    const ccz *s = (ccz *)bn;
    ccz *r = (ccz *)CCCreateBigNum(status);
    if (r)
        ccz_set(r, s);
    return (CCBigNumRef)r;
}

uint32_t
CCBigNumBitCount(const CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    const ccz *s = (ccz *)bn;
    return ccz_bitlen(s);
}

uint32_t
CCBigNumZeroLSBCount(const CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    const ccz *s = (ccz *)bn;
    return ccz_trailing_zeros(s);
}

uint32_t
CCBigNumByteCount(const CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    const ccz *s = (ccz *)bn;
    return ccz_write_uint_size(s);
}

CCBigNumRef
CCBigNumFromData(CCStatus *status, const void *s, size_t len)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = (ccz *)CCCreateBigNum(status);
    if (r) {
        ccz_read_uint(r, len, s);
    }
    return (CCBigNumRef)r;
}

size_t
CCBigNumToData(CCStatus *status, const CCBigNumRef bn, void *to)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    const ccz *s = (ccz *)bn;
    size_t to_size = ccz_write_uint_size(s);
    ccz_write_uint(s, to_size, to);
    return to_size;
}

CCBigNumRef
CCBigNumFromHexString(CCStatus *status, const char *in)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = (ccz *)CCCreateBigNum(status);
    if (r) {
        if (ccz_read_radix(r, strlen(in), in, 16)) {
            ccz_zero(r);
            if (status)
                *status = kCCDecodeError;
            return NULL;
        }
    }
    return (CCBigNumRef)r;
}

char *
CCBigNumToHexString(CCStatus *status, const CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    const ccz *s = (ccz *)bn;
    size_t to_size = ccz_write_radix_size(s, 16);
    char *to = malloc(to_size+1);
    ccz_write_radix(s, to_size, to, 16);
    to[to_size] = 0;
    return to;
}

int
CCBigNumCompare(const CCBigNumRef bn1, const CCBigNumRef bn2)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    const ccz *s = (const ccz *)bn1;
    const ccz *t = (const ccz *)bn2;
	return ccz_cmp(s, t);
}

int
CCBigNumCompareI(const CCBigNumRef bn1, const uint32_t num)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    const ccz *s = (const ccz *)bn1;
	return ccz_cmpi(s, num);
}

CCStatus
CCBigNumSetNegative(CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = (ccz *)bn;
    ccz_neg(r);
    return kCCSuccess;
}

CCStatus
CCBigNumSetI(CCBigNumRef bn, uint64_t num)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = (ccz *)bn;
    ccz_seti(r, num);
    return kCCSuccess;
}

uint32_t
CCBigNumGetI(CCStatus *status, const CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    /* TODO: This could be done more efficiently if we pushed a ccz_readi and
       ccn_readi routine all the way down into corecrypto. */
    ccz *s = (const ccz *)bn;
    uint32_t v = 0;
    if(ccz_write_int_size(s) > sizeof(v)) {
        *status = kCCOverflow;
        return 0;
    }

    uint8_t to[sizeof(v)];
    ccz_write_uint(s, sizeof(v), to);
    CC_LOAD32_BE(v, to);

    if (status)
        *status = kCCSuccess;
    return v;
}

CCBigNumRef
CCBigNumCreateRandom(CCStatus *status, int bits, int top, int bottom)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    struct ccrng_state *rng = ccDRBGGetRngState();
    ccz *r = (ccz *)CCCreateBigNum(status);
    if (r && top > 0) {
        /* TODO: Use the #if 0'd code once CommonCrypto has a native ccrng handle to use. */
#if 1
        do {
            ccz_random_bits(r, top, rng);
        } while(ccz_bitlen(r) - ccz_trailing_zeros(r) < bottom);
#else
        size_t data_size = ccn_sizeof(top);
        uint8_t data[data_size];
        CCStatus st;
        do {
            st = CCRandomCopyBytes(kCCRandomDefault, data, data_size);
            if (st) {
                break;
            }
            if (top & 7)
                data[0] &= 0xff >> 8 - (top & 7);

            ccz_read_uint(r, data_size, data);
        } while(ccz_bitlen(r) - ccz_trailing_zeros(r) < bottom);
        memset(data, 0, data_size);
        if (st) {
            if (status)
                *status = st;
            CCBigNumFree(r);
            r = NULL;
        }
#endif
    }
    return (CCBigNumRef)r;
}

CCStatus
CCBigNumAdd(CCBigNumRef res, const CCBigNumRef a, const CCBigNumRef b)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = (ccz *)res;
    ccz *s = (const ccz *)a;
    ccz *t = (const ccz *)b;
    ccz_add(r, s, t);
    return kCCSuccess;
}

CCStatus
CCBigNumAddI(CCBigNumRef res, const CCBigNumRef a, const uint32_t b)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = (ccz *)res;
    ccz *s = (const ccz *)a;
    ccz_addi(r, s, b);
    return kCCSuccess;
}

CCStatus
CCBigNumSub(CCBigNumRef res, const CCBigNumRef a, const CCBigNumRef b)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = (ccz *)res;
    ccz *s = (const ccz *)a;
    ccz *t = (const ccz *)b;
    ccz_sub(r, s, t);
    return kCCSuccess;
}

CCStatus
CCBigNumSubI(CCBigNumRef res, const CCBigNumRef a, const uint32_t b)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz *r = (ccz *)res;
    ccz *s = (const ccz *)a;
    ccz_subi(r, s, b);
    return kCCSuccess;
}

CCStatus
CCBigNumMul(CCBigNumRef res, const CCBigNumRef a, const CCBigNumRef b)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz_mul(res, a, b);
    return kCCSuccess;
}

CCStatus
CCBigNumMulI(CCBigNumRef res, const CCBigNumRef a, const uint32_t b)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz_muli(res, a, b);
    return kCCSuccess;
}

CCStatus
CCBigNumDiv(CCBigNumRef quotient, CCBigNumRef remainder, const CCBigNumRef a, const CCBigNumRef b)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz_divmod(quotient, remainder, a, b);
    return kCCSuccess;
}

CCStatus
CCBigNumDiv2(CCBigNumRef res, const CCBigNumRef a)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz_div2(res, a);
    return kCCSuccess;
}

CCStatus
CCBigNumMod(CCBigNumRef res, CCBigNumRef dividend, CCBigNumRef modulus)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz_mod(res, dividend, modulus);
    return kCCSuccess;
}

CCStatus
CCBigNumModI(uint32_t *res, CCBigNumRef dividend, uint32_t modulus)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CCStatus status = 0;
    CCBigNumRef r = CCCreateBigNum(&status);
    if(!r) goto err;
    CCBigNumRef mod = CCCreateBigNum(&status);
    if(!mod) goto err;
    status = CCBigNumSetI(mod, modulus);
    ccz_mod(r, dividend, mod);

    *res = CCBigNumGetI(&status, r);
err:
    if(r) CCBigNumFree(r);
    if(mod) CCBigNumFree(mod);
    return status;
}

CCStatus
CCBigNumSquare(CCBigNumRef res, const CCBigNumRef a)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz_sqr(res, a);
    return kCCSuccess;
}

CCStatus
CCBigNumGCD(CCBigNumRef res, const CCBigNumRef a, const CCBigNumRef b)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz_gcd(res, a, b);
    return kCCSuccess;
}

CCStatus
CCBigNumLCM(CCBigNumRef res, const CCBigNumRef a, const CCBigNumRef b)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz_lcm(res, a, b);
    return kCCSuccess;
}

CCStatus
CCBigNumMulMod(CCBigNumRef res, const CCBigNumRef a, const CCBigNumRef b, const CCBigNumRef modulus)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	ccz_mulmod(res, a, b, modulus);
    return kCCSuccess;
}

CCStatus
CCBigNumSquareMod(CCBigNumRef res, const CCBigNumRef a, const CCBigNumRef modulus)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	ccz_sqrmod(res, a, modulus);
    return kCCSuccess;
}

CCStatus
CCBigNumInverseMod(CCBigNumRef res, const CCBigNumRef a, const CCBigNumRef modulus)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	ccz_invmod(res, a, modulus);
    return kCCSuccess;
}

CCStatus
CCBigNumModExp(CCBigNumRef res, const CCBigNumRef a, const CCBigNumRef power, const CCBigNumRef modulus)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	ccz_expmod(res, a, power, modulus);
    return kCCSuccess;
}

CCStatus
CCBigNumLeftShift(CCBigNumRef res, const CCBigNumRef a, const uint32_t digits)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz_lsl(res, a, digits);
    return kCCSuccess;
}

CCStatus
CCBigNumRightShift(CCBigNumRef res, const CCBigNumRef a, const uint32_t digits)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccz_lsr(res, a, digits);
    return kCCSuccess;
}

CCStatus
CCBigNumMontgomerySetup(CCBigNumRef num, uint32_t *rho)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	return kCCUnimplemented; // ccLTCErr(mp_montgomery_setup(num, rho));
}

CCStatus
CCBigNumMontgomeryNormalization(CCBigNumRef a, CCBigNumRef b)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	return kCCUnimplemented; // ccLTCErr(mp_montgomery_normalization(a, b));
}

CCStatus
CCBigNumMontgomeryReduce(CCBigNumRef x, CCBigNumRef n, uint32_t rho)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	return kCCUnimplemented; // ccLTCErr(mp_montgomery_reduce(x, n, rho));
}

bool
CCBigNumIsPrime(CCStatus *status, const CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if (status)
        *status = kCCSuccess;

    /* TODO: Figure out right number of rounds (or depth). */
    return ccz_is_prime(bn, 16);
}

bool
CCBigNumIsOdd(CCStatus *status, const CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if (status)
        *status = kCCSuccess;

    return ccz_is_odd(bn);
}

bool
CCBigNumIsZero(CCStatus *status, const CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if (status)
        *status = kCCSuccess;

    return ccz_is_zero(bn);
}

bool
CCBigNumIsNegative(CCStatus *status, const CCBigNumRef bn)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if (status)
        *status = kCCSuccess;

    return ccz_is_negative(bn);
}

Added Source/API/CommonBigNumPriv.h.

















































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef _CC_BIGNUM_PRIV_H_
#define _CC_BIGNUM_PRIV_H_

#include <stdint.h>
/* Uses the tomcrypt math structure to harness math libraries */
/* we probably want to convert this to a CCRandomRef later */
typedef void prng_state;
#define LTC_SOURCE

// #include "tomcrypt_math.h"

typedef void ccBigNum;

typedef ccBigNum *CCBigNumber;


#endif /* _CC_BIGNUM_PRIV_H_ */

Changes to Source/API/CommonCMAC.c.

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37


38
39
40
41
42
43
44
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include "CommonCMACSPI.h"

#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <CommonCrypto/CommonCryptor.h>
#include <CommonCrypto/CommonHMAC.h>

/* Internal functions to support one-shot */

uint8_t const_Rb[16] = {
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87
};



void leftshift_onebit(uint8_t *input, uint8_t *output)
{
    int		i;
    uint8_t	overflow = 0;
    
    for ( i=15; i>=0; i-- ) {







|

|
|
|
|
|



|



>
>







17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_CMAC_FUNCTIONS

#include "CommonCMACSPI.h"
#include "CommonCryptorPriv.h"
#include <corecrypto/ccaes.h>
#include "ccdebug.h"


/* Internal functions to support one-shot */

const uint8_t const_Rb[16] = {
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87
};



void leftshift_onebit(uint8_t *input, uint8_t *output)
{
    int		i;
    uint8_t	overflow = 0;
    
    for ( i=15; i>=0; i-- ) {
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
void xor_128(const uint8_t *a, const uint8_t *b, uint8_t *out)
{
    int i;
    for (i=0;i<16; i++) out[i] = a[i] ^ b[i];
}


void ccGenAESSubKey(const void *key, void *key1, void *key2)
{
    uint8_t L[16];
    uint8_t Z[16];
    uint8_t tmp[16];
    size_t	moved = 0;
    
	memset(Z, 0, 16);
    
	CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode, key, 16, NULL, Z, 16, L, 16, &moved);
    
    if ( (L[0] & 0x80) == 0 ) { /* If MSB(L) = 0, then K1 = L << 1 */
        leftshift_onebit(L, key1);
    } else {    /* Else K1 = ( L << 1 ) (+) Rb */
        leftshift_onebit(L, tmp);
        xor_128(tmp,const_Rb, key1);
    }







|








|







54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
void xor_128(const uint8_t *a, const uint8_t *b, uint8_t *out)
{
    int i;
    for (i=0;i<16; i++) out[i] = a[i] ^ b[i];
}


void ccGenAESSubKey(struct ccmode_ecb *aesmode, ccecb_ctx *ctx, void *key1, void *key2)
{
    uint8_t L[16];
    uint8_t Z[16];
    uint8_t tmp[16];
    size_t	moved = 0;
    
	memset(Z, 0, 16);
    
    aesmode->ecb(ctx, 1, Z, L);
    
    if ( (L[0] & 0x80) == 0 ) { /* If MSB(L) = 0, then K1 = L << 1 */
        leftshift_onebit(L, key1);
    } else {    /* Else K1 = ( L << 1 ) (+) Rb */
        leftshift_onebit(L, tmp);
        xor_128(tmp,const_Rb, key1);
    }
102
103
104
105
106
107
108


109


110
111


112
113
114
115
116
117
118
119
               size_t dataLength,			/* length of data in bytes */
               void *macOut)				/* MAC written here */
{
    uint8_t       X[16],Y[16], M_last[16], padded[16];
    uint8_t       K1[16], K2[16];
    int         n, i, flag;
    size_t		moved = 0;


    


	// CMacInit
    


    ccGenAESSubKey(key,K1,K2);
    
    // CMacUpdates (all in this case)
    
    n = (dataLength+15) / 16;       /* n is number of rounds */
    
    if ( 0 == n ) {
        n = 1;







>
>
|
>
>


>
>
|







104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
               size_t dataLength,			/* length of data in bytes */
               void *macOut)				/* MAC written here */
{
    uint8_t       X[16],Y[16], M_last[16], padded[16];
    uint8_t       K1[16], K2[16];
    int         n, i, flag;
    size_t		moved = 0;
    struct ccmode_ecb *aesmode = getCipherMode(kCCAlgorithmAES128, kCCModeECB, kCCEncrypt).ecb;
    ccecb_ctx_decl(aesmode->size, ctx);

    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");

	// CMacInit
    
    aesmode->init(aesmode, &ctx, 16, key);
    aesmode->ecb(&ctx, 1, Y, X);
    ccGenAESSubKey(aesmode, &ctx, K1, K2);
    
    // CMacUpdates (all in this case)
    
    n = (dataLength+15) / 16;       /* n is number of rounds */
    
    if ( 0 == n ) {
        n = 1;
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
        ccAESCMacPadding(&data[16*(n-1)],padded,dataLength%16);
        xor_128(padded,K2,M_last);
    }
    
    memset(X, 0, 16);
    for ( i=0; i<n-1; i++ ) {
        xor_128(X,&data[16*i],Y); /* Y := Mi (+) X  */
        CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode, key, 16, NULL, Y, 16, X, 16, &moved);
    }
    
    // CMacFinal
    
    xor_128(X,M_last,Y);
	CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode, key, 16, NULL, Y, 16, X, 16, &moved);
    
    memcpy(macOut, X, 16);
}







|





|



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        ccAESCMacPadding(&data[16*(n-1)],padded,dataLength%16);
        xor_128(padded,K2,M_last);
    }
    
    memset(X, 0, 16);
    for ( i=0; i<n-1; i++ ) {
        xor_128(X,&data[16*i],Y); /* Y := Mi (+) X  */
        aesmode->ecb(&ctx, 1, Y, X);
    }
    
    // CMacFinal
    
    xor_128(X,M_last,Y);
    aesmode->ecb(&ctx, 1, Y, X);
    
    memcpy(macOut, X, 16);
}

Added Source/API/CommonCryptoAESShoefly.c.









































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
 *  CommonCryptoAESShoefly.c
 *  CommonCrypto
 *
 *  Shim for Diskimages to bridge to a non-hw based aes-cbc
 *
 */

// #define COMMON_AESSHOEFLY_FUNCTIONS
#define CC_Building
#include "aes.h"

#include "ccdebug.h"


void aes_encrypt_key128(const unsigned char *in_key, aes_encrypt_ctx cx[1])
{
    CCCryptorRef encCryptorRef;
    aes_encrypt_ctx *ctx = cx;
    size_t dataUsed;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");

    (void) CCCryptorCreateFromDataWithMode(kCCEncrypt, kCCModeCBC, kCCAlgorithmAES128NoHardware, ccNoPadding, NULL, in_key, 16, NULL, 0, 0, 0, 
    	&ctx->ctx, kCCContextSizeGENERIC, &ctx->cref, &dataUsed);
}

void aes_encrypt_key256(const unsigned char *in_key, aes_encrypt_ctx cx[1])
{
    CCCryptorRef encCryptorRef;
    aes_encrypt_ctx *ctx = cx;
    size_t dataUsed;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    (void) CCCryptorCreateFromDataWithMode(kCCEncrypt, kCCModeCBC, kCCAlgorithmAES128NoHardware, ccNoPadding, NULL, in_key, 32, NULL, 0, 0, 0, 
                                           &ctx->ctx, kCCContextSizeGENERIC, &ctx->cref, &dataUsed);
}

void aes_decrypt_key128(const unsigned char *in_key, aes_decrypt_ctx cx[1])
{
    CCCryptorRef encCryptorRef;
    aes_encrypt_ctx *ctx = cx;
    size_t dataUsed;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    (void) CCCryptorCreateFromDataWithMode(kCCDecrypt, kCCModeCBC, kCCAlgorithmAES128NoHardware, ccNoPadding, NULL, in_key, 16, NULL, 0, 0, 0, 
                                           &ctx->ctx, kCCContextSizeGENERIC, &ctx->cref, &dataUsed);
}

void aes_decrypt_key256(const unsigned char *in_key, aes_decrypt_ctx cx[1])
{
    CCCryptorRef encCryptorRef;
    aes_encrypt_ctx *ctx = cx;
    size_t dataUsed;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    (void) CCCryptorCreateFromDataWithMode(kCCDecrypt, kCCModeCBC, kCCAlgorithmAES128NoHardware, ccNoPadding, NULL, in_key, 32, NULL, 0, 0, 0, 
                                           &ctx->ctx, kCCContextSizeGENERIC, &ctx->cref, &dataUsed);
}


void aes_encrypt_cbc(const unsigned char *in_blk, const unsigned char *in_iv, unsigned int num_blk,
                     unsigned char *out_blk, aes_encrypt_ctx cx[1])
{
    aes_encrypt_ctx *ctx = cx;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	(void) CCCryptorEncryptDataBlock(ctx->cref, in_iv, in_blk, num_blk * AES_BLOCK_SIZE, out_blk);
}


void aes_decrypt_cbc(const unsigned char *in_blk, const unsigned char *in_iv, unsigned int num_blk,
                     unsigned char *out_blk, aes_decrypt_ctx cx[1])
{
    aes_encrypt_ctx *ctx = cx;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	(void) CCCryptorDecryptDataBlock(ctx->cref, in_iv, in_blk, num_blk * AES_BLOCK_SIZE, out_blk);
}

Added Source/API/CommonCryptoCASTShoefly.c.















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_CASTSHOEFLY_FUNCTIONS

#include <stdio.h>
#include "lionCompat.h"
#include "CommonCryptorSPI.h"
#define DIAGNOSTIC

#include "ccdebug.h"

void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data)
{
    CCCryptorRef *encCryptorRef;
    size_t dataUsed;
    
    encCryptorRef = key->cref;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    (void) CCCryptorCreateWithMode(kCCBoth, kCCModeECB, kCCAlgorithmCAST, ccNoPadding, NULL, data, len, NULL, 0, 0, 0, encCryptorRef);
}

void CAST_ecb_encrypt(const unsigned char *in,unsigned char *out, CAST_KEY *key, int enc)
{
    size_t moved;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering Op: %d\n", enc);
    if(enc)
        CCCryptorEncryptDataBlock(key->cref, NULL, in, kCCBlockSizeCAST, out);
    else
        CCCryptorDecryptDataBlock(key->cref, NULL, in, kCCBlockSizeCAST, out);
    
}

Changes to Source/API/CommonCryptor.c.

1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
|
|







1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
22
23
24
25
26
27
28




29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46










47

48
49

50








51
52
53

54
55
56

















57
58
59
60

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

78
79
80




















81

82





83
84



85





86
87




88






89





















90







91

92




93

94
95


96



97

98

99



100
101

102


103









104
105
106
107


108


109
110


111


112
113


114






115



116
117
118


119



120

121
122

123
124
125






126












127
128


129
130


131


132





133
134

135



136
137




138







139



140





141
142
143
144
145
146
147
148
149
150












151
152
153
154
155
156
157
158
159
160
161
162
163
164

165
166
167
168
169
170
171
172
173
174
 */

/*
 * CommonCryptor.c - common crypto context.
 *
 */





#include "CommonCryptor.h"
#include "CommonCryptorSPI.h"
#include "CommonCryptorPriv.h"
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <stddef.h>			/* for offsetof() */
#include "tomcrypt.h"
#include "rc4.h"
#include "pkcs7pad.h"
#include "ccdebug.h"

/* 
 * CommonCryptor's portion of a CCCryptorRef. 
 */


#define DEFAULT_CRYPTOR_MALLOC 4096












#define OPENCRYPT "Encrypt"
#define OPDECRYPT "Decrypt"










#define NOPADDING "OFF"
#define PKCS7PADDING "PKCS7"


/*
 * Convert a CommonCrypto alg into an LTC index, register LTC alg as a side-effect.
 */

















 
static int
ccGetAlgorithm(CCAlgorithm alg)
{

	switch(alg) {
		case kCCAlgorithmAES128:
		if(register_cipher(&aesedp_desc) == -1) return -1;
		return find_cipher("aesedp");
		case kCCAlgorithmDES:
		if(register_cipher(&des_desc) == -1) return -1;
		return find_cipher("des");
		case kCCAlgorithm3DES:
		if(register_cipher(&des3_desc) == -1) return -1;
		return find_cipher("3des");
		case kCCAlgorithmCAST:
		if(register_cipher(&cast5_desc) == -1) return -1;
		return find_cipher("cast5");
		case kCCAlgorithmRC2:
		if(register_cipher(&rc2_desc) == -1) return -1;
		return find_cipher("rc2");
		default:

		return -1;
	}
}




























static CCCryptorStatus
ccLTCErr(uint32_t err)



{





	switch(err) {
	case CRYPT_OK: return kCCSuccess;




	case CRYPT_ERROR: return -1;






	case CRYPT_NOP: return kCCSuccess;





























	case CRYPT_INVALID_KEYSIZE: return kCCParamError;

	case CRYPT_INVALID_ROUNDS: return kCCParamError;




	case CRYPT_FAIL_TESTVECTOR: return -1;


	case CRYPT_BUFFER_OVERFLOW: return kCCBufferTooSmall;


	case CRYPT_INVALID_PACKET: return kCCParamError;





	case CRYPT_INVALID_PRNGSIZE: return kCCParamError;

	case CRYPT_ERROR_READPRNG: return kCCParamError;




	case CRYPT_INVALID_CIPHER: return kCCParamError;

	case CRYPT_INVALID_HASH: return kCCParamError;


	case CRYPT_INVALID_PRNG: return kCCParamError;










	case CRYPT_MEM: return kCCBufferTooSmall;

	case CRYPT_PK_TYPE_MISMATCH: return kCCParamError;


	case CRYPT_PK_NOT_PRIVATE: return kCCParamError;



	case CRYPT_INVALID_ARG: return kCCParamError;


	case CRYPT_FILE_NOTFOUND: return kCCParamError;



	case CRYPT_PK_INVALID_TYPE: return kCCParamError;


	case CRYPT_PK_INVALID_SYSTEM: return kCCParamError;






	case CRYPT_PK_DUP: return kCCParamError;



	case CRYPT_PK_NOT_FOUND: return kCCParamError;
	case CRYPT_PK_INVALID_SIZE: return kCCParamError;



	case CRYPT_INVALID_PRIME_SIZE: return kCCParamError;



	case CRYPT_PK_INVALID_PADDING: return kCCParamError;


	case CRYPT_HASH_OVERFLOW: return kCCParamError;

	default: return -1;
	}
}




















/*


 Generally IVs are the same size as the blocksize of the cipher in use.
 This routine will use that value unless it's going to blow past the end


 of the cryptor IV buffer.  This is just a safety measure in case some


 upper level code is blindly triggering an IV reset for a cipher/mode





 combo that really wouldn't use the IV and may have a huge blocksize.
 */





#define CC_XZEROMEM(p, n)	memset((p), 0, (n))
#define CC_XMEMCPY(s1, s2, n) memcpy((s1), (s2), (n))












static void



ccSetIV(CCCryptor *cryptor, void *iv)





{
	uint32_t ivSize;
    
    ivSize = (cryptor->blocksize > CCMAXBUFFERSIZE) ? CCMAXBUFFERSIZE: cryptor->blocksize;
	if(iv == NULL) {
		CC_XZEROMEM(cryptor->iv, ivSize);
	} else {
    	CC_XMEMCPY(cryptor->iv, iv, ivSize);
	}
}













CCCryptorStatus CCCryptorCreate(
	CCOperation op,             /* kCCEncrypt, etc. */
	CCAlgorithm alg,            /* kCCAlgorithmDES, etc. */
	CCOptions options,          /* kCCOptionPKCS7Padding, etc. */
	const void *key,            /* raw key material */
	size_t keyLength,	
	const void *iv,             /* optional initialization vector */
	CCCryptorRef *cryptorRef)  /* RETURNED */
{
	CCCryptorStatus err;
	CCCompatCryptor *compat_cryptor = NULL;
	size_t dataUsed = 0;
	

	if((compat_cryptor = (CCCompatCryptor *)malloc(sizeof(CCCompatCryptor))) == NULL) return kCCMemoryFailure;
	err = CCCryptorCreateFromData( op, alg,  options, key,  keyLength, iv, compat_cryptor, sizeof(CCCompatCryptor), cryptorRef, &dataUsed); 
	if(err != kCCSuccess)  free(compat_cryptor);
	else compat_cryptor->weMallocd = true;
	return err;
}

CCCryptorStatus CCCryptorCreateFromData(
	CCOperation op,             /* kCCEncrypt, etc. */
	CCAlgorithm alg,            /* kCCAlgorithmDES, etc. */







>
>
>
>



|
<
|
<
<
<
<
<






|
>
>
>
>
>
>
>
>
>
>

>
|
<
>
|
>
>
>
>
>
>
>
>
|
<
|
>
|
|
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
<
<
>
|
|
<
|
|
<
|
|
<
|
|
<
<
|
<
<
<
>
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>

>
>
>
>
>
|
|
>
>
>
|
>
>
>
>
>
|
|
>
>
>
>
|
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
|
>
|
>
>
>
>
|
>
|
|
>
>
|
>
>
>
|
>
|
>
|
>
>
>
|
|
>
|
>
>
|
>
>
>
>
>
>
>
>
>
|
|
|
|
>
>
|
>
>
|
|
>
>
|
>
>
|
|
>
>
|
>
>
>
>
>
>
|
>
>
>
|
|

>
>
|
>
>
>
|
>
|
|
>
|
|
|
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
|
<
>
>
|
<
>
>
|
>
>
|
>
>
>
>
>
|
<
>
|
>
>
>
|
<
>
>
>
>

>
>
>
>
>
>
>
|
>
>
>
|
>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>














>
|

|







22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

37





38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

58
59
60
61
62
63
64
65
66
67
68

69
70
71
72

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90



91
92
93

94
95

96
97

98
99


100



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295

296
297
298

299
300
301
302
303
304
305
306
307
308
309
310

311
312
313
314
315
316

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
 */

/*
 * CommonCryptor.c - common crypto context.
 *
 */

// #define COMMON_CRYPTOR_FUNCTIONS

#include "ccMemory.h"
#include "ccdebug.h"
#include "CommonCryptor.h"
#include "CommonCryptorSPI.h"
#include "CommonCryptorPriv.h"
#include <dispatch/dispatch.h>

#include <dispatch/queue.h>






/* 
 * CommonCryptor's portion of a CCCryptorRef. 
 */


typedef struct cipherMode_t {
    dispatch_once_t init;
    struct ccmode_ecb* ecb;
    struct ccmode_cbc* cbc;
    struct ccmode_cfb* cfb;
    struct ccmode_cfb8* cfb8;
    struct ccmode_ctr* ctr;
    struct ccmode_ofb* ofb;
    struct ccmode_xts* xts;
    struct ccmode_gcm* gcm;
} cipherMode;

static cipherMode cipherModeTab[7][2];


static inline size_t ccGetCipherBlockSize(CCCryptor *ref)
{
    switch(ref->cipher) {
        case kCCAlgorithmAES128:    return kCCBlockSizeAES128;
        case kCCAlgorithmDES:       return kCCBlockSizeDES;  
        case kCCAlgorithm3DES:      return kCCBlockSize3DES;       
        case kCCAlgorithmCAST:      return kCCBlockSizeCAST;      
        case kCCAlgorithmRC4:       return 1;
        case kCCAlgorithmRC2:       return kCCBlockSizeRC2;
        case kCCAlgorithmBlowfish:  return kCCBlockSizeBlowfish;
        default: return kCCBlockSizeAES128;

    }
}



corecryptoMode getCipherMode(CCAlgorithm cipher, CCMode mode, CCOperation direction)
{
    for(int i = 0; i<2; i++) {
        dispatch_once(&(cipherModeTab[cipher][i].init), ^{
            cipherModeTab[cipher][i].ecb = ccmodeList[cipher][i].ecb();
            cipherModeTab[cipher][i].cbc = ccmodeList[cipher][i].cbc();
            cipherModeTab[cipher][i].cfb = ccmodeList[cipher][i].cfb();
            cipherModeTab[cipher][i].cfb8 = ccmodeList[cipher][i].cfb8();
            cipherModeTab[cipher][i].ctr = ccmodeList[cipher][i].ctr();
            cipherModeTab[cipher][i].ofb = ccmodeList[cipher][i].ofb();
#if defined(__i386__) || defined(__x86_64__)
            cipherModeTab[cipher][i].xts = ccmodeList[cipher][i].xts();
#else
            cipherModeTab[cipher][i].xts = NULL;
#endif
            cipherModeTab[cipher][i].gcm = ccmodeList[cipher][i].gcm();
        });
    }



    // printf("%lu Size %lu Blocksize\n\n", cipherModeTab[cipher][direction].ecb->size, cipherModeTab[cipher][direction].ecb->block_size);
    switch(mode) {
        case kCCModeECB: return (corecryptoMode) cipherModeTab[cipher][direction].ecb;

        case kCCModeCBC: return (corecryptoMode) cipherModeTab[cipher][direction].cbc;
        case kCCModeCFB: return (corecryptoMode) cipherModeTab[cipher][direction].cfb;

        case kCCModeCFB8: return (corecryptoMode) cipherModeTab[cipher][direction].cfb8;
        case kCCModeCTR: return (corecryptoMode) cipherModeTab[cipher][direction].ctr;

        case kCCModeOFB: return (corecryptoMode) cipherModeTab[cipher][direction].ofb;
        case kCCModeXTS: return (corecryptoMode) cipherModeTab[cipher][direction].xts;


        case kCCModeGCM: return (corecryptoMode) cipherModeTab[cipher][direction].gcm;



    }
    return (corecryptoMode) (struct ccmode_ecb*) NULL;
}

static CCCryptorStatus setCryptorCipherMode(CCCryptor *ref, CCAlgorithm cipher, CCMode mode, CCOperation direction)
{
    switch(mode) {
        case kCCModeECB: if((ref->symMode[direction].ecb = getCipherMode(cipher, mode, direction).ecb) == NULL) return kCCUnimplemented;
            ref->modeDesc = &ccecb_mode; break;
        case kCCModeCBC: if((ref->symMode[direction].cbc = getCipherMode(cipher, mode, direction).cbc) == NULL) return kCCUnimplemented;
            ref->modeDesc = &cccbc_mode; break;
        case kCCModeCFB: if((ref->symMode[direction].cfb = getCipherMode(cipher, mode, direction).cfb) == NULL) return kCCUnimplemented;
            ref->modeDesc = &cccfb_mode; break;
        case kCCModeCFB8: if((ref->symMode[direction].cfb8 = getCipherMode(cipher, mode, direction).cfb8) == NULL) return kCCUnimplemented;
            ref->modeDesc = &cccfb8_mode; break;
        case kCCModeCTR: if((ref->symMode[direction].ctr = getCipherMode(cipher, mode, direction).ctr) == NULL) return kCCUnimplemented;
            ref->modeDesc = &ccctr_mode; break;
        case kCCModeOFB: if((ref->symMode[direction].ofb = getCipherMode(cipher, mode, direction).ofb) == NULL) return kCCUnimplemented;
            ref->modeDesc = &ccofb_mode; break;
        case kCCModeXTS: if((ref->symMode[direction].xts = getCipherMode(cipher, mode, direction).xts) == NULL) return kCCUnimplemented;
            ref->modeDesc = &ccxts_mode; break;
        case kCCModeGCM: if((ref->symMode[direction].gcm = getCipherMode(cipher, mode, direction).gcm) == NULL) return kCCUnimplemented;
            ref->modeDesc = &ccgcm_mode; break;
        default: return kCCParamError;
    }
    return kCCSuccess;

}


static inline CCCryptorStatus ccSetupCryptor(CCCryptor *ref, CCAlgorithm cipher, CCMode mode, CCOperation direction, CCPadding padding)
{
    CCCryptorStatus retval;
    
    if(cipher > 6) return kCCParamError;
    if(direction > kCCBoth) return kCCParamError;
    if(cipher == kCCAlgorithmRC4) mode = kCCModeOFB;
    
    ref->mode = mode;
    CCOperation op = direction;
    if(ref->mode == kCCModeXTS || ref->mode == kCCModeECB || ref->mode == kCCModeCBC) op = kCCBoth;

    // printf("Cryptor setup - cipher %d mode %d direction %d padding %d\n", cipher, mode, direction, padding);
    switch(op) {
        case kCCEncrypt:
        case kCCDecrypt:
            if((retval = setCryptorCipherMode(ref, cipher, mode, op)) != kCCSuccess) return retval;
            if((ref->ctx[op].data = CC_XMALLOC(ref->modeDesc->mode_get_ctx_size(ref->symMode[op]))) == NULL) return kCCMemoryFailure;
            break;
        case kCCBoth:
            if((retval = setCryptorCipherMode(ref, cipher, mode, kCCEncrypt)) != kCCSuccess) return retval;
            if((ref->ctx[kCCEncrypt].data = CC_XMALLOC(ref->modeDesc->mode_get_ctx_size(ref->symMode[kCCEncrypt]))) == NULL) return kCCMemoryFailure;
            if((retval = setCryptorCipherMode(ref, cipher, mode, kCCDecrypt)) != kCCSuccess) return retval;
            if((ref->ctx[kCCDecrypt].data = CC_XMALLOC(ref->modeDesc->mode_get_ctx_size(ref->symMode[kCCDecrypt]))) == NULL) return kCCMemoryFailure;
            break;
    }
    
    switch(padding) {
        case ccNoPadding:
            ref->padptr = &ccnopad_pad;
            break;
        case ccPKCS7Padding:
            if(mode == kCCModeCBC)
                ref->padptr = &ccpkcs7_pad;
            else
                ref->padptr = &ccpkcs7_ecb_pad;
            break;
        case ccCBCCTS1:
            ref->padptr = &cccts1_pad;
            break;
        case ccCBCCTS2:
            ref->padptr = &cccts2_pad;
            break;
        case ccCBCCTS3:
            ref->padptr = &cccts3_pad;
            break;
        default:
            ref->padptr = &ccnopad_pad;
    }
    ref->cipher = cipher;
    ref->cipherBlocksize = ccGetCipherBlockSize(ref);
    ref->op = direction;
    ref->bufferPos = 0;
    ref->bytesProcessed = 0;
    return kCCSuccess;
}

#define OP4INFO(X) (((X)->op == 3) ? 0: (X)->op)

static inline size_t ccGetBlockSize(CCCryptor *ref)
{
    return ref->modeDesc->mode_get_block_size(ref->symMode[OP4INFO(ref)]);
}

static inline bool ccIsStreaming(CCCryptor *ref)
{
    
    return ref->modeDesc->mode_get_block_size(ref->symMode[ref->op]) == 1;
}

static inline CCCryptorStatus ccInitCryptor(CCCryptor *ref, const void *key, unsigned long key_len,
                                            const void *tweak_key, 
                                            const void *iv)
{
    size_t blocksize = ccGetCipherBlockSize(ref);
    if(!ref->modeDesc) return kCCParamError;
    uint8_t defaultIV[blocksize];
    
    if(iv == NULL) {
        CC_XZEROMEM(defaultIV, blocksize);
        iv = defaultIV;
    }
    
    CCOperation op = ref->op;
    
    // This will create both sides of the context/mode pairs for now.
    if(ref->mode == kCCModeXTS || ref->mode == kCCModeECB || ref->mode == kCCModeCBC) op = kCCBoth;
    
    switch(op) {
        case kCCEncrypt:
        case kCCDecrypt:
            ref->modeDesc->mode_setup(ref->symMode[ref->op], iv, key, key_len, tweak_key, 0, 0, ref->ctx[ref->op]);
            break;
        case kCCBoth:
            ref->modeDesc->mode_setup(ref->symMode[kCCEncrypt], iv, key, key_len, tweak_key, 0, 0, ref->ctx[kCCEncrypt]);
            ref->modeDesc->mode_setup(ref->symMode[kCCDecrypt], iv, key, key_len, tweak_key, 0, 0, ref->ctx[kCCDecrypt]);
            break;
    }
    return kCCSuccess;    
}

static inline CCCryptorStatus ccDoEnCrypt(CCCryptor *ref, const void *dataIn, size_t dataInLength, void *dataOut)
{
    if(!ref->modeDesc->mode_encrypt) return kCCParamError;
    ref->modeDesc->mode_encrypt(ref->symMode[kCCEncrypt], dataIn, dataOut, dataInLength, ref->ctx[kCCEncrypt]);
    return kCCSuccess;
}

static inline CCCryptorStatus ccDoDeCrypt(CCCryptor *ref, const void *dataIn, size_t dataInLength, void *dataOut)
{
    if(!ref->modeDesc->mode_decrypt) return kCCParamError;
    ref->modeDesc->mode_decrypt(ref->symMode[kCCDecrypt], dataIn, dataOut, dataInLength, ref->ctx[kCCDecrypt]);
    return kCCSuccess;
}

static inline CCCryptorStatus ccDoEnCryptTweaked(CCCryptor *ref, const void *dataIn, size_t dataInLength, void *dataOut, const void *tweak)
{
    if(!ref->modeDesc->mode_encrypt_tweaked) return kCCParamError;
    ref->modeDesc->mode_encrypt_tweaked(ref->symMode[kCCEncrypt], dataIn, dataOut, dataInLength, tweak, ref->ctx[kCCEncrypt]);
    return kCCSuccess;
}

static inline CCCryptorStatus ccDoDeCryptTweaked(CCCryptor *ref, const void *dataIn, size_t dataInLength, void *dataOut, const void *tweak)
{
    if(!ref->modeDesc->mode_decrypt_tweaked) return kCCParamError;
    ref->modeDesc->mode_decrypt_tweaked(ref->symMode[kCCDecrypt], dataIn, dataOut, dataInLength, tweak, ref->ctx[kCCDecrypt]);
    return kCCSuccess;
}



static inline CCCryptorStatus ccGetIV(CCCryptor *ref, void *iv, size_t *ivLen)
{
    if(ref->modeDesc->mode_getiv == NULL) return kCCParamError;
    if(ref->modeDesc->mode_getiv(ref->symMode[OP4INFO(ref)], iv, ivLen, ref->ctx[OP4INFO(ref)]) != 0) return kCCMemoryFailure;
    return kCCSuccess;
}

static inline CCCryptorStatus ccSetIV(CCCryptor *ref, void *iv, size_t ivLen)
{
    if(ref->modeDesc->mode_setiv == NULL) return kCCParamError;
    if(ref->modeDesc->mode_setiv(ref->symMode[OP4INFO(ref)], iv, ivLen, ref->ctx[OP4INFO(ref)]) != 0) return kCCMemoryFailure;
    return kCCSuccess;
}



static inline void ccClearCryptor(CCCryptor *ref)
{
    CC_XZEROMEM(ref->buffptr, sizeof(ref->buffptr));
    CCOperation op = ref->op;
    
    // This will clear both sides of the context/mode pairs for now.
    if(ref->mode == kCCModeXTS || ref->mode == kCCModeECB || ref->mode == kCCModeCBC) op = kCCBoth;
    switch(op) {
        case kCCEncrypt:
        case kCCDecrypt:
            CC_XZEROMEM(ref->ctx[ref->op].data, ref->modeDesc->mode_get_ctx_size(ref->symMode[ref->op]));
            CC_XFREE(ref->ctx[ref->op].data, ref->modeDesc->mode_get_ctx_size(ref->symMode[ref->op]));
            break;
        case kCCBoth:
            for(int i = 0; i<2; i++) {
                CC_XZEROMEM(ref->ctx[i].data, ref->modeDesc->mode_get_ctx_size(ref->symMode[i]));
                CC_XFREE(ref->ctx[i].data, ref->modeDesc->mode_get_ctx_size(ref->symMode[i]));
            }

            break;
    }
    ref->cipher = 0;

    ref->mode = 0;
    ref->op = 0;
    ref->bufferPos = 0;
    ref->bytesProcessed = 0;
}

static inline CCCryptorStatus ccEncryptPad(CCCryptor	*cryptor, void *buf, size_t *moved)
{
    if(cryptor->padptr->encrypt_pad(cryptor->ctx[cryptor->op], cryptor->modeDesc, cryptor->symMode[cryptor->op], cryptor->buffptr, cryptor->bufferPos, buf, moved)) return kCCDecodeError;
    return kCCSuccess;
}


static inline CCCryptorStatus ccDecryptPad(CCCryptor	*cryptor, void *buf, size_t *moved)
{
    if(cryptor->padptr->decrypt_pad(cryptor->ctx[cryptor->op], cryptor->modeDesc, cryptor->symMode[cryptor->op], cryptor->buffptr, cryptor->bufferPos, buf, moved)) return kCCDecodeError;
    return kCCSuccess;
}


static inline size_t ccGetReserve(CCCryptor *cryptor)
{
    return cryptor->padptr->padreserve(cryptor->op == kCCEncrypt, cryptor->modeDesc, cryptor->symMode[cryptor->op]);
}

static inline size_t ccGetPadlen(CCCryptor *cryptor)
{
    return cryptor->padptr->padlen(cryptor->op == kCCEncrypt, cryptor->modeDesc, cryptor->symMode[cryptor->op], cryptor->buffptr);
}



static uint8_t *
ccGetBytesAligned64(uint8_t *fromptr, uint32_t *bytesused)
{
	uint8_t *retval;
    
	retval = fromptr;
	if((uintptr_t) fromptr % 8) retval = (uint8_t *)(((uintptr_t) fromptr / 8) * 8 + 8);
	*bytesused = retval - fromptr;
	return retval;
}














static int ccAddBuff(CCCryptor *cryptor, const void *dataIn, size_t dataInLength)
{
    CC_XMEMCPY((char *) cryptor->buffptr + cryptor->bufferPos, dataIn, dataInLength);
    cryptor->bufferPos += dataInLength;
    return dataInLength;
}



CCCryptorStatus CCCryptorCreate(
	CCOperation op,             /* kCCEncrypt, etc. */
	CCAlgorithm alg,            /* kCCAlgorithmDES, etc. */
	CCOptions options,          /* kCCOptionPKCS7Padding, etc. */
	const void *key,            /* raw key material */
	size_t keyLength,	
	const void *iv,             /* optional initialization vector */
	CCCryptorRef *cryptorRef)  /* RETURNED */
{
	CCCryptorStatus err;
	CCCompatCryptor *compat_cryptor = NULL;
	size_t dataUsed = 0;
	
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if((compat_cryptor = (CCCompatCryptor *)CC_XMALLOC(sizeof(CCCompatCryptor))) == NULL) return kCCMemoryFailure;
	err = CCCryptorCreateFromData( op, alg,  options, key,  keyLength, iv, compat_cryptor, sizeof(CCCompatCryptor), cryptorRef, &dataUsed); 
	if(err != kCCSuccess)  CC_XFREE(compat_cryptor, sizeof(CCCompatCryptor));
	else compat_cryptor->weMallocd = true;
	return err;
}

CCCryptorStatus CCCryptorCreateFromData(
	CCOperation op,             /* kCCEncrypt, etc. */
	CCAlgorithm alg,            /* kCCAlgorithmDES, etc. */
184
185
186
187
188
189
190

191
192
193
194
195
196
197
198

199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216


















































































































































217
218
219
220
221
222
223
224
225

226
227
228
229
230
231
232












233




234




235
236
237
238
239
240
241
242
243
244
245
246

247
248

249
250

251


252
253
254
255
256
257
258
259
260
261
262



263
264
265
266
267
268
269
270
271
272

273
274
275
276
277
278

279
280
281
282
283
284
285

286

287





288
289

290
291



292
293

294
295
296
297
298


299
300
301
302
303
304
305
306

307
308

309
310
311


312
313
314


315
316





317


318
319
320
321
322
323






324
325
326


327





328

329

330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347


348
349
350
351
352
353


354
355
356

357
358
359
360
361
362
363
364
365
366
367
368
369







370



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390

391



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406

407

408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426

427
428
429
430
431
432
433
434
435



436



437
438
439
440
441
442
443
444
445
446
447
448
449

450




































451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
	CCMode			mode;
    CCPadding		padding;		
	const void 		*tweak;
	size_t 			tweakLength;	
	int				numRounds;
	CCModeOptions 	modeOptions;
    

	/* Determine mode from options - old call only supported ECB and CBC 
     we treat RC4 as a "mode" in that it's the only streaming cipher
     currently supported 
     */
	
	mode = kCCModeCBC;
    if(alg == kCCAlgorithmRC4) mode = kCCModeRC4;
    else if(options & kCCOptionECBMode) mode = kCCModeECB;

    
	/* Determine padding from options - only PKCS7 was available */
    padding = ccDefaultPadding;
	if(options & kCCOptionPKCS7Padding) padding = ccPKCS7Padding;
    
	/* No tweak was ever used */
   	tweak = NULL;
    tweakLength = 0;
    
	/* default rounds */
    numRounds = 0;
    
	/* No mode options needed */
    modeOptions = 0;
    
	return CCCryptorCreateFromDataWithMode(op, mode, alg, padding, iv, key, keyLength, tweak, tweakLength, numRounds, modeOptions, data, dataLength, cryptorRef, dataUsed);
	
		}



















































































































































CCCryptorStatus CCCryptorRelease(
	CCCryptorRef cryptorRef)
{
	uint32_t err;
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor *cryptor;
	uint32_t weMallocd;
    

	if(cryptorRef == NULL) return kCCSuccess;
    cryptor = compat_cryptor->cryptor;
	weMallocd = compat_cryptor->weMallocd;
	
	if(cryptor->modeptr->mode_done) cryptor->modeptr->mode_done(cryptor->ctx);
    
	memset(cryptor, 0, CCCRYPTOR_SIZE);












    free(cryptor);




    if(weMallocd) free(compat_cryptor);





	return kCCSuccess;
	}


CCCryptorStatus CCCryptorUpdate(CCCryptorRef cryptorRef, const void *dataIn, size_t dataInLength, void *dataOut, size_t dataOutAvailable, size_t *dataOutMoved)
{
	CCCryptorStatus	retval;
	char *inp, *outp, *bufp;
	size_t inlen, outlen, movecnt, blocksize;
	int willneed;
	int	done = 0;

    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;

	
	if(compat_cryptor == NULL)  return kCCParamError;

    cryptor = compat_cryptor->cryptor;


    
	if(cryptor == NULL)  return kCCParamError;
    void *checkedDataIn = dataIn;
    if (checkedDataIn == NULL) checkedDataIn = "";
	if(cryptor->bufStrat == ccStreaming) {		
		if(dataOutAvailable < dataInLength) return kCCBufferTooSmall;
		if(cryptor->op == kCCEncrypt) {
			if((retval = ccLTCErr(cryptor->modeptr->mode_encrypt(dataIn, dataOut, dataInLength, cryptor->ctx))) != kCCSuccess) return retval;
		} else {
			if((retval = ccLTCErr(cryptor->modeptr->mode_decrypt(dataIn, dataOut, dataInLength, cryptor->ctx))) != kCCSuccess) return retval;
	}



		cryptor->bytesProcessed += dataInLength;
		if(dataOutMoved) *dataOutMoved = dataInLength;
	return kCCSuccess;
}

	if(!(cryptor->bufStrat & ccStreamMode)) {	
			return kCCParamError; // ZZZ Need an invalid mode error before this goes public.
	}
	
	blocksize = cryptor->blocksize;

	willneed = ((cryptor->bufferPos + dataInLength) / blocksize) * blocksize;
	if(cryptor->padding == ccPKCS7Padding) willneed -= blocksize;
	if(willneed < 0) willneed = 0;
	if(dataOutAvailable < willneed) {
		ccdebug(ASL_LEVEL_ERR, "Pos %d InLength %d Needed %d Provided %d\n", cryptor->bufferPos, dataInLength, willneed, dataOutAvailable); 
		return kCCBufferTooSmall;

	}
	
	inp = (char *) dataIn;
	outp = (char *) dataOut;
	inlen = dataInLength;
	outlen = 0;
	bufp = cryptor->buffptr;

    

    if(cryptor->bufferPos == 0 && cryptor->padding != ccPKCS7Padding 





       /* && (((size_t) dataIn % 4) == 0) && (((size_t) dataOut % 4) == 0) */  ) { 
        // No Padding, not buffering, aligned pointers don't appear necessary for the entry into the x86 optimized routines. */

        
        size_t chunklen;



                
        chunklen = (dataInLength / cryptor->blocksize) * cryptor->blocksize;

        
        if(chunklen) {
            if(cryptor->op == kCCEncrypt) {
                if((retval = ccLTCErr(cryptor->modeptr->mode_encrypt(inp, outp, chunklen, cryptor->ctx))) != kCCSuccess) return retval;
            } else {


                if((retval = ccLTCErr(cryptor->modeptr->mode_decrypt(inp, outp, chunklen, cryptor->ctx))) != kCCSuccess) return retval;
            }
            inp += chunklen;
            outp += chunklen;
            inlen -= chunklen;
            outlen += chunklen;
            done = (inlen == 0);
        }

        if(done) {
            *dataOutMoved = outlen;

            return kCCSuccess;
	}
    }


    
    /* fprintf(stderr, "CRYPTORUPDATE BufferPos %d Padding is %s dataIn %16llx dataOut %16llx %lld\n",
           (int) cryptor->bufferPos, (cryptor->padding != ccPKCS7Padding) ? "None": "PKCS7",


           (unsigned long) dataIn, (unsigned long) dataOut,
            (unsigned long) dataInLength); */









	while(!done) {
		// determine how much to move to fill buffer

		movecnt = blocksize - cryptor->bufferPos;
		if(movecnt > inlen) movecnt = inlen;






		
		if(movecnt || cryptor->bufferPos == blocksize) {
			memmove(bufp + cryptor->bufferPos, inp, movecnt);


			inp += movecnt;





			inlen -= movecnt;

			cryptor->bufferPos += movecnt;

			
			if(cryptor->op == kCCEncrypt) {
				if(cryptor->bufferPos == blocksize) {
					if((retval = ccLTCErr(cryptor->modeptr->mode_encrypt(bufp, outp, blocksize, cryptor->ctx))) != kCCSuccess) return retval;
					cryptor->bytesProcessed += blocksize;
					cryptor->bufferPos = 0;
					outp += blocksize;
					outlen += blocksize;
					dataOutAvailable -= blocksize;
				} else {
					done = 1;
				}
			} else {
				if(cryptor->bufferPos == blocksize) {
					/* Need to delay by one block to know when we're processing a padded block if padding is enabled */
					if(cryptor->padding == ccPKCS7Padding && inlen == 0) done = 1; 
	else {
						if((retval = ccLTCErr(cryptor->modeptr->mode_decrypt(bufp, outp, blocksize, cryptor->ctx))) != kCCSuccess) return retval;


						cryptor->bytesProcessed += blocksize;
						cryptor->bufferPos = 0;
						outp += blocksize;
						outlen += blocksize;
						dataOutAvailable -= blocksize;
	}


	}
}
		} else done = 1;

	}
	*dataOutMoved = outlen;
	return kCCSuccess;
}



CCCryptorStatus CCCryptorFinal(
	CCCryptorRef cryptorRef,
	void *dataOut,			/* data RETURNED here */
	size_t dataOutAvailable,
	size_t *dataOutMoved)		/* number of bytes written */
{







	CCCryptorStatus	retval;



	char *bufp;
	size_t blocksize, moved;
	uint8_t padval;
	char tmpbuf[ccMaxCipherBlockSize];
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;

    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
	if(cryptor == NULL) return kCCParamError;
	if(dataOutMoved) *dataOutMoved = 0;
	if(cryptor->bufStrat == ccStreaming) return kCCSuccess;

	blocksize = cryptor->blocksize;
	bufp = cryptor->buffptr;

	if(cryptor->op == kCCEncrypt) {
		if(cryptor->padding == ccPKCS7Padding) {
			padval = pkcs7_pad(bufp, blocksize, cryptor->bufferPos);
			moved = cryptor->bufferPos + padval;

			if(dataOutAvailable < moved) return kCCBufferTooSmall;



			if((retval = ccLTCErr(cryptor->modeptr->mode_encrypt(bufp, (char *) dataOut, moved, cryptor->ctx))) != kCCSuccess) return retval;
			*dataOutMoved = moved;
			cryptor->bytesProcessed += moved;
		}
		cryptor->bufferPos = 0;
	} else if(cryptor->op == kCCDecrypt) {
	  if(cryptor->padding == ccPKCS7Padding) {
			if(cryptor->bufferPos != blocksize) {
				return kCCAlignmentError;
			}
		   if((retval = ccLTCErr(cryptor->modeptr->mode_decrypt(bufp, tmpbuf, blocksize, cryptor->ctx))) != kCCSuccess) return retval;
			if((moved = pkcs7_unpadlen(tmpbuf, blocksize)) == -1) {
				return kCCAlignmentError;
			}
			if(dataOutAvailable < moved) return kCCBufferTooSmall;

			*dataOutMoved = moved;

			cryptor->bytesProcessed += *dataOutMoved;
			memmove((char *) dataOut, tmpbuf, *dataOutMoved);
	}
	} else /* Block I/O */ {
		// Nothing for now.  Block I/O will go here.
	}
	return kCCSuccess;
}

size_t CCCryptorGetOutputLength(
	CCCryptorRef cryptorRef,
	size_t inputLength,
	bool final)
{
	size_t retval;
	size_t totallength;
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
	

    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
	
	if(cryptor == NULL) return kCCParamError;
	totallength = cryptor->bufferPos + inputLength;
	if((cryptor->bufStrat == ccStreaming) || (cryptor->padding == 0)) retval = totallength;
	else if(cryptor->op == kCCEncrypt) retval = (totallength/cryptor->blocksize + 1) * cryptor->blocksize;
	else retval = totallength;
	ccdebug(ASL_LEVEL_ERR, " InputLength %d  Final is %s  OutputLength %d\n", inputLength, (final = true) ? "TRUE": "FALSE", retval);



	return retval;



}

/*
 * This routine needs to reset both the buffer position and the IV.
 * If the IV isn't used, don't attempt to reset it (RC4 is an example).
 */
 
CCCryptorStatus CCCryptorReset(
	CCCryptorRef cryptorRef,
	const void *iv)
{
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;

    




































    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    
	/* <rdar://problem/8552731> need to reset buffering position. */
	cryptor->bufferPos = 0;
    cryptor->bytesProcessed = 0;
	/* <rdar://problem/8833770> (and others) Don't reset the IV if a streaming cipher is being used. */ 
	if(cryptor->blocksize == 1) return CRYPT_OK; // RC4
    ccSetIV(cryptor, iv);
    
    /* Make sure the mode has a "setter" for the IV - if not, we're done. */
    if(cryptor->modeptr->mode_setiv == NULL) 
    	return kCCSuccess;

	return ccLTCErr(cryptor->modeptr->mode_setiv(cryptor->iv, cryptor->ctx->cbcContext.blocklen, cryptor->ctx));
}


/* 
 * One-shot is mostly service provider independent, except for the
 * dataOutLength check.
 */
CCCryptorStatus CCCrypt(







>

|
|
|
<
<


>


|

|











|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>









>



|
|

|
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
|
>
>
>
>
|
|
|


|

|
|
|
<
|
>
|
|
>
|
<
>
|
>
>
|
|
<
<
<
|
<
<
<
<
|
>
>
>
|
<
<
|
|
<
<
|
|
|
>
|
|
<
<
<
<
>
|
|
<
<
|
<
<
>

>
|
>
>
>
>
>
|
<
>
|
<
>
>
>
|
<
>
|
<
|
|
|
>
>
|
|
<
<
|
<
|
|
>
|
<
>
|
|
<
>
>
|
|
|
>
>
|
|
>
>
>
>
>
|
>
>
|
<
<
|
|
|
>
>
>
>
>
>
|
|
|
>
>
|
>
>
>
>
>
|
>
|
>
|
|
|
<
<
|
|
|
<
<
<
|
<
<
<
<
<
<
>
>
|
|
|
<
|
|
>
>

|
<
>
|
<
|






|



>
>
>
>
>
>
>

>
>
>
|
|

|
|
|
|
<
<
<

<

<
|

|
|
<
<
>
|
>
>
>
|
|
<
|

|
|
|
<
<
|
|
|
|
|
>
|
>

|
|
<
<










<



>


|
<
|
|
|
|
|
>
>
>
|
>
>
>
|
|
<
<
<
<
|






>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



<
|
<
<
<
|
|
<
<
<

<
<







395
396
397
398
399
400
401
402
403
404
405
406


407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622

623
624
625
626
627
628

629
630
631
632
633
634



635




636
637
638
639
640


641
642


643
644
645
646
647
648




649
650
651


652


653
654
655
656
657
658
659
660
661
662

663
664

665
666
667
668

669
670

671
672
673
674
675
676
677


678

679
680
681
682

683
684
685

686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703


704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730


731
732
733



734






735
736
737
738
739

740
741
742
743
744
745

746
747

748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776



777

778

779
780
781
782


783
784
785
786
787
788
789

790
791
792
793
794


795
796
797
798
799
800
801
802
803
804
805


806
807
808
809
810
811
812
813
814
815

816
817
818
819
820
821
822

823
824
825
826
827
828
829
830
831
832
833
834
835
836




837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884

885



886
887



888


889
890
891
892
893
894
895
	CCMode			mode;
    CCPadding		padding;		
	const void 		*tweak;
	size_t 			tweakLength;	
	int				numRounds;
	CCModeOptions 	modeOptions;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	/* Determine mode from options - old call only supported ECB and CBC 
       we treat RC4 as a "mode" in that it's the only streaming cipher
       currently supported 
    */


    if(alg == kCCAlgorithmRC4) mode = kCCModeRC4;
    else if(options & kCCOptionECBMode) mode = kCCModeECB;
	else mode = kCCModeCBC;
    
	/* Determine padding from options - only PKCS7 was available */
    padding = ccNoPadding;
	if(options & kCCOptionPKCS7Padding) padding = ccPKCS7Padding;
   
	/* No tweak was ever used */
   	tweak = NULL;
    tweakLength = 0;
    
	/* default rounds */
    numRounds = 0;
    
	/* No mode options needed */
    modeOptions = 0;
    
	return CCCryptorCreateFromDataWithMode(op, mode, alg, padding, iv, key, keyLength, tweak, tweakLength, numRounds, modeOptions, data, dataLength, cryptorRef, dataUsed);
}

/* This version mallocs the CCCryptorRef */

CCCryptorStatus CCCryptorCreateWithMode(
	CCOperation 	op,				/* kCCEncrypt, kCCEncrypt, kCCBoth (default for BlockMode) */
	CCMode			mode,
	CCAlgorithm		alg,
	CCPadding		padding,		
	const void 		*iv,			/* optional initialization vector */
	const void 		*key,			/* raw key material */
	size_t 			keyLength,	
	const void 		*tweak,			/* raw tweak material */
	size_t 			tweakLength,	
	int				numRounds,		/* 0 == default */
	CCModeOptions 	options,
	CCCryptorRef	*cryptorRef)	/* RETURNED */
{
	CCCryptorStatus err;
	CCCompatCryptor *compat_cryptor = NULL;
	size_t dataUsed = 0;
	
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if((compat_cryptor = (CCCompatCryptor *)CC_XMALLOC(sizeof(CCCompatCryptor))) == NULL) return kCCMemoryFailure;
	err = CCCryptorCreateFromDataWithMode( op, mode, alg, padding, iv, key,  keyLength, tweak, tweakLength, numRounds, options, compat_cryptor, DEFAULT_CRYPTOR_MALLOC, cryptorRef, &dataUsed); 
	if(err != kCCSuccess)  CC_XFREE(compat_cryptor, sizeof(CCCompatCryptor));
	else compat_cryptor->weMallocd = true;
	return err;
}

#define KEYALIGNMENT (sizeof(int)-1)

CCCryptorStatus CCCryptorCreateFromDataWithMode(
	CCOperation 	op,				/* kCCEncrypt, kCCEncrypt, kCCBoth (default for BlockMode) */
	CCMode			mode,
	CCAlgorithm		alg,
	CCPadding		padding,		
	const void 		*iv,			/* optional initialization vector */
	const void 		*key,			/* raw key material */
	size_t 			keyLength,	
	const void 		*tweak,			/* raw tweak material */
	size_t 			tweakLength,	
	int				numRounds,
	CCModeOptions 	options,
	const void		*data,			/* caller-supplied memory */
	size_t			dataLength,		/* length of data in bytes */
	CCCryptorRef	*cryptorRef,	/* RETURNED */
	size_t			*dataUsed)		/* optional, RETURNED */
{
	CCCryptorStatus retval = kCCSuccess;
	CCCryptor *cryptor = NULL;
    CCCompatCryptor *compat_cryptor = NULL;
	int	needed, needed2aligncryptor;
    uint8_t *alignedKey = NULL;

    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering Op: %d Mode: %d Cipher: %d Padding: %d\n", op, mode, alg, padding);

    // For now we're mapping these two AES selectors to the stock one.
    if(alg == kCCAlgorithmAES128NoHardware || alg == kCCAlgorithmAES128WithHardware) 
        alg = kCCAlgorithmAES128;
    
    /* corecrypto only implements CTR_BE.  No use of CTR_LE was found so we're marking
       this as unimplemented for now.  Also in Lion this was defined in reverse order.
       See <rdar://problem/10306112> */
    
    if(mode == kCCModeCTR && options != kCCModeOptionCTR_BE) {
        CC_DEBUG_LOG(ASL_LEVEL_ERR, "Mode is CTR, but options isn't BE\n", op, mode, alg, padding);
        return kCCUnimplemented;
    }

    // validate pointers
	if((data == NULL) || (cryptorRef == NULL) || (key == NULL)) {
		CC_DEBUG_LOG(ASL_LEVEL_ERR, "bad arguments\n", 0);
		return kCCParamError;
	}
    
    /*
     * Some implementations are sensitive to keys not being 4 byte aligned.
     * We'll move the key into an aligned buffer for the call to setup
     * the key schedule.
     */
    
    if((intptr_t) key & KEYALIGNMENT) {
        if((alignedKey = CC_XMALLOC(keyLength)) == NULL) {
            return kCCMemoryFailure;
        }
        CC_XMEMCPY(alignedKey, key, keyLength);
        key = alignedKey;
    }
    

	/* Get Space for Cryptor Structure */	
	compat_cryptor = (CCCompatCryptor *) ccGetBytesAligned64((uint8_t *)data, &needed2aligncryptor);
    needed = needed2aligncryptor + sizeof(CCCompatCryptor);
    if(dataUsed != NULL) *dataUsed = needed;

	if (needed > dataLength) {
		if(dataUsed != NULL) *dataUsed += 16; /* in case it's not on a doubleword boundary */
		CC_DEBUG_LOG(ASL_LEVEL_ERR, "Needed %d Have %d\n", needed, dataLength);
        retval = kCCBufferTooSmall;
        goto out;
	}
    compat_cryptor->weMallocd = false;
    
    if((cryptor = (CCCryptor *)CC_XMALLOC(DEFAULT_CRYPTOR_MALLOC)) == NULL) {
        retval = kCCMemoryFailure;
        goto out;
    }
	compat_cryptor->cryptor = cryptor;
		
	*cryptorRef = compat_cryptor;
        
    if((retval = ccSetupCryptor(cryptor, alg, mode, op, padding)) != kCCSuccess) {
        printf("Failed to setup Cryptor struct with alg/mode %d\n", retval);
        goto out;
    }
    
    if((retval = ccInitCryptor(cryptor, key, keyLength, tweak, iv)) != kCCSuccess) {
        printf("Failed to init Cryptor %d\n", retval);
        goto out;
    }


out:
    // Things to destroy if setup failed
    if(retval) {
        *cryptorRef = NULL;
        if(compat_cryptor) compat_cryptor->cryptor = NULL;
        if(cryptor) {
            CC_XZEROMEM(cryptor, DEFAULT_CRYPTOR_MALLOC);
            CC_XFREE(cryptor, DEFAULT_CRYPTOR_MALLOC);
        }
    } else {
        // printf("Blocksize = %d mode = %d pad = %d\n", ccGetBlockSize(cryptor), cryptor->mode, padding);
    }
    
    // Things to destroy all the time
    if(alignedKey) {
        CC_XZEROMEM(alignedKey, keyLength);
        CC_XFREE(alignedKey, keyLength);
    }
    
    return retval;
}





CCCryptorStatus CCCryptorRelease(
	CCCryptorRef cryptorRef)
{
	uint32_t err;
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor *cryptor;
	uint32_t weMallocd;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(cryptorRef == NULL) return kCCSuccess;
    cryptor = compat_cryptor->cryptor;
	weMallocd = compat_cryptor->weMallocd;
    
    ccClearCryptor(cryptor);
    
	CC_XMEMSET(cryptor, 0, CCCRYPTOR_SIZE);
    CC_XFREE(cryptor, DEFAULT_CRYPTOR_MALLOC);
	if(weMallocd)  CC_XFREE(compat_cryptor, sizeof(CCCompatCryptor));
	return kCCSuccess;
}

#define FULLBLOCKSIZE(X,BLOCKSIZE) (((X)/(BLOCKSIZE))*BLOCKSIZE)
#define FULLBLOCKREMAINDER(X,BLOCKSIZE) ((X)%(BLOCKSIZE))

static CCCryptorStatus ccSimpleUpdate(CCCryptor *cryptor, const void *dataIn, size_t dataInLength, void **dataOut, size_t *dataOutAvailable, size_t *dataOutMoved)
{		
	CCCryptorStatus	retval;
    if(dataOutAvailable < dataInLength) return kCCBufferTooSmall;
    if(cryptor->op == kCCEncrypt) {
        if((retval = ccDoEnCrypt(cryptor, dataIn, dataInLength, *dataOut)) != kCCSuccess) return retval;
    } else {
        if((retval = ccDoDeCrypt(cryptor, dataIn, dataInLength, *dataOut)) != kCCSuccess) return retval;
    }

    cryptor->bytesProcessed += dataInLength;
    if(dataOutMoved) *dataOutMoved += dataInLength;
    *dataOut += dataInLength;
    *dataOutAvailable -= dataInLength;
    
    return kCCSuccess;
}


static CCCryptorStatus ccBlockUpdate(CCCryptor *cryptor, const void *dataIn, size_t dataInLength, void *dataOut, size_t *dataOutAvailable, size_t *dataOutMoved)
{
    CCCryptorStatus retval;
	uint32_t encrypting = (cryptor->op == kCCEncrypt);
    size_t blocksize = ccGetCipherBlockSize(cryptor);

    size_t reserve = ccGetReserve(cryptor);
    size_t buffsize = (reserve) ? reserve: blocksize; /* minimum buffering is a block */
    size_t dataCount = cryptor->bufferPos + dataInLength; /* Total amount of data we have "in hand" to process now. */
    size_t dataCountToHold, dataCountToProcess;
    size_t remainder, movecnt;
    

    /* This is a simple optimization */
    if(reserve == 0 && cryptor->bufferPos == 0 && (dataInLength % blocksize) == 0) { // No Padding, not buffering, even blocks
        // printf("simple processing\n");
    	return ccSimpleUpdate(cryptor, dataIn, dataInLength, &dataOut, &dataOutAvailable, dataOutMoved);
    }
    



    /* From this point on we're dealing with a Block Cipher with Block oriented I/O




     
     We always fallback to buffering once we're processing non-block aligned data.
     If the data inputs result in data becoming block aligned once again we can 
     move back to block aligned I/O - even if it's only for partial processing
     of the data supplied to this routine.


     
     */


    
    if(dataCount <= reserve) {
    	dataCountToHold = dataCount;
    } else {
    	remainder = FULLBLOCKREMAINDER(dataCount, blocksize);
		dataCountToHold = buffsize - blocksize + remainder;




        dataCountToHold = (remainder) ? dataCountToHold: reserve;
    }
    


    dataCountToProcess = dataCount - dataCountToHold;


    // printf("DataCount %d Processing %d Holding %d\n", dataCount, dataCountToProcess, dataCountToHold);
    
    if(dataCountToProcess > 0) {
    	if(cryptor->bufferPos == 0) {
        	// printf("CCCryptorUpdate checkpoint 0\n");
        	/* nothing to do yet */
    	} else if(cryptor->bufferPos < dataCountToProcess) {
        	// printf("CCCryptorUpdate checkpoint 1\n");
            movecnt = blocksize - (cryptor->bufferPos % blocksize);
            ccAddBuff(cryptor, dataIn, movecnt);

            dataIn += movecnt; dataInLength -= movecnt;
            

         	// printf("CCCryptorUpdate checkpoint 1.1 bufpos = %d\n", (int) cryptor->bufferPos);
           	if((retval = ccSimpleUpdate(cryptor, cryptor->buffptr, cryptor->bufferPos, &dataOut, &dataOutAvailable, dataOutMoved)) != kCCSuccess) {
                return retval;
        	}

			// printf("CCCryptorUpdate checkpoint 1.2\n");
            

			dataCountToProcess -= cryptor->bufferPos;
        	cryptor->bufferPos = 0;
        } else if(cryptor->bufferPos == dataCountToProcess) {
        	// printf("CCCryptorUpdate checkpoint 2\n");
			if((retval = ccSimpleUpdate(cryptor, cryptor->buffptr, cryptor->bufferPos, &dataOut, &dataOutAvailable, dataOutMoved)) != kCCSuccess) {
                return retval;
        	}


			dataCountToProcess -= cryptor->bufferPos;

        	cryptor->bufferPos = 0;
        } else /* (cryptor->bufferPos > dataCountToProcess) */ {
         	// printf("CCCryptorUpdate checkpoint 3\n");
       		if(dataCountToHold) {

            	// printf("CCCryptorUpdate bad calculation 1\n");
                return kCCDecodeError;
            }

			if((retval = ccSimpleUpdate(cryptor, cryptor->buffptr, dataCountToProcess, &dataOut, &dataOutAvailable, dataOutMoved)) != kCCSuccess) {
                return retval;
        	}
            cryptor->bufferPos = reserve - dataCountToProcess;
            memmove(cryptor->buffptr, ((uint8_t *) cryptor->buffptr)+ dataCountToProcess, cryptor->bufferPos);
            return kCCSuccess;
        }
        
        if(dataCountToProcess > 0) {
         	// printf("CCCryptorUpdate checkpoint 4\n");
   			movecnt = FULLBLOCKREMAINDER(dataCountToProcess, blocksize);
            if(movecnt) {
            	// printf("CCCryptorUpdate bad calculation 2\n");
                return kCCDecodeError;
            }
        	if((retval = ccSimpleUpdate(cryptor, dataIn, dataCountToProcess, &dataOut, &dataOutAvailable, dataOutMoved)) != kCCSuccess) return retval;
        	dataIn += dataCountToProcess; dataInLength -= dataCountToProcess;
        }


    }
    
    if(dataCountToHold) {
		// printf("CCCryptorUpdate checkpoint 1\n");
    	movecnt = dataCountToHold - cryptor->bufferPos;
        if(movecnt) {
        	if(movecnt != dataInLength) {
            	// printf("CCCryptorUpdate bad calculation 3\n");
                return kCCDecodeError;
            }
            ccAddBuff(cryptor, dataIn, movecnt);
        	dataIn += movecnt; dataInLength -= movecnt;
        }
    }
    
    if(dataInLength) {
        // printf("CCCryptorUpdate bad calculation 4\n");
        return kCCDecodeError;
    }
    return kCCSuccess;

}

CCCryptorStatus CCCryptorUpdate(CCCryptorRef cryptorRef, const void *dataIn, size_t dataInLength, void *dataOut, size_t dataOutAvailable, size_t *dataOutMoved)
{
	CCCryptorStatus     retval;
    CCCompatCryptor     *compat_cryptor = cryptorRef;


    CCCryptor           *cryptor;





    






    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(dataOutMoved) *dataOutMoved = 0;
    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    

	if(dataInLength == 0) return kCCSuccess;

	if(ccIsStreaming(cryptor)) {
    	return ccSimpleUpdate(cryptor, dataIn, dataInLength, &dataOut, &dataOutAvailable, dataOutMoved);
	}
	

    retval = ccBlockUpdate(cryptor, dataIn, dataInLength, dataOut, dataOutAvailable, dataOutMoved);
        

	return retval;
}



CCCryptorStatus CCCryptorFinal(
	CCCryptorRef cryptorRef,
	void *dataOut,					/* data RETURNED here */
	size_t dataOutAvailable,
	size_t *dataOutMoved)		/* number of bytes written */
{
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(compat_cryptor == NULL)  return kCCParamError;
    CCCryptor	*cryptor = compat_cryptor->cryptor;
    if(cryptor == NULL) return kCCSuccess; // Some old behavior .. CDSA? has zapped the Cryptor.
    
    
	CCCryptorStatus	retval;
    int encrypting = (cryptor->op == kCCEncrypt);
	uint8_t *bufp = cryptor->buffptr;
	uint32_t blocksize = ccGetCipherBlockSize(cryptor);
    
    size_t moved;
	uint8_t padval;
	char tmpbuf[blocksize*2];

    
    



	if(dataOutMoved) *dataOutMoved = 0;



    if(ccIsStreaming(cryptor)) return kCCSuccess;

	if(encrypting) {
        retval = ccEncryptPad(cryptor, tmpbuf, &moved);


        if(retval != kCCSuccess) return retval;
		if(dataOutAvailable < moved) {
            return kCCBufferTooSmall;
        }
        if(dataOut) {
            CC_XMEMCPY(dataOut, tmpbuf, moved);
            if(dataOutMoved) *dataOutMoved = moved;

        }
		cryptor->bufferPos = 0;
	} else {
		if(ccGetReserve(cryptor) != 0) {
            retval = ccDecryptPad(cryptor, tmpbuf, &moved);


            if(retval != kCCSuccess) return retval;
            if(dataOutAvailable < moved) {
                return kCCBufferTooSmall;
            }
            if(dataOut) {
                CC_XMEMCPY(dataOut, tmpbuf, moved);
                if(dataOutMoved) *dataOutMoved = moved;
            }
			cryptor->bytesProcessed += *dataOutMoved;
            cryptor->bufferPos = 0;
		}


	}
	return kCCSuccess;
}

size_t CCCryptorGetOutputLength(
	CCCryptorRef cryptorRef,
	size_t inputLength,
	bool final)
{
	size_t retval;

    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
	
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    

	retval = cryptor->bufferPos + inputLength;

    if(ccIsStreaming(cryptor))
    	return retval;
    
    if(cryptor->op == kCCEncrypt) {
        retval = FULLBLOCKSIZE(retval, ccGetCipherBlockSize(cryptor));        
        if(final) retval += ccGetPadlen(cryptor);
        return retval;
    } else {
        if(final) return retval;
        else return FULLBLOCKSIZE(retval, ccGetCipherBlockSize(cryptor));
    }
}





CCCryptorStatus CCCryptorReset(
	CCCryptorRef cryptorRef,
	const void *iv)
{
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    CCCryptorStatus retval;
    
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    /* 
    	This routine resets all buffering and sets or clears the IV.  It is
    	documented to throw away any in-flight buffer data.
    */
    
    cryptor->bytesProcessed = cryptor->bufferPos = 0;
    
    /* 
    	Call the common routine to reset the IV - this will copy in the new 
       	value. There is now always space for an IV in the cryptor.
    */
    
    if(iv) {
        retval = ccSetIV(cryptor, iv, ccGetCipherBlockSize(cryptor));
    } else {
        uint8_t ivzero[ccGetCipherBlockSize(cryptor)];
        CC_XZEROMEM(ivzero, ccGetCipherBlockSize(cryptor));
        retval = ccSetIV(cryptor, ivzero, ccGetCipherBlockSize(cryptor));
    }
    if(retval == kCCParamError) return kCCSuccess;
    return retval;
}

CCCryptorStatus
CCCryptorGetIV(CCCryptorRef cryptorRef, void *iv)
{
    uint32_t blocklen;
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    

    if(ccIsStreaming(cryptor)) return kCCParamError;



    return ccGetIV(cryptor, iv, ccGetCipherBlockSize(cryptor));
}








/* 
 * One-shot is mostly service provider independent, except for the
 * dataOutLength check.
 */
CCCryptorStatus CCCrypt(
481
482
483
484
485
486
487
488
489
490
491
492

493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511

512
513

514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653

654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678

679
680
681
682


683
684
685

686



687





688


689



690


691

692



693





















	size_t dataInLength,
	void *dataOut,			/* data RETURNED here */
	size_t dataOutAvailable,
	size_t *dataOutMoved)	
{
	CCCryptorRef cryptor = NULL;
	CCCryptorStatus retval;
    uint8_t *outp;
	size_t outputSize;
	size_t used = 0;
	size_t moved;


	if(retval = CCCryptorCreate(op, alg, options, key, keyLength, iv, &cryptor)) {
		return retval;
	}
	
	if((outputSize = CCCryptorGetOutputLength(cryptor, dataInLength, false)) > dataOutAvailable) {
		CCCryptorRelease(cryptor);
		if(dataOutMoved != NULL) *dataOutMoved = outputSize;
		return kCCBufferTooSmall;
	}
    
    outp = (uint8_t *) dataOut;
	
	if(retval = CCCryptorUpdate(cryptor, dataIn, dataInLength, outp, dataOutAvailable, &moved)) {
		CCCryptorRelease(cryptor);
		return retval;
	}
	outp += moved;
	used += moved;
	dataOutAvailable  -= moved;

	if(retval = CCCryptorFinal(cryptor, outp, dataOutAvailable, &moved)) {
		ccdebug(ASL_LEVEL_ERR, "Final Error\n", 0);

	} else {
		used += moved;
		if(dataOutMoved != NULL) *dataOutMoved = used;
	}
	
	CCCryptorRelease(cryptor);
	return retval;
}



CCCryptorStatus CCCryptorCreateFromDataWithMode(
	CCOperation 	op,				/* kCCEncrypt, kCCEncrypt, kCCBoth (default for BlockMode) */
	CCMode			mode,
	CCAlgorithm		alg,
	CCPadding		padding,		
	const void 		*iv,			/* optional initialization vector */
	const void 		*key,			/* raw key material */
	size_t 			keyLength,	
	const void 		*tweak,			/* raw tweak material */
	size_t 			tweakLength,	
	int				numRounds,
	CCModeOptions 	options,
	const void		*data,			/* caller-supplied memory */
	size_t			dataLength,		/* length of data in bytes */
	CCCryptorRef	*cryptorRef,	/* RETURNED */
	size_t			*dataUsed)		/* optional, RETURNED */
{
    CCCompatCryptor *compat_cryptor = NULL;
	CCCryptor *cryptor = NULL;
	uint32_t err;
    size_t needed;

	/* validate pointers */
	if((data == NULL) || (cryptorRef == NULL) || (key == NULL)) {
		ccdebug(ASL_LEVEL_ERR, "bad arguments\n", 0);
		return kCCParamError;
	}
	
    if((size_t)data % 4) return kCCAlignmentError;

    compat_cryptor = data;
    
    needed = sizeof(CCCompatCryptor);
    if(dataUsed != NULL) *dataUsed = needed;
    
	if(needed > dataLength) {
		return kCCBufferTooSmall;
	}
	
    compat_cryptor->weMallocd = false;
    if((cryptor = (CCCryptor *)malloc(DEFAULT_CRYPTOR_MALLOC)) == NULL) return kCCMemoryFailure;
	compat_cryptor->cryptor = cryptor;
    
	cryptor->mode = mode;
	cryptor->modeptr = mode_descriptor[cryptor->mode];
	
	cryptor->ctx = (mode_context *) cryptor->modeContext;
	
	ccdebug(ASL_LEVEL_ERR, "Entered - data (%016llx) cryptor (%016llx) ctx (%016llx)\n", (uint64_t) data, (uint64_t) cryptor, (uint64_t) cryptor->ctx);

	/* Setup the easy parts of the Cryptor - some will be used in other APIs */
	cryptor->op = op;
	cryptor->mallocAddress = NULL;
	cryptor->cipher = alg;
	cryptor->bytesProcessed = cryptor->bufferPos = 0;
	cryptor->bufferPos = 0;

	cryptor->padding = padding;
		
	if(alg == kCCAlgorithmRC4) {  // Only pure streaming algorithm currently supported.
		cryptor->blocksize = 1;
		cryptor->bufStrat = ccStreaming;
		cryptor->ltcAlgIndex = -1;
	} else {
		if((cryptor->ltcAlgIndex = ccGetAlgorithm(alg)) == -1) return kCCParamError;
		if(cipher_descriptor[cryptor->ltcAlgIndex].keysize && 
           cipher_descriptor[cryptor->ltcAlgIndex].keysize(&keyLength) != CRYPT_OK) 
            return kCCParamError;
		cryptor->blocksize = cipher_descriptor[cryptor->ltcAlgIndex].block_length;
		cryptor->bufStrat = ccStreaming;
		if(cryptor->mode == kCCModeECB) cryptor->bufStrat = ccBlockMode | ccStreamMode;
		if(cryptor->mode == kCCModeCBC) cryptor->bufStrat = ccBlockMode | ccStreamMode;
		if(cryptor->mode == kCCModeXTS) cryptor->bufStrat = ccBlockMode;
	}
	
	ccSetIV(cryptor, iv);	
	*cryptorRef = compat_cryptor;

	/* once the cryptor is all setup - initialize the context */
	
    if(cryptor->modeptr->mode_setup) {
        err = cryptor->modeptr->mode_setup(cryptor->ltcAlgIndex, cryptor->iv, 
                                    key, keyLength, tweak, tweakLength,
                                    numRounds, options, cryptor->ctx);
    } else {
        /* There *should* be no cases where this occurs. */
        return kCCUnimplemented;
	}
	
	return ccLTCErr(err);
	}
	
/* This version mallocs the CCCryptorRef */

CCCryptorStatus CCCryptorCreateWithMode(
	CCOperation 	op,				/* kCCEncrypt, kCCEncrypt, kCCBoth (default for BlockMode) */
	CCMode			mode,
	CCAlgorithm		alg,
	CCPadding		padding,		
	const void 		*iv,			/* optional initialization vector */
	const void 		*key,			/* raw key material */
	size_t 			keyLength,	
	const void 		*tweak,			/* raw tweak material */
	size_t 			tweakLength,	
	int				numRounds,		/* 0 == default */
	CCModeOptions 	options,
	CCCryptorRef	*cryptorRef)	/* RETURNED */
{
	CCCryptorStatus err;
	CCCompatCryptor *compat_cryptor = NULL;
	size_t dataUsed = 0;
	
	if((compat_cryptor = (CCCompatCryptor *)malloc(sizeof(CCCompatCryptor))) == NULL) return kCCMemoryFailure;
	err = CCCryptorCreateFromDataWithMode( op, mode, alg, padding, iv, key,  keyLength, tweak, tweakLength, numRounds, options, compat_cryptor, DEFAULT_CRYPTOR_MALLOC, cryptorRef, &dataUsed); 
	if(err != kCCSuccess)  free(compat_cryptor);
	else compat_cryptor->weMallocd = true;
	return err;
	}

CCCryptorStatus CCCryptorEncryptDataBlock(
	CCCryptorRef cryptorRef,
	const void *iv,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
{
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    

    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    
	if((cryptor->bufStrat & ccBlockMode) == 0) return kCCParamError;
    
	if(iv && cryptor->modeptr->mode_encrypt_tweaked != NULL && cryptor->modeptr->mode_encrypt_tweaked != unimp_mode_encrypt_tweaked)
		return ccLTCErr(cryptor->modeptr->mode_encrypt_tweaked(dataIn, dataInLength, dataOut, (const unsigned char *) iv, cryptor->ctx));

	if(cryptor->modeptr->mode_encrypt != NULL && cryptor->modeptr->mode_encrypt != unimp_mode_encrypt)
        return ccLTCErr(cryptor->modeptr->mode_encrypt(dataIn, dataOut, dataInLength, cryptor->ctx));
    
	return kCCUnimplemented;
}


CCCryptorStatus CCCryptorDecryptDataBlock(
	CCCryptorRef cryptorRef,
	const void *iv,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
{
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    

    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;

	if((cryptor->bufStrat & ccBlockMode) == 0) return kCCParamError;



	if(iv && cryptor->modeptr->mode_decrypt_tweaked != NULL && cryptor->modeptr->mode_decrypt_tweaked != unimp_mode_decrypt_tweaked)
		return ccLTCErr(cryptor->modeptr->mode_decrypt_tweaked(dataIn, dataInLength, dataOut, (const unsigned char *) iv, cryptor->ctx));





	if(cryptor->modeptr->mode_decrypt != NULL && cryptor->modeptr->mode_decrypt != unimp_mode_decrypt)





        return ccLTCErr(cryptor->modeptr->mode_decrypt(dataIn, dataOut, dataInLength, cryptor->ctx));


    



	return kCCUnimplemented;


}


































<



|
>



|
|




|
<
<
|



|


>
|
|
>




|




<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










>



|
|
<
<
|
<
<
<
<













>


|
|
>
>
|
|
|
>
|
>
>
>
|
>
>
>
>
>
|
>
>
|
>
>
>
|
>
>
|
>
|
>
>
>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
903
904
905
906
907
908
909

910
911
912
913
914
915
916
917
918
919
920
921
922
923
924


925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944

























































































































945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960


961




962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
	size_t dataInLength,
	void *dataOut,			/* data RETURNED here */
	size_t dataOutAvailable,
	size_t *dataOutMoved)	
{
	CCCryptorRef cryptor = NULL;
	CCCryptorStatus retval;

	size_t outputSize;
	size_t used = 0;
	size_t moved;
            
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(retval = CCCryptorCreate(op, alg, options, key, keyLength, iv, &cryptor)) {
		return retval;
	}

	if((outputSize = CCCryptorGetOutputLength(cryptor, dataInLength, true)) > dataOutAvailable) {
		CCCryptorRelease(cryptor);
		if(dataOutMoved != NULL) *dataOutMoved = outputSize;
		return kCCBufferTooSmall;
	}



	if(retval = CCCryptorUpdate(cryptor, dataIn, dataInLength, dataOut, dataOutAvailable, &moved)) {
		CCCryptorRelease(cryptor);
		return retval;
	}
	dataOut += moved;
	used += moved;
	dataOutAvailable  -= moved;

	if(retval = CCCryptorFinal(cryptor, dataOut, dataOutAvailable, &moved)) {
		CC_DEBUG_LOG(ASL_LEVEL_ERR, "Final Error\n", 0);
        // printf("Failing on final\n");
	} else {
		used += moved;
		if(dataOutMoved != NULL) *dataOutMoved = used;
	}

	CCCryptorRelease(cryptor);
	return retval;
}


























































































































CCCryptorStatus CCCryptorEncryptDataBlock(
	CCCryptorRef cryptorRef,
	const void *iv,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
{
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    
    if(ccIsStreaming(cryptor)) return kCCParamError;
    if(!iv) return ccDoEnCrypt(cryptor, dataIn, dataInLength, dataOut);


    return ccDoEnCryptTweaked(cryptor, dataIn, dataInLength, dataOut, iv);    




}


CCCryptorStatus CCCryptorDecryptDataBlock(
	CCCryptorRef cryptorRef,
	const void *iv,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
{
    CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    
    if(ccIsStreaming(cryptor)) return kCCParamError;
    if(!iv) return ccDoDeCrypt(cryptor, dataIn, dataInLength, dataOut);
    return ccDoDeCryptTweaked(cryptor, dataIn, dataInLength, dataOut, iv);    
}


CCCryptorStatus CCDesIsWeakKey( void *key, size_t length)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    return ccdes_key_is_weak(key, length);
}

void CCDesSetOddParity(void *key, size_t Length)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccdes_key_set_odd_parity(key, Length);
}

uint32_t CCDesCBCCksum(void *in, void *out, size_t length,
                       void *key, size_t keylen, void *ivec)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    return ccdes_cbc_cksum(in, out, length, key, keylen, ivec);
}

// Legacy SPI
#include <corecrypto/ccrc4.h>

typedef struct current_rc4_key_st
{
	uint32_t x,y;
	uint32_t data[256];
} RC4_KEY;

#ifndef	NDEBUG
#define ASSERT(s)
#else
#define ASSERT(s)	assert(s)
#endif

void CC_RC4_set_key(void *ctx, int len, const unsigned char *data)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ASSERT(sizeof(RC4_KEY) == ccrc4_eay.size);
    ccrc4_eay.init(ctx, len, data);
}

void CC_RC4(void *ctx, unsigned long len, const unsigned char *indata,
            unsigned char *outdata)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccrc4_eay.crypt(ctx, len, indata, outdata);
}


Changes to Source/API/CommonCryptorPriv.h.

1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at

|







1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2006-2010 Apple, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49


50
51
52
53
54
55
56
57



58


59
60
61
62
63
64
65
66
67
68
69
70
71

72
73
74
75
76
77
78
79
80
81
82
83
84
85


86
87
88
89
90
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* 
 * CommonCryptorPriv.h - interface between CommonCryptor and operation- and
 *						 algorithm-specific service providers. 
 */

#ifndef	_CC_COMMON_CRYPTOR_PRIV_
#define	_CC_COMMON_CRYPTOR_PRIV_

#include "CommonCryptor.h"
#include "CommonCryptorSPI.h"
#include "tomcrypt.h"
#include "rc4.h"
#include "pkcs7pad.h"

#ifdef __cplusplus
extern "C" {
#endif

static enum {
    ccStreaming		= 0x00000001,
    ccStreamMode	= 0x00000002,
    ccBlockMode		= 0x00000004
};
typedef uint32_t CCBufStrat;
    
#define CCMAXBUFFERSIZE 128


#define CCMAXCONTEXTSIZE 1032
    
static uint32_t ccMaxCipherBlockSize = CCMAXBUFFERSIZE; // rc2/rc5 max blocksize
static uint32_t ccDefaultRounds = 0;

typedef struct _CCCryptor {
    char					buffptr[CCMAXBUFFERSIZE];
    char			 		iv[CCMAXBUFFERSIZE];



    


    CCOperation				op;         // kCCEncrypt, kCCDecrypt, or kCCBoth
    CCAlgorithm				cipher;     // encryption algorithm
    CCMode					mode;       // one of pre-defined modes
    mode_descriptor_ptr		modeptr;
    CCBufStrat				bufStrat;
    CCPadding				padding;    // padding to use 0 (default) or kCCOptionPKCS7Padding
    int32_t					ltcAlgIndex;    // LibTomCrypt cipher index
    uint32_t				blocksize;
    uint32_t				bufferPos;
    uint32_t				bytesProcessed;
    mode_context			*ctx;       // largest size context in use
    void*					mallocAddress;  // if Not NULL, we mallocd this and must free it in CCCryptorRelease()
    uint32_t                modeContext[CCMAXCONTEXTSIZE/4];

} CCCryptor;
static uint32_t cryptorSize = sizeof(struct _CCCryptor);
    
    
typedef struct _CCCompat {
    uint32_t			weMallocd;
    CCCryptor			*cryptor;
} CCCompatCryptor;
    
    
#define CCCRYPTOR_SIZE  sizeof(struct _CCCryptor)
#define kCCContextSizeGENERIC (sizeof(CCCompatCryptor))




#ifdef __cplusplus
}
#endif

#endif	/* _CC_COMMON_CRYPTOR_PRIV_ */







|


|
|



|
|
<




|
<
<
<
<
<
<
|
|
>
>
|
|
<
<
|

|
<
>
>
>
|
>
>
|
|
|
|
<
<
<
<
<
<
<
<
|
>

<

|




|





>
>




|
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

36
37
38
39
40






41
42
43
44
45
46


47
48
49

50
51
52
53
54
55
56
57
58
59








60
61
62

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* 
 * CommonCryptorPriv.h - interface between CommonCryptor and operation- and
 *           algorithm-specific service providers. 
 */

#ifndef _CC_COMMON_CRYPTOR_PRIV_
#define _CC_COMMON_CRYPTOR_PRIV_

#include "CommonCryptor.h"
#include "CommonCryptorSPI.h"
#include <dispatch/dispatch.h>
#include "corecryptoSymmetricBridge.h"


#ifdef __cplusplus
extern "C" {
#endif
    






    /* Byte-Size Constants */
#define CCMAXBUFFERSIZE 128             /* RC2/RC5 Max blocksize */
#define DEFAULT_CRYPTOR_MALLOC 4096
#define CC_STREAMKEYSCHED  2048
#define CC_MODEKEYSCHED  2048
#define CC_MAXBLOCKSIZE  128


    
typedef struct _CCCryptor {
    uint8_t        buffptr[32];

    uint32_t        bufferPos;
    uint32_t        bytesProcessed;
    uint32_t        cipherBlocksize;

    CCAlgorithm     cipher;
    CCMode          mode;
    CCOperation     op;        /* kCCEncrypt, kCCDecrypt, or kCCBoth */
    
    corecryptoMode  symMode[2];
    cc2CCModeDescriptor *modeDesc;








    modeCtx         ctx[2];
    cc2CCPaddingDescriptor *padptr;
} CCCryptor;

    

typedef struct _CCCompat {
    uint32_t			weMallocd;
    CCCryptor			*cryptor;
} CCCompatCryptor;

    
#define CCCRYPTOR_SIZE  sizeof(struct _CCCryptor)
#define kCCContextSizeGENERIC (sizeof(CCCompatCryptor))


    corecryptoMode getCipherMode(CCAlgorithm cipher, CCMode mode, CCOperation direction);

#ifdef __cplusplus
}
#endif

#endif  /* _CC_COMMON_CRYPTOR_PRIV_ */

Added Source/API/CommonDH.c.









































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_DH_FUNCTIONS
#include "CommonDH.h"
#include "CommonRandomSPI.h"
#include <dispatch/dispatch.h>
#include <dispatch/queue.h>
#include <corecrypto/ccn.h>
#include <corecrypto/ccdh.h>
#include <corecrypto/ccdh_gp.h>
#include "ccMemory.h"
#include "ccErrors.h"
#include "ccdebug.h"

typedef struct CCDHParameters_s {
    ccdh_const_gp_t gp;
    size_t malloced;
} CCDHParmSetstruct, *CCDHParmSet; 

typedef struct DH_ {
	CCDHParmSet parms;
    ccdh_full_ctx_t ctx;
} CCDHstruct, *CCDH;


static struct CCDHParameters_s gp2;
static struct CCDHParameters_s gp5;
CCDHParameters kCCDHRFC2409Group2 = &gp2;
CCDHParameters kCCDHRFC3526Group5 = &gp5;

// = ccdh_gp_rfc3526group05(void);
static void
ccdhInitGPs() {
    static dispatch_once_t dhgpinit;
    dispatch_once(&dhgpinit, ^{
        kCCDHRFC3526Group5->malloced = 0;
        kCCDHRFC3526Group5->gp = ccdh_gp_rfc3526group05();
    });
}


CCDHRef
CCDHCreate(CCDHParameters dhParameter)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CC_NONULLPARM(dhParameter);
    if(dhParameter == kCCDHRFC2409Group2) return NULL; // no corecrypto group yet for this.
    ccdhInitGPs();
    
    CCDHParmSet CCDHParm = (CCDHParmSet) dhParameter;
    
    CCDH retval = CC_XMALLOC(sizeof(CCDHstruct));
    if(retval == NULL) return retval;
        
    retval->ctx._full = CC_XMALLOC(ccdh_full_ctx_size(ccdh_ccn_size(CCDHParm->gp)));
    
    

    if(retval->ctx._full == NULL) {
        CC_XFREE(retval, sizeof(CCDHstruct));
        return NULL;
    }
    
    ccdh_ctx_init(CCDHParm->gp, retval->ctx);
    retval->parms = CCDHParm;
        
    return retval;
}

void
CCDHRelease(CCDHRef ref)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(ref == NULL) return;
    CCDH keyref = (CCDH) ref;
    if(keyref->ctx._full) 
        CC_XFREE(keyref->ctx._full, ccdh_full_ctx_size(ccdh_ccn_size(keyref->parms->gp)));
    keyref->ctx._full = keyref->parms = NULL;
    CC_XFREE(keyref, sizeof(CCDHstruct));
}

int
CCDHGenerateKey(CCDHRef ref, void *output, size_t *outputLength)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CC_NONULLPARM(ref);
    CC_NONULLPARM(output);
    CC_NONULLPARM(outputLength);
    
    CCDH keyref = (CCDH) ref;
    
    if(ccdh_generate_key(keyref->parms->gp, ccDRBGGetRngState(), keyref->ctx.pub))
        return -1;
    
    size_t size_needed = ccdh_export_pub_size(keyref->ctx);
    if(size_needed > *outputLength) {
        *outputLength = size_needed;
        return -1;
    }
    
    *outputLength = size_needed;
    ccdh_export_pub(keyref->ctx, output);
    return 0;
}


int
CCDHComputeKey(unsigned char *sharedKey, size_t *sharedKeyLen, const void *peerPubKey, size_t peerPubKeyLen, CCDHRef ref)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CC_NONULLPARM(sharedKey);
    CC_NONULLPARM(sharedKeyLen);
    CC_NONULLPARM(peerPubKey);
    CC_NONULLPARM(ref);
    
    CCDH keyref = (CCDH) ref;
    ccdh_pub_ctx_decl_gp(keyref->parms->gp, peer_pub);
    cc_size n = ccdh_ctx_n(keyref->ctx);
    cc_unit skey[n];
    
    if(ccdh_import_pub(keyref->parms->gp, peerPubKeyLen, peerPubKey,
                    peer_pub))
        return -1;
    
    if(ccdh_compute_key(keyref->ctx, peer_pub, skey))
        return -1;
    
    size_t size_needed = ccn_write_uint_size(n, skey);
    if(size_needed > *sharedKeyLen) {
        *sharedKeyLen = size_needed;
        return -1;
    }
    *sharedKeyLen = size_needed;
    (void) ccn_write_uint_padded(n, skey, *sharedKeyLen, sharedKey);
    
    return 0;

}

CCDHParameters
CCDHParametersCreateFromData(const void *p, size_t pLen, const void *g, size_t gLen, size_t l)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CC_NONULLPARM(p);
    CC_NONULLPARM(g);
    
    cc_size psize = ccn_nof_size(pLen);
    cc_size gsize = ccn_nof_size(gLen);
    cc_size n = (psize > gsize) ? psize: gsize;
    cc_unit pval[n], gval[n];
    
    CCDHParmSet retval = CC_XMALLOC(sizeof(CCDHParmSetstruct));
    if(retval == NULL) return NULL;
    
    retval->malloced = ccdh_gp_size(n);
    retval->gp.gp = (ccdh_gp *) CC_XMALLOC(retval->malloced);
    if(retval->gp.gp == NULL) {
        retval->malloced = 0;
        CC_XFREE(retval, sizeof(CCDHParmSetstruct));
        return NULL;
    }
    
    if(ccdh_init_gp(retval->gp._ncgp, n, pval, gval, (cc_size) l))
        return NULL;
    return retval;

}

void
CCDHParametersRelease(CCDHParameters parameters)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(parameters == NULL) return;
    if(parameters == kCCDHRFC2409Group2) return;
    if(parameters == kCCDHRFC3526Group5) return;

    CCDHParmSet CCDHParm = (CCDHParmSet) parameters;
    if(CCDHParm->malloced) 
        CC_XFREE(CCDHParm->gp.gp, retval->malloced);
    CCDHParm->malloced = 0;
    CCDHParm->gp.gp = NULL;
    CC_XFREE(CCDHParm, sizeof(CCDHParmSetstruct));
}

// TODO - needs PKCS3 in/out
CCDHParameters
CCDHParametersCreateFromPKCS3(const void *data, size_t len)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CC_NONULLPARM(data);
    return NULL;
}

size_t
CCDHParametersPKCS3EncodeLength(CCDHParameters parms)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    return 0;
}

size_t
CCDHParametersPKCS3Encode(CCDHParameters parms, void *data, size_t dataAvailable)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    return 0;
}

Changes to Source/API/CommonDigest.c.

1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at

|







1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
17
18
19
20
21
22
23



24
25
26
27
28










29
30
31

32
33

34
35
36

37
38


39

40




41
42
43
44
45
46
47
48
49
50
51
52
53
54

55
56
57
58
59
60
61
62


63


64
65
66




67
68







69






70




71
72
73
74
75
76
77


78


79
80

81

82
83
84
85

































86































87



88








89
90






91
92





93
94
95
96
97
98

99
100
101

102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

121


122












































































































































































































































































































































































































123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */




#include "CommonDigest.h"
#include "CommonDigestPriv.h"
#include "CommonDigestSPI.h"
#include "tomcrypt.h"
#include "skein_ltc.h"











#define SELECT_HASH(X,Y,Z) case X: \
	ptr->hashIndex = register_hash(&Y); \

	break
	

	
int 
CCDigestInit(CCDigestAlg algorithm, CCDigestRef ctx)

{
	CCDigestCtxPtr ptr = (CCDigestCtxPtr) ctx;


	

	switch(algorithm) {




	SELECT_HASH(kCCDigestMD2,md2_desc,7);
	SELECT_HASH(kCCDigestMD4,md4_desc,6);
	SELECT_HASH(kCCDigestMD5,ltc_md5_desc,3);
	SELECT_HASH(kCCDigestRMD128,rmd128_desc,8);
	SELECT_HASH(kCCDigestRMD160,rmd160_desc,9);
	SELECT_HASH(kCCDigestRMD256,rmd256_desc,11);
	SELECT_HASH(kCCDigestRMD320,rmd320_desc,12);
	SELECT_HASH(kCCDigestSHA1,sha1_desc,2);
	SELECT_HASH(kCCDigestSHA224,sha224_desc,10);
	SELECT_HASH(kCCDigestSHA256,sha256_desc,0);
	SELECT_HASH(kCCDigestSHA384,sha384_desc,4);
	SELECT_HASH(kCCDigestSHA512,sha512_desc,5);
	SELECT_HASH(kCCDigestSkein128,skein512_128_desc,SKEIN512_128_LTC_TAG);
	SELECT_HASH(kCCDigestSkein160,skein512_160_desc,SKEIN512_160_LTC_TAG);

	SELECT_HASH(kCCDigestSkein224,skein512_224_desc,SKEIN512_224_LTC_TAG);
	SELECT_HASH(kCCDigestSkein256,skein512_256_desc,SKEIN512_256_LTC_TAG);
	SELECT_HASH(kCCDigestSkein384,skein512_384_desc,SKEIN512_384_LTC_TAG);
	SELECT_HASH(kCCDigestSkein512,skein512_512_desc,SKEIN512_512_LTC_TAG);
	default: return -1;
	}
	return hash_descriptor[ptr->hashIndex].init(&ptr->md);
}





int
CCDigestUpdate(CCDigestRef ctx, const void *data, size_t len)
{




	CCDigestCtxPtr ptr = (CCDigestCtxPtr) ctx;
    uint8_t* checkedData = (const uint8_t *)data;







    if (checkedData == NULL) {






        checkedData = "";




    }
	return hash_descriptor[ptr->hashIndex].process(&ptr->md, checkedData, len);
}

int
CCDigestFinal(CCDigestRef ctx, uint8_t *output)
{


	CCDigestCtxPtr ptr = (CCDigestCtxPtr) ctx;


	return hash_descriptor[ptr->hashIndex].done(&ptr->md, output);
}



int
CCDigest(CCDigestAlg algorithm, const uint8_t *data, size_t length, uint8_t *output)
{
	CCDigestCtx_t c;

































	CCDigestCtxPtr ptr = &c;































	CCDigestInit(algorithm, ptr);



    uint8_t* checkedData = data;








    if (checkedData == NULL) {
        checkedData = "";






    }
	hash_descriptor[ptr->hashIndex].process(&ptr->md, checkedData, length);





	return hash_descriptor[ptr->hashIndex].done(&ptr->md, output);
}

CCDigestRef
CCDigestCreate(CCDigestAlg algorithm)
{

    CCDigestRef ctx;
    
    if(!(ctx = (CCDigestCtx *) malloc(CC_DIGEST_SIZE))) {

        return NULL;
    }
    if(CCDigestInit(algorithm, ctx) != 0) { 
        free(ctx); 
        return NULL; 
    }
    return ctx;
}

void
CCDigestDestroy(CCDigestRef ctx)
{
    bzero(ctx, sizeof(CCDigestCtx));
    free(ctx);
}

void
CCDigestReset(CCDigestRef ctx)
{

	CCDigestCtxPtr ptr = (CCDigestCtxPtr) ctx;


    hash_descriptor[ptr->hashIndex].init(&ptr->md);












































































































































































































































































































































































































}

int
CCDigestInterrimResult(CCDigestRef ctx, uint8_t *output)
{
    CCDigestCtx tmp;
    
    memcpy(&tmp, ctx, CC_DIGEST_SIZE);
    return CCDigestFinal(&tmp, output);
}

size_t
CCDigestBlockSize(CCDigestRef ctx) 
{
    size_t retval = 0;
	CCDigestCtxPtr ptr = (CCDigestCtxPtr) ctx;
    if(ptr) retval = hash_descriptor[ptr->hashIndex].blocksize;
    return retval;
}

size_t
CCDigestOutputSize(CCDigestRef ctx) 
{
    size_t retval = 0;
	CCDigestCtxPtr ptr = (CCDigestCtxPtr) ctx;
    if(ptr) retval = hash_descriptor[ptr->hashIndex].hashsize;
    return retval;
}








>
>
>



|
|
>
>
>
>
>
>
>
>
>
>

|
|
>
|
|
>
|
<
|
>
|
<
>
>
|
>
|
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
<
<
<
<
>
>
|
>
>
|
|

>
>
>
>
|
|
>
>
>
>
>
>
>
|
>
>
>
>
>
>
|
>
>
>
>

|



|

>
>
|
>
>
|
|
>
|
>

|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
|
>
>
>
>
>
>
>
>
|
|
>
>
>
>
>
>
|
|
>
>
>
>
>
|



|
|
>
|
|
<
>
|

<
<
|
<
<
<
<
<
<
<
<
<





>
|
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



|

<
|
<
<
|
|
<
<
<
|
<
<
<
<
|
<
<
<
<
<
<
|


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

50
51
52

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80




81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236

237
238
239


240









241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651

652


653
654



655




656






657
658
659
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_DIGEST_FUNCTIONS
#define COMMON_DIGEST_FOR_RFC_1321

#include "CommonDigest.h"
#include "CommonDigestPriv.h"
#include "CommonDigestSPI.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "ccdebug.h"
#include <stdio.h>
#include <dispatch/dispatch.h>
#include <dispatch/queue.h>
#include <corecrypto/ccmd2.h>
#include <corecrypto/ccmd4.h>
#include <corecrypto/ccmd5.h>
#include <corecrypto/ccripemd.h>
#include <corecrypto/ccsha1.h>
#include <corecrypto/ccsha2.h>

#define NDEBUG
#ifndef	NDEBUG
#define ASSERT(s)
#else
#define ASSERT(s)	assert(s)
#endif


static const size_t diMax = kCCDigestSkein512+1;
static struct ccdigest_info *di[diMax];


// This returns a pointer to the corecrypto "di" structure for a digest.
// It's used for all functions that need a di (HMac, Key Derivation, etc).

struct ccdigest_info *
CCDigestGetDigestInfo(CCDigestAlgorithm algorithm) {
    static dispatch_once_t di_init;

    dispatch_once(&di_init, ^{
        di[kCCDigestNone] = NULL;
        di[kCCDigestMD2] = &ccmd2_di;
        di[kCCDigestMD4] = &ccmd4_di;
        di[kCCDigestMD5] = ccmd5_di();
        di[kCCDigestRMD128] = &ccrmd128_di;
        di[kCCDigestRMD160] = &ccrmd160_di;
        di[kCCDigestRMD256] = &ccrmd256_di;
        di[kCCDigestRMD320] = &ccrmd320_di;
        di[kCCDigestSHA1] = ccsha1_di();
        di[kCCDigestSHA224] = ccsha224_di();
        di[kCCDigestSHA256] = ccsha256_di();
        di[kCCDigestSHA384] = ccsha384_di();
        di[kCCDigestSHA512] = ccsha512_di();
        di[kCCDigestSkein128] = NULL;
        di[kCCDigestSkein160] = NULL;
        di[15] = NULL; // gap
        di[kCCDigestSkein224] = NULL;
        di[kCCDigestSkein256] = NULL;
        di[kCCDigestSkein384] = NULL;
        di[kCCDigestSkein512] = NULL;




    });
    return di[algorithm];
}

    
int 
CCDigestInit(CCDigestAlgorithm alg, CCDigestRef c)
{
    if(alg == 0 || alg >= diMax) return kCCParamError;
    if(!c) return kCCParamError;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering Algorithm: %d\n", alg);
    CCDigestCtxPtr p = (CCDigestCtxPtr) c;

    if(p->di = CCDigestGetDigestInfo(alg)) {
        ccdigest_init(p->di, (struct ccdigest_ctx *) p->md);
		return 0;
    } else {
        return kCCUnimplemented;
    }
}

int
CCDigestUpdate(CCDigestRef c, const void *data, size_t len)
{
    // CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(c == NULL) return kCCParamError;
    if(len == 0) return kCCSuccess;
    if(data == NULL) return kCCParamError; /* this is only a problem if len > 0 */
    CCDigestCtxPtr p = (CCDigestCtxPtr) c;
    if(p->di) {
        ccdigest_update(p->di, (struct ccdigest_ctx *) p->md, len, data);
        return kCCSuccess;
    }
    return kCCUnimplemented;
}

int
CCDigestFinal(CCDigestRef c, uint8_t *out)
{
    // CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(c == NULL || out == NULL) return kCCParamError;
	CCDigestCtxPtr p = (CCDigestCtxPtr) c;
    if(p->di) {
        ccdigest_final(p->di, (struct ccdigest_ctx *) p->md, out);
        return 0;
    }
    return kCCUnimplemented;
}

int
CCDigest(CCDigestAlgorithm alg, const uint8_t *data, size_t len, uint8_t *out)
{
	CCDigestCtx_t c;
    int retval;
    struct ccdigest_info *di;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering Algorithm: %d\n", alg);
    if(di = CCDigestGetDigestInfo(alg)) {
        ccdigest(di, len, data, out);
        return 0;
    }
    return kCCUnimplemented;
}

size_t
CCDigestGetBlockSize(CCDigestAlgorithm algorithm) 
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering Algorithm: %d\n", algorithm);
    struct ccdigest_info *di = CCDigestGetDigestInfo(algorithm);
    if(di) return di->block_size;
    return kCCUnimplemented;
}

size_t
CCDigestGetOutputSize(CCDigestAlgorithm algorithm)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering Algorithm: %d\n", algorithm);
    struct ccdigest_info *di = CCDigestGetDigestInfo(algorithm);
    if(di) return di->output_size;
    return kCCUnimplemented;
}

size_t
CCDigestGetBlockSizeFromRef(CCDigestRef ctx) 
{
    // CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CCDigestCtxPtr p = (CCDigestCtxPtr) ctx;
    if(p->di) return p->di->block_size;
    return kCCUnimplemented;
}

size_t
CCDigestBlockSize(CCDigestRef ctx)
{
    // CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    return CCDigestGetBlockSizeFromRef(ctx);
}

size_t
CCDigestOutputSize(CCDigestRef ctx)
{
    // CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    return CCDigestGetOutputSizeFromRef(ctx);
}

size_t
CCDigestGetOutputSizeFromRef(CCDigestRef ctx)
{
    // CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CCDigestCtxPtr p = (CCDigestCtxPtr) ctx;
    if(p->di) return p->di->output_size;
    return kCCUnimplemented;
}





CCDigestRef
CCDigestCreate(CCDigestAlgorithm alg)
{
	CCDigestCtxPtr retval = CC_XMALLOC(sizeof(CCDigestCtx_t));
    
    // CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!retval) return NULL;
    if(CCDigestInit(alg, retval)) {
    	CC_XFREE(retval, sizeof(CCDigestCtx_t));
    	return NULL;
    }
    return retval;
}


uint8_t *
CCDigestOID(CCDigestRef ctx)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CCDigestCtxPtr p = (CCDigestCtxPtr) ctx;
	return p->di->oid;
}

size_t
CCDigestOIDLen(CCDigestRef ctx)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CCDigestCtxPtr p = (CCDigestCtxPtr) ctx;
	return p->di->oid_size;
}

CCDigestRef
CCDigestCreateByOID(uint8_t *OID, size_t OIDlen)
{    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    for(int i=kCCDigestMD2; i<diMax; i++) {
        struct ccdigest_info *di = CCDigestGetDigestInfo(i);

        if(di && (OIDlen == di->oid_size) && (CC_XMEMCMP(OID, di->oid, OIDlen) == 0))
            return CCDigestCreate(i);
    }


    return NULL;









}

void
CCDigestReset(CCDigestRef ctx)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    CCDigestCtxPtr p = (CCDigestCtxPtr) ctx;
    if(p->di) ccdigest_init(p->di, (struct ccdigest_ctx *) p->md);
}


void
CCDigestDestroy(CCDigestRef ctx)
{
    // CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(ctx) {
		CC_XZEROMEM(ctx, sizeof(CCDigestCtx_t));
		CC_XFREE(ctx, sizeof(CCDigestCtx_t));
    }
}
/*
 * Legacy CommonDigest API shims.
 */

#define CC_COMPAT_DIGEST_RETURN 1

#define DIGEST_SHIMS(_name_,_constant_) \
\
static size_t CC_##_name_##_Len = 0; \
static size_t CC_##_name_##_Ctr = 0; \
\
int CC_##_name_##_Init(CC_##_name_##_CTX *c) { \
    struct ccdigest_info *di = CCDigestGetDigestInfo(_constant_); \
    ASSERT(sizeof(CC_##_name_##_CTX) <= ccdigest_di_size(di)); \   
    ccdigest_init(CCDigestGetDigestInfo(_constant_), (struct ccdigest_ctx *) c); \
	return 1; \
} \
 \
int \
CC_##_name_##_Update(CC_##_name_##_CTX *c, const void *data, CC_LONG len) \
{ \
    CC_##_name_##_Len += len; \
    ccdigest_update(CCDigestGetDigestInfo(_constant_), (struct ccdigest_ctx *) c, len, data); \
	return 1; \
} \
 \
int \
CC_##_name_##_Final(unsigned char *md, CC_##_name_##_CTX *c) \
{ \
    if(((++CC_##_name_##_Ctr) % 50) == 0) CC_DEBUG_LOG(ASL_LEVEL_ERR, "Len = %lu\n", CC_##_name_##_Len); \
    ccdigest_final(CCDigestGetDigestInfo(_constant_), (struct ccdigest_ctx *) c, md); \
	return 1; \
} \
 \
unsigned char * \
CC_##_name_ (const void *data, CC_LONG len, unsigned char *md) \
{ \
	(void) CCDigest(_constant_, data, len, md); \
	return md; \
}


#define DIGEST_FINAL_SHIMS(_name_,_constant_) \
unsigned char * \
CC_##_name_ (const void *data, CC_LONG len, unsigned char *md) \
{ \
(void) CCDigest(_constant_, data, len, md); \
return md; \
}



DIGEST_FINAL_SHIMS(MD2, kCCDigestMD2)
DIGEST_SHIMS(MD4, kCCDigestMD4)
DIGEST_SHIMS(MD5, kCCDigestMD5)
DIGEST_SHIMS(SHA1, kCCDigestSHA1)
DIGEST_FINAL_SHIMS(SHA224, kCCDigestSHA224)
DIGEST_FINAL_SHIMS(SHA256, kCCDigestSHA256)
DIGEST_FINAL_SHIMS(SHA384, kCCDigestSHA384)
DIGEST_FINAL_SHIMS(SHA512, kCCDigestSHA512)


#define MD5_CTX                     CC_MD5_CTX
void MD5Final(unsigned char md[16], MD5_CTX *c)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    (void) CC_MD5_Final(md, c);
}

static void
ccdigest_process(struct ccdigest_info *di, uint8_t *bufptr, ccdigest_state_t state,
                 uint64_t curlen, size_t len, uint8_t *data)
{
    while(len) { 
        if (curlen == 0 && len >= di->block_size) {
            uint64_t fullblocks = len / di->block_size;
            di->compress(state, fullblocks, data);
            uint64_t nbytes = fullblocks * di->block_size;
            len -= nbytes; data += nbytes;
        } else {
            uint64_t n = CC_XMIN(len, (di->block_size - curlen)); 
            CC_XMEMCPY(bufptr + curlen, data, n); 
            curlen += n; len -= n; data += n;
            if (curlen == di->block_size) {
                di->compress(state, 1, bufptr);
                curlen = 0; 
            }
        } 
    }
}

static void
ccdigest_finalize(struct ccdigest_info *di, uint8_t *bufptr, ccdigest_state_t state, 
                  uint64_t curlen, uint64_t totalLen)
{
    bufptr[curlen++] = (unsigned char)0x80;
    int reserve = 8;
    if(di->block_size == 128) reserve = 16; // SHA384/512 reserves 16 bytes below.
    
    /* if the length is currently above block_size - reserve bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    
    if (curlen > (di->block_size - reserve)) {
        while (curlen < di->block_size) bufptr[curlen++] = (unsigned char)0;
        di->compress(state, 1, bufptr);        
        curlen = 0;
    }
    
    /* pad out with zeros, but store length in last 8 bytes (sizeof uint64_t) */
    while (curlen < (di->block_size - 8))  bufptr[curlen++] = (unsigned char)0;
    totalLen *= 8; // size in bits
    CC_XSTORE64H(totalLen, bufptr+(di->block_size - 8));
    di->compress(state, 1, bufptr);
}

/*
 #define CC_MD2_DIGEST_LENGTH    16
 #define CC_MD2_BLOCK_BYTES      64
 #define CC_MD2_BLOCK_LONG       (CC_MD2_BLOCK_BYTES / sizeof(CC_LONG))


 typedef struct CC_MD2state_st
 {
 int num;
 unsigned char data[CC_MD2_DIGEST_LENGTH];
 CC_LONG cksm[CC_MD2_BLOCK_LONG];
 CC_LONG state[CC_MD2_BLOCK_LONG];
 } CC_MD2_CTX;
 */

static inline void md2in(struct ccdigest_info *di, ccdigest_ctx_t ctx, CC_MD2_CTX *c)
{
    CC_XMEMCPY(ccdigest_state_u8(di, ctx)+48, c->cksm, CC_MD2_BLOCK_LONG);    
    CC_XMEMCPY(ccdigest_state_u8(di, ctx), c->state, CC_MD2_BLOCK_LONG);    
    CC_XMEMCPY(ccdigest_data(di, ctx), c->data, CC_MD2_DIGEST_LENGTH);
    ccdigest_num(di, ctx) = c->num;    
}

static inline void md2out(struct ccdigest_info *di, CC_MD2_CTX *c, ccdigest_ctx_t ctx)
{
    CC_XMEMCPY(c->cksm, ccdigest_state_u8(di, ctx)+48, CC_MD2_BLOCK_LONG);    
    CC_XMEMCPY(c->state, ccdigest_state_u8(di, ctx), CC_MD2_BLOCK_LONG);    
    CC_XMEMCPY(c->data, ccdigest_data(di, ctx), CC_MD2_DIGEST_LENGTH);
    c->num = (int) ccdigest_num(di, ctx);    
}

int CC_MD2_Init(CC_MD2_CTX *c)
{
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestMD2);
    ccdigest_di_decl(di, ctx);
    ccdigest_init(di, ctx);
    md2out(di, c, ctx);
    return CC_COMPAT_DIGEST_RETURN;
}

int CC_MD2_Update(CC_MD2_CTX *c, const void *data, CC_LONG len)
{
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestMD2);
    ccdigest_di_decl(di, ctx);
    md2in(di, ctx, c);
    ccdigest_update(di, ctx, len, data);
    md2out(di, c, ctx);
    return CC_COMPAT_DIGEST_RETURN;
}

extern int CC_MD2_Final(unsigned char *md, CC_MD2_CTX *c)
{
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestMD2);
    ccdigest_di_decl(di, ctx);
    md2in(di, ctx, c);
    ccdigest_final(di, ctx, md);
    md2out(di, c, ctx);
    return CC_COMPAT_DIGEST_RETURN;
}





/*
 typedef struct CC_SHA256state_st
 {   
     CC_LONG count[2];
     CC_LONG hash[8];
     CC_LONG wbuf[16];
 } CC_SHA256_CTX;
 
 */

typedef struct CC_SHA256state_x
{   
    uint64_t count;
    uint32_t hash[8];
    uint32_t wbuf[16];
} CC_SHA256_CTX_X;



int
CC_SHA256_Init(CC_SHA256_CTX *x)
{
    CC_SHA256_CTX_X *c = (CC_SHA256_CTX_X *) x;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ASSERT(sizeof(CC_SHA256_CTX) == sizeof(CC_SHA256_CTX_X));
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestSHA256);
    ASSERT(di->state_size == CC_SHA256_DIGEST_LENGTH);
    CC_XZEROMEM(c->hash, CC_SHA256_DIGEST_LENGTH);
    ASSERT(di->block_size == CC_SHA256_BLOCK_BYTES);
    CC_XZEROMEM(c->wbuf, CC_SHA256_BLOCK_BYTES);
    c->count = 0;
    CC_XMEMCPY(c->hash, di->initial_state, di->state_size);
	return CC_COMPAT_DIGEST_RETURN;
}

int
CC_SHA256_Update(CC_SHA256_CTX *x, const void *data, CC_LONG len)
{
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestSHA256);
    CC_SHA256_CTX_X *c = (CC_SHA256_CTX_X *) x;
    uint64_t totalLen = c->count;
	uint64_t curlen = totalLen % di->block_size;
	uint8_t *bufptr = (uint8_t *) c->wbuf;
    struct ccdigest_state *state = c->hash;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
   	if(!len || !data) return CC_COMPAT_DIGEST_RETURN;
    c->count += len;
    
    ccdigest_process(di, bufptr, state, curlen, len, data);

    return CC_COMPAT_DIGEST_RETURN;
}    

int
CC_SHA256_Final(unsigned char *md, CC_SHA256_CTX *x)
{
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestSHA256);
    CC_SHA256_CTX_X *c = (CC_SHA256_CTX_X *) x;
    uint64_t totalLen = c->count;
	uint64_t curlen = totalLen % di->block_size;
	uint8_t *bufptr = (uint8_t *) c->wbuf;
    struct ccdigest_state *state = c->hash;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!md) return CC_COMPAT_DIGEST_RETURN;
    
    ccdigest_finalize(di, bufptr, state, curlen, totalLen);
    
    /* copy output */
    for (int i = 0; i < 8; i++)  CC_XSTORE32H(c->hash[i], md+(4*i));

	return CC_COMPAT_DIGEST_RETURN;
}


/*
typedef struct CC_SHA512state_st
{   CC_LONG64 count[2];
    CC_LONG64 hash[8];
    CC_LONG64 wbuf[16];
} CC_SHA512_CTX;
*/

typedef struct CC_SHA512state_x
{   
    uint64_t count;
    uint64_t countx;
    uint64_t hash[8];
    uint64_t wbuf[16];
} CC_SHA512_CTX_X;


int
CC_SHA512_Init(CC_SHA512_CTX *x)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestSHA512);
    CC_SHA512_CTX_X *c = (CC_SHA512_CTX_X *) x;
    ASSERT(di->state_size == CC_SHA512_DIGEST_LENGTH);
    CC_XZEROMEM(c->hash, CC_SHA512_DIGEST_LENGTH);
    ASSERT(di->block_size == CC_SHA512_BLOCK_BYTES);
    CC_XZEROMEM(c->wbuf, CC_SHA512_BLOCK_BYTES);
    c->count = 0;
    CC_XMEMCPY(c->hash, di->initial_state, di->state_size);
	return CC_COMPAT_DIGEST_RETURN;
}

int
CC_SHA512_Update(CC_SHA512_CTX *x, const void *data, CC_LONG len)
{
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestSHA512);
    CC_SHA512_CTX_X *c = (CC_SHA512_CTX_X *) x;
    uint64_t totalLen = c->count;
	uint64_t curlen = totalLen % di->block_size;
	uint8_t *bufptr = (uint8_t *) c->wbuf;
    struct ccdigest_state *state = c->hash;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    
   	if(!len || !data) return CC_COMPAT_DIGEST_RETURN;
    
    c->count += len;
    ccdigest_process(di, bufptr, state, curlen, len, data);
    return CC_COMPAT_DIGEST_RETURN;
}    

int
CC_SHA512_Final(unsigned char *md, CC_SHA512_CTX *x)
{
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestSHA512);
    CC_SHA512_CTX_X *c = (CC_SHA512_CTX_X *) x;
    uint64_t totalLen = c->count;
	uint64_t curlen = totalLen % di->block_size;
	uint8_t *bufptr = (uint8_t *) c->wbuf;
    struct ccdigest_state *state = c->hash;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!md) return CC_COMPAT_DIGEST_RETURN;
    
    ccdigest_finalize(di, bufptr, state, curlen, totalLen);

    /* copy output */
    for (int i = 0; i < di->output_size/8; i++)  CC_XSTORE64H(c->hash[i], md+(8*i));
    
	return CC_COMPAT_DIGEST_RETURN;
}

/*
 * Dependent sets of routines (SHA224 and SHA384)
 */

int
CC_SHA224_Init(CC_SHA256_CTX *c)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestSHA224);
    ASSERT(di->state_size == CC_SHA256_DIGEST_LENGTH);
    CC_XZEROMEM(c->hash, CC_SHA256_DIGEST_LENGTH);
    ASSERT(di->block_size == CC_SHA256_BLOCK_BYTES);
    CC_XZEROMEM(c->wbuf, CC_SHA256_BLOCK_BYTES);
    c->count[0] = c->count[1] = 0;
    CC_XMEMCPY(c->hash, di->initial_state, di->state_size);
	return CC_COMPAT_DIGEST_RETURN;
}

int
CC_SHA224_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	return CC_SHA256_Update(c, data, len);
}

int
CC_SHA224_Final(unsigned char *md, CC_SHA256_CTX *c)
{
    uint32_t buf[CC_SHA256_DIGEST_LENGTH/4];
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    
    CC_SHA256_Final(buf, c);
    CC_XMEMCPY(md, buf, CC_SHA224_DIGEST_LENGTH);
	return CC_COMPAT_DIGEST_RETURN;
}


int
CC_SHA384_Init(CC_SHA512_CTX *c)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    struct ccdigest_info *di = CCDigestGetDigestInfo(kCCDigestSHA384);
    ASSERT(di->state_size == CC_SHA512_DIGEST_LENGTH);
    CC_XZEROMEM(c->hash, CC_SHA512_DIGEST_LENGTH);
    ASSERT(di->block_size == CC_SHA512_BLOCK_BYTES);
    CC_XZEROMEM(c->wbuf, CC_SHA512_BLOCK_BYTES);
    c->count[0] = c->count[1] = 0;
    CC_XMEMCPY(c->hash, di->initial_state, di->state_size);
	return CC_COMPAT_DIGEST_RETURN;
}


int
CC_SHA384_Update(CC_SHA512_CTX *c, const void *data, CC_LONG len)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	return CC_SHA512_Update(c, data, len);
}

int
CC_SHA384_Final(unsigned char *md, CC_SHA512_CTX *c)
{

    uint64_t buf[CC_SHA512_DIGEST_LENGTH/8];


    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");



    CC_SHA512_Final(buf, c);




    CC_XMEMCPY(md, buf, CC_SHA384_DIGEST_LENGTH);






	return CC_COMPAT_DIGEST_RETURN;
}

Changes to Source/API/CommonDigestPriv.h.

1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2004 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at

|







1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2004-2010 Apple, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 * CommonDigestPriv.h - private typedefs and defines for ComonCrypto digest routines
 */
 
#ifndef	_COMMON_DIGEST_PRIV_H_
#define _COMMON_DIGEST_PRIV_H_

#include <CommonCrypto/CommonCryptoPriv.h>
#include <CommonCrypto/CommonDigest.h>
#include "tomcrypt.h"

/* MD2 */

#define MD2_DIGEST_LENGTH	CC_MD2_DIGEST_LENGTH
#define MD2_BLOCK			CC_MD2_BLOCK_LONG
typedef	CC_MD2_CTX			MD2_CTX;
typedef CC_LONG				MD2_INT;

/* MD4 */

#define MD4_DIGEST_LENGTH 	CC_MD4_DIGEST_LENGTH
#define MD4_CBLOCK			CC_MD4_BLOCK_BYTES
#define MD4_LBLOCK			(MD4_CBLOCK/4)
#define MD4_LONG_LOG2 		3
typedef CC_MD4_CTX			MD4_CTX;
typedef CC_LONG				MD4_LONG;

/* MD5 */

#define MD5_DIGEST_LENGTH 	CC_MD5_DIGEST_LENGTH
#define MD5_CBLOCK			CC_MD5_BLOCK_BYTES
#define MD5_LBLOCK			(MD5_CBLOCK/4)
typedef CC_MD5_CTX			MD5_CTX;
typedef CC_LONG				MD5_LONG;

/* SHA1 */

#define SHA_DIGEST_LENGTH 	CC_SHA1_DIGEST_LENGTH
#define SHA_CBLOCK			CC_SHA1_BLOCK_BYTES
#define SHA_LBLOCK			CC_SHA1_BLOCK_LONG
#define SHA_LONG_LOG2 		2
#define SHA_LAST_BLOCK  	(SHA_CBLOCK-8)
typedef CC_SHA1_CTX			SHA_CTX;
typedef CC_LONG				SHA_LONG;

/* 
 * Macro to make an algorithm-specific one shot.
 */
#define CC_DIGEST_ONE_SHOT(fcnName, ctxName, initFcn, updateFcn, finalFcn)	\
unsigned char * fcnName (const void *data, CC_LONG len, unsigned char *md) \
{									\
	ctxName ctx;					\
	if(md == NULL) {				\
		return NULL;				\
	}								\
	initFcn(&ctx);					\
	updateFcn(&ctx, data, len);		\
	finalFcn(md, &ctx);				\
	return md;						\
}

typedef struct ccDigest_s {
	hash_state	md;
	int hashIndex;
} CCDigestCtx_t, *CCDigestCtxPtr;

#endif	/* _COMMON_DIGEST_PRIV_H_ */







|
|
<

<
|
<
<
<
<
|
<
|
<
<
<
<
<
<
|
<
|
<
<
<
<
<

<

<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
|
<
<
|


24
25
26
27
28
29
30
31
32

33

34




35

36






37

38





39

40







41














42

43


44
45
46
/*
 * CommonDigestPriv.h - private typedefs and defines for ComonCrypto digest routines
 */
 
#ifndef	_COMMON_DIGEST_PRIV_H_
#define _COMMON_DIGEST_PRIV_H_

#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonDigestSPI.h>



// This has to fit in 1032 bytes for static context clients - until we move them.




typedef struct ccDigest_s {

    struct ccdigest_info *di;






    uint8_t            md[512];

} CCDigestCtx_t, *CCDigestCtxPtr;















// This should remain internal only.  This bridges the CommonCrypto->corecrypto structures
















struct ccdigest_info *


CCDigestGetDigestInfo(CCDigestAlgorithm algorithm);

#endif	/* _COMMON_DIGEST_PRIV_H_ */

Added Source/API/CommonECCryptor.c.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_EC_FUNCTIONS
#include "CommonECCryptor.h"
#include "CommonDigest.h"
#include "CommonDigestPriv.h"
#include "CommonRandomSPI.h"
#include "ccMemory.h"
#import <corecrypto/ccec.h>
#include <AssertMacros.h>
#include "ccdebug.h"


#pragma mark Internal Structures and Functions

typedef struct _CCECCryptor {
    union {
        ccec_full_ctx *private;
        ccec_pub_ctx *public;
        uint8_t *bytes;
    } ecKey;
    size_t keySize;
    CCECKeyType keyType;
} CCECCryptor;


static CCECCryptor *
ccMallocECCryptor(size_t nbits, CCECKeyType keyType)
{
    CCECCryptor *retval;
    size_t ctxSize = 0;
    
    
    if(!ccec_keysize_is_supported(nbits)) return kCCParamError;
    ccec_const_cp_t cp = ccec_get_cp(nbits);    
    size_t len = ccec_cp_prime_size(cp);

    if((retval = CC_XMALLOC(sizeof(CCECCryptor))) == NULL) return NULL;
    
    retval->keySize = nbits;
    retval->ecKey.bytes = NULL;
    
    switch(keyType) {
        case ccECKeyPublic:
            retval->keyType = ccECBlankPublicKey;
            ctxSize = ccec_pub_ctx_size(len);
            break;
        case ccECKeyPrivate:
            retval->keyType = ccECBlankPrivateKey;
            ctxSize = ccec_full_ctx_size(len);
            break;
        default:
            retval = kCCParamError;
            goto errOut;
    }
    
    if((retval->ecKey.bytes = CC_XMALLOC(ctxSize)) == NULL) goto errOut;
    ccec_ctx_init(cp, retval->ecKey.public);

    return retval;
errOut:
    if(retval) {
        CC_XFREE(retval, sizeof(CCECCryptor));
    }
    return retval;
}

static void
ccECCryptorClear(CCECCryptor *theKey)
{
    size_t nbits = theKey->keySize;
    size_t ctxSize = 0;
    
    if(!ccec_keysize_is_supported(nbits)) return ; //kCCParamError;
    ccec_const_cp_t cp = ccec_get_cp(nbits);    
    size_t len = ccec_cp_prime_size(cp);
    
    CCECCryptor *key = (CCECCryptor *) theKey;
    if(!key) return;
    
    switch(key->keyType) {
        case ccECKeyPublic:
        case ccECBlankPublicKey:
            ctxSize = ccec_pub_ctx_size(len);
            break;
        case ccECKeyPrivate:
        case ccECBlankPrivateKey:
            ctxSize = ccec_full_ctx_size(len);
            break;
        default:
            break;
    }
    
    if(ctxSize && key->ecKey.bytes) {
        CC_XZEROMEM(key->ecKey.bytes, ctxSize);
        CC_XFREE(key->ecKey.bytes, ctxSize);
    }

errOut:
    CC_XZEROMEM(key, sizeof(CCECCryptor));
    CC_XFREE(key, sizeof(CCECCryptor));
}

static bool
ccECpairwiseConsistencyCheck(CCECCryptorRef privateKey, CCECCryptorRef publicKey)
{
	CCCryptorStatus status = kCCSuccess;
    uint8_t digestBuffer[CC_SHA1_DIGEST_LENGTH];
	size_t signedDataLen = 4096;
	uint8_t signedData[4096];
	uint32_t isValid = 0;
    
    CC_XMEMSET(digestBuffer, 0x0a, CC_SHA1_DIGEST_LENGTH);
    
	status = CCECCryptorSignHash(privateKey, 
                                 digestBuffer, CC_SHA1_DIGEST_LENGTH,
                                 signedData, &signedDataLen);
    
	if (kCCSuccess != status) return false;
	
	status = CCECCryptorVerifyHash(publicKey, 
                                   digestBuffer, CC_SHA1_DIGEST_LENGTH, 
                                   signedData, signedDataLen, &isValid);
    
	if (kCCSuccess != status || isValid != 1) return false;
	return true;	
}


#pragma mark API (SPI for now)


CCCryptorStatus 
CCECCryptorGeneratePair(size_t nbits, CCECCryptorRef *publicKey, CCECCryptorRef *privateKey)
{
    CCCryptorStatus retval;
    CCECCryptor *privateCryptor = NULL;
    CCECCryptor *publicCryptor = NULL;
    struct ccrng_state *theRng = ccDRBGGetRngState();
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!ccec_keysize_is_supported(nbits)) return kCCParamError;
    ccec_const_cp_t cp = ccec_get_cp(nbits);    
    cc_size n = ccec_cp_n(cp);
    __Require_Action((privateCryptor = ccMallocECCryptor(nbits, ccECKeyPrivate)) != NULL, errOut, retval = kCCMemoryFailure);
    privateCryptor->keySize = nbits;

    __Require_Action((ccec_generate_key(cp, theRng, privateCryptor->ecKey.private) == 0), errOut, retval = kCCDecodeError);
        
    privateCryptor->keyType = ccECKeyPrivate;
    
    __Require_Action((publicCryptor = CCECCryptorGetPublicKeyFromPrivateKey(privateCryptor)) != NULL, errOut, retval = kCCMemoryFailure);
    
    __Require_Action(ccECpairwiseConsistencyCheck(privateCryptor, publicCryptor) == true, errOut, retval = kCCDecodeError);
    
    *publicKey = publicCryptor;
    *privateKey = privateCryptor;

    return kCCSuccess;
    
errOut:
    if(privateCryptor) ccECCryptorClear(privateCryptor);
    if(publicCryptor) ccECCryptorClear(publicCryptor);
    *publicKey = *privateKey = NULL;
    return kCCDecodeError;
    
}

CCECCryptorRef 
CCECCryptorGetPublicKeyFromPrivateKey(CCECCryptorRef privateKey)
{
    CCECCryptor *publicCryptor = NULL;

    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    __Require((publicCryptor = ccMallocECCryptor(privateKey->keySize, ccECKeyPublic)) != NULL, errOut);
    if(!ccec_keysize_is_supported(privateKey->keySize)) return kCCParamError;
    ccec_const_cp_t cp = ccec_get_cp(privateKey->keySize);    
    size_t ctx_size = ccec_pub_ctx_size(ccec_cp_prime_size(cp));
    CC_XMEMCPY(publicCryptor->ecKey.public, privateKey->ecKey.public, ctx_size);
    publicCryptor->keySize = privateKey->keySize;
    publicCryptor->keyType = ccECKeyPublic;
    
    if(ccECpairwiseConsistencyCheck(privateKey, publicCryptor) == false) goto errOut;
    return publicCryptor;
    
errOut:
    if(publicCryptor) ccECCryptorClear(publicCryptor);
    return NULL;
    
}


CCCryptorStatus 
CCECCryptorGetKeyComponents(CCECCryptorRef ecKey, size_t *keySize,
                            uint8_t *qX, size_t *qXLength, 
                            uint8_t *qY, size_t *qYLength,
                            uint8_t *d, size_t *dLength)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    switch(ecKey->keyType) {
        case ccECKeyPublic:
            if(ccec_get_pubkey_components(ecKey->ecKey.public, keySize, 
                                          qX, qXLength, 
                                          qY, qYLength)) return kCCMemoryFailure;
            break;
        case ccECKeyPrivate:
            if(ccec_get_fullkey_components(ecKey->ecKey.private, keySize,
                                           qX, qXLength, 
                                           qY, qYLength, 
                                           d, dLength)) return kCCMemoryFailure;
            break;
        default: return kCCParamError;
    }
    return kCCSuccess;
}

CCCryptorStatus
CCECCryptorCreateFromData(size_t nbits,
                          uint8_t *qX, size_t qXLength, 
                          uint8_t *qY, size_t qYLength,
                          CCECCryptorRef *ref)
{
    CCECCryptor *publicCryptor;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    *ref = NULL;
    if((publicCryptor = ccMallocECCryptor(nbits, ccECKeyPublic)) == NULL) return kCCMemoryFailure;
    if(ccec_make_pub(nbits, qXLength, qX, qYLength, qY, publicCryptor->ecKey.public)) {
        ccECCryptorClear(publicCryptor);
        return kCCDecodeError;
    }
    publicCryptor->keyType = ccECKeyPublic;

    *ref = publicCryptor;
    return kCCSuccess;
}

CCECKeyType CCECGetKeyType(CCECCryptorRef key)
{
    CCECCryptor *cryptor = key;
    CCECKeyType retval;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(key == NULL) return ccECBlankPublicKey;
    retval = cryptor->keyType;
    if(retval != ccECKeyPublic && retval != ccECKeyPrivate) return ccECBadKey;
    return retval;
}

int CCECGetKeySize(CCECCryptorRef key)
{
    CCECCryptor *cryptor = key;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(key == NULL) return kCCParamError;
    return key->keySize;
}

void 
CCECCryptorRelease(CCECCryptorRef key)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccECCryptorClear(key);
}

CCCryptorStatus CCECCryptorImportPublicKey(void *keyPackage, size_t keyPackageLen, CCECCryptorRef *key)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    return CCECCryptorImportKey(kCCImportKeyBinary, keyPackage, keyPackageLen, ccECKeyPublic, key);
}


CCCryptorStatus CCECCryptorImportKey(CCECKeyExternalFormat format, void *keyPackage, size_t keyPackageLen, CCECKeyType keyType, CCECCryptorRef *key)
{
    CCECCryptor *cryptor = NULL;
    CCCryptorStatus retval = kCCSuccess;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(keyPackage == NULL) return kCCParamError;
        
    switch(format) {
        case kCCImportKeyBinary:
            if(keyType == ccECKeyPrivate) {
                size_t nbits = ccec_x963_import_priv_size(keyPackageLen);
                if((cryptor = ccMallocECCryptor(nbits, ccECKeyPrivate)) == NULL) return kCCMemoryFailure;
                ccec_const_cp_t cp = ccec_get_cp(nbits);
                __Require_Action(ccec_x963_import_priv(cp, keyPackageLen, keyPackage, cryptor->ecKey.private) == 0, errOut, retval = kCCDecodeError);
                cryptor->keySize = nbits;
            } else if(keyType == ccECKeyPublic) {
                size_t nbits = ccec_x963_import_pub_size(keyPackageLen);
                if((cryptor = ccMallocECCryptor(nbits, ccECKeyPublic)) == NULL) return kCCMemoryFailure;
                ccec_const_cp_t cp = ccec_get_cp(nbits);
                __Require_Action(ccec_x963_import_pub(cp, keyPackageLen, keyPackage, cryptor->ecKey.public) == 0, errOut, retval = kCCDecodeError);
                cryptor->keySize = nbits;
            } else return kCCParamError;

            cryptor->keyType = keyType;
            *key = cryptor;
            break;
        case kCCImportKeyDER:
            retval = kCCUnimplemented;
            break;
        default:
            retval = kCCParamError;
            break;
    }
    
    
errOut:
    if(retval) {
        *key = NULL;
        if(cryptor) ccECCryptorClear(cryptor);
    }
    
    return retval;
}


CCCryptorStatus CCECCryptorExportPublicKey(CCECCryptorRef key, void *out, size_t *outLen)
{    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(key == NULL) return kCCParamError;
    if(out == NULL) return kCCParamError;
    
    return CCECCryptorExportKey(kCCImportKeyBinary, out, outLen, ccECKeyPublic, key);
}

CCCryptorStatus CCECCryptorExportKey(CCECKeyExternalFormat format, void *keyPackage, size_t *keyPackageLen, CCECKeyType keyType, CCECCryptorRef key)
{
    CCCryptorStatus retval = kCCSuccess;
    unsigned long len = *keyPackageLen;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(key == NULL) return kCCParamError;
    if(keyPackage == NULL) return kCCParamError;
    
    switch(format) {
        case kCCImportKeyBinary: {
            CCECCryptorRef tmpkey;
            size_t len = ccec_x963_export_size(keyType == ccECKeyPrivate, key->ecKey.private);
            
            if(len > *keyPackageLen) {
                *keyPackageLen = len;
                return kCCMemoryFailure;
            }
            *keyPackageLen = len;
            
            ccec_x963_export(keyType == ccECKeyPrivate, keyPackage, key->ecKey.private);
            break;
        }
        case kCCImportKeyDER:
            retval = kCCUnimplemented;
            break;
        default:
            retval = kCCParamError;
            break;
    }

    return retval;    
}



CCCryptorStatus 
CCECCryptorSignHash(CCECCryptorRef privateKey, 
                    const void *hashToSign, size_t hashSignLen,
                    void *signedData, size_t *signedDataLen)
{
    CCCryptorStatus retval = kCCSuccess;
    CCECCryptor *privateCryptor = privateKey;
    
    // CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(privateKey == NULL || hashToSign == NULL || signedData == NULL || signedDataLen == NULL) return kCCParamError;
    
    struct ccrng_state *therng = ccDRBGGetRngState();
    
    if(ccec_sign(privateKey->ecKey.private, hashSignLen, hashToSign, signedDataLen, signedData, therng) != 0)
        retval = kCCDecodeError;
    return retval;
}



CCCryptorStatus 
CCECCryptorVerifyHash(CCECCryptorRef publicKey,
                      const void *hash, size_t hashLen, 
                      const void *signedData, size_t signedDataLen, uint32_t *valid)
{
    CCCryptorStatus retval = kCCSuccess;
    bool           stat = 0;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(publicKey == NULL || hash == NULL || signedData == NULL) return kCCParamError;
    
    if(ccec_verify(publicKey->ecKey.public, hashLen, hash,
                   signedDataLen, signedData, &stat)) retval = kCCDecodeError;
	*valid = stat;
    return retval;
}


#pragma mark API for ECDH - needs corecrypto key import / export capability (SPI for now)


CCCryptorStatus 
CCECCryptorWrapKey(CCECCryptorRef publicKey, 
                   const void *plainText, size_t plainTextLen, 
                   void *cipherText, size_t *cipherTextLen,
                   CCDigestAlg digestType)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    return kCCUnimplemented;
}


CCCryptorStatus 
CCECCryptorUnwrapKey(CCECCryptorRef privateKey, 
                     const void *cipherText, size_t cipherTextLen,
                     void *plainText, size_t *plainTextLen)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    return kCCUnimplemented;
}


CCCryptorStatus 
CCECCryptorComputeSharedSecret(CCECCryptorRef privateKey, CCECCryptorRef publicKey, 
                               void *out, size_t *outLen)
{
    CCCryptorStatus retval = kCCSuccess;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(privateKey == NULL || publicKey == NULL) return kCCParamError;
    if(out == NULL) return kCCParamError;
    
    if(ccec_compute_key(privateKey->ecKey.private, publicKey->ecKey.public,
                        outLen, out)) return kCCDecodeError;
    
    return retval;
}


Added Source/API/CommonGCMCryptor.c.

















































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_GCM_FUNCTIONS
#include "ccMemory.h"
#include "ccdebug.h"
#include "CommonCryptor.h"
#include "CommonCryptorSPI.h"
#include "CommonCryptorPriv.h"
#include <corecrypto/ccmode_factory.h>


CCCryptorStatus
CCCryptorGCMAddIV(CCCryptorRef cryptorRef,
                	const void 		*iv,
                    size_t ivLen)
{
	CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    ccmode_gcm_set_iv(cryptor->ctx[cryptor->op].gcm, ivLen, iv);
 	return kCCSuccess;
}


CCCryptorStatus
CCCryptorGCMAddAAD(CCCryptorRef cryptorRef,
                	const void 		*aData,
                    size_t aDataLen)
{
	CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    
    ccmode_gcm_gmac(cryptor->ctx[cryptor->op].gcm, aDataLen, aData);
 	return kCCSuccess;
}

// This is for old iOS5 clients
CCCryptorStatus
CCCryptorGCMAddADD(CCCryptorRef cryptorRef,
                   const void 		*aData,
                   size_t aDataLen)
{
    return CCCryptorGCMAddAAD(cryptorRef, aData, aDataLen);
}

// This was a temp mistake in MacOSX8
CCCryptorStatus
CCCryptorGCMaddAAD(CCCryptorRef cryptorRef,
                   const void 		*aData,
                   size_t aDataLen)
{
    return CCCryptorGCMAddAAD(cryptorRef, aData, aDataLen);
}



CCCryptorStatus CCCryptorGCMEncrypt(
	CCCryptorRef cryptorRef,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
{
	CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    if(dataIn == NULL || dataOut == NULL) return kCCParamError;
    
    ccmode_gcm_encrypt(cryptor->ctx[cryptor->op].gcm, dataInLength, dataIn, dataOut);
 	return kCCSuccess;
}



CCCryptorStatus CCCryptorGCMDecrypt(
	CCCryptorRef cryptorRef,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
{
	CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    if(dataIn == NULL || dataOut == NULL) return kCCParamError;

    ccmode_gcm_decrypt(cryptor->ctx[cryptor->op].gcm, dataInLength, dataIn, dataOut);
 	return kCCSuccess;
}



CCCryptorStatus CCCryptorGCMFinal(
	CCCryptorRef cryptorRef,
	const void *tag,
	size_t *tagLength)
{
	CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
	if(tag == NULL || tagLength == NULL)  return kCCParamError;
    
    ccmode_gcm_finalize(cryptor->ctx[cryptor->op].gcm, tagLength, tag);
 	return kCCSuccess;
}



CCCryptorStatus CCCryptorGCMReset(
	CCCryptorRef cryptorRef)
{
	CCCompatCryptor *compat_cryptor = cryptorRef;
    CCCryptor	*cryptor;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if(compat_cryptor == NULL)  return kCCParamError;
    cryptor = compat_cryptor->cryptor;
    ccmode_gcm_reset(cryptor->ctx[cryptor->op].gcm);
 	return kCCSuccess;
}



CCCryptorStatus CCCryptorGCM(
	CCOperation 	op,				/* kCCEncrypt, kCCDecrypt */
	CCAlgorithm		alg,
	const void 		*key,			/* raw key material */
	size_t 			keyLength,	
	const void 		*iv,
	size_t 			ivLen,
	const void 		*aData,
	size_t 			aDataLen,
	const void 		*dataIn,
	size_t 			dataInLength,
  	void 			*dataOut,
	const void 		*tag,
	size_t 			*tagLength)
{
    CCCryptorRef cryptorRef;
    CCCryptorStatus retval;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering Op: %d Cipher: %d\n", op, alg);

    retval = CCCryptorCreateWithMode(op, kCCModeGCM, alg, 0, NULL, key, keyLength,
                                         NULL, 0, 0, 0, &cryptorRef);
    if(retval) return retval;
    
    // IV is optional
    if(ivLen) {
        retval = CCCryptorGCMAddIV(cryptorRef, iv, ivLen);
        if(retval) return retval;
    }
    
    // This must always be called - even with no aData.
    retval = CCCryptorGCMaddAAD(cryptorRef, aData, aDataLen);
    if(retval) return retval;
    
    if(op == kCCEncrypt)
        retval = CCCryptorGCMEncrypt(cryptorRef, dataIn, dataInLength, dataOut);
    else if(op == kCCDecrypt)
        retval = CCCryptorGCMDecrypt(cryptorRef, dataIn, dataInLength, dataOut);
    else return kCCParamError;
    if(retval) return retval;

    retval = CCCryptorGCMFinal(cryptorRef, tag, tagLength);
    CCCryptorRelease(cryptorRef);
    
    return retval;
}


Changes to Source/API/CommonHMAC.c.

1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
|
|







1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

32

33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

55

56
57


58
59





60
61




62

63
64
65

66
67



68


69



70
71
72
73
74
75
76
77
78
79
80
81
82



83

84

85
86
87

88
89
90
91



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138

139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181


182
183
184
185
186
187
188
189



190






191
192







193
194





195
196

197
198
199
200
201
202
203
204
205
206
207
208






209

210







211



212

213



214





 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 * CommonHMAC.h - Keyed Message Authentication Code (HMAC) functions.
 *
 * Created 3/27/2006 by Doug Mitchell.
 */

#include <CommonCrypto/CommonHMAC.h>
#include <strings.h>

#include <stdlib.h>

#include <assert.h>

#ifndef	NDEBUG
#define ASSERT(s)
#else
#define ASSERT(s)	assert(s)
#endif

/* 
 * Callouts for digest ops.
 * The void *ctx pointers are needed to accommodate different underlying
 * digest context types. 
 */
typedef void (*ccDigestInit)(void *ctx);
typedef void (*ccDigestUpdate)(void *ctx, const void *data, CC_LONG len);
typedef void (*ccDigestFinal)(unsigned char *md, void *ctx);

#define HMAC_MAX_BLOCK_SIZE		CC_SHA512_BLOCK_BYTES
#define HMAC_MAX_DIGEST_SIZE	CC_SHA512_DIGEST_LENGTH

/* 
 * This is what a CCHmacContext actually points to.

 */

typedef struct {
	uint32_t			digestLen;


	uint32_t			blockLen;
	union {





		CC_MD5_CTX		md5Ctx;
		CC_SHA1_CTX		sha1Ctx;




		CC_SHA256_CTX 	sha256Ctx;

		CC_SHA512_CTX 	sha512Ctx;
	} digest;
	uint8_t				k_opad[HMAC_MAX_BLOCK_SIZE];	/* max block size */

	
	ccDigestInit		digestInit;



	ccDigestUpdate		digestUpdate;


	ccDigestFinal		digestFinal;



} _CCHmacContext;

void CCHmacInit(
	CCHmacContext *ctx, 
	CCHmacAlgorithm algorithm,	/* kCCHmacSHA1, kCCHmacMD5 */
	const void *key,
	size_t keyLength)			/* length of key in bytes */
{
	_CCHmacContext	*hmacCtx = (_CCHmacContext *)ctx;
	uint8_t			tk[HMAC_MAX_DIGEST_SIZE];
	uint8_t			*keyP;
	uint32_t		byte;
	uint8_t			k_ipad[HMAC_MAX_BLOCK_SIZE]; 





	/* if this fails, it's time to adjust CC_HMAC_CONTEXT_SIZE */

	ASSERT(sizeof(_CCHmacContext) < sizeof(CCHmacContext));
	
	if(hmacCtx == NULL) {

		return;
	}
	
	memset(hmacCtx, 0, sizeof(*hmacCtx));



	
	switch(algorithm) {
		case kCCHmacAlgMD5:
			hmacCtx->digestLen    = CC_MD5_DIGEST_LENGTH;
			hmacCtx->blockLen     = CC_MD5_BLOCK_BYTES;
			hmacCtx->digestInit   = (void *)CC_MD5_Init;
			hmacCtx->digestUpdate = (void *)CC_MD5_Update;
			hmacCtx->digestFinal  = (void *)CC_MD5_Final;
			break;
		case kCCHmacAlgSHA1:
			hmacCtx->digestLen    = CC_SHA1_DIGEST_LENGTH;
			hmacCtx->blockLen     = CC_SHA1_BLOCK_BYTES;
			hmacCtx->digestInit   = (void *)CC_SHA1_Init;
			hmacCtx->digestUpdate = (void *)CC_SHA1_Update;
			hmacCtx->digestFinal  = (void *)CC_SHA1_Final;
			break;
		case kCCHmacAlgSHA224:
			hmacCtx->digestLen    = CC_SHA224_DIGEST_LENGTH;
			hmacCtx->blockLen     = CC_SHA224_BLOCK_BYTES;
			hmacCtx->digestInit   = (void *)CC_SHA224_Init;
			hmacCtx->digestUpdate = (void *)CC_SHA224_Update;
			hmacCtx->digestFinal  = (void *)CC_SHA224_Final;
			break;
		case kCCHmacAlgSHA256:
			hmacCtx->digestLen    = CC_SHA256_DIGEST_LENGTH;
			hmacCtx->blockLen     = CC_SHA256_BLOCK_BYTES;
			hmacCtx->digestInit   = (void *)CC_SHA256_Init;
			hmacCtx->digestUpdate = (void *)CC_SHA256_Update;
			hmacCtx->digestFinal  = (void *)CC_SHA256_Final;
			break;
		case kCCHmacAlgSHA384:
			hmacCtx->digestLen    = CC_SHA384_DIGEST_LENGTH;
			hmacCtx->blockLen     = CC_SHA384_BLOCK_BYTES;
			hmacCtx->digestInit   = (void *)CC_SHA384_Init;
			hmacCtx->digestUpdate = (void *)CC_SHA384_Update;
			hmacCtx->digestFinal  = (void *)CC_SHA384_Final;
			break;
		case kCCHmacAlgSHA512:
			hmacCtx->digestLen    = CC_SHA512_DIGEST_LENGTH;
			hmacCtx->blockLen     = CC_SHA512_BLOCK_BYTES;
			hmacCtx->digestInit   = (void *)CC_SHA512_Init;
			hmacCtx->digestUpdate = (void *)CC_SHA512_Update;
			hmacCtx->digestFinal  = (void *)CC_SHA512_Final;
			break;
		default:
			return;
	}

	
	hmacCtx->digestInit(&hmacCtx->digest);
	
	/* If the key is longer than block size, reset it to key=digest(key) */
	if (keyLength <= hmacCtx->blockLen)
		keyP = (uint8_t *)key;
	else {
		hmacCtx->digestUpdate(&hmacCtx->digest, key, keyLength);
		hmacCtx->digestFinal(tk, &hmacCtx->digest);
		keyP = tk;
		keyLength = hmacCtx->digestLen;
		hmacCtx->digestInit(&hmacCtx->digest);
	}
	
	/* The HMAC_<DIG> transform looks like:
	   <DIG> (K XOR opad || <DIG> (K XOR ipad || text))
	   Where K is a n byte key
	   ipad is the byte 0x36 repeated 64 times.
	   opad is the byte 0x5c repeated 64 times.
	   text is the data being protected.
	  */
	/* Copy the key into k_ipad and k_opad while doing the XOR. */
	for (byte = 0; byte < keyLength; byte++)
	{
		k_ipad[byte] = keyP[byte] ^ 0x36;
		hmacCtx->k_opad[byte] = keyP[byte] ^ 0x5c;
	}
	/* Fill the remainder of k_ipad and k_opad with 0 XORed with the appropriate value. */
	if (keyLength < hmacCtx->blockLen)
	{
		memset (k_ipad + keyLength, 0x36, hmacCtx->blockLen - keyLength);
		memset (hmacCtx->k_opad + keyLength, 0x5c, hmacCtx->blockLen - keyLength);
	}
	hmacCtx->digestUpdate(&hmacCtx->digest, k_ipad, hmacCtx->blockLen);
}

void CCHmacUpdate(
	CCHmacContext *ctx, 
	const void *dataIn,
	size_t dataInLength)			/* length of data in bytes */
{
	_CCHmacContext	*hmacCtx = (_CCHmacContext *)ctx;
	hmacCtx->digestUpdate(&hmacCtx->digest, dataIn, dataInLength);


}

void CCHmacFinal(
	CCHmacContext *ctx, 
	void *macOut)
{
	_CCHmacContext	*hmacCtx = (_CCHmacContext *)ctx;
	hmacCtx->digestFinal(macOut, &hmacCtx->digest);



	hmacCtx->digestInit(&hmacCtx->digest);






	/* Perform outer digest */
	hmacCtx->digestUpdate(&hmacCtx->digest, hmacCtx->k_opad, hmacCtx->blockLen);







	hmacCtx->digestUpdate(&hmacCtx->digest, macOut, hmacCtx->digestLen);
	hmacCtx->digestFinal(macOut, &hmacCtx->digest);





}


/*
 * Stateless, one-shot HMAC function. 
 * Output is written to caller-spullied buffer, as in CCHmacFinal().
 */
void CCHmac(
	CCHmacAlgorithm algorithm,	/* kCCHmacSHA1, kCCHmacMD5 */
	const void *key,
	size_t keyLength,			/* length of key in bytes */
	const void *data,
	size_t dataLength,			/* length of data in bytes */
	void *macOut)				/* MAC written here */
{






	CCHmacContext ctx;

	







	CCHmacInit(&ctx, algorithm, key, keyLength);



	CCHmacUpdate(&ctx, data, dataLength);

	CCHmacFinal(&ctx, macOut);



}












|
|
<
<
<
|
|
|
>
|
>
|







<
<
<
<
<
<
<
<
<
|
|



>

>

|
>
>
|
|
>
>
>
>
>
|
|
>
>
>
>
|
>
|
|
|
>
|
|
>
>
>
|
>
>
|
>
>
>
|


|
|
|
|

|

|

|
>
>
>
|
>
|
>
|


>
|
|

<
>
>
>
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
>

|
|
<
<
<
|
<
<
<
<
<

|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
<
|
<



|
|
|

|
|
>
>



|
|

|
|
>
>
>
|
>
>
>
>
>
>
|
|
>
>
>
>
>
>
>
|
|
>
>
>
>
>


>


|


|
|
|
|
|
|

>
>
>
>
>
>
|
>
|
>
>
>
>
>
>
>
|
>
>
>
|
>
|
>
>
>
|
>
>
>
>
>
17
18
19
20
21
22
23
24
25



26
27
28
29
30
31
32
33
34
35
36
37
38
39









40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109

110
111
112
113













































114
115
116
117
118



119





120
121














122
123


124

125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_HMAC_FUNCTIONS
#include "CommonHMAC.h"



#include "CommonHmacSPI.h"
#include "CommonDigest.h"
#include "CommonDigestSPI.h"
#include "CommonDigestPriv.h"
#include <corecrypto/cchmac.h>
#include "ccMemory.h"
#include "ccdebug.h"

#ifndef	NDEBUG
#define ASSERT(s)
#else
#define ASSERT(s)	assert(s)
#endif










#define	HMAC_MAX_BLOCK_SIZE     CC_SHA512_BLOCK_BYTES
#define	HMAC_MAX_DIGEST_SIZE    CC_SHA512_DIGEST_LENGTH

/* 
 * This is what a CCHmacContext actually points to.
 * we have 384 bytes to work with
 */

typedef struct {
    struct ccdigest_info *di;
    cchmac_ctx_decl(HMAC_MAX_BLOCK_SIZE, HMAC_MAX_DIGEST_SIZE, ctx);
} _NewHmacContext;


typedef struct {
    CCHmacAlgorithm ccHmacValue;
    CCDigestAlgorithm ccDigestAlg;
    const char *ccDigestName;
} ccHmac2DigestConversion;


const ccHmac2DigestConversion ccconversionTable[] = {
    { kCCHmacAlgSHA1, kCCDigestSHA1, "sha1" },
    { kCCHmacAlgMD5, kCCDigestMD5, "md5" },
    { kCCHmacAlgSHA224, kCCDigestSHA224, "sha224" },
    { kCCHmacAlgSHA256, kCCDigestSHA256, "sha256" },
    { kCCHmacAlgSHA384, kCCDigestSHA384, "sha384" },
    { kCCHmacAlgSHA512, kCCDigestSHA512, "sha512" },
};

const static int ccHmacConversionTableLength = sizeof(ccconversionTable) / sizeof(ccHmac2DigestConversion);

static struct ccdigest_info *
convertccHmacSelector(CCHmacAlgorithm oldSelector)
{
    int i;
    
    for(i=0; i<ccHmacConversionTableLength; i++) 
        if(oldSelector == ccconversionTable[i].ccHmacValue) {
            return CCDigestGetDigestInfo(ccconversionTable[i].ccDigestAlg);
        }
    return NULL;
}


void CCHmacInit(
                CCHmacContext *ctx, 
                CCHmacAlgorithm algorithm,	/* kCCHmacSHA1, kCCHmacMD5 */
                const void *key,
                size_t keyLength)		/* length of key in bytes */
{
	_NewHmacContext		*hmacCtx = (_NewHmacContext *)ctx;
	uint8_t			tk[HMAC_MAX_DIGEST_SIZE];
	const uint8_t	*keyP;
	uint32_t		byte;
	uint8_t			k_ipad[HMAC_MAX_BLOCK_SIZE];
    size_t          digestLen;
    size_t          blockLen;
    // CCDigestCtxPtr  digestCtx = &hmacCtx->digestCtx;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering Algorithm: %d\n", algorithm);


	ASSERT(sizeof(_NewHmacContext) < sizeof(CCHmacContext));    
	
	if(hmacCtx == NULL) {
        CC_DEBUG_LOG(CC_DEBUG, "NULL Context passed in\n");
        return;
    }
	

	if(key == NULL) {
        CC_DEBUG_LOG(CC_DEBUG, "NULL Context passed in\n");
        return;
    }














































	CC_XZEROMEM(hmacCtx, sizeof(_NewHmacContext));
	
    if((hmacCtx->di = convertccHmacSelector(algorithm)) == NULL) {
        CC_DEBUG_LOG(CC_DEBUG, "CCHMac Unknown Digest %d\n", algorithm);



        return;





	}
    














    cchmac_init(hmacCtx->di, hmacCtx->ctx, keyLength, key);
    


    

}

void CCHmacUpdate(
                  CCHmacContext *ctx, 
                  const void *dataIn,
                  size_t dataInLength)	/* length of data in bytes */
{
	_NewHmacContext	*hmacCtx = (_NewHmacContext *)ctx;

    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    cchmac_update(hmacCtx->di, hmacCtx->ctx, dataInLength, dataIn);
}

void CCHmacFinal(
                 CCHmacContext *ctx, 
                 void *macOut)
{
	_NewHmacContext	*hmacCtx = (_NewHmacContext *)ctx;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    cchmac_final(hmacCtx->di, hmacCtx->ctx, macOut);
}

void
CCHmacDestroy(CCHmacContextRef ctx)
{
	CC_XZEROMEM(ctx, sizeof(_NewHmacContext));
    CC_XFREE(ctx, sizeof(_NewHmacContext));
}


size_t
CCHmacOutputSizeFromRef(CCHmacContextRef ctx)
{
	_NewHmacContext		*hmacCtx = (_NewHmacContext *)ctx;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	return hmacCtx->di->output_size;
}


size_t
CCHmacOutputSize(CCDigestAlg alg)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	return CCDigestGetOutputSize(alg);
}


/*
 * Stateless, one-shot HMAC function. 
 * Output is written to caller-supplied buffer, as in CCHmacFinal().
 */
void CCHmac(
            CCHmacAlgorithm algorithm,	/* kCCHmacSHA1, kCCHmacMD5 */
            const void *key,
            size_t keyLength,		/* length of key in bytes */
            const void *data,
            size_t dataLength,		/* length of data in bytes */
            void *macOut)			/* MAC written here */
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering Algorithm: %d\n", algorithm);
    cchmac(convertccHmacSelector(algorithm), keyLength, key, dataLength, data, macOut);
}



CCHmacContextRef
CCHmacCreate(CCDigestAlg alg, const void *key, size_t keyLength)
{
	_NewHmacContext		*hmacCtx;
	uint8_t			tk[HMAC_MAX_DIGEST_SIZE];
	const uint8_t		*keyP;
	uint32_t		byte;
	uint8_t			k_ipad[HMAC_MAX_BLOCK_SIZE]; 
    size_t digestLen = CCDigestGetOutputSize(alg);
    size_t blockLen = CCDigestGetBlockSize(alg);
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	/* if this fails, it's time to adjust CC_HMAC_CONTEXT_SIZE */
    if((hmacCtx = CC_XMALLOC(sizeof(_NewHmacContext))) == NULL) return NULL;
	
	CC_XZEROMEM(hmacCtx, sizeof(_NewHmacContext));
	
    if((hmacCtx->di = CCDigestGetDigestInfo(alg)) == NULL) {
        CC_DEBUG_LOG(CC_DEBUG, "CCHMac Unknown Digest %d\n");
        return NULL;
	}
    
    cchmac_init(hmacCtx->di, hmacCtx->ctx, keyLength, key);
	return hmacCtx;
}

Changes to Source/API/CommonKeyDerivation.c.

1
2
3
4
5
6
7
8
9
10
11
12

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29




30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227






228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/*	$OpenBSD: pbkdf2.c,v 1.1 2008/06/14 06:28:27 djm Exp $	*/
/*
 * This version was derived by generalizing the original code by Damien Bergamini
 * for use with alternate pseudo-random functions.
 */

/*-
 * Copyright (c) 2008 Damien Bergamini <damien.bergamini@free.fr>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.

 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <sys/types.h>
#include <sys/param.h>
#include <stdio.h>

#include <string.h>
#include <limits.h>
#include <stdlib.h>





#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#include "CommonKeyDerivation.h"
#include "CommonKeyDerivationPriv.h"

#define kCCPRFHmacAlgSHA1hlen	CC_SHA1_DIGEST_LENGTH
#define kCCPRFHmacAlgSHA224hlen CC_SHA224_DIGEST_LENGTH
#define kCCPRFHmacAlgSHA256hlen CC_SHA256_DIGEST_LENGTH
#define kCCPRFHmacAlgSHA384hlen CC_SHA384_DIGEST_LENGTH
#define kCCPRFHmacAlgSHA512hlen CC_SHA512_DIGEST_LENGTH

#if defined(USE_DIGEST_PRF)
#define kCCPRFSHA1hlen			CC_SHA1_DIGEST_LENGTH
#define kCCPRFSHA224hlen		CC_SHA224_DIGEST_LENGTH
#define kCCPRFSHA256hlen		CC_SHA256_DIGEST_LENGTH
#define kCCPRFSHA384hlen		CC_SHA384_DIGEST_LENGTH
#define kCCPRFSHA512hlen		CC_SHA512_DIGEST_LENGTH
#define kCCPRFSkeinhlen			CC_SHA512_DIGEST_LENGTH
#define kCCPRFSHA3hlen			CC_SHA512_DIGEST_LENGTH
#endif /* USE_DIGEST_PRF */

// This is for the scratchspace - it's twice the size of the max PRF buffer + 4 to work within the pbkdf2 code we currently
// have.

#define CC_MAX_PRF_WORKSPACE 128+4

static size_t
getPRFhlen(CCPseudoRandomAlgorithm prf)
{
	switch(prf) {
		case kCCPRFHmacAlgSHA1:		return kCCPRFHmacAlgSHA1hlen;
		case kCCPRFHmacAlgSHA224:	return kCCPRFHmacAlgSHA224hlen;
		case kCCPRFHmacAlgSHA256:	return kCCPRFHmacAlgSHA256hlen;
		case kCCPRFHmacAlgSHA384:	return kCCPRFHmacAlgSHA384hlen;
		case kCCPRFHmacAlgSHA512:	return kCCPRFHmacAlgSHA512hlen;
#if defined(USE_DIGEST_PRF)
		case kCCPRFSHA1:			return kCCPRFSHA1hlen;
		case kCCPRFSHA224:			return kCCPRFSHA224hlen;
		case kCCPRFSHA256:			return kCCPRFSHA256hlen;
		case kCCPRFSHA384:			return kCCPRFSHA384hlen;
		case kCCPRFSHA512:			return kCCPRFSHA512hlen;
#endif /* USE_DIGEST_PRF */
		default: return 0;
	}
}

#if defined(USE_DIGEST_PRF)
static u_int8_t *
prefixSalt(const char *password, size_t passwordLen, u_int8_t *salt, size_t saltLen, u_int8_t *output)
{	
	memcpy(output, salt, saltLen);
	memcpy(output+saltLen, password, passwordLen);
	return output;
}
#endif /* USE_DIGEST_PRF */


static void 
PRF(CCPseudoRandomAlgorithm prf, const char *password, size_t passwordLen, u_int8_t *salt, size_t saltLen, u_int8_t *output)
{
	u_int8_t tmpbuf[1024]; // ZZZfor now
	
	switch(prf) {
		case kCCPRFHmacAlgSHA1:	
			CCHmac(kCCHmacAlgSHA1, password, passwordLen, salt, saltLen, output);
			break;
		case kCCPRFHmacAlgSHA224:
			CCHmac(kCCHmacAlgSHA224, password, passwordLen, salt, saltLen, output);
			break;
		case kCCPRFHmacAlgSHA256:
			CCHmac(kCCHmacAlgSHA256, password, passwordLen, salt, saltLen, output);
			break;
		case kCCPRFHmacAlgSHA384:
			CCHmac(kCCHmacAlgSHA384, password, passwordLen, salt, saltLen, output);
			break;
		case kCCPRFHmacAlgSHA512:
			CCHmac(kCCHmacAlgSHA512, password, passwordLen, salt, saltLen, output);
			break;
#if defined(USE_DIGEST_PRF)
		case kCCPRFSHA1:
			CC_SHA1(prefixSalt(password, passwordLen, salt, saltLen, tmpbuf), saltLen+passwordLen, output);
			break;
		case kCCPRFSHA224:
			CC_SHA224(prefixSalt(password, passwordLen, salt, saltLen, tmpbuf), saltLen+passwordLen, output);
			break;
		case kCCPRFSHA256:
			CC_SHA256(prefixSalt(password, passwordLen, salt, saltLen, tmpbuf), saltLen+passwordLen, output);
			break;
		case kCCPRFSHA384:
			CC_SHA384(prefixSalt(password, passwordLen, salt, saltLen, tmpbuf), saltLen+passwordLen, output);
			break;
		case kCCPRFSHA512:
			CC_SHA512(prefixSalt(password, passwordLen, salt, saltLen, tmpbuf), saltLen+passwordLen, output);
			break;
#endif /* USE_DIGEST_PRF */
			
	}
}


int 
CCKeyDerivationPBKDF( CCPBKDFAlgorithm algorithm, const char *password, size_t passwordLen,
					 const uint8_t *salt, size_t saltLen,
					 CCPseudoRandomAlgorithm prf, uint rounds, 
					 uint8_t *derivedKey, size_t derivedKeyLen)
{
	u_int8_t oldbuffer[CC_MAX_PRF_WORKSPACE], newbuffer[CC_MAX_PRF_WORKSPACE], 
			 saltCopy[CC_MAX_PRF_WORKSPACE+4], collector[CC_MAX_PRF_WORKSPACE];
	int rawblock, i, j, r, nblocks;
	size_t	hlen, offset;
	

	if(algorithm != kCCPBKDF2) return -1;
	
	/*
	 * Check initial parameters
	 */
	
	if (rounds < 1 || derivedKeyLen == 0)
		return -1; // bad parameters
	if (saltLen == 0 || saltLen > CC_MAX_PRF_WORKSPACE)
		return -1; // out of bounds parameters
	
	hlen = getPRFhlen(prf);
		
	/*
	 * FromSpec: Let l be the number of hLen-octet blocks in the derived key, rounding up, 
	 * and let r be the number of octets in the last block:
	 */
	
	nblocks = (derivedKeyLen+hlen-1)/hlen; // in the spec nblocks is referred to as l
	r = derivedKeyLen % hlen;
    r = (r) ? r: hlen;
		
	/*
	 * Make a copy of the salt buffer so we can concatenate the
	 * block counter for each series of rounds.
	 */
	
	memcpy(saltCopy, salt, saltLen);
	bzero(derivedKey, derivedKeyLen);
	
	/*
	 * FromSpec: 
	 *
	 * For each block of the derived key apply the function F defined below to the password P,
	 * the salt S, the iteration count c, and the block index to compute the block:
	 * 
	 *           F(P,S,c,i)=U1 \xorU2 \xorâ‹…â‹…â‹…\xorUc
	 *
	 * where
	 *				U1 =PRF(P,S||INT (i)),
	 *				U2 =PRF(P,U1), 
	 *				... 
	 *				Uc = PRF (P, Uc-1) .
	 */
	
	for(rawblock = 0; rawblock < nblocks; rawblock++) {
		int block = rawblock+1;
		int copyLen;

		offset = rawblock * hlen;
		copyLen = (block != nblocks) ? hlen: r;
		
		/*
		 * FromSpec: Here, INT (i) is a four-octet encoding of the integer i, most significant octet first.
		 */
		
		for(i=0; i<4; i++) saltCopy[saltLen+i] = (block >> 8*(3-i)) & 0xff;
		
		PRF(prf, password, passwordLen, saltCopy, saltLen+4, oldbuffer);					// Initial PRF with the modified salt
		
		memcpy(collector, oldbuffer, hlen);												// Initial value for this block of the derived key.
		
		for(i = 1; i < rounds; i++) {
			PRF(prf, password, passwordLen, oldbuffer, hlen, newbuffer);						// Subsequent PRF with the previous result as the salt
			memcpy(oldbuffer, newbuffer, hlen);
			for(j = 0; j < hlen; j++) collector[j] ^= newbuffer[j];					// Xoring the round into the collector
		}
		memcpy(derivedKey+offset, collector, copyLen);
	}
	
	/*
	 * Clear temp buffers.
	 */
	
	bzero(oldbuffer, CC_MAX_PRF_WORKSPACE);
	bzero(newbuffer, CC_MAX_PRF_WORKSPACE);
	bzero(collector, CC_MAX_PRF_WORKSPACE);
	bzero(saltCopy, CC_MAX_PRF_WORKSPACE+4);
	
	return 0;
}

#ifndef KERNEL
#include <mach/mach.h>
#include <mach/mach_time.h>
#define ROUNDMEASURE 100000






static uint64_t
timer()
{
	static mach_timebase_info_data_t    sTimebaseInfo;
    uint64_t        timeNano;

	if ( sTimebaseInfo.denom == 0 ) {
        (void) mach_timebase_info(&sTimebaseInfo);
    }
	
	timeNano = mach_absolute_time();
	return (uint64_t) (timeNano * sTimebaseInfo.numer) / (sTimebaseInfo.denom * 1000000);
}

uint
CCCalibratePBKDF(CCPBKDFAlgorithm algorithm, size_t passwordLen, size_t saltLen,
				 CCPseudoRandomAlgorithm prf, size_t derivedKeyLen, uint32_t msec)
{
	char        *password;
	uint8_t     *salt;
	uint64_t	startTime, endTime, elapsedTime;
	uint8_t     *derivedKey;
	int         i;


	if (derivedKeyLen == 0) return -1; // bad parameters
	if (saltLen == 0 || saltLen > CC_MAX_PRF_WORKSPACE) return -1; // out of bounds parameters
	if (passwordLen == 0 ) return -1; // out of bounds parameters
	if(algorithm != kCCPBKDF2) return -1;
    
	if((password = malloc(passwordLen)) == NULL) return -1;
	for(i=0; i<passwordLen; i++) password[i] = 'a';
	if((salt = malloc(saltLen)) == NULL) return -1;
	for(i=0; i<saltLen; i++) salt[i] = i%256;
	if((derivedKey = malloc(derivedKeyLen)) == NULL) return -1;

    for(elapsedTime = 0, i=0; i < 5 && elapsedTime == 0; i++) {
        startTime = timer();
        if(CCKeyDerivationPBKDF(algorithm, password, passwordLen, salt, saltLen, prf, ROUNDMEASURE, derivedKey, derivedKeyLen)) return -2;
        endTime = timer();

        elapsedTime = endTime - startTime;
	}
    
    if(elapsedTime == 0) return 123456; // arbitrary, but something is seriously wrong
    
	free(password);
	free(salt);
	free(derivedKey);
	   
	return (msec * ROUNDMEASURE)/elapsedTime;
}
#endif
<

<
<
<
|
<
<
|
<
<
<
>
|
<
<
<
<
<
<
<
<
|
<
<
<
|
<
<
<
>
>
>
>
|
<
<
|
|
|
|
|
|
<
<
|
<
<
<
<
<
<
<
<
<
|
<
<
|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
|
<
<
<
|
<
<
<
<
<
|
|
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<








|
<
<
<
|
>
|
|
<
<
<
|
<
<
<
<
|
<
|
<
<
<
<
|
<
<
<
|
<
<
<
<
|
<
<
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|


<



>
>
>
>
>
>





|

















|
>


|







|




|








|


|

1



2


3



4
5








6



7



8
9
10
11
12


13
14
15
16
17
18


19









20


21

22

















23

24



25





26
27
28



29

































30


31
32
33
34
35
36
37
38
39



40
41
42
43



44




45

46




47



48




49


50



51










52



53






























54
55
56

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

/*



 * Copyright (c) 2012 Apple Inc. All Rights Reserved.


 * 



 * @APPLE_LICENSE_HEADER_START@
 * 








 * This file contains Original Code and/or Modifications of Original Code



 * as defined in and that are subject to the Apple Public Source License



 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 


 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and


 * limitations under the License.









 * 


 * @APPLE_LICENSE_HEADER_END@

 */



















// #define COMMON_KEYDERIVATION_FUNCTIONS









#include "CommonKeyDerivation.h"
#include <corecrypto/ccpbkdf2.h>
#include "CommonDigestPriv.h"



#include "CommonDigestSPI.h"

































#include "ccdebug.h"




int 
CCKeyDerivationPBKDF( CCPBKDFAlgorithm algorithm, const char *password, size_t passwordLen,
					 const uint8_t *salt, size_t saltLen,
					 CCPseudoRandomAlgorithm prf, uint rounds, 
					 uint8_t *derivedKey, size_t derivedKeyLen)
{
    const struct ccdigest_info *di;




    CC_DEBUG_LOG(ASL_LEVEL_ERR, "PasswordLen %lu SaltLen %lU PRF %d Rounds %u DKLen %lu\n", passwordLen, saltLen, prf, rounds, derivedKeyLen);
    if(algorithm != kCCPBKDF2) return -1;
    switch(prf) {



        case kCCPRFHmacAlgSHA1: di = CCDigestGetDigestInfo(kCCDigestSHA1); break;




        case kCCPRFHmacAlgSHA224: di = CCDigestGetDigestInfo(kCCDigestSHA224); break;

        case kCCPRFHmacAlgSHA256: di = CCDigestGetDigestInfo(kCCDigestSHA256); break;




        case kCCPRFHmacAlgSHA384: di = CCDigestGetDigestInfo(kCCDigestSHA384); break;



        case kCCPRFHmacAlgSHA512: di = CCDigestGetDigestInfo(kCCDigestSHA512); break;




        default: return -1;


    }



    if(!password || !salt || !derivedKey || (derivedKeyLen == 0) || (rounds == 0)) return -1;










    



    ccpbkdf2_hmac(di, passwordLen, password, saltLen, salt, rounds, derivedKeyLen, derivedKey);






























    return 0;
}


#include <mach/mach.h>
#include <mach/mach_time.h>
#define ROUNDMEASURE 100000
// This is for the scratchspace - it's twice the size of the max PRF buffer + 4 to work within the pbkdf2 code we currently
// have.

#define CC_MAX_PRF_WORKSPACE 128+4


static uint64_t
timer()
{
	static mach_timebase_info_data_t    sTimebaseInfo;
    uint64_t        timeNano;
    
	if ( sTimebaseInfo.denom == 0 ) {
        (void) mach_timebase_info(&sTimebaseInfo);
    }
	
	timeNano = mach_absolute_time();
	return (uint64_t) (timeNano * sTimebaseInfo.numer) / (sTimebaseInfo.denom * 1000000);
}

uint
CCCalibratePBKDF(CCPBKDFAlgorithm algorithm, size_t passwordLen, size_t saltLen,
				 CCPseudoRandomAlgorithm prf, size_t derivedKeyLen, uint32_t msec)
{
	char        *password;
	uint8_t     *salt;
	uint64_t	startTime, endTime, elapsedTime;
	uint8_t     *derivedKey;
	int         i;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	if (derivedKeyLen == 0) return -1; // bad parameters
	if (saltLen == 0 || saltLen > CC_MAX_PRF_WORKSPACE) return -1; // out of bounds parameters
	if (passwordLen == 0 ) passwordLen = 1;
	if(algorithm != kCCPBKDF2) return -1;
    
	if((password = malloc(passwordLen)) == NULL) return -1;
	for(i=0; i<passwordLen; i++) password[i] = 'a';
	if((salt = malloc(saltLen)) == NULL) return -1;
	for(i=0; i<saltLen; i++) salt[i] = i%256;
	if((derivedKey = malloc(derivedKeyLen)) == NULL) return -1;
    
    for(elapsedTime = 0, i=0; i < 5 && elapsedTime == 0; i++) {
        startTime = timer();
        if(CCKeyDerivationPBKDF(algorithm, password, passwordLen, salt, saltLen, prf, ROUNDMEASURE, derivedKey, derivedKeyLen)) return -2;
        endTime = timer();
        
        elapsedTime = endTime - startTime;
	}
    
    if(elapsedTime == 0) return 123456; // arbitrary, but something is seriously wrong
    
	free(password);
	free(salt);
	free(derivedKey);
    
	return (msec * ROUNDMEASURE)/elapsedTime;
}

Deleted Source/API/CommonKeyDerivationPriv.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
 *  CommonKeyDerivationPriv.h
 *  CommonCrypto
 *
 *  Created by Richard Murphy on 1/13/10.
 *  Copyright 2010 McKenzie-Murphy. All rights reserved.
 *
 */

#include "CommonKeyDerivation.h"

/* Uncomment this if you want to enable using a pure digest as the PRF.  There currently
 * isn't a standard way of doing this.  We prepend the "key" material in front of the data
 * and hash the result in the current implementation.
 */

// #define USE_DIGEST_PRF

/* Reserved PRF IDs */

#if defined(USE_DIGEST_PRF)

enum {
	kCCPRFSHA1 = 6,
	kCCPRFSHA224 = 7,
	kCCPRFSHA256 = 8,
	kCCPRFSHA384 = 9,
	kCCPRFSHA512 = 10
};

static u_int8_t *
prefixSalt(const char *password, size_t passwordLen, u_int8_t *salt, size_t saltLen, u_int8_t *output);

#endif /* USE_DIGEST_PRF */

static size_t
getPRFhlen(CCPseudoRandomAlgorithm prf);


static void 
PRF(CCPseudoRandomAlgorithm prf, const char *password, size_t passwordLen,
		 u_int8_t *salt, size_t saltLen, u_int8_t *output);

static uint64_t 
timer(void);

/* 
	This or some version of it might go into the public API at some point
	the idea is that if some process goes wild while someone uses CCCalibratePBKDF()
	to determine the number of rounds to use for a desired amount of delay per attack
	the resulting number can be "sniff tested" to determine if it's in the ballpark
	and a "floor" can be set for the round count.
	
	The number "MIN_ROUNDS_PER_MSEC" is the result of running CCCalibratePBKDF for a
	10 char password and salt, HMAC-SHA256 to generate a 16 byte key on a 2.5 ghz macbook pro.
	
	To use the macro you'd do the following:
	
		rounds = CCCalibratePBKDF(kCCPBKDF2, passwordLen, saltLen, kCCPRFHmacAlgSHA256, derivedKeyLen, msec);
		rounds = FLOOR_ROUNDS(msec, rounds);
*/

#define MIN_ROUNDS_PER_MSEC 410
#define FLOOR_ROUNDS(MSEC,INROUNDS) (((INROUNDS)/(MSEC)) < MIN_ROUNDS_PER_MSEC) ? ((MSEC) * MIN_ROUNDS_PER_MSEC) : INROUNDS


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































Added Source/API/CommonRSACryptor.c.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_RSA_FUNCTIONS
#include "CommonRSACryptor.h"
#include "CommonDigest.h"
#include "CommonDigestSPI.h"
#include "CommonDigestPriv.h"

#include "CommonRandomSPI.h"
#include <corecrypto/ccrsa.h>
#include <corecrypto/ccrsa_priv.h>
#include <corecrypto/ccasn1.h>

#include "asn1Types.h"
#include "DER_Keys.h"
#include "DER_Encode.h"


#include "ccErrors.h"
#include "ccMemory.h"
// #include "ccCoreCryptoInterface.h"
#include "ccdebug.h"
#include <AssertMacros.h>

#pragma mark internal

#define kCCMaximumRSAKeyBits 4096
#define kCCMaximumRSAKeyBytes ccn_sizeof(kCCMaximumRSAKeyBits)
#define kCCRSAKeyContextSize ccrsa_full_ctx_size(kCCMaximumRSAKeyBytes)
#define RSA_PKCS1_PAD_ENCRYPT	0x02


typedef struct _CCRSACryptor {
    union {
        ccrsa_full_ctx *full;
        ccrsa_priv_ctx *private;
        ccrsa_pub_ctx *public;
        uint8_t *bytes;
    } rsaKey;
    size_t keySize;
    size_t ctxSize;
    CCRSAKeyType keyType;
} CCRSACryptor;

static CCRSACryptor *
ccMallocRSACryptor(size_t nbits, CCRSAKeyType keyType)
{
    CCRSACryptor *retval;
    size_t ctxSize = 0;
    cc_size n = ccn_nof(nbits);

    if((retval = CC_XMALLOC(sizeof(CCRSACryptor))) == NULL) return NULL;

    retval->keySize = nbits;
    retval->rsaKey.bytes = NULL;
    
    switch(keyType) {
        case ccRSAKeyPublic:
            retval->keyType = ccRSABlankPublicKey;
            retval->ctxSize = ccrsa_pub_ctx_size(ccn_sizeof(nbits));
            break;
        case ccRSAKeyPrivate:
            retval->keyType = ccRSABlankPrivateKey;
            retval->ctxSize = ccrsa_full_ctx_size(ccn_sizeof(nbits));
            break;
        default:
            retval = kCCParamError;
            goto errOut;
    }
    
    if((retval->rsaKey.bytes = CC_XMALLOC(retval->ctxSize)) == NULL) goto errOut;
    ccrsa_ctx_n(retval->rsaKey.full) = n;

    return retval;
errOut:
    if(retval) {
        CC_XFREE(retval, sizeof(CCRSACryptor));
    }
    return retval;
}

static void
ccRSACryptorClear(CCRSACryptorRef theKey)
{
    size_t nbits;
    size_t ctxSize = 0;
    
    CCRSACryptor *key = (CCRSACryptor *) theKey;
    if(!key) return;
    
    if(ctxSize && key->rsaKey.bytes) {
        CC_XZEROMEM(key->rsaKey.bytes, key->ctxSize);
        CC_XFREE(key->rsaKey.bytes, key->ctxSize);
    }
    
    CC_XZEROMEM(key, sizeof(CCRSACryptor));
    CC_XFREE(key, sizeof(CCRSACryptor));
}

/*
 
 This is done for FIPS.  Basically we make sure that the two keys will work to encrypt/decrypt
 each other's data.  This will test up to 4K bit keys.
 
*/

#define MAXKEYTEST 512

static bool
ccRSApairwiseConsistencyCheck(CCRSACryptorRef privateKey, CCRSACryptorRef publicKey)
{
	CCCryptorStatus status = kCCSuccess;
    uint8_t digestBuffer[CC_SHA1_DIGEST_LENGTH];
	size_t theDataLen = MAXKEYTEST, resultLen, recoveryLen;
	uint8_t theData[MAXKEYTEST];
	uint8_t theResult[MAXKEYTEST];
	uint8_t theRecovered[MAXKEYTEST];

    /* 
     
     the RSA keysize had better be equal - we convert keysizes to bytes since we need to
     work with the appropriate size data buffers for tests.
     
     */
    
    theDataLen = CCRSAGetKeySize(privateKey) / 8;
    if(theDataLen > MAXKEYTEST || theDataLen != (CCRSAGetKeySize(publicKey) / 8)) {
        return false;
    }
    
    /* Fill the input buffer for the test */
    
    CC_XMEMSET(theData, 0x0a, theDataLen);
    
    /* Encrypt the buffer with the private key then be sure the output isn't the same as the input */
    resultLen = theDataLen;
    status = CCRSACryptorCrypt(privateKey, theData, theDataLen, theResult, &resultLen);
        
	if (kCCSuccess != status) {
        return false;
    }
    
    if(CC_XMEMCMP(theData, theResult, theDataLen) == 0) { 
        return false; 
    }
    
    /* Decrypt the buffer with the public key and be sure the output matches the original input */
	
    recoveryLen = theDataLen;
    status = CCRSACryptorCrypt(publicKey, theResult, resultLen, theRecovered, &recoveryLen);

	if (kCCSuccess != status) { 
        return false; 
    }
    
    if(recoveryLen != theDataLen) { 
        return false; 
    }
    
    if(CC_XMEMCMP(theData, theRecovered, theDataLen) != 0) { 
        return false; 
    }
    
    /* Cleanup and leave */
    
    CC_XZEROMEM(theData, MAXKEYTEST);
    CC_XZEROMEM(theResult, MAXKEYTEST);
    CC_XZEROMEM(theRecovered, MAXKEYTEST);

	return true;	
}


#pragma mark APIDone

CCCryptorStatus 
CCRSACryptorGeneratePair(size_t keysize, uint32_t e, CCRSACryptorRef *publicKey, CCRSACryptorRef *privateKey)
{
    CCCryptorStatus retval;
    CCRSACryptor *privateCryptor = NULL;
    CCRSACryptor *publicCryptor = NULL;
    struct ccrng_state *theRng1 = ccDRBGGetRngState();
    struct ccrng_state *theRng2 = ccDevRandomGetRngState();
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    // ccrsa_generate_key() requires the exponent as length / pointer to bytes
    cc_unit cc_unit_e = (cc_unit) e;
    
    size_t eSize = ccn_write_int_size(1, &cc_unit_e);
    uint8_t eBytes[eSize];
    ccn_write_int(1, &cc_unit_e, eSize, eBytes);
    
    *publicKey = *privateKey = NULL;
    
    __Require_Action((privateCryptor = ccMallocRSACryptor(keysize, ccRSAKeyPrivate)) != NULL, errOut, retval = kCCMemoryFailure);
        
    // __Require_Action((ccrsa_generate_key(keysize, privateCryptor->rsaKey.full, sizeof(e), &e, theRng) == 0), errOut, retval = kCCDecodeError);
    __Require_Action((ccrsa_generate_931_key(keysize, privateCryptor->rsaKey.full, eSize, eBytes, theRng1, theRng2) == 0), errOut, retval = kCCDecodeError);
    
    privateCryptor->keyType = ccRSAKeyPrivate;
    
    __Require_Action((publicCryptor = CCRSACryptorGetPublicKeyFromPrivateKey(privateCryptor)) != NULL, errOut, retval = kCCMemoryFailure);
    
    *publicKey = publicCryptor;
    *privateKey = privateCryptor;
    
    __Require_Action(ccRSApairwiseConsistencyCheck(*privateKey, *publicKey) == true, errOut, retval = kCCDecodeError);

    return kCCSuccess;
    
errOut:
    if(privateCryptor) ccRSACryptorClear(privateCryptor);
    if(publicCryptor) ccRSACryptorClear(publicCryptor);
    *publicKey = *privateKey = NULL;
    return retval;
}

CCRSACryptorRef CCRSACryptorGetPublicKeyFromPrivateKey(CCRSACryptorRef privateCryptorRef)
{
    int tcReturn;
    CCRSACryptor *publicCryptor = NULL, *privateCryptor = privateCryptorRef;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if((publicCryptor = ccMallocRSACryptor(privateCryptor->keySize, ccRSAKeyPublic)) == NULL)  return NULL;    
    CC_XMEMCPY(publicCryptor->rsaKey.public, privateCryptor->rsaKey.private, ccrsa_pub_ctx_size(privateCryptor->keySize));
    publicCryptor->keyType = ccRSAKeyPublic;
    return publicCryptor;
}

CCRSAKeyType CCRSAGetKeyType(CCRSACryptorRef key)
{
    CCRSACryptor *cryptor = key;
    CCRSAKeyType retval;

    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(key == NULL) return ccRSABadKey;
    retval = cryptor->keyType;
    if(retval != ccRSAKeyPublic && retval != ccRSAKeyPrivate) return ccRSABadKey;
    return retval;
}

int CCRSAGetKeySize(CCRSACryptorRef key)
{
    CCRSACryptor *cryptor = key;
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(key == NULL) return kCCParamError;    
    
    return cryptor->keySize;
}

void 
CCRSACryptorRelease(CCRSACryptorRef key)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccRSACryptorClear(key);
}


CCCryptorStatus CCRSACryptorImport(const void *keyPackage, size_t keyPackageLen, CCRSACryptorRef *key)
{
    CCRSACryptor *cryptor = NULL;
    CCCryptorStatus retval;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!keyPackage || !key) return kCCParamError;

    DERItem keyItem = {(DERByte *)keyPackage, keyPackageLen};
    DERRSAPubKeyPKCS1 decodedKey;
    
	if(DERParseSequence(&keyItem, DERNumRSAPubKeyPKCS1ItemSpecs, DERRSAPubKeyPKCS1ItemSpecs,
                        &decodedKey, sizeof(decodedKey))) return kCCDecodeError;
    
    size_t n = ccn_nof_size(decodedKey.modulus.length);
    cc_unit m[n], e[n];
    __Require_Action(ccn_read_uint(n, m, decodedKey.modulus.length, decodedKey.modulus.data) == 0, errOut, retval = kCCParamError);
    __Require_Action(ccn_read_uint(n, e, decodedKey.pubExponent.length, decodedKey.pubExponent.data) == 0, errOut, retval = kCCParamError);
    size_t nbits = ccn_bitlen(n, m);
        
    __Require_Action((cryptor = ccMallocRSACryptor(nbits, ccRSAKeyPublic)) != NULL, errOut, retval = kCCMemoryFailure);
    
    ccrsa_init_pub(cryptor->rsaKey.public, m, e);
    
    *key = cryptor;
    cryptor->keyType = ccRSAKeyPublic;
    return kCCSuccess;
    
errOut:
    if(cryptor) ccRSACryptorClear(cryptor);
    *key = NULL;
    return retval;
}


CCCryptorStatus CCRSACryptorExport(CCRSACryptorRef key, void *out, size_t *outLen)
{
	CCRSACryptor *cryptor = key;
    CCCryptorStatus retval = kCCSuccess;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!key || !out) return kCCParamError;
    __Require_Action(ccrsa_export_pub(key->rsaKey.public, outLen, out) == 0, errOut, retval = kCCDecodeError);

errOut:
    return retval;
}







CCCryptorStatus 
CCRSACryptorEncrypt(CCRSACryptorRef publicKey, CCAsymetricPadding padding, const void *plainText, size_t plainTextLen, void *cipherText, size_t *cipherTextLen,
	const void *tagData, size_t tagDataLen, CCDigestAlgorithm digestType)
{
    CCCryptorStatus retval = kCCSuccess;
    ccrsa_pub_ctx_t pubkey;

    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!publicKey || !cipherText || !plainText || !cipherTextLen) return kCCParamError;

    pubkey.pub = publicKey->rsaKey.public;
    
    switch(padding) {
        case ccPKCS1Padding:
            if(ccrsa_encrypt_eme_pkcs1v15(pubkey, ccDRBGGetRngState(), cipherTextLen, cipherText, plainTextLen, plainText)  != 0) 
                retval =  kCCDecodeError;
            break;
        case ccOAEPPadding:         
            if(ccrsa_encrypt_oaep(pubkey, CCDigestGetDigestInfo(digestType), ccDRBGGetRngState(), cipherTextLen, cipherText, plainTextLen, plainText,
                                  tagDataLen, tagData) != 0) 
                retval =  kCCDecodeError;
            break;
        default:
            retval = kCCParamError;
            goto errOut;

    }
        
errOut:
    return retval;
}



CCCryptorStatus 
CCRSACryptorDecrypt(CCRSACryptorRef privateKey, CCAsymetricPadding padding, const void *cipherText, size_t cipherTextLen,
				 void *plainText, size_t *plainTextLen, const void *tagData, size_t tagDataLen, CCDigestAlgorithm digestType)
{
    CCCryptorStatus retval = kCCSuccess;
    ccrsa_full_ctx_t fullkey;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!privateKey || !cipherText || !plainText || !plainTextLen) return kCCParamError;

    fullkey.full = privateKey->rsaKey.private;
    
    switch (padding) {
        case ccPKCS1Padding:
            if(ccrsa_decrypt_eme_pkcs1v15(fullkey, plainTextLen, plainText, cipherTextLen, cipherText) != 0) 
                retval =  kCCDecodeError;
            break;
        case ccOAEPPadding:
            if(ccrsa_decrypt_oaep(fullkey, CCDigestGetDigestInfo(digestType), plainTextLen, plainText, cipherTextLen, cipherText,
                                  tagDataLen, tagData) != 0) 
                retval =  kCCDecodeError;
            break;
        default:
            goto errOut;
    }
    
errOut:
    
    return retval;
}

CCCryptorStatus 
CCRSACryptorCrypt(CCRSACryptorRef rsaKey, const void *in, size_t inLen, void *out, size_t *outLen)
{    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!rsaKey || !in || !out || !outLen) return kCCParamError;
    
    size_t keysizeBytes = rsaKey->keySize/8;
    
    if(inLen != keysizeBytes || *outLen < keysizeBytes) return kCCMemoryFailure;
    
    cc_size n = ccrsa_ctx_n(rsaKey->rsaKey.full);
    cc_unit buf[n];
    ccn_read_uint(n, buf, inLen, in);
    
    switch(rsaKey->keyType) {
        case ccRSAKeyPublic: 
            ccrsa_pub_crypt(rsaKey->rsaKey.public, buf, buf);
            break;
        case ccRSAKeyPrivate:
            ccrsa_priv_crypt(ccrsa_ctx_private(rsaKey->rsaKey.full), buf, buf);
            break;
        default:
            return kCCParamError;
    }
    
    *outLen = keysizeBytes;
    ccn_write_uint_padded(n, buf, *outLen, out);
    return kCCSuccess;
}



static inline cczp_read_uint(cczp_t r, size_t data_size, const uint8_t *data)
{
    if(ccn_read_uint(ccn_nof_size(data_size), CCZP_PRIME(r), data_size, data) != 0) return -1;
    CCZP_N(r) = ccn_nof_size(data_size);
    cczp_init(r);
    return 0;
}

static inline
CCCryptorStatus ccn_write_arg(size_t n, const cc_unit *source, uint8_t *dest, size_t *destLen)
{
    size_t len;
    if((len = ccn_write_uint_size(n, source)) > *destLen) {
        return kCCMemoryFailure;
    }
    *destLen = len;
    ccn_write_uint(n, source, *destLen, dest);
    return kCCSuccess;
}


CCCryptorStatus 
CCRSACryptorCreatePairFromData(uint32_t e, 
    uint8_t *xp1, size_t xp1Length,
    uint8_t *xp2, size_t xp2Length,
    uint8_t *xp, size_t xpLength,
    uint8_t *xq1, size_t xq1Length,
    uint8_t *xq2, size_t xq2Length,
    uint8_t *xq, size_t xqLength,
    CCRSACryptorRef *publicKey, CCRSACryptorRef *privateKey,
    uint8_t *retp, size_t *retpLength,
    uint8_t *retq, size_t *retqLength,
    uint8_t *retm, size_t *retmLength,
    uint8_t *retd, size_t *retdLength)
{
    CCCryptorStatus retval;
    CCRSACryptor *privateCryptor = NULL;
    CCRSACryptor *publicCryptor = NULL;
    cc_unit x_p1[ccn_nof_size(xp1Length)];
    cc_unit x_p2[ccn_nof_size(xp2Length)];
    cc_unit x_p[ccn_nof_size(xpLength)];
    cc_unit x_q1[ccn_nof_size(xq1Length)];
    cc_unit x_q2[ccn_nof_size(xq2Length)];
    cc_unit x_q[ccn_nof_size(xqLength)];
    cc_unit e_value[1];
    size_t nbits = xpLength * 8 + xqLength * 8; // or we'll add this as a parameter.  This appears to be correct for FIPS
    cc_size n = ccn_nof(nbits);
    cc_unit p[n], q[n], m[n], d[n];
    cc_size np, nq, nm, nd;
    
    np = nq = nm = nd = n;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    e_value[0] = (cc_unit) e;

    __Require_Action((privateCryptor = ccMallocRSACryptor(nbits, ccRSAKeyPrivate)) != NULL, errOut, retval = kCCMemoryFailure);

    ccrsa_pub_ctx_t pubk = ccrsa_ctx_public(privateCryptor->rsaKey.full);
    ccrsa_priv_ctx_t privk = ccrsa_ctx_private(privateCryptor->rsaKey.full);
    
    __Require_Action(ccn_read_uint(ccn_nof_size(xp1Length), x_p1, xp1Length, xp1) == 0, errOut, kCCParamError);
    __Require_Action(ccn_read_uint(ccn_nof_size(xp2Length), x_p2, xp2Length, xp2)== 0, errOut, kCCParamError);
    __Require_Action(ccn_read_uint(ccn_nof_size(xpLength), x_p, xpLength, xp) == 0, errOut, kCCParamError);
    __Require_Action(ccn_read_uint(ccn_nof_size(xq1Length), x_q1, xq1Length, xq1) == 0, errOut, kCCParamError);
    __Require_Action(ccn_read_uint(ccn_nof_size(xq2Length), x_q2, xq2Length, xq2) == 0, errOut, kCCParamError);
    __Require_Action(ccn_read_uint(ccn_nof_size(xqLength), x_q, xqLength, xq) == 0, errOut, kCCParamError);
    
	__Require_Action(ccrsa_make_931_key(nbits, 1, e_value, 
                                        ccn_nof_size(xp1Length), x_p1, ccn_nof_size(xp2Length), x_p2, ccn_nof_size(xpLength), x_p,
                                        ccn_nof_size(xq1Length), x_q1, ccn_nof_size(xq2Length), x_q2, ccn_nof_size(xqLength), x_q,
                                        privateCryptor->rsaKey.full,
                                        &np, p,
                                        &nq, q,
                                        &nm, m,
                                        &nd, d) == 0, errOut, retval = kCCDecodeError);
    
    privateCryptor->keyType = ccRSAKeyPrivate;
    
    __Require_Action((publicCryptor = CCRSACryptorGetPublicKeyFromPrivateKey(privateCryptor)) != NULL, errOut, retval = kCCMemoryFailure);

    *publicKey = publicCryptor;
    *privateKey = privateCryptor;
    ccn_write_arg(np, p, retp, retpLength);
    ccn_write_arg(nq, q, retq, retqLength);
    ccn_write_arg(nm, m, retm, retmLength);
    ccn_write_arg(nd, d, retd, retdLength);
    
    return kCCSuccess;
    
errOut:
    if(privateCryptor) ccRSACryptorClear(privateCryptor);
    if(publicCryptor) ccRSACryptorClear(publicCryptor);
    // CLEAR the bits
    *publicKey = *privateKey = NULL;
    return retval;

}



CCCryptorStatus
CCRSACryptorCreateFromData( CCRSAKeyType keyType, uint8_t *modulus, size_t modulusLength, 
                            uint8_t *exponent, size_t exponentLength,
                            uint8_t *p, size_t pLength, uint8_t *q, size_t qLength,
                            CCRSACryptorRef *ref)
{
    CCCryptorStatus retval = kCCSuccess;
	CCRSACryptor *rsaKey = NULL;
    size_t n = ccn_nof_size(modulusLength);
    cc_unit m[n];
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    __Require_Action(ccn_read_uint(n, m, modulusLength, modulus), errOut, retval = kCCParamError);
    size_t nbits = ccn_bitlen(n, m);

    __Require_Action((rsaKey = ccMallocRSACryptor(nbits, keyType)) != NULL, errOut, retval = kCCMemoryFailure);

    __Require_Action(ccn_read_uint(n, ccrsa_ctx_m(rsaKey->rsaKey.public), modulusLength, modulus), errOut, retval = kCCParamError);
    __Require_Action(ccn_read_uint(n, ccrsa_ctx_e(rsaKey->rsaKey.public), exponentLength, exponent), errOut, retval = kCCParamError);
    cczp_init(ccrsa_ctx_zm(rsaKey->rsaKey.public));
    rsaKey->keySize = ccn_bitlen(n, ccrsa_ctx_m(rsaKey->rsaKey.public));

	switch(keyType) {
		case ccRSAKeyPublic:
            rsaKey->keyType = ccRSAKeyPublic;
            break;
		
		case ccRSAKeyPrivate: {
            ccrsa_full_ctx_t fk;
            fk.full = rsaKey->rsaKey.full;
            ccrsa_pub_ctx_t pubk = ccrsa_ctx_public(rsaKey->rsaKey.public);
            ccrsa_priv_ctx_t privk = ccrsa_ctx_private(rsaKey->rsaKey.full);
            size_t psize = ccn_nof_size(pLength);
            size_t qsize = ccn_nof_size(qLength);

            
            CCZP_N(ccrsa_ctx_private_zp(privk)) = psize;
            __Require_Action(ccn_read_uint(psize, CCZP_PRIME(ccrsa_ctx_private_zp(privk)), pLength, p), errOut, kCCParamError);
            CCZP_N(ccrsa_ctx_private_zq(privk)) = qsize;
            __Require_Action(ccn_read_uint(qsize, CCZP_PRIME(ccrsa_ctx_private_zq(privk)), qLength, q), errOut, kCCParamError);

            ccrsa_crt_makekey(ccrsa_ctx_zm(pubk), ccrsa_ctx_e(pubk), ccrsa_ctx_d(fk),
                              ccrsa_ctx_private_zp(privk),
                              ccrsa_ctx_private_dp(privk), ccrsa_ctx_private_qinv(privk),
                              ccrsa_ctx_private_zq(privk), ccrsa_ctx_private_dq(privk));
            
            rsaKey->keyType = ccRSAKeyPrivate;

       		break;
        }
		
		default:
            retval = kCCParamError;
			goto errOut;
	}
	*ref = rsaKey;
	return kCCSuccess;
	
errOut:
	if(rsaKey) ccRSACryptorClear(rsaKey);
	return retval;
}




CCCryptorStatus
CCRSAGetKeyComponents(CCRSACryptorRef rsaKey, uint8_t *modulus, size_t *modulusLength, uint8_t *exponent, size_t *exponentLength,
                      uint8_t *p, size_t *pLength, uint8_t *q, size_t *qLength)
{
    CCRSACryptor *rsa = rsaKey;
    ccrsa_pub_ctx *pubkey = rsaKey->rsaKey.public;
    const cc_size n = ccrsa_ctx_n(pubkey);
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	switch(rsa->keyType) {
		case ccRSAKeyPublic: {
            if(ccrsa_get_pubkey_components(pubkey, modulus, modulusLength, exponent, exponentLength)) return kCCParamError;
            break;
        }
            
		case ccRSAKeyPrivate: {
            ccrsa_full_ctx *key = rsaKey->rsaKey.private;
            if(ccrsa_get_fullkey_components(key, modulus, modulusLength, exponent, exponentLength,
                                             p, pLength, q, qLength)) return kCCParamError;
            break;
        }
            
		default:
			return kCCParamError;
    }
            
    return kCCSuccess;
}


CCCryptorStatus 
CCRSACryptorSign(CCRSACryptorRef privateKey, CCAsymetricPadding padding, 
                 const void *hashToSign, size_t hashSignLen,
                 CCDigestAlgorithm digestType, size_t saltLen,
                 void *signedData, size_t *signedDataLen)
{    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!privateKey || !hashToSign || !signedData) return kCCParamError;
    
    switch(padding) {
        case ccPKCS1Padding: 
            if(ccrsa_sign_pkcs1v15(privateKey->rsaKey.full, CCDigestGetDigestInfo(digestType)->oid,
                                   hashSignLen, hashToSign, signedDataLen, signedData) != 0)
                return kCCDecodeError;
            break;
            
        case ccOAEPPadding:           
            if(ccrsa_sign_oaep(privateKey->rsaKey.full, CCDigestGetDigestInfo(digestType), 
                               ccDRBGGetRngState(), hashSignLen, hashToSign, 
                               signedDataLen, signedData) != 0)
                return kCCDecodeError;
            break;
        case ccX931Padding:
        case ccPKCS1PaddingRaw:
        case ccPaddingNone:
        default:
            return kCCParamError;
            break;
    }
    return kCCSuccess;
}



CCCryptorStatus 
CCRSACryptorVerify(CCRSACryptorRef publicKey, CCAsymetricPadding padding,
                   const void *hash, size_t hashLen, 
                   CCDigestAlgorithm digestType, size_t saltLen,
                   const void *signedData, size_t signedDataLen)
{
    bool valid;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(!publicKey || !hash || !signedData) return kCCParamError;
    
    switch(padding) {
        case ccPKCS1Padding: 
            if(ccrsa_verify_pkcs1v15(publicKey->rsaKey.public, CCDigestGetDigestInfo(digestType)->oid,
                                     hashLen, hash, signedDataLen, signedData, &valid) != 0)
                return kCCDecodeError;
            if(!valid) return kCCDecodeError;
            break;
            
        case ccOAEPPadding:
            if(ccrsa_verify_oaep(publicKey->rsaKey.public,  CCDigestGetDigestInfo(digestType),
                                 hashLen, hash, signedDataLen, signedData, &valid) != 0)
                return kCCDecodeError;
            if(!valid) return kCCDecodeError;
            break;
        case ccX931Padding:
        case ccPKCS1PaddingRaw:
        case ccPaddingNone:
        default:
            return kCCParamError;
            break;
    }
    return kCCSuccess;
}

#pragma mark APINotDone
#ifdef NEVER

// This was only here for FIPS.  If we move FIPS to the corecrypto layer it will need to be there.

CCCryptorStatus 
CCRSACryptorDecodePayloadPKCS1(
                               CCRSACryptorRef publicKey, 
                               const void *cipherText, 
                               size_t cipherTextLen,
                               void *plainText, 
                               size_t *plainTextLen)
{
    int tcReturn;
	int stat = 0;
    CCRSACryptor *publicCryptor = publicKey;
    uint8_t *message;
    unsigned long messageLen, modulusLen;
    CCCryptorStatus retval = kCCSuccess;
    
    modulusLen = CCRSAGetKeySize(publicKey);
    messageLen = modulusLen / 8;
    
    if((message = CC_XMALLOC(messageLen)) == NULL) return kCCMemoryFailure;
    
	tcReturn = rsa_exptmod(cipherText, cipherTextLen, message, messageLen, publicCryptor->keyType, &publicCryptor->key);
    if(tcReturn) {
        retval = kCCDecodeError;
        goto out;
    }
    tcReturn = pkcs_1_v1_5_decode(message, messageLen, LTC_PKCS_1_EME, modulusLen, plainText, plainTextLen, &stat);
    if(tcReturn) {
        retval = kCCDecodeError;
        goto out;        
    }
    if(!stat) {
        retval = kCCDecodeError;
        goto out;
    }
    
out:    
    CC_XZEROMEM(message, messageLen);
    CC_XFREE(message, messageLen);
    return retval;
}

#endif



Changes to Source/API/CommonRandom.c.

1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2006-2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at

|







1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
17
18
19
20
21
22
23












24



25












26



27



































































































28
29






30
31



32
33
34
35
36
37
38

39

40








41

42
43

44
45
46



47






48
49


50



51










52


53
54

55
56


57





58
59
60



61

62
63
64
65



66
67



68












69
70
71
72
73
74
75
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */













/* 



 * CommonRandom.c - Access to PRNGs












 *



 * this code was modified from the original embedded SecRandomCopyBytes.



































































































 */








#include "CommonRandomSPI.h"



#include "CommonCryptor.h"
#include <pthread.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <dispatch/dispatch.h>














/* Default random ref for /dev/random. */
CCRandomRef kCCRandomDefault = (CCRandomRef) NULL;


/* File descriptor for "/dev/random". */
static int kCCRandomFD;










int CCRandomCopyBytes(CCRandomRef rnd, void *bytes, size_t count) {
    static dispatch_once_t randopen;


    



    if (rnd != kCCRandomDefault) return kCCParamError;










    


    dispatch_once(&randopen, ^{ 
        kCCRandomFD = open("/dev/random", O_RDONLY); 

        if(kCCRandomFD > -1) fcntl(kCCRandomFD, F_SETFD, fcntl(kCCRandomFD, F_GETFD, 0) | FD_CLOEXEC);
    });


    





    if (kCCRandomFD < 0) return -1;
    
    while (count) {



        ssize_t bytes_read = read(kCCRandomFD, bytes, count);

 
        if (bytes_read == -1) {
            if (errno == EINTR) continue;
            return -1;



        }
        



        if (bytes_read == 0) return -1;













        bytes += bytes_read;
        count -= bytes_read;
    }
	return kCCSuccess;
}








>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


>
>
>
>
>
>

<
>
>
>
|
|
|
<
<
<
<
>
|
>
|
>
>
>
>
>
>
>
>
|
>
|
|
>
|
|
|
>
>
>

>
>
>
>
>
>
|
|
>
>
|
>
>
>
|
>
>
>
>
>
>
>
>
>
>

>
>
|
|
>
|
<
>
>
|
>
>
>
>
>
|
|
|
>
>
>
|
>
|
|
|
|
>
>
>
|
|
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
|
<
<
|
|
|

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

166
167
168
169
170
171




172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227

228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269


270
271
272
273
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_RANDOM_FUNCTIONS
#include "CommonRandomSPI.h"
#include <dispatch/dispatch.h>
#include <dispatch/queue.h>
#include <corecrypto/ccaes.h>
#include <corecrypto/ccdrbg.h>
#include <corecrypto/ccrng_CommonCrypto.h>
#include <corecrypto/ccrng_system.h>
#include "ccMemory.h"
#include "ccdebug.h"


/*
 This is an internal structure used to represent the two types
 of random number generators we're using.
*/

typedef struct __CCRandom {
    uint32_t rngtype;
    union {
        struct ccrng_system_state *devrandom;
        struct ccrng_CommonCrypto_state *drbg;
    } state;
    union {
        uint8_t *bytes;
        struct ccdrbg_info *drbg;
    } info;
    struct ccdrbg_state *drbg_state;
} ccInternalRandom, *ccInternalRandomRef;

/*
 The types of refs including "undefined" and "user created".
*/

static const uint32_t rng_undefined = 0;
static const uint32_t rng_default = 1;
static const uint32_t rng_devrandom = 2;
static const uint32_t rng_created = 99;

/*
 These are the two internal structures for a DRBG and /dev/random
 based accessor.
*/

ccInternalRandom ccRandomDefaultStruct = {
    .rngtype = rng_default,
};

ccInternalRandom ccRandomDevRandomStruct = {
    .rngtype = rng_devrandom,
};

CCRandomRef kCCRandomDefault = &ccRandomDefaultStruct;
CCRandomRef kCCRandomDevRandom = &ccRandomDevRandomStruct;

/*
 Initialize (if necessary) and return the ccrng_state pointer for
 the /dev/random rng.
 */

struct ccrng_state *
ccDevRandomGetRngState()
{
    static dispatch_once_t rnginit;
    dispatch_once(&rnginit, ^{        
        kCCRandomDevRandom->state.devrandom = (struct ccrng_state *) CC_XMALLOC(sizeof(struct ccrng_system_state));
        ccrng_system_init(kCCRandomDevRandom->state.devrandom);
        
    });
    return kCCRandomDevRandom->state.devrandom;
}

/*
 Read bytes from /dev/random
*/

int
ccDevRandomReadBytes(void *ptr, size_t length)
{    
    for(int retries = 5; retries && ccrng_generate(kCCRandomDevRandom->state.devrandom, length, ptr); retries--)
        if(retries == 0) return -1;
    return 0;
}



/*
 Initialize (if necessary) and return the ccrng_state pointer for
 the DRBG.
 */

static int
ccInitDRBG(ccInternalRandomRef drbg, struct ccdrbg_nistctr_custom *options, int function_options)
{
    CCRNGStatus retval = kCCSuccess;
    //uint8_t entropy[64];
    //struct timeval now;
    
    //gettimeofday(&now, NULL);
    // ccDevRandomGetRngState();
    // if(ccDevRandomReadBytes(entropy, sizeof(entropy))) return kCCDecodeError;
    
    
    retval = kCCMemoryFailure; // errors following will be memory failures.
    
    if((drbg->info.drbg = CC_XMALLOC(sizeof(struct ccdrbg_info))) == NULL) goto errOut;
    ccdrbg_factory_nistctr(drbg->info.drbg, options);
    if((drbg->drbg_state = CC_XMALLOC(drbg->info.drbg->size)) == NULL) goto errOut;
    if((drbg->state.drbg = CC_XMALLOC(sizeof(struct ccrng_CommonCrypto_state))) == NULL) goto errOut;
    
    if(ccrng_CommonCrypto_init(drbg->state.drbg, drbg->info.drbg, drbg->drbg_state, function_options)) {
        retval = kCCDecodeError;
        goto errOut;
    }
    
    return 0;
errOut:
    if(drbg->info.drbg) {
        if(drbg->state.drbg) CC_XFREE(drbg->state.drbg, sizeof(struct ccrng_CommonCrypto_state));
        if(drbg->drbg_state) CC_XFREE(drbg->drbg_state, drbg->info.drbg->size);
        CC_XFREE(drbg->info.drbg, sizeof(struct ccdrbg_info));
    }
    return retval;
}

#ifndef	NDEBUG
#define ASSERT(s)
#else
#define ASSERT(s)	assert(s)
#endif

/*
 Default DRGB setup
 */

static const struct ccdrbg_nistctr_custom CCDRGBcustom = {
    .ecb = &ccaes_ltc_ecb_encrypt_mode,
    .keylen = 16,
    .strictFIPS = 1,
    .use_df = 1
};


static struct ccdrbg_info CCDRGBinfo;
#define KNOWN_DRGB_STATE_SIZE 1160
static uint8_t CCDRGBstate[KNOWN_DRGB_STATE_SIZE];
struct ccrng_CommonCrypto_state CCDRGBrngstate;

struct ccrng_state *




ccDRBGGetRngState()
{
    static dispatch_once_t rnginit;
    
    dispatch_once(&rnginit, ^{
        kCCRandomDefault->info.drbg = &CCDRGBinfo;
        ccdrbg_factory_nistctr(kCCRandomDefault->info.drbg, &CCDRGBcustom);
        ASSERT(kCCRandomDefault->info.drbg->size <= sizeof(CCDRGBstate));    
        kCCRandomDefault->drbg_state = CCDRGBstate;
        kCCRandomDefault->state.drbg = &CCDRGBrngstate;
        if(ccrng_CommonCrypto_init(&CCDRGBrngstate, &CCDRGBinfo, CCDRGBstate, 0)) {
            kCCRandomDefault = NULL;
        }
    });
    ASSERT(kCCRandomDefault != NULL);
    if(kCCRandomDefault == NULL) return NULL;
    return kCCRandomDefault->state.drbg;
}


/*
 Read bytes from the DRBG
*/

int
ccDRBGReadBytes(struct ccrng_CommonCrypto_state *state, void *ptr, size_t length)
{
    ccrng_generate(state, length, ptr);
    return 0;
}


CCRNGStatus
CCRNGCreate(uint32_t options, CCRandomRef *rngRef)
{
    CCRNGStatus retval;
    ccInternalRandomRef ref;
    struct ccdrbg_nistctr_custom custom_options;

    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ref = CC_XMALLOC(sizeof(ccInternalRandom));
    if(NULL == ref) return kCCMemoryFailure;
    
    ref->rngtype = rng_created;
    // defaults
    custom_options.ecb = &ccaes_ltc_ecb_encrypt_mode;
    custom_options.keylen = 16;
    custom_options.strictFIPS = 1;
    custom_options.use_df = 1;
    
    if(retval = ccInitDRBG(ref, &custom_options, options)) return retval;
    *rngRef = ref;

    return kCCSuccess;    
}
    

CCRNGStatus
CCRNGRelease(CCRandomRef rng)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    if(rng->rngtype == rng_created) {
        ccrng_CommonCrypto_done(rng->state.drbg);
        CC_XFREE(rng, sizeof(ccInternalRandom));
    }
    return kCCSuccess;        
}

int CCRandomCopyBytes(CCRandomRef rnd, void *bytes, size_t count)
{
    struct ccrng_state *rng;
    
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering rnd(NULL) = %s\n", (rnd == NULL) ? "TRUE": "FALSE");

    
    if(NULL == bytes) return -1;
    if(0 == count) return 0;
    if(NULL == rnd) {
        rng = ccDRBGGetRngState();
        return ccDRBGReadBytes(rng, bytes, count);
    }
    
    switch(rnd->rngtype) {
        case rng_default:
            rng = ccDRBGGetRngState();
            return ccDRBGReadBytes(rng, bytes, count);
            break;
        case rng_devrandom:
            rng = ccDevRandomGetRngState();
            return ccDevRandomReadBytes(bytes, count);
            break;
        case rng_created:
            return ccDRBGReadBytes(rnd->state.drbg, bytes, count);
            break;
        default: // we can get bytes from the DRBG
            rng = ccDRBGGetRngState();
            return ccDRBGReadBytes(rng, bytes, count);
            break;
    }


}



Changes to Source/API/CommonSymmetricKeywrap.c.

1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at

|







1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
17
18
19
20
21
22
23

24


25
26
27
28
29
30

31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */


#include "CommonSymmetricKeywrap.h"


#include <AssertMacros.h>
#include <stdint.h>
#include <libkern/OSByteOrder.h>


static const uint8_t rfc3394_iv_data[] = { 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6 };


const uint8_t* CCrfc3394_iv = rfc3394_iv_data;
const size_t CCrfc3394_ivLen = sizeof(rfc3394_iv_data);

static uint64_t 
pack64(uint8_t *iv, size_t ivLen)
{
	uint64_t retval;
	int i;
	
	for(i=0, retval=0; i<8; i++) retval = (retval<<8) + iv[i];
	return retval;
}

#if KERNEL

#include <crypto/aes.h>
#include <libkern/OSByteOrder.h>

#define AES128_KEK 1
#define AES192_KEK 0
#define AES256_KEK 0

#define debug kprintf

static bool 
aes_operation(bool encrypt, const uint8_t *kek, size_t kek_len, uint8_t *block)
{
    uint64_t iv[2] = { 0 };

    if (encrypt) {
        aes_encrypt_ctx encrypt_ctx[1];
        switch(kek_len) {
#if AES128_KEK
            case 16: aes_encrypt_key128(kek, encrypt_ctx); break;
#endif
#if AES192_KEK
            case 24: aes_encrypt_key192(kek, encrypt_ctx); break;
#endif
#if AES256_KEK
            case 32: aes_encrypt_key256(kek, encrypt_ctx); break;
#endif
            default: return false;
        }
        aes_encrypt_cbc(block, (uint8_t*)iv, 1, block, encrypt_ctx);
    } else {
        aes_decrypt_ctx decrypt_ctx[1];
        switch(kek_len) {
#if AES128_KEK
            case 16: aes_decrypt_key128(kek, decrypt_ctx); break;
#endif
#if AES192_KEK
            case 24: aes_decrypt_key192(kek, decrypt_ctx); break;
#endif
#if AES256_KEK
            case 32: aes_decrypt_key256(kek, decrypt_ctx); break;
#endif
            default: return false;
        }
        aes_decrypt_cbc(block, (uint8_t*)iv, 1, block, decrypt_ctx);
    }

    return true;
}

#else

#include "CommonCryptor.h"

#define debug printf

static bool 
aes_operation(bool encrypt, const uint8_t *kek, size_t kek_len, uint8_t *block)
{
    uint64_t iv[2] = { 0 };
    size_t bytes_moved = 0;

    return (0 == CCCrypt(encrypt? kCCEncrypt : kCCDecrypt, 
                kCCAlgorithmAES128, 0, kek, kek_len, iv, 
                block, kCCBlockSizeAES128,
                block, kCCBlockSizeAES128, &bytes_moved));
}
#endif


/*
    1) Initialize variables.

    Set A = IV, an initial value (see 2.2.3) 
	For i = 1 to n R[i] = P[i] 







>

>
>

|
<


|
>





|




|
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|


<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







17
18
19
20
21
22
23
24
25
26
27
28
29

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44


45
















































46
47
48

49
















50
51
52
53
54
55
56
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

// #define COMMON_SYMMETRIC_KEYWRAP_FUNCTIONS
#include "CommonSymmetricKeywrap.h"
#include "CommonCryptor.h"
#include "CommonCryptorPriv.h"
#include <AssertMacros.h>
#include "ccdebug.h"



static const uint8_t rfc3394_iv_data[] = { 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6,
	0xA6, 0xA6 };

const uint8_t* CCrfc3394_iv = rfc3394_iv_data;
const size_t CCrfc3394_ivLen = sizeof(rfc3394_iv_data);

static uint64_t 
pack64(const uint8_t *iv, size_t ivLen)
{
	uint64_t retval;
	int i;
	
	for(i=0, retval=0; i<8; i++)


		retval = (retval<<8) + iv[i];
















































	return retval;
}





















/*
    1) Initialize variables.

    Set A = IV, an initial value (see 2.2.3) 
	For i = 1 to n R[i] = P[i] 
143
144
145
146
147
148
149
150

151
152


153
154
155
156

157
158
159
160
161
162
163
164
165
166
167
168
169


170
171
172
173
174
175
176
177
178
179
180
181
182


183

184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200

201


202
203
204
205
206
207
208
209
210
211
212
213
214

215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233


234
235
236
237
238
239
240
241
242
243
244

245
246
247
248
249
250

251
252
253
254
255
256
257
258
				   const uint8_t *iv, const size_t ivLen,
				   const uint8_t *kek, size_t kekLen,
				   const uint8_t *rawKey, size_t rawKeyLen,
				   uint8_t  *wrappedKey, size_t *wrappedKeyLen)
{
    uint32_t n = rawKeyLen / 8; /* key size in 64 bit blocks */
    uint64_t (*R)[2]; /* R is a two-dimensional array, with n rows of 2 columns */
    int i, j, err;

	
	// allocate R


	R = calloc(n, sizeof(uint64_t[2])); 
    require_action(R, out, err = -1);
    // don't wrap with something smaller
    require_action(rawKeyLen >= kekLen, out, err = -1);

    // kek multiple of 64 bits: 128, 192, 256
    require_action(kekLen == 16 || kekLen == 24 || kekLen == 32, out, err = -1);
    // wrapped_key_len 64 bits larger than key_len
    require_action(wrappedKeyLen && (*wrappedKeyLen >= rawKeyLen + 64/8), out, err = -1);

    // R[0][1] = P[0] ... R[1][n-1] = P[n-1]
    for (i = 0; i < n; i++)
        memcpy(&R[i][1], rawKey + (64/8) * i, (64/8));

	uint64_t kek_iv = pack64(iv, ivLen);
	
    R[0][0] = kek_iv;



    for (j = 0; j < 6; j++) {
        for (i = 0; i < n; i++)
        {
            require_action(aes_operation(true, kek, kekLen, (uint8_t*)&R[i][0]), out, err = -1);
            R[(i + 1) % n][0] = R[i][0] ^ _OSSwapInt64((n*j)+i+1);
        }
    }
	
    // write output
    memcpy(wrappedKey, &R[0][0], 8);
    for (i = 0; i < n; i++)
        memcpy(wrappedKey + 8 + i * 8, &R[i][1], 8);



    err = 0;

out:
    if (R) free(R);
    return err;
}



int  
CCSymmetricKeyUnwrap( CCWrappingAlgorithm algorithm, 
					 const uint8_t *iv, const size_t ivLen,
					 const uint8_t *kek, size_t kekLen,
					 const uint8_t  *wrappedKey, size_t wrappedKeyLen,
					 uint8_t  *rawKey, size_t *rawKeyLen)
{
    uint32_t n = wrappedKeyLen/8 - 1; /* raw key size in 64 bit blocks */
    uint64_t (*R)[2]; /* R is a two-dimensional array, with n rows of 2 columns */
    int i, j, err;




	// allocate R
	R = calloc(n, sizeof(uint64_t[2])); 
    require_action(R, out, err = -1);
	// kek multiple of 64 bits: 128, 192, 256
    require_action(kekLen == 16 || kekLen == 32, out, err = -1);
    // wrapped_key_len 64 bits larger than key_len
    require_action(rawKeyLen && (*rawKeyLen >= wrappedKeyLen - 64/8), out, err = -1);

    // R[0][1] = C[0] ... R[1][n-1] = C[n-1]
    memcpy(&R[0][0], wrappedKey, 64/8); 
    for (i = 0; i < n; i++)
        memcpy(&R[i][1], wrappedKey + (64/8) * (i+1), 64/8);


    for (j = 5; j >= 0; j--) {
        for (i = n - 1; i >= 0; i--)
        {
           R[i][0] = R[(i + 1) % n][0] ^ _OSSwapInt64((n*j)+i+1);
            require_action(aes_operation(false, kek, kekLen, (uint8_t*)&R[i][0]), out, err = -1);
        }
    }

	uint64_t kek_iv = pack64(iv, ivLen);

    // R[0][0] == iv?
    require_action(R[0][0] == kek_iv, out, err = -1);

    // write output
    for (i = 0; i < n; i++)
        memcpy(rawKey + i * 8, &R[i][1], 8);

    // clean all stack variables



    err = 0;
    
out:
	if (R) free(R);
    return err;
}


size_t
CCSymmetricWrappedSize( CCWrappingAlgorithm algorithm, size_t rawKeyLen)
{

	return (rawKeyLen + 8);
}

size_t
CCSymmetricUnwrappedSize( CCWrappingAlgorithm algorithm, size_t wrappedKeyLen)
{

    return (wrappedKeyLen - 8);
}













|
>
|
<
>
>

|

|
>













>
>



|









>
>
|
>

|














|
>

>
>
|

|
|
|

|






>



|
|














>
>
|
|









>






>








79
80
81
82
83
84
85
86
87
88

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
				   const uint8_t *iv, const size_t ivLen,
				   const uint8_t *kek, size_t kekLen,
				   const uint8_t *rawKey, size_t rawKeyLen,
				   uint8_t  *wrappedKey, size_t *wrappedKeyLen)
{
    uint32_t n = rawKeyLen / 8; /* key size in 64 bit blocks */
    uint64_t (*R)[2]; /* R is a two-dimensional array, with n rows of 2 columns */
    int i, j, err = 0;
    struct ccmode_ecb *ccmode = getCipherMode(kCCAlgorithmAES128, kCCModeECB, kCCEncrypt).ecb;


    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccecb_ctx_decl(ccmode->size, ctx);
	R = calloc(n, sizeof(uint64_t[2])); 
	
    // don't wrap with something smaller
    // require_action(rawKeyLen <= kekLen, out, err = -1);

    // kek multiple of 64 bits: 128, 192, 256
    require_action(kekLen == 16 || kekLen == 24 || kekLen == 32, out, err = -1);
    // wrapped_key_len 64 bits larger than key_len
    require_action(wrappedKeyLen && (*wrappedKeyLen >= rawKeyLen + 64/8), out, err = -1);

    // R[0][1] = P[0] ... R[1][n-1] = P[n-1]
    for (i = 0; i < n; i++)
        memcpy(&R[i][1], rawKey + (64/8) * i, (64/8));

	uint64_t kek_iv = pack64(iv, ivLen);
	
    R[0][0] = kek_iv;

    ccmode->init(ccmode, &ctx, kekLen, kek);

    for (j = 0; j < 6; j++) {
        for (i = 0; i < n; i++)
        {
            ccmode->ecb(&ctx, 1, (uint8_t*)&R[i][0], (uint8_t*)&R[i][0]);
            R[(i + 1) % n][0] = R[i][0] ^ _OSSwapInt64((n*j)+i+1);
        }
    }
	
    // write output
    memcpy(wrappedKey, &R[0][0], 8);
    for (i = 0; i < n; i++)
        memcpy(wrappedKey + 8 + i * 8, &R[i][1], 8);

    for(i=0; i<n; i++)
        for(j=0; j<2; j++)
            R[i][j] = 0;

out:
	if (R) free(R);
    return err;
}



int  
CCSymmetricKeyUnwrap( CCWrappingAlgorithm algorithm, 
					 const uint8_t *iv, const size_t ivLen,
					 const uint8_t *kek, size_t kekLen,
					 const uint8_t  *wrappedKey, size_t wrappedKeyLen,
					 uint8_t  *rawKey, size_t *rawKeyLen)
{
    uint32_t n = wrappedKeyLen/8 - 1; /* raw key size in 64 bit blocks */
    uint64_t (*R)[2]; /* R is a two-dimensional array, with n rows of 2 columns */
    int i, j, err = 0;
    struct ccmode_ecb *ccmode = getCipherMode(kCCAlgorithmAES128, kCCModeECB, kCCDecrypt).ecb;

    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    ccecb_ctx_decl(ccmode->size, ctx);

	R = calloc(n, sizeof(uint64_t[2])); 

    // kek multiple of 64 bits: 128, 192, 256
    require_action(kekLen == 16 || kekLen == 24 || kekLen == 32, out, err = -1);
    // wrapped_key_len 64 bits larger than key_len
    // require_action(rawKeyLen && (*rawKeyLen <= wrappedKeyLen - 64/8), out, err = -1);

    // R[0][1] = C[0] ... R[1][n-1] = C[n-1]
    memcpy(&R[0][0], wrappedKey, 64/8); 
    for (i = 0; i < n; i++)
        memcpy(&R[i][1], wrappedKey + (64/8) * (i+1), 64/8);

    ccmode->init(ccmode, &ctx, kekLen, kek);
    for (j = 5; j >= 0; j--) {
        for (i = n - 1; i >= 0; i--)
        {
            R[i][0] = R[(i + 1) % n][0] ^ _OSSwapInt64((n*j)+i+1);
            ccmode->ecb(&ctx, 1, (uint8_t*)&R[i][0], (uint8_t*)&R[i][0]);
        }
    }

	uint64_t kek_iv = pack64(iv, ivLen);

    // R[0][0] == iv?
    require_action(R[0][0] == kek_iv, out, err = -1);

    // write output
    for (i = 0; i < n; i++)
        memcpy(rawKey + i * 8, &R[i][1], 8);

    // clean all stack variables

    for(i=0; i<n; i++)
        for(j=0; j<2; j++)
            R[i][j] = 0;

out:
	if (R) free(R);
    return err;
}


size_t
CCSymmetricWrappedSize( CCWrappingAlgorithm algorithm, size_t rawKeyLen)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
	return (rawKeyLen + 8);
}

size_t
CCSymmetricUnwrappedSize( CCWrappingAlgorithm algorithm, size_t wrappedKeyLen)
{
    CC_DEBUG_LOG(ASL_LEVEL_ERR, "Entering\n");
    return (wrappedKeyLen - 8);
}






Deleted Source/CAST/c_ecb.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* crypto/cast/c_ecb.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <CommonCrypto/cast.h>
#include "cast_lcl.h"

#ifndef	_APPLE_COMMON_CRYPTO_
#include <openssl/opensslv.h>

const char *CAST_version="CAST" OPENSSL_VERSION_PTEXT;
#endif	/* _APPLE_COMMON_CRYPTO_ */

void CAST_ecb_encrypt(const unsigned char *in, unsigned char *out,
		      CAST_KEY *ks, int enc)
	{
	CAST_LONG l,d[2];

	n2l(in,l); d[0]=l;
	n2l(in,l); d[1]=l;
	if (enc)
		CAST_encrypt(d,ks);
	else
		CAST_decrypt(d,ks);
	l=d[0]; l2n(l,out);
	l=d[1]; l2n(l,out);
	l=d[0]=d[1]=0;
	}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































































Deleted Source/CAST/c_enc.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/* crypto/cast/c_enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <CommonCrypto/cast.h>
#include "cast_lcl.h"

void CAST_encrypt(CAST_LONG *data, CAST_KEY *key)
	{
	register CAST_LONG l,r,*k,t;

	k= &(key->data[0]);
	l=data[0];
	r=data[1];

	E_CAST( 0,k,l,r,+,^,-);
	E_CAST( 1,k,r,l,^,-,+);
	E_CAST( 2,k,l,r,-,+,^);
	E_CAST( 3,k,r,l,+,^,-);
	E_CAST( 4,k,l,r,^,-,+);
	E_CAST( 5,k,r,l,-,+,^);
	E_CAST( 6,k,l,r,+,^,-);
	E_CAST( 7,k,r,l,^,-,+);
	E_CAST( 8,k,l,r,-,+,^);
	E_CAST( 9,k,r,l,+,^,-);
	E_CAST(10,k,l,r,^,-,+);
	E_CAST(11,k,r,l,-,+,^);
	if(!key->short_key)
	    {
	    E_CAST(12,k,l,r,+,^,-);
	    E_CAST(13,k,r,l,^,-,+);
	    E_CAST(14,k,l,r,-,+,^);
	    E_CAST(15,k,r,l,+,^,-);
	    }

	data[1]=l&0xffffffffL;
	data[0]=r&0xffffffffL;
	}

void CAST_decrypt(CAST_LONG *data, CAST_KEY *key)
	{
	register CAST_LONG l,r,*k,t;

	k= &(key->data[0]);
	l=data[0];
	r=data[1];

	if(!key->short_key)
	    {
	    E_CAST(15,k,l,r,+,^,-);
	    E_CAST(14,k,r,l,-,+,^);
	    E_CAST(13,k,l,r,^,-,+);
	    E_CAST(12,k,r,l,+,^,-);
	    }
	E_CAST(11,k,l,r,-,+,^);
	E_CAST(10,k,r,l,^,-,+);
	E_CAST( 9,k,l,r,+,^,-);
	E_CAST( 8,k,r,l,-,+,^);
	E_CAST( 7,k,l,r,^,-,+);
	E_CAST( 6,k,r,l,+,^,-);
	E_CAST( 5,k,l,r,-,+,^);
	E_CAST( 4,k,r,l,^,-,+);
	E_CAST( 3,k,l,r,+,^,-);
	E_CAST( 2,k,r,l,-,+,^);
	E_CAST( 1,k,l,r,^,-,+);
	E_CAST( 0,k,r,l,+,^,-);

	data[1]=l&0xffffffffL;
	data[0]=r&0xffffffffL;
	}

#ifndef	_APPLE_COMMON_CRYPTO_
/* CBC logic not needed here */
void CAST_cbc_encrypt(const unsigned char *in, unsigned char *out, long length,
	     CAST_KEY *ks, unsigned char *iv, int enc)
	{
	register CAST_LONG tin0,tin1;
	register CAST_LONG tout0,tout1,xor0,xor1;
	register long l=length;
	CAST_LONG tin[2];

	if (enc)
		{
		n2l(iv,tout0);
		n2l(iv,tout1);
		iv-=8;
		for (l-=8; l>=0; l-=8)
			{
			n2l(in,tin0);
			n2l(in,tin1);
			tin0^=tout0;
			tin1^=tout1;
			tin[0]=tin0;
			tin[1]=tin1;
			CAST_encrypt(tin,ks);
			tout0=tin[0];
			tout1=tin[1];
			l2n(tout0,out);
			l2n(tout1,out);
			}
		if (l != -8)
			{
			n2ln(in,tin0,tin1,l+8);
			tin0^=tout0;
			tin1^=tout1;
			tin[0]=tin0;
			tin[1]=tin1;
			CAST_encrypt(tin,ks);
			tout0=tin[0];
			tout1=tin[1];
			l2n(tout0,out);
			l2n(tout1,out);
			}
		l2n(tout0,iv);
		l2n(tout1,iv);
		}
	else
		{
		n2l(iv,xor0);
		n2l(iv,xor1);
		iv-=8;
		for (l-=8; l>=0; l-=8)
			{
			n2l(in,tin0);
			n2l(in,tin1);
			tin[0]=tin0;
			tin[1]=tin1;
			CAST_decrypt(tin,ks);
			tout0=tin[0]^xor0;
			tout1=tin[1]^xor1;
			l2n(tout0,out);
			l2n(tout1,out);
			xor0=tin0;
			xor1=tin1;
			}
		if (l != -8)
			{
			n2l(in,tin0);
			n2l(in,tin1);
			tin[0]=tin0;
			tin[1]=tin1;
			CAST_decrypt(tin,ks);
			tout0=tin[0]^xor0;
			tout1=tin[1]^xor1;
			l2nn(tout0,tout1,out,l+8);
			xor0=tin0;
			xor1=tin1;
			}
		l2n(xor0,iv);
		l2n(xor1,iv);
		}
	tin0=tin1=tout0=tout1=xor0=xor1=0;
	tin[0]=tin[1]=0;
	}

#endif	/* _APPLE_COMMON_CRYPTO_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































































































































































































































































































Deleted Source/CAST/c_skey.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/* crypto/cast/c_skey.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <CommonCrypto/cast.h>
#include "cast_lcl.h"
#include "cast_s.h"

#define CAST_exp(l,A,a,n) \
	A[n/4]=l; \
	a[n+3]=(l    )&0xff; \
	a[n+2]=(l>> 8)&0xff; \
	a[n+1]=(l>>16)&0xff; \
	a[n+0]=(l>>24)&0xff;

#define S4 CAST_S_table4
#define S5 CAST_S_table5
#define S6 CAST_S_table6
#define S7 CAST_S_table7

void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data)
	{
	CAST_LONG x[16];
	CAST_LONG z[16];
	CAST_LONG k[32];
	CAST_LONG X[4],Z[4];
	CAST_LONG l,*K;
	int i;

	for (i=0; i<16; i++) x[i]=0;
	if (len > 16) len=16;
	for (i=0; i<len; i++)
		x[i]=data[i];
	if(len <= 10)
	    key->short_key=1;
	else
	    key->short_key=0;

	K= &k[0];
	X[0]=((x[ 0]<<24)|(x[ 1]<<16)|(x[ 2]<<8)|x[ 3])&0xffffffffL;
	X[1]=((x[ 4]<<24)|(x[ 5]<<16)|(x[ 6]<<8)|x[ 7])&0xffffffffL;
	X[2]=((x[ 8]<<24)|(x[ 9]<<16)|(x[10]<<8)|x[11])&0xffffffffL;
	X[3]=((x[12]<<24)|(x[13]<<16)|(x[14]<<8)|x[15])&0xffffffffL;

	for (;;)
		{
	l=X[0]^S4[x[13]]^S5[x[15]]^S6[x[12]]^S7[x[14]]^S6[x[ 8]];
	CAST_exp(l,Z,z, 0);
	l=X[2]^S4[z[ 0]]^S5[z[ 2]]^S6[z[ 1]]^S7[z[ 3]]^S7[x[10]];
	CAST_exp(l,Z,z, 4);
	l=X[3]^S4[z[ 7]]^S5[z[ 6]]^S6[z[ 5]]^S7[z[ 4]]^S4[x[ 9]];
	CAST_exp(l,Z,z, 8);
	l=X[1]^S4[z[10]]^S5[z[ 9]]^S6[z[11]]^S7[z[ 8]]^S5[x[11]];
	CAST_exp(l,Z,z,12);

	K[ 0]= S4[z[ 8]]^S5[z[ 9]]^S6[z[ 7]]^S7[z[ 6]]^S4[z[ 2]];
	K[ 1]= S4[z[10]]^S5[z[11]]^S6[z[ 5]]^S7[z[ 4]]^S5[z[ 6]];
	K[ 2]= S4[z[12]]^S5[z[13]]^S6[z[ 3]]^S7[z[ 2]]^S6[z[ 9]];
	K[ 3]= S4[z[14]]^S5[z[15]]^S6[z[ 1]]^S7[z[ 0]]^S7[z[12]];

	l=Z[2]^S4[z[ 5]]^S5[z[ 7]]^S6[z[ 4]]^S7[z[ 6]]^S6[z[ 0]];
	CAST_exp(l,X,x, 0);
	l=Z[0]^S4[x[ 0]]^S5[x[ 2]]^S6[x[ 1]]^S7[x[ 3]]^S7[z[ 2]];
	CAST_exp(l,X,x, 4);
	l=Z[1]^S4[x[ 7]]^S5[x[ 6]]^S6[x[ 5]]^S7[x[ 4]]^S4[z[ 1]];
	CAST_exp(l,X,x, 8);
	l=Z[3]^S4[x[10]]^S5[x[ 9]]^S6[x[11]]^S7[x[ 8]]^S5[z[ 3]];
	CAST_exp(l,X,x,12);

	K[ 4]= S4[x[ 3]]^S5[x[ 2]]^S6[x[12]]^S7[x[13]]^S4[x[ 8]];
	K[ 5]= S4[x[ 1]]^S5[x[ 0]]^S6[x[14]]^S7[x[15]]^S5[x[13]];
	K[ 6]= S4[x[ 7]]^S5[x[ 6]]^S6[x[ 8]]^S7[x[ 9]]^S6[x[ 3]];
	K[ 7]= S4[x[ 5]]^S5[x[ 4]]^S6[x[10]]^S7[x[11]]^S7[x[ 7]];

	l=X[0]^S4[x[13]]^S5[x[15]]^S6[x[12]]^S7[x[14]]^S6[x[ 8]];
	CAST_exp(l,Z,z, 0);
	l=X[2]^S4[z[ 0]]^S5[z[ 2]]^S6[z[ 1]]^S7[z[ 3]]^S7[x[10]];
	CAST_exp(l,Z,z, 4);
	l=X[3]^S4[z[ 7]]^S5[z[ 6]]^S6[z[ 5]]^S7[z[ 4]]^S4[x[ 9]];
	CAST_exp(l,Z,z, 8);
	l=X[1]^S4[z[10]]^S5[z[ 9]]^S6[z[11]]^S7[z[ 8]]^S5[x[11]];
	CAST_exp(l,Z,z,12);

	K[ 8]= S4[z[ 3]]^S5[z[ 2]]^S6[z[12]]^S7[z[13]]^S4[z[ 9]];
	K[ 9]= S4[z[ 1]]^S5[z[ 0]]^S6[z[14]]^S7[z[15]]^S5[z[12]];
	K[10]= S4[z[ 7]]^S5[z[ 6]]^S6[z[ 8]]^S7[z[ 9]]^S6[z[ 2]];
	K[11]= S4[z[ 5]]^S5[z[ 4]]^S6[z[10]]^S7[z[11]]^S7[z[ 6]];

	l=Z[2]^S4[z[ 5]]^S5[z[ 7]]^S6[z[ 4]]^S7[z[ 6]]^S6[z[ 0]];
	CAST_exp(l,X,x, 0);
	l=Z[0]^S4[x[ 0]]^S5[x[ 2]]^S6[x[ 1]]^S7[x[ 3]]^S7[z[ 2]];
	CAST_exp(l,X,x, 4);
	l=Z[1]^S4[x[ 7]]^S5[x[ 6]]^S6[x[ 5]]^S7[x[ 4]]^S4[z[ 1]];
	CAST_exp(l,X,x, 8);
	l=Z[3]^S4[x[10]]^S5[x[ 9]]^S6[x[11]]^S7[x[ 8]]^S5[z[ 3]];
	CAST_exp(l,X,x,12);

	K[12]= S4[x[ 8]]^S5[x[ 9]]^S6[x[ 7]]^S7[x[ 6]]^S4[x[ 3]];
	K[13]= S4[x[10]]^S5[x[11]]^S6[x[ 5]]^S7[x[ 4]]^S5[x[ 7]];
	K[14]= S4[x[12]]^S5[x[13]]^S6[x[ 3]]^S7[x[ 2]]^S6[x[ 8]];
	K[15]= S4[x[14]]^S5[x[15]]^S6[x[ 1]]^S7[x[ 0]]^S7[x[13]];
	if (K != k)  break;
	K+=16;
		}

	for (i=0; i<16; i++)
		{
		key->data[i*2]=k[i];
		key->data[i*2+1]=((k[i+16])+16)&0x1f;
		}
	}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































Deleted Source/CAST/cast_lcl.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/* crypto/cast/cast_lcl.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#ifdef WIN32
#include <stdlib.h>
#endif

#include <CommonCrypto/CommonCryptoPriv.h>

#define OPENSSL_EXTERN	extern
//#include "openssl/e_os.h" /* OPENSSL_EXTERN */

#undef c2l
#define c2l(c,l)	(l =((unsigned long)(*((c)++)))    , \
			 l|=((unsigned long)(*((c)++)))<< 8L, \
			 l|=((unsigned long)(*((c)++)))<<16L, \
			 l|=((unsigned long)(*((c)++)))<<24L)

/* NOTE - c is not incremented as per c2l */
#undef c2ln
#define c2ln(c,l1,l2,n)	{ \
			c+=n; \
			l1=l2=0; \
			switch (n) { \
			case 8: l2 =((unsigned long)(*(--(c))))<<24L; \
			case 7: l2|=((unsigned long)(*(--(c))))<<16L; \
			case 6: l2|=((unsigned long)(*(--(c))))<< 8L; \
			case 5: l2|=((unsigned long)(*(--(c))));     \
			case 4: l1 =((unsigned long)(*(--(c))))<<24L; \
			case 3: l1|=((unsigned long)(*(--(c))))<<16L; \
			case 2: l1|=((unsigned long)(*(--(c))))<< 8L; \
			case 1: l1|=((unsigned long)(*(--(c))));     \
				} \
			}

#undef l2c
#define l2c(l,c)	(*((c)++)=(unsigned char)(((l)     )&0xff), \
			 *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \
			 *((c)++)=(unsigned char)(((l)>>16L)&0xff), \
			 *((c)++)=(unsigned char)(((l)>>24L)&0xff))

/* NOTE - c is not incremented as per l2c */
#undef l2cn
#define l2cn(l1,l2,c,n)	{ \
			c+=n; \
			switch (n) { \
			case 8: *(--(c))=(unsigned char)(((l2)>>24L)&0xff); \
			case 7: *(--(c))=(unsigned char)(((l2)>>16L)&0xff); \
			case 6: *(--(c))=(unsigned char)(((l2)>> 8L)&0xff); \
			case 5: *(--(c))=(unsigned char)(((l2)     )&0xff); \
			case 4: *(--(c))=(unsigned char)(((l1)>>24L)&0xff); \
			case 3: *(--(c))=(unsigned char)(((l1)>>16L)&0xff); \
			case 2: *(--(c))=(unsigned char)(((l1)>> 8L)&0xff); \
			case 1: *(--(c))=(unsigned char)(((l1)     )&0xff); \
				} \
			}

/* NOTE - c is not incremented as per n2l */
#define n2ln(c,l1,l2,n)	{ \
			c+=n; \
			l1=l2=0; \
			switch (n) { \
			case 8: l2 =((unsigned long)(*(--(c))))    ; \
			case 7: l2|=((unsigned long)(*(--(c))))<< 8; \
			case 6: l2|=((unsigned long)(*(--(c))))<<16; \
			case 5: l2|=((unsigned long)(*(--(c))))<<24; \
			case 4: l1 =((unsigned long)(*(--(c))))    ; \
			case 3: l1|=((unsigned long)(*(--(c))))<< 8; \
			case 2: l1|=((unsigned long)(*(--(c))))<<16; \
			case 1: l1|=((unsigned long)(*(--(c))))<<24; \
				} \
			}

/* NOTE - c is not incremented as per l2n */
#define l2nn(l1,l2,c,n)	{ \
			c+=n; \
			switch (n) { \
			case 8: *(--(c))=(unsigned char)(((l2)    )&0xff); \
			case 7: *(--(c))=(unsigned char)(((l2)>> 8)&0xff); \
			case 6: *(--(c))=(unsigned char)(((l2)>>16)&0xff); \
			case 5: *(--(c))=(unsigned char)(((l2)>>24)&0xff); \
			case 4: *(--(c))=(unsigned char)(((l1)    )&0xff); \
			case 3: *(--(c))=(unsigned char)(((l1)>> 8)&0xff); \
			case 2: *(--(c))=(unsigned char)(((l1)>>16)&0xff); \
			case 1: *(--(c))=(unsigned char)(((l1)>>24)&0xff); \
				} \
			}

#undef n2l
#if	defined(__GNUC__) && defined(__ppc__)
/* alignment tolerant big-endian optimization */
	#define n2l(c,l)	{ l= *((unsigned long *)c); c += 4; }
#else
/* little endian, etc. */
	#define n2l(c,l)	(l =((unsigned long)(*((c)++)))<<24L, \
                         l|=((unsigned long)(*((c)++)))<<16L, \
                         l|=((unsigned long)(*((c)++)))<< 8L, \
                         l|=((unsigned long)(*((c)++))))
#endif

#undef l2n
#if	defined(__GNUC__) && defined(__ppc__)
	/* alignment tolerant big-endian optimization */
	#define l2n(l,c)	{ *((unsigned long *)c) = l; c += 4; }
#else
	/* little endian, etc. */
	#define l2n(l,c)    (*((c)++)=(unsigned char)(((l)>>24L)&0xff), \
                         *((c)++)=(unsigned char)(((l)>>16L)&0xff), \
                         *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \
                         *((c)++)=(unsigned char)(((l)     )&0xff))
						 
#endif	/* GNU, big endian */

#if defined(WIN32) && defined(_MSC_VER)
#define ROTL(a,n)     (_lrotl(a,n))
#else
#define ROTL(a,n)     ((((a)<<(n))&0xffffffffL)|((a)>>(32-(n))))
#endif

#define C_M    0x3fc
#define C_0    22L
#define C_1    14L
#define C_2     6L
#define C_3     2L /* left shift */

/* The rotate has an extra 16 added to it to help the x86 asm */
#if defined(CAST_PTR)
#define E_CAST(n,key,L,R,OP1,OP2,OP3) \
	{ \
	int i; \
	t=(key[n*2] OP1 R)&0xffffffffL; \
	i=key[n*2+1]; \
	t=ROTL(t,i); \
	L^= (((((*(CAST_LONG *)((unsigned char *) \
			CAST_S_table0+((t>>C_2)&C_M)) OP2 \
		*(CAST_LONG *)((unsigned char *) \
			CAST_S_table1+((t<<C_3)&C_M)))&0xffffffffL) OP3 \
		*(CAST_LONG *)((unsigned char *) \
			CAST_S_table2+((t>>C_0)&C_M)))&0xffffffffL) OP1 \
		*(CAST_LONG *)((unsigned char *) \
			CAST_S_table3+((t>>C_1)&C_M)))&0xffffffffL; \
	}
#elif defined(CAST_PTR2)
#define E_CAST(n,key,L,R,OP1,OP2,OP3) \
	{ \
	int i; \
	CAST_LONG u,v,w; \
	w=(key[n*2] OP1 R)&0xffffffffL; \
	i=key[n*2+1]; \
	w=ROTL(w,i); \
	u=w>>C_2; \
	v=w<<C_3; \
	u&=C_M; \
	v&=C_M; \
	t= *(CAST_LONG *)((unsigned char *)CAST_S_table0+u); \
	u=w>>C_0; \
	t=(t OP2 *(CAST_LONG *)((unsigned char *)CAST_S_table1+v))&0xffffffffL;\
	v=w>>C_1; \
	u&=C_M; \
	v&=C_M; \
	t=(t OP3 *(CAST_LONG *)((unsigned char *)CAST_S_table2+u)&0xffffffffL);\
	t=(t OP1 *(CAST_LONG *)((unsigned char *)CAST_S_table3+v)&0xffffffffL);\
	L^=(t&0xffffffff); \
	}
#else
#define E_CAST(n,key,L,R,OP1,OP2,OP3) \
	{ \
	CAST_LONG a,b,c,d; \
	t=(key[n*2] OP1 R)&0xffffffff; \
	t=ROTL(t,(key[n*2+1])); \
	a=CAST_S_table0[(t>> 8)&0xff]; \
	b=CAST_S_table1[(t    )&0xff]; \
	c=CAST_S_table2[(t>>24)&0xff]; \
	d=CAST_S_table3[(t>>16)&0xff]; \
	L^=(((((a OP2 b)&0xffffffffL) OP3 c)&0xffffffffL) OP1 d)&0xffffffffL; \
	}
#endif

#ifdef	_APPLE_COMMON_CRYPTO_
/* CommonCrypto defines */
#define OPENSSL_GLOBAL
/* 
 * These rename this tables to avoid symbols collision between libSystem 
 * and libcrypto.
 */
#define CAST_S_table0	CC_CAST_S_table0
#define CAST_S_table1	CC_CAST_S_table1
#define CAST_S_table2	CC_CAST_S_table2
#define CAST_S_table3	CC_CAST_S_table3
#define CAST_S_table4	CC_CAST_S_table4
#define CAST_S_table5	CC_CAST_S_table5
#define CAST_S_table6	CC_CAST_S_table6
#define CAST_S_table7	CC_CAST_S_table7
#endif	/* _APPLE_COMMON_CRYPTO_ */

OPENSSL_EXTERN const CAST_LONG CAST_S_table0[256];
OPENSSL_EXTERN const CAST_LONG CAST_S_table1[256];
OPENSSL_EXTERN const CAST_LONG CAST_S_table2[256];
OPENSSL_EXTERN const CAST_LONG CAST_S_table3[256];
OPENSSL_EXTERN const CAST_LONG CAST_S_table4[256];
OPENSSL_EXTERN const CAST_LONG CAST_S_table5[256];
OPENSSL_EXTERN const CAST_LONG CAST_S_table6[256];
OPENSSL_EXTERN const CAST_LONG CAST_S_table7[256];
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































































































































































































































































































































































































Deleted Source/CAST/cast_s.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
/* crypto/cast/cast_s.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

OPENSSL_GLOBAL const CAST_LONG CAST_S_table0[256]={
	0x30fb40d4,0x9fa0ff0b,0x6beccd2f,0x3f258c7a,
	0x1e213f2f,0x9c004dd3,0x6003e540,0xcf9fc949,
	0xbfd4af27,0x88bbbdb5,0xe2034090,0x98d09675,
	0x6e63a0e0,0x15c361d2,0xc2e7661d,0x22d4ff8e,
	0x28683b6f,0xc07fd059,0xff2379c8,0x775f50e2,
	0x43c340d3,0xdf2f8656,0x887ca41a,0xa2d2bd2d,
	0xa1c9e0d6,0x346c4819,0x61b76d87,0x22540f2f,
	0x2abe32e1,0xaa54166b,0x22568e3a,0xa2d341d0,
	0x66db40c8,0xa784392f,0x004dff2f,0x2db9d2de,
	0x97943fac,0x4a97c1d8,0x527644b7,0xb5f437a7,
	0xb82cbaef,0xd751d159,0x6ff7f0ed,0x5a097a1f,
	0x827b68d0,0x90ecf52e,0x22b0c054,0xbc8e5935,
	0x4b6d2f7f,0x50bb64a2,0xd2664910,0xbee5812d,
	0xb7332290,0xe93b159f,0xb48ee411,0x4bff345d,
	0xfd45c240,0xad31973f,0xc4f6d02e,0x55fc8165,
	0xd5b1caad,0xa1ac2dae,0xa2d4b76d,0xc19b0c50,
	0x882240f2,0x0c6e4f38,0xa4e4bfd7,0x4f5ba272,
	0x564c1d2f,0xc59c5319,0xb949e354,0xb04669fe,
	0xb1b6ab8a,0xc71358dd,0x6385c545,0x110f935d,
	0x57538ad5,0x6a390493,0xe63d37e0,0x2a54f6b3,
	0x3a787d5f,0x6276a0b5,0x19a6fcdf,0x7a42206a,
	0x29f9d4d5,0xf61b1891,0xbb72275e,0xaa508167,
	0x38901091,0xc6b505eb,0x84c7cb8c,0x2ad75a0f,
	0x874a1427,0xa2d1936b,0x2ad286af,0xaa56d291,
	0xd7894360,0x425c750d,0x93b39e26,0x187184c9,
	0x6c00b32d,0x73e2bb14,0xa0bebc3c,0x54623779,
	0x64459eab,0x3f328b82,0x7718cf82,0x59a2cea6,
	0x04ee002e,0x89fe78e6,0x3fab0950,0x325ff6c2,
	0x81383f05,0x6963c5c8,0x76cb5ad6,0xd49974c9,
	0xca180dcf,0x380782d5,0xc7fa5cf6,0x8ac31511,
	0x35e79e13,0x47da91d0,0xf40f9086,0xa7e2419e,
	0x31366241,0x051ef495,0xaa573b04,0x4a805d8d,
	0x548300d0,0x00322a3c,0xbf64cddf,0xba57a68e,
	0x75c6372b,0x50afd341,0xa7c13275,0x915a0bf5,
	0x6b54bfab,0x2b0b1426,0xab4cc9d7,0x449ccd82,
	0xf7fbf265,0xab85c5f3,0x1b55db94,0xaad4e324,
	0xcfa4bd3f,0x2deaa3e2,0x9e204d02,0xc8bd25ac,
	0xeadf55b3,0xd5bd9e98,0xe31231b2,0x2ad5ad6c,
	0x954329de,0xadbe4528,0xd8710f69,0xaa51c90f,
	0xaa786bf6,0x22513f1e,0xaa51a79b,0x2ad344cc,
	0x7b5a41f0,0xd37cfbad,0x1b069505,0x41ece491,
	0xb4c332e6,0x032268d4,0xc9600acc,0xce387e6d,
	0xbf6bb16c,0x6a70fb78,0x0d03d9c9,0xd4df39de,
	0xe01063da,0x4736f464,0x5ad328d8,0xb347cc96,
	0x75bb0fc3,0x98511bfb,0x4ffbcc35,0xb58bcf6a,
	0xe11f0abc,0xbfc5fe4a,0xa70aec10,0xac39570a,
	0x3f04442f,0x6188b153,0xe0397a2e,0x5727cb79,
	0x9ceb418f,0x1cacd68d,0x2ad37c96,0x0175cb9d,
	0xc69dff09,0xc75b65f0,0xd9db40d8,0xec0e7779,
	0x4744ead4,0xb11c3274,0xdd24cb9e,0x7e1c54bd,
	0xf01144f9,0xd2240eb1,0x9675b3fd,0xa3ac3755,
	0xd47c27af,0x51c85f4d,0x56907596,0xa5bb15e6,
	0x580304f0,0xca042cf1,0x011a37ea,0x8dbfaadb,
	0x35ba3e4a,0x3526ffa0,0xc37b4d09,0xbc306ed9,
	0x98a52666,0x5648f725,0xff5e569d,0x0ced63d0,
	0x7c63b2cf,0x700b45e1,0xd5ea50f1,0x85a92872,
	0xaf1fbda7,0xd4234870,0xa7870bf3,0x2d3b4d79,
	0x42e04198,0x0cd0ede7,0x26470db8,0xf881814c,
	0x474d6ad7,0x7c0c5e5c,0xd1231959,0x381b7298,
	0xf5d2f4db,0xab838653,0x6e2f1e23,0x83719c9e,
	0xbd91e046,0x9a56456e,0xdc39200c,0x20c8c571,
	0x962bda1c,0xe1e696ff,0xb141ab08,0x7cca89b9,
	0x1a69e783,0x02cc4843,0xa2f7c579,0x429ef47d,
	0x427b169c,0x5ac9f049,0xdd8f0f00,0x5c8165bf,
	};
OPENSSL_GLOBAL const CAST_LONG CAST_S_table1[256]={
	0x1f201094,0xef0ba75b,0x69e3cf7e,0x393f4380,
	0xfe61cf7a,0xeec5207a,0x55889c94,0x72fc0651,
	0xada7ef79,0x4e1d7235,0xd55a63ce,0xde0436ba,
	0x99c430ef,0x5f0c0794,0x18dcdb7d,0xa1d6eff3,
	0xa0b52f7b,0x59e83605,0xee15b094,0xe9ffd909,
	0xdc440086,0xef944459,0xba83ccb3,0xe0c3cdfb,
	0xd1da4181,0x3b092ab1,0xf997f1c1,0xa5e6cf7b,
	0x01420ddb,0xe4e7ef5b,0x25a1ff41,0xe180f806,
	0x1fc41080,0x179bee7a,0xd37ac6a9,0xfe5830a4,
	0x98de8b7f,0x77e83f4e,0x79929269,0x24fa9f7b,
	0xe113c85b,0xacc40083,0xd7503525,0xf7ea615f,
	0x62143154,0x0d554b63,0x5d681121,0xc866c359,
	0x3d63cf73,0xcee234c0,0xd4d87e87,0x5c672b21,
	0x071f6181,0x39f7627f,0x361e3084,0xe4eb573b,
	0x602f64a4,0xd63acd9c,0x1bbc4635,0x9e81032d,
	0x2701f50c,0x99847ab4,0xa0e3df79,0xba6cf38c,
	0x10843094,0x2537a95e,0xf46f6ffe,0xa1ff3b1f,
	0x208cfb6a,0x8f458c74,0xd9e0a227,0x4ec73a34,
	0xfc884f69,0x3e4de8df,0xef0e0088,0x3559648d,
	0x8a45388c,0x1d804366,0x721d9bfd,0xa58684bb,
	0xe8256333,0x844e8212,0x128d8098,0xfed33fb4,
	0xce280ae1,0x27e19ba5,0xd5a6c252,0xe49754bd,
	0xc5d655dd,0xeb667064,0x77840b4d,0xa1b6a801,
	0x84db26a9,0xe0b56714,0x21f043b7,0xe5d05860,
	0x54f03084,0x066ff472,0xa31aa153,0xdadc4755,
	0xb5625dbf,0x68561be6,0x83ca6b94,0x2d6ed23b,
	0xeccf01db,0xa6d3d0ba,0xb6803d5c,0xaf77a709,
	0x33b4a34c,0x397bc8d6,0x5ee22b95,0x5f0e5304,
	0x81ed6f61,0x20e74364,0xb45e1378,0xde18639b,
	0x881ca122,0xb96726d1,0x8049a7e8,0x22b7da7b,
	0x5e552d25,0x5272d237,0x79d2951c,0xc60d894c,
	0x488cb402,0x1ba4fe5b,0xa4b09f6b,0x1ca815cf,
	0xa20c3005,0x8871df63,0xb9de2fcb,0x0cc6c9e9,
	0x0beeff53,0xe3214517,0xb4542835,0x9f63293c,
	0xee41e729,0x6e1d2d7c,0x50045286,0x1e6685f3,
	0xf33401c6,0x30a22c95,0x31a70850,0x60930f13,
	0x73f98417,0xa1269859,0xec645c44,0x52c877a9,
	0xcdff33a6,0xa02b1741,0x7cbad9a2,0x2180036f,
	0x50d99c08,0xcb3f4861,0xc26bd765,0x64a3f6ab,
	0x80342676,0x25a75e7b,0xe4e6d1fc,0x20c710e6,
	0xcdf0b680,0x17844d3b,0x31eef84d,0x7e0824e4,
	0x2ccb49eb,0x846a3bae,0x8ff77888,0xee5d60f6,
	0x7af75673,0x2fdd5cdb,0xa11631c1,0x30f66f43,
	0xb3faec54,0x157fd7fa,0xef8579cc,0xd152de58,
	0xdb2ffd5e,0x8f32ce19,0x306af97a,0x02f03ef8,
	0x99319ad5,0xc242fa0f,0xa7e3ebb0,0xc68e4906,
	0xb8da230c,0x80823028,0xdcdef3c8,0xd35fb171,
	0x088a1bc8,0xbec0c560,0x61a3c9e8,0xbca8f54d,
	0xc72feffa,0x22822e99,0x82c570b4,0xd8d94e89,
	0x8b1c34bc,0x301e16e6,0x273be979,0xb0ffeaa6,
	0x61d9b8c6,0x00b24869,0xb7ffce3f,0x08dc283b,
	0x43daf65a,0xf7e19798,0x7619b72f,0x8f1c9ba4,
	0xdc8637a0,0x16a7d3b1,0x9fc393b7,0xa7136eeb,
	0xc6bcc63e,0x1a513742,0xef6828bc,0x520365d6,
	0x2d6a77ab,0x3527ed4b,0x821fd216,0x095c6e2e,
	0xdb92f2fb,0x5eea29cb,0x145892f5,0x91584f7f,
	0x5483697b,0x2667a8cc,0x85196048,0x8c4bacea,
	0x833860d4,0x0d23e0f9,0x6c387e8a,0x0ae6d249,
	0xb284600c,0xd835731d,0xdcb1c647,0xac4c56ea,
	0x3ebd81b3,0x230eabb0,0x6438bc87,0xf0b5b1fa,
	0x8f5ea2b3,0xfc184642,0x0a036b7a,0x4fb089bd,
	0x649da589,0xa345415e,0x5c038323,0x3e5d3bb9,
	0x43d79572,0x7e6dd07c,0x06dfdf1e,0x6c6cc4ef,
	0x7160a539,0x73bfbe70,0x83877605,0x4523ecf1,
	};
OPENSSL_GLOBAL const CAST_LONG CAST_S_table2[256]={
	0x8defc240,0x25fa5d9f,0xeb903dbf,0xe810c907,
	0x47607fff,0x369fe44b,0x8c1fc644,0xaececa90,
	0xbeb1f9bf,0xeefbcaea,0xe8cf1950,0x51df07ae,
	0x920e8806,0xf0ad0548,0xe13c8d83,0x927010d5,
	0x11107d9f,0x07647db9,0xb2e3e4d4,0x3d4f285e,
	0xb9afa820,0xfade82e0,0xa067268b,0x8272792e,
	0x553fb2c0,0x489ae22b,0xd4ef9794,0x125e3fbc,
	0x21fffcee,0x825b1bfd,0x9255c5ed,0x1257a240,
	0x4e1a8302,0xbae07fff,0x528246e7,0x8e57140e,
	0x3373f7bf,0x8c9f8188,0xa6fc4ee8,0xc982b5a5,
	0xa8c01db7,0x579fc264,0x67094f31,0xf2bd3f5f,
	0x40fff7c1,0x1fb78dfc,0x8e6bd2c1,0x437be59b,
	0x99b03dbf,0xb5dbc64b,0x638dc0e6,0x55819d99,
	0xa197c81c,0x4a012d6e,0xc5884a28,0xccc36f71,
	0xb843c213,0x6c0743f1,0x8309893c,0x0feddd5f,
	0x2f7fe850,0xd7c07f7e,0x02507fbf,0x5afb9a04,
	0xa747d2d0,0x1651192e,0xaf70bf3e,0x58c31380,
	0x5f98302e,0x727cc3c4,0x0a0fb402,0x0f7fef82,
	0x8c96fdad,0x5d2c2aae,0x8ee99a49,0x50da88b8,
	0x8427f4a0,0x1eac5790,0x796fb449,0x8252dc15,
	0xefbd7d9b,0xa672597d,0xada840d8,0x45f54504,
	0xfa5d7403,0xe83ec305,0x4f91751a,0x925669c2,
	0x23efe941,0xa903f12e,0x60270df2,0x0276e4b6,
	0x94fd6574,0x927985b2,0x8276dbcb,0x02778176,
	0xf8af918d,0x4e48f79e,0x8f616ddf,0xe29d840e,
	0x842f7d83,0x340ce5c8,0x96bbb682,0x93b4b148,
	0xef303cab,0x984faf28,0x779faf9b,0x92dc560d,
	0x224d1e20,0x8437aa88,0x7d29dc96,0x2756d3dc,
	0x8b907cee,0xb51fd240,0xe7c07ce3,0xe566b4a1,
	0xc3e9615e,0x3cf8209d,0x6094d1e3,0xcd9ca341,
	0x5c76460e,0x00ea983b,0xd4d67881,0xfd47572c,
	0xf76cedd9,0xbda8229c,0x127dadaa,0x438a074e,
	0x1f97c090,0x081bdb8a,0x93a07ebe,0xb938ca15,
	0x97b03cff,0x3dc2c0f8,0x8d1ab2ec,0x64380e51,
	0x68cc7bfb,0xd90f2788,0x12490181,0x5de5ffd4,
	0xdd7ef86a,0x76a2e214,0xb9a40368,0x925d958f,
	0x4b39fffa,0xba39aee9,0xa4ffd30b,0xfaf7933b,
	0x6d498623,0x193cbcfa,0x27627545,0x825cf47a,
	0x61bd8ba0,0xd11e42d1,0xcead04f4,0x127ea392,
	0x10428db7,0x8272a972,0x9270c4a8,0x127de50b,
	0x285ba1c8,0x3c62f44f,0x35c0eaa5,0xe805d231,
	0x428929fb,0xb4fcdf82,0x4fb66a53,0x0e7dc15b,
	0x1f081fab,0x108618ae,0xfcfd086d,0xf9ff2889,
	0x694bcc11,0x236a5cae,0x12deca4d,0x2c3f8cc5,
	0xd2d02dfe,0xf8ef5896,0xe4cf52da,0x95155b67,
	0x494a488c,0xb9b6a80c,0x5c8f82bc,0x89d36b45,
	0x3a609437,0xec00c9a9,0x44715253,0x0a874b49,
	0xd773bc40,0x7c34671c,0x02717ef6,0x4feb5536,
	0xa2d02fff,0xd2bf60c4,0xd43f03c0,0x50b4ef6d,
	0x07478cd1,0x006e1888,0xa2e53f55,0xb9e6d4bc,
	0xa2048016,0x97573833,0xd7207d67,0xde0f8f3d,
	0x72f87b33,0xabcc4f33,0x7688c55d,0x7b00a6b0,
	0x947b0001,0x570075d2,0xf9bb88f8,0x8942019e,
	0x4264a5ff,0x856302e0,0x72dbd92b,0xee971b69,
	0x6ea22fde,0x5f08ae2b,0xaf7a616d,0xe5c98767,
	0xcf1febd2,0x61efc8c2,0xf1ac2571,0xcc8239c2,
	0x67214cb8,0xb1e583d1,0xb7dc3e62,0x7f10bdce,
	0xf90a5c38,0x0ff0443d,0x606e6dc6,0x60543a49,
	0x5727c148,0x2be98a1d,0x8ab41738,0x20e1be24,
	0xaf96da0f,0x68458425,0x99833be5,0x600d457d,
	0x282f9350,0x8334b362,0xd91d1120,0x2b6d8da0,
	0x642b1e31,0x9c305a00,0x52bce688,0x1b03588a,
	0xf7baefd5,0x4142ed9c,0xa4315c11,0x83323ec5,
	0xdfef4636,0xa133c501,0xe9d3531c,0xee353783,
	};
OPENSSL_GLOBAL const CAST_LONG CAST_S_table3[256]={
	0x9db30420,0x1fb6e9de,0xa7be7bef,0xd273a298,
	0x4a4f7bdb,0x64ad8c57,0x85510443,0xfa020ed1,
	0x7e287aff,0xe60fb663,0x095f35a1,0x79ebf120,
	0xfd059d43,0x6497b7b1,0xf3641f63,0x241e4adf,
	0x28147f5f,0x4fa2b8cd,0xc9430040,0x0cc32220,
	0xfdd30b30,0xc0a5374f,0x1d2d00d9,0x24147b15,
	0xee4d111a,0x0fca5167,0x71ff904c,0x2d195ffe,
	0x1a05645f,0x0c13fefe,0x081b08ca,0x05170121,
	0x80530100,0xe83e5efe,0xac9af4f8,0x7fe72701,
	0xd2b8ee5f,0x06df4261,0xbb9e9b8a,0x7293ea25,
	0xce84ffdf,0xf5718801,0x3dd64b04,0xa26f263b,
	0x7ed48400,0x547eebe6,0x446d4ca0,0x6cf3d6f5,
	0x2649abdf,0xaea0c7f5,0x36338cc1,0x503f7e93,
	0xd3772061,0x11b638e1,0x72500e03,0xf80eb2bb,
	0xabe0502e,0xec8d77de,0x57971e81,0xe14f6746,
	0xc9335400,0x6920318f,0x081dbb99,0xffc304a5,
	0x4d351805,0x7f3d5ce3,0xa6c866c6,0x5d5bcca9,
	0xdaec6fea,0x9f926f91,0x9f46222f,0x3991467d,
	0xa5bf6d8e,0x1143c44f,0x43958302,0xd0214eeb,
	0x022083b8,0x3fb6180c,0x18f8931e,0x281658e6,
	0x26486e3e,0x8bd78a70,0x7477e4c1,0xb506e07c,
	0xf32d0a25,0x79098b02,0xe4eabb81,0x28123b23,
	0x69dead38,0x1574ca16,0xdf871b62,0x211c40b7,
	0xa51a9ef9,0x0014377b,0x041e8ac8,0x09114003,
	0xbd59e4d2,0xe3d156d5,0x4fe876d5,0x2f91a340,
	0x557be8de,0x00eae4a7,0x0ce5c2ec,0x4db4bba6,
	0xe756bdff,0xdd3369ac,0xec17b035,0x06572327,
	0x99afc8b0,0x56c8c391,0x6b65811c,0x5e146119,
	0x6e85cb75,0xbe07c002,0xc2325577,0x893ff4ec,
	0x5bbfc92d,0xd0ec3b25,0xb7801ab7,0x8d6d3b24,
	0x20c763ef,0xc366a5fc,0x9c382880,0x0ace3205,
	0xaac9548a,0xeca1d7c7,0x041afa32,0x1d16625a,
	0x6701902c,0x9b757a54,0x31d477f7,0x9126b031,
	0x36cc6fdb,0xc70b8b46,0xd9e66a48,0x56e55a79,
	0x026a4ceb,0x52437eff,0x2f8f76b4,0x0df980a5,
	0x8674cde3,0xedda04eb,0x17a9be04,0x2c18f4df,
	0xb7747f9d,0xab2af7b4,0xefc34d20,0x2e096b7c,
	0x1741a254,0xe5b6a035,0x213d42f6,0x2c1c7c26,
	0x61c2f50f,0x6552daf9,0xd2c231f8,0x25130f69,
	0xd8167fa2,0x0418f2c8,0x001a96a6,0x0d1526ab,
	0x63315c21,0x5e0a72ec,0x49bafefd,0x187908d9,
	0x8d0dbd86,0x311170a7,0x3e9b640c,0xcc3e10d7,
	0xd5cad3b6,0x0caec388,0xf73001e1,0x6c728aff,
	0x71eae2a1,0x1f9af36e,0xcfcbd12f,0xc1de8417,
	0xac07be6b,0xcb44a1d8,0x8b9b0f56,0x013988c3,
	0xb1c52fca,0xb4be31cd,0xd8782806,0x12a3a4e2,
	0x6f7de532,0x58fd7eb6,0xd01ee900,0x24adffc2,
	0xf4990fc5,0x9711aac5,0x001d7b95,0x82e5e7d2,
	0x109873f6,0x00613096,0xc32d9521,0xada121ff,
	0x29908415,0x7fbb977f,0xaf9eb3db,0x29c9ed2a,
	0x5ce2a465,0xa730f32c,0xd0aa3fe8,0x8a5cc091,
	0xd49e2ce7,0x0ce454a9,0xd60acd86,0x015f1919,
	0x77079103,0xdea03af6,0x78a8565e,0xdee356df,
	0x21f05cbe,0x8b75e387,0xb3c50651,0xb8a5c3ef,
	0xd8eeb6d2,0xe523be77,0xc2154529,0x2f69efdf,
	0xafe67afb,0xf470c4b2,0xf3e0eb5b,0xd6cc9876,
	0x39e4460c,0x1fda8538,0x1987832f,0xca007367,
	0xa99144f8,0x296b299e,0x492fc295,0x9266beab,
	0xb5676e69,0x9bd3ddda,0xdf7e052f,0xdb25701c,
	0x1b5e51ee,0xf65324e6,0x6afce36c,0x0316cc04,
	0x8644213e,0xb7dc59d0,0x7965291f,0xccd6fd43,
	0x41823979,0x932bcdf6,0xb657c34d,0x4edfd282,
	0x7ae5290c,0x3cb9536b,0x851e20fe,0x9833557e,
	0x13ecf0b0,0xd3ffb372,0x3f85c5c1,0x0aef7ed2,
	};
OPENSSL_GLOBAL const CAST_LONG CAST_S_table4[256]={
	0x7ec90c04,0x2c6e74b9,0x9b0e66df,0xa6337911,
	0xb86a7fff,0x1dd358f5,0x44dd9d44,0x1731167f,
	0x08fbf1fa,0xe7f511cc,0xd2051b00,0x735aba00,
	0x2ab722d8,0x386381cb,0xacf6243a,0x69befd7a,
	0xe6a2e77f,0xf0c720cd,0xc4494816,0xccf5c180,
	0x38851640,0x15b0a848,0xe68b18cb,0x4caadeff,
	0x5f480a01,0x0412b2aa,0x259814fc,0x41d0efe2,
	0x4e40b48d,0x248eb6fb,0x8dba1cfe,0x41a99b02,
	0x1a550a04,0xba8f65cb,0x7251f4e7,0x95a51725,
	0xc106ecd7,0x97a5980a,0xc539b9aa,0x4d79fe6a,
	0xf2f3f763,0x68af8040,0xed0c9e56,0x11b4958b,
	0xe1eb5a88,0x8709e6b0,0xd7e07156,0x4e29fea7,
	0x6366e52d,0x02d1c000,0xc4ac8e05,0x9377f571,
	0x0c05372a,0x578535f2,0x2261be02,0xd642a0c9,
	0xdf13a280,0x74b55bd2,0x682199c0,0xd421e5ec,
	0x53fb3ce8,0xc8adedb3,0x28a87fc9,0x3d959981,
	0x5c1ff900,0xfe38d399,0x0c4eff0b,0x062407ea,
	0xaa2f4fb1,0x4fb96976,0x90c79505,0xb0a8a774,
	0xef55a1ff,0xe59ca2c2,0xa6b62d27,0xe66a4263,
	0xdf65001f,0x0ec50966,0xdfdd55bc,0x29de0655,
	0x911e739a,0x17af8975,0x32c7911c,0x89f89468,
	0x0d01e980,0x524755f4,0x03b63cc9,0x0cc844b2,
	0xbcf3f0aa,0x87ac36e9,0xe53a7426,0x01b3d82b,
	0x1a9e7449,0x64ee2d7e,0xcddbb1da,0x01c94910,
	0xb868bf80,0x0d26f3fd,0x9342ede7,0x04a5c284,
	0x636737b6,0x50f5b616,0xf24766e3,0x8eca36c1,
	0x136e05db,0xfef18391,0xfb887a37,0xd6e7f7d4,
	0xc7fb7dc9,0x3063fcdf,0xb6f589de,0xec2941da,
	0x26e46695,0xb7566419,0xf654efc5,0xd08d58b7,
	0x48925401,0xc1bacb7f,0xe5ff550f,0xb6083049,
	0x5bb5d0e8,0x87d72e5a,0xab6a6ee1,0x223a66ce,
	0xc62bf3cd,0x9e0885f9,0x68cb3e47,0x086c010f,
	0xa21de820,0xd18b69de,0xf3f65777,0xfa02c3f6,
	0x407edac3,0xcbb3d550,0x1793084d,0xb0d70eba,
	0x0ab378d5,0xd951fb0c,0xded7da56,0x4124bbe4,
	0x94ca0b56,0x0f5755d1,0xe0e1e56e,0x6184b5be,
	0x580a249f,0x94f74bc0,0xe327888e,0x9f7b5561,
	0xc3dc0280,0x05687715,0x646c6bd7,0x44904db3,
	0x66b4f0a3,0xc0f1648a,0x697ed5af,0x49e92ff6,
	0x309e374f,0x2cb6356a,0x85808573,0x4991f840,
	0x76f0ae02,0x083be84d,0x28421c9a,0x44489406,
	0x736e4cb8,0xc1092910,0x8bc95fc6,0x7d869cf4,
	0x134f616f,0x2e77118d,0xb31b2be1,0xaa90b472,
	0x3ca5d717,0x7d161bba,0x9cad9010,0xaf462ba2,
	0x9fe459d2,0x45d34559,0xd9f2da13,0xdbc65487,
	0xf3e4f94e,0x176d486f,0x097c13ea,0x631da5c7,
	0x445f7382,0x175683f4,0xcdc66a97,0x70be0288,
	0xb3cdcf72,0x6e5dd2f3,0x20936079,0x459b80a5,
	0xbe60e2db,0xa9c23101,0xeba5315c,0x224e42f2,
	0x1c5c1572,0xf6721b2c,0x1ad2fff3,0x8c25404e,
	0x324ed72f,0x4067b7fd,0x0523138e,0x5ca3bc78,
	0xdc0fd66e,0x75922283,0x784d6b17,0x58ebb16e,
	0x44094f85,0x3f481d87,0xfcfeae7b,0x77b5ff76,
	0x8c2302bf,0xaaf47556,0x5f46b02a,0x2b092801,
	0x3d38f5f7,0x0ca81f36,0x52af4a8a,0x66d5e7c0,
	0xdf3b0874,0x95055110,0x1b5ad7a8,0xf61ed5ad,
	0x6cf6e479,0x20758184,0xd0cefa65,0x88f7be58,
	0x4a046826,0x0ff6f8f3,0xa09c7f70,0x5346aba0,
	0x5ce96c28,0xe176eda3,0x6bac307f,0x376829d2,
	0x85360fa9,0x17e3fe2a,0x24b79767,0xf5a96b20,
	0xd6cd2595,0x68ff1ebf,0x7555442c,0xf19f06be,
	0xf9e0659a,0xeeb9491d,0x34010718,0xbb30cab8,
	0xe822fe15,0x88570983,0x750e6249,0xda627e55,
	0x5e76ffa8,0xb1534546,0x6d47de08,0xefe9e7d4,
	};
OPENSSL_GLOBAL const CAST_LONG CAST_S_table5[256]={
	0xf6fa8f9d,0x2cac6ce1,0x4ca34867,0xe2337f7c,
	0x95db08e7,0x016843b4,0xeced5cbc,0x325553ac,
	0xbf9f0960,0xdfa1e2ed,0x83f0579d,0x63ed86b9,
	0x1ab6a6b8,0xde5ebe39,0xf38ff732,0x8989b138,
	0x33f14961,0xc01937bd,0xf506c6da,0xe4625e7e,
	0xa308ea99,0x4e23e33c,0x79cbd7cc,0x48a14367,
	0xa3149619,0xfec94bd5,0xa114174a,0xeaa01866,
	0xa084db2d,0x09a8486f,0xa888614a,0x2900af98,
	0x01665991,0xe1992863,0xc8f30c60,0x2e78ef3c,
	0xd0d51932,0xcf0fec14,0xf7ca07d2,0xd0a82072,
	0xfd41197e,0x9305a6b0,0xe86be3da,0x74bed3cd,
	0x372da53c,0x4c7f4448,0xdab5d440,0x6dba0ec3,
	0x083919a7,0x9fbaeed9,0x49dbcfb0,0x4e670c53,
	0x5c3d9c01,0x64bdb941,0x2c0e636a,0xba7dd9cd,
	0xea6f7388,0xe70bc762,0x35f29adb,0x5c4cdd8d,
	0xf0d48d8c,0xb88153e2,0x08a19866,0x1ae2eac8,
	0x284caf89,0xaa928223,0x9334be53,0x3b3a21bf,
	0x16434be3,0x9aea3906,0xefe8c36e,0xf890cdd9,
	0x80226dae,0xc340a4a3,0xdf7e9c09,0xa694a807,
	0x5b7c5ecc,0x221db3a6,0x9a69a02f,0x68818a54,
	0xceb2296f,0x53c0843a,0xfe893655,0x25bfe68a,
	0xb4628abc,0xcf222ebf,0x25ac6f48,0xa9a99387,
	0x53bddb65,0xe76ffbe7,0xe967fd78,0x0ba93563,
	0x8e342bc1,0xe8a11be9,0x4980740d,0xc8087dfc,
	0x8de4bf99,0xa11101a0,0x7fd37975,0xda5a26c0,
	0xe81f994f,0x9528cd89,0xfd339fed,0xb87834bf,
	0x5f04456d,0x22258698,0xc9c4c83b,0x2dc156be,
	0x4f628daa,0x57f55ec5,0xe2220abe,0xd2916ebf,
	0x4ec75b95,0x24f2c3c0,0x42d15d99,0xcd0d7fa0,
	0x7b6e27ff,0xa8dc8af0,0x7345c106,0xf41e232f,
	0x35162386,0xe6ea8926,0x3333b094,0x157ec6f2,
	0x372b74af,0x692573e4,0xe9a9d848,0xf3160289,
	0x3a62ef1d,0xa787e238,0xf3a5f676,0x74364853,
	0x20951063,0x4576698d,0xb6fad407,0x592af950,
	0x36f73523,0x4cfb6e87,0x7da4cec0,0x6c152daa,
	0xcb0396a8,0xc50dfe5d,0xfcd707ab,0x0921c42f,
	0x89dff0bb,0x5fe2be78,0x448f4f33,0x754613c9,
	0x2b05d08d,0x48b9d585,0xdc049441,0xc8098f9b,
	0x7dede786,0xc39a3373,0x42410005,0x6a091751,
	0x0ef3c8a6,0x890072d6,0x28207682,0xa9a9f7be,
	0xbf32679d,0xd45b5b75,0xb353fd00,0xcbb0e358,
	0x830f220a,0x1f8fb214,0xd372cf08,0xcc3c4a13,
	0x8cf63166,0x061c87be,0x88c98f88,0x6062e397,
	0x47cf8e7a,0xb6c85283,0x3cc2acfb,0x3fc06976,
	0x4e8f0252,0x64d8314d,0xda3870e3,0x1e665459,
	0xc10908f0,0x513021a5,0x6c5b68b7,0x822f8aa0,
	0x3007cd3e,0x74719eef,0xdc872681,0x073340d4,
	0x7e432fd9,0x0c5ec241,0x8809286c,0xf592d891,
	0x08a930f6,0x957ef305,0xb7fbffbd,0xc266e96f,
	0x6fe4ac98,0xb173ecc0,0xbc60b42a,0x953498da,
	0xfba1ae12,0x2d4bd736,0x0f25faab,0xa4f3fceb,
	0xe2969123,0x257f0c3d,0x9348af49,0x361400bc,
	0xe8816f4a,0x3814f200,0xa3f94043,0x9c7a54c2,
	0xbc704f57,0xda41e7f9,0xc25ad33a,0x54f4a084,
	0xb17f5505,0x59357cbe,0xedbd15c8,0x7f97c5ab,
	0xba5ac7b5,0xb6f6deaf,0x3a479c3a,0x5302da25,
	0x653d7e6a,0x54268d49,0x51a477ea,0x5017d55b,
	0xd7d25d88,0x44136c76,0x0404a8c8,0xb8e5a121,
	0xb81a928a,0x60ed5869,0x97c55b96,0xeaec991b,
	0x29935913,0x01fdb7f1,0x088e8dfa,0x9ab6f6f5,
	0x3b4cbf9f,0x4a5de3ab,0xe6051d35,0xa0e1d855,
	0xd36b4cf1,0xf544edeb,0xb0e93524,0xbebb8fbd,
	0xa2d762cf,0x49c92f54,0x38b5f331,0x7128a454,
	0x48392905,0xa65b1db8,0x851c97bd,0xd675cf2f,
	};
OPENSSL_GLOBAL const CAST_LONG CAST_S_table6[256]={
	0x85e04019,0x332bf567,0x662dbfff,0xcfc65693,
	0x2a8d7f6f,0xab9bc912,0xde6008a1,0x2028da1f,
	0x0227bce7,0x4d642916,0x18fac300,0x50f18b82,
	0x2cb2cb11,0xb232e75c,0x4b3695f2,0xb28707de,
	0xa05fbcf6,0xcd4181e9,0xe150210c,0xe24ef1bd,
	0xb168c381,0xfde4e789,0x5c79b0d8,0x1e8bfd43,
	0x4d495001,0x38be4341,0x913cee1d,0x92a79c3f,
	0x089766be,0xbaeeadf4,0x1286becf,0xb6eacb19,
	0x2660c200,0x7565bde4,0x64241f7a,0x8248dca9,
	0xc3b3ad66,0x28136086,0x0bd8dfa8,0x356d1cf2,
	0x107789be,0xb3b2e9ce,0x0502aa8f,0x0bc0351e,
	0x166bf52a,0xeb12ff82,0xe3486911,0xd34d7516,
	0x4e7b3aff,0x5f43671b,0x9cf6e037,0x4981ac83,
	0x334266ce,0x8c9341b7,0xd0d854c0,0xcb3a6c88,
	0x47bc2829,0x4725ba37,0xa66ad22b,0x7ad61f1e,
	0x0c5cbafa,0x4437f107,0xb6e79962,0x42d2d816,
	0x0a961288,0xe1a5c06e,0x13749e67,0x72fc081a,
	0xb1d139f7,0xf9583745,0xcf19df58,0xbec3f756,
	0xc06eba30,0x07211b24,0x45c28829,0xc95e317f,
	0xbc8ec511,0x38bc46e9,0xc6e6fa14,0xbae8584a,
	0xad4ebc46,0x468f508b,0x7829435f,0xf124183b,
	0x821dba9f,0xaff60ff4,0xea2c4e6d,0x16e39264,
	0x92544a8b,0x009b4fc3,0xaba68ced,0x9ac96f78,
	0x06a5b79a,0xb2856e6e,0x1aec3ca9,0xbe838688,
	0x0e0804e9,0x55f1be56,0xe7e5363b,0xb3a1f25d,
	0xf7debb85,0x61fe033c,0x16746233,0x3c034c28,
	0xda6d0c74,0x79aac56c,0x3ce4e1ad,0x51f0c802,
	0x98f8f35a,0x1626a49f,0xeed82b29,0x1d382fe3,
	0x0c4fb99a,0xbb325778,0x3ec6d97b,0x6e77a6a9,
	0xcb658b5c,0xd45230c7,0x2bd1408b,0x60c03eb7,
	0xb9068d78,0xa33754f4,0xf430c87d,0xc8a71302,
	0xb96d8c32,0xebd4e7be,0xbe8b9d2d,0x7979fb06,
	0xe7225308,0x8b75cf77,0x11ef8da4,0xe083c858,
	0x8d6b786f,0x5a6317a6,0xfa5cf7a0,0x5dda0033,
	0xf28ebfb0,0xf5b9c310,0xa0eac280,0x08b9767a,
	0xa3d9d2b0,0x79d34217,0x021a718d,0x9ac6336a,
	0x2711fd60,0x438050e3,0x069908a8,0x3d7fedc4,
	0x826d2bef,0x4eeb8476,0x488dcf25,0x36c9d566,
	0x28e74e41,0xc2610aca,0x3d49a9cf,0xbae3b9df,
	0xb65f8de6,0x92aeaf64,0x3ac7d5e6,0x9ea80509,
	0xf22b017d,0xa4173f70,0xdd1e16c3,0x15e0d7f9,
	0x50b1b887,0x2b9f4fd5,0x625aba82,0x6a017962,
	0x2ec01b9c,0x15488aa9,0xd716e740,0x40055a2c,
	0x93d29a22,0xe32dbf9a,0x058745b9,0x3453dc1e,
	0xd699296e,0x496cff6f,0x1c9f4986,0xdfe2ed07,
	0xb87242d1,0x19de7eae,0x053e561a,0x15ad6f8c,
	0x66626c1c,0x7154c24c,0xea082b2a,0x93eb2939,
	0x17dcb0f0,0x58d4f2ae,0x9ea294fb,0x52cf564c,
	0x9883fe66,0x2ec40581,0x763953c3,0x01d6692e,
	0xd3a0c108,0xa1e7160e,0xe4f2dfa6,0x693ed285,
	0x74904698,0x4c2b0edd,0x4f757656,0x5d393378,
	0xa132234f,0x3d321c5d,0xc3f5e194,0x4b269301,
	0xc79f022f,0x3c997e7e,0x5e4f9504,0x3ffafbbd,
	0x76f7ad0e,0x296693f4,0x3d1fce6f,0xc61e45be,
	0xd3b5ab34,0xf72bf9b7,0x1b0434c0,0x4e72b567,
	0x5592a33d,0xb5229301,0xcfd2a87f,0x60aeb767,
	0x1814386b,0x30bcc33d,0x38a0c07d,0xfd1606f2,
	0xc363519b,0x589dd390,0x5479f8e6,0x1cb8d647,
	0x97fd61a9,0xea7759f4,0x2d57539d,0x569a58cf,
	0xe84e63ad,0x462e1b78,0x6580f87e,0xf3817914,
	0x91da55f4,0x40a230f3,0xd1988f35,0xb6e318d2,
	0x3ffa50bc,0x3d40f021,0xc3c0bdae,0x4958c24c,
	0x518f36b2,0x84b1d370,0x0fedce83,0x878ddada,
	0xf2a279c7,0x94e01be8,0x90716f4b,0x954b8aa3,
	};
OPENSSL_GLOBAL const CAST_LONG CAST_S_table7[256]={
	0xe216300d,0xbbddfffc,0xa7ebdabd,0x35648095,
	0x7789f8b7,0xe6c1121b,0x0e241600,0x052ce8b5,
	0x11a9cfb0,0xe5952f11,0xece7990a,0x9386d174,
	0x2a42931c,0x76e38111,0xb12def3a,0x37ddddfc,
	0xde9adeb1,0x0a0cc32c,0xbe197029,0x84a00940,
	0xbb243a0f,0xb4d137cf,0xb44e79f0,0x049eedfd,
	0x0b15a15d,0x480d3168,0x8bbbde5a,0x669ded42,
	0xc7ece831,0x3f8f95e7,0x72df191b,0x7580330d,
	0x94074251,0x5c7dcdfa,0xabbe6d63,0xaa402164,
	0xb301d40a,0x02e7d1ca,0x53571dae,0x7a3182a2,
	0x12a8ddec,0xfdaa335d,0x176f43e8,0x71fb46d4,
	0x38129022,0xce949ad4,0xb84769ad,0x965bd862,
	0x82f3d055,0x66fb9767,0x15b80b4e,0x1d5b47a0,
	0x4cfde06f,0xc28ec4b8,0x57e8726e,0x647a78fc,
	0x99865d44,0x608bd593,0x6c200e03,0x39dc5ff6,
	0x5d0b00a3,0xae63aff2,0x7e8bd632,0x70108c0c,
	0xbbd35049,0x2998df04,0x980cf42a,0x9b6df491,
	0x9e7edd53,0x06918548,0x58cb7e07,0x3b74ef2e,
	0x522fffb1,0xd24708cc,0x1c7e27cd,0xa4eb215b,
	0x3cf1d2e2,0x19b47a38,0x424f7618,0x35856039,
	0x9d17dee7,0x27eb35e6,0xc9aff67b,0x36baf5b8,
	0x09c467cd,0xc18910b1,0xe11dbf7b,0x06cd1af8,
	0x7170c608,0x2d5e3354,0xd4de495a,0x64c6d006,
	0xbcc0c62c,0x3dd00db3,0x708f8f34,0x77d51b42,
	0x264f620f,0x24b8d2bf,0x15c1b79e,0x46a52564,
	0xf8d7e54e,0x3e378160,0x7895cda5,0x859c15a5,
	0xe6459788,0xc37bc75f,0xdb07ba0c,0x0676a3ab,
	0x7f229b1e,0x31842e7b,0x24259fd7,0xf8bef472,
	0x835ffcb8,0x6df4c1f2,0x96f5b195,0xfd0af0fc,
	0xb0fe134c,0xe2506d3d,0x4f9b12ea,0xf215f225,
	0xa223736f,0x9fb4c428,0x25d04979,0x34c713f8,
	0xc4618187,0xea7a6e98,0x7cd16efc,0x1436876c,
	0xf1544107,0xbedeee14,0x56e9af27,0xa04aa441,
	0x3cf7c899,0x92ecbae6,0xdd67016d,0x151682eb,
	0xa842eedf,0xfdba60b4,0xf1907b75,0x20e3030f,
	0x24d8c29e,0xe139673b,0xefa63fb8,0x71873054,
	0xb6f2cf3b,0x9f326442,0xcb15a4cc,0xb01a4504,
	0xf1e47d8d,0x844a1be5,0xbae7dfdc,0x42cbda70,
	0xcd7dae0a,0x57e85b7a,0xd53f5af6,0x20cf4d8c,
	0xcea4d428,0x79d130a4,0x3486ebfb,0x33d3cddc,
	0x77853b53,0x37effcb5,0xc5068778,0xe580b3e6,
	0x4e68b8f4,0xc5c8b37e,0x0d809ea2,0x398feb7c,
	0x132a4f94,0x43b7950e,0x2fee7d1c,0x223613bd,
	0xdd06caa2,0x37df932b,0xc4248289,0xacf3ebc3,
	0x5715f6b7,0xef3478dd,0xf267616f,0xc148cbe4,
	0x9052815e,0x5e410fab,0xb48a2465,0x2eda7fa4,
	0xe87b40e4,0xe98ea084,0x5889e9e1,0xefd390fc,
	0xdd07d35b,0xdb485694,0x38d7e5b2,0x57720101,
	0x730edebc,0x5b643113,0x94917e4f,0x503c2fba,
	0x646f1282,0x7523d24a,0xe0779695,0xf9c17a8f,
	0x7a5b2121,0xd187b896,0x29263a4d,0xba510cdf,
	0x81f47c9f,0xad1163ed,0xea7b5965,0x1a00726e,
	0x11403092,0x00da6d77,0x4a0cdd61,0xad1f4603,
	0x605bdfb0,0x9eedc364,0x22ebe6a8,0xcee7d28a,
	0xa0e736a0,0x5564a6b9,0x10853209,0xc7eb8f37,
	0x2de705ca,0x8951570f,0xdf09822b,0xbd691a6c,
	0xaa12e4f2,0x87451c0f,0xe0f6a27a,0x3ada4819,
	0x4cf1764f,0x0d771c2b,0x67cdb156,0x350d8384,
	0x5938fa0f,0x42399ef3,0x36997b07,0x0e84093d,
	0x4aa93e61,0x8360d87b,0x1fa98b0c,0x1149382c,
	0xe97625a5,0x0614d1b7,0x0e25244b,0x0c768347,
	0x589e8d82,0x0d2059d1,0xa466bb1e,0xf8da0a82,
	0x04f19130,0xba6e4ec0,0x99265164,0x1ee7230d,
	0x50b2ad80,0xeaee6801,0x8db2a283,0xea8bf59e,
	};
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/CAST/ccCast.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 * ccCAST.c - shim between openssl-based CAST and CommonEncryption.
 *
 * Created 3/30/06 by Doug Mitchell. 
 */

#include <CommonCrypto/ccCast.h>
#include <sys/types.h>

int cast_cc_set_key(
	CAST_KEY *cx, 
	const void *rawKey, 
	size_t keyLength,
	int forEncrypt)
{
	CAST_set_key(cx, keyLength, rawKey);
	return 0;
}

void cast_cc_encrypt(CAST_KEY *cx, const void *blockIn, void *blockOut)
{
	CAST_ecb_encrypt((const unsigned char *)blockIn, (unsigned char *)blockOut,
		cx, CAST_ENCRYPT);
}

void cast_cc_decrypt(CAST_KEY *cx, const void *blockIn, void *blockOut)
{
	CAST_ecb_encrypt((const unsigned char *)blockIn, (unsigned char *)blockOut,
		cx, CAST_DECRYPT);
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































Deleted Source/CommonCrypto.exp.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
_CCAESCmac
_CCCalibratePBKDF
_CCCrypt
_CCCryptorCreate
_CCCryptorCreateFromData
_CCCryptorCreateFromDataWithMode
_CCCryptorCreateWithMode
_CCCryptorDecryptDataBlock
_CCCryptorEncryptDataBlock
_CCCryptorFinal
_CCCryptorGetOutputLength
_CCCryptorRelease
_CCCryptorReset
_CCCryptorUpdate
_CCDesCBCCksum
_CCDesIsWeakKey
_CCDesSetOddParity
_CCDigest
_CCDigestFinal
_CCDigestInit
_CCDigestUpdate
_CCDigestCreate
_CCDigestDestroy
_CCDigestReset
_CCDigestInterrimResult
_CCDigestBlockSize
_CCDigestOutputSize
_CCHmac
_CCHmacFinal
_CCHmacInit
_CCHmacUpdate
_CCKeyDerivationPBKDF
_CCRandomCopyBytes
_CCSymmetricKeyUnwrap
_CCSymmetricKeyWrap
_CCSymmetricUnwrappedSize
_CCSymmetricWrappedSize
_CC_CAST_decrypt
_CC_CAST_ecb_encrypt
_CC_CAST_encrypt
_CC_CAST_set_key
_CC_MD2
_CC_MD2_Final
_CC_MD2_Init
_CC_MD2_Update
_CC_MD4
_CC_MD4_Final
_CC_MD4_Init
_CC_MD4_Update
_CC_MD5
_CC_MD5_Final
_CC_MD5_Init
_CC_MD5_Update
_CC_RC4
_CC_RC4_set_key
_CC_SHA1
_CC_SHA1_Final
_CC_SHA1_Init
_CC_SHA1_Update
_CC_SHA224
_CC_SHA224_Final
_CC_SHA224_Init
_CC_SHA224_Update
_CC_SHA256
_CC_SHA256_Final
_CC_SHA256_Init
_CC_SHA256_Update
_CC_SHA384
_CC_SHA384_Final
_CC_SHA384_Init
_CC_SHA384_Update
_CC_SHA512
_CC_SHA512_Final
_CC_SHA512_Init
_CC_SHA512_Update
_CCrfc3394_iv
_CCrfc3394_ivLen
_aes_cc_decrypt
_aes_cc_encrypt
_aes_cc_set_iv
_aes_cc_set_key
_aes_decrypt_cbc
_aes_decrypt_key128
_aes_decrypt_key192
_aes_decrypt_key256
_aes_encrypt_cbc
_aes_encrypt_key128
_aes_encrypt_key192
_aes_encrypt_key256
_kCCRandomDefault
_osDes3Decrypt
_osDes3Encrypt
_osDes3Setkey
_osDesDecrypt
_osDesEncrypt
_osDesSetkey
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































Added Source/CommonCryptoSPI/CommonBigNum.h.







































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
/*
 * Copyright (c) 2011 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef _CC_BIGNUM_H_
#define _CC_BIGNUM_H_

#include <Availability.h>
#include <stdint.h>
#include <CommonCrypto/CommonCryptor.h>

#ifdef __cplusplus
extern "C" {
#endif

/*
 * This is an SPI - it isn't intended to be generally used.  If you 
 * intend to use this we strongly urge you to talk to someone in the
 * Information Security Group to see if there isn't an alternative
 * set of functions to implement your cryptographic needs.
 */

/*
 * This shares the error status of CommonCryptor.h
 */
  
typedef CCCryptorStatus CCStatus;
typedef struct _CCBigNumRef *CCBigNumRef;

/*!
	@function   CCCreateBigNum
	@abstract   Creates a BigNum - must be freed later with
             	CCBigNumFree.
  
	@param      status  A pointer to a CCStatus for return codes. 

	@result		On success this returns a newly
    			allocated BigNum (must be freed with 
                CCBigNumFree).
                Returns NULL on failure.
 */

CCBigNumRef
CCCreateBigNum(CCStatus *status)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumClear
	@abstract   Zeroes (clears) a BigNum.
  
	@param      bn The BigNum to clear. 
	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumClear(CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumFree
	@abstract   Frees and clears a BigNum.
  
	@param      bn The BigNum to free. 

 */

void
CCBigNumFree(CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumCopy
	@abstract   Copies a BigNum.
  
	@param      status  A pointer to a CCStatus for return codes. 
	@param      bn The BigNum to copy. 
	@result		On success this returns a newly
    			allocated BigNum (must be freed with 
                CCBigNumFree).
                Returns NULL on failure.
 */

CCBigNumRef
CCBigNumCopy(CCStatus *status, const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumBitCount
	@abstract   Returns the number of significant bits 
    			in a BigNum.
  
	@param      bn The BigNum. 
	@result		Returns number of bits.

 */

uint32_t
CCBigNumBitCount(const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumZeroLSBCount
	@abstract   Returns the number of zero bits 
    			before the least significant 1 bit.
  
	@param      bn The BigNum. 
	@result		Returns number of bits.

 */

uint32_t
CCBigNumZeroLSBCount(const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumByteCount
	@abstract   Returns the number of bytes if
    			converted to binary data.
  
	@param      bn The BigNum. 
	@result		Returns number of bytes.

 */

uint32_t
CCBigNumByteCount(const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumFromData
	@abstract   Creates a BigNum from binary data.
  
	@param      status  A pointer to a CCStatus for return codes. 
	@param      s - the data pointer.  The data is expected to be
    			an array of octets in big endian format. 
	@param      len - the length of the data. 
	@result		On success this returns a newly
    			allocated BigNum (must be freed with 
                CCBigNumFree).
                Returns NULL on failure.
 */

CCBigNumRef
CCBigNumFromData(CCStatus *status, const void *s, size_t len)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumToData
	@abstract   Dumps a BigNum into binary data.
  
	@param      status  A pointer to a CCStatus for return codes. 
	@param      bn The BigNum. 
	@param      s - the pointer to the data area.
    			You can use CCBigNumByteCount() to
                determine the size of the data area
                to provide. 
	@result     Returns the length of the data area.

 */

size_t
CCBigNumToData(CCStatus *status, const CCBigNumRef bn, void *to)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumFromHexString
	@abstract   Creates a BigNum from a hexadecimal string.
  
	@param      status  A pointer to a CCStatus for return codes. 
	@param      in - a null terminated hexadecimal string. 
	@result		On success this returns a newly
    			allocated BigNum (must be freed with 
                CCBigNumFree).
                Returns NULL on failure.
 */

CCBigNumRef
CCBigNumFromHexString(CCStatus *status, const char *in)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumToHexString
	@abstract   Dumps a BigNum into binary data.
  
	@param      status  A pointer to a CCStatus for return codes. 
	@param      bn The BigNum. 
	@result     Returns a hexadecimal string representation
    			of the BigNum.  This must be freed by the caller.
                Returns NULL on failure.

 */

char *
CCBigNumToHexString(CCStatus *status, const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumByteCount
	@abstract   Returns the number of bytes that will result from
    			converting a BigNum to octets.
  
	@param      bn The BigNum. 
	@result		The number of bytes.
 */

uint32_t
CCBigNumByteCount(const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumCompare
	@abstract   Compares two BigNums.
  
	@param      bn1 - a BigNum. 
	@param      bn2 - a BigNum. 
	@result		Returns -1 if bn1 is less than bn2.
                Returns 0 if bn1 and bn2 are equal.
                Returns 1 if bn1 is greater than bn2.

 */

int
CCBigNumCompare(const CCBigNumRef bn1, const CCBigNumRef bn2)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumCompareI
	@abstract   Compares a BigNum and a 32 bit integer.
  
	@param      bn1 - a BigNum. 
	@param      num - an integer. 
	@result		Returns -1 if bn1 is less than num.
                Returns 0 if bn1 and num are equal.
                Returns 1 if bn1 is greater than num.

 */


int
CCBigNumCompareI(const CCBigNumRef bn1, const uint32_t num)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


/*!
	@function   CCBigNumSetNegative
	@abstract   Negates a BigNum.
  
	@param      bn - a BigNum. 
	@result		returns a CCStatus (See CommonCryptor.h for values).

 */

CCStatus
CCBigNumSetNegative(CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumSetI
	@abstract   Sets a BigNum value using an unsigned integer.
  
	@param      bn The BigNum. 
	@param      num The value to set. 
	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumSetI(CCBigNumRef bn, uint64_t num)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumGetI
	@abstract   Get an unsigned integer representation of the BigNum.
                This assumes the BigNum can actually fit within the 
                unsigned integer representation.
  
	@param      status  A pointer to a CCStatus for return codes. 
	@param      bn The BigNum. 
	@result		returns the unsigned integer value.
 */

uint32_t
CCBigNumGetI(CCStatus *status, const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumAdd
	@abstract   Adds two BigNums.

	@param		result  A bigNum in which to place the result.
    @param		a		The first BigNum to add.
    @param		b		The second BigNum to add.
     
	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumAdd(CCBigNumRef result, const CCBigNumRef a, const CCBigNumRef b)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumAddI
	@abstract   Adds a BigNum and an unsigned integer.

	@param		result  A bigNum in which to place the result.
    @param		a		The first BigNum to add.
    @param		b		The unsigned integer to add.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumAddI(CCBigNumRef result, const CCBigNumRef a, const uint32_t b)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumSub
	@abstract   Subtracts a BigNum from a BigNum.

	@param		result  A bigNum in which to place the result.
    @param		a		The BigNum.
    @param		b		The BigNum to subtract.
     
	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumSub(CCBigNumRef result, const CCBigNumRef a, const CCBigNumRef b)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumSubI
	@abstract   Subtracts an unsigned integer from a BigNum.

	@param		result  A bigNum in which to place the result.
    @param		a		The BigNum.
    @param		b		The unsigned integer to subtract.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumSubI(CCBigNumRef result, const CCBigNumRef a, const uint32_t b)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumMul
	@abstract   Multiplies two BigNums.

	@param		result  A bigNum in which to place the result.
    @param		a		The first BigNum to multiply.
    @param		b		The second BigNum to multiply.
     
    @result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumMul(CCBigNumRef result, const CCBigNumRef a, const CCBigNumRef b)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumMulI
	@abstract   Multiplies a BigNum and an unsigned integer.

	@param		result  A bigNum in which to place the result.
    @param		a		The first BigNum to multiply.
    @param		b		The unsigned integer to multiply.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumMulI(CCBigNumRef result, const CCBigNumRef a, const uint32_t b)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumDiv
	@abstract   Divides a BigNum (a) by another Bignum (b).
    
	@param		quotient  A bigNum in which to place the quotient (a div b).
	@param		remainder  A bigNum in which to place the remainder (a mod b).
    @param		a		The BigNum to divide.
    @param		b		The BigNum used to divide a.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumDiv(CCBigNumRef quotient, CCBigNumRef remainder, const CCBigNumRef a, const CCBigNumRef b)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumDiv2
	@abstract   Divides a BigNum (a) by 2.
    
	@param		result  A bigNum in which to place the result.
    @param		a		The BigNum to divide.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumDiv2(CCBigNumRef result, const CCBigNumRef a)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumMod
	@abstract   Find the remainder of a BigNum for a given modulus.
    
	@param		result  A bigNum in which to place the result.
    @param		dividend	The BigNum to divide.
    @param		modulus		The BigNum used to divide a and produce the mod value.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumMod(CCBigNumRef result, CCBigNumRef dividend, CCBigNumRef modulus)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumModI
	@abstract   Find the remainder of a BigNum for a given modulus (unsigned integer version).
    
	@param		result      A pointer to an unsigned integer in which to place the result.
    @param		dividend	The BigNum to divide.
    @param		modulus		The BigNum used to divide a and produce the mod value.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumModI(uint32_t *result, CCBigNumRef dividend, uint32_t modulus)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumSquare
	@abstract   Find the square of a BigNum.
    
	@param		result  A bigNum in which to place the result.
    @param		a	The BigNum to square.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumSquare(CCBigNumRef result, const CCBigNumRef a)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumGCD
	@abstract   Find the Greatest Common Denominator of two BigNums.
    
	@param		result  A bigNum in which to place the result.
    @param		a	A BigNum.
    @param		b	A BigNum.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumGCD(CCBigNumRef result, const CCBigNumRef a, const CCBigNumRef b)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumLCM
	@abstract   Find the Least Common Multiple of two BigNums.
    
	@param		result  A bigNum in which to place the result.
    @param		a	A BigNum.
    @param		b	A BigNum.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumLCM(CCBigNumRef result, const CCBigNumRef a, const CCBigNumRef b)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumMulMod
	@abstract   Perform Modular Multiplication.
    
	@param		result  A bigNum in which to place the result.
    @param		a	A BigNum.
    @param		b	A BigNum.
    @param		modulus	The Modulus.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumMulMod(CCBigNumRef result, const CCBigNumRef a, const CCBigNumRef b, const CCBigNumRef modulus)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumSquareMod
	@abstract   Perform Modular Squaring.
    
	@param		result  A bigNum in which to place the result.
    @param		a	A BigNum.
    @param		modulus	The Modulus.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumSquareMod(CCBigNumRef result, const CCBigNumRef a, const CCBigNumRef modulus)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumInverseMod
	@abstract   Perform Modular Inversion.
    
	@param		result  A bigNum in which to place the result.
    @param		a		A BigNum.
    @param		modulus	The Modulus.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumInverseMod(CCBigNumRef result, const CCBigNumRef a, const CCBigNumRef modulus)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumModExp
	@abstract   Perform Modular Exponentiation.
    
	@param		result  A bigNum in which to place the result.
    @param		a		The base integer.
    @param		power	The power integer.
    @param		modulus	The Modulus.

	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumModExp(CCBigNumRef result, const CCBigNumRef a, const CCBigNumRef power, const CCBigNumRef modulus)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumLeftShift
	@abstract   Shift a BigNum left
  
	@param		result  A bigNum in which to place the result.
	@param      a		The BigNum. 
	@param      digits	How many bit places to shift left.
     
	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumLeftShift(CCBigNumRef result, const CCBigNumRef a, const uint32_t digits)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumRightShift
	@abstract   Shift a BigNum right
  
	@param		result  A bigNum in which to place the result.
	@param      a		The BigNum. 
	@param      digits	How many bit places to shift right.
     
	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumRightShift(CCBigNumRef result, const CCBigNumRef a, const uint32_t digits)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumMontgomerySetup
	@abstract   Setup Montgomery
  
	@param      num	The modulus. 
	@param      rho	The destination for the reduction digit.
     
	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumMontgomerySetup(CCBigNumRef num, uint32_t *rho)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumMontgomeryNormalization
	@abstract   Get the normalization value.
  
	@param		result  A bigNum in which to place the result.
	@param      modulus	The modulus. 
    
	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumMontgomeryNormalization(CCBigNumRef result, CCBigNumRef modulus)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumMontgomeryReduce
	@abstract   Reduce a number
  
	@param      x 	The BigNum to reduce - the result will be stored back into
    				this BigNum.
	@param      modulus	The modulus. 
	@param      rho		The reduction digit.
    
	@result		returns a CCStatus (See CommonCryptor.h for values).
 */

CCStatus
CCBigNumMontgomeryReduce(CCBigNumRef x, CCBigNumRef modulus, uint32_t rho)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);



/*!
	@function   CCBigNumCreateRandom
	@abstract   Creates a BigNum with a random value.
    ZZZZZ
  
	@param      status  A pointer to a CCStatus for return codes. 
	@result		On success this returns a newly
    			allocated BigNum (must be freed with 
                CCBigNumFree).
                Returns NULL on failure.
 */

CCBigNumRef
CCBigNumCreateRandom(CCStatus *status, int bits, int top, int bottom)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*!
	@function   CCBigNumIsPrime
	@abstract   Determines if a BigNum is prime.
  
	@param      status  A pointer to a CCStatus for return codes. 
	@param      bn - a BigNum. 
	@result		Returns true or false.
 */

bool
CCBigNumIsPrime(CCStatus *status, const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*!
	@function   CCBigNumIsOdd
	@abstract   Determines if a BigNum is odd.
  
	@param      status  A pointer to a CCStatus for return codes. 
	@param      bn - a BigNum. 
	@result		Returns true or false.
 */

bool
CCBigNumIsOdd(CCStatus *status, const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*!
	@function   CCBigNumIsZero
	@abstract   Determines if a BigNum is zero.
  
	@param      status  A pointer to a CCStatus for return codes. 
	@param      bn - a BigNum. 
	@result		Returns true or false.
 */

bool
CCBigNumIsZero(CCStatus *status, const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*!
	@function   CCBigNumIsNegative
	@abstract   Determines if a BigNum is negative.
  
	@param      status  A pointer to a CCStatus for return codes. 
	@param      bn - a BigNum. 
	@result		Returns true or false.
 */

bool
CCBigNumIsNegative(CCStatus *status, const CCBigNumRef bn)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

#ifdef __cplusplus
}
#endif

#endif  /* _CC_BIGNUM_H_ */

Changes to Source/CommonCryptoSPI/CommonCMACSPI.h.

45
46
47
48
49
50
51
52
53
54
55
56
57
58
@param      macOut      The digest bytes (space provided by the caller). 
    
Output is written to caller-supplied buffer.
*/
    
void
    CCAESCmac(const void *key, const uint8_t *data, size_t dataLength, void *macOut)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

#ifdef __cplusplus
}
#endif

#endif /* _CC_CMACSPI_H_ */







|






45
46
47
48
49
50
51
52
53
54
55
56
57
58
@param      macOut      The digest bytes (space provided by the caller). 
    
Output is written to caller-supplied buffer.
*/
    
void
    CCAESCmac(const void *key, const uint8_t *data, size_t dataLength, void *macOut)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_6_0);

#ifdef __cplusplus
}
#endif

#endif /* _CC_CMACSPI_H_ */

Changes to Source/CommonCryptoSPI/CommonCryptoPriv.h.

1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2004 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at

|







1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2006-2012 Apple, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
21
22
23
24
25
26
27
28
29
30
31









32

33
34
35


36
37
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 * CommonCryptoPriv.h - private typedefs and defines for ComonCrypto 
 */
 
#ifndef	_COMMON_CRYPTO_PRIV_H_
#define _COMMON_CRYPTO_PRIV_H_

/*









 * All CommomCrypto-specific mods to the various open source implementations

 * in this package are flagged with this symbol.
 */
#define _APPLE_COMMON_CRYPTO_



#endif	/* _COMMON_CRYPTO_PRIV_H_ */







|
|

|
>
>
>
>
>
>
>
>
>
|
>
|
|
<
>
>

|
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

45
46
47
48
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 * CommonCryptoPriv.h - private typedefs and defines for ComonCrypto 
 */
 
#ifndef	__COMMONCRYPTO_PRIVATE__
#define __COMMONCRYPTO_PRIVATE__

#include <CommonCrypto/CommonCryptorSPI.h>
#include <CommonCrypto/CommonDigestSPI.h>
#include <CommonCrypto/CommonECCryptor.h>
#include <CommonCrypto/CommonRSACryptor.h>
#include <CommonCrypto/CommonBigNum.h>
#include <CommonCrypto/CommonDH.h>
#include <CommonCrypto/CommonHMacSPI.h>
#include <CommonCrypto/CommonCMACSPI.h>
#include <CommonCrypto/CommonRandomSPI.h>
#include <CommonCrypto/CommonSelfTest.h>

// The following headers will be jettisoned once all internal projects
// are weaned from them.


#include <CommonCrypto/aes.h>
#include <CommonCrypto/lionCompat.h>

#endif	/* __COMMONCRYPTO_PRIVATE__ */

Changes to Source/CommonCryptoSPI/CommonCryptorSPI.h.

25
26
27
28
29
30
31



32
33

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48




49
50

51
52

53
54
55
56
57
58
59
60
61
62
63
64
65



66



67
68
69
70
71

72
73
74
75
76

77
78
79
80
81

82
83
84

85
86
87
88
89
90
91
#define _CC_CryptorSPI_H_

#include <sys/types.h>
#include <sys/param.h>
#include <stdint.h>

#include <string.h>



#include <limits.h>
#include <stdlib.h>

#include <Availability.h>

#ifdef __cplusplus
extern "C" {
#endif

/*
	This is an SPI header.  It includes some work in progress implementation notes that
	will be removed when this is promoted to an API set.
*/

/*
	Cipher Modes
*/





enum {
	kCCModeECB		= 1,

	kCCModeCBC		= 2,
	kCCModeCFB		= 3,

	kCCModeCTR		= 4,
	kCCModeF8		= 5, // Unimplemented for now (not included)
	kCCModeLRW		= 6, // Unimplemented for now (not included)
	kCCModeOFB		= 7,
	kCCModeXTS		= 8,
	kCCModeRC4		= 9, // RC4 as a streaming cipher is handled internally as a mode.
	kCCModeCFB8		= 10,
};
typedef uint32_t CCMode;

/*
	Padding for block ciphers
*/







enum {
	ccDefaultPadding	= 0,
	ccPKCS7Padding		= 1,
	ccANSIx923Padding	= 2, // Unimplemented for now (not included)
	ccISO10126Padding	= 3, // Unimplemented for now (not included)

};
typedef uint32_t CCPadding;

/*
	Mode options - so far only used for CTR mode

*/

enum {
	kCCModeOptionCTR_LE	= 0x0001, // CTR Mode Little Endian
	kCCModeOptionCTR_BE = 0x0002  // CTR Mode Big Endian

};

typedef uint32_t CCModeOptions;


/*
	Supports a mode call of 
	int mode_setup(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
		const unsigned char *tweak, int tweaklen, int num_rounds, int options, mode_context *ctx);
*/








>
>
>


>












|
|

>
>
>
>

|
>
|
|
>
|
<
<
|
<
<
<

<


|
|
>
>
>

>
>
>

|
|
<
<
>

<


<
>
|
<

<
<
>


|
>







25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63


64



65

66
67
68
69
70
71
72
73
74
75
76
77
78
79


80
81

82
83

84
85

86


87
88
89
90
91
92
93
94
95
96
97
98
#define _CC_CryptorSPI_H_

#include <sys/types.h>
#include <sys/param.h>
#include <stdint.h>

#include <string.h>
#ifdef KERNEL
#include <machine/limits.h>
#else
#include <limits.h>
#include <stdlib.h>
#endif /* KERNEL */
#include <Availability.h>

#ifdef __cplusplus
extern "C" {
#endif

/*
	This is an SPI header.  It includes some work in progress implementation notes that
	will be removed when this is promoted to an API set.
*/

/*
 	Private Ciphers
 */

/* Lion SPI name for no padding.  Defining for compatibility.  Is now
   ccNoPadding in CommonCryptor.h
 */
    
enum {
    ccDefaultPadding			= 0,
};


enum {
	kCCAlgorithmAES128NoHardware = 20,


	kCCAlgorithmAES128WithHardware = 21



};


/*
 	Private Modes
 */
enum {
	kCCModeGCM		= 11,
};

/*
 	Private Paddings
 */
enum {
    ccCBCCTS1			= 10,
    ccCBCCTS2			= 11,


    ccCBCCTS3			= 12,
};


/*

    Private Cryptor direction (op)
 */

enum {


    kCCBoth		= 3,
};




/*
	Supports a mode call of 
	int mode_setup(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
		const unsigned char *tweak, int tweaklen, int num_rounds, int options, mode_context *ctx);
*/

103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
































































































































191
192
193
194
195
196
	size_t 			tweakLength,	
	int				numRounds,
	CCModeOptions 	options,
	const void		*data,			/* caller-supplied memory */
	size_t			dataLength,		/* length of data in bytes */
	CCCryptorRef	*cryptorRef,	/* RETURNED */
	size_t			*dataUsed)		/* optional, RETURNED */
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/* This version mallocs the CCCryptorRef */

CCCryptorStatus CCCryptorCreateWithMode(
	CCOperation 	op,				/* kCCEncrypt, kCCEncrypt, kCCBoth (default for BlockMode) */
	CCMode			mode,
	CCAlgorithm		alg,
	CCPadding		padding,		
	const void 		*iv,			/* optional initialization vector */
	const void 		*key,			/* raw key material */
	size_t 			keyLength,	
	const void 		*tweak,			/* raw tweak material */
	size_t 			tweakLength,	
	int				numRounds,		/* 0 == default */
	CCModeOptions 	options,
	CCCryptorRef	*cryptorRef)	/* RETURNED */
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*
	Assuming we can use existing CCCryptorCreateFromData for all modes serviced by these:
	int mode_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, mode_context *ctx);
	int mode_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, mode_context *ctx);
*/

/*
	Block mode encrypt and decrypt interfaces for IV tweaked blocks (XTS and CBC)
	
	int mode_encrypt_tweaked(const unsigned char *pt, unsigned long len, unsigned char *ct, const unsigned char *tweak, mode_context *ctx);
	int mode_decrypt_tweaked(const unsigned char *ct, unsigned long len, unsigned char *pt, const unsigned char *tweak, mode_context *ctx);
*/

CCCryptorStatus CCCryptorEncryptDataBlock(
	CCCryptorRef cryptorRef,
	const void *iv,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);


CCCryptorStatus CCCryptorDecryptDataBlock(
	CCCryptorRef cryptorRef,
	const void *iv,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*
	Assuming we can use the existing CCCryptorRelease() interface for 
	int mode_done(mode_context *ctx);
*/

/*
	Not surfacing these other than with CCCryptorReset()
	
	int mode_setiv(const unsigned char *IV, unsigned long len, mode_context *ctx);
	int mode_getiv(const unsigned char *IV, unsigned long *len, mode_context *ctx);
*/
    
/*
    DES key utilities
*/
    
CCCryptorStatus CCDesIsWeakKey(
                               void *key,
                               size_t Length)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

void CCDesSetOddParity(
                       void *key,
                       size_t Length)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

uint32_t CCDesCBCCksum(void *input, void *output,
                       size_t length, void *key, size_t keylen,
                       void *ivec)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
    
    

































































































































#ifdef __cplusplus
}
#endif

#endif /* _CC_CryptorSPI_H_ */







|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















|








|




















|




|




|

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






110
111
112
113
114
115
116
117
118
















119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
	size_t 			tweakLength,	
	int				numRounds,
	CCModeOptions 	options,
	const void		*data,			/* caller-supplied memory */
	size_t			dataLength,		/* length of data in bytes */
	CCCryptorRef	*cryptorRef,	/* RETURNED */
	size_t			*dataUsed)		/* optional, RETURNED */
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


















/*
	Assuming we can use existing CCCryptorCreateFromData for all modes serviced by these:
	int mode_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, mode_context *ctx);
	int mode_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, mode_context *ctx);
*/

/*
	Block mode encrypt and decrypt interfaces for IV tweaked blocks (XTS and CBC)
	
	int mode_encrypt_tweaked(const unsigned char *pt, unsigned long len, unsigned char *ct, const unsigned char *tweak, mode_context *ctx);
	int mode_decrypt_tweaked(const unsigned char *ct, unsigned long len, unsigned char *pt, const unsigned char *tweak, mode_context *ctx);
*/

CCCryptorStatus CCCryptorEncryptDataBlock(
	CCCryptorRef cryptorRef,
	const void *iv,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


CCCryptorStatus CCCryptorDecryptDataBlock(
	CCCryptorRef cryptorRef,
	const void *iv,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*
	Assuming we can use the existing CCCryptorRelease() interface for 
	int mode_done(mode_context *ctx);
*/

/*
	Not surfacing these other than with CCCryptorReset()
	
	int mode_setiv(const unsigned char *IV, unsigned long len, mode_context *ctx);
	int mode_getiv(const unsigned char *IV, unsigned long *len, mode_context *ctx);
*/
    
/*
    DES key utilities
*/
    
CCCryptorStatus CCDesIsWeakKey(
                               void *key,
                               size_t Length)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

void CCDesSetOddParity(
                       void *key,
                       size_t Length)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

uint32_t CCDesCBCCksum(void *input, void *output,
                       size_t length, void *key, size_t keylen,
                       void *ivec)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    

/*
 * returns a cipher blocksize length iv in the provided iv buffer.
 */
    
CCCryptorStatus
CCCryptorGetIV(CCCryptorRef cryptorRef, void *iv)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*
    GCM Support Interfaces

	Use CCCryptorCreateWithMode() with the kCCModeGCM selector to initialize 
    a CryptoRef.  Only kCCAlgorithmAES128 can be used with GCM and these
    functions.  IV Setting etc will be ignored from CCCryptorCreateWithMode().
    Use the CCCryptorGCMAddIV() routine below for IV setup.
*/

/*
	This adds the initial vector octets from iv of length ivLen to the GCM
	CCCryptorRef. You can call this function as many times as required to
	process the entire IV.
*/
    
CCCryptorStatus
CCCryptorGCMAddIV(CCCryptorRef cryptorRef,
                	const void 		*iv,
                    size_t ivLen)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*
	Additional Authentication Data
	After the entire IV has been processed, the additional authentication 
    data can be processed. Unlike the IV, a packet/session does not require 
    additional authentication data (AAD) for security. The AAD is meant to 
    be used as side–channel data you want to be authenticated with the packet. 
    Note: once you begin adding AAD to the GCM CCCryptorRef you cannot return 
    to adding IV data until the state has been reset.
*/

CCCryptorStatus
CCCryptorGCMAddAAD(CCCryptorRef cryptorRef,
                   const void 		*aData,
                   size_t aDataLen)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0);

// Maintain the old symbol with incorrect camel-case for now.
CCCryptorStatus
CCCryptorGCMaddAAD(CCCryptorRef cryptorRef,
                	const void 		*aData,
                    size_t aDataLen)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0);

// This is for old iOS5 clients
CCCryptorStatus
CCCryptorGCMAddADD(CCCryptorRef cryptorRef,
                   const void 		*aData,
                   size_t aDataLen)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


CCCryptorStatus CCCryptorGCMEncrypt(
	CCCryptorRef cryptorRef,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


CCCryptorStatus CCCryptorGCMDecrypt(
	CCCryptorRef cryptorRef,
	const void *dataIn,
	size_t dataInLength,
	void *dataOut)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*
	This terminates the GCM state gcm and stores the tag in tag of length
    taglen octets.
*/

CCCryptorStatus CCCryptorGCMFinal(
	CCCryptorRef cryptorRef,
	const void *tag,
	size_t *tagLength)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*
	This will reset the GCM CCCryptorRef to the state that CCCryptorCreateWithMode() 
    left it. The user would then call CCCryptorGCMAddIV(), CCCryptorGCMaddAAD(), etc.
*/

CCCryptorStatus CCCryptorGCMReset(
	CCCryptorRef cryptorRef)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*
	This will initialize the GCM state with the given key, IV and AAD value 
    then proceed to encrypt or decrypt the message text and store the final 
    message tag. The definition of the variables is the same as it is for all 
    the manual functions. If you are processing many packets under the same 
    key you shouldn’t use this function as it invokes the pre–computation 
    with each call.
*/

CCCryptorStatus CCCryptorGCM(
	CCOperation 	op,				/* kCCEncrypt, kCCDecrypt */
	CCAlgorithm		alg,
	const void 		*key,			/* raw key material */
	size_t 			keyLength,	
	const void 		*iv,
	size_t 			ivLen,
	const void 		*aData,
	size_t 			aDataLen,
	const void 		*dataIn,
	size_t 			dataInLength,
  	void 			*dataOut,
	const void 		*tag,
	size_t 			*tagLength)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);
    

void CC_RC4_set_key(void *ctx, int len, const unsigned char *data)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

void CC_RC4(void *ctx, unsigned long len, const unsigned char *indata,
                unsigned char *outdata)
__OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);


#ifdef __cplusplus
}
#endif

#endif /* _CC_CryptorSPI_H_ */

Added Source/CommonCryptoSPI/CommonDH.h.





































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef _CC_DH_H_
#define _CC_DH_H_

#include <Availability.h>

#include <stddef.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct CCDHRef_s *CCDHRef;

typedef struct CCDHParameters_s *CCDHParameters;

extern CCDHParameters kCCDHRFC2409Group2
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);
extern CCDHParameters kCCDHRFC3526Group5
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*!
    @function   CCDHCreate
    @abstract   Creates a Diffie-Hellman context. 
    
	@param      dhParameter  The Diffie-Hellman Group to use (provides p and g).
                             The only appropriate values are kCCDHGenerator2 or
                             kCCDHGenerator5, defined above.
                            
    @result     If unable to allocate memory this returns NULL.
*/

CCDHRef
CCDHCreate(CCDHParameters dhParameter)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*!
    @function   CCDHRelease
    @abstract   Releases a Diffie-Hellman context. 
    
	@param      ref  The Diffie-Hellman context to clear and deallocate.
                            
*/

void
CCDHRelease(CCDHRef ref)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*!
    @function   CCDHGenerateKey
    @abstract   Generate the public key for use in a Diffie-Hellman handshake. 
                This value is returned as a byte string.
    
	@param      ref  The Diffie-Hellman context.
    @result		returns -1 on failure.
                            
*/


int
CCDHGenerateKey(CCDHRef ref, void *output, size_t *outputLength)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

/*!
    @function   CCDHComputeKey
    @abstract   Compute the shared Diffie-Hellman key using the peer's public
                key.
    
	@param      sharedKey  Shared key computed from the peer public key, p, g,
                            and the private key.
	@param      peerPubKey  Public key received from the peer.
    @param		peerPubKeyLen Length of peer public key.
	@param      ref  The Diffie-Hellman context to clear and deallocate.

	@param      returns the length of the shared key.
                            
*/

int
CCDHComputeKey(unsigned char *sharedKey, size_t *sharedKeyLen, const void *peerPubKey, size_t peerPubKeyLen, CCDHRef ref)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


CCDHParameters
CCDHParametersCreateFromData(const void *p, size_t pLen, const void *g, size_t gLen, size_t l)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

CCDHParameters
CCDHParametersCreateFromPKCS3(const void *data, size_t len)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

size_t
CCDHParametersPKCS3EncodeLength(CCDHParameters parms)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

size_t
CCDHParametersPKCS3Encode(CCDHParameters parms, void *data, size_t dataAvailable)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

void
CCDHParametersRelease(CCDHParameters parameters)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

#ifdef __cplusplus
}
#endif

#endif  /* _CC_DH_H_ */

Changes to Source/CommonCryptoSPI/CommonDigestSPI.h.

20
21
22
23
24
25
26



27

28
29
30
31
32
33
34
35
36

37
38
39
40
41
42
43
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef	_CC_DigestSPI_H_
#define _CC_DigestSPI_H_




#include <Availability.h>

#ifdef __cplusplus
extern "C" {
#endif
    

/*!
    @enum       CCDigestAlg
    @abstract   Algorithms implemented in this module.


    @constant 	kCCDigestMD2		MD2 digest
    @constant 	kCCDigestMD4		MD4 digest
    @constant 	kCCDigestMD5		MD5 digest
    @constant 	kCCDigestRMD128		RMD 128 bit digest
    @constant 	kCCDigestRMD160		RMD 160 bit digest
    @constant 	kCCDigestRMD256		RMD 256 bit digest
    @constant 	kCCDigestRMD320		RMD 320 bit digest







>
>
>

>






|


>







20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef	_CC_DigestSPI_H_
#define _CC_DigestSPI_H_

#include <stdint.h>
#include <sys/types.h>

#include <Availability.h>

#ifdef __cplusplus
extern "C" {
#endif
    

/*!
    @enum       CCDigestAlgorithm
    @abstract   Algorithms implemented in this module.

    @constant 	kCCDigestNone		Digest Selector for "no digest"
    @constant 	kCCDigestMD2		MD2 digest
    @constant 	kCCDigestMD4		MD4 digest
    @constant 	kCCDigestMD5		MD5 digest
    @constant 	kCCDigestRMD128		RMD 128 bit digest
    @constant 	kCCDigestRMD160		RMD 160 bit digest
    @constant 	kCCDigestRMD256		RMD 256 bit digest
    @constant 	kCCDigestRMD320		RMD 320 bit digest
51
52
53
54
55
56
57

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77




78
79
80
81
82
83
84
85
86
87
88
















89
90
91
92
93
94
95
    @constant 	kCCDigestSkein224	Skein 224 bit digest
    @constant 	kCCDigestSkein256	Skein 256 bit digest
    @constant 	kCCDigestSkein384	Skein 384 bit digest
    @constant 	kCCDigestSkein512	Skein 512 bit digest
 */

enum {

	kCCDigestMD2				= 1,
	kCCDigestMD4				= 2,
	kCCDigestMD5				= 3,
	kCCDigestRMD128				= 4,
	kCCDigestRMD160				= 5,
	kCCDigestRMD256				= 6,
	kCCDigestRMD320				= 7,
	kCCDigestSHA1				= 8,
	kCCDigestSHA224				= 9,
	kCCDigestSHA256				= 10,
	kCCDigestSHA384				= 11,
	kCCDigestSHA512				= 12,
	kCCDigestSkein128			= 13,
	kCCDigestSkein160			= 14,
	kCCDigestSkein224			= 16,
	kCCDigestSkein256			= 17,
	kCCDigestSkein384			= 18,
	kCCDigestSkein512			= 19,
};
typedef uint32_t CCDigestAlg;





/*!
    @typedef    CCDigestCtx
    @abstract   Digest context. 
 */

#define CC_DIGEST_SIZE 1032 
typedef struct CCDigestCtx_t {
    uint8_t context[CC_DIGEST_SIZE];
} CCDigestCtx, *CCDigestRef;

















/**************************************************************************/
/* SPI Only                                                               */
/**************************************************************************/

/*
 * This information will remain SPI - internal functions available
 * to callers not needing a stable ABI that have a need to provide







>



















|
>
>
>
>











>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
    @constant 	kCCDigestSkein224	Skein 224 bit digest
    @constant 	kCCDigestSkein256	Skein 256 bit digest
    @constant 	kCCDigestSkein384	Skein 384 bit digest
    @constant 	kCCDigestSkein512	Skein 512 bit digest
 */

enum {
    kCCDigestNone               = 0,
	kCCDigestMD2				= 1,
	kCCDigestMD4				= 2,
	kCCDigestMD5				= 3,
	kCCDigestRMD128				= 4,
	kCCDigestRMD160				= 5,
	kCCDigestRMD256				= 6,
	kCCDigestRMD320				= 7,
	kCCDigestSHA1				= 8,
	kCCDigestSHA224				= 9,
	kCCDigestSHA256				= 10,
	kCCDigestSHA384				= 11,
	kCCDigestSHA512				= 12,
	kCCDigestSkein128			= 13,
	kCCDigestSkein160			= 14,
	kCCDigestSkein224			= 16,
	kCCDigestSkein256			= 17,
	kCCDigestSkein384			= 18,
	kCCDigestSkein512			= 19,
};
typedef uint32_t CCDigestAlgorithm;

// Hold this until Heimdal has changed.

#define CCDigestAlg CCDigestAlgorithm

/*!
    @typedef    CCDigestCtx
    @abstract   Digest context. 
 */

#define CC_DIGEST_SIZE 1032 
typedef struct CCDigestCtx_t {
    uint8_t context[CC_DIGEST_SIZE];
} CCDigestCtx, *CCDigestRef;

#define CC_RMD128_DIGEST_LENGTH   16          /* digest length in bytes */
#define CC_RMD128_BLOCK_BYTES     64          /* block size in bytes */
#define CC_RMD128_BLOCK_LONG      (CC_RMD128_BLOCK_BYTES / sizeof(CC_LONG))
    
#define CC_RMD160_DIGEST_LENGTH   20          /* digest length in bytes */
#define CC_RMD160_BLOCK_BYTES     64          /* block size in bytes */
#define CC_RMD160_BLOCK_LONG      (CC_RMD160_BLOCK_BYTES / sizeof(CC_LONG))
    
#define CC_RMD256_DIGEST_LENGTH   32          /* digest length in bytes */
#define CC_RMD256_BLOCK_BYTES     64          /* block size in bytes */
#define CC_RMD256_BLOCK_LONG      (CC_RMD256_BLOCK_BYTES / sizeof(CC_LONG))
    
#define CC_RMD320_DIGEST_LENGTH   40          /* digest length in bytes */
#define CC_RMD320_BLOCK_BYTES     64          /* block size in bytes */
#define CC_RMD320_BLOCK_LONG      (CC_RMD320_BLOCK_BYTES / sizeof(CC_LONG))
    
/**************************************************************************/
/* SPI Only                                                               */
/**************************************************************************/

/*
 * This information will remain SPI - internal functions available
 * to callers not needing a stable ABI that have a need to provide
104
105
106
107
108
109
110
111
112

113
114
115
116
117
118
119
    @param      algorithm   Digest algorithm to perform. 
    @param      ctx         A digest context.
    
    returns 0 on success.
 */

int 
CCDigestInit(CCDigestAlg algorithm, CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);



/**************************************************************************/
/* Future API                                                             */
/**************************************************************************/

/*







|
|
>







130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    @param      algorithm   Digest algorithm to perform. 
    @param      ctx         A digest context.
    
    returns 0 on success.
 */

int 
CCDigestInit(CCDigestAlgorithm algorithm, CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);



/**************************************************************************/
/* Future API                                                             */
/**************************************************************************/

/*
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221




























222
223
224
225
226
227
228
229






230
231
232
233
234
235
236
237
238
239
240
241
242






243
244
















245
246
247
248
249
250
    @param      length      The length of the data to digest. 
    @param      output      The digest bytes (space provided by the caller). 
    
    Output is written to caller-supplied buffer, as in CCDigestFinal().
 */

int
CCDigest(CCDigestAlg algorithm, 
         const uint8_t *data, size_t length, uint8_t *output)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*!
    @function   CCDigestCreate
    @abstract   Allocate and initialize a CCDigestCtx for a digest.
    
    @param      algorithm   Digest algorithm to setup. 
    
    returns 0 on success.
 */

CCDigestRef
CCDigestCreate(CCDigestAlg alg)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*!
    @function   CCDigestUpdate
    @abstract   Continue to digest data.
    
    @param      ctx         A digest context.
    @param      data        The data to digest. 
    @param      length      The length of the data to digest. 
    
    returns 0 on success.
 */
 
int
CCDigestUpdate(CCDigestRef ctx, const void *data, size_t length)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*!
    @function   CCDigestFinal
    @abstract   Conclude digest operations and produce the digest output.
    
    @param      ctx         A digest context.
    @param      output      The digest bytes (space provided by the caller). 
    
    returns 0 on success.
 */

int
CCDigestFinal(CCDigestRef ctx, uint8_t *output)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
/*!
    @function   CCDigestDestroy
    @abstract   Clear and free a CCDigestCtx
    
    @param      ctx         A digest context.
 */


void
CCDigestDestroy(CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*!
    @function   CCDigestReset
    @abstract   Clear and re-initialize a CCDigestCtx for the same algorithm.
    
    @param      ctx         A digest context.
 */
 
void
CCDigestReset(CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*!
    @function   CCDigestInterrimResult
    @abstract   Produce the digest output result for the bytes currently
                processed.
    
    @param      ctx         A digest context.
    @param      output      The digest bytes (space provided by the caller). 
    
    returns 0 on success.
 */

int
CCDigestInterrimResult(CCDigestRef ctx, uint8_t *output)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*!
 @function   CCDigestBlockSize




























 @abstract   Provides the block size of the digest algorithm
 
 @param      ctx         A digest context.
 
 returns 0 on failure or the block size on success.
 */
    
size_t






CCDigestBlockSize(CCDigestRef ctx) 
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
    
/*!
 @function   CCDigestOutputSize
 @abstract   Provides the digest output size of the digest algorithm
 
 @param      ctx         A digest context.
 
 returns 0 on failure or the digest output size on success.
 */

size_t






CCDigestOutputSize(CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
















    
#ifdef __cplusplus
}
#endif

#endif /* _CC_DigestSPI_H_ */







|

|







|



|
|














|













|










|










|


|










|
|


|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>








>
>
>
>
>
>


|

|








>
>
>
>
>
>

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
    @param      length      The length of the data to digest. 
    @param      output      The digest bytes (space provided by the caller). 
    
    Output is written to caller-supplied buffer, as in CCDigestFinal().
 */

int
CCDigest(CCDigestAlgorithm algorithm, 
         const uint8_t *data, size_t length, uint8_t *output)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
    @function   CCDigestCreate
    @abstract   Allocate and initialize a CCDigestCtx for a digest.
    
    @param      algorithm   Digest algorithm to setup. 
    
    returns a pointer to a digestRef on success.
 */

CCDigestRef
CCDigestCreate(CCDigestAlgorithm alg)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
    @function   CCDigestUpdate
    @abstract   Continue to digest data.
    
    @param      ctx         A digest context.
    @param      data        The data to digest. 
    @param      length      The length of the data to digest. 
    
    returns 0 on success.
 */
 
int
CCDigestUpdate(CCDigestRef ctx, const void *data, size_t length)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
    @function   CCDigestFinal
    @abstract   Conclude digest operations and produce the digest output.
    
    @param      ctx         A digest context.
    @param      output      The digest bytes (space provided by the caller). 
    
    returns 0 on success.
 */

int
CCDigestFinal(CCDigestRef ctx, uint8_t *output)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
/*!
    @function   CCDigestDestroy
    @abstract   Clear and free a CCDigestCtx
    
    @param      ctx         A digest context.
 */


void
CCDigestDestroy(CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
    @function   CCDigestReset
    @abstract   Clear and re-initialize a CCDigestCtx for the same algorithm.
    
    @param      ctx         A digest context.
 */
 
void
CCDigestReset(CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
    @function   CCDigestRefGetDigest
    @abstract   Produce the digest output result for the bytes currently
                processed.
    
    @param      ctx         A digest context.
    @param      output      The digest bytes (space provided by the caller). 
    
    returns 0 on success.
 */

int
CCDigestGetDigest(CCDigestRef ctx, uint8_t *output)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 @function   CCDigestGetBlockSize
 @abstract   Provides the block size of the digest algorithm
 
 @param      algorithm         A digest algorithm selector.
 
 returns 0 on failure or the block size on success.
 */
    
size_t
CCDigestGetBlockSize(CCDigestAlgorithm algorithm) 
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


    
/*!
 @function   CCDigestGetOutputSize
 @abstract   Provides the digest output size of the digest algorithm
 
 @param      algorithm         A digest algorithm selector.
 
 returns 0 on failure or the digest output size on success.
 */

size_t
CCDigestGetOutputSize(CCDigestAlgorithm algorithm)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 @function   CCDigestGetBlockSizeFromRef
 @abstract   Provides the block size of the digest algorithm
 
 @param      ctx         A digest context.
 
 returns 0 on failure or the block size on success.
 */
    
size_t
CCDigestGetBlockSizeFromRef(CCDigestRef ctx) 
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

// Until Heimdal Changes
// #define CCDigestBlockSize CCDigestGetBlockSizeFromRef
size_t
CCDigestBlockSize(CCDigestRef ctx) 
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

/*!
 @function   CCDigestGetOutputSizeFromRef
 @abstract   Provides the digest output size of the digest algorithm
 
 @param      ctx         A digest context.
 
 returns 0 on failure or the digest output size on success.
 */

size_t
CCDigestGetOutputSizeFromRef(CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

// Until Heimdal Changes
// #define CCDigestOutputSize CCDigestGetOutputSizeFromRef
size_t
CCDigestOutputSize(CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


   
uint8_t *
CCDigestOID(CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

size_t
CCDigestOIDLen(CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

CCDigestRef
CCDigestCreateByOID(uint8_t *OID, size_t OIDlen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    

    
#ifdef __cplusplus
}
#endif

#endif /* _CC_DigestSPI_H_ */

Added Source/CommonCryptoSPI/CommonECCryptor.h.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef _CC_ECCRYPTOR_H_
#define _CC_ECCRYPTOR_H_

#include <Availability.h>

#include <CommonCrypto/CommonCryptor.h>
#include <CommonCrypto/CommonDigestSPI.h>
#include "CommonRSACryptor.h"


#ifdef __cplusplus
extern "C" {
#endif

/*!
    @typedef    CCECCryptorRef
    @abstract   Opaque reference to a CCECCryptor object.
 */

typedef struct _CCECCryptor *CCECCryptorRef;


/*
 	EC Key Types
 */

enum {
    ccECKeyPublic		= 0,
    ccECKeyPrivate		= 1,
    ccECBlankPublicKey    = 97,
    ccECBlankPrivateKey   = 98,
    ccECBadKey          = 99,
};
typedef uint32_t CCECKeyType;

/*
 EC Key Import/Export Formats
 */

enum {
    kCCImportKeyBinary  = 0,
    kCCImportKeyDER		= 1,
};
typedef uint32_t CCECKeyExternalFormat;

/*!
	@discussion
    
    Key sizes for this set of interfaces must be between 128 and 384 bits. 
    The key size must also be evenly divisible by 8
*/

/*!
    @function   CCECCryptorGeneratePair
    @abstract   Generate an EC public and private key.  A curve will be chosen from
    			ECC-256 or ECC-384.
    
	@param      keysize     Must be between 192 and 521 (inclusive)
    
    @param      publicKey	A (required) pointer for the returned public CCECCryptorRef.
    
    @param      privateKey	A (required) pointer for the returned private CCECCryptorRef.
    
                            
    @result     Possible error returns are kCCParamError and kCCMemoryFailure.
*/

CCCryptorStatus 
CCECCryptorGeneratePair( size_t keysize, 
                         CCECCryptorRef *publicKey, 
                         CCECCryptorRef *privateKey)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
     @function   CCECCryptorGetPublicKeyFromPrivateKey
     @abstract   Grab the parts from a private key to make a public key.
     
     @param      privateKey		A pointer to a private CCECCryptorRef.
     
     
     @result     Possible error returns are kCCParamError and kCCMemoryFailure.
 */

CCECCryptorRef 
CCECCryptorGetPublicKeyFromPrivateKey(CCECCryptorRef privateKey)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
    @function   CCECCryptorImportPublicKey
    @abstract   Import an Elliptic Curve public key from data. This imports public
    			keys in ANSI X.9.63 format.
    
    @param      keyPackage		The data package containing the encoded key. 

	@param      keyPackageLen   The length of the encoded key package. 
	
    @param      key				A CCECCryptorRef of the decoded key. 

    @result     Possible error returns are kCCParamError and kCCMemoryFailure.
*/
    

CCCryptorStatus CCECCryptorImportPublicKey( void *keyPackage, 
											size_t keyPackageLen, 
                                            CCECCryptorRef *key)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    
/*!
     @function   CCECCryptorImportKey
     @abstract   Import an Elliptic Curve public key from data.
 
     @param      format		The format in which the key is encoded. 
 
     @param      keyPackage		The data package containing the encoded key. 
     
     @param      keyPackageLen   The length of the encoded key package. 
     
     @param      keyType		The type of key to be imported (public or private). 

     @param      key				A CCECCryptorRef of the decoded key. 
     
     @result     Possible error returns are kCCParamError and kCCMemoryFailure.
 */

CCCryptorStatus CCECCryptorImportKey(CCECKeyExternalFormat format, void *keyPackage, size_t keyPackageLen, CCECKeyType keyType, CCECCryptorRef *key)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
 	@function   CCECCryptorExportPublicKey
 	@abstract   Export an Elliptic Curve public key from data. This exports public
 				keys in ANSI X.9.63 format.
 
 	@param      key				The CCECCryptorRef of the key to encode. 

    @param      out             The destination for the encoded key. 
 
 	@param      outLen          A pointer to the length of the encoded key.
    							This is an in/out parameter.
 
 
 	@result     Possible error returns are kCCParamError and kCCMemoryFailure.
 */
 
CCCryptorStatus CCECCryptorExportPublicKey( CCECCryptorRef key, 
											void *out, 
                                            size_t *outLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    
    
// We'll remove the   CCECCryptorExportPublicKey later - we like this better.  
CCCryptorStatus CCECCryptorExportKey(CCECKeyExternalFormat format, void *keyPackage, size_t *keyPackageLen, CCECKeyType keyType, CCECCryptorRef key)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
 	@function   CCECGetKeyType
 	@abstract   Determine whether a CCECCryptorRef is public or private

 	@param      key				The CCECCryptorRef. 
 	@result     Return values are ccECKeyPublic, ccECKeyPrivate, or ccECBadKey

*/

CCECKeyType CCECGetKeyType(CCECCryptorRef key)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 	@function   CCECGetKeySize
 	@abstract   Return the key size

 	@param      key				The CCECCryptorRef. 
 	@result     Returns the keysize in bits or kCCParamError.

*/

int CCECGetKeySize(CCECCryptorRef key)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
     @function   CCECCryptorRelease
     @abstract   Clear and release a CCECCryptorRef.
     
     @param      key	The CCECCryptorRef of the key to release. 
*/


void CCECCryptorRelease(CCECCryptorRef key)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    
/*!
    @function   CCECCryptorSignHash

    @abstract   Compute a signature for a hash with an EC private key. 
    
    @param      privateKey		A pointer to a private CCECCryptorRef.

    @param      hashToSign		A pointer to the bytes of the value to be signed. 

 	@param      hashSignLen		Length of data to be signed. 
 		    
    @param      signedData      The signature bytes. 

	@param      signedDataLen   A pointer to the length of signature material.
    							This is an in/out parameter value.     
                                
    @result     Possible error returns are kCCParamError and kCCMemoryFailure.
*/


CCCryptorStatus 
CCECCryptorSignHash( CCECCryptorRef privateKey, 
                 const void *hashToSign, 
                 size_t hashSignLen,
				 void *signedData, 
                 size_t *signedDataLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
    @function   CCECCryptorVerifyHash

	@abstract   Verify a signature for data with an EC private key. 
    
    @param      publicKey		A pointer to a public CCECCryptorRef.
    
 	@param      hash			A pointer to the bytes of the hash of the data. 
 
	@param      hashLen			Length of hash. 
   
    @param      signedData		The bytes of the signature to be verified. 

	@param      signedDataLen	Length of data associated with the signature. 

	@param		valid			An indicator whether the signature was valid	
                                
    @result     Possible error returns are kCCParamError, kCCMemoryFailure 
				or kCCNotVerified.
*/

CCCryptorStatus 
CCECCryptorVerifyHash(  CCECCryptorRef publicKey,
      				const void *hash, 
                    size_t hashLen, 
      				const void *signedData, 
                    size_t signedDataLen, 
                    uint32_t *valid)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);



/*!
    @function   CCECCryptorWrapKey

	@abstract   Encrypt data (wrap a symmetric key) with an EC public key. 
    
    @param      publicKey		A pointer to a public CCECCryptorRef.

    @param      plainText		A pointer to the data to be encrypted.

	@param      plainTextLen	Length of data to be encrypted. 
	
    @param      cipherText		The encrypted byte result. 

	@param      cipherTextLen	Length of encrypted bytes.     
   
 	@param      digestType		The digest algorithm to use (See CommonDigestSPI.h). 
    
    @result     Possible error returns are kCCParamError.
*/

CCCryptorStatus 
CCECCryptorWrapKey(CCECCryptorRef publicKey, 
                   const void *plainText, 
                   size_t plainTextLen, 
                   void *cipherText, 
                   size_t *cipherTextLen,
                   CCDigestAlg digestType)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
    @function   CCECCryptorUnwrapKey

	@abstract   Decrypt data (unwrap a symmetric key) with an EC private key. 
    
    @param      privateKey		A pointer to a private CCECCryptorRef.

	@param      cipherText		The encrypted bytes. 

	@param      cipherTextLen	Length of encrypted bytes.     

    @param      plainText		The decrypted data bytes.

	@param      plainTextLen	A pointer to the length of data decrypted.
    							This is an in/out parameter. 	
 	                                  
    @result     Possible error returns are kCCParamError.
*/

CCCryptorStatus 
CCECCryptorUnwrapKey(CCECCryptorRef privateKey, 
                     const void *cipherText, 
                     size_t cipherTextLen,
                     void *plainText, 
                     size_t *plainTextLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    

/*!
    @function   CCECCryptorComputeSharedSecret

	@abstract   Construct a Diffie-Hellman shared secret with a private and 
    			public ECC key. 

    @param      privateKey		A pointer to a private CCECCryptorRef.

 	@param      publicKey		A pointer to a public CCECCryptorRef (usually
    							obtained from the other party in the session.)
	
	@param      out          The output data buffer. 

	@param      outLen       The output data buffer size.  This is an in-out
                            parameter.  When the function returns this is set
                            to the length of the result.

    @result     Possible error returns are kCCParamError, kCCDecodeError
                or kCCBufferTooSmall.

*/

CCCryptorStatus 
CCECCryptorComputeSharedSecret( CCECCryptorRef privateKey, 
								CCECCryptorRef publicKey, 
                                void *out, 
                                size_t *outLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    
/*======================================================================================*/
/* Only for FIPS Testing                                                                */
/*======================================================================================*/
    
/*!
 @function   CCECCryptorGetKeyComponents
 @abstract   Get EC Public Key Parameters for FIPS tests
 
 @param      ecKey              The EC Key to deconstruct
 @param      keySize            The EC Keysize.
 @param      qX, qXLength       The pointer and length(return) for the X Parameter.
 @param      qY, qYLength       The pointer and length(return) for the Y Parameter.
 @param      d, dLength         The pointer and length(return) for the D (Private Key Only)
                                Parameter.
 
 @result    If the function is successful (kCCSuccess) the X and Y parameters contain the
            discreet public key point coordinate values.  If the key passed in is a Private 
            Key the D parameter will contain the private key.
            All other errors result in kCCParamError.
 */

CCCryptorStatus
CCECCryptorGetKeyComponents(CCECCryptorRef ecKey, size_t *keySize,
                            uint8_t *qX, size_t *qXLength, 
                            uint8_t *qY, size_t *qYLength,
                            uint8_t *d, size_t *dLength)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
 @function   CCECCryptorCreateFromData
 @abstract   For FIPS CAVS testing we need the ability to create an EC 
             key from an X and Y parameter set.
 
 @param      keySize            The EC Keysize.
 @param      qX, qXLength       The pointer and length for the X Parameter.
 @param      qY, qYLength       The pointer and length for the Y Parameter.
 @param      ref                A pointer to the CCECCryptorRef to contain the result.
 @result    If the function is successful (kCCSuccess) a CCECCryptorRef is 
            returned in the ref parameter.  All other errors result in
            kCCParamError.
 */

CCCryptorStatus
CCECCryptorCreateFromData(size_t keySize,
                          uint8_t *qX, size_t qXLength, 
                          uint8_t *qY, size_t qYLength, 
                          CCECCryptorRef *ref)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 @function   CCECSignatureDecode
 @abstract   For FIPS CAVS testing we need the ability to get the binary S and R values
             from the DER signature blob.
 @param      SignedData, signedDataLen  The pointer and length of the DER formatted signature
 @param      r, rLength         The pointer and length for the R component (return value).
 @param      s, sLength         The pointer and length for the S component (return value).
 @result        If the function is successful (kCCSuccess) the r and s parameters have the
                individual values from the signature.
 */

CCCryptorStatus
CCECSignatureDecode(const void *signedData, size_t signedDataLen,
                    uint8_t *r, size_t *rLength,
                    uint8_t *s, size_t *sLength)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 @function   CCECSignatureEncode
 @abstract   For FIPS CAVS testing we need the ability to produce a DER formatted signature from
             discreet R and S components.
 @param      r, rLength         The pointer and length for the R component.
 @param      s, sLength         The pointer and length for the S component.
 @param      signedData, signedDataLen  The pointer and length of the DER formatted 
             signature ( return value)
 @result     If the function is successful (kCCSuccess) the signature is returned as a 
            DER-formatted blob. */
    
CCCryptorStatus
CCECSignatureEncode(uint8_t *r, size_t rLength,
                    uint8_t *s, size_t sLength,
                    void *signedData, size_t *signedDataLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

#ifdef __cplusplus
}
#endif

#endif  /* _CC_ECCRYPTOR_H_ */

Added Source/CommonCryptoSPI/CommonHMacSPI.h.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef	_CC_HmacSPI_H_
#define _CC_HmacSPI_H_

#include <CommonCrypto/CommonHMAC.h>
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonDigestSPI.h>

#include <stdint.h>
#include <sys/types.h>

#include <Availability.h>
#ifdef __cplusplus
extern "C" {
#endif

typedef struct CCHmacContext * CCHmacContextRef;

CCHmacContextRef
CCHmacCreate(CCDigestAlg alg, const void *key, size_t keyLength)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/* Update and Final are reused from existing api, type changed from struct CCHmacContext * to CCHmacContextRef though */            

void
CCHmacDestroy(CCHmacContextRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

size_t
CCHmacOutputSizeFromRef(CCHmacContextRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


size_t
CCHmacOutputSize(CCDigestAlg alg)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

    
#ifdef __cplusplus
}
#endif

#endif /* _CC_HmacSPI_H_ */

Added Source/CommonCryptoSPI/CommonRSACryptor.h.















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef _CC_RSACRYPTOR_H_
#define _CC_RSACRYPTOR_H_

#include <Availability.h>

#include <CommonCrypto/CommonCryptor.h>
#include <CommonCrypto/CommonDigestSPI.h>

#ifdef __cplusplus
extern "C" {
#endif

/*!
    @typedef    CCRSACryptorRef
    @abstract   Opaque reference to a CCRSACryptor object.
 */

typedef struct _CCRSACryptor *CCRSACryptorRef;


/*
 	RSA Key Types
 */

enum {
    ccRSAKeyPublic          = 0,
    ccRSAKeyPrivate         = 1,
    ccRSABlankPublicKey     = 97,
    ccRSABlankPrivateKey    = 98,
    ccRSABadKey             = 99,
};
typedef uint32_t CCRSAKeyType;

/*
	Padding for Asymmetric ciphers
*/

enum {
	ccPaddingNone		= 1000,
	ccPKCS1Padding		= 1001,
	ccOAEPPadding		= 1002,
	ccX931Padding		= 1003, // Work in Progress - don't use.
    ccPKCS1PaddingRaw   = 1004,
};
typedef uint32_t CCAsymetricPadding;

/*
	Additional CCCryptorStatus for signature verification failure.
 */

enum {
    kCCNotVerified    = -4306
};

/*!
	@discussion
    
    Key sizes for this set of interfaces must be between 1024 and 4096 bits. 
    The key size must also be evenly divisible by 32.
*/

/*!
    @function   CCRSACryptorGeneratePair
    @abstract   Generate an RSA public and private key. 
    
	@param      keysize     Example sizes for RSA keys are: 512, 768, 1024, 2048.

	@param      e           The "e" value (public key). Must be odd; 65537 or larger
    
    @param      publicKey	A (required) pointer for the returned public CCRSACryptorRef.
    
    @param      privateKey	A (required) pointer for the returned private CCRSACryptorRef.
    
                            
    @result     Possible error returns are kCCParamError and kCCMemoryFailure.
*/

CCCryptorStatus CCRSACryptorGeneratePair(
	size_t keysize, 
    uint32_t e,
	CCRSACryptorRef *publicKey, 
    CCRSACryptorRef *privateKey)
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    

/*!
    @function   CCRSACryptorGetPublicKeyFromPrivateKey
    @abstract   Create an RSA public key from a full private key. 
    
    @param      privateKey		A pointer to a private CCRSACryptorRef.
    @result     returns either a valid public key CCRSACryptorRef or NULL.
 */
    
CCRSACryptorRef CCRSACryptorGetPublicKeyFromPrivateKey(CCRSACryptorRef privkey)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
    @function   CCRSACryptorImport
    @abstract   Import an RSA key from data. This imports public or private
    			keys in PKCS#1 format.
    
    @param      keyPackage		The data package containing the encoded key. 

	@param      keyPackageLen   The length of the encoded key package. 
	
    @param      key				A CCRSACryptorRef of the decoded key. 

    @result     Possible error returns are kCCParamError and kCCMemoryFailure.
*/

CCCryptorStatus CCRSACryptorImport( const void *keyPackage, 
                                    size_t keyPackageLen, 
                                    CCRSACryptorRef *key)
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 	@function   CCRSACryptorExport
 	@abstract   Import an RSA key from data. This exports public or private
 				keys in PKCS#1 format.
 
 	@param      key				The CCRSACryptorRef of the key to encode. 

    @param      keyPackage		The data package in which to put the encoded key. 
 
 	@param      keyPackageLen   A pointer to the length of the encoded key 
    							package.  This is an in/out parameter.
 
 
 	@result     Possible error returns are kCCParamError and kCCMemoryFailure.
 */
 
CCCryptorStatus CCRSACryptorExport( CCRSACryptorRef key, 
									void *out, 
                                    size_t *outLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
 	@function   CCRSAGetKeyType
 	@abstract   Determine whether a CCRSACryptorRef is public or private

 	@param      key				The CCRSACryptorRef. 
 	@result     Return values are ccRSAKeyPublic, ccRSAKeyPrivate, or ccRSABadKey

*/

CCRSAKeyType CCRSAGetKeyType(CCRSACryptorRef key)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 	@function   CCRSAGetKeySize
 	@abstract   Return the key size

 	@param      key				The CCRSACryptorRef. 
 	@result     Returns the keysize in bits or kCCParamError.

*/

int CCRSAGetKeySize(CCRSACryptorRef key)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
     @function   CCRSACryptorRelease
     @abstract   Clear and release a CCRSACryptorRef.
     
     @param      key	The CCRSACryptorRef of the key to release. 
*/


void CCRSACryptorRelease(CCRSACryptorRef key)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    
/*!
    @function   CCRSACryptorSign

    @abstract   Compute a signature for data with an RSA private key. 
    
    @param      privateKey		A pointer to a private CCRSACryptorRef.

	@param		padding			A selector for the padding to be used.

    @param      hashToSign		A pointer to the bytes of the value to be signed. 

 	@param      hashSignLen		Length of data to be signed. 
 	
    @param      digestType		The digest algorithm to use (See CommonDigestSPI.h). 
	
 	@param      saltLen			Length of salt to use for the signature. 
    
    @param      sig				The signature bytes. 

	@param      sigLen			A pointer to the length of signature material.
    							This is an in/out parameter value.     
                                
    @result     Possible error returns are kCCParamError and kCCMemoryFailure.
*/


CCCryptorStatus 
CCRSACryptorSign(	CCRSACryptorRef privateKey,
					CCAsymetricPadding padding, 
                 	const void *hashToSign, 
                    size_t hashSignLen,
                 	CCDigestAlgorithm digestType,
                    size_t saltLen,
                 	void *signedData, 
                    size_t *signedDataLen)
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
    @function   CCRSACryptorVerify

	@abstract   Verify a signature for data with an RSA private key. 
    
    @param      publicKey		A pointer to a public CCRSACryptorRef.

	@param		padding			A selector for the padding to be used.
    
 	@param      hash			A pointer to the bytes of the hash of the data. 
 
	@param      hashLen			Length of hash. 
 
 	@param      digestType		The digest algorithm to use (See CommonDigestSPI.h). 
 
 	@param      saltLen			Length of salt to use for the signature. 
 
    @param      signedData		The bytes of the signature to be verified. 

	@param      signedDataLen	Length of data associated with the signature. 
	
                                
    @result     Possible error returns are kCCParamError, kCCMemoryFailure 
				or kCCNotVerified.
*/

CCCryptorStatus 
CCRSACryptorVerify(	CCRSACryptorRef publicKey, 
					CCAsymetricPadding padding,
                   	const void *hash, 
                    size_t hashLen, 
                   	CCDigestAlgorithm digestType, 
                    size_t saltLen,
                   	const void *signedData, 
                    size_t signedDataLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);



/*!
    @function   CCRSACryptorEncrypt

	@abstract   Encrypt data with an RSA public key. 
    
    @param      publicKey		A pointer to a public CCRSACryptorRef.

	@param		padding			A selector for the padding to be used.

    @param      plainText		A pointer to the data to be encrypted.

	@param      plainTextLen	Length of data to be encrypted. 
	
    @param      cipherText		The encrypted byte result. 

	@param      cipherTextLen	Length of encrypted bytes.     
 
 	@param      tagData			tag to be included in the encryption. 
 
	@param      tagDataLen		Length of tag bytes.     
 
 	@param      digestType		The digest algorithm to use (See CommonDigestSPI.h). 
    
    @result     Possible error returns are kCCParamError.
*/

CCCryptorStatus CCRSACryptorEncrypt( 
    CCRSACryptorRef publicKey, 
	CCAsymetricPadding padding, 
	const void *plainText, 
    size_t plainTextLen, 
	void *cipherText, 
    size_t *cipherTextLen,
    const void *tagData, 
    size_t tagDataLen, 
    CCDigestAlgorithm digestType)
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


/*!
    @function   CCRSACryptorDecrypt

	@abstract   Decrypt data with an RSA private key. 
    
    @param      privateKey		A pointer to a private CCRSACryptorRef.

	@param		padding			A selector for the padding to be used.

	@param      cipherText		The encrypted bytes. 

	@param      cipherTextLen	Length of encrypted bytes.     

    @param      plainText		The decrypted data bytes.

	@param      plainTextLen	A pointer to the length of data decrypted.
    							This is an in/out parameter. 	
 	 
	@param      tagData			tag to be included in the encryption. 
 
	@param      tagDataLen		Length of tag bytes.     

	@param      digestType		The digest algorithm to use (See CommonDigestSPI.h). 
                                
    @result     Possible error returns are kCCParamError.
*/

CCCryptorStatus 
CCRSACryptorDecrypt(
	CCRSACryptorRef privateKey, 
    CCAsymetricPadding padding, 
    const void *cipherText, 
    size_t cipherTextLen,
    void *plainText, 
    size_t *plainTextLen, 
    const void *tagData, 
    size_t tagDataLen, 
    CCDigestAlgorithm digestType)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
    
/*!
 @function   CCRSACryptorDecodePayloadPKCS1
 
 @abstract   Decrypt data with an RSA public key, strip off PKCS1 padding and return the payload. 
 
 @param      publicKey		A pointer to a public CCRSACryptorRef.
  
 @param      cipherText		The encrypted bytes. 
 
 @param      cipherTextLen	Length of encrypted bytes.     
 
 @param      plainText		The decrypted data bytes.
 
 @param      plainTextLen	A pointer to the length of data decrypted.
 This is an in/out parameter. 	
 
 @param      digestType		The digest algorithm to use (See CommonDigestSPI.h). 
 
 @result     Possible error returns are kCCParamError.
 */

CCCryptorStatus 
CCRSACryptorDecodePayloadPKCS1(
                    CCRSACryptorRef publicKey, 
                    const void *cipherText, 
                    size_t cipherTextLen,
                    void *plainText, 
                    size_t *plainTextLen)
__OSX_AVAILABLE_STARTING(__MAC_NA, __IPHONE_5_0);

/*!
    @function   CCRSACryptorCrypt

	@abstract   En/Decrypt data with an RSA key. 

    @param      rsaKey		A pointer to a CCRSACryptorRef.

	@param      in          The input data. 

	@param      inLen       The input data length.     

	@param      out          The output data buffer. 

	@param      outLen       The output data buffer size.  This is an in-out
                            parameter.  When the function returns this is set
                            to the length of the result.

    @result     Possible error returns are kCCParamError, kCCDecodeError
                or kCCBufferTooSmall.

*/

CCCryptorStatus 
CCRSACryptorCrypt(
	CCRSACryptorRef rsaKey, 
    const void *in, 
    size_t inLen, 
    void *out, 
    size_t *outLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
    @function   CCRSAGetKeyComponents
	@abstract   En/Decrypt data with an RSA key. 
    @param      rsaKey		A pointer to a CCRSACryptorRef.
	@param      modulus     		The modulus in MSB format.
	@param      modulusLength     	The modulus data length. 	(in/out parameter)
    @param      exponent			The raw data bytes of the exponent.
	@param      exponentLength     	The exponent data length.	(in/out parameter)
    @param      p					The raw data bytes of the modulus factor P.
    								(ccRSAKeyPrivate only)
	@param      pLength     		The P data length.	(in/out parameter)
    @param      q					The raw data bytes of the modulus factor Q.
    								(ccRSAKeyPrivate only)
	@param      qLength     		The Q data length.	(in/out parameter)
    @result		If the function is successful (kCCSuccess)
*/

CCCryptorStatus
CCRSAGetKeyComponents(CCRSACryptorRef rsaKey, uint8_t *modulus, size_t *modulusLength, uint8_t *exponent, size_t *exponentLength,
	uint8_t *p, size_t *pLength, uint8_t *q, size_t *qLength)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
    @function   CCRSACryptorCreateFromData
	@abstract   For FIPS CAVS testing we need the ability to create an RSA 
    			key from an exponent and Modulus.

	@param      keyType     		The type of key to create - ccRSAKeyPublic
    								 or ccRSAKeyPrivate.
	@param      modulus     		The modulus in MSB format.
	@param      modulusLength     	The modulus data length.
    @param      exponent			The raw data bytes of the exponent.
	@param      exponentLength     	The exponent data length.
    @param      p					The raw data bytes of the modulus factor P.
    								(ccRSAKeyPrivate only)
	@param      pLength     		The P data length.
    @param      q					The raw data bytes of the modulus factor Q.
    								(ccRSAKeyPrivate only)
	@param      qLength     		The Q data length.

    @result		If the function is successful (kCCSuccess) a RSACryptoRef is 
    			returned in the ref parameter.  All other errors result in
                kCCParamError.
*/

CCCryptorStatus
CCRSACryptorCreateFromData( CCRSAKeyType keyType, uint8_t *modulus, size_t modulusLength, uint8_t *exponent, size_t exponentLength,
 							uint8_t *p, size_t pLength, uint8_t *q, size_t qLength, CCRSACryptorRef *ref)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


CCCryptorStatus 
CCRSACryptorCreatePairFromData(uint32_t e, 
    uint8_t *xp1, size_t xp1Length,
    uint8_t *xp2, size_t xp2Length,
    uint8_t *xp, size_t xpLength,
    uint8_t *xq1, size_t xq1Length,
    uint8_t *xq2, size_t xq2Length,
    uint8_t *xq, size_t xqLength,
    CCRSACryptorRef *publicKey, 
    CCRSACryptorRef *privateKey,
    uint8_t *retp, size_t *retpLength,
    uint8_t *retq, size_t *retqLength,
    uint8_t *retm, size_t *retmLength,
    uint8_t *retd, size_t *retdLength)
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0);


#ifdef __cplusplus
}
#endif

#endif  /* _CC_RSACRYPTOR_H_ */

Changes to Source/CommonCryptoSPI/CommonRandomSPI.h.




1


2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

22
23







24
25
26


27


28









29
30
31










32
33





34
35






36
37
38



39
40
41
42
43
44
45
46
47

48

49
50
51

52
53
54

55


56




















57
58
































59














60

61


62







63






64



65



66




67
68
69



70









71



72
73
74
75
76
77
78




/*


 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@

 */








/*!
    @header CommonRandom
    The functions provided in CommonRandom.h implement accessors


    to cryptographically secure random numbers.


*/










#ifndef _COMMON_SECRANDOM_H_
#define _COMMON_SECRANDOM_H_











#include <Availability.h>





#include <stdint.h>
#include <sys/types.h>







/*
    When this becomes API we should really make a CommonCrypto/CCErrors.h and



    centralize CC error codes
 */

#include <CommonCrypto/CommonCryptor.h>

#if defined(__cplusplus)
extern "C" {
#endif




/*!
    @typedef SecRandomRef
    @abstract Reference to a (psuedo) random number generator.

*/

typedef struct __CCRandom *CCRandomRef;

























extern CCRandomRef kCCRandomDefault
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);
































    














/*!

    @function CCRandomCopyBytes


    @abstract Return count random bytes in *bytes, allocated by the caller.







    @result Return kCCSuccess on success, kCCParamError for parameter error






        (unimplemented PRNG) or -1 if something went wrong, check errno



        to find out the real error.



    @discussion The default PRNG returns cryptographically strong random bits




        suitable for use as cryptographic keys, IVs, nonces etc.
*/
    



int CCRandomCopyBytes(CCRandomRef rnd, void *bytes, size_t count)









    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);




    
#if defined(__cplusplus)
}
#endif

#endif /* !_COMMON_SECRANDOM_H_ */

>
>
>

>
>
|
|


















>


>
>
>
>
>
>
>

|
|
>
>
|
>
>
|
>
>
>
>
>
>
>
>
>
|
<
<
>
>
>
>
>
>
>
>
>
>

<
>
>
>
>
>
|
|
>
>
>
>
>
>

<
<
>
>
>
|


<



|

>

>

|
|
>

|

>

>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
|
>
>
|
>
>
>
>
>
>
>
|
>
>
>
>
>
>
|
>
>
>
|
>
>
>
|
>
>
>
>
|

|
>
>
>
|
>
>
>
>
>
>
>
>
>
|
>
>
>

|




|
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55


56
57
58
59
60
61
62
63
64
65
66

67
68
69
70
71
72
73
74
75
76
77
78
79
80


81
82
83
84
85
86

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#ifndef  COMMONRANDOM_H
#define  COMMONRANDOM_H 1

/*
 *  CommonRandom.h
 *
 * Copyright © 2010-2011 by Apple, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 *
 */

#include <dispatch/dispatch.h>
#include <dispatch/queue.h>
#include <Availability.h>
#include <stdint.h>
#include <sys/types.h>
#include <CommonCrypto/CommonCryptor.h>

/*!

	@header     CommonRNG.h
	@abstract   An interface to a system random number generator. This module
	            provides a managed way either to get random numbers from a
	            NIST-approved random number generator or /dev/random. The NIST
	            random number generator gets its entropy from /dev/random, but
	            operates 9x-10x faster than it.

    @discussion It is inconvenient to call system random number generators
				directly. In the simple case of calling /dev/random, the caller
				has to open the device and close it in addition to managing it
				while it's open. This module has as its immediate raison d'tre
				the inconvenience of doing this. It manages a file descriptor to
				/dev/random including the exception processing of what happens
				in a fork() and exec(). Call CCRandomCopyBytes() and all the
				fiddly bits are managed for you. Just get on with whatever you
				were really trying to do.
				


				More importantly, though, it also manages a FIPS 140-compliant
				way to get random numbers. NIST created in their document SP
				800-90 a new type of AES-based "Deterministic Random Bit
				Generator" (DRBG) (what is often called a PRNG) and guidelines
				on how to use it. There are two reasons to prefer it over
				directly calling /dev/random. It's a standard and immediately
				compliant with FIPS 140, and it is dramatically faster per-byte.
				For complete disclosure, this implements an AES-CTR DRBG with
				derivation function using AES-128 as the cipher and prediction
				resistance.


				Thus, we provide two RNGs to call, kCCRandomDefault (the NIST
				one) and kCCRandomDevRandom (a managed wrapper around
				/dev/random). If you are doing anything involving security, call
				the default one. You'll be glad you did, because it does much
				security-related housekeeping for you and you don't have to
				think about it. Really.

				In implementation details, the first time you call
				CCRandomCopyBytes(), it will open up /dev/random and seed the RNG
				with 64 bytes. After each call, there is a reseed operation that
				happens on an async GCD queue that reseeds with 32 bytes and a
				nonce from mach_absolute_time(). All access to the internal DRBG
				is serialized through a GCD queue and is therefore thread safe. 



				Should you need to create your own RNG context or have a secondary
				RNG context, CCRNGCreate() and CCRNGRelease() will let you create
				an RNG yourself and then call CCRandomCopyBytes() with that 
				context.
 */



#if defined(__cplusplus)
extern "C" {
#endif	

typedef CCCryptorStatus CCRNGStatus;


/*!
    @typedef    CCRandomRef
    @abstract   Abstract Reference to a random number generator.

*/
#ifndef  COMMONRANDOMPRIV_H // Check for the private header
typedef struct __CCRandom *CCRandomRef;
#endif

/*!
 @function      CCRandomCopyBytes
 
 @abstract      Return random bytes in a buffer allocated by the caller.
 
 @discussion    The default PRNG returns cryptographically strong random 
                bits suitable for use as cryptographic keys, IVs, nonces etc.
                
 @param         rnd     The random number generator to use. Pre-defined values:
                        kCCRandomDefault, the NIST AES-based one and
                        kCCRandomDevRandom, /dev/random itself.
 
						Alternately, you can create one with CCRNGCreate().
 
 @param         bytes   Pointer to the return buffer.
 @param         count   Number of random bytes to return.

 @result        Return kCCSuccess on success.  Other values are ...
 */

int CCRandomCopyBytes(CCRandomRef rnd, void *bytes, size_t count)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
	
extern CCRandomRef kCCRandomDefault
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);
	
extern CCRandomRef kCCRandomDevRandom
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 @function      CCRNGCreate
 
 @abstract      Create an RNG context.
 
 @discussion    This creates a CCRandomRef that you can then pass into
				CCRandomCopyBytes(). Only call this if you need to create
				your own context. You can call CCRandomCopyBytes() with this
				context. Remember to release it.
 
 @param			options	Option flags. See below. Unless you have a very
						good reason, just use kCCRNGOptionCryptoRNG.
 
 @param			rngRef	A pointer to a CCRandomRef.
 
 @result		Returns kCCSuccess on success.
 
 
 */
	
CCRNGStatus
CCRNGCreate(uint32_t options, CCRandomRef *rngRef)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

/*!
 @function      CCRNGRelease
 
 @abstract      Release an RNG context.
 
 @discussion    This releases and deallocates a context.
 
 @param			rng		A CCRandomRef.
 
 @result		Returns kCCSuccess on success.
 
 
 */

CCRNGStatus
CCRNGRelease(CCRandomRef rng)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

	
/*
 Options flags
 
 The option flags are not exposed through the default use of CCRandomGetBytes(). 
 They are only exposed through direct use of a CCRandomRef.

 The polarity is reversed here for two reasons. One is that I want people to
 think before they make a non-FIPS, predictable RNG. If you're doing any sort of
 crypto, you want FIPS and you want prediction resistance. Prediction resistance
 reseeds after every query which is slightly slower, but more secure. Non-FIPS
 is about 20% faster for very large reads, where very large means well over a MB
 per get, which you will probably never do. If you pull under 500 bytes from the
 RNG, there is *NO* change in performance for non-FIPS.

 Non-FIPS makes two changes. First, it increments the counter in machine-natural
 order, which on little-endian machines makes a very small performance
 improvement. It saves you two byte-swaps for every 32-bit increment of the
 counter, for every int that has to be incremented, which is admittedly not
 much. It is so much not much that this is a compile-time option in the DRBG,
 and likely to be turned off.

 But something that makes a difference is that it  reads from the DRBG in one
 lump sum, instead of in 500 byte chunks, as FIPS demands. On a 50MB test, runs
 about 20% faster, but obviously for 500 bytes would run the same.

 Arguably, we should remove the non-FIPS thing because in most circumstances it
 matters naught. Also, as we've said before, if you're interested in security,
 you shouldn't be worrying about a small performance tweaks.

 Prediction resistance re-seeds the DRBG after every request with 32 bytes from
 /dev/random and a timestamp from mach_absolute_time(). This is a legitimate
 thing you might want and a difference between a "random" and a "urandom"
 variant.
 
*/

enum {
	kCCRNGOptionIgnoreFIPS				= 0x00000001,
	kCCRNGOptionNoPredictionResistance	= 0x00000002,
	
	kCCRNGOptionCryptoRNG				= 0x00000000,
};
    
// Accessor functions to get the rng "states" for internal Security Framework
// use.
#include <corecrypto/ccdrbg.h>
#include <corecrypto/ccrng_system.h>
    
struct ccrng_state *ccDevRandomGetRngState()
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0);

struct ccrng_state *ccDRBGGetRngState()
__OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0);


#if defined(__cplusplus)
}
#endif

#endif /* COMMONRANDOM_H */

Changes to Source/CommonCryptoSPI/aes.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

65

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193

194
195
196
197
198
199
200
201
202


203
204
205
206

207
208
209
210
211

212
213
214
215
216
217
218
219

220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237

238
239
240

241
242
243
244


245
246
247
248
249
250
251
252
253
254
255
256
/*
 ---------------------------------------------------------------------------
 Copyright (c) 2003, Dr Brian Gladman, Worcester, UK.   All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue 28/01/2004

 This file contains the definitions required to use AES in C. See aesopt.h
 for optimisation details.
*/

#if !defined( _CC_AES_H_ )
#define _CC_AES_H_

// Generate nothing if this file has been included in an assembly language file.
#if !__ASSEMBLER__

#include <Availability.h>
#include <AvailabilityMacros.h>
#include <CommonCrypto/CommonCryptoPriv.h>

/*  This include is used to find 8 & 32 bit unsigned integer types  */
#include <machine/limits.h>

#include <TargetConditionals.h>
#if TARGET_OS_EMBEDDED && __arm__
#define CC_AES_USE_HARDWARE				1
#endif

#if CC_AES_USE_HARDWARE
#define CC_AES_MAX_KEYSIZE				32 //32 bytes or 256 bits
#endif

#if defined(__cplusplus)
extern "C"
{
#endif

/*	CommonCrypto-specific mods. 


	_APPLE_COMMON_CRYPTO_, when defined, enables the following:

	
	 -- IV/chain buffer stored in the aes_{en,de}crypt_ctx (though it 
	    can still be passed to the encrypt/decrypt routines)
	 -- ECB/CBC controlled per ctx->cbcEnable
	 -- common SPI functions 
	 -- disables AES_VAR
*/

#define AES_128     /* define if AES with 128 bit keys is needed    */
#define AES_192     /* define if AES with 192 bit keys is needed    */
#define AES_256     /* define if AES with 256 bit keys is needed    */
#ifndef		_APPLE_COMMON_CRYPTO_
#define AES_VAR     /* define if a variable key size is needed      */
#endif

/* The following must also be set in assembler files if being used  */

#define AES_ENCRYPT /* if support for encryption is needed          */
#define AES_DECRYPT /* if support for decryption is needed          */
//#define AES_ERR_CHK /* for parameter checks & error return codes    */

#if UCHAR_MAX == 0xff                   /* an unsigned 8 bit type   */
  typedef unsigned char      aes_08t;
#else
#  error Please define aes_08t as an 8-bit unsigned integer type in aes.h
#endif

#if UINT_MAX == 4294967295              /* an unsigned 32 bit type  */
  typedef   unsigned int     aes_32t;
#elif ULONG_MAX == 4294967295ul
  typedef   unsigned long    aes_32t;
#else
#  error Please define aes_32t as a 32-bit unsigned integer type in aes.h
#endif

#define AES_BLOCK_SIZE  16  /* the AES block size in bytes          */
#define N_COLS           4  /* the number of columns in the state   */

/* The key schedule length is 11, 13 or 15 16-byte blocks for 128,  */
/* 192 or 256-bit keys respectively. That is 176, 208 or 240 bytes  */
/* or 44, 52 or 60 32-bit words. For simplicity this code allocates */
/* the maximum 60 word array for the key schedule for all key sizes */

#if defined( AES_VAR ) || defined( AES_256 )
#define KS_LENGTH       60
#elif defined( AES_192 )
#define KS_LENGTH       52
#else
#define KS_LENGTH       44
#endif

#if defined( AES_ERR_CHK )
#define aes_ret     int
#define aes_good    0
#define aes_error  -1
#else
#define aes_ret     void
#endif

#if !defined( AES_DLL )                 /* implement normal/DLL functions   */
#define aes_rval    aes_ret
#else
#define aes_rval    aes_ret __declspec(dllexport) _stdcall
#endif

typedef struct
{   aes_32t ks[KS_LENGTH];
    aes_32t rn;
	#ifdef	_APPLE_COMMON_CRYPTO_
	unsigned char chainBuf[AES_BLOCK_SIZE];
	aes_32t cbcEnable;
	#if CC_AES_USE_HARDWARE
	unsigned char keyBytes[CC_AES_MAX_KEYSIZE];
	aes_32t keyLength;
	#endif
	#endif
} aes_encrypt_ctx;

typedef struct
{   aes_32t ks[KS_LENGTH];
    aes_32t rn;
	#ifdef	_APPLE_COMMON_CRYPTO_
	unsigned char chainBuf[AES_BLOCK_SIZE];
	aes_32t cbcEnable;
	#if CC_AES_USE_HARDWARE
	unsigned char keyBytes[CC_AES_MAX_KEYSIZE];
	aes_32t keyLength;
	#endif
	#endif
} aes_decrypt_ctx;

typedef struct
{   
	aes_decrypt_ctx decrypt;
    aes_encrypt_ctx encrypt;
} aes_ctx;


/* This routine must be called before first use if non-static       */
/* tables are being used                                            */

void gen_tabs(void);

/* The key length (klen) is input in bytes when it is in the range  */
/* 16 <= klen <= 32 or in bits when in the range 128 <= klen <= 256 */

#if defined( AES_ENCRYPT )

#if defined(AES_128) || defined(AES_VAR)
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
aes_rval aes_encrypt_key128(const unsigned char *in_key, aes_encrypt_ctx cx[1]);
#endif

#if defined(AES_192) || defined(AES_VAR)
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
aes_rval aes_encrypt_key192(const unsigned char *in_key, aes_encrypt_ctx cx[1]);
#endif

#if defined(AES_256) || defined(AES_VAR)
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
aes_rval aes_encrypt_key256(const unsigned char *in_key, aes_encrypt_ctx cx[1]);
#endif

#if defined(AES_VAR)
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
aes_rval aes_encrypt_key(const unsigned char *in_key, int key_len, aes_encrypt_ctx cx[1]);
#endif


__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
aes_rval aes_encrypt_cbc(const unsigned char *in_blk, const unsigned char *in_iv, unsigned int num_blk,
					 unsigned char *out_blk, aes_encrypt_ctx cx[1]);
#endif

#if defined( AES_DECRYPT )

#if defined(AES_128) || defined(AES_VAR)
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)


aes_rval aes_decrypt_key128(const unsigned char *in_key, aes_decrypt_ctx cx[1]);
#endif

#if defined(AES_192) || defined(AES_VAR)

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
aes_rval aes_decrypt_key192(const unsigned char *in_key, aes_decrypt_ctx cx[1]);
#endif

#if defined(AES_256) || defined(AES_VAR)

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
aes_rval aes_decrypt_key256(const unsigned char *in_key, aes_decrypt_ctx cx[1]);
#endif

#if defined(AES_VAR)
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
aes_rval aes_decrypt_key(const unsigned char *in_key, int key_len, aes_decrypt_ctx cx[1]);
#endif


__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
aes_rval aes_decrypt_cbc(const unsigned char *in_blk, const unsigned char *in_iv, unsigned int num_blk,
					 unsigned char *out_blk, aes_decrypt_ctx cx[1]);
#endif

#ifdef	_APPLE_COMMON_CRYPTO_

typedef union
{   
	aes_decrypt_ctx decrypt;
    aes_encrypt_ctx encrypt;
} aes_cc_ctx;

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
int aes_cc_set_key(aes_cc_ctx *cx, const void *rawKey, aes_32t keyLength, 
	int forEncrypt);


__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void aes_cc_set_iv(aes_cc_ctx *cx, int forEncrypt, const void *iv);


__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void aes_cc_encrypt(aes_cc_ctx *cx, const void *blocksIn, aes_32t numBlocks,
	void *blocksOut);



__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void aes_cc_decrypt(aes_cc_ctx *cx, const void *blocksIn, aes_32t numBlocks,
	void *blocksOut);
#endif

#if defined(__cplusplus)
}
#endif

#endif	// !__ASSEMBLER__

#endif	/* _CC_AES_H_ */

<
<
|
<
|
<
<
|
<
<
|
<
<
<
|
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|
|
|
|
|
|
|
|
<
<
|
<
<
|
<
<
<
|
|
|
<
<
|
<
<
<
<
|
<

>
|
>
|
<
<
<
<
<
|

<
<
<
<
<
<
|
<
|
<
<
<
|
<
<
<
<
<
|
<
<
<
<

<
<
|
<
<
|
<
<
<
<
<
<
<
<
<
<
<
|

<
<
<
<
<
<
<
<
|
|
<
<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
|
|
<
|
|
>
|
<
|
<
|
|
|
<
<
>
>
|
|
|
|
>
|
<
<

<
>
|
<
<

<
<
|
<
>

<
|
|
<
|
<

<
<
<
<
<
|
|
<
<

>
|
<

>
|
<
<

>
>
|
|
<
<





<


1


2

3


4


5



6


7












8
9
10
11
12
13
14
15
16
17
18


19


20



21
22
23


24




25

26
27
28
29
30





31
32






33

34



35





36




37


38


39











40
41








42
43



44









































45
46













47
48
49
50

51
52
53
54

55

56
57
58


59
60
61
62
63
64
65
66


67

68
69


70


71

72
73

74
75

76

77





78
79


80
81
82

83
84
85


86
87
88
89
90


91
92
93
94
95

96
97
/*


 *  aes.h

 *


 * Copyright © 2010 by Apple, Inc. All rights reserved.


 *



 * @APPLE_LICENSE_HEADER_START@


 * 












 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,


 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.


 * Please see the License for the specific language governing rights and



 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@


 *




 */


/*
 *  aes.h
 *  CommonCrypto shoefly for compatability with older versions
 *





 */







#ifdef CC_Building

#include "CommonCryptor.h"



#include "CommonCryptorSPI.h"





#include "CommonCryptorPriv.h"




#else


#include <CommonCrypto/CommonCryptor.h>


#include <CommonCrypto/CommonCryptorSPI.h>











#endif /* CC_Building */









#if !defined( _CC_AES_H_ )
#define _CC_AES_H_













































#if defined(__cplusplus)
extern "C" {













#endif	
    
#define AES_BLOCK_SIZE  16  /* the AES block size in bytes          */
    

typedef struct
{
	CCCryptorRef	cref;
	uint32_t		ctx[kCCContextSizeAES128/4];

} aes_encrypt_ctx;

    
typedef struct
{


	CCCryptorRef	cref;
	uint32_t		ctx[kCCContextSizeAES128/4];
} aes_decrypt_ctx;
    
    
    
void aes_encrypt_key128(const unsigned char *in_key, aes_encrypt_ctx cx[1])
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_5_0, __IPHONE_5_0);




void aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1])
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_5_0, __IPHONE_5_0);





void aes_encrypt_key256(const unsigned char *in_key, aes_encrypt_ctx cx[1])

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_5_0, __IPHONE_5_0);


void aes_encrypt_cbc(const unsigned char *in_blk, const unsigned char *in_iv, unsigned int num_blk,
                         unsigned char *out_blk, aes_encrypt_ctx cx[1])

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_5_0, __IPHONE_5_0);







void aes_decrypt_key128(const unsigned char *in_key, aes_decrypt_ctx cx[1])
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_5_0, __IPHONE_5_0);



void aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1])
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_5_0, __IPHONE_5_0);


void aes_decrypt_key256(const unsigned char *in_key, aes_decrypt_ctx cx[1])
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_5_0, __IPHONE_5_0);



void aes_decrypt_cbc(const unsigned char *in_blk, const unsigned char *in_iv, unsigned int num_blk,
                         unsigned char *out_blk, aes_decrypt_ctx cx[1])
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_5_0, __IPHONE_5_0);




#if defined(__cplusplus)
}
#endif



#endif	/* _CC_AES_H_ */

Deleted Source/CommonCryptoSPI/aesopt.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
/*
The bulk of this file is from Dr. Brian Gladman's AES implementation, described
in the comments below.  But some code has been added to select the
implementation.  See comments below, where UseGladmanAES is defined.  The new
code does not alter Gladman's AES implementation except to completely include
or exclude it from compilation.

		-- Eric Postpischil, January 8, 2008.


 ---------------------------------------------------------------------------
 Copyright (c) 2003, Dr Brian Gladman, Worcester, UK.   All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue 28/01/2004

 My thanks go to Dag Arne Osvik for devising the schemes used here for key
 length derivation from the form of the key schedule

 This file contains the compilation options for AES (Rijndael) and code
 that is common across encryption, key scheduling and table generation.

 OPERATION

 These source code files implement the AES algorithm Rijndael designed by
 Joan Daemen and Vincent Rijmen. This version is designed for the standard
 block size of 16 bytes and for key sizes of 128, 192 and 256 bits (16, 24
 and 32 bytes).

 This version is designed for flexibility and speed using operations on
 32-bit words rather than operations on bytes.  It can be compiled with
 either big or little endian internal byte order but is faster when the
 native byte order for the processor is used.

 THE CIPHER INTERFACE

 The cipher interface is implemented as an array of bytes in which lower
 AES bit sequence indexes map to higher numeric significance within bytes.

  aes_08t                 (an unsigned  8-bit type)
  aes_32t                 (an unsigned 32-bit type)
  struct aes_encrypt_ctx  (structure for the cipher encryption context)
  struct aes_decrypt_ctx  (structure for the cipher decryption context)
  aes_rval                the function return type

  C subroutine calls:

  aes_rval aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]);
  aes_rval aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]);
  aes_rval aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]);
  aes_rval aes_encrypt(const unsigned char *in, unsigned char *out,
                                                  const aes_encrypt_ctx cx[1]);

  aes_rval aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]);
  aes_rval aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]);
  aes_rval aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]);
  aes_rval aes_decrypt(const unsigned char *in, unsigned char *out,
                                                  const aes_decrypt_ctx cx[1]);

 IMPORTANT NOTE: If you are using this C interface with dynamic tables make sure that
 you call genTabs() before AES is used so that the tables are initialised.

 C++ aes class subroutines:

     Class AESencrypt  for encryption

      Construtors:
          AESencrypt(void)
          AESencrypt(const unsigned char *key) - 128 bit key
      Members:
          aes_rval key128(const unsigned char *key)
          aes_rval key192(const unsigned char *key)
          aes_rval key256(const unsigned char *key)
          aes_rval encrypt(const unsigned char *in, unsigned char *out) const

      Class AESdecrypt  for encryption
      Construtors:
          AESdecrypt(void)
          AESdecrypt(const unsigned char *key) - 128 bit key
      Members:
          aes_rval key128(const unsigned char *key)
          aes_rval key192(const unsigned char *key)
          aes_rval key256(const unsigned char *key)
          aes_rval decrypt(const unsigned char *in, unsigned char *out) const

    COMPILATION

    The files used to provide AES (Rijndael) are

    a. aes.h for the definitions needed for use in C.
    b. aescpp.h for the definitions needed for use in C++.
    c. aesopt.h for setting compilation options (also includes common code).
    d. aescrypt.c for encryption and decrytpion, or
    e. aeskey.c for key scheduling.
    f. aestab.c for table loading or generation.
    g. aescrypt.asm for encryption and decryption using assembler code.
    h. aescrypt.mmx.asm for encryption and decryption using MMX assembler.

    To compile AES (Rijndael) for use in C code use aes.h and set the
    defines here for the facilities you need (key lengths, encryption
    and/or decryption). Do not define AES_DLL or AES_CPP.  Set the options
    for optimisations and table sizes here.

    To compile AES (Rijndael) for use in in C++ code use aescpp.h but do
    not define AES_DLL

    To compile AES (Rijndael) in C as a Dynamic Link Library DLL) use
    aes.h and include the AES_DLL define.

    CONFIGURATION OPTIONS (here and in aes.h)

    a. set AES_DLL in aes.h if AES (Rijndael) is to be compiled as a DLL
    b. You may need to set PLATFORM_BYTE_ORDER to define the byte order.
    c. If you want the code to run in a specific internal byte order, then
       ALGORITHM_BYTE_ORDER must be set accordingly.
    d. set other configuration options decribed below.
*/

#if !defined( _CC_AESOPT_H )
#define _CC_AESOPT_H

/*	Select which AES implementation to use.  Preprocessor directives decide
	whether to define UseGladmanAES or UseAESedp or, in the future, other
	symbols.  Source files for the implementations contain preprocessor
	directives to compile their code iff the matching symbol is defined.

	The names GladmanAES and AESedp come from the directories containing the
	source code.  (I prefer putting "AES" first and am tempted to renamed
	"GladmanAES" to "AESGladman", since this groups directories by algorithm in
	listings, but I am resisting for the moment.)
*/
#if defined __i386__ || defined __x86_64__
	// On Intel architectures, use AESedp.
	#define	UseAESedp
#else
	// Otherwise, use Gladman AES.
	#define	UseGladmanAES
#endif

/*	Suppressing all source in a module would yield an empty module after
	preprocessing.  GCC allows this, but standard C requires a module to
	contain at least one external declaration.  So here we make an otherwise
	unused declaration that generates no object code.
*/
#if !defined __ASSEMBLER__
	typedef char DummyDeclarationToMakeValidC;
#endif

#include <CommonCrypto/CommonCryptoPriv.h>
#include <CommonCrypto/aes.h>

/*  CONFIGURATION - USE OF DEFINES

    Later in this section there are a number of defines that control the
    operation of the code.  In each section, the purpose of each define is
    explained so that the relevant form can be included or excluded by
    setting either 1's or 0's respectively on the branches of the related
    #if clauses.

    PLATFORM SPECIFIC INCLUDES AND BYTE ORDER IN 32-BIT WORDS

    To obtain the highest speed on processors with 32-bit words, this code
    needs to determine the byte order of the target machine. The following
    block of code is an attempt to capture the most obvious ways in which
    various environemnts define byte order. It may well fail, in which case
    the definitions will need to be set by editing at the points marked
    **** EDIT HERE IF NECESSARY **** below.  My thanks go to Peter Gutmann
    for his assistance with this endian detection nightmare.
*/

#define BRG_LITTLE_ENDIAN   1234 /* byte 0 is least significant (i386) */
#define BRG_BIG_ENDIAN      4321 /* byte 0 is most significant (mc68k) */

#if defined(__GNUC__) || defined(__GNU_LIBRARY__)
#  if defined(__FreeBSD__) || defined(__OpenBSD__)
#    include <sys/endian.h>
#  elif defined( BSD ) && BSD >= 199103
#      include <machine/endian.h>
#  elif defined(__APPLE__)
#    if defined(__BIG_ENDIAN__) && !defined( BIG_ENDIAN )
#      define BIG_ENDIAN
#    elif defined(__LITTLE_ENDIAN__) && !defined( LITTLE_ENDIAN )
#      define LITTLE_ENDIAN
#    endif
#  else
#    include <endian.h>
#    if defined(__BEOS__)
#      include <byteswap.h>
#    endif
#  endif
#endif

#if !defined(PLATFORM_BYTE_ORDER)
#  if defined(LITTLE_ENDIAN) || defined(BIG_ENDIAN)
#    if    defined(LITTLE_ENDIAN) && !defined(BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif !defined(LITTLE_ENDIAN) &&  defined(BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#    elif defined(BYTE_ORDER) && (BYTE_ORDER == LITTLE_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif defined(BYTE_ORDER) && (BYTE_ORDER == BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#    endif
#  elif defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)
#    if    defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif !defined(_LITTLE_ENDIAN) &&  defined(_BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#    elif defined(_BYTE_ORDER) && (_BYTE_ORDER == _LITTLE_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif defined(_BYTE_ORDER) && (_BYTE_ORDER == _BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#   endif
#  elif defined(__LITTLE_ENDIAN__) || defined(__BIG_ENDIAN__)
#    if    defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif !defined(__LITTLE_ENDIAN__) &&  defined(__BIG_ENDIAN__)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#    elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __LITTLE_ENDIAN__)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __BIG_ENDIAN__)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#    endif
#  endif
#endif

/*  if the platform is still unknown, try to find its byte order    */
/*  from commonly used machine defines                              */

#if !defined(PLATFORM_BYTE_ORDER)

#if   defined( __alpha__ ) || defined( __alpha ) || defined( i386 )       || \
      defined( __i386__ )  || defined( _M_I86 )  || defined( _M_IX86 )    || \
      defined( __OS2__ )   || defined( sun386 )  || defined( __TURBOC__ ) || \
      defined( vax )       || defined( vms )     || defined( VMS )        || \
      defined( __VMS )	   || defined(__x86_64__)
#  define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN

#elif defined( AMIGA )    || defined( applec )  || defined( __AS400__ )  || \
      defined( _CRAY )    || defined( __hppa )  || defined( __hp9000 )   || \
      defined( ibm370 )   || defined( mc68000 ) || defined( m68k )       || \
      defined( __MRC__ )  || defined( __MVS__ ) || defined( __MWERKS__ ) || \
      defined( sparc )    || defined( __sparc)  || defined( SYMANTEC_C ) || \
      defined( __TANDEM ) || defined( THINK_C ) || defined( __VMCMS__ )
#  define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN

#elif 0     /* **** EDIT HERE IF NECESSARY **** */
#  define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#elif 0     /* **** EDIT HERE IF NECESSARY **** */
#  define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#else
#  error Please edit aesopt.h (line 234 or 236) to set the platform byte order
#endif

#endif

/*  SOME LOCAL DEFINITIONS  */

#define NO_TABLES              0
#define ONE_TABLE              1
#define FOUR_TABLES            4
#define NONE                   0
#define PARTIAL                1
#define FULL                   2

#if defined(bswap32)
#define aes_sw32    bswap32
#elif defined(bswap_32)
#define aes_sw32    bswap_32
#else
#define brot(x,n)   (((aes_32t)(x) <<  n) | ((aes_32t)(x) >> (32 - n)))
#define aes_sw32(x) ((brot((x),8) & 0x00ff00ff) | (brot((x),24) & 0xff00ff00))
#endif

/*  1. FUNCTIONS REQUIRED

    This implementation provides subroutines for encryption, decryption
    and for setting the three key lengths (separately) for encryption
    and decryption. When the assembler code is not being used the following
    definition blocks allow the selection of the routines that are to be
    included in the compilation.
*/
#if defined( AES_ENCRYPT )
#define ENCRYPTION
#define ENCRYPTION_KEY_SCHEDULE
#endif

#if defined( AES_DECRYPT )
#define DECRYPTION
#define DECRYPTION_KEY_SCHEDULE
#endif

/*  2. ASSEMBLER SUPPORT

    This define (which can be on the command line) enables the use of the
    assembler code routines for encryption and decryption with the C code
    only providing key scheduling
*/
#if 0 && !defined(AES_ASM)
#define AES_ASM
#endif

/*  3. BYTE ORDER WITHIN 32 BIT WORDS

    The fundamental data processing units in Rijndael are 8-bit bytes. The
    input, output and key input are all enumerated arrays of bytes in which
    bytes are numbered starting at zero and increasing to one less than the
    number of bytes in the array in question. This enumeration is only used
    for naming bytes and does not imply any adjacency or order relationship
    from one byte to another. When these inputs and outputs are considered
    as bit sequences, bits 8*n to 8*n+7 of the bit sequence are mapped to
    byte[n] with bit 8n+i in the sequence mapped to bit 7-i within the byte.
    In this implementation bits are numbered from 0 to 7 starting at the
    numerically least significant end of each byte (bit n represents 2^n).

    However, Rijndael can be implemented more efficiently using 32-bit
    words by packing bytes into words so that bytes 4*n to 4*n+3 are placed
    into word[n]. While in principle these bytes can be assembled into words
    in any positions, this implementation only supports the two formats in
    which bytes in adjacent positions within words also have adjacent byte
    numbers. This order is called big-endian if the lowest numbered bytes
    in words have the highest numeric significance and little-endian if the
    opposite applies.

    This code can work in either order irrespective of the order used by the
    machine on which it runs. Normally the internal byte order will be set
    to the order of the processor on which the code is to be run but this
    define can be used to reverse this in special situations

    NOTE: Assembler code versions rely on PLATFORM_BYTE_ORDER being set
*/
#if 1 || defined(AES_ASM)
#define ALGORITHM_BYTE_ORDER PLATFORM_BYTE_ORDER
#elif 0
#define ALGORITHM_BYTE_ORDER BRG_LITTLE_ENDIAN
#elif 0
#define ALGORITHM_BYTE_ORDER BRG_BIG_ENDIAN
#else
#error The algorithm byte order is not defined
#endif

/*  4. FAST INPUT/OUTPUT OPERATIONS.

    On some machines it is possible to improve speed by transferring the
    bytes in the input and output arrays to and from the internal 32-bit
    variables by addressing these arrays as if they are arrays of 32-bit
    words.  On some machines this will always be possible but there may
    be a large performance penalty if the byte arrays are not aligned on
    the normal word boundaries. On other machines this technique will
    lead to memory access errors when such 32-bit word accesses are not
    properly aligned. The option SAFE_IO avoids such problems but will
    often be slower on those machines that support misaligned access
    (especially so if care is taken to align the input  and output byte
    arrays on 32-bit word boundaries). If SAFE_IO is not defined it is
    assumed that access to byte arrays as if they are arrays of 32-bit
    words will not cause problems when such accesses are misaligned.
*/
#if 0 && !defined(_MSC_VER)
#define SAFE_IO
#endif

/*  5. LOOP UNROLLING

    The code for encryption and decrytpion cycles through a number of rounds
    that can be implemented either in a loop or by expanding the code into a
    long sequence of instructions, the latter producing a larger program but
    one that will often be much faster. The latter is called loop unrolling.
    There are also potential speed advantages in expanding two iterations in
    a loop with half the number of iterations, which is called partial loop
    unrolling.  The following options allow partial or full loop unrolling
    to be set independently for encryption and decryption
*/
#if 1
#define ENC_UNROLL  FULL
#elif 0
#define ENC_UNROLL  PARTIAL
#else
#define ENC_UNROLL  NONE
#endif

#if 1
#define DEC_UNROLL  FULL
#elif 0
#define DEC_UNROLL  PARTIAL
#else
#define DEC_UNROLL  NONE
#endif

/*  6. FAST FINITE FIELD OPERATIONS

    If this section is included, tables are used to provide faster finite
    field arithmetic (this has no effect if FIXED_TABLES is defined).
*/
#if 1
#define FF_TABLES
#endif

/*  7. INTERNAL STATE VARIABLE FORMAT

    The internal state of Rijndael is stored in a number of local 32-bit
    word varaibles which can be defined either as an array or as individual
    names variables. Include this section if you want to store these local
    varaibles in arrays. Otherwise individual local variables will be used.
*/
#if 0
#define ARRAYS
#endif

/* In this implementation the columns of the state array are each held in
   32-bit words. The state array can be held in various ways: in an array
   of words, in a number of individual word variables or in a number of
   processor registers. The following define maps a variable name x and
   a column number c to the way the state array variable is to be held.
   The first define below maps the state into an array x[c] whereas the
   second form maps the state into a number of individual variables x0,
   x1, etc.  Another form could map individual state colums to machine
   register names.
*/

#if defined(ARRAYS)
#define s(x,c) x[c]
#else
#define s(x,c) x##c
#endif

/*  8. FIXED OR DYNAMIC TABLES

    When this section is included the tables used by the code are compiled
    statically into the binary file.  Otherwise the subroutine gen_tabs()
    must be called to compute them before the code is first used.
*/
#if 1
#define FIXED_TABLES
#endif

/*  9. TABLE ALIGNMENT

    On some sytsems speed will be improved by aligning the AES large lookup
    tables on particular boundaries. This define should be set to a power of
    two giving the desired alignment. It can be left undefined if alignment
    is not needed.  This option is specific to the Microsft VC++ compiler -
    it seems to sometimes cause trouble for the VC++ version 6 compiler.
*/

#if 0 && defined(_MSC_VER) && (_MSC_VER >= 1300)
#define TABLE_ALIGN 64
#endif

/*  10. INTERNAL TABLE CONFIGURATION

    This cipher proceeds by repeating in a number of cycles known as 'rounds'
    which are implemented by a round function which can optionally be speeded
    up using tables.  The basic tables are each 256 32-bit words, with either
    one or four tables being required for each round function depending on
    how much speed is required. The encryption and decryption round functions
    are different and the last encryption and decrytpion round functions are
    different again making four different round functions in all.

    This means that:
      1. Normal encryption and decryption rounds can each use either 0, 1
         or 4 tables and table spaces of 0, 1024 or 4096 bytes each.
      2. The last encryption and decryption rounds can also use either 0, 1
         or 4 tables and table spaces of 0, 1024 or 4096 bytes each.

    Include or exclude the appropriate definitions below to set the number
    of tables used by this implementation.
*/

#if 1   /* set tables for the normal encryption round */
#define ENC_ROUND   FOUR_TABLES
#elif 0
#define ENC_ROUND   ONE_TABLE
#else
#define ENC_ROUND   NO_TABLES
#endif

#if 1   /* set tables for the last encryption round */
#define LAST_ENC_ROUND  FOUR_TABLES
#elif 0
#define LAST_ENC_ROUND  ONE_TABLE
#else
#define LAST_ENC_ROUND  NO_TABLES
#endif

#if 1   /* set tables for the normal decryption round */
#define DEC_ROUND   FOUR_TABLES
#elif 0
#define DEC_ROUND   ONE_TABLE
#else
#define DEC_ROUND   NO_TABLES
#endif

#if 1   /* set tables for the last decryption round */
#define LAST_DEC_ROUND  FOUR_TABLES
#elif 0
#define LAST_DEC_ROUND  ONE_TABLE
#else
#define LAST_DEC_ROUND  NO_TABLES
#endif

/*  The decryption key schedule can be speeded up with tables in the same
    way that the round functions can.  Include or exclude the following
    defines to set this requirement.
*/
#if 1
#define KEY_SCHED   FOUR_TABLES
#elif 0
#define KEY_SCHED   ONE_TABLE
#else
#define KEY_SCHED   NO_TABLES
#endif

/*  11. TABLE POINTER CACHING

    Normally tables are referenced directly, Enable this option if you wish to
    cache pointers to the tables in the encrypt/decrypt code.  Note that this
	only works if you are using FOUR_TABLES for the ROUND you enable this for.
*/
#if 1
#define ENC_ROUND_CACHE_TABLES
#endif
#if 1
#define LAST_ENC_ROUND_CACHE_TABLES
#endif
#if 1
#define DEC_ROUND_CACHE_TABLES
#endif
#if 1
#define LAST_DEC_ROUND_CACHE_TABLES
#endif

/* END OF CONFIGURATION OPTIONS */

#define RC_LENGTH   (5 * (AES_BLOCK_SIZE / 4 - 2))

/* Disable or report errors on some combinations of options */

#if ENC_ROUND == NO_TABLES && LAST_ENC_ROUND != NO_TABLES
#undef  LAST_ENC_ROUND
#define LAST_ENC_ROUND  NO_TABLES
#elif ENC_ROUND == ONE_TABLE && LAST_ENC_ROUND == FOUR_TABLES
#undef  LAST_ENC_ROUND
#define LAST_ENC_ROUND  ONE_TABLE
#endif

#if ENC_ROUND == NO_TABLES && ENC_UNROLL != NONE
#undef  ENC_UNROLL
#define ENC_UNROLL  NONE
#endif

#if DEC_ROUND == NO_TABLES && LAST_DEC_ROUND != NO_TABLES
#undef  LAST_DEC_ROUND
#define LAST_DEC_ROUND  NO_TABLES
#elif DEC_ROUND == ONE_TABLE && LAST_DEC_ROUND == FOUR_TABLES
#undef  LAST_DEC_ROUND
#define LAST_DEC_ROUND  ONE_TABLE
#endif

#if DEC_ROUND == NO_TABLES && DEC_UNROLL != NONE
#undef  DEC_UNROLL
#define DEC_UNROLL  NONE
#endif

/*  upr(x,n):  rotates bytes within words by n positions, moving bytes to
               higher index positions with wrap around into low positions
    ups(x,n):  moves bytes by n positions to higher index positions in
               words but without wrap around
    bval(x,n): extracts a byte from a word

    NOTE:      The definitions given here are intended only for use with
               unsigned variables and with shift counts that are compile
               time constants
*/

#if (ALGORITHM_BYTE_ORDER == BRG_LITTLE_ENDIAN)
#define upr(x,n)        (((aes_32t)(x) << (8 * (n))) | ((aes_32t)(x) >> (32 - 8 * (n))))
#define ups(x,n)        ((aes_32t) (x) << (8 * (n)))
#define bval(x,n)       ((aes_08t)((x) >> (8 * (n))))
#define bytes2word(b0, b1, b2, b3)  \
        (((aes_32t)(b3) << 24) | ((aes_32t)(b2) << 16) | ((aes_32t)(b1) << 8) | (b0))
#endif

#if (ALGORITHM_BYTE_ORDER == BRG_BIG_ENDIAN)
#define upr(x,n)        (((aes_32t)(x) >> (8 * (n))) | ((aes_32t)(x) << (32 - 8 * (n))))
#define ups(x,n)        ((aes_32t) (x) >> (8 * (n))))
#define bval(x,n)       ((aes_08t)((x) >> (24 - 8 * (n))))
#define bytes2word(b0, b1, b2, b3)  \
        (((aes_32t)(b0) << 24) | ((aes_32t)(b1) << 16) | ((aes_32t)(b2) << 8) | (b3))
#endif

#if defined(SAFE_IO)

#define word_in(x,c)    bytes2word(((aes_08t*)(x)+4*c)[0], ((aes_08t*)(x)+4*c)[1], \
                                   ((aes_08t*)(x)+4*c)[2], ((aes_08t*)(x)+4*c)[3])
#define word_out(x,c,v) { ((aes_08t*)(x)+4*c)[0] = bval(v,0); ((aes_08t*)(x)+4*c)[1] = bval(v,1); \
                          ((aes_08t*)(x)+4*c)[2] = bval(v,2); ((aes_08t*)(x)+4*c)[3] = bval(v,3); }

#elif (ALGORITHM_BYTE_ORDER == PLATFORM_BYTE_ORDER)

#define word_in(x,c)    (*((aes_32t*)(x)+(c)))
#define word_out(x,c,v) (*((aes_32t*)(x)+(c)) = (v))

#else

#define word_in(x,c)    aes_sw32(*((aes_32t*)(x)+(c)))
#define word_out(x,c,v) (*((aes_32t*)(x)+(c)) = aes_sw32(v))

#endif

/* the finite field modular polynomial and elements */

#define WPOLY   0x011b
#define BPOLY     0x1b

/* multiply four bytes in GF(2^8) by 'x' {02} in parallel */

#define m1  0x80808080
#define m2  0x7f7f7f7f
#define gf_mulx(x)  ((((x) & m2) << 1) ^ ((((x) & m1) >> 7) * BPOLY))

/* The following defines provide alternative definitions of gf_mulx that might
   give improved performance if a fast 32-bit multiply is not available. Note
   that a temporary variable u needs to be defined where gf_mulx is used.

#define gf_mulx(x) (u = (x) & m1, u |= (u >> 1), ((x) & m2) << 1) ^ ((u >> 3) | (u >> 6))
#define m4  (0x01010101 * BPOLY)
#define gf_mulx(x) (u = (x) & m1, ((x) & m2) << 1) ^ ((u - (u >> 7)) & m4)
*/

/* Work out which tables are needed for the different options   */

#if defined( AES_ASM )
#if defined( ENC_ROUND )
#undef  ENC_ROUND
#endif
#define ENC_ROUND   FOUR_TABLES
#if defined( LAST_ENC_ROUND )
#undef  LAST_ENC_ROUND
#endif
#define LAST_ENC_ROUND  FOUR_TABLES
#if defined( DEC_ROUND )
#undef  DEC_ROUND
#endif
#define DEC_ROUND   FOUR_TABLES
#if defined( LAST_DEC_ROUND )
#undef  LAST_DEC_ROUND
#endif
#define LAST_DEC_ROUND  FOUR_TABLES
#if defined( KEY_SCHED )
#undef  KEY_SCHED
#define KEY_SCHED   FOUR_TABLES
#endif
#endif

#if defined(ENCRYPTION) || defined(AES_ASM)
#if ENC_ROUND == ONE_TABLE
#define FT1_SET
#elif ENC_ROUND == FOUR_TABLES
#define FT4_SET
#else
#define SBX_SET
#endif
#if LAST_ENC_ROUND == ONE_TABLE
#define FL1_SET
#elif LAST_ENC_ROUND == FOUR_TABLES
#define FL4_SET
#elif !defined(SBX_SET)
#define SBX_SET
#endif
#endif

#if defined(DECRYPTION) || defined(AES_ASM)
#if DEC_ROUND == ONE_TABLE
#define IT1_SET
#elif DEC_ROUND == FOUR_TABLES
#define IT4_SET
#else
#define ISB_SET
#endif
#if LAST_DEC_ROUND == ONE_TABLE
#define IL1_SET
#elif LAST_DEC_ROUND == FOUR_TABLES
#define IL4_SET
#elif !defined(ISB_SET)
#define ISB_SET
#endif
#endif

#if defined(ENCRYPTION_KEY_SCHEDULE) || defined(DECRYPTION_KEY_SCHEDULE)
#if KEY_SCHED == ONE_TABLE
#define LS1_SET
#define IM1_SET
#elif KEY_SCHED == FOUR_TABLES
#define LS4_SET
#define IM4_SET
#elif !defined(SBX_SET)
#define SBX_SET
#endif
#endif

/* generic definitions of Rijndael macros that use tables    */

#define no_table(x,box,vf,rf,c) bytes2word( \
    box[bval(vf(x,0,c),rf(0,c))], \
    box[bval(vf(x,1,c),rf(1,c))], \
    box[bval(vf(x,2,c),rf(2,c))], \
    box[bval(vf(x,3,c),rf(3,c))])

#define one_table(x,op,tab,vf,rf,c) \
 (     tab[bval(vf(x,0,c),rf(0,c))] \
  ^ op(tab[bval(vf(x,1,c),rf(1,c))],1) \
  ^ op(tab[bval(vf(x,2,c),rf(2,c))],2) \
  ^ op(tab[bval(vf(x,3,c),rf(3,c))],3))

#define four_tables(x,tab,vf,rf,c) \
 (  tab[0][bval(vf(x,0,c),rf(0,c))] \
  ^ tab[1][bval(vf(x,1,c),rf(1,c))] \
  ^ tab[2][bval(vf(x,2,c),rf(2,c))] \
  ^ tab[3][bval(vf(x,3,c),rf(3,c))])

#define four_cached_tables(x,tab,vf,rf,c) \
(  tab##0[bval(vf(x,0,c),rf(0,c))] \
   ^ tab##1[bval(vf(x,1,c),rf(1,c))] \
   ^ tab##2[bval(vf(x,2,c),rf(2,c))] \
   ^ tab##3[bval(vf(x,3,c),rf(3,c))])

#define vf1(x,r,c)  (x)
#define rf1(r,c)    (r)
#define rf2(r,c)    ((8+r-c)&3)

/* perform forward and inverse column mix operation on four bytes in long word x in */
/* parallel. NOTE: x must be a simple variable, NOT an expression in these macros.  */

#if defined(FM4_SET)    /* not currently used */
#define fwd_mcol(x)     four_tables(x,t_use(f,m),vf1,rf1,0)
#elif defined(FM1_SET)  /* not currently used */
#define fwd_mcol(x)     one_table(x,upr,t_use(f,m),vf1,rf1,0)
#else
#define dec_fmvars      aes_32t g2
#define fwd_mcol(x)     (g2 = gf_mulx(x), g2 ^ upr((x) ^ g2, 3) ^ upr((x), 2) ^ upr((x), 1))
#endif

#if defined(IM4_SET)
#define inv_mcol(x)     four_tables(x,t_use(i,m),vf1,rf1,0)
#elif defined(IM1_SET)
#define inv_mcol(x)     one_table(x,upr,t_use(i,m),vf1,rf1,0)
#else
#define dec_imvars      aes_32t g2, g4, g9
#define inv_mcol(x)     (g2 = gf_mulx(x), g4 = gf_mulx(g2), g9 = (x) ^ gf_mulx(g4), g4 ^= g9, \
                        (x) ^ g2 ^ g4 ^ upr(g2 ^ g9, 3) ^ upr(g4, 2) ^ upr(g9, 1))
#endif

#if defined(FL4_SET)
#define ls_box(x,c)     four_tables(x,t_use(f,l),vf1,rf2,c)
#elif   defined(LS4_SET)
#define ls_box(x,c)     four_tables(x,t_use(l,s),vf1,rf2,c)
#elif defined(FL1_SET)
#define ls_box(x,c)     one_table(x,upr,t_use(f,l),vf1,rf2,c)
#elif defined(LS1_SET)
#define ls_box(x,c)     one_table(x,upr,t_use(l,s),vf1,rf2,c)
#else
#define ls_box(x,c)     no_table(x,t_use(s,box),vf1,rf2,c)
#endif

#endif	/* _CC_AESOPT_H */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/CommonCryptoSPI/cast.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/* crypto/cast/cast.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#ifndef CC_CAST_H
#define CC_CAST_H

#include <Availability.h>
#include <AvailabilityMacros.h>

#ifdef  __cplusplus
extern "C" {
#endif

#include <CommonCrypto/CommonCryptoPriv.h>
#include <stdint.h>

#ifdef	_APPLE_COMMON_CRYPTO_
/* avoid symbol collision with libSystem & libcrypto */
#define CAST_set_key		CC_CAST_set_key
#define CAST_ecb_encrypt	CC_CAST_ecb_encrypt
#define CAST_encrypt		CC_CAST_encrypt
#define CAST_decrypt		CC_CAST_decrypt
#endif	/* _APPLE_COMMON_CRYPTO_ */

#ifdef NO_CAST
#error CAST is disabled.
#endif

#define CAST_ENCRYPT	1
#define CAST_DECRYPT	0

#ifdef	_APPLE_COMMON_CRYPTO_
#define CAST_LONG uint32_t
#else
#define CAST_LONG unsigned long
#endif	/* _APPLE_COMMON_CRYPTO_ */

#define CAST_BLOCK			8			/* block size in bytes */
#define CAST_KEY_LENGTH		16			/* MAX key size in bytes */
#define CAST_MIN_KEY_LENGTH	5			/* MIN key size in bytes */
typedef struct cast_key_st
	{
	CAST_LONG data[32];
	int short_key;	/* Use reduced rounds for short key */
	} CAST_KEY;

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data);

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void CAST_ecb_encrypt(const unsigned char *in,unsigned char *out,CAST_KEY *key,
		      int enc);

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void CAST_encrypt(CAST_LONG *data,CAST_KEY *key);

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void CAST_decrypt(CAST_LONG *data,CAST_KEY *key);
#ifndef	_APPLE_COMMON_CRYPTO_

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void CAST_cbc_encrypt(const unsigned char *in, unsigned char *out, long length,
		      CAST_KEY *ks, unsigned char *iv, int enc);

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void CAST_cfb64_encrypt(const unsigned char *in, unsigned char *out,
			long length, CAST_KEY *schedule, unsigned char *ivec,
			int *num, int enc);

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void CAST_ofb64_encrypt(const unsigned char *in, unsigned char *out, 
			long length, CAST_KEY *schedule, unsigned char *ivec,
			int *num);
#endif	/* _APPLE_COMMON_CRYPTO_ */
#ifdef  __cplusplus
}
#endif

#endif	/* CC_CAST_H */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































Deleted Source/CommonCryptoSPI/ccCast.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 * ccCast.h - shim between openssl-based CAST and CommonEncryption.
 *
 * Created 3/30/06 by Doug Mitchell. 
 */

#ifndef	_CC_CCCAST_H_
#define _CC_CCCAST_H_

#include <CommonCrypto/CommonCryptoPriv.h>
#include <CommonCrypto/cast.h>
#include <sys/types.h>

#ifdef  __cplusplus
extern "C" {
#endif

int cast_cc_set_key(
	CAST_KEY *cx, 
	const void *rawKey, 
	size_t keyLength,
	int forEncrypt);

void cast_cc_encrypt(CAST_KEY *cx, const void *blockIn, void *blockOut);
void cast_cc_decrypt(CAST_KEY *cx, const void *blockIn, void *blockOut);

#ifdef  __cplusplus
}
#endif

#endif	/* _CC_CCCAST_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































Deleted Source/CommonCryptoSPI/ccRC2.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef	_CC_RC2_H_
#define _CC_RC2_H_

#include <CommonCrypto/CommonCryptoPriv.h>
#include "rc2.h"
#include <sys/types.h>

#ifdef  __cplusplus
extern "C" {
#endif

int rc2_cc_set_key(RC2_Schedule *cx, const void *rawKey, size_t keyLength);
void rc2_cc_encrypt(RC2_Schedule *cx, const void *blockIn, void *blockOut);
void rc2_cc_decrypt(RC2_Schedule *cx, const void *blockIn, void *blockOut);

#ifdef  __cplusplus
}
#endif

#endif	/* _CC_RC2_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































Added Source/CommonCryptoSPI/lionCompat.h.













































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
 * Copyright © 2011 by Apple, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 *
 */


#if !defined( _COMMON_CRYPTO_LION_COMPAT_ )
#define _COMMON_CRYPTO_LION_COMPAT_

#include <Availability.h>
#include <CommonCrypto/CommonDigestSPI.h>
#include <CommonCrypto/CommonCryptor.h>

typedef struct
{
	CCCryptorRef	cref;
} CAST_KEY;


size_t
CCDigestBlockSize(CCDigestRef ctx)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_NA);

// might be needed.
void CAST_ecb_encrypt(const unsigned char *in,unsigned char *out, CAST_KEY *key, int enc)
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA);
		


// might be needed.
void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data)
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA);


#endif	/* _COMMON_CRYPTO_LION_COMPAT_ */

Deleted Source/CommonCryptoSPI/opensslDES.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/* crypto/des/des.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

/* 
 * This is pared-down version of <openssl/des.h>, shorn of 
 * everything except the bare-bones single-block encrypt/decrypt
 * routine DES_encrypt1() and the types and #defines needed to use
 * it. Plus it has the shim code needed to use this function in 
 * CommonEncryption. 
 */
 
#ifndef	_CC_OPENSSL_DES_H_
#define _CC_OPENSSL_DES_H_

#include <Availability.h>
#include <AvailabilityMacros.h>
#include <CommonCrypto/CommonCryptoPriv.h>

#define OPENSSL_DISABLE_OLD_DES_SUPPORT

// #include <ccOpenssl/des_locl.h>
#include <stdint.h>
#include <sys/types.h>

#ifdef __cplusplus
extern "C" {
#endif

/* 
 * These typedefs and defines moved here from des.h to allow
 * this interface to be exported (via private SPI) to the CSP.
 */
typedef unsigned char DES_cblock[8];
typedef /* const */ unsigned char const_DES_cblock[8];
/* With "const", gcc 2.8.1 on Solaris thinks that DES_cblock *
 * and const_DES_cblock * are incompatible pointer types. */

#undef	DES_LONG
#define DES_LONG	uint32_t

typedef struct DES_ks
    {
    union
	{
	DES_cblock cblock;
	/* make sure things are correct size on machines with
	 * 8 byte longs */
	DES_LONG deslong[2];
	} ks[16];
    } DES_key_schedule;


__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
int osDesSetkey(DES_key_schedule *dinst, char *key, size_t keyLength,
	int forEencrypt);

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void osDesEncrypt(DES_key_schedule *ks, 
	const_DES_cblock *input, 
	DES_cblock *output);

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void osDesDecrypt(DES_key_schedule *ks, 
	const_DES_cblock *input, 
	DES_cblock *output);

/* triple DES */
typedef struct {
	DES_key_schedule	ks[3];
} DES3_Schedule;

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
int osDes3Setkey(DES3_Schedule *dinst, char *key, size_t keyLength,
	int forEencrypt);

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void osDes3Encrypt(DES3_Schedule *ks, 
	const_DES_cblock *input, 
	DES_cblock *output);

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void osDes3Decrypt(DES3_Schedule *ks, 
	const_DES_cblock *input, 
	DES_cblock *output);

#ifdef __cplusplus
}
#endif

#endif	/* _CC_OPENSSL_DES_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































Deleted Source/CommonCryptoSPI/rc2.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

#ifndef	_RC2_H_
#define _RC2_H_

typedef struct rc2_key_st {
    unsigned short xkey[64];
} RC2_Schedule;

/**********************************************************************\ 
* Expand a variable-length user key (between 1 and 128 bytes) to a     * 
* 64-short working rc2 key, of at most "bits" effective key bits.      * 
* The effective key bits parameter looks like an export control hack.  * 
* For normal use, it should always be set to 1024.  For convenience,   * 
* zero is accepted as an alias for 1024.                               * 
\**********************************************************************/ 
void rc2_keyschedule( RC2_Schedule *key_schedule, 
                      const unsigned char *key, 
                      unsigned len, 
                      unsigned bits );

/**********************************************************************\ 
* Encrypt an 8-byte block of plaintext using the given key.            * 
\**********************************************************************/ 
void rc2_encrypt( const RC2_Schedule *key_schedule, 
                  const unsigned char *plain, 
                  unsigned char *cipher );

/**********************************************************************\ 
* Decrypt an 8-byte block of ciphertext using the given key.           * 
\**********************************************************************/ 
void rc2_decrypt( const RC2_Schedule *key_schedule, 
                  unsigned char *plain, 
                  const unsigned char *cipher );

#endif /* _RC2_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































Deleted Source/Digest/md2_dgst.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/* crypto/md2/md2_dgst.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "CommonDigestPriv.h"
#ifndef	 _APPLE_COMMON_CRYPTO_
#include <openssl/md2.h>
#include "opensslv.h"
#endif

#ifndef	_APPLE_COMMON_CRYPTO_
const char *MD2_version="MD2" OPENSSL_VERSION_PTEXT;
#endif

/* Implemented from RFC1319 The MD2 Message-Digest Algorithm
 */

#define UCHAR	unsigned char

static void md2_block(MD2_CTX *c, const unsigned char *d);
/* The magic S table - I have converted it to hex since it is
 * basically just a random byte string. */
static const MD2_INT S[256]={
	0x29, 0x2E, 0x43, 0xC9, 0xA2, 0xD8, 0x7C, 0x01,
	0x3D, 0x36, 0x54, 0xA1, 0xEC, 0xF0, 0x06, 0x13,
	0x62, 0xA7, 0x05, 0xF3, 0xC0, 0xC7, 0x73, 0x8C,
	0x98, 0x93, 0x2B, 0xD9, 0xBC, 0x4C, 0x82, 0xCA,
	0x1E, 0x9B, 0x57, 0x3C, 0xFD, 0xD4, 0xE0, 0x16,
	0x67, 0x42, 0x6F, 0x18, 0x8A, 0x17, 0xE5, 0x12,
	0xBE, 0x4E, 0xC4, 0xD6, 0xDA, 0x9E, 0xDE, 0x49,
	0xA0, 0xFB, 0xF5, 0x8E, 0xBB, 0x2F, 0xEE, 0x7A,
	0xA9, 0x68, 0x79, 0x91, 0x15, 0xB2, 0x07, 0x3F,
	0x94, 0xC2, 0x10, 0x89, 0x0B, 0x22, 0x5F, 0x21,
	0x80, 0x7F, 0x5D, 0x9A, 0x5A, 0x90, 0x32, 0x27,
	0x35, 0x3E, 0xCC, 0xE7, 0xBF, 0xF7, 0x97, 0x03,
	0xFF, 0x19, 0x30, 0xB3, 0x48, 0xA5, 0xB5, 0xD1,
	0xD7, 0x5E, 0x92, 0x2A, 0xAC, 0x56, 0xAA, 0xC6,
	0x4F, 0xB8, 0x38, 0xD2, 0x96, 0xA4, 0x7D, 0xB6,
	0x76, 0xFC, 0x6B, 0xE2, 0x9C, 0x74, 0x04, 0xF1,
	0x45, 0x9D, 0x70, 0x59, 0x64, 0x71, 0x87, 0x20,
	0x86, 0x5B, 0xCF, 0x65, 0xE6, 0x2D, 0xA8, 0x02,
	0x1B, 0x60, 0x25, 0xAD, 0xAE, 0xB0, 0xB9, 0xF6,
	0x1C, 0x46, 0x61, 0x69, 0x34, 0x40, 0x7E, 0x0F,
	0x55, 0x47, 0xA3, 0x23, 0xDD, 0x51, 0xAF, 0x3A,
	0xC3, 0x5C, 0xF9, 0xCE, 0xBA, 0xC5, 0xEA, 0x26,
	0x2C, 0x53, 0x0D, 0x6E, 0x85, 0x28, 0x84, 0x09,
	0xD3, 0xDF, 0xCD, 0xF4, 0x41, 0x81, 0x4D, 0x52,
	0x6A, 0xDC, 0x37, 0xC8, 0x6C, 0xC1, 0xAB, 0xFA,
	0x24, 0xE1, 0x7B, 0x08, 0x0C, 0xBD, 0xB1, 0x4A,
	0x78, 0x88, 0x95, 0x8B, 0xE3, 0x63, 0xE8, 0x6D,
	0xE9, 0xCB, 0xD5, 0xFE, 0x3B, 0x00, 0x1D, 0x39,
	0xF2, 0xEF, 0xB7, 0x0E, 0x66, 0x58, 0xD0, 0xE4,
	0xA6, 0x77, 0x72, 0xF8, 0xEB, 0x75, 0x4B, 0x0A,
	0x31, 0x44, 0x50, 0xB4, 0x8F, 0xED, 0x1F, 0x1A,
	0xDB, 0x99, 0x8D, 0x33, 0x9F, 0x11, 0x83, 0x14,
	};

#ifndef	_APPLE_COMMON_CRYPTO_
const char *MD2_options(void)
	{
	if (sizeof(MD2_INT) == 1)
		return("md2(char)");
	else
		return("md2(int)");
	}
#endif

int CC_MD2_Init(MD2_CTX *c)
	{
	c->num=0;
	memset(c->state,0,MD2_BLOCK*sizeof(MD2_INT));
	memset(c->cksm,0,MD2_BLOCK*sizeof(MD2_INT));
	memset(c->data,0,MD2_BLOCK);
    return 1;
	}

int CC_MD2_Update(MD2_CTX *c, const void *inData, CC_LONG len)
	{
    const unsigned char *data = (const unsigned char *)inData;
	register UCHAR *p;

	if (len == 0) return 1;

	p=c->data;
	if (c->num != 0)
		{
		if ((c->num+len) >= MD2_BLOCK)
			{
			memcpy(&(p[c->num]),data,MD2_BLOCK-c->num);
			md2_block(c,c->data);
			data+=(MD2_BLOCK - c->num);
			len-=(MD2_BLOCK - c->num);
			c->num=0;
			/* drop through and do the rest */
			}
		else
			{
			memcpy(&(p[c->num]),data,(int)len);
			/* data+=len; */
			c->num+=(int)len;
			return 1;
			}
		}
	/* we now can process the input data in blocks of MD2_BLOCK
	 * chars and save the leftovers to c->data. */
	while (len >= MD2_BLOCK)
		{
		md2_block(c,data);
		data+=MD2_BLOCK;
		len-=MD2_BLOCK;
		}
	memcpy(p,data,(int)len);
	c->num=(int)len;
    return 1;
	}

static void md2_block(MD2_CTX *c, const unsigned char *d)
	{
	register MD2_INT t,*sp1,*sp2;
	register int i,j;
	MD2_INT state[48];

	sp1=c->state;
	sp2=c->cksm;
	j=sp2[MD2_BLOCK-1];
	for (i=0; i<16; i++)
		{
		state[i]=sp1[i];
		state[i+16]=t=d[i];
		state[i+32]=(t^sp1[i]);
		j=sp2[i]^=S[t^j];
		}
	t=0;
	for (i=0; i<18; i++)
		{
		for (j=0; j<48; j+=8)
			{
			t= state[j+ 0]^=S[t];
			t= state[j+ 1]^=S[t];
			t= state[j+ 2]^=S[t];
			t= state[j+ 3]^=S[t];
			t= state[j+ 4]^=S[t];
			t= state[j+ 5]^=S[t];
			t= state[j+ 6]^=S[t];
			t= state[j+ 7]^=S[t];
			}
		t=(t+i)&0xff;
		}
	memcpy(sp1,state,16*sizeof(MD2_INT));
	memset(state,0,48*sizeof(MD2_INT));
	}

int CC_MD2_Final(unsigned char *md, MD2_CTX *c)
	{
	int i,v;
	register UCHAR *cp;
	register MD2_INT *p1,*p2;

	cp=c->data;
	p1=c->state;
	p2=c->cksm;
	v=MD2_BLOCK-c->num;
	for (i=c->num; i<MD2_BLOCK; i++)
		cp[i]=(UCHAR)v;

	md2_block(c,cp);

	for (i=0; i<MD2_BLOCK; i++)
		cp[i]=(UCHAR)p2[i];
	md2_block(c,cp);

	for (i=0; i<16; i++)
		md[i]=(UCHAR)(p1[i]&0xff);
	memset((char *)&c,0,sizeof(c));
    return 1;
	}

#ifdef	_APPLE_COMMON_CRYPTO_

CC_DIGEST_ONE_SHOT(CC_MD2, CC_MD2_CTX, CC_MD2_Init, CC_MD2_Update, CC_MD2_Final)

#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































Deleted Source/Digest/md32_common.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
/* crypto/md32_common.h */
/* ====================================================================
 * Copyright (c) 1999-2002 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    licensing@OpenSSL.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

/*
 * This is a generic 32 bit "collector" for message digest algorithms.
 * Whenever needed it collects input character stream into chunks of
 * 32 bit values and invokes a block function that performs actual hash
 * calculations.
 *
 * Porting guide.
 *
 * Obligatory macros:
 *
 * DATA_ORDER_IS_BIG_ENDIAN or DATA_ORDER_IS_LITTLE_ENDIAN
 *	this macro defines byte order of input stream.
 * HASH_CBLOCK
 *	size of a unit chunk HASH_BLOCK operates on.
 * HASH_LONG
 *	has to be at lest 32 bit wide, if it's wider, then
 *	HASH_LONG_LOG2 *has to* be defined along
 * HASH_CTX
 *	context structure that at least contains following
 *	members:
 *		typedef struct {
 *			...
 *			HASH_LONG	Nl,Nh;
 *			HASH_LONG	data[HASH_LBLOCK];
 *			int		num;
 *			...
 *			} HASH_CTX;
 * HASH_UPDATE
 *	name of "Update" function, implemented here.
 * HASH_TRANSFORM
 *	name of "Transform" function, implemented here.
 * HASH_FINAL
 *	name of "Final" function, implemented here.
 * HASH_BLOCK_HOST_ORDER
 *	name of "block" function treating *aligned* input message
 *	in host byte order, implemented externally.
 * HASH_BLOCK_DATA_ORDER
 *	name of "block" function treating *unaligned* input message
 *	in original (data) byte order, implemented externally (it
 *	actually is optional if data and host are of the same
 *	"endianess").
 * HASH_MAKE_STRING
 *	macro convering context variables to an ASCII hash string.
 *
 * Optional macros:
 *
 * B_ENDIAN or L_ENDIAN
 *	defines host byte-order.
 * HASH_LONG_LOG2
 *	defaults to 2 if not states otherwise.
 * HASH_LBLOCK
 *	assumed to be HASH_CBLOCK/4 if not stated otherwise.
 * HASH_BLOCK_DATA_ORDER_ALIGNED
 *	alternative "block" function capable of treating
 *	aligned input message in original (data) order,
 *	implemented externally.
 *
 * MD5 example:
 *
 *	#define DATA_ORDER_IS_LITTLE_ENDIAN
 *
 *	#define HASH_LONG		MD5_LONG
 *	#define HASH_LONG_LOG2		MD5_LONG_LOG2
 *	#define HASH_CTX		MD5_CTX
 *	#define HASH_CBLOCK		MD5_CBLOCK
 *	#define HASH_LBLOCK		MD5_LBLOCK
 *	#define HASH_UPDATE		MD5_Update
 *	#define HASH_TRANSFORM		MD5_Transform
 *	#define HASH_FINAL		MD5_Final
 *	#define HASH_BLOCK_HOST_ORDER	md5_block_host_order
 *	#define HASH_BLOCK_DATA_ORDER	md5_block_data_order
 *
 *					<appro@fy.chalmers.se>
 */

#if !defined(DATA_ORDER_IS_BIG_ENDIAN) && !defined(DATA_ORDER_IS_LITTLE_ENDIAN)
#error "DATA_ORDER must be defined!"
#endif

#ifndef HASH_CBLOCK
#error "HASH_CBLOCK must be defined!"
#endif
#ifndef HASH_LONG
#error "HASH_LONG must be defined!"
#endif
#ifndef HASH_CTX
#error "HASH_CTX must be defined!"
#endif

#ifndef HASH_UPDATE
#error "HASH_UPDATE must be defined!"
#endif
#ifndef HASH_TRANSFORM
#error "HASH_TRANSFORM must be defined!"
#endif
#ifndef HASH_FINAL
#error "HASH_FINAL must be defined!"
#endif

#ifndef HASH_BLOCK_HOST_ORDER
#error "HASH_BLOCK_HOST_ORDER must be defined!"
#endif

#if 0
/*
 * Moved below as it's required only if HASH_BLOCK_DATA_ORDER_ALIGNED
 * isn't defined.
 */
#ifndef HASH_BLOCK_DATA_ORDER
#error "HASH_BLOCK_DATA_ORDER must be defined!"
#endif
#endif

#ifndef HASH_LBLOCK
#define HASH_LBLOCK	(HASH_CBLOCK/4)
#endif

#ifndef HASH_LONG_LOG2
#define HASH_LONG_LOG2	2
#endif

/*
 * Engage compiler specific rotate intrinsic function if available.
 */
#undef ROTATE
#ifndef PEDANTIC
# if 0 /* defined(_MSC_VER) */
#  define ROTATE(a,n)	_lrotl(a,n)
# elif defined(__MWERKS__)
#  if defined(__POWERPC__)
#   define ROTATE(a,n)	__rlwinm(a,n,0,31)
#  elif defined(__MC68K__)
    /* Motorola specific tweak. <appro@fy.chalmers.se> */
#   define ROTATE(a,n)	( n<24 ? __rol(a,n) : __ror(a,32-n) )
#  else
#   define ROTATE(a,n)	__rol(a,n)
#  endif
# elif defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
  /*
   * Some GNU C inline assembler templates. Note that these are
   * rotates by *constant* number of bits! But that's exactly
   * what we need here...
   *
   * 					<appro@fy.chalmers.se>
   */
#  if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)
#   define ROTATE(a,n)	({ register unsigned int ret;	\
				asm (			\
				"roll %1,%0"		\
				: "=r"(ret)		\
				: "I"(n), "0"((unsigned int)a)	\
				: "cc");		\
			   ret;				\
			})
#  elif defined(__powerpc) || defined(__ppc)
#   define ROTATE(a,n)	({ register unsigned int ret;	\
				asm (			\
				"rlwinm %0,%1,%2,0,31"	\
				: "=r"(ret)		\
				: "r"(a), "I"(n));	\
			   ret;				\
			})
#  endif
# endif

/*
 * Engage compiler specific "fetch in reverse byte order"
 * intrinsic function if available.
 */
# if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
  /* some GNU C inline assembler templates by <appro@fy.chalmers.se> */
#  if (defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)) && !defined(I386_ONLY)
#   define BE_FETCH32(a)	({ register unsigned int l=(a);\
				asm (			\
				"bswapl %0"		\
				: "=r"(l) : "0"(l));	\
			  l;				\
			})
#  elif defined(__powerpc)
#   define LE_FETCH32(a)	({ register unsigned int l;	\
				asm (			\
				"lwbrx %0,0,%1"		\
				: "=r"(l)		\
				: "r"(a));		\
			   l;				\
			})

#  elif defined(__sparc) && defined(OPENSSL_SYS_ULTRASPARC)
#  define LE_FETCH32(a)	({ register unsigned int l;		\
				asm (				\
				"lda [%1]#ASI_PRIMARY_LITTLE,%0"\
				: "=r"(l)			\
				: "r"(a));			\
			   l;					\
			})
#  endif
# endif
#endif /* PEDANTIC */

#if HASH_LONG_LOG2==2	/* Engage only if sizeof(HASH_LONG)== 4 */
/* A nice byte order reversal from Wei Dai <weidai@eskimo.com> */
#ifdef ROTATE
/* 5 instructions with rotate instruction, else 9 */
#define REVERSE_FETCH32(a,l)	(					\
		l=*(const HASH_LONG *)(a),				\
		((ROTATE(l,8)&0x00FF00FF)|(ROTATE((l&0x00FF00FF),24)))	\
				)
#else
/* 6 instructions with rotate instruction, else 8 */
#define REVERSE_FETCH32(a,l)	(				\
		l=*(const HASH_LONG *)(a),			\
		l=(((l>>8)&0x00FF00FF)|((l&0x00FF00FF)<<8)),	\
		ROTATE(l,16)					\
				)
/*
 * Originally the middle line started with l=(((l&0xFF00FF00)>>8)|...
 * It's rewritten as above for two reasons:
 *	- RISCs aren't good at long constants and have to explicitely
 *	  compose 'em with several (well, usually 2) instructions in a
 *	  register before performing the actual operation and (as you
 *	  already realized:-) having same constant should inspire the
 *	  compiler to permanently allocate the only register for it;
 *	- most modern CPUs have two ALUs, but usually only one has
 *	  circuitry for shifts:-( this minor tweak inspires compiler
 *	  to schedule shift instructions in a better way...
 *
 *				<appro@fy.chalmers.se>
 */
#endif
#endif

#ifndef ROTATE
#define ROTATE(a,n)     (((a)<<(n))|(((a)&0xffffffff)>>(32-(n))))
#endif

/*
 * Make some obvious choices. E.g., HASH_BLOCK_DATA_ORDER_ALIGNED
 * and HASH_BLOCK_HOST_ORDER ought to be the same if input data
 * and host are of the same "endianess". It's possible to mask
 * this with blank #define HASH_BLOCK_DATA_ORDER though...
 *
 *				<appro@fy.chalmers.se>
 */
#if defined(B_ENDIAN)
#  if defined(DATA_ORDER_IS_BIG_ENDIAN)
#    if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED) && HASH_LONG_LOG2==2
#      define HASH_BLOCK_DATA_ORDER_ALIGNED	HASH_BLOCK_HOST_ORDER
#    endif
#  elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
#    ifndef HOST_FETCH32
#      ifdef LE_FETCH32
#        define HOST_FETCH32(p,l)	LE_FETCH32(p)
#      elif defined(REVERSE_FETCH32)
#        define HOST_FETCH32(p,l)	REVERSE_FETCH32(p,l)
#      endif
#    endif
#  endif
#elif defined(L_ENDIAN)
#  if defined(DATA_ORDER_IS_LITTLE_ENDIAN)
#    if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED) && HASH_LONG_LOG2==2
#      define HASH_BLOCK_DATA_ORDER_ALIGNED	HASH_BLOCK_HOST_ORDER
#    endif
#  elif defined(DATA_ORDER_IS_BIG_ENDIAN)
#    ifndef HOST_FETCH32
#      ifdef BE_FETCH32
#        define HOST_FETCH32(p,l)	BE_FETCH32(p)
#      elif defined(REVERSE_FETCH32)
#        define HOST_FETCH32(p,l)	REVERSE_FETCH32(p,l)
#      endif
#    endif
#  endif
#endif

#if !defined(HASH_BLOCK_DATA_ORDER_ALIGNED)
#ifndef HASH_BLOCK_DATA_ORDER
#error "HASH_BLOCK_DATA_ORDER must be defined!"
#endif
#endif

#if defined(DATA_ORDER_IS_BIG_ENDIAN)

#define HOST_c2l(c,l)	(l =(((unsigned long)(*((c)++)))<<24),		\
			 l|=(((unsigned long)(*((c)++)))<<16),		\
			 l|=(((unsigned long)(*((c)++)))<< 8),		\
			 l|=(((unsigned long)(*((c)++)))    ),		\
			 l)
#define HOST_p_c2l(c,l,n)	{					\
			switch (n) {					\
			case 0: l =((unsigned long)(*((c)++)))<<24;	\
			case 1: l|=((unsigned long)(*((c)++)))<<16;	\
			case 2: l|=((unsigned long)(*((c)++)))<< 8;	\
			case 3: l|=((unsigned long)(*((c)++)));		\
				} }
#define HOST_p_c2l_p(c,l,sc,len) {					\
			switch (sc) {					\
			case 0: l =((unsigned long)(*((c)++)))<<24;	\
				if (--len == 0) break;			\
			case 1: l|=((unsigned long)(*((c)++)))<<16;	\
				if (--len == 0) break;			\
			case 2: l|=((unsigned long)(*((c)++)))<< 8;	\
				} }
/* NOTE the pointer is not incremented at the end of this */
#define HOST_c2l_p(c,l,n)	{					\
			l=0; (c)+=n;					\
			switch (n) {					\
			case 3: l =((unsigned long)(*(--(c))))<< 8;	\
			case 2: l|=((unsigned long)(*(--(c))))<<16;	\
			case 1: l|=((unsigned long)(*(--(c))))<<24;	\
				} }
#define HOST_l2c(l,c)	(*((c)++)=(unsigned char)(((l)>>24)&0xff),	\
			 *((c)++)=(unsigned char)(((l)>>16)&0xff),	\
			 *((c)++)=(unsigned char)(((l)>> 8)&0xff),	\
			 *((c)++)=(unsigned char)(((l)    )&0xff),	\
			 l)

#elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)

#define HOST_c2l(c,l)	(l =(((unsigned long)(*((c)++)))    ),		\
			 l|=(((unsigned long)(*((c)++)))<< 8),		\
			 l|=(((unsigned long)(*((c)++)))<<16),		\
			 l|=(((unsigned long)(*((c)++)))<<24),		\
			 l)
#define HOST_p_c2l(c,l,n)	{					\
			switch (n) {					\
			case 0: l =((unsigned long)(*((c)++)));		\
			case 1: l|=((unsigned long)(*((c)++)))<< 8;	\
			case 2: l|=((unsigned long)(*((c)++)))<<16;	\
			case 3: l|=((unsigned long)(*((c)++)))<<24;	\
				} }
#define HOST_p_c2l_p(c,l,sc,len) {					\
			switch (sc) {					\
			case 0: l =((unsigned long)(*((c)++)));		\
				if (--len == 0) break;			\
			case 1: l|=((unsigned long)(*((c)++)))<< 8;	\
				if (--len == 0) break;			\
			case 2: l|=((unsigned long)(*((c)++)))<<16;	\
				} }
/* NOTE the pointer is not incremented at the end of this */
#define HOST_c2l_p(c,l,n)	{					\
			l=0; (c)+=n;					\
			switch (n) {					\
			case 3: l =((unsigned long)(*(--(c))))<<16;	\
			case 2: l|=((unsigned long)(*(--(c))))<< 8;	\
			case 1: l|=((unsigned long)(*(--(c))));		\
				} }
#define HOST_l2c(l,c)	(*((c)++)=(unsigned char)(((l)    )&0xff),	\
			 *((c)++)=(unsigned char)(((l)>> 8)&0xff),	\
			 *((c)++)=(unsigned char)(((l)>>16)&0xff),	\
			 *((c)++)=(unsigned char)(((l)>>24)&0xff),	\
			 l)

#endif

/*
 * Time for some action:-)
 */

int HASH_UPDATE (HASH_CTX *c, const void *data_, CC_LONG len)
	{
	const unsigned char *data=data_;
	register HASH_LONG * p;
	register unsigned long l;
	int sw,sc,ew,ec;

	if (len==0) return 1;

	l=(c->Nl+(len<<3))&0xffffffffL;
	/* 95-05-24 eay Fixed a bug with the overflow handling, thanks to
	 * Wei Dai <weidai@eskimo.com> for pointing it out. */
	if (l < c->Nl) /* overflow */
		c->Nh++;
	c->Nh+=(len>>29);
	c->Nl=l;

	if (c->num != 0)
		{
		p=c->data;
		sw=c->num>>2;
		sc=c->num&0x03;

		if ((c->num+len) >= HASH_CBLOCK)
			{
			l=p[sw]; HOST_p_c2l(data,l,sc); p[sw++]=l;
			for (; sw<HASH_LBLOCK; sw++)
				{
				HOST_c2l(data,l); p[sw]=l;
				}
			HASH_BLOCK_HOST_ORDER (c,p,1);
			len-=(HASH_CBLOCK-c->num);
			c->num=0;
			/* drop through and do the rest */
			}
		else
			{
			c->num+=len;
			if ((sc+len) < 4) /* ugly, add char's to a word */
				{
				l=p[sw]; HOST_p_c2l_p(data,l,sc,len); p[sw]=l;
				}
			else
				{
				ew=(c->num>>2);
				ec=(c->num&0x03);
				if (sc)
					l=p[sw];
				HOST_p_c2l(data,l,sc);
				p[sw++]=l;
				for (; sw < ew; sw++)
					{
					HOST_c2l(data,l); p[sw]=l;
					}
				if (ec)
					{
					HOST_c2l_p(data,l,ec); p[sw]=l;
					}
				}
			return 1;
			}
		}

	sw=len/HASH_CBLOCK;
	if (sw > 0)
		{
#if defined(HASH_BLOCK_DATA_ORDER_ALIGNED)
		/*
		 * Note that HASH_BLOCK_DATA_ORDER_ALIGNED gets defined
		 * only if sizeof(HASH_LONG)==4.
		 */
		if ((((unsigned long)data)%4) == 0)
			{
			/* data is properly aligned so that we can cast it: */
			HASH_BLOCK_DATA_ORDER_ALIGNED (c,(HASH_LONG *)data,sw);
			sw*=HASH_CBLOCK;
			data+=sw;
			len-=sw;
			}
		else
#if !defined(HASH_BLOCK_DATA_ORDER)
			while (sw--)
				{
				memcpy (p=c->data,data,HASH_CBLOCK);
				HASH_BLOCK_DATA_ORDER_ALIGNED(c,p,1);
				data+=HASH_CBLOCK;
				len-=HASH_CBLOCK;
				}
#endif
#endif
#if defined(HASH_BLOCK_DATA_ORDER)
			{
			HASH_BLOCK_DATA_ORDER(c,data,sw);
			sw*=HASH_CBLOCK;
			data+=sw;
			len-=sw;
			}
#endif
		}

	if (len!=0)
		{
		p = c->data;
		c->num = len;
		ew=len>>2;	/* words to copy */
		ec=len&0x03;
		for (; ew; ew--,p++)
			{
			HOST_c2l(data,l); *p=l;
			}
		HOST_c2l_p(data,l,ec);
		*p=l;
		}
	return 1;
	}

void HASH_TRANSFORM (HASH_CTX *c, const unsigned char *data);

void HASH_TRANSFORM (HASH_CTX *c, const unsigned char *data)
	{
#if defined(HASH_BLOCK_DATA_ORDER_ALIGNED)
	if ((((unsigned long)data)%4) == 0)
		/* data is properly aligned so that we can cast it: */
		HASH_BLOCK_DATA_ORDER_ALIGNED (c,(HASH_LONG *)data,1);
	else
#if !defined(HASH_BLOCK_DATA_ORDER)
		{
		memcpy (c->data,data,HASH_CBLOCK);
		HASH_BLOCK_DATA_ORDER_ALIGNED (c,c->data,1);
		}
#endif
#endif
#if defined(HASH_BLOCK_DATA_ORDER)
	HASH_BLOCK_DATA_ORDER (c,data,1);
#endif
	}


int HASH_FINAL (unsigned char *md, HASH_CTX *c)
	{
	register HASH_LONG *p;
	register unsigned long l;
	register int i,j;
	static const unsigned char end[4]={0x80,0x00,0x00,0x00};
	const unsigned char *cp=end;

	/* c->num should definitly have room for at least one more byte. */
	p=c->data;
	i=c->num>>2;
	j=c->num&0x03;

#if 0
	/* purify often complains about the following line as an
	 * Uninitialized Memory Read.  While this can be true, the
	 * following p_c2l macro will reset l when that case is true.
	 * This is because j&0x03 contains the number of 'valid' bytes
	 * already in p[i].  If and only if j&0x03 == 0, the UMR will
	 * occur but this is also the only time p_c2l will do
	 * l= *(cp++) instead of l|= *(cp++)
	 * Many thanks to Alex Tang <altitude@cic.net> for pickup this
	 * 'potential bug' */
#ifdef PURIFY
	if (j==0) p[i]=0; /* Yeah, but that's not the way to fix it:-) */
#endif
	l=p[i];
#else
	l = (j==0) ? 0 : p[i];
#endif
	HOST_p_c2l(cp,l,j); p[i++]=l; /* i is the next 'undefined word' */

	if (i>(HASH_LBLOCK-2)) /* save room for Nl and Nh */
		{
		if (i<HASH_LBLOCK) p[i]=0;
		HASH_BLOCK_HOST_ORDER (c,p,1);
		i=0;
		}
	for (; i<(HASH_LBLOCK-2); i++)
		p[i]=0;

#if   defined(DATA_ORDER_IS_BIG_ENDIAN)
	p[HASH_LBLOCK-2]=c->Nh;
	p[HASH_LBLOCK-1]=c->Nl;
#elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
	p[HASH_LBLOCK-2]=c->Nl;
	p[HASH_LBLOCK-1]=c->Nh;
#endif
	HASH_BLOCK_HOST_ORDER (c,p,1);

#ifndef HASH_MAKE_STRING
#error "HASH_MAKE_STRING must be defined!"
#else
	HASH_MAKE_STRING(c,md);
#endif

	c->num=0;
	/* clear stuff, HASH_BLOCK may be leaving some stuff on the stack
	 * but I'm not worried :-)
	OPENSSL_cleanse((void *)c,sizeof(HASH_CTX));
	 */
	return 1;
	}

#ifndef MD32_REG_T
#define MD32_REG_T long
/*
 * This comment was originaly written for MD5, which is why it
 * discusses A-D. But it basically applies to all 32-bit digests,
 * which is why it was moved to common header file.
 *
 * In case you wonder why A-D are declared as long and not
 * as MD5_LONG. Doing so results in slight performance
 * boost on LP64 architectures. The catch is we don't
 * really care if 32 MSBs of a 64-bit register get polluted
 * with eventual overflows as we *save* only 32 LSBs in
 * *either* case. Now declaring 'em long excuses the compiler
 * from keeping 32 MSBs zeroed resulting in 13% performance
 * improvement under SPARC Solaris7/64 and 5% under AlphaLinux.
 * Well, to be honest it should say that this *prevents* 
 * performance degradation.
 *				<appro@fy.chalmers.se>
 * Apparently there're LP64 compilers that generate better
 * code if A-D are declared int. Most notably GCC-x86_64
 * generates better code.
 *				<appro@fy.chalmers.se>
 */
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/Digest/md4_dgst.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/* crypto/md4/md4_dgst.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <stdio.h>
#include "CommonDigestPriv.h"
#include "md4_locl.h"
#ifndef		_APPLE_COMMON_CRYPTO_
#include <openssl/opensslv.h>

const char *MD4_version="MD4" OPENSSL_VERSION_PTEXT;
#endif		/* _APPLE_COMMON_CRYPTO_ */


/* Implemented from RFC1186 The MD4 Message-Digest Algorithm
 */

#define INIT_DATA_A (unsigned long)0x67452301L
#define INIT_DATA_B (unsigned long)0xefcdab89L
#define INIT_DATA_C (unsigned long)0x98badcfeL
#define INIT_DATA_D (unsigned long)0x10325476L

int CC_MD4_Init(MD4_CTX *c)
	{
	c->A=INIT_DATA_A;
	c->B=INIT_DATA_B;
	c->C=INIT_DATA_C;
	c->D=INIT_DATA_D;
	c->Nl=0;
	c->Nh=0;
	c->num=0;
	return 1;
	}

#ifndef md4_block_host_order
__private_extern__ void md4_block_host_order (MD4_CTX *c, const void *data, int num)
	{
	const MD4_LONG *X=data;
	register unsigned MD32_REG_T A,B,C,D;

	A=c->A;
	B=c->B;
	C=c->C;
	D=c->D;

	for (;num--;X+=HASH_LBLOCK)
		{
	/* Round 0 */
	R0(A,B,C,D,X[ 0], 3,0);
	R0(D,A,B,C,X[ 1], 7,0);
	R0(C,D,A,B,X[ 2],11,0);
	R0(B,C,D,A,X[ 3],19,0);
	R0(A,B,C,D,X[ 4], 3,0);
	R0(D,A,B,C,X[ 5], 7,0);
	R0(C,D,A,B,X[ 6],11,0);
	R0(B,C,D,A,X[ 7],19,0);
	R0(A,B,C,D,X[ 8], 3,0);
	R0(D,A,B,C,X[ 9], 7,0);
	R0(C,D,A,B,X[10],11,0);
	R0(B,C,D,A,X[11],19,0);
	R0(A,B,C,D,X[12], 3,0);
	R0(D,A,B,C,X[13], 7,0);
	R0(C,D,A,B,X[14],11,0);
	R0(B,C,D,A,X[15],19,0);
	/* Round 1 */
	R1(A,B,C,D,X[ 0], 3,0x5A827999L);
	R1(D,A,B,C,X[ 4], 5,0x5A827999L);
	R1(C,D,A,B,X[ 8], 9,0x5A827999L);
	R1(B,C,D,A,X[12],13,0x5A827999L);
	R1(A,B,C,D,X[ 1], 3,0x5A827999L);
	R1(D,A,B,C,X[ 5], 5,0x5A827999L);
	R1(C,D,A,B,X[ 9], 9,0x5A827999L);
	R1(B,C,D,A,X[13],13,0x5A827999L);
	R1(A,B,C,D,X[ 2], 3,0x5A827999L);
	R1(D,A,B,C,X[ 6], 5,0x5A827999L);
	R1(C,D,A,B,X[10], 9,0x5A827999L);
	R1(B,C,D,A,X[14],13,0x5A827999L);
	R1(A,B,C,D,X[ 3], 3,0x5A827999L);
	R1(D,A,B,C,X[ 7], 5,0x5A827999L);
	R1(C,D,A,B,X[11], 9,0x5A827999L);
	R1(B,C,D,A,X[15],13,0x5A827999L);
	/* Round 2 */
	R2(A,B,C,D,X[ 0], 3,0x6ED9EBA1);
	R2(D,A,B,C,X[ 8], 9,0x6ED9EBA1);
	R2(C,D,A,B,X[ 4],11,0x6ED9EBA1);
	R2(B,C,D,A,X[12],15,0x6ED9EBA1);
	R2(A,B,C,D,X[ 2], 3,0x6ED9EBA1);
	R2(D,A,B,C,X[10], 9,0x6ED9EBA1);
	R2(C,D,A,B,X[ 6],11,0x6ED9EBA1);
	R2(B,C,D,A,X[14],15,0x6ED9EBA1);
	R2(A,B,C,D,X[ 1], 3,0x6ED9EBA1);
	R2(D,A,B,C,X[ 9], 9,0x6ED9EBA1);
	R2(C,D,A,B,X[ 5],11,0x6ED9EBA1);
	R2(B,C,D,A,X[13],15,0x6ED9EBA1);
	R2(A,B,C,D,X[ 3], 3,0x6ED9EBA1);
	R2(D,A,B,C,X[11], 9,0x6ED9EBA1);
	R2(C,D,A,B,X[ 7],11,0x6ED9EBA1);
	R2(B,C,D,A,X[15],15,0x6ED9EBA1);

	A = c->A += A;
	B = c->B += B;
	C = c->C += C;
	D = c->D += D;
		}
	}
#endif

#ifndef md4_block_data_order
#ifdef X
#undef X
#endif
__private_extern__ void md4_block_data_order (MD4_CTX *c, const void *data_, int num)
	{
	const unsigned char *data=data_;
	register unsigned MD32_REG_T A,B,C,D,l;
#ifndef MD32_XARRAY
	/* See comment in crypto/sha/sha_locl.h for details. */
	unsigned MD32_REG_T	XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7,
				XX8, XX9,XX10,XX11,XX12,XX13,XX14,XX15;
# define X(i)	XX##i
#else
	MD4_LONG XX[MD4_LBLOCK];
# define X(i)	XX[i]
#endif

	A=c->A;
	B=c->B;
	C=c->C;
	D=c->D;

	for (;num--;)
		{
	HOST_c2l(data,l); X( 0)=l;		HOST_c2l(data,l); X( 1)=l;
	/* Round 0 */
	R0(A,B,C,D,X( 0), 3,0);	HOST_c2l(data,l); X( 2)=l;
	R0(D,A,B,C,X( 1), 7,0);	HOST_c2l(data,l); X( 3)=l;
	R0(C,D,A,B,X( 2),11,0);	HOST_c2l(data,l); X( 4)=l;
	R0(B,C,D,A,X( 3),19,0);	HOST_c2l(data,l); X( 5)=l;
	R0(A,B,C,D,X( 4), 3,0);	HOST_c2l(data,l); X( 6)=l;
	R0(D,A,B,C,X( 5), 7,0);	HOST_c2l(data,l); X( 7)=l;
	R0(C,D,A,B,X( 6),11,0);	HOST_c2l(data,l); X( 8)=l;
	R0(B,C,D,A,X( 7),19,0);	HOST_c2l(data,l); X( 9)=l;
	R0(A,B,C,D,X( 8), 3,0);	HOST_c2l(data,l); X(10)=l;
	R0(D,A,B,C,X( 9), 7,0);	HOST_c2l(data,l); X(11)=l;
	R0(C,D,A,B,X(10),11,0);	HOST_c2l(data,l); X(12)=l;
	R0(B,C,D,A,X(11),19,0);	HOST_c2l(data,l); X(13)=l;
	R0(A,B,C,D,X(12), 3,0);	HOST_c2l(data,l); X(14)=l;
	R0(D,A,B,C,X(13), 7,0);	HOST_c2l(data,l); X(15)=l;
	R0(C,D,A,B,X(14),11,0);
	R0(B,C,D,A,X(15),19,0);
	/* Round 1 */
	R1(A,B,C,D,X( 0), 3,0x5A827999L);
	R1(D,A,B,C,X( 4), 5,0x5A827999L);
	R1(C,D,A,B,X( 8), 9,0x5A827999L);
	R1(B,C,D,A,X(12),13,0x5A827999L);
	R1(A,B,C,D,X( 1), 3,0x5A827999L);
	R1(D,A,B,C,X( 5), 5,0x5A827999L);
	R1(C,D,A,B,X( 9), 9,0x5A827999L);
	R1(B,C,D,A,X(13),13,0x5A827999L);
	R1(A,B,C,D,X( 2), 3,0x5A827999L);
	R1(D,A,B,C,X( 6), 5,0x5A827999L);
	R1(C,D,A,B,X(10), 9,0x5A827999L);
	R1(B,C,D,A,X(14),13,0x5A827999L);
	R1(A,B,C,D,X( 3), 3,0x5A827999L);
	R1(D,A,B,C,X( 7), 5,0x5A827999L);
	R1(C,D,A,B,X(11), 9,0x5A827999L);
	R1(B,C,D,A,X(15),13,0x5A827999L);
	/* Round 2 */
	R2(A,B,C,D,X( 0), 3,0x6ED9EBA1L);
	R2(D,A,B,C,X( 8), 9,0x6ED9EBA1L);
	R2(C,D,A,B,X( 4),11,0x6ED9EBA1L);
	R2(B,C,D,A,X(12),15,0x6ED9EBA1L);
	R2(A,B,C,D,X( 2), 3,0x6ED9EBA1L);
	R2(D,A,B,C,X(10), 9,0x6ED9EBA1L);
	R2(C,D,A,B,X( 6),11,0x6ED9EBA1L);
	R2(B,C,D,A,X(14),15,0x6ED9EBA1L);
	R2(A,B,C,D,X( 1), 3,0x6ED9EBA1L);
	R2(D,A,B,C,X( 9), 9,0x6ED9EBA1L);
	R2(C,D,A,B,X( 5),11,0x6ED9EBA1L);
	R2(B,C,D,A,X(13),15,0x6ED9EBA1L);
	R2(A,B,C,D,X( 3), 3,0x6ED9EBA1L);
	R2(D,A,B,C,X(11), 9,0x6ED9EBA1L);
	R2(C,D,A,B,X( 7),11,0x6ED9EBA1L);
	R2(B,C,D,A,X(15),15,0x6ED9EBA1L);

	A = c->A += A;
	B = c->B += B;
	C = c->C += C;
	D = c->D += D;
		}
	}
#endif

#ifdef undef
int printit(unsigned long *l)
	{
	int i,ii;

	for (i=0; i<2; i++)
		{
		for (ii=0; ii<8; ii++)
			{
			fprintf(stderr,"%08lx ",l[i*8+ii]);
			}
		fprintf(stderr,"\n");
		}
	}
#endif

#ifdef	_APPLE_COMMON_CRYPTO_

CC_DIGEST_ONE_SHOT(CC_MD4, CC_MD4_CTX, CC_MD4_Init, CC_MD4_Update, CC_MD4_Final)

#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































Deleted Source/Digest/md4_locl.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/* crypto/md4/md4_locl.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <stdlib.h>
#include <string.h>
#include "CommonDigestPriv.h"

#ifndef	_APPLE_COMMON_CRYPTO_
#include <openssl/opensslconf.h>
#include <openssl/md4.h>
#endif	/* _APPLE_COMMON_CRYPTO_ */

#ifndef MD4_LONG_LOG2
#define MD4_LONG_LOG2 2 /* default to 32 bits */
#endif

__private_extern__ void md4_block_host_order (MD4_CTX *c, const void *p,int num);
__private_extern__ void md4_block_data_order (MD4_CTX *c, const void *p,int num);

#if defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(__INTEL__) || defined(__x86_64__)
/*
 * *_block_host_order is expected to handle aligned data while
 * *_block_data_order - unaligned. As algorithm and host (x86)
 * are in this case of the same "endianness" these two are
 * otherwise indistinguishable. But normally you don't want to
 * call the same function because unaligned access in places
 * where alignment is expected is usually a "Bad Thing". Indeed,
 * on RISCs you get punished with BUS ERROR signal or *severe*
 * performance degradation. Intel CPUs are in turn perfectly
 * capable of loading unaligned data without such drastic side
 * effect. Yes, they say it's slower than aligned load, but no
 * exception is generated and therefore performance degradation
 * is *incomparable* with RISCs. What we should weight here is
 * costs of unaligned access against costs of aligning data.
 * According to my measurements allowing unaligned access results
 * in ~9% performance improvement on Pentium II operating at
 * 266MHz. I won't be surprised if the difference will be higher
 * on faster systems:-)
 *
 *				<appro@fy.chalmers.se>
 */
#define md4_block_data_order md4_block_host_order
#endif

#define DATA_ORDER_IS_LITTLE_ENDIAN

#define HASH_LONG		MD4_LONG
#define HASH_LONG_LOG2	MD4_LONG_LOG2
#define HASH_CTX		MD4_CTX
#define HASH_CBLOCK		MD4_CBLOCK
#define HASH_LBLOCK		MD4_LBLOCK
#ifdef	_APPLE_COMMON_CRYPTO_
#define HASH_UPDATE		CC_MD4_Update
#define HASH_TRANSFORM	CC_MD4_Transform
#define HASH_FINAL		CC_MD4_Final
#else
#define HASH_UPDATE		MD4_Update
#define HASH_TRANSFORM	MD4_Transform
#define HASH_FINAL		MD4_Final
#endif

#define	HASH_MAKE_STRING(c,s)	do {	\
	unsigned long ll;		\
	ll=(c)->A; HOST_l2c(ll,(s));	\
	ll=(c)->B; HOST_l2c(ll,(s));	\
	ll=(c)->C; HOST_l2c(ll,(s));	\
	ll=(c)->D; HOST_l2c(ll,(s));	\
	} while (0)
#define HASH_BLOCK_HOST_ORDER	md4_block_host_order
#if !defined(L_ENDIAN) || defined(md4_block_data_order)
#define	HASH_BLOCK_DATA_ORDER	md4_block_data_order
/*
 * Little-endians (Intel and Alpha) feel better without this.
 * It looks like memcpy does better job than generic
 * md4_block_data_order on copying-n-aligning input data.
 * But frankly speaking I didn't expect such result on Alpha.
 * On the other hand I've got this with egcs-1.0.2 and if
 * program is compiled with another (better?) compiler it
 * might turn out other way around.
 *
 *				<appro@fy.chalmers.se>
 */
#endif

#include "md32_common.h"

/*
#define	F(x,y,z)	(((x) & (y))  |  ((~(x)) & (z)))
#define	G(x,y,z)	(((x) & (y))  |  ((x) & ((z))) | ((y) & ((z))))
*/

/* As pointed out by Wei Dai <weidai@eskimo.com>, the above can be
 * simplified to the code below.  Wei attributes these optimizations
 * to Peter Gutmann's SHS code, and he attributes it to Rich Schroeppel.
 */
#define	F(b,c,d)	((((c) ^ (d)) & (b)) ^ (d))
#define G(b,c,d)	(((b) & (c)) | ((b) & (d)) | ((c) & (d)))
#define	H(b,c,d)	((b) ^ (c) ^ (d))

#define R0(a,b,c,d,k,s,t) { \
	a+=((k)+(t)+F((b),(c),(d))); \
	a=ROTATE(a,s); };

#define R1(a,b,c,d,k,s,t) { \
	a+=((k)+(t)+G((b),(c),(d))); \
	a=ROTATE(a,s); };\

#define R2(a,b,c,d,k,s,t) { \
	a+=((k)+(t)+H((b),(c),(d))); \
	a=ROTATE(a,s); };
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































































Deleted Source/Digest/md5_dgst.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/* crypto/md5/md5_dgst.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <stdio.h>
#include "CommonDigestPriv.h"
#include "md5_locl.h"

#ifndef		_APPLE_COMMON_CRYPTO_
#include <openssl/opensslv.h>
const char *MD5_version="MD5" OPENSSL_VERSION_PTEXT;
#endif

/* Implemented from RFC1321 The MD5 Message-Digest Algorithm
 */

#define INIT_DATA_A (unsigned long)0x67452301L
#define INIT_DATA_B (unsigned long)0xefcdab89L
#define INIT_DATA_C (unsigned long)0x98badcfeL
#define INIT_DATA_D (unsigned long)0x10325476L

int CC_MD5_Init(MD5_CTX *c)
	{
	c->A=INIT_DATA_A;
	c->B=INIT_DATA_B;
	c->C=INIT_DATA_C;
	c->D=INIT_DATA_D;
	c->Nl=0;
	c->Nh=0;
	c->num=0;
	return 1;
	}

#ifndef md5_block_host_order
__private_extern__ void md5_block_host_order (MD5_CTX *c, const void *data, int num)
	{
	const MD5_LONG *X=data;
	register unsigned MD32_REG_T A,B,C,D;

	A=c->A;
	B=c->B;
	C=c->C;
	D=c->D;

	for (;num--;X+=HASH_LBLOCK)
		{
	/* Round 0 */
	R0(A,B,C,D,X[ 0], 7,0xd76aa478L);
	R0(D,A,B,C,X[ 1],12,0xe8c7b756L);
	R0(C,D,A,B,X[ 2],17,0x242070dbL);
	R0(B,C,D,A,X[ 3],22,0xc1bdceeeL);
	R0(A,B,C,D,X[ 4], 7,0xf57c0fafL);
	R0(D,A,B,C,X[ 5],12,0x4787c62aL);
	R0(C,D,A,B,X[ 6],17,0xa8304613L);
	R0(B,C,D,A,X[ 7],22,0xfd469501L);
	R0(A,B,C,D,X[ 8], 7,0x698098d8L);
	R0(D,A,B,C,X[ 9],12,0x8b44f7afL);
	R0(C,D,A,B,X[10],17,0xffff5bb1L);
	R0(B,C,D,A,X[11],22,0x895cd7beL);
	R0(A,B,C,D,X[12], 7,0x6b901122L);
	R0(D,A,B,C,X[13],12,0xfd987193L);
	R0(C,D,A,B,X[14],17,0xa679438eL);
	R0(B,C,D,A,X[15],22,0x49b40821L);
	/* Round 1 */
	R1(A,B,C,D,X[ 1], 5,0xf61e2562L);
	R1(D,A,B,C,X[ 6], 9,0xc040b340L);
	R1(C,D,A,B,X[11],14,0x265e5a51L);
	R1(B,C,D,A,X[ 0],20,0xe9b6c7aaL);
	R1(A,B,C,D,X[ 5], 5,0xd62f105dL);
	R1(D,A,B,C,X[10], 9,0x02441453L);
	R1(C,D,A,B,X[15],14,0xd8a1e681L);
	R1(B,C,D,A,X[ 4],20,0xe7d3fbc8L);
	R1(A,B,C,D,X[ 9], 5,0x21e1cde6L);
	R1(D,A,B,C,X[14], 9,0xc33707d6L);
	R1(C,D,A,B,X[ 3],14,0xf4d50d87L);
	R1(B,C,D,A,X[ 8],20,0x455a14edL);
	R1(A,B,C,D,X[13], 5,0xa9e3e905L);
	R1(D,A,B,C,X[ 2], 9,0xfcefa3f8L);
	R1(C,D,A,B,X[ 7],14,0x676f02d9L);
	R1(B,C,D,A,X[12],20,0x8d2a4c8aL);
	/* Round 2 */
	R2(A,B,C,D,X[ 5], 4,0xfffa3942L);
	R2(D,A,B,C,X[ 8],11,0x8771f681L);
	R2(C,D,A,B,X[11],16,0x6d9d6122L);
	R2(B,C,D,A,X[14],23,0xfde5380cL);
	R2(A,B,C,D,X[ 1], 4,0xa4beea44L);
	R2(D,A,B,C,X[ 4],11,0x4bdecfa9L);
	R2(C,D,A,B,X[ 7],16,0xf6bb4b60L);
	R2(B,C,D,A,X[10],23,0xbebfbc70L);
	R2(A,B,C,D,X[13], 4,0x289b7ec6L);
	R2(D,A,B,C,X[ 0],11,0xeaa127faL);
	R2(C,D,A,B,X[ 3],16,0xd4ef3085L);
	R2(B,C,D,A,X[ 6],23,0x04881d05L);
	R2(A,B,C,D,X[ 9], 4,0xd9d4d039L);
	R2(D,A,B,C,X[12],11,0xe6db99e5L);
	R2(C,D,A,B,X[15],16,0x1fa27cf8L);
	R2(B,C,D,A,X[ 2],23,0xc4ac5665L);
	/* Round 3 */
	R3(A,B,C,D,X[ 0], 6,0xf4292244L);
	R3(D,A,B,C,X[ 7],10,0x432aff97L);
	R3(C,D,A,B,X[14],15,0xab9423a7L);
	R3(B,C,D,A,X[ 5],21,0xfc93a039L);
	R3(A,B,C,D,X[12], 6,0x655b59c3L);
	R3(D,A,B,C,X[ 3],10,0x8f0ccc92L);
	R3(C,D,A,B,X[10],15,0xffeff47dL);
	R3(B,C,D,A,X[ 1],21,0x85845dd1L);
	R3(A,B,C,D,X[ 8], 6,0x6fa87e4fL);
	R3(D,A,B,C,X[15],10,0xfe2ce6e0L);
	R3(C,D,A,B,X[ 6],15,0xa3014314L);
	R3(B,C,D,A,X[13],21,0x4e0811a1L);
	R3(A,B,C,D,X[ 4], 6,0xf7537e82L);
	R3(D,A,B,C,X[11],10,0xbd3af235L);
	R3(C,D,A,B,X[ 2],15,0x2ad7d2bbL);
	R3(B,C,D,A,X[ 9],21,0xeb86d391L);

	A = c->A += A;
	B = c->B += B;
	C = c->C += C;
	D = c->D += D;
		}
	}
#endif

#ifndef md5_block_data_order
#ifdef X
#undef X
#endif
__private_extern__ void md5_block_data_order (MD5_CTX *c, const void *data_, int num)
	{
	const unsigned char *data=data_;
	register unsigned MD32_REG_T A,B,C,D,l;
#ifndef MD32_XARRAY
	/* See comment in crypto/sha/sha_locl.h for details. */
	unsigned MD32_REG_T	XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7,
				XX8, XX9,XX10,XX11,XX12,XX13,XX14,XX15;
# define X(i)	XX##i
#else
	MD5_LONG XX[MD5_LBLOCK];
# define X(i)	XX[i]
#endif

	A=c->A;
	B=c->B;
	C=c->C;
	D=c->D;

	for (;num--;)
		{
	HOST_c2l(data,l); X( 0)=l;		HOST_c2l(data,l); X( 1)=l;
	/* Round 0 */
	R0(A,B,C,D,X( 0), 7,0xd76aa478L);	HOST_c2l(data,l); X( 2)=l;
	R0(D,A,B,C,X( 1),12,0xe8c7b756L);	HOST_c2l(data,l); X( 3)=l;
	R0(C,D,A,B,X( 2),17,0x242070dbL);	HOST_c2l(data,l); X( 4)=l;
	R0(B,C,D,A,X( 3),22,0xc1bdceeeL);	HOST_c2l(data,l); X( 5)=l;
	R0(A,B,C,D,X( 4), 7,0xf57c0fafL);	HOST_c2l(data,l); X( 6)=l;
	R0(D,A,B,C,X( 5),12,0x4787c62aL);	HOST_c2l(data,l); X( 7)=l;
	R0(C,D,A,B,X( 6),17,0xa8304613L);	HOST_c2l(data,l); X( 8)=l;
	R0(B,C,D,A,X( 7),22,0xfd469501L);	HOST_c2l(data,l); X( 9)=l;
	R0(A,B,C,D,X( 8), 7,0x698098d8L);	HOST_c2l(data,l); X(10)=l;
	R0(D,A,B,C,X( 9),12,0x8b44f7afL);	HOST_c2l(data,l); X(11)=l;
	R0(C,D,A,B,X(10),17,0xffff5bb1L);	HOST_c2l(data,l); X(12)=l;
	R0(B,C,D,A,X(11),22,0x895cd7beL);	HOST_c2l(data,l); X(13)=l;
	R0(A,B,C,D,X(12), 7,0x6b901122L);	HOST_c2l(data,l); X(14)=l;
	R0(D,A,B,C,X(13),12,0xfd987193L);	HOST_c2l(data,l); X(15)=l;
	R0(C,D,A,B,X(14),17,0xa679438eL);
	R0(B,C,D,A,X(15),22,0x49b40821L);
	/* Round 1 */
	R1(A,B,C,D,X( 1), 5,0xf61e2562L);
	R1(D,A,B,C,X( 6), 9,0xc040b340L);
	R1(C,D,A,B,X(11),14,0x265e5a51L);
	R1(B,C,D,A,X( 0),20,0xe9b6c7aaL);
	R1(A,B,C,D,X( 5), 5,0xd62f105dL);
	R1(D,A,B,C,X(10), 9,0x02441453L);
	R1(C,D,A,B,X(15),14,0xd8a1e681L);
	R1(B,C,D,A,X( 4),20,0xe7d3fbc8L);
	R1(A,B,C,D,X( 9), 5,0x21e1cde6L);
	R1(D,A,B,C,X(14), 9,0xc33707d6L);
	R1(C,D,A,B,X( 3),14,0xf4d50d87L);
	R1(B,C,D,A,X( 8),20,0x455a14edL);
	R1(A,B,C,D,X(13), 5,0xa9e3e905L);
	R1(D,A,B,C,X( 2), 9,0xfcefa3f8L);
	R1(C,D,A,B,X( 7),14,0x676f02d9L);
	R1(B,C,D,A,X(12),20,0x8d2a4c8aL);
	/* Round 2 */
	R2(A,B,C,D,X( 5), 4,0xfffa3942L);
	R2(D,A,B,C,X( 8),11,0x8771f681L);
	R2(C,D,A,B,X(11),16,0x6d9d6122L);
	R2(B,C,D,A,X(14),23,0xfde5380cL);
	R2(A,B,C,D,X( 1), 4,0xa4beea44L);
	R2(D,A,B,C,X( 4),11,0x4bdecfa9L);
	R2(C,D,A,B,X( 7),16,0xf6bb4b60L);
	R2(B,C,D,A,X(10),23,0xbebfbc70L);
	R2(A,B,C,D,X(13), 4,0x289b7ec6L);
	R2(D,A,B,C,X( 0),11,0xeaa127faL);
	R2(C,D,A,B,X( 3),16,0xd4ef3085L);
	R2(B,C,D,A,X( 6),23,0x04881d05L);
	R2(A,B,C,D,X( 9), 4,0xd9d4d039L);
	R2(D,A,B,C,X(12),11,0xe6db99e5L);
	R2(C,D,A,B,X(15),16,0x1fa27cf8L);
	R2(B,C,D,A,X( 2),23,0xc4ac5665L);
	/* Round 3 */
	R3(A,B,C,D,X( 0), 6,0xf4292244L);
	R3(D,A,B,C,X( 7),10,0x432aff97L);
	R3(C,D,A,B,X(14),15,0xab9423a7L);
	R3(B,C,D,A,X( 5),21,0xfc93a039L);
	R3(A,B,C,D,X(12), 6,0x655b59c3L);
	R3(D,A,B,C,X( 3),10,0x8f0ccc92L);
	R3(C,D,A,B,X(10),15,0xffeff47dL);
	R3(B,C,D,A,X( 1),21,0x85845dd1L);
	R3(A,B,C,D,X( 8), 6,0x6fa87e4fL);
	R3(D,A,B,C,X(15),10,0xfe2ce6e0L);
	R3(C,D,A,B,X( 6),15,0xa3014314L);
	R3(B,C,D,A,X(13),21,0x4e0811a1L);
	R3(A,B,C,D,X( 4), 6,0xf7537e82L);
	R3(D,A,B,C,X(11),10,0xbd3af235L);
	R3(C,D,A,B,X( 2),15,0x2ad7d2bbL);
	R3(B,C,D,A,X( 9),21,0xeb86d391L);

	A = c->A += A;
	B = c->B += B;
	C = c->C += C;
	D = c->D += D;
		}
	}
#endif

#ifdef undef
int printit(unsigned long *l)
	{
	int i,ii;

	for (i=0; i<2; i++)
		{
		for (ii=0; ii<8; ii++)
			{
			fprintf(stderr,"%08lx ",l[i*8+ii]);
			}
		fprintf(stderr,"\n");
		}
	}
#endif

#ifdef	_APPLE_COMMON_CRYPTO_

CC_DIGEST_ONE_SHOT(CC_MD5, CC_MD5_CTX, CC_MD5_Init, CC_MD5_Update, CC_MD5_Final)

#endif

/*
	The following is needed because CC_MD5_Final takes an unsigned char*, not an unsigned char digest[16].
	We previously handled this with a macro, but we take this approach because it allows a function pointer to
	MD5Final to be created.
*/
void MD5Final (unsigned char digest[16], MD5_CTX *context);
void MD5Final (unsigned char digest[16], MD5_CTX *context)
{
	CC_MD5_Final(digest, context);
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































































































































































































































































































































































































































































































Deleted Source/Digest/md5_locl.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/* crypto/md5/md5_locl.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#ifndef	_APPLE_COMMON_CRYPTO_
#error Compile order requires _APPLE_COMMON_CRYPTO_.

#include <stdlib.h>
#include <string.h>
#include <openssl/e_os2.h>
#include <openssl/md5.h>
#endif	_APPLE_COMMON_CRYPTO_

#ifndef MD5_LONG_LOG2
#define MD5_LONG_LOG2 2 /* default to 32 bits */
#endif

#ifdef MD5_ASM
# if defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(__INTEL__) || defined(__x86_64__)
#  define md5_block_host_order md5_block_asm_host_order
# elif defined(__sparc) && defined(OPENSSL_SYS_ULTRASPARC)
   void md5_block_asm_data_order_aligned (MD5_CTX *c, const MD5_LONG *p,int num);
#  define HASH_BLOCK_DATA_ORDER_ALIGNED md5_block_asm_data_order_aligned
# endif
#endif

__private_extern__ void md5_block_host_order (MD5_CTX *c, const void *p,int num);
__private_extern__ void md5_block_data_order (MD5_CTX *c, const void *p,int num);

#if defined(__i386) || defined(__i386__) || defined(_M_IX86) || defined(__INTEL__) || defined(__x86_64__)
/*
 * *_block_host_order is expected to handle aligned data while
 * *_block_data_order - unaligned. As algorithm and host (x86)
 * are in this case of the same "endianness" these two are
 * otherwise indistinguishable. But normally you don't want to
 * call the same function because unaligned access in places
 * where alignment is expected is usually a "Bad Thing". Indeed,
 * on RISCs you get punished with BUS ERROR signal or *severe*
 * performance degradation. Intel CPUs are in turn perfectly
 * capable of loading unaligned data without such drastic side
 * effect. Yes, they say it's slower than aligned load, but no
 * exception is generated and therefore performance degradation
 * is *incomparable* with RISCs. What we should weight here is
 * costs of unaligned access against costs of aligning data.
 * According to my measurements allowing unaligned access results
 * in ~9% performance improvement on Pentium II operating at
 * 266MHz. I won't be surprised if the difference will be higher
 * on faster systems:-)
 *
 *				<appro@fy.chalmers.se>
 */
#define md5_block_data_order md5_block_host_order
#endif

#define DATA_ORDER_IS_LITTLE_ENDIAN

#define HASH_LONG		MD5_LONG
#define HASH_LONG_LOG2		MD5_LONG_LOG2
#define HASH_CTX		MD5_CTX
#define HASH_CBLOCK		MD5_CBLOCK
#define HASH_LBLOCK		MD5_LBLOCK
#ifdef	_APPLE_COMMON_CRYPTO_
#define HASH_UPDATE		CC_MD5_Update
#define HASH_TRANSFORM	CC_MD5_Transform
#define HASH_FINAL		CC_MD5_Final
#else
#define HASH_UPDATE		MD5_Update
#define HASH_TRANSFORM	MD5_Transform
#define HASH_FINAL		MD5_Final
#endif	/* _APPLE_COMMON_CRYPTO_ */

#define	HASH_MAKE_STRING(c,s)	do {	\
	unsigned long ll;		\
	ll=(c)->A; HOST_l2c(ll,(s));	\
	ll=(c)->B; HOST_l2c(ll,(s));	\
	ll=(c)->C; HOST_l2c(ll,(s));	\
	ll=(c)->D; HOST_l2c(ll,(s));	\
	} while (0)
#define HASH_BLOCK_HOST_ORDER	md5_block_host_order
#if !defined(L_ENDIAN) || defined(md5_block_data_order)
#define	HASH_BLOCK_DATA_ORDER	md5_block_data_order
/*
 * Little-endians (Intel and Alpha) feel better without this.
 * It looks like memcpy does better job than generic
 * md5_block_data_order on copying-n-aligning input data.
 * But frankly speaking I didn't expect such result on Alpha.
 * On the other hand I've got this with egcs-1.0.2 and if
 * program is compiled with another (better?) compiler it
 * might turn out other way around.
 *
 *				<appro@fy.chalmers.se>
 */
#endif

#include "md32_common.h"

/*
#define	F(x,y,z)	(((x) & (y))  |  ((~(x)) & (z)))
#define	G(x,y,z)	(((x) & (z))  |  ((y) & (~(z))))
*/

/* As pointed out by Wei Dai <weidai@eskimo.com>, the above can be
 * simplified to the code below.  Wei attributes these optimizations
 * to Peter Gutmann's SHS code, and he attributes it to Rich Schroeppel.
 */
#define	F(b,c,d)	((((c) ^ (d)) & (b)) ^ (d))
#define	G(b,c,d)	((((b) ^ (c)) & (d)) ^ (c))
#define	H(b,c,d)	((b) ^ (c) ^ (d))
#define	I(b,c,d)	(((~(d)) | (b)) ^ (c))

#define R0(a,b,c,d,k,s,t) { \
	a+=((k)+(t)+F((b),(c),(d))); \
	a=ROTATE(a,s); \
	a+=b; };\

#define R1(a,b,c,d,k,s,t) { \
	a+=((k)+(t)+G((b),(c),(d))); \
	a=ROTATE(a,s); \
	a+=b; };

#define R2(a,b,c,d,k,s,t) { \
	a+=((k)+(t)+H((b),(c),(d))); \
	a=ROTATE(a,s); \
	a+=b; };

#define R3(a,b,c,d,k,s,t) { \
	a+=((k)+(t)+I((b),(c),(d))); \
	a=ROTATE(a,s); \
	a+=b; };
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































Deleted Source/Digest/sha1.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/* crypto/sha/sha1.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

/* 
 * In this odd implementation, the actual SHA1 code is in the sha_locl.h header.
 * Compile it exactly once, here.
 */
#define SHA_1   	1

#include <TargetConditionals.h>
#include <CommonCrypto/CommonDigest.h>

#if TARGET_OS_EMBEDDED && __arm__
#define CC_SHA1_USE_HARDWARE			1
#endif

#if CC_SHA1_USE_HARDWARE
#define CC_SHA1_USE_HARDWARE_THRESHOLD	4096
extern int _CC_SHA1_Update(CC_SHA1_CTX *c, const void *data, CC_LONG len);
#endif

#include "sha_locl.h"

#ifdef	_APPLE_COMMON_CRYPTO_

#if CC_SHA1_USE_HARDWARE
//Need the IOKitLib.h only to keep IOSHA1Types.h happy.
#include <IOKit/IOKitLib.h>
#include <Kernel/IOKit/crypto/IOSHA1Types.h>
#include <libkern/OSByteOrder.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <pthread.h>

static int cc_sha1_device = -1;
static pthread_once_t cc_sha1_connect_once = PTHREAD_ONCE_INIT;
static CC_LONG cc_sha1_hardware_quantum = (256*4096); //.25 M default value.

static void cc_sha1_connect(void) {
    struct IOSHA1AcceleratorInfo shaInfo;
	
	cc_sha1_device = open("/dev/sha1_0", O_RDWR, 0);
	if(cc_sha1_device < 0)
		return;

	if(ioctl(cc_sha1_device, IOSHA1_GET_INFO, &shaInfo) != -1) {
        cc_sha1_hardware_quantum = shaInfo.maxBytesPerCall;
	}
}

static CC_LONG sha1_hash_in_hardware(CC_SHA1_CTX *c, const UInt8 *data_buff, CC_LONG length, bool do_final)
{
	// Handle the hardware SHA1. 
	struct IOSHA1AcceleratorRequest shaRequest;
	CC_LONG quantum = cc_sha1_hardware_quantum;
	const UInt8 *data = data_buff;
	CC_LONG bytes_left = length;
	CC_LONG bytes_hashed = 0;
	
	//Load the saved context 
	shaRequest.hashBuffer.hashWords[0] = c->h0;
	shaRequest.hashBuffer.hashWords[1] = c->h1;
	shaRequest.hashBuffer.hashWords[2] = c->h2;
	shaRequest.hashBuffer.hashWords[3] = c->h3;
	shaRequest.hashBuffer.hashWords[4] = c->h4;
    shaRequest.options = 0;

	do {
		if (bytes_left < cc_sha1_hardware_quantum) {
            quantum = bytes_left;
            if (do_final) {
                shaRequest.options = kIOSHA1AcceleratorFinal;
				shaRequest.totalLength = (UInt64)(length) << 3; //Totallength is in bits.
            }
        } else {
            quantum = cc_sha1_hardware_quantum;
        }

		//Split the request in quantums if it is too large.
		shaRequest.sourceText = (UInt8 *)data;
		shaRequest.textLength = quantum;

		if(ioctl(cc_sha1_device, IOSHA1_PERFORM_HASH, &shaRequest) == -1) {
			break; //Failed to complete the whole request but fall back to the software only for the remaining bytes.
		}
		bytes_left -= quantum; 
		data += quantum;
	}while (bytes_left);

	bytes_hashed = (length - bytes_left); 
	if(bytes_hashed) {
		//Save the result in the CC_SHA1_CTX.
		c->h0 = shaRequest.hashBuffer.hashWords[0];
		c->h1 = shaRequest.hashBuffer.hashWords[1];
		c->h2 = shaRequest.hashBuffer.hashWords[2];
		c->h3 = shaRequest.hashBuffer.hashWords[3];
		c->h4 = shaRequest.hashBuffer.hashWords[4];

		//Update Nl and Nh in the context. Required to finish the hash.
		//Copied from the software SHA1 code. 
		CC_LONG l=(c->Nl+(bytes_hashed<<3))&0xffffffffL;
		if (l < c->Nl) /* overflow */
				c->Nh++;
		c->Nh+=(bytes_hashed>>29);
		c->Nl=l;
	}
	return bytes_hashed;
}

int CC_SHA1_Update(CC_SHA1_CTX *c, const void *data, CC_LONG len)
{
	const UInt8 *data_buff = (const UInt8 *) data;
	if (len > CC_SHA1_USE_HARDWARE_THRESHOLD &&
        !(((intptr_t)data_buff + CC_SHA1_BLOCK_BYTES - c->num) & 3) &&
        !pthread_once(&cc_sha1_connect_once, cc_sha1_connect) && cc_sha1_device >= 0) 
    {
		//USE SHA1 hardware.
		if(c->num) {
			//Do the first block or less in software
			CC_LONG partial = CC_SHA1_BLOCK_BYTES - c->num;
			_CC_SHA1_Update(c, data_buff, partial);
			len -= partial;
			data_buff += partial;
		}
		
		CC_LONG bytes_4_hardware = len & ~(CC_SHA1_BLOCK_BYTES - 1); //Send only mulitple of 64 bytes to the hardware.
		CC_LONG bytes_hashed = 0; 
		bytes_hashed = sha1_hash_in_hardware(c, data_buff, bytes_4_hardware, false);
        len -= bytes_hashed;
        data_buff += bytes_hashed;
	}

    //USE SHA1 software. If len is zero then this immediately returns;
    return _CC_SHA1_Update(c, data_buff, len);
}

UInt8* CC_SHA1(const void *data, CC_LONG len, UInt8 *md)
{	
	CC_LONG bytes_hashed = 0;
	const UInt8 *data_buff = (const UInt8 *)data;
	
	if(md == NULL)
		return NULL;									
		
	CC_SHA1_CTX ctx;
	CC_SHA1_Init(&ctx);
	
	if (len > CC_SHA1_USE_HARDWARE_THRESHOLD &&
        !((intptr_t)data_buff & 3) &&
        !pthread_once(&cc_sha1_connect_once, cc_sha1_connect) && cc_sha1_device >= 0) 
    {
		bytes_hashed = sha1_hash_in_hardware(&ctx, data_buff, len, true);
		if (bytes_hashed == len) {
            OSWriteBigInt32(md, 0, ctx.h0);
            OSWriteBigInt32(md, 4, ctx.h1);
            OSWriteBigInt32(md, 8, ctx.h2);
            OSWriteBigInt32(md, 12, ctx.h3);
            OSWriteBigInt32(md, 16, ctx.h4); 
			return md;
        }

		//Either we have failed partially or completely.
		//Fall through to the software.
		data_buff += bytes_hashed;
		len -= bytes_hashed;
	}
	//Fall back to Software SHA1.
	CC_SHA1_Update(&ctx, data_buff, len);
	CC_SHA1_Final(md, &ctx);					
	return md;												
}
#else //#if CC_SHA1_USE_HARDWARE
CC_DIGEST_ONE_SHOT(CC_SHA1, CC_SHA1_CTX, CC_SHA1_Init, CC_SHA1_Update, CC_SHA1_Final)
#endif

#endif //#ifdef	_APPLE_COMMON_CRYPTO_

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































































































































































Deleted Source/Digest/sha1edp.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#if !defined sha1edp_h
#define	sha1edp_h


/*	This file is included in sha1edpLittleEndian.s and sha1edpBigEndian.s to
	define the symbols below for use in assembly code.

	It is also included in sha1_locl.h and compiled in C to test that the
	hard-coded values here match the values used in C.  CC_SHA1_BLOCK_BYTES
	is defined in another header, so an error will be generated if its
	definition here conflicts.  The other symbols are tested below, with
	the CheckAssertion definition.
*/


// Number of bytes in a SHA-1 block.
#define	CC_SHA1_BLOCK_BYTES	64

// Offset of h0 to h4 members in SHA-1 context structure.
#define	Contexth0	(0*4)
#define	Contexth1	(1*4)
#define	Contexth2	(2*4)
#define	Contexth3	(3*4)
#define	Contexth4	(4*4)


#if !defined __ASSEMBLER__

	#include <stddef.h>	// Get offsetof macro.

	/*	Declare CheckAssertion so that if any of the declarations below
		differ from it, the compiler will report an error.
	*/
	extern char CheckAssertion[1];

	/*	Ensure that Contexth0 through Contexth4 are the byte offsets of the
		h0 through h4 members of the SHA-1 context structure.
	*/
	extern char CheckAssertion[Contexth0 == offsetof(SHA_CTX, h0)];
	extern char CheckAssertion[Contexth1 == offsetof(SHA_CTX, h1)];
	extern char CheckAssertion[Contexth2 == offsetof(SHA_CTX, h2)];
	extern char CheckAssertion[Contexth3 == offsetof(SHA_CTX, h3)];
	extern char CheckAssertion[Contexth4 == offsetof(SHA_CTX, h4)];
		/*	If these assertions fail, change the definitions of Contexth0 to
			Contexth4 to match the offsets of the members.
		*/

#endif	// !defined __ASSEMBLER__


#endif	// !defined sha1edp_h
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































Deleted Source/Digest/sha1edpBigEndian.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
/* 	sha1edp.s : this file provides optimized x86_64 and i386 implementation of the sha1 function
	CoreOS - vector and numerics group
	cclee	6-21-10
	
	The implementation is based on the principle described in an Intel online article
	"Improving the Performance of the Secure Hash Algorithm (SHA-1)"
	http://software.intel.com/en-us/articles/improving-the-performance-of-the-secure-hash-algorithm-1/


	Update HASH[] by processing a one 64-byte block in MESSAGE[] can be represented by the following C function

void SHA1( int HASH[], int MESSAGE[] )
{
    int A[81], B[81], C[81], D[81], E[81];
    int W[80];

    int i, FN;

    A[0] = HASH[0]; 
    B[0] = HASH[1];
    C[0] = HASH[2];
    D[0] = HASH[3];
    E[0] = HASH[4];

    for ( i=0; i<80; ++i )
    {
        if ( i < 16 )
            W[i] = BIG_ENDIAN_LOAD( MESSAGE[i] );
        else
            W[i] = ROTATE_LEFT( W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1 );

        FN = F( i, B[i], C[i], D[i] );

        A[i+1] = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + W[i] + K(i);
        B[i+1] = A[i];
        C[i+1] = ROTATE_LEFT( B[i], 30 );
        D[i+1] = C[i];
        E[i+1] = D[i];
    }

    HASH[0] += A[80];
    HASH[1] += B[80];
    HASH[2] += C[80];
    HASH[3] += D[80];
    HASH[4] += E[80];
} 

	For i=0:15, W[i] is simply big-endian loading of MESSAGE[i]. For i=16:79, W[i] is updated according to W[i] = ROTATE_LEFT( W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1 );

	The approach (by Dean Gaudet) can be used to vectorize the computation of W[i] for i=16:79,

	1. done on 4 consequtive W[i] values in a single XMM register
    W[i  ] = (W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]) rol 1
    W[i+1] = (W[i-2] ^ W[i-7] ^ W[i-13] ^ W[i-15]) rol 1
    W[i+2] = (W[i-1] ^ W[i-6] ^ W[i-12] ^ W[i-14]) rol 1
    W[i+3] = (   0   ^ W[i-5] ^ W[i-11] ^ W[i-13]) rol 1

    2. this additional calculation unfortunately requires many additional operations
    W[i+3] ^= W[i] rol 1

    3. once we have 4 W[i] values in XMM we can also add four K values with one instruction
    W[i:i+3] += {K,K,K,K}

	Let W0 = {W[i] W[i+1] W[i+2] W[i+3]} be the current W-vector to be computed, W4 = {W[i-4] W[i-3] W[i-2] W[i-1]} be the previous vector, and so on
	The Dean Gaudet approach can be expressed as

	1. W0 = rotate_left(left_shift(W4,32) ^ W8 ^ left_shift(concatenate(W16,W12),64) ^ W16,1);
	2. W[i+3] ^= W[i] rol 1
	3. W0 += {K,K,K,K}

	For i>=32, the Intel online article suggests that (using a basic identity (X rol 1) rol 1 = X rol 2) the update equation is equivalent to

	1. W0 = rotate_left(left_shift(concatenate(W8,W4),64) ^ W16 ^ W28 ^ W32, 2); 

	Note:
	1. In total, we need 8 16-byte registers or memory for W0,W4,...,W28. W0 and W32 can be the same register or memory.
	2. The registers are used in a circular buffering mode. For example, we start with W28,W24,...,W0 (with W0 indicating the most recent 16-byte)
		i=0, W28,W24,...,W0
		i=4, W24,W20,...,W28
		i=8, W20,W16,...,W24
		.
		.
		and so forth.
	3. 2 ssse3 instructions are used in the Intel article, pshufb and palignr.
		a. pshufb is used to simplify the BIG_ENDIAN_LOAD operation 
		b. palignr is used to simplify the computation of left_shift(concatenate(W12,W8),64)
	4. we probe __cpu_capabilities to detect ssse3 support and dispatch code with ssse3 support when available.
	   If ssse3 is not supported, a suboptimal code (pshufb and palignr workaround) is dispatched. 

*/

/* the code can be compiled into single block (64 bytes) per call mode by setting Multiple_blocks to 0 */
#define	Multiple_Blocks	1

#if defined (__x86_64__) || defined(__i386__)		// x86_64 or i386 architectures

#if defined(__x86_64__)

	// set up for x86_64
#define	stack_size	(8+16*11+16*4)					// 8 (alignedment) + x0-x10 + 4 128-bits for intermediate WK(t) storage
#define	sp			%rsp							// unifying architectural stack pointer representation
#define	ctx			%rdi							// 1st input argument, will move to HASH_PTR (%r9)
#define	buf			%rsi							// 2nd input argument, will move to BUFFER_PTR (%r10) 
#define	cnt			%r11							// will copy from the 3rd input argument (%rdx)
#define K_BASE		%r8								// an aligned pointer to point to shufb reference numbers of table of K values
#define HASH_PTR	%r9								// pointer to Hash values (A,B,C,D,E)
#define BUFFER_PTR	%r10							// pointer to input blocks 

#else	// !__x86_64__

	// set up for i386 
#define stack_size	(12+16*2+16*11+16*4)			// 12-bytes (alignment) + extra 2 + 3 (W24/W28/XMM_SHUFB_BSWAP) + 8 (xmm0-xmm7) + 4 (WK(t))
#define	sp			%esp							// unifying architectural stack pointer representation
#define HASH_PTR	stack_size+16+4(sp)				// use 1st input argument from caller function, 16 for (esi/edi/ebx/ebp)
#define BUFFER_PTR	stack_size+16+8(sp)				// use 2nd input argument from caller function 
#define cnt			stack_size+16+12(sp)			// use 3rd input argument from caller function
#define K_BASE		stack_size-4(sp)				// use for K_BASE

#endif	// __x86_64__

// symbolizing registers or stack memory with algorithmic variables	W0,W4,...,W28 + W_TMP, W_TMP2, and XMM_SHUFB_BSWAP for code with ssse3 support

#define W_TMP  	%xmm0
#define W_TMP2 	%xmm1
#define W0  	%xmm2
#define W4  	%xmm3
#define W8  	%xmm4
#define W12 	%xmm5
#define W16 	%xmm6
#define W20 	%xmm7
#if defined(__x86_64__)
#define W24 	%xmm8
#define W28 	%xmm9
#define XMM_SHUFB_BSWAP %xmm10				// used only when ssse3 is supported
#else	// defined (__i386__)
#define W24     12*16(sp)
#define W28     13*16(sp)
#define XMM_SHUFB_BSWAP 14*16(sp)			// used only when ssse3 is supported 
#endif

#define	xmov	movaps						// aligned 16-byte move
#define	xmovu	movups						// unaligned 16-byte move

// intermediate hash variables
#define A %ecx
#define B %esi
#define C %edi
#define D %ebp
#define E %edx

// temp variables
#define T1 %eax
#define T2 %ebx

#define	WK(t)	(t&15)*4(sp)

	// int F1(int B, int C, int D) { return (D ^ ( B & (C ^ D)); }
	// result in T1
	.macro	F1
	mov	$1, T1
	xor	$2, T1
	and	$0, T1
	xor	$2, T1
	.endm

	// int F2(int B, int C, int D) { return (D ^ B ^ C); }
	// result in T1
	.macro	F2
	mov	$2, T1
	xor	$1, T1
	xor	$0, T1
	.endm

	// int F3(int B, int C, int D) { return (B & C) | (D & (B ^ C)); }
	// result in T1
	.macro	F3
		mov $1, T1
        mov $0, T2
        or  $0, T1
        and $1, T2
        and $2, T1
        or  T2, T1
	.endm

	// for i=60:79, F4 is identical to F2
	#define	F4	F2


	/*
		i=0:15, W[i] = BIG_ENDIAN_LOAD(MESSAGE[i]);

		with ssse3 support, this is achived via
		for (i=0;i<16;i+=4) {
			1. W_TMP = new 16 bytes from MESSAGE[]
			2. W_TMP = pshufb(W_TMP, XMM_SHUFB_BSWAP); save to W circular buffer for updating W 
			3. WTMP += {K,K,K,K};
			4. save quadruple W[i]+K[i] = W_TMP in the stack memory;
		}

		each step is represented in one of the following 4 macro definitions

*/

	.macro	W_PRECALC_00_15_0				// input argument $0 : 0/4/8/12
#if defined (__x86_64__)					// BUFFER_PTR is already an address register in x86_64
	xmovu	$0*4(BUFFER_PTR), W_TMP			// read 16-bytes into W_TMP, BUFFER_PTR possibly not 16-byte aligned
#else										// BUFFER_PTR is from the argument set up in the caller
	mov     BUFFER_PTR, T1					// T1 = BUFFER_PTR
    xmovu  $0*4(T1), W_TMP					// read 16-bytes into W_TMP, BUFFER_PTR possibly not 16-byte aligned
#endif
	.endm

	.macro	W_PRECALC_00_15_1				// input argument $0 : current 16-bytes in the circular buffer, one of W0,W4,W8,...,W28
	xmov	W_TMP, $0						// save W_TMP in the circular buffer
	.endm

	.macro	W_PRECALC_00_15_2				// K_BASE points to the current K quadruple.
#if defined (__x86_64__)					// K_BASE is already an address register in x86_64
	paddd	(K_BASE), W_TMP					// W_TMP += {K,K,K,K};
#else										// K_BASE is previously set up in the stack memory
	mov     K_BASE, T1						// T1 = K_BASE
    paddd   (T1), W_TMP						// W_TMP += {K,K,K,K};
#endif
	.endm

	.macro	W_PRECALC_00_15_3
	xmov	W_TMP, WK($0&~3)				// save quadruple W[i]+K in the stack memory, which would be used later for updating the hashes A/B/C/D/E
	.endm

	// rounds 16-31 compute W[0] using the vectorization approach by Dean Gaudet
	/*
	W[i  ] = (W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]) rol 1
    W[i+1] = (W[i-2] ^ W[i-7] ^ W[i-13] ^ W[i-15]) rol 1
    W[i+2] = (W[i-1] ^ W[i-6] ^ W[i-12] ^ W[i-14]) rol 1
    W[i+3] = (   0   ^ W[i-5] ^ W[i-11] ^ W[i-13]) rol 1

	W[i+3] ^= W[i] rol 1;	// this W[i] is already rol by 1, if we are taking from the intial W before rol 1, we should rol this by 2

	The operation (updating W and W+K) is scheduled as and divided into 4 steps

	0. W_tmp = W3; W = W14 ^ W8
	1. W = W3 ^ W8 ^ W14 ^ W16; W_TMP = W; W_TMP2 = (W[i] 0 0 0); 
	2. W_TMP = (W3 ^ W8 ^ W14 ^ W16) rol 1; split (W[i] 0 0 0) rol 2 in W_TMP2 and W
	3. W = W_TMP = W_TMP ^ W_TMP2 ^ W = (W3 ^ W8 ^ W14 ^ W16) rol 1 ^ (W[i] 0 0 0) rol 2; WK = W _TMP+K;  

	*/

	.macro	W_PRECALC_16_31_0_ssse3	// input arguments : W16,W12,W8,W4,W
	xmov	$1, $4					// W = W12
	palignr	$$8, $0, $4				// W = W14
	xmov	$3, W_TMP				// W_TMP = W4
	psrldq	$$4, W_TMP				// W_TMP = W3
	pxor	$2, $4					// W = W8 ^ W14	
	.endm

	.macro	W_PRECALC_16_31_1		// input arguments : W16,W
	pxor	$0, W_TMP				// W_TMP = W3 ^ W16
	pxor	W_TMP, $1				// W = W3 ^ W16 ^ W8 ^ W14
	xmov	$1, W_TMP2				// W_TMP2 = W3 ^ W16 ^ W8 ^ W14 
	xmov	$1, W_TMP				// W_TMP = W3 ^ W16 ^ W8 ^ W14
	pslldq	$$12, W_TMP2			// W_TMP2 = (W[i] 0 0 0)
	.endm

	.macro	W_PRECALC_16_31_2		// input argument : W
	psrld	$$31, $0				// (W3 ^ W16 ^ W8 ^ W14)>>31
	pslld	$$1, W_TMP				// (W3 ^ W16 ^ W8 ^ W14)<<1
	por		$0, W_TMP				// W_TMP = (W3 ^ W16 ^ W8 ^ W14) rol 1
	xmov	W_TMP2, $0				// copy W[i] at location of W[i+3]
	psrld	$$30, W_TMP2			// W_TMP2 = W[i] lower 2 bits after rol 2
	pslld	$$2, $0					// W = W[i] higher 30 bits after rol 2
	.endm

	.macro	W_PRECALC_16_31_3		// input arguments: W, i, K_XMM
#if defined (__i386__)
	mov     K_BASE, T1				// K_BASE is store in the stack memory for i386
#endif
	pxor	$0, W_TMP
	pxor	W_TMP2, W_TMP			// W_TMP = (W3 ^ W16 ^ W8 ^ W14) rol 1 ^ (W[i] 0 0 0) rol 2
	xmov	W_TMP, $0				// save W = W_TMP in the W circular buffer
#if defined (__x86_64__)
	paddd	$2(K_BASE), W_TMP		// W+K
#else
    paddd   $2(T1), W_TMP			// W+K
#endif
	xmov	W_TMP, WK($1&~3)		// save WK = W+K for later update of the hashes A/B/C/D/E
	.endm

	// the following is a variant of W_PRECALC_16_31_0_ssse3 to be used for system without ssse3, palignr is replaced with 4 instructions

	.macro	W_PRECALC_16_31_0_nossse3	// input arguments : W16,W12,W8,W4,W
	xmov	$1, $4						// W = W12 = (w9 w10 w11 w12)

	// the following is a wrokaround for palignr
	xmov	$0, W_TMP					// W16 = (w13 w14 w15 w16)
	pslldq	$$8, $4						// shift left to make (w11 w12 0 0)
	psrldq	$$8, W_TMP					// shift right to make (0 0 w13 w14)
	por		W_TMP, $4					// W = W14 = (w11 w12 w13 w14)

	xmov	$3, W_TMP					// W_TMP = W4 = (w1 w2 w3 w4)
	psrldq	$$4, W_TMP					// W_TMP = W3 = (0 w1 w2 w3)
	pxor	$2, $4						// W = W8 ^ W14	
	.endm

	/* rounds 32-79 compute W und W+K iusing the vectorization approach from the Intel article

		W = rotate_left(left_shift(concatenate(W8,W4),64) ^ W16 ^ W28 ^ W32, 2);

		where left_shift(concatenate(W8,W4),64) is equivalent to W6. Note also that W32 and W use the same register.


	0. W_tmp = W6; W = W28 ^ W32;
	1. W = W_tmp = W6 ^ W16 ^ W28 ^ W32;
	2. W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2;
	3. W = W_Tmp; WK = W_tmp + K;

*/


	.macro	W_PRECALC_32_79_0_ssse3		// inputr arguments : W28,W8,W4,W
	xmov	$2, W_TMP					// (w1 w2 w3 w4)
	pxor	$0, $3						// W = W28 ^ W32;
	palignr	$$8, $1, W_TMP				// W_tmp = (w3 w4 w5 w6) = W6;
	.endm

	// the following is a variant and will be used for system without ssse3 support
	.macro	W_PRECALC_32_79_0_nossse3	// input arguments : W28,W8,W4,W
	xmov	$2, W_TMP					// (w1 w2 w3 w4)
	xmov    $1, W_TMP2					// (w5 w6 w7 w8)
	pxor	$0, $3						// W = W28 ^ W32
	pslldq	$$8, W_TMP					// (w3 w4 0 0)
	psrldq	$$8, W_TMP2					// (0 0 w5 w6)
	por		W_TMP2, W_TMP				// W_tmp = (w3 w4 w5 w6) = W6
	.endm

	// this is a variant of W_PRECALC_32_79_0_ssse3 for i386 (as W24/W28 are stored in memory, not in registers)
	.macro  W_PRECALC_32_79_0_i386_ssse3	// input arguments : W28,W8,W4,W
    xmov    $3, W_TMP						// W32
    pxor    $0, W_TMP						// W28 ^ W32
    xmov    W_TMP, $3						// W = W28 ^ W32;
    xmov    $2, W_TMP						// W4
    palignr $$8, $1, W_TMP					// W_tmp = (w3 w4 w5 w6) = W6;
    .endm

	// this is a variant of W_PRECALC_32_79_0_nossse3 for i386 (as W24/W28 are stored in memory, not in registers)
	.macro  W_PRECALC_32_79_0_i386_nossse3  // input arguments : W28,W8,W4,W
    xmov    $3, W_TMP						// W32
    pxor    $0, W_TMP						// W28 ^ W32
    xmov    W_TMP, $3						// W = W28 ^ W32
    xmov    $2, W_TMP						// W4 = (w1 w2 w3 w4)
	xmov    $1, W_TMP2						// W8 = (w5 w6 w7 w8)
	pslldq	$$8, W_TMP						// (w3 w4 0 0)
	psrldq	$$8, W_TMP2						// (0 0 w5 w6)
	por		W_TMP2, W_TMP					// W_tmp = (w3 w4 w5 w6) = W6
    .endm

	.macro	W_PRECALC_32_79_1			// input arguments : W16,W
	pxor	$0, W_TMP					// W_tmp = W6 ^ W16
	pxor	$1, W_TMP					// W_tmp = W6 ^ W16 ^ W28 ^ W32
	xmov	W_TMP, $1					// W = W_tmp = W6 ^ W16 ^ W28 ^ W32
	.endm

	.macro	W_PRECALC_32_79_2			// input argument : W
	psrld	$$30, $0					// W >> 30
	pslld	$$2, W_TMP					// W << 2
	por		$0, W_TMP					// W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2
	.endm

	// this is a variant of W_PRECALC_32_79_2 for i386 (as W24/W28 are stored in memory, not in registers)
	// this should be used when the input is either W24 or W28 on i386 architecture
    .macro  W_PRECALC_32_79_2_i386  	// input argument : W
    xmov    $0, W_TMP2					// W
    psrld   $$30, W_TMP2				// W >> 30
    xmov    W_TMP2, $0					// save (W >> 30) at W
    pslld   $$2, W_TMP					// W_tmp << 2
    por     $0, W_TMP					// W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2
    .endm

	.macro	W_PRECALC_32_79_3			// input argument W, i, K_XMM
#if defined (__x86_64__)
	xmov	W_TMP, $0					// W = (W6 ^ W16 ^ W28 ^ W32) rol 2
	paddd	$2(K_BASE), W_TMP			// W + K
	xmov	W_TMP, WK($1&~3)			// write W+K
#else
    mov     K_BASE, T1					// T1 = K_BASE (which is in the caller argument)
    xmov    W_TMP, $0					// W = (W6 ^ W16 ^ W28 ^ W32) rol 2
    paddd   $2(T1), W_TMP				// W_tmp = W + K
    xmov    W_TMP, WK($1&~3)			// write WK
	#endif
	.endm


	/* The hash update operation is completed by the following statements.

		A[i+1] = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + WK(i);
        B[i+1] = A[i];
        C[i+1] = ROTATE_LEFT( B[i], 30 );
        D[i+1] = C[i];
        E[i+1] = D[i];

		Suppose we start with A0,B0,C0,D0,E0. The 1st iteration can be expressed as follows:

		A1 = FN + E0 + rol(A0,5) + WK;
		B1 = A0;
		C1 = rol(B0, 30);
		D1 = C0;
		E1 = D0;

		to avoid excessive memory movement between registers, 
			1. A1 = FN + E0 + rol(A0,5) + WK; can be temporarily saved in E0, 
			2. C1 = rol(B0,30) can be temporarily saved in B0. 

		Therefore, ignoring the time index, the update operation is equivalent to
			1. E = FN(B,C,D) + E + rol(A,5) + WK(i)
			2. B = rol(B,30)
			3. the hashes are now stored in the order of E,A,B,C,D


		To pack 2 hash update operations in 1 iteration, starting with A,B,C,D,E
		1. E = FN(B,C,D) + E + rol(A,5) + WK(i)
		2. B = rol(B,30)
		// now the hashes are in the order of E,A,B,C,D
		3. D = FN(A,B,C) + D + rol(E,5) + WK(i+1)
		4. A = rol(A,30)
		// now the hashes are in the order of D,E,A,B,C
	
		These operations are distributed into the following 2 macro definitions RR0 and RR1.	

*/

	.macro	RR0				// input arguments : FN, A, B, C, D, E, i
	$0		$2, $3, $4		// T1 = FN(B,C,D)
	add		WK($6), $5		// E + WK(i)
	rol		$$30, $2		// B = rol(B,30)
	mov		$1, T2			// T2 = A
	add		WK($6+1), $4	// D + WK(i+1)
	rol		$$5, T2			// rol(A,5)
	add		T1, $5			// E = FN(B,C,D) + E + WK(i)
	.endm

	.macro	RR1
	add		$5, T2			// T2 = FN(B,C,D) + E + rol(A,5) + WK(i)
	mov		T2, $5			// E = FN(B,C,D) + E + rol(A,5) + WK(i)
	rol		$$5, T2			// rol(E,5)
	add		T2, $4			// D + WK(i+1) + rol(E,5)
	$0		$1, $2, $3		// FN(A,B,C)
	add		T1, $4			// D = FN(A,B,C) + D + rol(E,5) + WK(i+1)
	rol		$$30, $1		// A = rol(A,30)
	.endm



	/*

		The following macro definitions are used to expand code for the per-block sha1 operation.

			INITIAL_W_PRECALC_ssse3	: BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack memory
			INTERNAL_ssse3 : updating W (16:79) and update the digests A/B/C/D/E (i=0:63, based on W+K stored in the stack memory) 
			ENDING : finishing up update the digests A/B/C/D/E (i=64:79)

		For multiple-block sha1 operation (Multiple_Blocks = 1), INITIAL_W_PRECALC_ssse3 and ENDING are combined
		into 1 macro definition for software pipeling.

			SOFTWARE_PIPELINING_ssse3 : BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack, and finishing up update the digests A/B/C/D/E (i=64:79) 

		assume cnt (the number of blocks)  >= 1, the main code body should look like

		INITIAL_W_PRECALC_ssse3				// W = big_endian_load and pre-compute W+K (i=0:15)
		do {
			INTERNAL_ssse3					// update W(i=16:79), and update hash digests A/B/C/D/E (i=0:63)
			cnt--;
			if (cnt==0) break;
			BUFFER_PTR += 64;
			SOFTWARE_PIPELINING_ssse3;		// update hash digests A/B/C/D/E (i=64:79) + W = big_endian_load and pre-compute W+K (i=0:15)
		}
		ENDING								// update hash digests A/B/C/D/E (i=64:79)

	*/

	#define	W_PRECALC_16_31_0	W_PRECALC_16_31_0_ssse3
	#define	W_PRECALC_32_79_0	W_PRECALC_32_79_0_ssse3
	#define	W_PRECALC_32_79_0_i386	W_PRECALC_32_79_0_i386_ssse3


	.macro	INITIAL_W_PRECALC_ssse3			// BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack memory	

	// i=0 	: W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K

	// i=4	: W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K

	.endm


	.macro	INTERNAL_ssse3					// updating W (16:79) and update the digests A/B/C/D/E (i=0:63, based on W+K stored in the stack memory)

	// i=16 : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_16_31_0	W0,W28,W24,W20,W16
	RR0					F1,A,B,C,D,E,0
	W_PRECALC_16_31_1	W0,W16
	RR1					F1,A,B,C,D,E,0
	W_PRECALC_16_31_2	W16
	RR0					F1,D,E,A,B,C,2
	W_PRECALC_16_31_3	W16, 2, 0
	RR1					F1,D,E,A,B,C,2

	// i=20 : W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_16_31_0	W28,W24,W20,W16,W12
	RR0					F1,B,C,D,E,A,4
	W_PRECALC_16_31_1	W28,W12
	RR1					F1,B,C,D,E,A,4
	W_PRECALC_16_31_2	W12
	RR0					F1,E,A,B,C,D,6
	W_PRECALC_16_31_3	W12, 6, 16
	RR1					F1,E,A,B,C,D,6

	// i=24 : W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_16_31_0	W24,W20,W16,W12,W8
	RR0					F1,C,D,E,A,B,8
	W_PRECALC_16_31_1	W24,W8
	RR1					F1,C,D,E,A,B,8
	W_PRECALC_16_31_2	W8
	RR0					F1,A,B,C,D,E,10
	W_PRECALC_16_31_3	W8,10,16
	RR1					F1,A,B,C,D,E,10

	// i=28 : W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_16_31_0	W20,W16,W12,W8,W4
	RR0					F1,D,E,A,B,C,12
	W_PRECALC_16_31_1	W20,W4
	RR1					F1,D,E,A,B,C,12
	W_PRECALC_16_31_2	W4
	RR0					F1,B,C,D,E,A,14
	W_PRECALC_16_31_3	W4,14,16
	RR1					F1,B,C,D,E,A,14

	// i=32 : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F1,E,A,B,C,D,16
	W_PRECALC_32_79_1	W16,W0
	RR1					F1,E,A,B,C,D,16
	W_PRECALC_32_79_2	W0
	RR0					F1,C,D,E,A,B,18
	W_PRECALC_32_79_3	W0,18,16
	RR1					F1,C,D,E,A,B,18

	// starting using F2	

	// i=36 : W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F2,A,B,C,D,E,20
	W_PRECALC_32_79_1	W12,W28
	RR1					F2,A,B,C,D,E,20
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F2,D,E,A,B,C,22
	W_PRECALC_32_79_3	W28,22,16
	RR1					F2,D,E,A,B,C,22

	// i=40 : W20,W16,W12,W8,W4,W0,W28,W24	
	#undef  K_XMM
    #define K_XMM   32
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F2,B,C,D,E,A,24
	W_PRECALC_32_79_1	W8,W24
	RR1					F2,B,C,D,E,A,24
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F2,E,A,B,C,D,26
	W_PRECALC_32_79_3	W24,26,K_XMM
	RR1					F2,E,A,B,C,D,26

	// i=44 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F2,C,D,E,A,B,28
	W_PRECALC_32_79_1	W4,W20
	RR1					F2,C,D,E,A,B,28
	W_PRECALC_32_79_2	W20
	RR0					F2,A,B,C,D,E,30
	W_PRECALC_32_79_3	W20,30,K_XMM
	RR1					F2,A,B,C,D,E,30

	// i=48 : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_32_79_0	W12,W24,W20,W16
	RR0					F2,D,E,A,B,C,32
	W_PRECALC_32_79_1	W0,W16
	RR1					F2,D,E,A,B,C,32
	W_PRECALC_32_79_2	W16
	RR0					F2,B,C,D,E,A,34
	W_PRECALC_32_79_3	W16,34,K_XMM
	RR1					F2,B,C,D,E,A,34

	// i=52 : W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_32_79_0	W8,W20,W16,W12
	RR0					F2,E,A,B,C,D,36
	W_PRECALC_32_79_1	W28,W12
	RR1					F2,E,A,B,C,D,36
	W_PRECALC_32_79_2	W12
	RR0					F2,C,D,E,A,B,38
	W_PRECALC_32_79_3	W12,38,K_XMM
	RR1					F2,C,D,E,A,B,38

	// starting using F3	

	// i=56 : W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_32_79_0	W4,W16,W12,W8
	RR0					F3,A,B,C,D,E,40
	W_PRECALC_32_79_1	W24,W8
	RR1					F3,A,B,C,D,E,40
	W_PRECALC_32_79_2	W8
	RR0					F3,D,E,A,B,C,42
	W_PRECALC_32_79_3	W8,42,K_XMM
	RR1					F3,D,E,A,B,C,42

	// i=60 : W0,W28,W24,W20,W16,W12,W8,W4
	#undef	K_XMM
	#define	K_XMM	48
	W_PRECALC_32_79_0	W0,W12,W8,W4
	RR0					F3,B,C,D,E,A,44
	W_PRECALC_32_79_1	W20,W4
	RR1					F3,B,C,D,E,A,44
	W_PRECALC_32_79_2	W4
	RR0					F3,E,A,B,C,D,46
	W_PRECALC_32_79_3	W4,46,K_XMM
	RR1					F3,E,A,B,C,D,46

	// i=64 : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F3,C,D,E,A,B,48
	W_PRECALC_32_79_1	W16,W0
	RR1					F3,C,D,E,A,B,48
	W_PRECALC_32_79_2	W0
	RR0					F3,A,B,C,D,E,50
	W_PRECALC_32_79_3	W0,50,K_XMM
	RR1					F3,A,B,C,D,E,50

	// i=68 : W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F3,D,E,A,B,C,52
	W_PRECALC_32_79_1	W12,W28
	RR1					F3,D,E,A,B,C,52
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F3,B,C,D,E,A,54
	W_PRECALC_32_79_3	W28,54,K_XMM
	RR1					F3,B,C,D,E,A,54

	// i=72 : W20,W16,W12,W8,W4,W0,W28,W24
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F3,E,A,B,C,D,56
	W_PRECALC_32_79_1	W8,W24
	RR1					F3,E,A,B,C,D,56
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F3,C,D,E,A,B,58
	W_PRECALC_32_79_3	W24,58,K_XMM
	RR1					F3,C,D,E,A,B,58

	// starting using F4	

	// i=76 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F4,A,B,C,D,E,60
	W_PRECALC_32_79_1	W4,W20
	RR1					F4,A,B,C,D,E,60
	W_PRECALC_32_79_2	W20
	RR0					F4,D,E,A,B,C,62
	W_PRECALC_32_79_3	W20,62,K_XMM
	RR1					F4,D,E,A,B,C,62

	.endm

	.macro	SOFTWARE_PIPELINING_ssse3
	// i=0  : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	RR0					F4,B,C,D,E,A,64
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	RR1					F4,B,C,D,E,A,64
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	RR0					F4,E,A,B,C,D,66
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K
	RR1					F4,E,A,B,C,D,66

	// i=4  : W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	RR0					F4,C,D,E,A,B,68
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	RR1					F4,C,D,E,A,B,68
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	RR0					F4,A,B,C,D,E,70
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K[0]
	RR1					F4,A,B,C,D,E,70

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	RR0					F4,D,E,A,B,C,72
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	RR1					F4,D,E,A,B,C,72
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	RR0					F4,B,C,D,E,A,74
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K
	RR1					F4,B,C,D,E,A,74

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	RR0					F4,E,A,B,C,D,76
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	RR1					F4,E,A,B,C,D,76
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	RR0					F4,C,D,E,A,B,78
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K
	RR1					F4,C,D,E,A,B,78
	.endm


	#undef	W_PRECALC_16_31_0
	#undef	W_PRECALC_32_79_0
	#undef	W_PRECALC_32_79_0_i386



	/* 

		The following are 3 macro definitions that are no-ssse3 variants of the previous 3 macro definitions.

		INITIAL_W_PRECALC_nossse3
		INTERNAL_nossse3
		SOFTWARE_PIPELINING_nossse3
		
		They will be used in a sha1 code main body definition that will be used for system without ssse3 support.	

	*/

	#define	W_PRECALC_16_31_0	W_PRECALC_16_31_0_nossse3
	#define	W_PRECALC_32_79_0	W_PRECALC_32_79_0_nossse3
	#define	W_PRECALC_32_79_0_i386	W_PRECALC_32_79_0_i386_nossse3


	.macro	INITIAL_W_PRECALC_nossse3

	// i=0 	: W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K

	// i=4	: W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K

	.endm


	.macro	INTERNAL_nossse3
	// i=16
	// circular buffer : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_16_31_0	W0,W28,W24,W20,W16
	RR0					F1,A,B,C,D,E,0
	W_PRECALC_16_31_1	W0,W16
	RR1					F1,A,B,C,D,E,0
	W_PRECALC_16_31_2	W16
	RR0					F1,D,E,A,B,C,2
	W_PRECALC_16_31_3	W16, 2, 0
	RR1					F1,D,E,A,B,C,2

	// i=20,
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_16_31_0	W28,W24,W20,W16,W12
	RR0					F1,B,C,D,E,A,4
	W_PRECALC_16_31_1	W28,W12
	RR1					F1,B,C,D,E,A,4

	W_PRECALC_16_31_2	W12
	RR0					F1,E,A,B,C,D,6
	W_PRECALC_16_31_3	W12, 6, 16
	RR1					F1,E,A,B,C,D,6

	// i=24,
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_16_31_0	W24,W20,W16,W12,W8
	RR0					F1,C,D,E,A,B,8
	W_PRECALC_16_31_1	W24,W8
	RR1					F1,C,D,E,A,B,8

	W_PRECALC_16_31_2	W8
	RR0					F1,A,B,C,D,E,10
	W_PRECALC_16_31_3	W8,10,16
	RR1					F1,A,B,C,D,E,10

	// i=28
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_16_31_0	W20,W16,W12,W8,W4
	RR0					F1,D,E,A,B,C,12
	W_PRECALC_16_31_1	W20,W4
	RR1					F1,D,E,A,B,C,12

	W_PRECALC_16_31_2	W4
	RR0					F1,B,C,D,E,A,14
	W_PRECALC_16_31_3	W4,14,16
	RR1					F1,B,C,D,E,A,14

	//i=32
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F1,E,A,B,C,D,16
	W_PRECALC_32_79_1	W16,W0
	RR1					F1,E,A,B,C,D,16
	W_PRECALC_32_79_2	W0
	RR0					F1,C,D,E,A,B,18
	W_PRECALC_32_79_3	W0,18,16
	RR1					F1,C,D,E,A,B,18

	//i=36
	// W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F2,A,B,C,D,E,20
	W_PRECALC_32_79_1	W12,W28
	RR1					F2,A,B,C,D,E,20
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F2,D,E,A,B,C,22
	W_PRECALC_32_79_3	W28,22,16
	RR1					F2,D,E,A,B,C,22

	//i=40
	#undef  K_XMM
    #define K_XMM   32
	// W20,W16,W12,W8,W4,W0,W28,W24	
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F2,B,C,D,E,A,24
	W_PRECALC_32_79_1	W8,W24
	RR1					F2,B,C,D,E,A,24
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F2,E,A,B,C,D,26
	W_PRECALC_32_79_3	W24,26,K_XMM
	RR1					F2,E,A,B,C,D,26

	//i=44
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F2,C,D,E,A,B,28
	W_PRECALC_32_79_1	W4,W20
	RR1					F2,C,D,E,A,B,28
	W_PRECALC_32_79_2	W20
	RR0					F2,A,B,C,D,E,30
	W_PRECALC_32_79_3	W20,30,K_XMM
	RR1					F2,A,B,C,D,E,30

	//i=48
	// W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_32_79_0	W12,W24,W20,W16
	RR0					F2,D,E,A,B,C,32
	W_PRECALC_32_79_1	W0,W16
	RR1					F2,D,E,A,B,C,32
	W_PRECALC_32_79_2	W16
	RR0					F2,B,C,D,E,A,34
	W_PRECALC_32_79_3	W16,34,K_XMM
	RR1					F2,B,C,D,E,A,34

	//i=52
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_32_79_0	W8,W20,W16,W12
	RR0					F2,E,A,B,C,D,36
	W_PRECALC_32_79_1	W28,W12
	RR1					F2,E,A,B,C,D,36
	W_PRECALC_32_79_2	W12
	RR0					F2,C,D,E,A,B,38
	W_PRECALC_32_79_3	W12,38,K_XMM
	RR1					F2,C,D,E,A,B,38

	//i=56
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_32_79_0	W4,W16,W12,W8
	RR0					F3,A,B,C,D,E,40
	W_PRECALC_32_79_1	W24,W8
	RR1					F3,A,B,C,D,E,40
	W_PRECALC_32_79_2	W8
	RR0					F3,D,E,A,B,C,42
	W_PRECALC_32_79_3	W8,42,K_XMM
	RR1					F3,D,E,A,B,C,42

	//i=60
	#undef	K_XMM
	#define	K_XMM	48
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_32_79_0	W0,W12,W8,W4
	RR0					F3,B,C,D,E,A,44
	W_PRECALC_32_79_1	W20,W4
	RR1					F3,B,C,D,E,A,44
	W_PRECALC_32_79_2	W4
	RR0					F3,E,A,B,C,D,46
	W_PRECALC_32_79_3	W4,46,K_XMM
	RR1					F3,E,A,B,C,D,46

	//i=64
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F3,C,D,E,A,B,48
	W_PRECALC_32_79_1	W16,W0
	RR1					F3,C,D,E,A,B,48
	W_PRECALC_32_79_2	W0
	RR0					F3,A,B,C,D,E,50
	W_PRECALC_32_79_3	W0,50,K_XMM
	RR1					F3,A,B,C,D,E,50

	//i=68
	// W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F3,D,E,A,B,C,52
	W_PRECALC_32_79_1	W12,W28
	RR1					F3,D,E,A,B,C,52
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F3,B,C,D,E,A,54
	W_PRECALC_32_79_3	W28,54,K_XMM
	RR1					F3,B,C,D,E,A,54

	//i=72
	// W20,W16,W12,W8,W4,W0,W28,W24
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F3,E,A,B,C,D,56
	W_PRECALC_32_79_1	W8,W24
	RR1					F3,E,A,B,C,D,56
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F3,C,D,E,A,B,58
	W_PRECALC_32_79_3	W24,58,K_XMM
	RR1					F3,C,D,E,A,B,58

	// starting using F4	

	//i=76
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F4,A,B,C,D,E,60
	W_PRECALC_32_79_1	W4,W20
	RR1					F4,A,B,C,D,E,60
	W_PRECALC_32_79_2	W20
	RR0					F4,D,E,A,B,C,62
	W_PRECALC_32_79_3	W20,62,K_XMM
	RR1					F4,D,E,A,B,C,62

	.endm

	.macro	SOFTWARE_PIPELINING_nossse3
	// i=0  : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	RR0					F4,B,C,D,E,A,64
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	RR1					F4,B,C,D,E,A,64
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	RR0					F4,E,A,B,C,D,66
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K
	RR1					F4,E,A,B,C,D,66

	// i=4  : W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	RR0					F4,C,D,E,A,B,68
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	RR1					F4,C,D,E,A,B,68
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	RR0					F4,A,B,C,D,E,70
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K[0]
	RR1					F4,A,B,C,D,E,70

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	RR0					F4,D,E,A,B,C,72
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	RR1					F4,D,E,A,B,C,72
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	RR0					F4,B,C,D,E,A,74
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K
	RR1					F4,B,C,D,E,A,74

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	RR0					F4,E,A,B,C,D,76
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	RR1					F4,E,A,B,C,D,76
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	RR0					F4,C,D,E,A,B,78
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K
	RR1					F4,C,D,E,A,B,78
	.endm

	.macro	ENDING		// finish up updating hash digests (i=64:79)
	//i=80
	RR0					F4,B,C,D,E,A,64
	RR1					F4,B,C,D,E,A,64
	RR0					F4,E,A,B,C,D,66
	RR1					F4,E,A,B,C,D,66

	//i=84
	RR0					F4,C,D,E,A,B,68
	RR1					F4,C,D,E,A,B,68
	RR0					F4,A,B,C,D,E,70
	RR1					F4,A,B,C,D,E,70

	//i=88
	RR0					F4,D,E,A,B,C,72
	RR1					F4,D,E,A,B,C,72
	RR0					F4,B,C,D,E,A,74
	RR1					F4,B,C,D,E,A,74

	//i=92
	RR0					F4,E,A,B,C,D,76
	RR1					F4,E,A,B,C,D,76
	RR0					F4,C,D,E,A,B,78
	RR1					F4,C,D,E,A,B,78
	.endm

	// load hash digests A,B,C,D,E from memory into registers
	.macro	LOAD_HASH
#if defined (__x86_64__)
	mov			(HASH_PTR), A
	mov			4(HASH_PTR), B
	mov			8(HASH_PTR), C
	mov			12(HASH_PTR), D
	mov			16(HASH_PTR), E
#else
    mov         HASH_PTR, T1
    mov         (T1), A
    mov         4(T1), B
    mov         8(T1), C
    mov         12(T1), D
    mov         16(T1), E
#endif
	.endm

	.macro	UPDATE_HASH
	add		$0, $1
	mov		$1, $0
	.endm

	.macro UPDATE_ALL_HASH	
#if defined (__x86_64__)
	UPDATE_HASH		(HASH_PTR), A
	UPDATE_HASH		4(HASH_PTR), B
	UPDATE_HASH		8(HASH_PTR), C
	UPDATE_HASH		12(HASH_PTR), D
	UPDATE_HASH		16(HASH_PTR), E
#else
    mov             HASH_PTR, T1
    UPDATE_HASH     (T1), A
    UPDATE_HASH     4(T1), B
    UPDATE_HASH     8(T1), C
    UPDATE_HASH     12(T1), D
    UPDATE_HASH     16(T1), E
#endif
	.endm


	/*
		 main sha1 code for system without ssse3 support
	*/

	.macro  SHA1_PIPELINED_MAIN_BODY_nossse3
	LOAD_HASH						// load initial hashes into A,B,C,D,E (registers)
	INITIAL_W_PRECALC_nossse3		// big_endian_load(W) and W+K (i=0:15)
	.align	4,0x90
0:
	INTERNAL_nossse3				// update W (i=16:79) and update ABCDE (i=0:63)	
#if Multiple_Blocks
	add	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	sub	$$1, cnt					// pre-decrement cnt by 1
	jbe	1f							// if cnt <= 0, branch to finish off
	SOFTWARE_PIPELINING_nossse3		// update ABCDE (i=64:79) || big_endian_load(W) and W+K (i=0:15)
	UPDATE_ALL_HASH					// update output hashes
	jmp	0b							// repeat for next block
	.align	4,0x90
1:
	#endif
	ENDING							// update ABCDE (i=64:79)
	UPDATE_ALL_HASH					// update output hashes
	.endm

	/*
		 main sha1 code for system with ssse3 support
*/

	.macro  SHA1_PIPELINED_MAIN_BODY_ssse3
	LOAD_HASH						// load initial hashes into A,B,C,D,E
	INITIAL_W_PRECALC_ssse3			// big_endian_load(W) and W+K (i=0:15)
	.align	4,0x90
0:
	INTERNAL_ssse3					// update W (i=16:79) and update ABCDE (i=0:63)
#if Multiple_Blocks
	add	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	sub	$$1, cnt					// pre-decrement cnt by 1
	jbe	1f							// if cnt <= 0, branch to finish off
	SOFTWARE_PIPELINING_ssse3		// update ABCDE (i=64:79) || big_endian_load(W) and W+K (i=0:15)
	UPDATE_ALL_HASH					// update output hashes
	jmp	0b							// repeat for next block
	.align	4,0x90
1:
#endif
	ENDING							// update ABCDE (i=64:79)
	UPDATE_ALL_HASH					// update output hashes
	.endm

#if	KERNEL
#include <i386/cpu_capabilities.h>
#else
#include <System/i386/cpu_capabilities.h>
#endif

	.text

	.globl _sha1_block_asm_host_order
    .private_extern _sha1_block_asm_host_order
_sha1_block_asm_host_order:

	// detect SSSE3 and dispatch appropriate code branch
	#if defined __x86_64__
    	movq    __cpu_capabilities@GOTPCREL(%rip), %rax         // %rax -> __cpu_capabilities
    	mov     (%rax), %eax                                    // %eax = __cpu_capabilities
	#else       // i386
		#if defined KERNEL
    		leal    __cpu_capabilities, %eax                    // %eax -> __cpu_capabilities
    		mov     (%eax), %eax                                // %eax = __cpu_capabilities
		#else
    		mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
#endif
	#endif
    test    $(kHasSupplementalSSE3), %eax
    je      _SHA1Transform_nossse3_host_order                    			// branch to no-ssse3 code


	// start the sha1 code with ssse3 support

	// save callee-save registers
#if defined (__x86_64__)
	push	%rbx
	push	%rbp
#else
    push    %ebx
    push    %ebp
    push    %esi
    push    %edi
#endif

	sub		$stack_size, sp					// allocate stack memory for use

	// save used xmm register if this is for kernel
#if	KERNEL
	xmov	%xmm0, 4*16(sp)
	xmov	%xmm1, 5*16(sp)
	xmov	%xmm2, 6*16(sp)
	xmov	%xmm3, 7*16(sp)
	xmov	%xmm4, 8*16(sp)
	xmov	%xmm5, 9*16(sp)
	xmov	%xmm6, 10*16(sp)
	xmov	%xmm7, 11*16(sp)
#if defined (__x86_64__)
	xmov	%xmm8, 12*16(sp)
	xmov	%xmm9, 13*16(sp)
	xmov	%xmm10, 14*16(sp)
#endif
#endif

#if defined (__x86_64__)

	// set up registers to free %edx/%edi/%esi for other use (ABCDE)
	mov		ctx, HASH_PTR
	mov		buf, BUFFER_PTR
#if Multiple_Blocks
	mov		%rdx, cnt
#endif
	lea		K_XMM_AR(%rip), K_BASE
	xmov	-16(K_BASE), XMM_SHUFB_BSWAP

#else	// __i386__

#if	KERNEL
    lea     K_XMM_AR, %eax
#else
	// Get address of 0 in R.
           call    0f          // Push program counter onto stack.
        0: pop     %eax      // Get program counter.
		lea	K_XMM_AR-0b(%eax), %eax
#endif
    mov     %eax, K_BASE
    xmov    -16(%eax), %xmm0
    xmov    %xmm0, XMM_SHUFB_BSWAP

#endif

	SHA1_PIPELINED_MAIN_BODY_ssse3

	// restore used xmm registers if this is for kernel
#if	KERNEL
	xmov	4*16(sp), %xmm0
	xmov	5*16(sp), %xmm1
	xmov	6*16(sp), %xmm2
	xmov	7*16(sp), %xmm3
	xmov	8*16(sp), %xmm4
	xmov	9*16(sp), %xmm5
	xmov	10*16(sp), %xmm6
	xmov	11*16(sp), %xmm7
#if defined (__x86_64__)
	xmov	12*16(sp), %xmm8
	xmov	13*16(sp), %xmm9
	xmov	14*16(sp), %xmm10
#endif
#endif

	add		$stack_size, sp		// deallocate stack memory

	// restore callee-save registers
#if defined (__x86_64__)
	pop		%rbp
	pop		%rbx
#else
    pop     %edi
    pop     %esi
    pop     %ebp
    pop     %ebx
#endif

	ret							// return

	// this is equivalent to the above function _SHA1Transform, but it does not use ssse3 instructions

	.globl _SHA1Transform_nossse3_host_order
	.private_extern	_SHA1Transform_nossse3_host_order
_SHA1Transform_nossse3_host_order:

	// push callee-save registers
#if defined (__x86_64__)
	push	%rbx
	push	%rbp
#else
    push    %ebx
    push    %ebp
    push    %esi
    push    %edi
#endif

	sub		$stack_size, sp			// allocate stack memory for local use

	// save used xmm registers if this is for kernel
#if	KERNEL
	xmov	%xmm0, 4*16(sp)
	xmov	%xmm1, 5*16(sp)
	xmov	%xmm2, 6*16(sp)
	xmov	%xmm3, 7*16(sp)
	xmov	%xmm4, 8*16(sp)
	xmov	%xmm5, 9*16(sp)
	xmov	%xmm6, 10*16(sp)
	xmov	%xmm7, 11*16(sp)
#if defined (__x86_64__)
	xmov	%xmm8, 12*16(sp)
	xmov	%xmm9, 13*16(sp)
#endif
	#endif

#if defined (__x86_64__)

	// set up registers to free %edx/%edi/%esi for other use (ABCDE)
	mov		ctx, HASH_PTR
	mov		buf, BUFFER_PTR
#if Multiple_Blocks
	mov		%rdx, cnt
	#endif
	lea		K_XMM_AR(%rip), K_BASE

#else	// __i386__

#if	KERNEL
    lea     K_XMM_AR, %eax
#else
	// Get address of 0 in R.
           call    0f          // Push program counter onto stack.
        0: pop     %eax      // Get program counter.
		lea	K_XMM_AR-0b(%eax), %eax
#endif
    mov     %eax, K_BASE

#endif

	SHA1_PIPELINED_MAIN_BODY_nossse3

	// restore used xmm registers if this is for kernel
#if	KERNEL
	xmov	4*16(sp), %xmm0
	xmov	5*16(sp), %xmm1
	xmov	6*16(sp), %xmm2
	xmov	7*16(sp), %xmm3
	xmov	8*16(sp), %xmm4
	xmov	9*16(sp), %xmm5
	xmov	10*16(sp), %xmm6
	xmov	11*16(sp), %xmm7
#if defined (__x86_64__)
	xmov	12*16(sp), %xmm8
	xmov	13*16(sp), %xmm9
#endif
#endif

	add		$stack_size, sp		// deallocate stack memory

	// restore callee-save registers
#if defined (__x86_64__)
	pop		%rbp
	pop		%rbx
#else
    pop     %edi
    pop     %esi
    pop     %ebp
    pop     %ebx
#endif

	ret							// return

	.const
	.align	4, 0x90	

#define K1 0x5a827999
#define K2 0x6ed9eba1
#define K3 0x8f1bbcdc
#define K4 0xca62c1d6

bswap_shufb_ctl:
    .long	0x00010203
    .long	0x04050607
    .long	0x08090a0b
    .long	0x0c0d0e0f

K_XMM_AR:
    .long	K1
	.long	K1
	.long	K1
	.long	K1
    .long	K2
	.long	K2
	.long	K2
	.long	K2
    .long	K3
	.long	K3
	.long	K3
	.long	K3
    .long	K4
	.long	K4
	.long	K4
	.long	K4


#endif	// architecture x86_64 or i386
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/Digest/sha1edpLittleEndian.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
/* 	sha1edp.s : this file provides optimized x86_64 and i386 implementation of the sha1 function
	CoreOS - vector and numerics group
	cclee	6-21-10
	
	The implementation is based on the principle described in an Intel online article
	"Improving the Performance of the Secure Hash Algorithm (SHA-1)"
	http://software.intel.com/en-us/articles/improving-the-performance-of-the-secure-hash-algorithm-1/


	Update HASH[] by processing a one 64-byte block in MESSAGE[] can be represented by the following C function

void SHA1( int HASH[], int MESSAGE[] )
{
    int A[81], B[81], C[81], D[81], E[81];
    int W[80];

    int i, FN;

    A[0] = HASH[0]; 
    B[0] = HASH[1];
    C[0] = HASH[2];
    D[0] = HASH[3];
    E[0] = HASH[4];

    for ( i=0; i<80; ++i )
    {
        if ( i < 16 )
            W[i] = BIG_ENDIAN_LOAD( MESSAGE[i] );
        else
            W[i] = ROTATE_LEFT( W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1 );

        FN = F( i, B[i], C[i], D[i] );

        A[i+1] = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + W[i] + K(i);
        B[i+1] = A[i];
        C[i+1] = ROTATE_LEFT( B[i], 30 );
        D[i+1] = C[i];
        E[i+1] = D[i];
    }

    HASH[0] += A[80];
    HASH[1] += B[80];
    HASH[2] += C[80];
    HASH[3] += D[80];
    HASH[4] += E[80];
} 

	For i=0:15, W[i] is simply big-endian loading of MESSAGE[i]. For i=16:79, W[i] is updated according to W[i] = ROTATE_LEFT( W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1 );

	The approach (by Dean Gaudet) can be used to vectorize the computation of W[i] for i=16:79,

	1. done on 4 consequtive W[i] values in a single XMM register
    W[i  ] = (W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]) rol 1
    W[i+1] = (W[i-2] ^ W[i-7] ^ W[i-13] ^ W[i-15]) rol 1
    W[i+2] = (W[i-1] ^ W[i-6] ^ W[i-12] ^ W[i-14]) rol 1
    W[i+3] = (   0   ^ W[i-5] ^ W[i-11] ^ W[i-13]) rol 1

    2. this additional calculation unfortunately requires many additional operations
    W[i+3] ^= W[i] rol 1

    3. once we have 4 W[i] values in XMM we can also add four K values with one instruction
    W[i:i+3] += {K,K,K,K}

	Let W0 = {W[i] W[i+1] W[i+2] W[i+3]} be the current W-vector to be computed, W4 = {W[i-4] W[i-3] W[i-2] W[i-1]} be the previous vector, and so on
	The Dean Gaudet approach can be expressed as

	1. W0 = rotate_left(left_shift(W4,32) ^ W8 ^ left_shift(concatenate(W16,W12),64) ^ W16,1);
	2. W[i+3] ^= W[i] rol 1
	3. W0 += {K,K,K,K}

	For i>=32, the Intel online article suggests that (using a basic identity (X rol 1) rol 1 = X rol 2) the update equation is equivalent to

	1. W0 = rotate_left(left_shift(concatenate(W8,W4),64) ^ W16 ^ W28 ^ W32, 2); 

	Note:
	1. In total, we need 8 16-byte registers or memory for W0,W4,...,W28. W0 and W32 can be the same register or memory.
	2. The registers are used in a circular buffering mode. For example, we start with W28,W24,...,W0 (with W0 indicating the most recent 16-byte)
		i=0, W28,W24,...,W0
		i=4, W24,W20,...,W28
		i=8, W20,W16,...,W24
		.
		.
		and so forth.
	3. 2 ssse3 instructions are used in the Intel article, pshufb and palignr.
		a. pshufb is used to simplify the BIG_ENDIAN_LOAD operation 
		b. palignr is used to simplify the computation of left_shift(concatenate(W12,W8),64)
	4. we probe __cpu_capabilities to detect ssse3 support and dispatch code with ssse3 support when available.
	   If ssse3 is not supported, a suboptimal code (pshufb and palignr workaround) is dispatched. 

*/

/* the code can be compiled into single block (64 bytes) per call mode by setting Multiple_blocks to 0 */
#define	Multiple_Blocks	1

#if defined (__x86_64__) || defined(__i386__)		// x86_64 or i386 architectures

#if defined(__x86_64__)

	// set up for x86_64
#define	stack_size	(8+16*11+16*4)					// 8 (alignedment) + x0-x10 + 4 128-bits for intermediate WK(t) storage
#define	sp			%rsp							// unifying architectural stack pointer representation
#define	ctx			%rdi							// 1st input argument, will move to HASH_PTR (%r9)
#define	buf			%rsi							// 2nd input argument, will move to BUFFER_PTR (%r10) 
#define	cnt			%r11							// will copy from the 3rd input argument (%rdx)
#define K_BASE		%r8								// an aligned pointer to point to shufb reference numbers of table of K values
#define HASH_PTR	%r9								// pointer to Hash values (A,B,C,D,E)
#define BUFFER_PTR	%r10							// pointer to input blocks 

#else	// !__x86_64__

	// set up for i386 
#define stack_size	(12+16*2+16*11+16*4)			// 12-bytes (alignment) + extra 2 + 3 (W24/W28/XMM_SHUFB_BSWAP) + 8 (xmm0-xmm7) + 4 (WK(t))
#define	sp			%esp							// unifying architectural stack pointer representation
#define HASH_PTR	stack_size+16+4(sp)				// use 1st input argument from caller function, 16 for (esi/edi/ebx/ebp)
#define BUFFER_PTR	stack_size+16+8(sp)				// use 2nd input argument from caller function 
#define cnt			stack_size+16+12(sp)			// use 3rd input argument from caller function
#define K_BASE		stack_size-4(sp)				// use for K_BASE

#endif	// __x86_64__

// symbolizing registers or stack memory with algorithmic variables	W0,W4,...,W28 + W_TMP, W_TMP2, and XMM_SHUFB_BSWAP for code with ssse3 support

#define W_TMP  	%xmm0
#define W_TMP2 	%xmm1
#define W0  	%xmm2
#define W4  	%xmm3
#define W8  	%xmm4
#define W12 	%xmm5
#define W16 	%xmm6
#define W20 	%xmm7
#if defined(__x86_64__)
#define W24 	%xmm8
#define W28 	%xmm9
#define XMM_SHUFB_BSWAP %xmm10				// used only when ssse3 is supported
#else	// defined (__i386__)
#define W24     12*16(sp)
#define W28     13*16(sp)
#define XMM_SHUFB_BSWAP 14*16(sp)			// used only when ssse3 is supported 
#endif

#define	xmov	movaps						// aligned 16-byte move
#define	xmovu	movups						// unaligned 16-byte move

// intermediate hash variables
#define A %ecx
#define B %esi
#define C %edi
#define D %ebp
#define E %edx

// temp variables
#define T1 %eax
#define T2 %ebx

#define	WK(t)	(t&15)*4(sp)

	// int F1(int B, int C, int D) { return (D ^ ( B & (C ^ D)); }
	// result in T1
	.macro	F1
	mov	$1, T1
	xor	$2, T1
	and	$0, T1
	xor	$2, T1
	.endm

	// int F2(int B, int C, int D) { return (D ^ B ^ C); }
	// result in T1
	.macro	F2
	mov	$2, T1
	xor	$1, T1
	xor	$0, T1
	.endm

	// int F3(int B, int C, int D) { return (B & C) | (D & (B ^ C)); }
	// result in T1
	.macro	F3
		mov $1, T1
        mov $0, T2
        or  $0, T1
        and $1, T2
        and $2, T1
        or  T2, T1
	.endm

	// for i=60:79, F4 is identical to F2
	#define	F4	F2


	/*
		i=0:15, W[i] = BIG_ENDIAN_LOAD(MESSAGE[i]);

		with ssse3 support, this is achived via
		for (i=0;i<16;i+=4) {
			1. W_TMP = new 16 bytes from MESSAGE[]
			2. W_TMP = pshufb(W_TMP, XMM_SHUFB_BSWAP); save to W circular buffer for updating W 
			3. WTMP += {K,K,K,K};
			4. save quadruple W[i]+K[i] = W_TMP in the stack memory;
		}

		each step is represented in one of the following 4 macro definitions

	*/

	.macro	W_PRECALC_00_15_0_ssse3			// input argument $0 : 0/4/8/12
#if defined (__x86_64__)					// BUFFER_PTR is already an address register in x86_64
	xmovu	$0*4(BUFFER_PTR), W_TMP			// read 16-bytes into W_TMP, BUFFER_PTR possibly not 16-byte aligned
#else										// BUFFER_PTR is from the argument set up in the caller
	mov     BUFFER_PTR, T1					// T1 = BUFFER_PTR
    xmovu  $0*4(T1), W_TMP					// read 16-bytes into W_TMP, BUFFER_PTR possibly not 16-byte aligned
#endif
	.endm

	.macro	W_PRECALC_00_15_1_ssse3			// input argument $0 : current 16-bytes in the circular buffer, one of W0,W4,W8,...,W28
	pshufb	XMM_SHUFB_BSWAP, W_TMP			// convert W_TMP from little-endian into big-endian
	xmov	W_TMP, $0						// save W_TMP in the circular buffer
	.endm

	.macro	W_PRECALC_00_15_2				// K_BASE points to the current K quadruple.
#if defined (__x86_64__)					// K_BASE is already an address register in x86_64
	paddd	(K_BASE), W_TMP					// W_TMP += {K,K,K,K};
#else										// K_BASE is previously set up in the stack memory
	mov     K_BASE, T1						// T1 = K_BASE
    paddd   (T1), W_TMP						// W_TMP += {K,K,K,K};
#endif
	.endm

	.macro	W_PRECALC_00_15_3
	xmov	W_TMP, WK($0&~3)				// save quadruple W[i]+K in the stack memory, which would be used later for updating the hashes A/B/C/D/E
	.endm

	/*
		without ssse3 support, steps 1 and 2 need to be modified
		1. sequentially load 4 words into T1, bswap T1, and save it to 4-bytes in the stack space
		2. load the 16-bytes from the aligned stack memory into W_TMP
*/

	.macro	W_PRECALC_00_15_0_nossse3		// input argument $0 : 0/4/8/12

#if	defined (__x86_64__)
	#define	BUFFERP	BUFFER_PTR
#else
	mov		BUFFER_PTR, T2					// copy BUFFER_PTR (from caller 2nd argument) to T2
	#define	BUFFERP	T2
#endif

	// load 1st word, bswap it, save it to stack
	mov		$0*4(BUFFERP), T1
	bswap	T1
	mov		T1, 14*16(sp)

	// load 2nd word, bswap it, save it to stack
	mov		4+$0*4(BUFFERP), T1
	bswap	T1
	mov		T1, 4+14*16(sp)

	// load 3rd word, bswap it, save it to stack
	mov		8+$0*4(BUFFERP), T1
	bswap	T1
	mov		T1, 8+14*16(sp)

	// load 4th word, bswap it, save it to stack
	mov		12+$0*4(BUFFERP), T1
	bswap	T1
	mov		T1, 12+14*16(sp)
	.endm

	.macro	W_PRECALC_00_15_1_nossse3 		// input argument $0 : current 16-bytes in the circular buffer, one of W0,W4,W8,...,W28
	xmov	14*16(sp), W_TMP				// load the bswapped 16-bytes from the aligned stack memory
	xmov	W_TMP, $0						// save W = W_TMP in the circular buffer
	.endm

	// rounds 16-31 compute W[0] using the vectorization approach by Dean Gaudet
	/*
	W[i  ] = (W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]) rol 1
    W[i+1] = (W[i-2] ^ W[i-7] ^ W[i-13] ^ W[i-15]) rol 1
    W[i+2] = (W[i-1] ^ W[i-6] ^ W[i-12] ^ W[i-14]) rol 1
    W[i+3] = (   0   ^ W[i-5] ^ W[i-11] ^ W[i-13]) rol 1

	W[i+3] ^= W[i] rol 1;	// this W[i] is already rol by 1, if we are taking from the intial W before rol 1, we should rol this by 2

	The operation (updating W and W+K) is scheduled as and divided into 4 steps

	0. W_tmp = W3; W = W14 ^ W8
	1. W = W3 ^ W8 ^ W14 ^ W16; W_TMP = W; W_TMP2 = (W[i] 0 0 0); 
	2. W_TMP = (W3 ^ W8 ^ W14 ^ W16) rol 1; split (W[i] 0 0 0) rol 2 in W_TMP2 and W
	3. W = W_TMP = W_TMP ^ W_TMP2 ^ W = (W3 ^ W8 ^ W14 ^ W16) rol 1 ^ (W[i] 0 0 0) rol 2; WK = W _TMP+K;  

	*/

	.macro	W_PRECALC_16_31_0_ssse3	// input arguments : W16,W12,W8,W4,W
	xmov	$1, $4					// W = W12
	palignr	$$8, $0, $4				// W = W14
	xmov	$3, W_TMP				// W_TMP = W4
	psrldq	$$4, W_TMP				// W_TMP = W3
	pxor	$2, $4					// W = W8 ^ W14	
	.endm

	.macro	W_PRECALC_16_31_1		// input arguments : W16,W
	pxor	$0, W_TMP				// W_TMP = W3 ^ W16
	pxor	W_TMP, $1				// W = W3 ^ W16 ^ W8 ^ W14
	xmov	$1, W_TMP2				// W_TMP2 = W3 ^ W16 ^ W8 ^ W14 
	xmov	$1, W_TMP				// W_TMP = W3 ^ W16 ^ W8 ^ W14
	pslldq	$$12, W_TMP2			// W_TMP2 = (W[i] 0 0 0)
	.endm

	.macro	W_PRECALC_16_31_2		// input argument : W
	psrld	$$31, $0				// (W3 ^ W16 ^ W8 ^ W14)>>31
	pslld	$$1, W_TMP				// (W3 ^ W16 ^ W8 ^ W14)<<1
	por		$0, W_TMP				// W_TMP = (W3 ^ W16 ^ W8 ^ W14) rol 1
	xmov	W_TMP2, $0				// copy W[i] at location of W[i+3]
	psrld	$$30, W_TMP2			// W_TMP2 = W[i] lower 2 bits after rol 2
	pslld	$$2, $0					// W = W[i] higher 30 bits after rol 2
	.endm

	.macro	W_PRECALC_16_31_3		// input arguments: W, i, K_XMM
#if defined (__i386__)
	mov     K_BASE, T1				// K_BASE is store in the stack memory for i386
#endif
	pxor	$0, W_TMP
	pxor	W_TMP2, W_TMP			// W_TMP = (W3 ^ W16 ^ W8 ^ W14) rol 1 ^ (W[i] 0 0 0) rol 2
	xmov	W_TMP, $0				// save W = W_TMP in the W circular buffer
#if defined (__x86_64__)
	paddd	$2(K_BASE), W_TMP		// W+K
#else
    paddd   $2(T1), W_TMP			// W+K
#endif
	xmov	W_TMP, WK($1&~3)		// save WK = W+K for later update of the hashes A/B/C/D/E
	.endm

	// the following is a variant of W_PRECALC_16_31_0_ssse3 to be used for system without ssse3, palignr is replaced with 4 instructions

	.macro	W_PRECALC_16_31_0_nossse3	// input arguments : W16,W12,W8,W4,W
	xmov	$1, $4						// W = W12 = (w9 w10 w11 w12)

	// the following is a wrokaround for palignr
	xmov	$0, W_TMP					// W16 = (w13 w14 w15 w16)
	pslldq	$$8, $4						// shift left to make (w11 w12 0 0)
	psrldq	$$8, W_TMP					// shift right to make (0 0 w13 w14)
	por		W_TMP, $4					// W = W14 = (w11 w12 w13 w14)

	xmov	$3, W_TMP					// W_TMP = W4 = (w1 w2 w3 w4)
	psrldq	$$4, W_TMP					// W_TMP = W3 = (0 w1 w2 w3)
	pxor	$2, $4						// W = W8 ^ W14	
	.endm

	/* rounds 32-79 compute W und W+K iusing the vectorization approach from the Intel article

		W = rotate_left(left_shift(concatenate(W8,W4),64) ^ W16 ^ W28 ^ W32, 2);

		where left_shift(concatenate(W8,W4),64) is equivalent to W6. Note also that W32 and W use the same register.


	0. W_tmp = W6; W = W28 ^ W32;
	1. W = W_tmp = W6 ^ W16 ^ W28 ^ W32;
	2. W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2;
	3. W = W_Tmp; WK = W_tmp + K;

*/


	.macro	W_PRECALC_32_79_0_ssse3		// inputr arguments : W28,W8,W4,W
	xmov	$2, W_TMP					// (w1 w2 w3 w4)
	pxor	$0, $3						// W = W28 ^ W32;
	palignr	$$8, $1, W_TMP				// W_tmp = (w3 w4 w5 w6) = W6;
	.endm

	// the following is a variant and will be used for system without ssse3 support
	.macro	W_PRECALC_32_79_0_nossse3	// input arguments : W28,W8,W4,W
	xmov	$2, W_TMP					// (w1 w2 w3 w4)
	xmov    $1, W_TMP2					// (w5 w6 w7 w8)
	pxor	$0, $3						// W = W28 ^ W32
	pslldq	$$8, W_TMP					// (w3 w4 0 0)
	psrldq	$$8, W_TMP2					// (0 0 w5 w6)
	por		W_TMP2, W_TMP				// W_tmp = (w3 w4 w5 w6) = W6
	.endm

	// this is a variant of W_PRECALC_32_79_0_ssse3 for i386 (as W24/W28 are stored in memory, not in registers)
	.macro  W_PRECALC_32_79_0_i386_ssse3	// input arguments : W28,W8,W4,W
    xmov    $3, W_TMP						// W32
    pxor    $0, W_TMP						// W28 ^ W32
    xmov    W_TMP, $3						// W = W28 ^ W32;
    xmov    $2, W_TMP						// W4
    palignr $$8, $1, W_TMP					// W_tmp = (w3 w4 w5 w6) = W6;
    .endm

	// this is a variant of W_PRECALC_32_79_0_nossse3 for i386 (as W24/W28 are stored in memory, not in registers)
	.macro  W_PRECALC_32_79_0_i386_nossse3  // input arguments : W28,W8,W4,W
    xmov    $3, W_TMP						// W32
    pxor    $0, W_TMP						// W28 ^ W32
    xmov    W_TMP, $3						// W = W28 ^ W32
    xmov    $2, W_TMP						// W4 = (w1 w2 w3 w4)
	xmov    $1, W_TMP2						// W8 = (w5 w6 w7 w8)
	pslldq	$$8, W_TMP						// (w3 w4 0 0)
	psrldq	$$8, W_TMP2						// (0 0 w5 w6)
	por		W_TMP2, W_TMP					// W_tmp = (w3 w4 w5 w6) = W6
    .endm

	.macro	W_PRECALC_32_79_1			// input arguments : W16,W
	pxor	$0, W_TMP					// W_tmp = W6 ^ W16
	pxor	$1, W_TMP					// W_tmp = W6 ^ W16 ^ W28 ^ W32
	xmov	W_TMP, $1					// W = W_tmp = W6 ^ W16 ^ W28 ^ W32
	.endm

	.macro	W_PRECALC_32_79_2			// input argument : W
	psrld	$$30, $0					// W >> 30
	pslld	$$2, W_TMP					// W << 2
	por		$0, W_TMP					// W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2
	.endm

	// this is a variant of W_PRECALC_32_79_2 for i386 (as W24/W28 are stored in memory, not in registers)
	// this should be used when the input is either W24 or W28 on i386 architecture
    .macro  W_PRECALC_32_79_2_i386  	// input argument : W
    xmov    $0, W_TMP2					// W
    psrld   $$30, W_TMP2				// W >> 30
    xmov    W_TMP2, $0					// save (W >> 30) at W
    pslld   $$2, W_TMP					// W_tmp << 2
    por     $0, W_TMP					// W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2
    .endm

	.macro	W_PRECALC_32_79_3			// input argument W, i, K_XMM
#if defined (__x86_64__)
	xmov	W_TMP, $0					// W = (W6 ^ W16 ^ W28 ^ W32) rol 2
	paddd	$2(K_BASE), W_TMP			// W + K
	xmov	W_TMP, WK($1&~3)			// write W+K
#else
    mov     K_BASE, T1					// T1 = K_BASE (which is in the caller argument)
    xmov    W_TMP, $0					// W = (W6 ^ W16 ^ W28 ^ W32) rol 2
    paddd   $2(T1), W_TMP				// W_tmp = W + K
    xmov    W_TMP, WK($1&~3)			// write WK
	#endif
	.endm


	/* The hash update operation is completed by the following statements.

		A[i+1] = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + WK(i);
        B[i+1] = A[i];
        C[i+1] = ROTATE_LEFT( B[i], 30 );
        D[i+1] = C[i];
        E[i+1] = D[i];

		Suppose we start with A0,B0,C0,D0,E0. The 1st iteration can be expressed as follows:

		A1 = FN + E0 + rol(A0,5) + WK;
		B1 = A0;
		C1 = rol(B0, 30);
		D1 = C0;
		E1 = D0;

		to avoid excessive memory movement between registers, 
			1. A1 = FN + E0 + rol(A0,5) + WK; can be temporarily saved in E0, 
			2. C1 = rol(B0,30) can be temporarily saved in B0. 

		Therefore, ignoring the time index, the update operation is equivalent to
			1. E = FN(B,C,D) + E + rol(A,5) + WK(i)
			2. B = rol(B,30)
			3. the hashes are now stored in the order of E,A,B,C,D


		To pack 2 hash update operations in 1 iteration, starting with A,B,C,D,E
		1. E = FN(B,C,D) + E + rol(A,5) + WK(i)
		2. B = rol(B,30)
		// now the hashes are in the order of E,A,B,C,D
		3. D = FN(A,B,C) + D + rol(E,5) + WK(i+1)
		4. A = rol(A,30)
		// now the hashes are in the order of D,E,A,B,C
	
		These operations are distributed into the following 2 macro definitions RR0 and RR1.	

*/

	.macro	RR0				// input arguments : FN, A, B, C, D, E, i
	$0		$2, $3, $4		// T1 = FN(B,C,D)
	add		WK($6), $5		// E + WK(i)
	rol		$$30, $2		// B = rol(B,30)
	mov		$1, T2			// T2 = A
	add		WK($6+1), $4	// D + WK(i+1)
	rol		$$5, T2			// rol(A,5)
	add		T1, $5			// E = FN(B,C,D) + E + WK(i)
	.endm

	.macro	RR1
	add		$5, T2			// T2 = FN(B,C,D) + E + rol(A,5) + WK(i)
	mov		T2, $5			// E = FN(B,C,D) + E + rol(A,5) + WK(i)
	rol		$$5, T2			// rol(E,5)
	add		T2, $4			// D + WK(i+1) + rol(E,5)
	$0		$1, $2, $3		// FN(A,B,C)
	add		T1, $4			// D = FN(A,B,C) + D + rol(E,5) + WK(i+1)
	rol		$$30, $1		// A = rol(A,30)
	.endm



	/*

		The following macro definitions are used to expand code for the per-block sha1 operation.

			INITIAL_W_PRECALC_ssse3	: BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack memory
			INTERNAL_ssse3 : updating W (16:79) and update the digests A/B/C/D/E (i=0:63, based on W+K stored in the stack memory) 
			ENDING : finishing up update the digests A/B/C/D/E (i=64:79)

		For multiple-block sha1 operation (Multiple_Blocks = 1), INITIAL_W_PRECALC_ssse3 and ENDING are combined
		into 1 macro definition for software pipeling.

			SOFTWARE_PIPELINING_ssse3 : BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack, and finishing up update the digests A/B/C/D/E (i=64:79) 

		assume cnt (the number of blocks)  >= 1, the main code body should look like

		INITIAL_W_PRECALC_ssse3				// W = big_endian_load and pre-compute W+K (i=0:15)
		do {
			INTERNAL_ssse3					// update W(i=16:79), and update hash digests A/B/C/D/E (i=0:63)
			cnt--;
			if (cnt==0) break;
			BUFFER_PTR += 64;
			SOFTWARE_PIPELINING_ssse3;		// update hash digests A/B/C/D/E (i=64:79) + W = big_endian_load and pre-compute W+K (i=0:15)
		}
		ENDING								// update hash digests A/B/C/D/E (i=64:79)

	*/

	#define	W_PRECALC_00_15_0	W_PRECALC_00_15_0_ssse3
	#define	W_PRECALC_00_15_1	W_PRECALC_00_15_1_ssse3
	#define	W_PRECALC_16_31_0	W_PRECALC_16_31_0_ssse3
	#define	W_PRECALC_32_79_0	W_PRECALC_32_79_0_ssse3
	#define	W_PRECALC_32_79_0_i386	W_PRECALC_32_79_0_i386_ssse3


	.macro	INITIAL_W_PRECALC_ssse3			// BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack memory	

	// i=0 	: W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K

	// i=4	: W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K

	.endm


	.macro	INTERNAL_ssse3					// updating W (16:79) and update the digests A/B/C/D/E (i=0:63, based on W+K stored in the stack memory)

	// i=16 : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_16_31_0	W0,W28,W24,W20,W16
	RR0					F1,A,B,C,D,E,0
	W_PRECALC_16_31_1	W0,W16
	RR1					F1,A,B,C,D,E,0
	W_PRECALC_16_31_2	W16
	RR0					F1,D,E,A,B,C,2
	W_PRECALC_16_31_3	W16, 2, 0
	RR1					F1,D,E,A,B,C,2

	// i=20 : W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_16_31_0	W28,W24,W20,W16,W12
	RR0					F1,B,C,D,E,A,4
	W_PRECALC_16_31_1	W28,W12
	RR1					F1,B,C,D,E,A,4
	W_PRECALC_16_31_2	W12
	RR0					F1,E,A,B,C,D,6
	W_PRECALC_16_31_3	W12, 6, 16
	RR1					F1,E,A,B,C,D,6

	// i=24 : W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_16_31_0	W24,W20,W16,W12,W8
	RR0					F1,C,D,E,A,B,8
	W_PRECALC_16_31_1	W24,W8
	RR1					F1,C,D,E,A,B,8
	W_PRECALC_16_31_2	W8
	RR0					F1,A,B,C,D,E,10
	W_PRECALC_16_31_3	W8,10,16
	RR1					F1,A,B,C,D,E,10

	// i=28 : W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_16_31_0	W20,W16,W12,W8,W4
	RR0					F1,D,E,A,B,C,12
	W_PRECALC_16_31_1	W20,W4
	RR1					F1,D,E,A,B,C,12
	W_PRECALC_16_31_2	W4
	RR0					F1,B,C,D,E,A,14
	W_PRECALC_16_31_3	W4,14,16
	RR1					F1,B,C,D,E,A,14

	// i=32 : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F1,E,A,B,C,D,16
	W_PRECALC_32_79_1	W16,W0
	RR1					F1,E,A,B,C,D,16
	W_PRECALC_32_79_2	W0
	RR0					F1,C,D,E,A,B,18
	W_PRECALC_32_79_3	W0,18,16
	RR1					F1,C,D,E,A,B,18

	// starting using F2	

	// i=36 : W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F2,A,B,C,D,E,20
	W_PRECALC_32_79_1	W12,W28
	RR1					F2,A,B,C,D,E,20
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F2,D,E,A,B,C,22
	W_PRECALC_32_79_3	W28,22,16
	RR1					F2,D,E,A,B,C,22

	// i=40 : W20,W16,W12,W8,W4,W0,W28,W24	
	#undef  K_XMM
    #define K_XMM   32
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F2,B,C,D,E,A,24
	W_PRECALC_32_79_1	W8,W24
	RR1					F2,B,C,D,E,A,24
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F2,E,A,B,C,D,26
	W_PRECALC_32_79_3	W24,26,K_XMM
	RR1					F2,E,A,B,C,D,26

	// i=44 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F2,C,D,E,A,B,28
	W_PRECALC_32_79_1	W4,W20
	RR1					F2,C,D,E,A,B,28
	W_PRECALC_32_79_2	W20
	RR0					F2,A,B,C,D,E,30
	W_PRECALC_32_79_3	W20,30,K_XMM
	RR1					F2,A,B,C,D,E,30

	// i=48 : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_32_79_0	W12,W24,W20,W16
	RR0					F2,D,E,A,B,C,32
	W_PRECALC_32_79_1	W0,W16
	RR1					F2,D,E,A,B,C,32
	W_PRECALC_32_79_2	W16
	RR0					F2,B,C,D,E,A,34
	W_PRECALC_32_79_3	W16,34,K_XMM
	RR1					F2,B,C,D,E,A,34

	// i=52 : W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_32_79_0	W8,W20,W16,W12
	RR0					F2,E,A,B,C,D,36
	W_PRECALC_32_79_1	W28,W12
	RR1					F2,E,A,B,C,D,36
	W_PRECALC_32_79_2	W12
	RR0					F2,C,D,E,A,B,38
	W_PRECALC_32_79_3	W12,38,K_XMM
	RR1					F2,C,D,E,A,B,38

	// starting using F3	

	// i=56 : W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_32_79_0	W4,W16,W12,W8
	RR0					F3,A,B,C,D,E,40
	W_PRECALC_32_79_1	W24,W8
	RR1					F3,A,B,C,D,E,40
	W_PRECALC_32_79_2	W8
	RR0					F3,D,E,A,B,C,42
	W_PRECALC_32_79_3	W8,42,K_XMM
	RR1					F3,D,E,A,B,C,42

	// i=60 : W0,W28,W24,W20,W16,W12,W8,W4
	#undef	K_XMM
	#define	K_XMM	48
	W_PRECALC_32_79_0	W0,W12,W8,W4
	RR0					F3,B,C,D,E,A,44
	W_PRECALC_32_79_1	W20,W4
	RR1					F3,B,C,D,E,A,44
	W_PRECALC_32_79_2	W4
	RR0					F3,E,A,B,C,D,46
	W_PRECALC_32_79_3	W4,46,K_XMM
	RR1					F3,E,A,B,C,D,46

	// i=64 : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F3,C,D,E,A,B,48
	W_PRECALC_32_79_1	W16,W0
	RR1					F3,C,D,E,A,B,48
	W_PRECALC_32_79_2	W0
	RR0					F3,A,B,C,D,E,50
	W_PRECALC_32_79_3	W0,50,K_XMM
	RR1					F3,A,B,C,D,E,50

	// i=68 : W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F3,D,E,A,B,C,52
	W_PRECALC_32_79_1	W12,W28
	RR1					F3,D,E,A,B,C,52
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F3,B,C,D,E,A,54
	W_PRECALC_32_79_3	W28,54,K_XMM
	RR1					F3,B,C,D,E,A,54

	// i=72 : W20,W16,W12,W8,W4,W0,W28,W24
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F3,E,A,B,C,D,56
	W_PRECALC_32_79_1	W8,W24
	RR1					F3,E,A,B,C,D,56
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F3,C,D,E,A,B,58
	W_PRECALC_32_79_3	W24,58,K_XMM
	RR1					F3,C,D,E,A,B,58

	// starting using F4	

	// i=76 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F4,A,B,C,D,E,60
	W_PRECALC_32_79_1	W4,W20
	RR1					F4,A,B,C,D,E,60
	W_PRECALC_32_79_2	W20
	RR0					F4,D,E,A,B,C,62
	W_PRECALC_32_79_3	W20,62,K_XMM
	RR1					F4,D,E,A,B,C,62

	.endm

	.macro	SOFTWARE_PIPELINING_ssse3
	// i=0  : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	RR0					F4,B,C,D,E,A,64
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	RR1					F4,B,C,D,E,A,64
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	RR0					F4,E,A,B,C,D,66
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K
	RR1					F4,E,A,B,C,D,66

	// i=4  : W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	RR0					F4,C,D,E,A,B,68
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	RR1					F4,C,D,E,A,B,68
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	RR0					F4,A,B,C,D,E,70
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K[0]
	RR1					F4,A,B,C,D,E,70

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	RR0					F4,D,E,A,B,C,72
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	RR1					F4,D,E,A,B,C,72
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	RR0					F4,B,C,D,E,A,74
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K
	RR1					F4,B,C,D,E,A,74

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	RR0					F4,E,A,B,C,D,76
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	RR1					F4,E,A,B,C,D,76
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	RR0					F4,C,D,E,A,B,78
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K
	RR1					F4,C,D,E,A,B,78
	.endm


	#undef	W_PRECALC_00_15_0
	#undef	W_PRECALC_00_15_1
	#undef	W_PRECALC_16_31_0
	#undef	W_PRECALC_32_79_0
	#undef	W_PRECALC_32_79_0_i386



	/* 

		The following are 3 macro definitions that are no-ssse3 variants of the previous 3 macro definitions.

		INITIAL_W_PRECALC_nossse3
		INTERNAL_nossse3
		SOFTWARE_PIPELINING_nossse3
		
		They will be used in a sha1 code main body definition that will be used for system without ssse3 support.	

	*/

	#define	W_PRECALC_00_15_0	W_PRECALC_00_15_0_nossse3
	#define	W_PRECALC_00_15_1	W_PRECALC_00_15_1_nossse3
	#define	W_PRECALC_16_31_0	W_PRECALC_16_31_0_nossse3
	#define	W_PRECALC_32_79_0	W_PRECALC_32_79_0_nossse3
	#define	W_PRECALC_32_79_0_i386	W_PRECALC_32_79_0_i386_nossse3


	.macro	INITIAL_W_PRECALC_nossse3

	// i=0 	: W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K

	// i=4	: W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K

	.endm


	.macro	INTERNAL_nossse3
	// i=16
	// circular buffer : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_16_31_0	W0,W28,W24,W20,W16
	RR0					F1,A,B,C,D,E,0
	W_PRECALC_16_31_1	W0,W16
	RR1					F1,A,B,C,D,E,0
	W_PRECALC_16_31_2	W16
	RR0					F1,D,E,A,B,C,2
	W_PRECALC_16_31_3	W16, 2, 0
	RR1					F1,D,E,A,B,C,2

	// i=20,
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_16_31_0	W28,W24,W20,W16,W12
	RR0					F1,B,C,D,E,A,4
	W_PRECALC_16_31_1	W28,W12
	RR1					F1,B,C,D,E,A,4

	W_PRECALC_16_31_2	W12
	RR0					F1,E,A,B,C,D,6
	W_PRECALC_16_31_3	W12, 6, 16
	RR1					F1,E,A,B,C,D,6

	// i=24,
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_16_31_0	W24,W20,W16,W12,W8
	RR0					F1,C,D,E,A,B,8
	W_PRECALC_16_31_1	W24,W8
	RR1					F1,C,D,E,A,B,8

	W_PRECALC_16_31_2	W8
	RR0					F1,A,B,C,D,E,10
	W_PRECALC_16_31_3	W8,10,16
	RR1					F1,A,B,C,D,E,10

	// i=28
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_16_31_0	W20,W16,W12,W8,W4
	RR0					F1,D,E,A,B,C,12
	W_PRECALC_16_31_1	W20,W4
	RR1					F1,D,E,A,B,C,12

	W_PRECALC_16_31_2	W4
	RR0					F1,B,C,D,E,A,14
	W_PRECALC_16_31_3	W4,14,16
	RR1					F1,B,C,D,E,A,14

	//i=32
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F1,E,A,B,C,D,16
	W_PRECALC_32_79_1	W16,W0
	RR1					F1,E,A,B,C,D,16
	W_PRECALC_32_79_2	W0
	RR0					F1,C,D,E,A,B,18
	W_PRECALC_32_79_3	W0,18,16
	RR1					F1,C,D,E,A,B,18

	//i=36
	// W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F2,A,B,C,D,E,20
	W_PRECALC_32_79_1	W12,W28
	RR1					F2,A,B,C,D,E,20
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F2,D,E,A,B,C,22
	W_PRECALC_32_79_3	W28,22,16
	RR1					F2,D,E,A,B,C,22

	//i=40
	#undef  K_XMM
    #define K_XMM   32
	// W20,W16,W12,W8,W4,W0,W28,W24	
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F2,B,C,D,E,A,24
	W_PRECALC_32_79_1	W8,W24
	RR1					F2,B,C,D,E,A,24
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F2,E,A,B,C,D,26
	W_PRECALC_32_79_3	W24,26,K_XMM
	RR1					F2,E,A,B,C,D,26

	//i=44
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F2,C,D,E,A,B,28
	W_PRECALC_32_79_1	W4,W20
	RR1					F2,C,D,E,A,B,28
	W_PRECALC_32_79_2	W20
	RR0					F2,A,B,C,D,E,30
	W_PRECALC_32_79_3	W20,30,K_XMM
	RR1					F2,A,B,C,D,E,30

	//i=48
	// W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_32_79_0	W12,W24,W20,W16
	RR0					F2,D,E,A,B,C,32
	W_PRECALC_32_79_1	W0,W16
	RR1					F2,D,E,A,B,C,32
	W_PRECALC_32_79_2	W16
	RR0					F2,B,C,D,E,A,34
	W_PRECALC_32_79_3	W16,34,K_XMM
	RR1					F2,B,C,D,E,A,34

	//i=52
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_32_79_0	W8,W20,W16,W12
	RR0					F2,E,A,B,C,D,36
	W_PRECALC_32_79_1	W28,W12
	RR1					F2,E,A,B,C,D,36
	W_PRECALC_32_79_2	W12
	RR0					F2,C,D,E,A,B,38
	W_PRECALC_32_79_3	W12,38,K_XMM
	RR1					F2,C,D,E,A,B,38

	//i=56
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_32_79_0	W4,W16,W12,W8
	RR0					F3,A,B,C,D,E,40
	W_PRECALC_32_79_1	W24,W8
	RR1					F3,A,B,C,D,E,40
	W_PRECALC_32_79_2	W8
	RR0					F3,D,E,A,B,C,42
	W_PRECALC_32_79_3	W8,42,K_XMM
	RR1					F3,D,E,A,B,C,42

	//i=60
	#undef	K_XMM
	#define	K_XMM	48
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_32_79_0	W0,W12,W8,W4
	RR0					F3,B,C,D,E,A,44
	W_PRECALC_32_79_1	W20,W4
	RR1					F3,B,C,D,E,A,44
	W_PRECALC_32_79_2	W4
	RR0					F3,E,A,B,C,D,46
	W_PRECALC_32_79_3	W4,46,K_XMM
	RR1					F3,E,A,B,C,D,46

	//i=64
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F3,C,D,E,A,B,48
	W_PRECALC_32_79_1	W16,W0
	RR1					F3,C,D,E,A,B,48
	W_PRECALC_32_79_2	W0
	RR0					F3,A,B,C,D,E,50
	W_PRECALC_32_79_3	W0,50,K_XMM
	RR1					F3,A,B,C,D,E,50

	//i=68
	// W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F3,D,E,A,B,C,52
	W_PRECALC_32_79_1	W12,W28
	RR1					F3,D,E,A,B,C,52
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F3,B,C,D,E,A,54
	W_PRECALC_32_79_3	W28,54,K_XMM
	RR1					F3,B,C,D,E,A,54

	//i=72
	// W20,W16,W12,W8,W4,W0,W28,W24
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F3,E,A,B,C,D,56
	W_PRECALC_32_79_1	W8,W24
	RR1					F3,E,A,B,C,D,56
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F3,C,D,E,A,B,58
	W_PRECALC_32_79_3	W24,58,K_XMM
	RR1					F3,C,D,E,A,B,58

	// starting using F4	

	//i=76
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F4,A,B,C,D,E,60
	W_PRECALC_32_79_1	W4,W20
	RR1					F4,A,B,C,D,E,60
	W_PRECALC_32_79_2	W20
	RR0					F4,D,E,A,B,C,62
	W_PRECALC_32_79_3	W20,62,K_XMM
	RR1					F4,D,E,A,B,C,62

	.endm

	.macro	SOFTWARE_PIPELINING_nossse3
	// i=0  : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	RR0					F4,B,C,D,E,A,64
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	RR1					F4,B,C,D,E,A,64
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	RR0					F4,E,A,B,C,D,66
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K
	RR1					F4,E,A,B,C,D,66

	// i=4  : W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	RR0					F4,C,D,E,A,B,68
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	RR1					F4,C,D,E,A,B,68
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	RR0					F4,A,B,C,D,E,70
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K[0]
	RR1					F4,A,B,C,D,E,70

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	RR0					F4,D,E,A,B,C,72
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	RR1					F4,D,E,A,B,C,72
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	RR0					F4,B,C,D,E,A,74
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K
	RR1					F4,B,C,D,E,A,74

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	RR0					F4,E,A,B,C,D,76
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	RR1					F4,E,A,B,C,D,76
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	RR0					F4,C,D,E,A,B,78
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K
	RR1					F4,C,D,E,A,B,78
	.endm

	.macro	ENDING		// finish up updating hash digests (i=64:79)
	//i=80
	RR0					F4,B,C,D,E,A,64
	RR1					F4,B,C,D,E,A,64
	RR0					F4,E,A,B,C,D,66
	RR1					F4,E,A,B,C,D,66

	//i=84
	RR0					F4,C,D,E,A,B,68
	RR1					F4,C,D,E,A,B,68
	RR0					F4,A,B,C,D,E,70
	RR1					F4,A,B,C,D,E,70

	//i=88
	RR0					F4,D,E,A,B,C,72
	RR1					F4,D,E,A,B,C,72
	RR0					F4,B,C,D,E,A,74
	RR1					F4,B,C,D,E,A,74

	//i=92
	RR0					F4,E,A,B,C,D,76
	RR1					F4,E,A,B,C,D,76
	RR0					F4,C,D,E,A,B,78
	RR1					F4,C,D,E,A,B,78
	.endm

	// load hash digests A,B,C,D,E from memory into registers
	.macro	LOAD_HASH
#if defined (__x86_64__)
	mov			(HASH_PTR), A
	mov			4(HASH_PTR), B
	mov			8(HASH_PTR), C
	mov			12(HASH_PTR), D
	mov			16(HASH_PTR), E
#else
    mov         HASH_PTR, T1
    mov         (T1), A
    mov         4(T1), B
    mov         8(T1), C
    mov         12(T1), D
    mov         16(T1), E
#endif
	.endm

	.macro	UPDATE_HASH
	add		$0, $1
	mov		$1, $0
	.endm

	.macro UPDATE_ALL_HASH	
#if defined (__x86_64__)
	UPDATE_HASH		(HASH_PTR), A
	UPDATE_HASH		4(HASH_PTR), B
	UPDATE_HASH		8(HASH_PTR), C
	UPDATE_HASH		12(HASH_PTR), D
	UPDATE_HASH		16(HASH_PTR), E
#else
    mov             HASH_PTR, T1
    UPDATE_HASH     (T1), A
    UPDATE_HASH     4(T1), B
    UPDATE_HASH     8(T1), C
    UPDATE_HASH     12(T1), D
    UPDATE_HASH     16(T1), E
#endif
	.endm


	/*
		 main sha1 code for system without ssse3 support
	*/

	.macro  SHA1_PIPELINED_MAIN_BODY_nossse3
	LOAD_HASH						// load initial hashes into A,B,C,D,E (registers)
	INITIAL_W_PRECALC_nossse3		// big_endian_load(W) and W+K (i=0:15)
	.align	4,0x90
0:
	INTERNAL_nossse3				// update W (i=16:79) and update ABCDE (i=0:63)	
#if Multiple_Blocks
	add	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	sub	$$1, cnt					// pre-decrement cnt by 1
	jbe	1f							// if cnt <= 0, branch to finish off
	SOFTWARE_PIPELINING_nossse3		// update ABCDE (i=64:79) || big_endian_load(W) and W+K (i=0:15)
	UPDATE_ALL_HASH					// update output hashes
	jmp	0b							// repeat for next block
	.align	4,0x90
1:
	#endif
	ENDING							// update ABCDE (i=64:79)
	UPDATE_ALL_HASH					// update output hashes
	.endm

	/*
		 main sha1 code for system with ssse3 support
*/

	.macro  SHA1_PIPELINED_MAIN_BODY_ssse3
	LOAD_HASH						// load initial hashes into A,B,C,D,E
	INITIAL_W_PRECALC_ssse3			// big_endian_load(W) and W+K (i=0:15)
	.align	4,0x90
0:
	INTERNAL_ssse3					// update W (i=16:79) and update ABCDE (i=0:63)
#if Multiple_Blocks
	add	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	sub	$$1, cnt					// pre-decrement cnt by 1
	jbe	1f							// if cnt <= 0, branch to finish off
	SOFTWARE_PIPELINING_ssse3		// update ABCDE (i=64:79) || big_endian_load(W) and W+K (i=0:15)
	UPDATE_ALL_HASH					// update output hashes
	jmp	0b							// repeat for next block
	.align	4,0x90
1:
#endif
	ENDING							// update ABCDE (i=64:79)
	UPDATE_ALL_HASH					// update output hashes
	.endm

#if	KERNEL
#include <i386/cpu_capabilities.h>
#else
#include <System/i386/cpu_capabilities.h>
#endif

	.text

    .globl _sha1_block_asm_data_order
    .private_extern _sha1_block_asm_data_order
_sha1_block_asm_data_order:

	// detect SSSE3 and dispatch appropriate code branch
	#if defined __x86_64__
    	movq    __cpu_capabilities@GOTPCREL(%rip), %rax         // %rax -> __cpu_capabilities
    	mov     (%rax), %eax                                    // %eax = __cpu_capabilities
	#else       // i386
		#if KERNEL
    		leal    __cpu_capabilities, %eax                    // %eax -> __cpu_capabilities
    		mov     (%eax), %eax                                // %eax = __cpu_capabilities
		#else
    		mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
#endif
	#endif
    test    $(kHasSupplementalSSE3), %eax
    je      _SHA1Transform_nossse3                    			// branch to no-ssse3 code

	// start the sha1 code with ssse3 support

	// save callee-save registers
#if defined (__x86_64__)
	push	%rbx
	push	%rbp
#else
    push    %ebx
    push    %ebp
    push    %esi
    push    %edi
#endif

	sub		$stack_size, sp					// allocate stack memory for use

	// save used xmm register if this is for kernel
#if	KERNEL
	xmov	%xmm0, 4*16(sp)
	xmov	%xmm1, 5*16(sp)
	xmov	%xmm2, 6*16(sp)
	xmov	%xmm3, 7*16(sp)
	xmov	%xmm4, 8*16(sp)
	xmov	%xmm5, 9*16(sp)
	xmov	%xmm6, 10*16(sp)
	xmov	%xmm7, 11*16(sp)
#if defined (__x86_64__)
	xmov	%xmm8, 12*16(sp)
	xmov	%xmm9, 13*16(sp)
	xmov	%xmm10, 14*16(sp)
#endif
#endif

#if defined (__x86_64__)

	// set up registers to free %edx/%edi/%esi for other use (ABCDE)
	mov		ctx, HASH_PTR
	mov		buf, BUFFER_PTR
#if Multiple_Blocks
	mov		%rdx, cnt
#endif
	lea		K_XMM_AR(%rip), K_BASE
	xmov	0x40(K_BASE), XMM_SHUFB_BSWAP

#else	// __i386__

#if	KERNEL
    lea     K_XMM_AR, %eax
#else
	// Get address of 0 in R.
           call    0f          // Push program counter onto stack.
        0: pop     %eax      // Get program counter.
		lea	K_XMM_AR-0b(%eax), %eax
#endif
    mov     %eax, K_BASE
    xmov    0x40(%eax), %xmm0
    xmov    %xmm0, XMM_SHUFB_BSWAP

#endif

	SHA1_PIPELINED_MAIN_BODY_ssse3

	// restore used xmm registers if this is for kernel
#if	KERNEL
	xmov	4*16(sp), %xmm0
	xmov	5*16(sp), %xmm1
	xmov	6*16(sp), %xmm2
	xmov	7*16(sp), %xmm3
	xmov	8*16(sp), %xmm4
	xmov	9*16(sp), %xmm5
	xmov	10*16(sp), %xmm6
	xmov	11*16(sp), %xmm7
#if defined (__x86_64__)
	xmov	12*16(sp), %xmm8
	xmov	13*16(sp), %xmm9
	xmov	14*16(sp), %xmm10
#endif
#endif

	add		$stack_size, sp		// deallocate stack memory

	// restore callee-save registers
#if defined (__x86_64__)
	pop		%rbp
	pop		%rbx
#else
    pop     %edi
    pop     %esi
    pop     %ebp
    pop     %ebx
#endif

	ret							// return

	// this is equivalent to the above function _SHA1Transform, but it does not use ssse3 instructions

	.globl _SHA1Transform_nossse3
	.private_extern	_SHA1Transform_nossse3
_SHA1Transform_nossse3:

	// push callee-save registers
#if defined (__x86_64__)
	push	%rbx
	push	%rbp
#else
    push    %ebx
    push    %ebp
    push    %esi
    push    %edi
#endif

	sub		$stack_size, sp			// allocate stack memory for local use

	// save used xmm registers if this is for kernel
#if	KERNEL
	xmov	%xmm0, 4*16(sp)
	xmov	%xmm1, 5*16(sp)
	xmov	%xmm2, 6*16(sp)
	xmov	%xmm3, 7*16(sp)
	xmov	%xmm4, 8*16(sp)
	xmov	%xmm5, 9*16(sp)
	xmov	%xmm6, 10*16(sp)
	xmov	%xmm7, 11*16(sp)
#if defined (__x86_64__)
	xmov	%xmm8, 12*16(sp)
	xmov	%xmm9, 13*16(sp)
#endif
#endif

#if defined (__x86_64__)

	// set up registers to free %edx/%edi/%esi for other use (ABCDE)
	mov		ctx, HASH_PTR
	mov		buf, BUFFER_PTR
#if Multiple_Blocks
	mov		%rdx, cnt
	#endif
	lea		K_XMM_AR(%rip), K_BASE

#else	// __i386__

#if	KERNEL
    lea     K_XMM_AR, %eax
#else
	// Get address of 0 in R.
           call    0f          // Push program counter onto stack.
        0: pop     %eax      // Get program counter.
		lea	K_XMM_AR-0b(%eax), %eax
#endif
    mov     %eax, K_BASE

#endif

	SHA1_PIPELINED_MAIN_BODY_nossse3

	// restore used xmm registers if this is for kernel
#if	KERNEL
	xmov	4*16(sp), %xmm0
	xmov	5*16(sp), %xmm1
	xmov	6*16(sp), %xmm2
	xmov	7*16(sp), %xmm3
	xmov	8*16(sp), %xmm4
	xmov	9*16(sp), %xmm5
	xmov	10*16(sp), %xmm6
	xmov	11*16(sp), %xmm7
#if defined (__x86_64__)
	xmov	12*16(sp), %xmm8
	xmov	13*16(sp), %xmm9
	#endif
#endif

	add		$stack_size, sp		// deallocate stack memory

	// restore callee-save registers
#if defined (__x86_64__)
	pop		%rbp
	pop		%rbx
#else
    pop     %edi
    pop     %esi
    pop     %ebp
    pop     %ebx
#endif

	ret							// return

	.const
	.align	4, 0x90	

#define K1 0x5a827999
#define K2 0x6ed9eba1
#define K3 0x8f1bbcdc
#define K4 0xca62c1d6

K_XMM_AR:
    .long	K1
	.long	K1
	.long	K1
	.long	K1
    .long	K2
	.long	K2
	.long	K2
	.long	K2
    .long	K3
	.long	K3
	.long	K3
	.long	K3
    .long	K4
	.long	K4
	.long	K4
	.long	K4
// bswap_shufb_ctl: accessed thru 0x40(K_XMM_AR)
    .long	0x00010203
    .long	0x04050607
    .long	0x08090a0b
    .long	0x0c0d0e0f



#endif	// architecture x86_64 or i386
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/Digest/sha2.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
/* 
 * Copyright (c) 2004 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 ---------------------------------------------------------------------------
 Copyright (c) 2002, Dr Brian Gladman, Worcester, UK.   All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue Date: 26/08/2003

 This is a byte oriented version of SHA2 that operates on arrays of bytes
 stored in memory. This code implements sha256, sha384 and sha512 but the
 latter two functions rely on efficient 64-bit integer operations that
 may not be very efficient on 32-bit machines

 The sha256 functions use a type 'sha256_ctx' to hold details of the
 current hash state and uses the following three calls:

       void sha256_begin(sha256_ctx ctx[1])
       void sha256_hash(const unsigned char data[],
                            unsigned long len, sha256_ctx ctx[1])
       void sha_end1(unsigned char hval[], sha256_ctx ctx[1])

 The first subroutine initialises a hash computation by setting up the
 context in the sha256_ctx context. The second subroutine hashes 8-bit
 bytes from array data[] into the hash state withinh sha256_ctx context,
 the number of bytes to be hashed being given by the the unsigned long
 integer len.  The third subroutine completes the hash calculation and
 places the resulting digest value in the array of 8-bit bytes hval[].

 The sha384 and sha512 functions are similar and use the interfaces:

       void sha384_begin(sha384_ctx ctx[1]);
       void sha384_hash(const unsigned char data[],
                            unsigned long len, sha384_ctx ctx[1]);
       void sha384_end(unsigned char hval[], sha384_ctx ctx[1]);

       void sha512_begin(sha512_ctx ctx[1]);
       void sha512_hash(const unsigned char data[],
                            unsigned long len, sha512_ctx ctx[1]);
       void sha512_end(unsigned char hval[], sha512_ctx ctx[1]);

 In addition there is a function sha2 that can be used to call all these
 functions using a call with a hash length parameter as follows:

       int sha2_begin(unsigned long len, sha2_ctx ctx[1]);
       void sha2_hash(const unsigned char data[],
                            unsigned long len, sha2_ctx ctx[1]);
       void sha2_end(unsigned char hval[], sha2_ctx ctx[1]);

 My thanks to Erik Andersen <andersen@codepoet.org> for testing this code
 on big-endian systems and for his assistance with corrections
*/

/*
 * Apple: Measurements indicate that we get both smaller code size and faster
 * performance when compiling this file with -O1 than with either -O3 or -Os.
 *
 * -O1
 * sha2.o 18652 bytes of text
 * 7.509 seconds to digest 100000000 bytes with SHA512
 *
 * -Os
 * sha2.o 19552 bytes of text
 * 8.693 seconds to process 100000000 bytes
 * 
 * -O3
 * sha2.o 20452 bytes of text
 * 8.535 seconds to process 100000000 bytes
 *
 * #defining UNROOL_SHA2 leads to no noticable improvement. 
 */
#include "sha2Priv.h"   /* Apple Common Digest version */

/* define the hash functions that you need          */

#ifndef _APPLE_COMMON_CRYPTO_
#define SHA_2           /* for dynamic hash length  */
#endif  /* _APPLE_COMMON_CRYPTO_ */
#define SHA_224
#define SHA_256
#define SHA_384
#define SHA_512

#if 0
#define UNROLL_SHA2     /* for SHA2 loop unroll     */
#endif

#include <string.h>     /* for memcpy() etc.        */
#include <stdlib.h>     /* for _lrotr with VC++     */

/* #include "sha2.h" */

#if defined(__cplusplus)
extern "C"
{
#endif

/*  PLATFORM SPECIFIC INCLUDES AND BYTE ORDER IN 32-BIT WORDS

    To obtain the highest speed on processors with 32-bit words, this code
    needs to determine the byte order of the target machine. The following
    block of code is an attempt to capture the most obvious ways in which
    various environemnts define byte order. It may well fail, in which case
    the definitions will need to be set by editing at the points marked
    **** EDIT HERE IF NECESSARY **** below.  My thanks go to Peter Gutmann
    for his assistance with this endian detection nightmare.
*/

#define BRG_LITTLE_ENDIAN   1234 /* byte 0 is least significant (i386) */
#define BRG_BIG_ENDIAN      4321 /* byte 0 is most significant (mc68k) */

#if defined(__GNUC__) || defined(__GNU_LIBRARY__)
#  if defined(__FreeBSD__) || defined(__OpenBSD__)
#    include <sys/endian.h>
#  elif defined( BSD ) && ( BSD >= 199103 )
#      include <machine/endian.h>
#  elif defined(__APPLE__)
#    if defined(__BIG_ENDIAN__) && !defined( BIG_ENDIAN )
#      define BIG_ENDIAN
#    elif defined(__LITTLE_ENDIAN__) && !defined( LITTLE_ENDIAN )
#      define LITTLE_ENDIAN
#    endif
#  else
#    include <endian.h>
#    if !defined(__BEOS__)
#      include <byteswap.h>
#    endif
#  endif
#endif

#if !defined(PLATFORM_BYTE_ORDER)
#  if defined(LITTLE_ENDIAN) || defined(BIG_ENDIAN)
#    if    defined(LITTLE_ENDIAN) && !defined(BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif !defined(LITTLE_ENDIAN) &&  defined(BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#    elif defined(BYTE_ORDER) && (BYTE_ORDER == LITTLE_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif defined(BYTE_ORDER) && (BYTE_ORDER == BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#    endif
#  elif defined(_LITTLE_ENDIAN) || defined(_BIG_ENDIAN)
#    if    defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif !defined(_LITTLE_ENDIAN) &&  defined(_BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#    elif defined(_BYTE_ORDER) && (_BYTE_ORDER == _LITTLE_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif defined(_BYTE_ORDER) && (_BYTE_ORDER == _BIG_ENDIAN)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#   endif
#  elif defined(__LITTLE_ENDIAN__) || defined(__BIG_ENDIAN__)
#    if    defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif !defined(__LITTLE_ENDIAN__) &&  defined(__BIG_ENDIAN__)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#    elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __LITTLE_ENDIAN__)
#      define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#    elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __BIG_ENDIAN__)
#      define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#    endif
#  endif
#endif

/*  if the platform is still unknown, try to find its byte order    */
/*  from commonly used machine defines                              */

#if !defined(PLATFORM_BYTE_ORDER)

#if   defined( __alpha__ ) || defined( __alpha ) || defined( i386 )       || \
      defined( __i386__ )  || defined( _M_I86 )  || defined( _M_IX86 )    || \
      defined( __OS2__ )   || defined( sun386 )  || defined( __TURBOC__ ) || \
      defined( vax )       || defined( vms )     || defined( VMS )        || \
      defined( __VMS )     || defined(__x86_64__)
#  define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN

#elif defined( AMIGA )    || defined( applec )  || defined( __AS400__ )  || \
      defined( _CRAY )    || defined( __hppa )  || defined( __hp9000 )   || \
      defined( ibm370 )   || defined( mc68000 ) || defined( m68k )       || \
      defined( __MRC__ )  || defined( __MVS__ ) || defined( __MWERKS__ ) || \
      defined( sparc )    || defined( __sparc)  || defined( SYMANTEC_C ) || \
      defined( __TANDEM ) || defined( THINK_C ) || defined( __VMCMS__ )
#  define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN

#elif 0     /* **** EDIT HERE IF NECESSARY **** */
#  define PLATFORM_BYTE_ORDER BRG_LITTLE_ENDIAN
#elif 0     /* **** EDIT HERE IF NECESSARY **** */
#  define PLATFORM_BYTE_ORDER BRG_BIG_ENDIAN
#else
#  error Please edit sha2.c (line 184 or 186) to set the platform byte order
#endif

#endif

#ifdef _MSC_VER
#pragma intrinsic(memcpy)
#endif

#if 0 && defined(_MSC_VER)
#define rotl32 _lrotl
#define rotr32 _lrotr
#else
#define rotl32(x,n)   (((x) << n) | ((x) >> (32 - n)))
#define rotr32(x,n)   (((x) >> n) | ((x) << (32 - n)))
#endif

#if !defined(bswap_32)
#define bswap_32(x) ((rotr32((x), 24) & 0x00ff00ff) | (rotr32((x), 8) & 0xff00ff00))
#endif

#if (PLATFORM_BYTE_ORDER == BRG_LITTLE_ENDIAN)
#define SWAP_BYTES
#else
#undef  SWAP_BYTES
#endif

#if 0

#define ch(x,y,z)       (((x) & (y)) ^ (~(x) & (z)))
#define maj(x,y,z)      (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

#else   /* Thanks to Rich Schroeppel and Colin Plumb for the following      */

#define ch(x,y,z)       ((z) ^ ((x) & ((y) ^ (z))))
#define maj(x,y,z)      (((x) & (y)) | ((z) & ((x) ^ (y))))

#endif

/* round transforms for SHA256 and SHA512 compression functions */

#define vf(n,i) v[(n - i) & 7]

#define hf(i) (p[i & 15] += \
    g_1(p[(i + 14) & 15]) + p[(i + 9) & 15] + g_0(p[(i + 1) & 15]))

#define v_cycle(i,j)                                \
    vf(7,i) += (j ? hf(i) : p[i]) + k_0[i+j]        \
    + s_1(vf(4,i)) + ch(vf(4,i),vf(5,i),vf(6,i));   \
    vf(3,i) += vf(7,i);                             \
    vf(7,i) += s_0(vf(0,i))+ maj(vf(0,i),vf(1,i),vf(2,i))

#if defined(SHA_224) || defined(SHA_256)

#define SHA256_MASK (SHA256_BLOCK_SIZE - 1)

#if defined(SWAP_BYTES)
#define bsw_32(p,n) \
    { int _i = (n); while(_i--) ((sha2_32t*)p)[_i] = bswap_32(((sha2_32t*)p)[_i]); }
#else
#define bsw_32(p,n)
#endif

#define s_0(x)  (rotr32((x),  2) ^ rotr32((x), 13) ^ rotr32((x), 22))
#define s_1(x)  (rotr32((x),  6) ^ rotr32((x), 11) ^ rotr32((x), 25))
#define g_0(x)  (rotr32((x),  7) ^ rotr32((x), 18) ^ ((x) >>  3))
#define g_1(x)  (rotr32((x), 17) ^ rotr32((x), 19) ^ ((x) >> 10))
#define k_0     k256

/* rotated SHA256 round definition. Rather than swapping variables as in    */
/* FIPS-180, different variables are 'rotated' on each round, returning     */
/* to their starting positions every eight rounds                           */

#define q(n)  v##n

#define one_cycle(a,b,c,d,e,f,g,h,k,w)  \
    q(h) += s_1(q(e)) + ch(q(e), q(f), q(g)) + k + w; \
    q(d) += q(h); q(h) += s_0(q(a)) + maj(q(a), q(b), q(c))

/* SHA256 mixing data   */
#if defined (SHA256_USE_ASSEMBLY) && (defined(__x86_64__) || defined(__i386__))
	const sha2_32t K256[64] =
#else
static const sha2_32t k256[64] =
#endif
{   0x428a2f98ul, 0x71374491ul, 0xb5c0fbcful, 0xe9b5dba5ul,
    0x3956c25bul, 0x59f111f1ul, 0x923f82a4ul, 0xab1c5ed5ul,
    0xd807aa98ul, 0x12835b01ul, 0x243185beul, 0x550c7dc3ul,
    0x72be5d74ul, 0x80deb1feul, 0x9bdc06a7ul, 0xc19bf174ul,
    0xe49b69c1ul, 0xefbe4786ul, 0x0fc19dc6ul, 0x240ca1ccul,
    0x2de92c6ful, 0x4a7484aaul, 0x5cb0a9dcul, 0x76f988daul,
    0x983e5152ul, 0xa831c66dul, 0xb00327c8ul, 0xbf597fc7ul,
    0xc6e00bf3ul, 0xd5a79147ul, 0x06ca6351ul, 0x14292967ul,
    0x27b70a85ul, 0x2e1b2138ul, 0x4d2c6dfcul, 0x53380d13ul,
    0x650a7354ul, 0x766a0abbul, 0x81c2c92eul, 0x92722c85ul,
    0xa2bfe8a1ul, 0xa81a664bul, 0xc24b8b70ul, 0xc76c51a3ul,
    0xd192e819ul, 0xd6990624ul, 0xf40e3585ul, 0x106aa070ul,
    0x19a4c116ul, 0x1e376c08ul, 0x2748774cul, 0x34b0bcb5ul,
    0x391c0cb3ul, 0x4ed8aa4aul, 0x5b9cca4ful, 0x682e6ff3ul,
    0x748f82eeul, 0x78a5636ful, 0x84c87814ul, 0x8cc70208ul,
    0x90befffaul, 0xa4506cebul, 0xbef9a3f7ul, 0xc67178f2ul,
};

/* Compile 64 bytes of hash data into SHA256 digest value   */
/* NOTE: this routine assumes that the byte order in the    */
/* ctx->wbuf[] at this point is such that low address bytes */
/* in the ORIGINAL byte stream will go into the high end of */
/* words on BOTH big and little endian systems              */

#if defined (SHA256_USE_ASSEMBLY) && (defined(__x86_64__) || defined(__i386__))
extern	sha2_void sha256_compile(sha256_ctx ctx[1]);
#else
static sha2_void sha256_compile(sha256_ctx ctx[1])
{
#if !defined(UNROLL_SHA2)

    sha2_32t j, *p = ctx->wbuf, v[8];

    memcpy(v, ctx->hash, 8 * sizeof(sha2_32t));

    for(j = 0; j < 64; j += 16)
    {
        v_cycle( 0, j); v_cycle( 1, j);
        v_cycle( 2, j); v_cycle( 3, j);
        v_cycle( 4, j); v_cycle( 5, j);
        v_cycle( 6, j); v_cycle( 7, j);
        v_cycle( 8, j); v_cycle( 9, j);
        v_cycle(10, j); v_cycle(11, j);
        v_cycle(12, j); v_cycle(13, j);
        v_cycle(14, j); v_cycle(15, j);
    }

    ctx->hash[0] += v[0]; ctx->hash[1] += v[1];
    ctx->hash[2] += v[2]; ctx->hash[3] += v[3];
    ctx->hash[4] += v[4]; ctx->hash[5] += v[5];
    ctx->hash[6] += v[6]; ctx->hash[7] += v[7];

#else

    sha2_32t *p = ctx->wbuf,v0,v1,v2,v3,v4,v5,v6,v7;

    v0 = ctx->hash[0]; v1 = ctx->hash[1];
    v2 = ctx->hash[2]; v3 = ctx->hash[3];
    v4 = ctx->hash[4]; v5 = ctx->hash[5];
    v6 = ctx->hash[6]; v7 = ctx->hash[7];

    one_cycle(0,1,2,3,4,5,6,7,k256[ 0],p[ 0]);
    one_cycle(7,0,1,2,3,4,5,6,k256[ 1],p[ 1]);
    one_cycle(6,7,0,1,2,3,4,5,k256[ 2],p[ 2]);
    one_cycle(5,6,7,0,1,2,3,4,k256[ 3],p[ 3]);
    one_cycle(4,5,6,7,0,1,2,3,k256[ 4],p[ 4]);
    one_cycle(3,4,5,6,7,0,1,2,k256[ 5],p[ 5]);
    one_cycle(2,3,4,5,6,7,0,1,k256[ 6],p[ 6]);
    one_cycle(1,2,3,4,5,6,7,0,k256[ 7],p[ 7]);
    one_cycle(0,1,2,3,4,5,6,7,k256[ 8],p[ 8]);
    one_cycle(7,0,1,2,3,4,5,6,k256[ 9],p[ 9]);
    one_cycle(6,7,0,1,2,3,4,5,k256[10],p[10]);
    one_cycle(5,6,7,0,1,2,3,4,k256[11],p[11]);
    one_cycle(4,5,6,7,0,1,2,3,k256[12],p[12]);
    one_cycle(3,4,5,6,7,0,1,2,k256[13],p[13]);
    one_cycle(2,3,4,5,6,7,0,1,k256[14],p[14]);
    one_cycle(1,2,3,4,5,6,7,0,k256[15],p[15]);

    one_cycle(0,1,2,3,4,5,6,7,k256[16],hf( 0));
    one_cycle(7,0,1,2,3,4,5,6,k256[17],hf( 1));
    one_cycle(6,7,0,1,2,3,4,5,k256[18],hf( 2));
    one_cycle(5,6,7,0,1,2,3,4,k256[19],hf( 3));
    one_cycle(4,5,6,7,0,1,2,3,k256[20],hf( 4));
    one_cycle(3,4,5,6,7,0,1,2,k256[21],hf( 5));
    one_cycle(2,3,4,5,6,7,0,1,k256[22],hf( 6));
    one_cycle(1,2,3,4,5,6,7,0,k256[23],hf( 7));
    one_cycle(0,1,2,3,4,5,6,7,k256[24],hf( 8));
    one_cycle(7,0,1,2,3,4,5,6,k256[25],hf( 9));
    one_cycle(6,7,0,1,2,3,4,5,k256[26],hf(10));
    one_cycle(5,6,7,0,1,2,3,4,k256[27],hf(11));
    one_cycle(4,5,6,7,0,1,2,3,k256[28],hf(12));
    one_cycle(3,4,5,6,7,0,1,2,k256[29],hf(13));
    one_cycle(2,3,4,5,6,7,0,1,k256[30],hf(14));
    one_cycle(1,2,3,4,5,6,7,0,k256[31],hf(15));

    one_cycle(0,1,2,3,4,5,6,7,k256[32],hf( 0));
    one_cycle(7,0,1,2,3,4,5,6,k256[33],hf( 1));
    one_cycle(6,7,0,1,2,3,4,5,k256[34],hf( 2));
    one_cycle(5,6,7,0,1,2,3,4,k256[35],hf( 3));
    one_cycle(4,5,6,7,0,1,2,3,k256[36],hf( 4));
    one_cycle(3,4,5,6,7,0,1,2,k256[37],hf( 5));
    one_cycle(2,3,4,5,6,7,0,1,k256[38],hf( 6));
    one_cycle(1,2,3,4,5,6,7,0,k256[39],hf( 7));
    one_cycle(0,1,2,3,4,5,6,7,k256[40],hf( 8));
    one_cycle(7,0,1,2,3,4,5,6,k256[41],hf( 9));
    one_cycle(6,7,0,1,2,3,4,5,k256[42],hf(10));
    one_cycle(5,6,7,0,1,2,3,4,k256[43],hf(11));
    one_cycle(4,5,6,7,0,1,2,3,k256[44],hf(12));
    one_cycle(3,4,5,6,7,0,1,2,k256[45],hf(13));
    one_cycle(2,3,4,5,6,7,0,1,k256[46],hf(14));
    one_cycle(1,2,3,4,5,6,7,0,k256[47],hf(15));

    one_cycle(0,1,2,3,4,5,6,7,k256[48],hf( 0));
    one_cycle(7,0,1,2,3,4,5,6,k256[49],hf( 1));
    one_cycle(6,7,0,1,2,3,4,5,k256[50],hf( 2));
    one_cycle(5,6,7,0,1,2,3,4,k256[51],hf( 3));
    one_cycle(4,5,6,7,0,1,2,3,k256[52],hf( 4));
    one_cycle(3,4,5,6,7,0,1,2,k256[53],hf( 5));
    one_cycle(2,3,4,5,6,7,0,1,k256[54],hf( 6));
    one_cycle(1,2,3,4,5,6,7,0,k256[55],hf( 7));
    one_cycle(0,1,2,3,4,5,6,7,k256[56],hf( 8));
    one_cycle(7,0,1,2,3,4,5,6,k256[57],hf( 9));
    one_cycle(6,7,0,1,2,3,4,5,k256[58],hf(10));
    one_cycle(5,6,7,0,1,2,3,4,k256[59],hf(11));
    one_cycle(4,5,6,7,0,1,2,3,k256[60],hf(12));
    one_cycle(3,4,5,6,7,0,1,2,k256[61],hf(13));
    one_cycle(2,3,4,5,6,7,0,1,k256[62],hf(14));
    one_cycle(1,2,3,4,5,6,7,0,k256[63],hf(15));

    ctx->hash[0] += v0; ctx->hash[1] += v1;
    ctx->hash[2] += v2; ctx->hash[3] += v3;
    ctx->hash[4] += v4; ctx->hash[5] += v5;
    ctx->hash[6] += v6; ctx->hash[7] += v7;
#endif
}
#endif	//	SHA256_USE_ASSEMBLY 

/* SHA256 hash data in an array of bytes into hash buffer   */
/* and call the hash_compile function as required.          */
#ifdef		_APPLE_COMMON_CRYPTO_
int CC_SHA256_Update(CC_SHA256_CTX *ctx, const void *data, CC_LONG len)
#else
sha2_void sha256_hash(const unsigned char data[], unsigned long len, sha256_ctx ctx[1])
#endif  /* _APPLE_COMMON_CRYPTO_ */
{   sha2_32t pos = (sha2_32t)(ctx->count[0] & SHA256_MASK),
             space = SHA256_BLOCK_SIZE - pos;
    const unsigned char *sp = data;

    if((ctx->count[0] += len) < len)
        ++(ctx->count[1]);

    while(len >= space)     /* tranfer whole blocks while possible  */
    {
        memcpy(((unsigned char*)ctx->wbuf) + pos, sp, space);
        sp += space; len -= space; space = SHA256_BLOCK_SIZE; pos = 0;
        bsw_32(ctx->wbuf, SHA256_BLOCK_SIZE >> 2)
        sha256_compile(ctx);
    }

    memcpy(((unsigned char*)ctx->wbuf) + pos, sp, len);
	return 1;
}

/* SHA256 Final padding and digest calculation  */

static sha2_void sha_end1(unsigned char hval[], sha256_ctx ctx[1], const unsigned int hlen)
{   sha2_32t    i = (sha2_32t)(ctx->count[0] & SHA256_MASK);

    /* put bytes in the buffer in an order in which references to   */
    /* 32-bit words will put bytes with lower addresses into the    */
    /* top of 32 bit words on BOTH big and little endian machines   */
    bsw_32(ctx->wbuf, (i + 3) >> 2)

    /* we now need to mask valid bytes and add the padding which is */
    /* a single 1 bit and as many zero bits as necessary. Note that */
    /* we can always add the first padding byte here because the    */
    /* buffer always has at least one empty slot                    */
    ctx->wbuf[i >> 2] &= 0xffffff80 << 8 * (~i & 3);
    ctx->wbuf[i >> 2] |= 0x00000080 << 8 * (~i & 3);

    /* we need 9 or more empty positions, one for the padding byte  */
    /* (above) and eight for the length count.  If there is not     */
    /* enough space pad and empty the buffer                        */
    if(i > SHA256_BLOCK_SIZE - 9)
    {
        if(i < 60) ctx->wbuf[15] = 0;
        sha256_compile(ctx);
        i = 0;
    }
    else    /* compute a word index for the empty buffer positions  */
        i = (i >> 2) + 1;

    while(i < 14) /* and zero pad all but last two positions        */
        ctx->wbuf[i++] = 0;

    /* the following 32-bit length fields are assembled in the      */
    /* wrong byte order on little endian machines but this is       */
    /* corrected later since they are only ever used as 32-bit      */
    /* word values.                                                 */
    ctx->wbuf[14] = (ctx->count[1] << 3) | (ctx->count[0] >> 29);
    ctx->wbuf[15] = ctx->count[0] << 3;
    sha256_compile(ctx);

    /* extract the hash value as bytes in case the hash buffer is   */
    /* mislaigned for 32-bit words                                  */
    for(i = 0; i < hlen; ++i)
        hval[i] = (unsigned char)(ctx->hash[i >> 2] >> (8 * (~i & 3)));
}

#endif

#if defined(SHA_224)

const sha2_32t i224[8] =
{
    0xc1059ed8ul, 0x367cd507ul, 0x3070dd17ul, 0xf70e5939ul,
    0xffc00b31ul, 0x68581511ul, 0x64f98fa7ul, 0xbefa4fa4ul
};

#ifdef _APPLE_COMMON_CRYPTO_
int sha224_begin(sha256_ctx ctx[1])
#else
sha2_void sha224_begin(sha256_ctx ctx[1])
#endif
{
    ctx->count[0] = ctx->count[1] = 0;
    memcpy(ctx->hash, i224, 8 * sizeof(sha2_32t));
	return 1;
}

#ifdef _APPLE_COMMON_CRYPTO_
int sha224_end(unsigned char hval[], sha256_ctx ctx[1])
#else
sha2_void sha224_end(unsigned char hval[], sha256_ctx ctx[1])
#endif
{
    sha_end1(hval, ctx, SHA224_DIGEST_SIZE);
	return 1;
}

#ifndef _APPLE_COMMON_CRYPTO_
sha2_void sha224(unsigned char hval[], const unsigned char data[], unsigned long len)
{   sha224_ctx  cx[1];

    sha224_begin(cx);
    sha224_hash(data, len, cx);
    sha_end1(hval, cx, SHA224_DIGEST_SIZE);
}
#endif	/* _APPLE_COMMON_CRYPTO_ */

/* provide an actual entry for this instead of #defining it */
extern int CC_SHA224_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len)
{
	return CC_SHA256_Update(c, data, len);
}

#endif	/* SHA_224 */

#if defined(SHA_256)

static const sha2_32t i256[8] =
{
    0x6a09e667ul, 0xbb67ae85ul, 0x3c6ef372ul, 0xa54ff53aul,
    0x510e527ful, 0x9b05688cul, 0x1f83d9abul, 0x5be0cd19ul
};

int sha256_begin(sha256_ctx ctx[1])
{
    ctx->count[0] = ctx->count[1] = 0;
    memcpy(ctx->hash, i256, 8 * sizeof(sha2_32t));
	return 1;
}

int sha256_end(unsigned char hval[], sha256_ctx ctx[1])
{
    sha_end1(hval, ctx, SHA256_DIGEST_SIZE);
	return 1;
}

#ifndef _APPLE_COMMON_CRYPTO_
sha2_void sha256(unsigned char hval[], const unsigned char data[], unsigned long len)
{   sha256_ctx  cx[1];

    sha256_begin(cx);
    sha256_hash(data, len, cx);
    sha_end1(hval, cx, SHA256_DIGEST_SIZE);
}
#endif  /* _APPLE_COMMON_CRYPTO_ */

#endif

#if defined(SHA_384) || defined(SHA_512)

#define SHA512_MASK (SHA512_BLOCK_SIZE - 1)

#define rotr64(x,n)   (((x) >> n) | ((x) << (64 - n)))

#if !defined(bswap_64)
#define bswap_64(x) (((sha2_64t)(bswap_32((sha2_32t)(x)))) << 32 | bswap_32((sha2_32t)((x) >> 32)))
#endif

#if defined(SWAP_BYTES)
#define bsw_64(p,n) \
    { int _i = (n); while(_i--) ((sha2_64t*)p)[_i] = bswap_64(((sha2_64t*)p)[_i]); }
#else
#define bsw_64(p,n)
#endif

/* SHA512 mixing function definitions   */

#ifdef   s_0
# undef  s_0
# undef  s_1
# undef  g_0
# undef  g_1
# undef  k_0
#endif

#define s_0(x)  (rotr64((x), 28) ^ rotr64((x), 34) ^ rotr64((x), 39))
#define s_1(x)  (rotr64((x), 14) ^ rotr64((x), 18) ^ rotr64((x), 41))
#define g_0(x)  (rotr64((x),  1) ^ rotr64((x),  8) ^ ((x) >>  7))
#define g_1(x)  (rotr64((x), 19) ^ rotr64((x), 61) ^ ((x) >>  6))
#define k_0     k512

/* SHA384/SHA512 mixing data    */

static const sha2_64t  k512[80] =
{
    0x428a2f98d728ae22ull, 0x7137449123ef65cdull,
    0xb5c0fbcfec4d3b2full, 0xe9b5dba58189dbbcull,
    0x3956c25bf348b538ull, 0x59f111f1b605d019ull,
    0x923f82a4af194f9bull, 0xab1c5ed5da6d8118ull,
    0xd807aa98a3030242ull, 0x12835b0145706fbeull,
    0x243185be4ee4b28cull, 0x550c7dc3d5ffb4e2ull,
    0x72be5d74f27b896full, 0x80deb1fe3b1696b1ull,
    0x9bdc06a725c71235ull, 0xc19bf174cf692694ull,
    0xe49b69c19ef14ad2ull, 0xefbe4786384f25e3ull,
    0x0fc19dc68b8cd5b5ull, 0x240ca1cc77ac9c65ull,
    0x2de92c6f592b0275ull, 0x4a7484aa6ea6e483ull,
    0x5cb0a9dcbd41fbd4ull, 0x76f988da831153b5ull,
    0x983e5152ee66dfabull, 0xa831c66d2db43210ull,
    0xb00327c898fb213full, 0xbf597fc7beef0ee4ull,
    0xc6e00bf33da88fc2ull, 0xd5a79147930aa725ull,
    0x06ca6351e003826full, 0x142929670a0e6e70ull,
    0x27b70a8546d22ffcull, 0x2e1b21385c26c926ull,
    0x4d2c6dfc5ac42aedull, 0x53380d139d95b3dfull,
    0x650a73548baf63deull, 0x766a0abb3c77b2a8ull,
    0x81c2c92e47edaee6ull, 0x92722c851482353bull,
    0xa2bfe8a14cf10364ull, 0xa81a664bbc423001ull,
    0xc24b8b70d0f89791ull, 0xc76c51a30654be30ull,
    0xd192e819d6ef5218ull, 0xd69906245565a910ull,
    0xf40e35855771202aull, 0x106aa07032bbd1b8ull,
    0x19a4c116b8d2d0c8ull, 0x1e376c085141ab53ull,
    0x2748774cdf8eeb99ull, 0x34b0bcb5e19b48a8ull,
    0x391c0cb3c5c95a63ull, 0x4ed8aa4ae3418acbull,
    0x5b9cca4f7763e373ull, 0x682e6ff3d6b2b8a3ull,
    0x748f82ee5defb2fcull, 0x78a5636f43172f60ull,
    0x84c87814a1f0ab72ull, 0x8cc702081a6439ecull,
    0x90befffa23631e28ull, 0xa4506cebde82bde9ull,
    0xbef9a3f7b2c67915ull, 0xc67178f2e372532bull,
    0xca273eceea26619cull, 0xd186b8c721c0c207ull,
    0xeada7dd6cde0eb1eull, 0xf57d4f7fee6ed178ull,
    0x06f067aa72176fbaull, 0x0a637dc5a2c898a6ull,
    0x113f9804bef90daeull, 0x1b710b35131c471bull,
    0x28db77f523047d84ull, 0x32caab7b40c72493ull,
    0x3c9ebe0a15c9bebcull, 0x431d67c49c100d4cull,
    0x4cc5d4becb3e42b6ull, 0x597f299cfc657e2aull,
    0x5fcb6fab3ad6faecull, 0x6c44198c4a475817ull
};

/* Compile 128 bytes of hash data into SHA384/512 digest    */
/* NOTE: this routine assumes that the byte order in the    */
/* ctx->wbuf[] at this point is such that low address bytes */
/* in the ORIGINAL byte stream will go into the high end of */
/* words on BOTH big and little endian systems              */

static sha2_void sha512_compile(sha512_ctx ctx[1])
{   sha2_64t    v[8], *p = ctx->wbuf;
    sha2_32t    j;

    memcpy(v, ctx->hash, 8 * sizeof(sha2_64t));

    for(j = 0; j < 80; j += 16)
    {
        v_cycle( 0, j); v_cycle( 1, j);
        v_cycle( 2, j); v_cycle( 3, j);
        v_cycle( 4, j); v_cycle( 5, j);
        v_cycle( 6, j); v_cycle( 7, j);
        v_cycle( 8, j); v_cycle( 9, j);
        v_cycle(10, j); v_cycle(11, j);
        v_cycle(12, j); v_cycle(13, j);
        v_cycle(14, j); v_cycle(15, j);
    }

    ctx->hash[0] += v[0]; ctx->hash[1] += v[1];
    ctx->hash[2] += v[2]; ctx->hash[3] += v[3];
    ctx->hash[4] += v[4]; ctx->hash[5] += v[5];
    ctx->hash[6] += v[6]; ctx->hash[7] += v[7];
}

/* Compile 128 bytes of hash data into SHA256 digest value  */
/* NOTE: this routine assumes that the byte order in the    */
/* ctx->wbuf[] at this point is in such an order that low   */
/* address bytes in the ORIGINAL byte stream placed in this */
/* buffer will now go to the high end of words on BOTH big  */
/* and little endian systems                                */

#ifdef  _APPLE_COMMON_CRYPTO_
int CC_SHA512_Update(CC_SHA512_CTX *ctx, const void *data, CC_LONG len)
#else
sha2_void sha512_hash(const unsigned char data[], unsigned long len, sha512_ctx ctx[1])
#endif
{   sha2_32t pos = (sha2_32t)(ctx->count[0] & SHA512_MASK),
             space = SHA512_BLOCK_SIZE - pos;
    const unsigned char *sp = data;

    if((ctx->count[0] += len) < len)
        ++(ctx->count[1]);

    while(len >= space)     /* tranfer whole blocks while possible  */
    {
        memcpy(((unsigned char*)ctx->wbuf) + pos, sp, space);
        sp += space; len -= space; space = SHA512_BLOCK_SIZE; pos = 0;
        bsw_64(ctx->wbuf, SHA512_BLOCK_SIZE >> 3);
        sha512_compile(ctx);
    }

    memcpy(((unsigned char*)ctx->wbuf) + pos, sp, len);
	return 1;
}

/* SHA384/512 Final padding and digest calculation  */

static void sha_end2(unsigned char hval[], sha512_ctx ctx[1], const unsigned int hlen)
{   sha2_32t    i = (sha2_32t)(ctx->count[0] & SHA512_MASK);

    /* put bytes in the buffer in an order in which references to   */
    /* 32-bit words will put bytes with lower addresses into the    */
    /* top of 32 bit words on BOTH big and little endian machines   */
    bsw_64(ctx->wbuf, (i + 7) >> 3);

    /* we now need to mask valid bytes and add the padding which is */
    /* a single 1 bit and as many zero bits as necessary. Note that */
    /* we can always add the first padding byte here because the    */
    /* buffer always has at least one empty slot                    */
    ctx->wbuf[i >> 3] &= 0xffffffffffffff00ull << 8 * (~i & 7);
    ctx->wbuf[i >> 3] |= 0x0000000000000080ull << 8 * (~i & 7);

    /* we need 17 or more empty byte positions, one for the padding */
    /* byte (above) and sixteen for the length count.  If there is  */
    /* not enough space pad and empty the buffer                    */
    if(i > SHA512_BLOCK_SIZE - 17)
    {
        if(i < 120) ctx->wbuf[15] = 0;
        sha512_compile(ctx);
        i = 0;
    }
    else
        i = (i >> 3) + 1;

    while(i < 14)
        ctx->wbuf[i++] = 0;

    /* the following 64-bit length fields are assembled in the      */
    /* wrong byte order on little endian machines but this is       */
    /* corrected later since they are only ever used as 64-bit      */
    /* word values.                                                 */
    ctx->wbuf[14] = (ctx->count[1] << 3) | (ctx->count[0] >> 61);
    ctx->wbuf[15] = ctx->count[0] << 3;
    sha512_compile(ctx);

    /* extract the hash value as bytes in case the hash buffer is   */
    /* misaligned for 32-bit words                                  */
    for(i = 0; i < hlen; ++i)
        hval[i] = (unsigned char)(ctx->hash[i >> 3] >> (8 * (~i & 7)));
}

#endif

#if defined(SHA_384)

/* SHA384 initialisation data   */

static const sha2_64t  i384[80] =
{
    0xcbbb9d5dc1059ed8ull, 0x629a292a367cd507ull,
    0x9159015a3070dd17ull, 0x152fecd8f70e5939ull,
    0x67332667ffc00b31ull, 0x8eb44a8768581511ull,
    0xdb0c2e0d64f98fa7ull, 0x47b5481dbefa4fa4ull
};

#ifdef _APPLE_COMMON_CRYPTO_
int sha384_begin(sha384_ctx *ctx)
#else
sha2_void sha384_begin(sha384_ctx ctx[1])
#endif
{
    ctx->count[0] = ctx->count[1] = 0;
    memcpy(ctx->hash, i384, 8 * sizeof(sha2_64t));
	return 1;
}

#ifdef _APPLE_COMMON_CRYPTO_
int sha384_end(unsigned char *hval, sha384_ctx *ctx)
#else
sha2_void sha384_end(unsigned char hval[], sha384_ctx ctx[1])
#endif
{
    sha_end2(hval, ctx, SHA384_DIGEST_SIZE);
	return 1;
}

/* provide an actual entry for this instead of #defining it */
extern int CC_SHA384_Update(CC_SHA512_CTX *c, const void *data, CC_LONG len)
{
	return CC_SHA512_Update(c, data, len);
}


#ifndef _APPLE_COMMON_CRYPTO_
sha2_void sha384(unsigned char hval[], const unsigned char data[], unsigned long len)
{   sha384_ctx  cx[1];

    sha384_begin(cx);
    sha384_hash(data, len, cx);
    sha_end2(hval, cx, SHA384_DIGEST_SIZE);
}
#endif  /* _APPLE_COMMON_CRYPTO_ */
#endif

#if defined(SHA_512)

/* SHA512 initialisation data   */

static const sha2_64t  i512[80] =
{
    0x6a09e667f3bcc908ull, 0xbb67ae8584caa73bull,
    0x3c6ef372fe94f82bull, 0xa54ff53a5f1d36f1ull,
    0x510e527fade682d1ull, 0x9b05688c2b3e6c1full,
    0x1f83d9abfb41bd6bull, 0x5be0cd19137e2179ull
};

#ifdef _APPLE_COMMON_CRYPTO_
int sha512_begin(sha512_ctx *ctx)
#else
sha2_void sha512_begin(sha512_ctx ctx[1])
#endif
{
    ctx->count[0] = ctx->count[1] = 0;
    memcpy(ctx->hash, i512, 8 * sizeof(sha2_64t));
	return 1;
}

#ifdef _APPLE_COMMON_CRYPTO_
int sha512_end(unsigned char *hval, sha512_ctx *ctx)
#else
sha2_void sha512_end(unsigned char hval[], sha512_ctx ctx[1])
#endif
{
    sha_end2(hval, ctx, SHA512_DIGEST_SIZE);
	return 1;
}

#ifndef _APPLE_COMMON_CRYPTO_
sha2_void sha512(unsigned char hval[], const unsigned char data[], unsigned long len)
{   sha512_ctx  cx[1];

    sha512_begin(cx);
    sha512_hash(data, len, cx);
    sha_end2(hval, cx, SHA512_DIGEST_SIZE);
}
#endif  /* _APPLE_COMMON_CRYPTO_ */

#endif

#if defined(SHA_2)

#define CTX_224(x)  ((x)->uu->ctx256)
#define CTX_256(x)  ((x)->uu->ctx256)
#define CTX_384(x)  ((x)->uu->ctx512)
#define CTX_512(x)  ((x)->uu->ctx512)

/* SHA2 initialisation */

sha2_int sha2_begin(unsigned long len, sha2_ctx ctx[1])
{   unsigned long   l = len;
    switch(len)
    {
#if defined(SHA224)
        case 224:
        case  28:   CTX_256(ctx)->count[0] = CTX_256(ctx)->count[1] = 0;
                    memcpy(CTX_256(ctx)->hash, i224, 32);
                    ctx->sha2_len = 28; return SHA2_GOOD;
#endif
#if defined(SHA256)
        case 256:
        case  32:   CTX_256(ctx)->count[0] = CTX_256(ctx)->count[1] = 0;
                    memcpy(CTX_256(ctx)->hash, i256, 32);
                    ctx->sha2_len = 32; return SHA2_GOOD;
#endif
#if defined(SHA384)
        case 384:
        case  48:   CTX_384(ctx)->count[0] = CTX_384(ctx)->count[1] = 0;
                    memcpy(CTX_384(ctx)->hash, i384, 64);
                    ctx->sha2_len = 48; return SHA2_GOOD;
#endif
#if defined(SHA512)
        case 512:
        case  64:   CTX_512(ctx)->count[0] = CTX_512(ctx)->count[1] = 0;
                    memcpy(CTX_512(ctx)->hash, i512, 64);
                    ctx->sha2_len = 64; return SHA2_GOOD;
#endif
        default:    return SHA2_BAD;
    }
}

sha2_void sha2_hash(const unsigned char data[], unsigned long len, sha2_ctx ctx[1])
{
    switch(ctx->sha2_len)
    {
#if defined(SHA224)
        case 28: sha224_hash(data, len, CTX_224(ctx)); return;
#endif
#if defined(SHA256)
        case 32: sha256_hash(data, len, CTX_256(ctx)); return;
#endif
#if defined(SHA384)
        case 48: sha384_hash(data, len, CTX_384(ctx)); return;
#endif
#if defined(SHA512)
        case 64: sha512_hash(data, len, CTX_512(ctx)); return;
#endif
    }
}

sha2_void sha2_end(unsigned char hval[], sha2_ctx ctx[1])
{
    switch(ctx->sha2_len)
    {
#if defined(SHA224)
        case 28: sha_end1(hval, CTX_224(ctx), SHA224_DIGEST_SIZE); return;
#endif
#if defined(SHA256)
        case 32: sha_end1(hval, CTX_256(ctx), SHA256_DIGEST_SIZE); return;
#endif
#if defined(SHA384)
        case 48: sha_end2(hval, CTX_384(ctx), SHA384_DIGEST_SIZE); return;
#endif
#if defined(SHA512)
        case 64: sha_end2(hval, CTX_512(ctx), SHA512_DIGEST_SIZE); return;
#endif
    }
}

sha2_int sha2(unsigned char hval[], unsigned long size,
                                const unsigned char data[], unsigned long len)
{   sha2_ctx    cx[1];

    if(sha2_begin(size, cx) == SHA2_GOOD)
    {
        sha2_hash(data, len, cx); sha2_end(hval, cx); return SHA2_GOOD;
    }
    else
        return SHA2_BAD;
}

#endif  /* SHA2 */

#if defined(__cplusplus)
}
#endif

CC_DIGEST_ONE_SHOT(CC_SHA224, CC_SHA256_CTX, CC_SHA224_Init, 
	CC_SHA224_Update, CC_SHA224_Final)

CC_DIGEST_ONE_SHOT(CC_SHA256, CC_SHA256_CTX, CC_SHA256_Init, 
	CC_SHA256_Update, CC_SHA256_Final)

CC_DIGEST_ONE_SHOT(CC_SHA384, CC_SHA512_CTX, CC_SHA384_Init, 
	CC_SHA384_Update, CC_SHA384_Final)

CC_DIGEST_ONE_SHOT(CC_SHA512, CC_SHA512_CTX, CC_SHA512_Init, 
	CC_SHA512_Update, CC_SHA512_Final)
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/Digest/sha256.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/*
	This file provides x86_64/i386 hand implementation of the following function

	sha2_void sha256_compile(sha256_ctx ctx[1]);

	which is a C function in CommonCrypto Source/Digest/sha2.c

	The implementation here is modified from another sha256 x86_64/i386 implementation for sha256 in the xnu.
	To modify to fit the new API, 
		the old ctx (points to ctx->hashes) shoule be changed to ctx->hashes, 8(ctx).
		the old data (points to ctx->wbuf), should be changed to ctx->wbuf, 40(ctx).

	sha256_compile handles 1 input block (64 bytes) per call. 

	cclee 8-10-10

	The following is comments for the initial xnu-sha256.s.

	void SHA256_Transform(SHA256_ctx *ctx, char *data, unsigned int num_blocks);

	which is a C function in sha2.c (from xnu).

	The code 1st probes cpu_capabilities to detect whether ssse3 is supported. If not, it branches to
	SHA256_Transform_nossse3 (in a separate source file sha256nossse3.s) that was cloned from this file
	with all ssse3 instructions replaced with sse3 or below instructions.

	sha256 algorithm per block description:

		1. W(0:15) = big-endian (per 4 bytes) loading of input data (64 byte) 
		2. load 8 digests a-h from ctx->state
		3. for r = 0:15
				T1 = h + Sigma1(e) + Ch(e,f,g) + K[r] + W[r];
				d += T1;
				h = T1 + Sigma0(a) + Maj(a,b,c)
				permute a,b,c,d,e,f,g,h into h,a,b,c,d,e,f,g
		4. for r = 16:63
				W[r] = W[r-16] + sigma1(W[r-2]) + W[r-7] + sigma0(W[r-15]);
				T1 = h + Sigma1(e) + Ch(e,f,g) + K[r] + W[r];
				d += T1;
				h = T1 + Sigma0(a) + Maj(a,b,c)
				permute a,b,c,d,e,f,g,h into h,a,b,c,d,e,f,g
				
	In the assembly implementation:	
		- a circular window of message schedule W(r:r+15) is updated and stored in xmm0-xmm3
		- its corresponding W+K(r:r+15) is updated and stored in a stack space circular buffer
		- the 8 digests (a-h) will be stored in GPR or m32 (all in GPR for x86_64, and some in m32 for i386)

	the implementation per block looks like

	----------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into xmm0:xmm3 
	pre_calculate and store W+K(0:15) in stack

	load digests a-h from ctx->state;

	for (r=0;r<48;r+=4) {
		digests a-h update and permute round r:r+3
		update W([r:r+3]%16) and WK([r:r+3]%16) for the next 4th iteration 
	}

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
	}

	ctx->states += digests a-h;

	----------------------------------------------------------------------------

	our implementation (allows multiple blocks per call) pipelines the loading of W/WK of a future block 
	into the last 16 rounds of its previous block:

	----------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into xmm0:xmm3 
	pre_calculate and store W+K(0:15) in stack

L_loop:

	load digests a-h from ctx->state;

	for (r=0;r<48;r+=4) {
		digests a-h update and permute round r:r+3
		update W([r:r+3]%16) and WK([r:r+3]%16) for the next 4th iteration 
	}

	num_block--;
	if (num_block==0)	jmp L_last_block;

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
		load W([r:r+3]%16) (big-endian per 4 bytes) into xmm0:xmm3 
		pre_calculate and store W+K([r:r+3]%16) in stack
	}

	ctx->states += digests a-h;

	jmp	L_loop;

L_last_block:

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
	}

	ctx->states += digests a-h;

	------------------------------------------------------------------------

	Apple CoreOS vector & numerics
	cclee 8-3-10
*/
#if defined __i386__ || defined __x86_64__
#if defined	KERNEL
#include <i386/cpu_capabilities.h>
#else
#include <System/i386/cpu_capabilities.h>
#endif

	// associate variables with registers or memory

#if defined	(__x86_64__)
	#define	sp			%rsp
	#define	ctx			%rdi
	#define data		%rsi
	#define	num_blocks	%rdx

	#define	a			%r8d
	#define	b			%r9d
	#define	c			%r10d
	#define	d			%r11d
	#define	e			%r12d
	#define	f			%r13d
	#define	g			%r14d
	#define	h			%r15d

	#define	K			%rbx
	#define stack_size	(8+16*8+16+64)	// 8 (align) + xmm0:xmm7 + L_aligned_bswap + WK(0:15)

	#define	L_aligned_bswap	64(sp)		// bswap : big-endian loading of 4-byte words
	#define	xmm_save	80(sp)			// starting address for xmm save/restore
#else
	#define	sp 	%esp
	#define stack_size	(12+16*8+16+16+64)	// 12 (align) + xmm0:xmm7 + 16 (c,f,h,K) + L_aligned_bswap + WK(0:15)
	#define	ctx_addr	20+stack_size(sp)	// ret_addr + 4 registers = 20, 1st caller argument
	#define	data_addr	24+stack_size(sp)	// 2nd caller argument
	#define	num_blocks	28+stack_size(sp)	// 3rd caller argument

	#define	a	%ebx
	#define	b	%edx
	#define	c	64(sp)
	#define	d	%ebp
	#define	e	%esi
	#define	f	68(sp)
	#define	g	%edi
	#define	h	72(sp)

	#define	K	76(sp)					// pointer to K256[] table
	#define	L_aligned_bswap	80(sp)		// bswap : big-endian loading of 4-byte words
	#define	xmm_save	96(sp)			// starting address for xmm save/restore
#endif

	// 2 local variables
	#define	t	%eax
	#define	s	%ecx

	// a window (16 words) of message scheule
	#define	W0	%xmm0
	#define	W1	%xmm1
	#define	W2	%xmm2
	#define	W3	%xmm3

	// circular buffer for WK[(r:r+15)%16]
	#define WK(x)   (x&15)*4(sp)

// #define Ch(x,y,z)   (((x) & (y)) ^ ((~(x)) & (z)))

	.macro Ch
	mov		$0, t		// x
	mov		$0, s		// x
	not		t			// ~x
	and		$1, s		// x & y
	and		$2, t		// ~x & z
	xor		s, t		// t = ((x) & (y)) ^ ((~(x)) & (z));
	.endm

// #define Maj(x,y,z)  (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

	.macro	Maj
#if 1		// steve's suggestion
	mov	 	$1,	t // y
	mov		$2,	s // z
	xor		$2,	t // y^z
	and		$1,	s // y&z
	and		$0, 	t // x&(y^z)
	xor		s,	t // Maj(x,y,z)
#else	
	mov		$0, t		// x
	mov		$1, s		// y
	and		s, t		// x&y
	and		$2, s		// y&z
	xor		s, t		// (x&y) ^ (y&z)
	mov		$2, s		// z
	and		$0, s		// (x&z)
	xor		s, t		// t = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) 
#endif
	.endm

// #define sigma0_256(x)   (S32(7,  (x)) ^ S32(18, (x)) ^ R(3 ,   (x)))

	// performs sigma0_256 on 4 words on an xmm registers
	// use xmm6/xmm7 as intermediate registers
	.macro	sigma0
	movdqa	$0, %xmm6
	movdqa	$0, %xmm7
	psrld	$$3, $0			// SHR3(x)
	psrld	$$7, %xmm6		// part of ROTR7
	pslld	$$14, %xmm7		// part of ROTR18
	pxor	%xmm6, $0
	pxor	%xmm7, $0
	psrld	$$11, %xmm6		// part of ROTR18
	pslld	$$11, %xmm7		// part of ROTR7
	pxor	%xmm6, $0
	pxor	%xmm7, $0
	.endm

// #define sigma1_256(x)   (S32(17, (x)) ^ S32(19, (x)) ^ R(10,   (x)))

	// performs sigma1_256 on 4 words on an xmm registers
	// use xmm6/xmm7 as intermediate registers
	.macro	sigma1
	movdqa	$0, %xmm6
	movdqa	$0, %xmm7
	psrld	$$10, $0		// SHR10(x)
	psrld	$$17, %xmm6		// part of ROTR17
	pxor	%xmm6, $0
	pslld	$$13, %xmm7		// part of ROTR19
	pxor	%xmm7, $0
	psrld	$$2, %xmm6		// part of ROTR19
	pxor	%xmm6, $0
	pslld	$$2, %xmm7		// part of ROTR17
	pxor	%xmm7, $0
	.endm

// #define Sigma0_256(x)   (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))

	.macro	Sigma0
	mov		$0, t			// x
	mov		$0, s			// x
	ror		$$2, t			// S32(2,  (x))
	ror		$$13, s			// S32(13,  (x))
	xor		s, t			// S32(2,  (x)) ^ S32(13, (x))
	ror		$$9, s			// S32(22,  (x))
	xor		s, t			// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))
	.endm

// #define Sigma1_256(x)   (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))

	.macro	Sigma1
	mov		$0, s			// x
	ror		$$6, s			// S32(6,  (x))
	mov		s, t			// S32(6,  (x))
	ror		$$5, s			// S32(11, (x))
	xor		s, t			// S32(6,  (x)) ^ S32(11, (x))
	ror		$$14, s			// S32(25, (x))
	xor		s, t			// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	.endm

	// per round digests update
	.macro	round
	Sigma1	$4				// t = T1
	add		t, $7			// use h to store h+Sigma1(e)
	Ch		$4, $5, $6		// t = Ch (e, f, g);
	add		$7, t			// t = h+Sigma1(e)+Ch(e,f,g);
	add		WK($8), t		// h = T1
	add		t, $3			// d += T1;
	mov		t, $7			// h = T1
	Sigma0	$0				// t = Sigma0(a);
	add		t, $7			// h = T1 + Sigma0(a);
	Maj		$0, $1, $2		// t = Maj(a,b,c)
	add		t, $7			// h = T1 + Sigma0(a) + Maj(a,b,c);			
	.endm

	// per 4 rounds digests update and permutation
	// permutation is absorbed by rotating the roles of digests a-h
	.macro	rounds
	round	$0, $1, $2, $3, $4, $5, $6, $7, 0+$8
	round	$7, $0, $1, $2, $3, $4, $5, $6, 1+$8
	round	$6, $7, $0, $1, $2, $3, $4, $5, 2+$8
	round	$5, $6, $7, $0, $1, $2, $3, $4, 3+$8
	.endm

	// update the message schedule W and W+K (4 rounds) 16 rounds ahead in the future 
	.macro	message_schedule

	// 4 32-bit K256 words in xmm5
#if defined	(__x86_64__)
	movdqu	(K), %xmm5
#else
	mov		K, t
	movdqu	(t), %xmm5 
#endif	
	add		$$16, K				// K points to next K256 word for next iteration
	movdqa	$1, %xmm4 			// W7:W4
	palignr	$$4, $0, %xmm4		// W4:W1
	sigma0	%xmm4				// sigma0(W4:W1)
	movdqa	$3, %xmm6 			// W15:W12
	paddd	%xmm4, $0			// $0 = W3:W0 + sigma0(W4:W1) 
	palignr	$$4, $2, %xmm6		// W12:W9
	paddd	%xmm6, $0			// $0 = W12:W9 + sigma0(W4:W1) + W3:W0	
	movdqa	$3, %xmm4			// W15:W12
	psrldq	$$8, %xmm4			// 0,0,W15,W14	
	sigma1	%xmm4				// sigma1(0,0,W15,W14)
	paddd	%xmm4, $0			// sigma1(0,0,W15,W14) + W12:W9 + sigma0(W4:W1) + W3:W0
	movdqa	$0, %xmm4			// W19-sigma1(W17), W18-sigma1(W16), W17, W16
	pslldq	$$8, %xmm4			// W17, W16, 0, 0
	sigma1	%xmm4				// sigma1(W17,W16,0,0)
	paddd	%xmm4, $0			// W19:W16
	paddd	$0, %xmm5			// WK
	movdqa	%xmm5, WK($4)
	.endm

	// this macro is used in the last 16 rounds of a current block
	// it reads the next message (16 4-byte words), load it into 4 words W[r:r+3], computes WK[r:r+3]
	// and save into stack to prepare for next block

	.macro	update_W_WK
#if defined (__x86_64__)
	movdqu	$0*16(data), $1		// read 4 4-byte words
	pshufb	L_aligned_bswap, $1	// big-endian of each 4-byte word, W[r:r+3]
	movdqu	$0*16(K), %xmm4		// K[r:r+3]
#else
	mov		data_addr, t
	movdqu	$0*16(t), $1		// read 4 4-byte words
	pshufb	L_aligned_bswap, $1	// big-endian of each 4-byte word, W[r:r+3]
	mov		K, t
	movdqu	$0*16(t), %xmm4		// K[r:r+3]
#endif
	paddd	$1, %xmm4			// WK[r:r+3]
	movdqa	%xmm4, WK($0*4)		// save WK[r:r+3] into stack circular buffer
	.endm

#if defined(__i386__)
    .section    __IMPORT,__pointers,non_lazy_symbol_pointers
L_K256$non_lazy_ptr:
.indirect_symbol _K256
    .long   0
#endif

	.text

#if defined (SHA256_USE_ASSEMBLY)
	.globl	_sha256_compile

_sha256_compile:

#if 1
	// detect SSSE3 and dispatch appropriate code branch
	#if defined __x86_64__
        movq    __cpu_capabilities@GOTPCREL(%rip), %rax         // %rax -> __cpu_capabilities
        mov     (%rax), %eax                                    // %eax = __cpu_capabilities
    #else       // i386
        #if defined KERNEL
            leal    __cpu_capabilities, %eax                    // %eax -> __cpu_capabilities
            mov     (%eax), %eax                                // %eax = __cpu_capabilities
        #else
            mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
        #endif
    #endif
    test    $(kHasSupplementalSSE3), %eax
    je      _sha256_compile_nossse3                              // branch to no-ssse3 code
#endif

	// push callee-saved registers
#if defined	(__x86_64__)
	push	%rbp
	push	%rbx
	push	%r12
	push	%r13
	push	%r14
	push	%r15
#else
    push    %ebp
	push    %ebx
    push    %esi
    push    %edi
#endif

	// allocate stack space
	sub		$stack_size, sp

	// set up ctx and data

#if defined (__x86_64__)
	add		$8, ctx				// now ctx = %rdi
	lea		32(ctx), data		// data points to ctx->wbuf
#else
	add		$8, ctx_addr		// now ctx points to ctx->hashes
	mov		ctx_addr, t
	add		$32, t
	mov		t, data_addr		// data points to ctx->wbuf
#endif

	// if kernel code, save used xmm registers
#if	KERNEL
	movdqa	%xmm0, 0*16+xmm_save
	movdqa	%xmm1, 1*16+xmm_save
	movdqa	%xmm2, 2*16+xmm_save
	movdqa	%xmm3, 3*16+xmm_save
	movdqa	%xmm4, 4*16+xmm_save
	movdqa	%xmm5, 5*16+xmm_save
	movdqa	%xmm6, 6*16+xmm_save
	movdqa	%xmm7, 7*16+xmm_save
#endif

	// set up bswap parameters in the aligned stack space and pointer to table K256[]
#if defined (__x86_64__)
	lea		_K256(%rip), K
#else
	call    0f          // Push program counter onto stack.
0:	pop     t      // Get program counter.
	mov L_K256$non_lazy_ptr-0b(t), t
	mov		t, K
#endif

	// load W[0:15] into xmm0-xmm3
#if defined (__x86_64__)
	movdqu	0*16(data), W0
	movdqu	1*16(data), W1
	movdqu	2*16(data), W2
	movdqu	3*16(data), W3
	add		$64, data
#else
	mov		data_addr, t
	movdqu	0*16(t), W0
	movdqu	1*16(t), W1
	movdqu	2*16(t), W2
	movdqu	3*16(t), W3
	add		$64, data_addr
#endif

	// compute WK[0:15] and save in stack
#if defined (__x86_64__)
	movdqu	0*16(K), %xmm4	
	movdqu	1*16(K), %xmm5
	movdqu	2*16(K), %xmm6	
	movdqu	3*16(K), %xmm7
#else
	mov		K, t
	movdqu	0*16(t), %xmm4	
	movdqu	1*16(t), %xmm5
	movdqu	2*16(t), %xmm6	
	movdqu	3*16(t), %xmm7
#endif
	add		$64, K
	paddd	%xmm0, %xmm4
	paddd	%xmm1, %xmm5
	paddd	%xmm2, %xmm6
	paddd	%xmm3, %xmm7
	movdqa	%xmm4, WK(0)
	movdqa	%xmm5, WK(4)
	movdqa	%xmm6, WK(8)
	movdqa	%xmm7, WK(12)

	// digests a-h = ctx->states;
#if defined (__x86_64__)
	mov		0*4(ctx), a
	mov		1*4(ctx), b
	mov		2*4(ctx), c
	mov		3*4(ctx), d
	mov		4*4(ctx), e
	mov		5*4(ctx), f
	mov		6*4(ctx), g
	mov		7*4(ctx), h
#else
	mov		ctx_addr, t
	mov 	0*4(t), a
	mov 	1*4(t), b
	mov 	2*4(t), s
	mov		s, c
	mov 	3*4(t), d
	mov 	4*4(t), e
	mov 	5*4(t), s
	mov		s, f
	mov 	6*4(t), g
	mov 	7*4(t), s
	mov		s, h
#endif

	// rounds 0:47 interleaved with W/WK update for rounds 16:63
	rounds	a, b, c, d, e, f, g, h, 0
	message_schedule W0,W1,W2,W3,16
	rounds	e, f, g, h, a, b, c, d, 4 
	message_schedule W1,W2,W3,W0,20
	rounds	a, b, c, d, e, f, g, h, 8
	message_schedule W2,W3,W0,W1,24
	rounds	e, f, g, h, a, b, c, d, 12 
	message_schedule W3,W0,W1,W2,28
	rounds	a, b, c, d, e, f, g, h, 16
	message_schedule W0,W1,W2,W3,32
	rounds	e, f, g, h, a, b, c, d, 20 
	message_schedule W1,W2,W3,W0,36
	rounds	a, b, c, d, e, f, g, h, 24
	message_schedule W2,W3,W0,W1,40
	rounds	e, f, g, h, a, b, c, d, 28 
	message_schedule W3,W0,W1,W2,44
	rounds	a, b, c, d, e, f, g, h, 32
	message_schedule W0,W1,W2,W3,48
	rounds	e, f, g, h, a, b, c, d, 36 
	message_schedule W1,W2,W3,W0,52
	rounds	a, b, c, d, e, f, g, h, 40
	message_schedule W2,W3,W0,W1,56
	rounds	e, f, g, h, a, b, c, d, 44 
	message_schedule W3,W0,W1,W2,60

	// wrap up digest update round 48:63 for final block
	rounds	a, b, c, d, e, f, g, h, 48
	rounds	e, f, g, h, a, b, c, d, 52 
	rounds	a, b, c, d, e, f, g, h, 56
	rounds	e, f, g, h, a, b, c, d, 60 

	// ctx->states += digests a-h
#if	defined (__x86_64__)
	add		a, 0*4(ctx)
	add		b, 1*4(ctx)
	add		c, 2*4(ctx)
	add		d, 3*4(ctx)
	add		e, 4*4(ctx)
	add		f, 5*4(ctx)
	add		g, 6*4(ctx)
	add		h, 7*4(ctx)
#else
	mov		ctx_addr, t
	add		a, 0*4(t)
	add		b, 1*4(t)
	mov		c, s
	add		s, 2*4(t)
	add		d, 3*4(t)
	add		e, 4*4(t)
	mov		f, s
	add		s, 5*4(t)
	add		g, 6*4(t)
	mov		h, s
	add		s, 7*4(t)
#endif

	// if kernel, restore xmm0-xmm7
#if	KERNEL
	movdqa	0*16+xmm_save, %xmm0
	movdqa	1*16+xmm_save, %xmm1
	movdqa	2*16+xmm_save, %xmm2
	movdqa	3*16+xmm_save, %xmm3
	movdqa	4*16+xmm_save, %xmm4
	movdqa	5*16+xmm_save, %xmm5
	movdqa	6*16+xmm_save, %xmm6
	movdqa	7*16+xmm_save, %xmm7
#endif

	// free allocated stack memory
	add		$stack_size, sp

	// restore callee-saved registers
#if defined (__x86_64__)
	pop		%r15
	pop		%r14
	pop		%r13
	pop		%r12
	pop		%rbx
	pop		%rbp
#else
    pop		%edi
    pop		%esi
	pop		%ebx
    pop		%ebp
#endif

	// return
	ret


#endif		// SHA256_USE_ASSEMBLY
#endif      // i386 || x86_64
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/Digest/sha256_nossse3.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/*
	This file provides x86_64/i386 hand implementation of the following function

	sha2_void sha256_compile(sha256_ctx ctx[1]);

	which is a C function in CommonCrypto Source/Digest/sha2.c

	The implementation here is modified from another sha256 x86_64/i386 implementation for sha256 in the xnu.
	To modify to fit the new API, 
		the old ctx (points to ctx->hashes) shoule be changed to ctx->hashes, 8(ctx).
		the old data (points to ctx->wbuf), should be changed to ctx->wbuf, 40(ctx).

	sha256_compile handles 1 input block (64 bytes) per call. 

	cclee 8-10-10

	The following is comments for the initial xnu-sha256.s.

	void SHA256_Transform(SHA256_ctx *ctx, char *data, unsigned int num_blocks);

	which is a C function in sha2.c (from xnu).

	The code 1st probes cpu_capabilities to detect whether ssse3 is supported. If not, it branches to
	SHA256_Transform_nossse3 (in a separate source file sha256nossse3.s) that was cloned from this file
	with all ssse3 instructions replaced with sse3 or below instructions.

	sha256 algorithm per block description:

		1. W(0:15) = big-endian (per 4 bytes) loading of input data (64 byte) 
		2. load 8 digests a-h from ctx->state
		3. for r = 0:15
				T1 = h + Sigma1(e) + Ch(e,f,g) + K[r] + W[r];
				d += T1;
				h = T1 + Sigma0(a) + Maj(a,b,c)
				permute a,b,c,d,e,f,g,h into h,a,b,c,d,e,f,g
		4. for r = 16:63
				W[r] = W[r-16] + sigma1(W[r-2]) + W[r-7] + sigma0(W[r-15]);
				T1 = h + Sigma1(e) + Ch(e,f,g) + K[r] + W[r];
				d += T1;
				h = T1 + Sigma0(a) + Maj(a,b,c)
				permute a,b,c,d,e,f,g,h into h,a,b,c,d,e,f,g
				
	In the assembly implementation:	
		- a circular window of message schedule W(r:r+15) is updated and stored in xmm0-xmm3
		- its corresponding W+K(r:r+15) is updated and stored in a stack space circular buffer
		- the 8 digests (a-h) will be stored in GPR or m32 (all in GPR for x86_64, and some in m32 for i386)

	the implementation per block looks like

	----------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into xmm0:xmm3 
	pre_calculate and store W+K(0:15) in stack

	load digests a-h from ctx->state;

	for (r=0;r<48;r+=4) {
		digests a-h update and permute round r:r+3
		update W([r:r+3]%16) and WK([r:r+3]%16) for the next 4th iteration 
	}

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
	}

	ctx->states += digests a-h;

	----------------------------------------------------------------------------

	our implementation (allows multiple blocks per call) pipelines the loading of W/WK of a future block 
	into the last 16 rounds of its previous block:

	----------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into xmm0:xmm3 
	pre_calculate and store W+K(0:15) in stack

L_loop:

	load digests a-h from ctx->state;

	for (r=0;r<48;r+=4) {
		digests a-h update and permute round r:r+3
		update W([r:r+3]%16) and WK([r:r+3]%16) for the next 4th iteration 
	}

	num_block--;
	if (num_block==0)	jmp L_last_block;

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
		load W([r:r+3]%16) (big-endian per 4 bytes) into xmm0:xmm3 
		pre_calculate and store W+K([r:r+3]%16) in stack
	}

	ctx->states += digests a-h;

	jmp	L_loop;

L_last_block:

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
	}

	ctx->states += digests a-h;

	------------------------------------------------------------------------

	Apple CoreOS vector & numerics
	cclee 8-3-10
*/

#if defined (__x86_64__) || defined (__i386__)

#if defined	KERNEL
#include <i386/cpu_capabilities.h>
#else
#include <System/i386/cpu_capabilities.h>
#endif

	// associate variables with registers or memory

#if defined	(__x86_64__)
	#define	sp			%rsp
	#define	ctx			%rdi
	#define data		%rsi
	#define	num_blocks	%rdx

	#define	a			%r8d
	#define	b			%r9d
	#define	c			%r10d
	#define	d			%r11d
	#define	e			%r12d
	#define	f			%r13d
	#define	g			%r14d
	#define	h			%r15d

	#define	K			%rbx
	#define stack_size	(8+16*8+16+64)	// 8 (align) + xmm0:xmm7 + L_aligned_bswap + WK(0:15)

	#define	L_aligned_bswap	64(sp)		// bswap : big-endian loading of 4-byte words
	#define	xmm_save	80(sp)			// starting address for xmm save/restore
#else
	#define	sp 	%esp
	#define stack_size	(12+16*8+16+16+64)	// 12 (align) + xmm0:xmm7 + 16 (c,f,h,K) + L_aligned_bswap + WK(0:15)
	#define	ctx_addr	20+stack_size(sp)	// ret_addr + 4 registers = 20, 1st caller argument
	#define	data_addr	24+stack_size(sp)	// 2nd caller argument
	#define	num_blocks	28+stack_size(sp)	// 3rd caller argument

	#define	a	%ebx
	#define	b	%edx
	#define	c	64(sp)
	#define	d	%ebp
	#define	e	%esi
	#define	f	68(sp)
	#define	g	%edi
	#define	h	72(sp)

	#define	K	76(sp)					// pointer to K256[] table
	#define	L_aligned_bswap	80(sp)		// bswap : big-endian loading of 4-byte words
	#define	xmm_save	96(sp)			// starting address for xmm save/restore
#endif

	// 2 local variables
	#define	t	%eax
	#define	s	%ecx

	// a window (16 words) of message scheule
	#define	W0	%xmm0
	#define	W1	%xmm1
	#define	W2	%xmm2
	#define	W3	%xmm3

	// circular buffer for WK[(r:r+15)%16]
	#define WK(x)   (x&15)*4(sp)

// #define Ch(x,y,z)   (((x) & (y)) ^ ((~(x)) & (z)))

	.macro Ch
	mov		$0, t		// x
	mov		$0, s		// x
	not		t			// ~x
	and		$1, s		// x & y
	and		$2, t		// ~x & z
	xor		s, t		// t = ((x) & (y)) ^ ((~(x)) & (z));
	.endm

// #define Maj(x,y,z)  (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

	.macro	Maj
#if 1		// steve's suggestion
	mov	 	$1,	t // y
	mov		$2,	s // z
	xor		$2,	t // y^z
	and		$1,	s // y&z
	and		$0, 	t // x&(y^z)
	xor		s,	t // Maj(x,y,z)
#else	
	mov		$0, t		// x
	mov		$1, s		// y
	and		s, t		// x&y
	and		$2, s		// y&z
	xor		s, t		// (x&y) ^ (y&z)
	mov		$2, s		// z
	and		$0, s		// (x&z)
	xor		s, t		// t = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) 
#endif
	.endm

// #define sigma0_256(x)   (S32(7,  (x)) ^ S32(18, (x)) ^ R(3 ,   (x)))

	// performs sigma0_256 on 4 words on an xmm registers
	// use xmm6/xmm7 as intermediate registers
	.macro	sigma0
	movdqa	$0, %xmm6
	movdqa	$0, %xmm7
	psrld	$$3, $0			// SHR3(x)
	psrld	$$7, %xmm6		// part of ROTR7
	pslld	$$14, %xmm7		// part of ROTR18
	pxor	%xmm6, $0
	pxor	%xmm7, $0
	psrld	$$11, %xmm6		// part of ROTR18
	pslld	$$11, %xmm7		// part of ROTR7
	pxor	%xmm6, $0
	pxor	%xmm7, $0
	.endm

// #define sigma1_256(x)   (S32(17, (x)) ^ S32(19, (x)) ^ R(10,   (x)))

	// performs sigma1_256 on 4 words on an xmm registers
	// use xmm6/xmm7 as intermediate registers
	.macro	sigma1
	movdqa	$0, %xmm6
	movdqa	$0, %xmm7
	psrld	$$10, $0		// SHR10(x)
	psrld	$$17, %xmm6		// part of ROTR17
	pxor	%xmm6, $0
	pslld	$$13, %xmm7		// part of ROTR19
	pxor	%xmm7, $0
	psrld	$$2, %xmm6		// part of ROTR19
	pxor	%xmm6, $0
	pslld	$$2, %xmm7		// part of ROTR17
	pxor	%xmm7, $0
	.endm

// #define Sigma0_256(x)   (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))

	.macro	Sigma0
	mov		$0, t			// x
	mov		$0, s			// x
	ror		$$2, t			// S32(2,  (x))
	ror		$$13, s			// S32(13,  (x))
	xor		s, t			// S32(2,  (x)) ^ S32(13, (x))
	ror		$$9, s			// S32(22,  (x))
	xor		s, t			// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))
	.endm

// #define Sigma1_256(x)   (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))

	.macro	Sigma1
	mov		$0, s			// x
	ror		$$6, s			// S32(6,  (x))
	mov		s, t			// S32(6,  (x))
	ror		$$5, s			// S32(11, (x))
	xor		s, t			// S32(6,  (x)) ^ S32(11, (x))
	ror		$$14, s			// S32(25, (x))
	xor		s, t			// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	.endm

	// per round digests update
	.macro	round
	Sigma1	$4				// t = T1
	add		t, $7			// use h to store h+Sigma1(e)
	Ch		$4, $5, $6		// t = Ch (e, f, g);
	add		$7, t			// t = h+Sigma1(e)+Ch(e,f,g);
	add		WK($8), t		// h = T1
	add		t, $3			// d += T1;
	mov		t, $7			// h = T1
	Sigma0	$0				// t = Sigma0(a);
	add		t, $7			// h = T1 + Sigma0(a);
	Maj		$0, $1, $2		// t = Maj(a,b,c)
	add		t, $7			// h = T1 + Sigma0(a) + Maj(a,b,c);			
	.endm

	// per 4 rounds digests update and permutation
	// permutation is absorbed by rotating the roles of digests a-h
	.macro	rounds
	round	$0, $1, $2, $3, $4, $5, $6, $7, 0+$8
	round	$7, $0, $1, $2, $3, $4, $5, $6, 1+$8
	round	$6, $7, $0, $1, $2, $3, $4, $5, 2+$8
	round	$5, $6, $7, $0, $1, $2, $3, $4, 3+$8
	.endm

	// update the message schedule W and W+K (4 rounds) 16 rounds ahead in the future 
	.macro	message_schedule

	// 4 32-bit K256 words in xmm5
#if defined	(__x86_64__)
	movdqu	(K), %xmm5
#else
	mov		K, t
	movdqu	(t), %xmm5 
#endif	
	add		$$16, K				// K points to next K256 word for next iteration
	movdqa	$1, %xmm4 			// W7:W4
#if 0
	palignr	$$4, $0, %xmm4		// W4:W1
#else
	movdqa  $0, %xmm7
    pslldq  $$12, %xmm4
    psrldq  $$4, %xmm7
    por     %xmm7, %xmm4
#endif
	sigma0	%xmm4				// sigma0(W4:W1)
	movdqa	$3, %xmm6 			// W15:W12
	paddd	%xmm4, $0			// $0 = W3:W0 + sigma0(W4:W1) 
#if 0
	palignr	$$4, $2, %xmm6		// W12:W9
#else
	movdqa  $2, %xmm7
    pslldq  $$12, %xmm6
    psrldq  $$4, %xmm7
    por     %xmm7, %xmm6
#endif
	paddd	%xmm6, $0			// $0 = W12:W9 + sigma0(W4:W1) + W3:W0	
	movdqa	$3, %xmm4			// W15:W12
	psrldq	$$8, %xmm4			// 0,0,W15,W14	
	sigma1	%xmm4				// sigma1(0,0,W15,W14)
	paddd	%xmm4, $0			// sigma1(0,0,W15,W14) + W12:W9 + sigma0(W4:W1) + W3:W0
	movdqa	$0, %xmm4			// W19-sigma1(W17), W18-sigma1(W16), W17, W16
	pslldq	$$8, %xmm4			// W17, W16, 0, 0
	sigma1	%xmm4				// sigma1(W17,W16,0,0)
	paddd	%xmm4, $0			// W19:W16
	paddd	$0, %xmm5			// WK
	movdqa	%xmm5, WK($4)
	.endm

	// this macro is used in the last 16 rounds of a current block
	// it reads the next message (16 4-byte words), load it into 4 words W[r:r+3], computes WK[r:r+3]
	// and save into stack to prepare for next block

	.macro	update_W_WK
#if defined (__x86_64__)
	movdqu	$0*16(data), $1		// read 4 4-byte words
	pshufb	L_aligned_bswap, $1	// big-endian of each 4-byte word, W[r:r+3]
	movdqu	$0*16(K), %xmm4		// K[r:r+3]
#else
	mov		data_addr, t
	movdqu	$0*16(t), $1		// read 4 4-byte words
	pshufb	L_aligned_bswap, $1	// big-endian of each 4-byte word, W[r:r+3]
	mov		K, t
	movdqu	$0*16(t), %xmm4		// K[r:r+3]
#endif
	paddd	$1, %xmm4			// WK[r:r+3]
	movdqa	%xmm4, WK($0*4)		// save WK[r:r+3] into stack circular buffer
	.endm


#if defined (SHA256_USE_ASSEMBLY)

#if defined (__i386__)
    .section    __IMPORT,__pointers,non_lazy_symbol_pointers
L_K256$non_lazy_ptr:
.indirect_symbol _K256
    .long   0
#endif

	.text
	.globl	_sha256_compile_nossse3

_sha256_compile_nossse3:

	// push callee-saved registers
#if defined	(__x86_64__)
	push	%rbp
	push	%rbx
	push	%r12
	push	%r13
	push	%r14
	push	%r15
#else
    push    %ebp
	push    %ebx
    push    %esi
    push    %edi
#endif

	// allocate stack space
	sub		$stack_size, sp

	// set up ctx and data

#if defined (__x86_64__)
	add		$8, ctx				// now ctx = %rdi
	lea		32(ctx), data		// data points to ctx->wbuf
#else
	add		$8, ctx_addr		// now ctx points to ctx->hashes
	mov		ctx_addr, t
	add		$32, t
	mov		t, data_addr		// data points to ctx->wbuf
#endif

	// if kernel code, save used xmm registers
#if	KERNEL
	movdqa	%xmm0, 0*16+xmm_save
	movdqa	%xmm1, 1*16+xmm_save
	movdqa	%xmm2, 2*16+xmm_save
	movdqa	%xmm3, 3*16+xmm_save
	movdqa	%xmm4, 4*16+xmm_save
	movdqa	%xmm5, 5*16+xmm_save
	movdqa	%xmm6, 6*16+xmm_save
	movdqa	%xmm7, 7*16+xmm_save
#endif

	// set up bswap parameters in the aligned stack space and pointer to table K256[]
#if defined (__x86_64__)
	lea		_K256(%rip), K
#else

        call    0f          // Push program counter onto stack.
    0:  pop     t      // Get program counter.
        movl L_K256$non_lazy_ptr-0b(t), t

	mov		t, K
#endif

	// load W[0:15] into xmm0-xmm3
#if defined (__x86_64__)
	movdqu	0*16(data), W0
	movdqu	1*16(data), W1
	movdqu	2*16(data), W2
	movdqu	3*16(data), W3
	add		$64, data
#else
	mov		data_addr, t
	movdqu	0*16(t), W0
	movdqu	1*16(t), W1
	movdqu	2*16(t), W2
	movdqu	3*16(t), W3
	add		$64, data_addr
#endif

	// compute WK[0:15] and save in stack
#if defined (__x86_64__)
	movdqu	0*16(K), %xmm4	
	movdqu	1*16(K), %xmm5
	movdqu	2*16(K), %xmm6	
	movdqu	3*16(K), %xmm7
#else
	mov		K, t
	movdqu	0*16(t), %xmm4	
	movdqu	1*16(t), %xmm5
	movdqu	2*16(t), %xmm6	
	movdqu	3*16(t), %xmm7
#endif
	add		$64, K
	paddd	%xmm0, %xmm4
	paddd	%xmm1, %xmm5
	paddd	%xmm2, %xmm6
	paddd	%xmm3, %xmm7
	movdqa	%xmm4, WK(0)
	movdqa	%xmm5, WK(4)
	movdqa	%xmm6, WK(8)
	movdqa	%xmm7, WK(12)

	// digests a-h = ctx->states;
#if defined (__x86_64__)
	mov		0*4(ctx), a
	mov		1*4(ctx), b
	mov		2*4(ctx), c
	mov		3*4(ctx), d
	mov		4*4(ctx), e
	mov		5*4(ctx), f
	mov		6*4(ctx), g
	mov		7*4(ctx), h
#else
	mov		ctx_addr, t
	mov 	0*4(t), a
	mov 	1*4(t), b
	mov 	2*4(t), s
	mov		s, c
	mov 	3*4(t), d
	mov 	4*4(t), e
	mov 	5*4(t), s
	mov		s, f
	mov 	6*4(t), g
	mov 	7*4(t), s
	mov		s, h
#endif

	// rounds 0:47 interleaved with W/WK update for rounds 16:63
	rounds	a, b, c, d, e, f, g, h, 0
	message_schedule W0,W1,W2,W3,16
	rounds	e, f, g, h, a, b, c, d, 4 
	message_schedule W1,W2,W3,W0,20
	rounds	a, b, c, d, e, f, g, h, 8
	message_schedule W2,W3,W0,W1,24
	rounds	e, f, g, h, a, b, c, d, 12 
	message_schedule W3,W0,W1,W2,28
	rounds	a, b, c, d, e, f, g, h, 16
	message_schedule W0,W1,W2,W3,32
	rounds	e, f, g, h, a, b, c, d, 20 
	message_schedule W1,W2,W3,W0,36
	rounds	a, b, c, d, e, f, g, h, 24
	message_schedule W2,W3,W0,W1,40
	rounds	e, f, g, h, a, b, c, d, 28 
	message_schedule W3,W0,W1,W2,44
	rounds	a, b, c, d, e, f, g, h, 32
	message_schedule W0,W1,W2,W3,48
	rounds	e, f, g, h, a, b, c, d, 36 
	message_schedule W1,W2,W3,W0,52
	rounds	a, b, c, d, e, f, g, h, 40
	message_schedule W2,W3,W0,W1,56
	rounds	e, f, g, h, a, b, c, d, 44 
	message_schedule W3,W0,W1,W2,60

	// wrap up digest update round 48:63 for final block
	rounds	a, b, c, d, e, f, g, h, 48
	rounds	e, f, g, h, a, b, c, d, 52 
	rounds	a, b, c, d, e, f, g, h, 56
	rounds	e, f, g, h, a, b, c, d, 60 

	// ctx->states += digests a-h
#if	defined (__x86_64__)
	add		a, 0*4(ctx)
	add		b, 1*4(ctx)
	add		c, 2*4(ctx)
	add		d, 3*4(ctx)
	add		e, 4*4(ctx)
	add		f, 5*4(ctx)
	add		g, 6*4(ctx)
	add		h, 7*4(ctx)
#else
	mov		ctx_addr, t
	add		a, 0*4(t)
	add		b, 1*4(t)
	mov		c, s
	add		s, 2*4(t)
	add		d, 3*4(t)
	add		e, 4*4(t)
	mov		f, s
	add		s, 5*4(t)
	add		g, 6*4(t)
	mov		h, s
	add		s, 7*4(t)
#endif

	// if kernel, restore xmm0-xmm7
#if	KERNEL
	movdqa	0*16+xmm_save, %xmm0
	movdqa	1*16+xmm_save, %xmm1
	movdqa	2*16+xmm_save, %xmm2
	movdqa	3*16+xmm_save, %xmm3
	movdqa	4*16+xmm_save, %xmm4
	movdqa	5*16+xmm_save, %xmm5
	movdqa	6*16+xmm_save, %xmm6
	movdqa	7*16+xmm_save, %xmm7
#endif

	// free allocated stack memory
	add		$stack_size, sp

	// restore callee-saved registers
#if defined (__x86_64__)
	pop		%r15
	pop		%r14
	pop		%r13
	pop		%r12
	pop		%rbx
	pop		%rbp
#else
    pop		%edi
    pop		%esi
	pop		%ebx
    pop		%ebp
#endif

	// return
	ret



#endif		// SHA256_USE_ASSEMBLY
#endif		// x86_64/i386
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/Digest/sha2Priv.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* 
 * Copyright (c) 2004 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
 
#ifndef _CC_SHA2_PRIV_H_
#define _CC_SHA2_PRIV_H_


/* 
 * This is a replacement for sha2.h; all types, consts, and prototypes are defined
 * in CommonDigest.h. We redefine them here so the original Gladman source is 
 * unmodified except for the include of sha2.h. 
 */
#include "CommonDigestPriv.h"
#include <CommonCrypto/CommonDigest.h>

#define SHA224_DIGEST_SIZE  CC_SHA224_DIGEST_LENGTH
#define SHA256_DIGEST_SIZE  CC_SHA256_DIGEST_LENGTH
#define SHA384_DIGEST_SIZE  CC_SHA384_DIGEST_LENGTH
#define SHA512_DIGEST_SIZE  CC_SHA512_DIGEST_LENGTH

#define SHA224_BLOCK_SIZE   CC_SHA224_BLOCK_BYTES
#define SHA256_BLOCK_SIZE   CC_SHA256_BLOCK_BYTES
#define SHA384_BLOCK_SIZE   CC_SHA384_BLOCK_BYTES
#define SHA512_BLOCK_SIZE   CC_SHA512_BLOCK_BYTES

#define SHA2_GOOD   0
#define SHA2_BAD    1

typedef void sha2_void;

typedef CC_LONG sha2_32t;
typedef CC_LONG64 sha2_64t;

typedef CC_SHA256_CTX sha224_ctx;	
typedef CC_SHA256_CTX sha256_ctx;
typedef CC_SHA512_CTX sha384_ctx;
typedef CC_SHA512_CTX sha512_ctx;

#define sha224_begin(c)			CC_SHA224_Init(c)
#define sha224_end(md, c)		CC_SHA224_Final(md, c)

#define sha256_begin(c)			CC_SHA256_Init(c)
#define sha256_end(md, c)		CC_SHA256_Final(md, c)

#define sha384_begin(c)			CC_SHA384_Init(c)
#define sha384_end(md, c)		CC_SHA384_Final(md, c)

#define sha512_begin(c)			CC_SHA512_Init(c)
#define sha512_end(md, c)		CC_SHA512_Final(md, c)

#endif  /* _CC_SHA2_PRIV_H_ */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































Deleted Source/Digest/sha_locl.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/* crypto/sha/sha_locl.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <stdlib.h>
#include <string.h>

#include "CommonDigestPriv.h"

#ifndef	_APPLE_COMMON_CRYPTO_
#include <openssl/opensslconf.h>
#include <openssl/sha.h>
#endif

#ifndef SHA_LONG_LOG2
#define SHA_LONG_LOG2	2	/* default to 32 bits */
#endif

#define DATA_ORDER_IS_BIG_ENDIAN

#define HASH_LONG               SHA_LONG
#define HASH_LONG_LOG2          SHA_LONG_LOG2
#define HASH_CTX                SHA_CTX
#define HASH_CBLOCK             SHA_CBLOCK
#define HASH_LBLOCK             SHA_LBLOCK
#define HASH_MAKE_STRING(c,s)   do {	\
	unsigned long ll;		\
	ll=(c)->h0; HOST_l2c(ll,(s));	\
	ll=(c)->h1; HOST_l2c(ll,(s));	\
	ll=(c)->h2; HOST_l2c(ll,(s));	\
	ll=(c)->h3; HOST_l2c(ll,(s));	\
	ll=(c)->h4; HOST_l2c(ll,(s));	\
	} while (0)

#if defined(SHA_0)

# define HASH_UPDATE             	SHA_Update
# define HASH_TRANSFORM          	SHA_Transform
# define HASH_FINAL              	SHA_Final
# define HASH_INIT			SHA_Init
# define HASH_BLOCK_HOST_ORDER   	sha_block_host_order
# define HASH_BLOCK_DATA_ORDER   	sha_block_data_order
# define Xupdate(a,ix,ia,ib,ic,id)	(ix=(a)=(ia^ib^ic^id))

  void sha_block_host_order (SHA_CTX *c, const void *p,int num);
  void sha_block_data_order (SHA_CTX *c, const void *p,int num);

#elif defined(SHA_1)

#ifdef	_APPLE_COMMON_CRYPTO_
#if CC_SHA1_USE_HARDWARE
# define HASH_UPDATE             	_CC_SHA1_Update
#else
# define HASH_UPDATE             	CC_SHA1_Update
#endif
# define HASH_TRANSFORM          	CC_SHA1_Transform
# define HASH_FINAL              	CC_SHA1_Final
# define HASH_INIT					CC_SHA1_Init
#else
# define HASH_UPDATE             	SHA1_Update
# define HASH_TRANSFORM          	SHA1_Transform
# define HASH_FINAL              	SHA1_Final
# define HASH_INIT			SHA1_Init
#endif	/* _APPLE_COMMON_CRYPTO_ */

# define HASH_BLOCK_HOST_ORDER   	sha1_block_host_order
# define HASH_BLOCK_DATA_ORDER   	sha1_block_data_order
# if defined(__MWERKS__) && defined(__MC68K__)
   /* Metrowerks for Motorola fails otherwise:-( <appro@fy.chalmers.se> */
#  define Xupdate(a,ix,ia,ib,ic,id)	do { (a)=(ia^ib^ic^id);		\
					     ix=(a)=ROTATE((a),1);	\
					} while (0)
# else
#  define Xupdate(a,ix,ia,ib,ic,id)	( (a)=(ia^ib^ic^id),	\
					  ix=(a)=ROTATE((a),1)	\
					)
# endif

#define SHA1_ASM
#ifdef SHA1_ASM
	#if defined __i386__ || defined __x86_64__
		#define sha1_block_host_order		sha1_block_asm_host_order
		#define DONT_IMPLEMENT_BLOCK_HOST_ORDER
		#define sha1_block_data_order		sha1_block_asm_data_order
		#define DONT_IMPLEMENT_BLOCK_DATA_ORDER
		#define HASH_BLOCK_DATA_ORDER_ALIGNED	sha1_block_asm_data_order
  		#include "sha1edp.h"
	#endif
#endif

__private_extern__ void sha1_block_host_order (SHA_CTX *c, const void *p,int num);
__private_extern__ void sha1_block_data_order (SHA_CTX *c, const void *p,int num);

#else
# error "Either SHA_0 or SHA_1 must be defined."
#endif

#include "md32_common.h"

#define INIT_DATA_h0 0x67452301UL
#define INIT_DATA_h1 0xefcdab89UL
#define INIT_DATA_h2 0x98badcfeUL
#define INIT_DATA_h3 0x10325476UL
#define INIT_DATA_h4 0xc3d2e1f0UL

int HASH_INIT (SHA_CTX *c)
	{
	c->h0=INIT_DATA_h0;
	c->h1=INIT_DATA_h1;
	c->h2=INIT_DATA_h2;
	c->h3=INIT_DATA_h3;
	c->h4=INIT_DATA_h4;
	c->Nl=0;
	c->Nh=0;
	c->num=0;
	return 1;
	}

#define K_00_19	0x5a827999UL
#define K_20_39 0x6ed9eba1UL
#define K_40_59 0x8f1bbcdcUL
#define K_60_79 0xca62c1d6UL

/* As  pointed out by Wei Dai <weidai@eskimo.com>, F() below can be
 * simplified to the code in F_00_19.  Wei attributes these optimisations
 * to Peter Gutmann's SHS code, and he attributes it to Rich Schroeppel.
 * #define F(x,y,z) (((x) & (y))  |  ((~(x)) & (z)))
 * I've just become aware of another tweak to be made, again from Wei Dai,
 * in F_40_59, (x&a)|(y&a) -> (x|y)&a
 */
#define	F_00_19(b,c,d)	((((c) ^ (d)) & (b)) ^ (d)) 
#define	F_20_39(b,c,d)	((b) ^ (c) ^ (d))
#define F_40_59(b,c,d)	(((b) & (c)) | (((b)|(c)) & (d))) 
#define	F_60_79(b,c,d)	F_20_39(b,c,d)

#define BODY_00_15(i,a,b,c,d,e,f,xi) \
	(f)=xi+(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \
	(b)=ROTATE((b),30);

#define BODY_16_19(i,a,b,c,d,e,f,xi,xa,xb,xc,xd) \
	Xupdate(f,xi,xa,xb,xc,xd); \
	(f)+=(e)+K_00_19+ROTATE((a),5)+F_00_19((b),(c),(d)); \
	(b)=ROTATE((b),30);

#define BODY_20_31(i,a,b,c,d,e,f,xi,xa,xb,xc,xd) \
	Xupdate(f,xi,xa,xb,xc,xd); \
	(f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \
	(b)=ROTATE((b),30);

#define BODY_32_39(i,a,b,c,d,e,f,xa,xb,xc,xd) \
	Xupdate(f,xa,xa,xb,xc,xd); \
	(f)+=(e)+K_20_39+ROTATE((a),5)+F_20_39((b),(c),(d)); \
	(b)=ROTATE((b),30);

#define BODY_40_59(i,a,b,c,d,e,f,xa,xb,xc,xd) \
	Xupdate(f,xa,xa,xb,xc,xd); \
	(f)+=(e)+K_40_59+ROTATE((a),5)+F_40_59((b),(c),(d)); \
	(b)=ROTATE((b),30);

#define BODY_60_79(i,a,b,c,d,e,f,xa,xb,xc,xd) \
	Xupdate(f,xa,xa,xb,xc,xd); \
	(f)=xa+(e)+K_60_79+ROTATE((a),5)+F_60_79((b),(c),(d)); \
	(b)=ROTATE((b),30);

#ifdef X
#undef X
#endif
#ifndef MD32_XARRAY
  /*
   * Originally X was an array. As it's automatic it's natural
   * to expect RISC compiler to accomodate at least part of it in
   * the register bank, isn't it? Unfortunately not all compilers
   * "find" this expectation reasonable:-( On order to make such
   * compilers generate better code I replace X[] with a bunch of
   * X0, X1, etc. See the function body below...
   *					<appro@fy.chalmers.se>
   */
# define X(i)	XX##i
#else
  /*
   * However! Some compilers (most notably HP C) get overwhelmed by
   * that many local variables so that we have to have the way to
   * fall down to the original behavior.
   */
# define X(i)	XX[i]
#endif

#ifndef DONT_IMPLEMENT_BLOCK_HOST_ORDER
__private_extern__ void HASH_BLOCK_HOST_ORDER (SHA_CTX *c, const void *d, int num)
	{
	const SHA_LONG *W=d;
	register unsigned MD32_REG_T A,B,C,D,E,T;
#ifndef MD32_XARRAY
	unsigned MD32_REG_T	XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7,
				XX8, XX9,XX10,XX11,XX12,XX13,XX14,XX15;
#else
	SHA_LONG	XX[16];
#endif

	A=c->h0;
	B=c->h1;
	C=c->h2;
	D=c->h3;
	E=c->h4;

	for (;;)
		{
	BODY_00_15( 0,A,B,C,D,E,T,W[ 0]);
	BODY_00_15( 1,T,A,B,C,D,E,W[ 1]);
	BODY_00_15( 2,E,T,A,B,C,D,W[ 2]);
	BODY_00_15( 3,D,E,T,A,B,C,W[ 3]);
	BODY_00_15( 4,C,D,E,T,A,B,W[ 4]);
	BODY_00_15( 5,B,C,D,E,T,A,W[ 5]);
	BODY_00_15( 6,A,B,C,D,E,T,W[ 6]);
	BODY_00_15( 7,T,A,B,C,D,E,W[ 7]);
	BODY_00_15( 8,E,T,A,B,C,D,W[ 8]);
	BODY_00_15( 9,D,E,T,A,B,C,W[ 9]);
	BODY_00_15(10,C,D,E,T,A,B,W[10]);
	BODY_00_15(11,B,C,D,E,T,A,W[11]);
	BODY_00_15(12,A,B,C,D,E,T,W[12]);
	BODY_00_15(13,T,A,B,C,D,E,W[13]);
	BODY_00_15(14,E,T,A,B,C,D,W[14]);
	BODY_00_15(15,D,E,T,A,B,C,W[15]);

	BODY_16_19(16,C,D,E,T,A,B,X( 0),W[ 0],W[ 2],W[ 8],W[13]);
	BODY_16_19(17,B,C,D,E,T,A,X( 1),W[ 1],W[ 3],W[ 9],W[14]);
	BODY_16_19(18,A,B,C,D,E,T,X( 2),W[ 2],W[ 4],W[10],W[15]);
	BODY_16_19(19,T,A,B,C,D,E,X( 3),W[ 3],W[ 5],W[11],X( 0));

	BODY_20_31(20,E,T,A,B,C,D,X( 4),W[ 4],W[ 6],W[12],X( 1));
	BODY_20_31(21,D,E,T,A,B,C,X( 5),W[ 5],W[ 7],W[13],X( 2));
	BODY_20_31(22,C,D,E,T,A,B,X( 6),W[ 6],W[ 8],W[14],X( 3));
	BODY_20_31(23,B,C,D,E,T,A,X( 7),W[ 7],W[ 9],W[15],X( 4));
	BODY_20_31(24,A,B,C,D,E,T,X( 8),W[ 8],W[10],X( 0),X( 5));
	BODY_20_31(25,T,A,B,C,D,E,X( 9),W[ 9],W[11],X( 1),X( 6));
	BODY_20_31(26,E,T,A,B,C,D,X(10),W[10],W[12],X( 2),X( 7));
	BODY_20_31(27,D,E,T,A,B,C,X(11),W[11],W[13],X( 3),X( 8));
	BODY_20_31(28,C,D,E,T,A,B,X(12),W[12],W[14],X( 4),X( 9));
	BODY_20_31(29,B,C,D,E,T,A,X(13),W[13],W[15],X( 5),X(10));
	BODY_20_31(30,A,B,C,D,E,T,X(14),W[14],X( 0),X( 6),X(11));
	BODY_20_31(31,T,A,B,C,D,E,X(15),W[15],X( 1),X( 7),X(12));

	BODY_32_39(32,E,T,A,B,C,D,X( 0),X( 2),X( 8),X(13));
	BODY_32_39(33,D,E,T,A,B,C,X( 1),X( 3),X( 9),X(14));
	BODY_32_39(34,C,D,E,T,A,B,X( 2),X( 4),X(10),X(15));
	BODY_32_39(35,B,C,D,E,T,A,X( 3),X( 5),X(11),X( 0));
	BODY_32_39(36,A,B,C,D,E,T,X( 4),X( 6),X(12),X( 1));
	BODY_32_39(37,T,A,B,C,D,E,X( 5),X( 7),X(13),X( 2));
	BODY_32_39(38,E,T,A,B,C,D,X( 6),X( 8),X(14),X( 3));
	BODY_32_39(39,D,E,T,A,B,C,X( 7),X( 9),X(15),X( 4));

	BODY_40_59(40,C,D,E,T,A,B,X( 8),X(10),X( 0),X( 5));
	BODY_40_59(41,B,C,D,E,T,A,X( 9),X(11),X( 1),X( 6));
	BODY_40_59(42,A,B,C,D,E,T,X(10),X(12),X( 2),X( 7));
	BODY_40_59(43,T,A,B,C,D,E,X(11),X(13),X( 3),X( 8));
	BODY_40_59(44,E,T,A,B,C,D,X(12),X(14),X( 4),X( 9));
	BODY_40_59(45,D,E,T,A,B,C,X(13),X(15),X( 5),X(10));
	BODY_40_59(46,C,D,E,T,A,B,X(14),X( 0),X( 6),X(11));
	BODY_40_59(47,B,C,D,E,T,A,X(15),X( 1),X( 7),X(12));
	BODY_40_59(48,A,B,C,D,E,T,X( 0),X( 2),X( 8),X(13));
	BODY_40_59(49,T,A,B,C,D,E,X( 1),X( 3),X( 9),X(14));
	BODY_40_59(50,E,T,A,B,C,D,X( 2),X( 4),X(10),X(15));
	BODY_40_59(51,D,E,T,A,B,C,X( 3),X( 5),X(11),X( 0));
	BODY_40_59(52,C,D,E,T,A,B,X( 4),X( 6),X(12),X( 1));
	BODY_40_59(53,B,C,D,E,T,A,X( 5),X( 7),X(13),X( 2));
	BODY_40_59(54,A,B,C,D,E,T,X( 6),X( 8),X(14),X( 3));
	BODY_40_59(55,T,A,B,C,D,E,X( 7),X( 9),X(15),X( 4));
	BODY_40_59(56,E,T,A,B,C,D,X( 8),X(10),X( 0),X( 5));
	BODY_40_59(57,D,E,T,A,B,C,X( 9),X(11),X( 1),X( 6));
	BODY_40_59(58,C,D,E,T,A,B,X(10),X(12),X( 2),X( 7));
	BODY_40_59(59,B,C,D,E,T,A,X(11),X(13),X( 3),X( 8));

	BODY_60_79(60,A,B,C,D,E,T,X(12),X(14),X( 4),X( 9));
	BODY_60_79(61,T,A,B,C,D,E,X(13),X(15),X( 5),X(10));
	BODY_60_79(62,E,T,A,B,C,D,X(14),X( 0),X( 6),X(11));
	BODY_60_79(63,D,E,T,A,B,C,X(15),X( 1),X( 7),X(12));
	BODY_60_79(64,C,D,E,T,A,B,X( 0),X( 2),X( 8),X(13));
	BODY_60_79(65,B,C,D,E,T,A,X( 1),X( 3),X( 9),X(14));
	BODY_60_79(66,A,B,C,D,E,T,X( 2),X( 4),X(10),X(15));
	BODY_60_79(67,T,A,B,C,D,E,X( 3),X( 5),X(11),X( 0));
	BODY_60_79(68,E,T,A,B,C,D,X( 4),X( 6),X(12),X( 1));
	BODY_60_79(69,D,E,T,A,B,C,X( 5),X( 7),X(13),X( 2));
	BODY_60_79(70,C,D,E,T,A,B,X( 6),X( 8),X(14),X( 3));
	BODY_60_79(71,B,C,D,E,T,A,X( 7),X( 9),X(15),X( 4));
	BODY_60_79(72,A,B,C,D,E,T,X( 8),X(10),X( 0),X( 5));
	BODY_60_79(73,T,A,B,C,D,E,X( 9),X(11),X( 1),X( 6));
	BODY_60_79(74,E,T,A,B,C,D,X(10),X(12),X( 2),X( 7));
	BODY_60_79(75,D,E,T,A,B,C,X(11),X(13),X( 3),X( 8));
	BODY_60_79(76,C,D,E,T,A,B,X(12),X(14),X( 4),X( 9));
	BODY_60_79(77,B,C,D,E,T,A,X(13),X(15),X( 5),X(10));
	BODY_60_79(78,A,B,C,D,E,T,X(14),X( 0),X( 6),X(11));
	BODY_60_79(79,T,A,B,C,D,E,X(15),X( 1),X( 7),X(12));
	
	c->h0=(c->h0+E)&0xffffffffL; 
	c->h1=(c->h1+T)&0xffffffffL;
	c->h2=(c->h2+A)&0xffffffffL;
	c->h3=(c->h3+B)&0xffffffffL;
	c->h4=(c->h4+C)&0xffffffffL;

	if (--num <= 0) break;

	A=c->h0;
	B=c->h1;
	C=c->h2;
	D=c->h3;
	E=c->h4;

	W+=SHA_LBLOCK;
		}
	}
#endif

#ifndef DONT_IMPLEMENT_BLOCK_DATA_ORDER
__private_extern__ void HASH_BLOCK_DATA_ORDER (SHA_CTX *c, const void *p, int num)
	{
	const unsigned char *data=p;
	register unsigned MD32_REG_T A,B,C,D,E,T,l;
#ifndef MD32_XARRAY
	unsigned MD32_REG_T	XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7,
				XX8, XX9,XX10,XX11,XX12,XX13,XX14,XX15;
#else
	SHA_LONG	XX[16];
#endif

	A=c->h0;
	B=c->h1;
	C=c->h2;
	D=c->h3;
	E=c->h4;

	for (;;)
		{

	HOST_c2l(data,l); X( 0)=l;		HOST_c2l(data,l); X( 1)=l;
	BODY_00_15( 0,A,B,C,D,E,T,X( 0));	HOST_c2l(data,l); X( 2)=l;
	BODY_00_15( 1,T,A,B,C,D,E,X( 1));	HOST_c2l(data,l); X( 3)=l;
	BODY_00_15( 2,E,T,A,B,C,D,X( 2));	HOST_c2l(data,l); X( 4)=l;
	BODY_00_15( 3,D,E,T,A,B,C,X( 3));	HOST_c2l(data,l); X( 5)=l;
	BODY_00_15( 4,C,D,E,T,A,B,X( 4));	HOST_c2l(data,l); X( 6)=l;
	BODY_00_15( 5,B,C,D,E,T,A,X( 5));	HOST_c2l(data,l); X( 7)=l;
	BODY_00_15( 6,A,B,C,D,E,T,X( 6));	HOST_c2l(data,l); X( 8)=l;
	BODY_00_15( 7,T,A,B,C,D,E,X( 7));	HOST_c2l(data,l); X( 9)=l;
	BODY_00_15( 8,E,T,A,B,C,D,X( 8));	HOST_c2l(data,l); X(10)=l;
	BODY_00_15( 9,D,E,T,A,B,C,X( 9));	HOST_c2l(data,l); X(11)=l;
	BODY_00_15(10,C,D,E,T,A,B,X(10));	HOST_c2l(data,l); X(12)=l;
	BODY_00_15(11,B,C,D,E,T,A,X(11));	HOST_c2l(data,l); X(13)=l;
	BODY_00_15(12,A,B,C,D,E,T,X(12));	HOST_c2l(data,l); X(14)=l;
	BODY_00_15(13,T,A,B,C,D,E,X(13));	HOST_c2l(data,l); X(15)=l;
	BODY_00_15(14,E,T,A,B,C,D,X(14));
	BODY_00_15(15,D,E,T,A,B,C,X(15));

	BODY_16_19(16,C,D,E,T,A,B,X( 0),X( 0),X( 2),X( 8),X(13));
	BODY_16_19(17,B,C,D,E,T,A,X( 1),X( 1),X( 3),X( 9),X(14));
	BODY_16_19(18,A,B,C,D,E,T,X( 2),X( 2),X( 4),X(10),X(15));
	BODY_16_19(19,T,A,B,C,D,E,X( 3),X( 3),X( 5),X(11),X( 0));

	BODY_20_31(20,E,T,A,B,C,D,X( 4),X( 4),X( 6),X(12),X( 1));
	BODY_20_31(21,D,E,T,A,B,C,X( 5),X( 5),X( 7),X(13),X( 2));
	BODY_20_31(22,C,D,E,T,A,B,X( 6),X( 6),X( 8),X(14),X( 3));
	BODY_20_31(23,B,C,D,E,T,A,X( 7),X( 7),X( 9),X(15),X( 4));
	BODY_20_31(24,A,B,C,D,E,T,X( 8),X( 8),X(10),X( 0),X( 5));
	BODY_20_31(25,T,A,B,C,D,E,X( 9),X( 9),X(11),X( 1),X( 6));
	BODY_20_31(26,E,T,A,B,C,D,X(10),X(10),X(12),X( 2),X( 7));
	BODY_20_31(27,D,E,T,A,B,C,X(11),X(11),X(13),X( 3),X( 8));
	BODY_20_31(28,C,D,E,T,A,B,X(12),X(12),X(14),X( 4),X( 9));
	BODY_20_31(29,B,C,D,E,T,A,X(13),X(13),X(15),X( 5),X(10));
	BODY_20_31(30,A,B,C,D,E,T,X(14),X(14),X( 0),X( 6),X(11));
	BODY_20_31(31,T,A,B,C,D,E,X(15),X(15),X( 1),X( 7),X(12));

	BODY_32_39(32,E,T,A,B,C,D,X( 0),X( 2),X( 8),X(13));
	BODY_32_39(33,D,E,T,A,B,C,X( 1),X( 3),X( 9),X(14));
	BODY_32_39(34,C,D,E,T,A,B,X( 2),X( 4),X(10),X(15));
	BODY_32_39(35,B,C,D,E,T,A,X( 3),X( 5),X(11),X( 0));
	BODY_32_39(36,A,B,C,D,E,T,X( 4),X( 6),X(12),X( 1));
	BODY_32_39(37,T,A,B,C,D,E,X( 5),X( 7),X(13),X( 2));
	BODY_32_39(38,E,T,A,B,C,D,X( 6),X( 8),X(14),X( 3));
	BODY_32_39(39,D,E,T,A,B,C,X( 7),X( 9),X(15),X( 4));

	BODY_40_59(40,C,D,E,T,A,B,X( 8),X(10),X( 0),X( 5));
	BODY_40_59(41,B,C,D,E,T,A,X( 9),X(11),X( 1),X( 6));
	BODY_40_59(42,A,B,C,D,E,T,X(10),X(12),X( 2),X( 7));
	BODY_40_59(43,T,A,B,C,D,E,X(11),X(13),X( 3),X( 8));
	BODY_40_59(44,E,T,A,B,C,D,X(12),X(14),X( 4),X( 9));
	BODY_40_59(45,D,E,T,A,B,C,X(13),X(15),X( 5),X(10));
	BODY_40_59(46,C,D,E,T,A,B,X(14),X( 0),X( 6),X(11));
	BODY_40_59(47,B,C,D,E,T,A,X(15),X( 1),X( 7),X(12));
	BODY_40_59(48,A,B,C,D,E,T,X( 0),X( 2),X( 8),X(13));
	BODY_40_59(49,T,A,B,C,D,E,X( 1),X( 3),X( 9),X(14));
	BODY_40_59(50,E,T,A,B,C,D,X( 2),X( 4),X(10),X(15));
	BODY_40_59(51,D,E,T,A,B,C,X( 3),X( 5),X(11),X( 0));
	BODY_40_59(52,C,D,E,T,A,B,X( 4),X( 6),X(12),X( 1));
	BODY_40_59(53,B,C,D,E,T,A,X( 5),X( 7),X(13),X( 2));
	BODY_40_59(54,A,B,C,D,E,T,X( 6),X( 8),X(14),X( 3));
	BODY_40_59(55,T,A,B,C,D,E,X( 7),X( 9),X(15),X( 4));
	BODY_40_59(56,E,T,A,B,C,D,X( 8),X(10),X( 0),X( 5));
	BODY_40_59(57,D,E,T,A,B,C,X( 9),X(11),X( 1),X( 6));
	BODY_40_59(58,C,D,E,T,A,B,X(10),X(12),X( 2),X( 7));
	BODY_40_59(59,B,C,D,E,T,A,X(11),X(13),X( 3),X( 8));

	BODY_60_79(60,A,B,C,D,E,T,X(12),X(14),X( 4),X( 9));
	BODY_60_79(61,T,A,B,C,D,E,X(13),X(15),X( 5),X(10));
	BODY_60_79(62,E,T,A,B,C,D,X(14),X( 0),X( 6),X(11));
	BODY_60_79(63,D,E,T,A,B,C,X(15),X( 1),X( 7),X(12));
	BODY_60_79(64,C,D,E,T,A,B,X( 0),X( 2),X( 8),X(13));
	BODY_60_79(65,B,C,D,E,T,A,X( 1),X( 3),X( 9),X(14));
	BODY_60_79(66,A,B,C,D,E,T,X( 2),X( 4),X(10),X(15));
	BODY_60_79(67,T,A,B,C,D,E,X( 3),X( 5),X(11),X( 0));
	BODY_60_79(68,E,T,A,B,C,D,X( 4),X( 6),X(12),X( 1));
	BODY_60_79(69,D,E,T,A,B,C,X( 5),X( 7),X(13),X( 2));
	BODY_60_79(70,C,D,E,T,A,B,X( 6),X( 8),X(14),X( 3));
	BODY_60_79(71,B,C,D,E,T,A,X( 7),X( 9),X(15),X( 4));
	BODY_60_79(72,A,B,C,D,E,T,X( 8),X(10),X( 0),X( 5));
	BODY_60_79(73,T,A,B,C,D,E,X( 9),X(11),X( 1),X( 6));
	BODY_60_79(74,E,T,A,B,C,D,X(10),X(12),X( 2),X( 7));
	BODY_60_79(75,D,E,T,A,B,C,X(11),X(13),X( 3),X( 8));
	BODY_60_79(76,C,D,E,T,A,B,X(12),X(14),X( 4),X( 9));
	BODY_60_79(77,B,C,D,E,T,A,X(13),X(15),X( 5),X(10));
	BODY_60_79(78,A,B,C,D,E,T,X(14),X( 0),X( 6),X(11));
	BODY_60_79(79,T,A,B,C,D,E,X(15),X( 1),X( 7),X(12));
	
	c->h0=(c->h0+E)&0xffffffffL; 
	c->h1=(c->h1+T)&0xffffffffL;
	c->h2=(c->h2+A)&0xffffffffL;
	c->h3=(c->h3+B)&0xffffffffL;
	c->h4=(c->h4+C)&0xffffffffL;

	if (--num <= 0) break;

	A=c->h0;
	B=c->h1;
	C=c->h2;
	D=c->h3;
	E=c->h4;

		}
	}
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Added Source/Exports/CommonCrypto.exp.





































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
_CCAESCmac
_CCBigNumAdd
_CCBigNumAddI
_CCBigNumBitCount
_CCBigNumByteCount
_CCBigNumByteCount
_CCBigNumClear
_CCBigNumCompare
_CCBigNumCompareI
_CCBigNumCopy
_CCBigNumCreateRandom
_CCBigNumDiv
_CCBigNumDiv2
_CCBigNumFree
_CCBigNumFromData
_CCBigNumFromHexString
_CCBigNumGCD
_CCBigNumGetI
_CCBigNumInverseMod
_CCBigNumIsNegative
_CCBigNumIsOdd
_CCBigNumIsPrime
_CCBigNumIsZero
_CCBigNumLCM
_CCBigNumLeftShift
_CCBigNumMod
_CCBigNumModExp
_CCBigNumModI
_CCBigNumMontgomeryNormalization
_CCBigNumMontgomeryReduce
_CCBigNumMontgomerySetup
_CCBigNumMul
_CCBigNumMulI
_CCBigNumMulMod
_CCBigNumRightShift
_CCBigNumSetI
_CCBigNumSetNegative
_CCBigNumSquare
_CCBigNumSquareMod
_CCBigNumSub
_CCBigNumSubI
_CCBigNumToData
_CCBigNumToHexString
_CCBigNumZeroLSBCount
_CCCalibratePBKDF
_CCCreateBigNum
_CCCrypt
_CCCryptorCreate
_CCCryptorCreateFromData
_CCCryptorCreateFromDataWithMode
_CCCryptorCreateWithMode
_CCCryptorDecryptDataBlock
_CCCryptorEncryptDataBlock
_CCCryptorFinal
_CCCryptorGCM
_CCCryptorGCMaddAAD
_CCCryptorGCMAddAAD
_CCCryptorGCMAddADD
_CCCryptorGCMAddIV
_CCCryptorGCMDecrypt
_CCCryptorGCMEncrypt
_CCCryptorGCMFinal
_CCCryptorGCMReset
_CCCryptorGetIV
_CCCryptorGetOutputLength
_CCCryptorRelease
_CCCryptorReset
_CCCryptorUpdate
_CCDHComputeKey
_CCDHCreate
_CCDHGenerateKey
_CCDHParametersCreateFromData
_CCDHParametersCreateFromPKCS3
_CCDHParametersPKCS3EncodeLength
_CCDHParametersPKCS3Encode
_CCDHParametersRelease
_CCDHRelease
_CCDesCBCCksum
_CCDesIsWeakKey
_CCDesSetOddParity
_CCDigest
_CCDigestCreate
_CCDigestCreateByOID
_CCDigestDestroy
_CCDigestFinal
_CCDigestGetBlockSize
_CCDigestGetBlockSizeFromRef
_CCDigestGetOutputSize
_CCDigestOutputSize
_CCDigestGetOutputSizeFromRef
_CCDigestInit
_CCDigestOID
_CCDigestOIDLen
_CCDigestReset
_CCDigestUpdate
_CCECCryptorComputeSharedSecret
_CCECCryptorCreateFromData
_CCECCryptorExportKey
_CCECCryptorExportPublicKey
_CCECCryptorGeneratePair
_CCECCryptorGetKeyComponents
_CCECCryptorImportKey
_CCECCryptorImportPublicKey
_CCECCryptorRelease
_CCECCryptorSignHash
_CCECCryptorUnwrapKey
_CCECCryptorVerifyHash
_CCECCryptorWrapKey
_CCECGetKeySize
_CCECGetKeyType
_CCHmac
_CCHmacCreate
_CCHmacDestroy
_CCHmacFinal
_CCHmacInit
_CCHmacOutputSize
_CCHmacOutputSizeFromRef
_CCHmacUpdate
_CCKeyDerivationPBKDF
_CCRNGCreate
_CCRNGRelease
_CCRSACryptorCreateFromData
_CCRSACryptorCreatePairFromData
_CCRSACryptorCrypt
_CCRSACryptorDecrypt
_CCRSACryptorEncrypt
_CCRSACryptorExport
_CCRSACryptorGeneratePair
_CCRSACryptorImport
_CCRSACryptorRelease
_CCRSACryptorSign
_CCRSACryptorVerify
_CCRSAGetKeyComponents
_CCRSAGetKeySize
_CCRSAGetKeyType
_CCRandomCopyBytes
_CCSymmetricKeyUnwrap
_CCSymmetricKeyWrap
_CCSymmetricUnwrappedSize
_CCSymmetricWrappedSize
_CC_MD2
_CC_MD2_Final
_CC_MD2_Init
_CC_MD2_Update
_CC_MD4
_CC_MD4_Final
_CC_MD4_Init
_CC_MD4_Update
_CC_MD5
_CC_MD5_Final
_CC_MD5_Init
_CC_MD5_Update
_CC_RC4
_CC_RC4_set_key
_CC_SHA1
_CC_SHA1_Final
_CC_SHA1_Init
_CC_SHA1_Update
_CC_SHA224
_CC_SHA224_Final
_CC_SHA224_Init
_CC_SHA224_Update
_CC_SHA256
_CC_SHA256_Final
_CC_SHA256_Init
_CC_SHA256_Update
_CC_SHA384
_CC_SHA384_Final
_CC_SHA384_Init
_CC_SHA384_Update
_CC_SHA512
_CC_SHA512_Final
_CC_SHA512_Init
_CC_SHA512_Update
_CCrfc3394_iv
_CCrfc3394_ivLen
_aes_decrypt_cbc
_aes_decrypt_key128
_aes_decrypt_key256
_aes_encrypt_cbc
_aes_encrypt_key128
_aes_encrypt_key256
_ccDRBGGetRngState
_ccDevRandomGetRngState
_kCCRandomDefault
_kCCRandomDevRandom
_kCCDHRFC2409Group2
_kCCDHRFC3526Group5
_CCDigestBlockSize
_CAST_ecb_encrypt
_CAST_set_key
_MD5Final


Added Source/Exports/CommonCryptoIOS5.exp.

































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
_CCAESCmac
_CCBigNumAdd
_CCBigNumAddI
_CCBigNumBitCount
_CCBigNumByteCount
_CCBigNumByteCount
_CCBigNumClear
_CCBigNumCompare
_CCBigNumCompareI
_CCBigNumCopy
_CCBigNumCreateRandom
_CCBigNumDiv
_CCBigNumDiv2
_CCBigNumFree
_CCBigNumFromData
_CCBigNumFromHexString
_CCBigNumGCD
_CCBigNumGetI
_CCBigNumInverseMod
_CCBigNumIsNegative
_CCBigNumIsOdd
_CCBigNumIsPrime
_CCBigNumIsZero
_CCBigNumLCM
_CCBigNumLeftShift
_CCBigNumMod
_CCBigNumModExp
_CCBigNumModI
_CCBigNumMontgomeryNormalization
_CCBigNumMontgomeryReduce
_CCBigNumMontgomerySetup
_CCBigNumMul
_CCBigNumMulI
_CCBigNumMulMod
_CCBigNumRightShift
_CCBigNumSetI
_CCBigNumSetNegative
_CCBigNumSquare
_CCBigNumSquareMod
_CCBigNumSub
_CCBigNumSubI
_CCBigNumToData
_CCBigNumToHexString
_CCBigNumZeroLSBCount
_CCCalibratePBKDF
_CCCreateBigNum
_CCCrypt
_CCCryptorCreate
_CCCryptorCreateFromData
_CCCryptorCreateFromDataWithMode
_CCCryptorCreateWithMode
_CCCryptorDecryptDataBlock
_CCCryptorEncryptDataBlock
_CCCryptorFinal
_CCCryptorGCM
_CCCryptorGCMaddAAD
_CCCryptorGCMAddAAD
_CCCryptorGCMAddADD
_CCCryptorGCMAddIV
_CCCryptorGCMDecrypt
_CCCryptorGCMEncrypt
_CCCryptorGCMFinal
_CCCryptorGCMReset
_CCCryptorGetIV
_CCCryptorGetOutputLength
_CCCryptorRelease
_CCCryptorReset
_CCCryptorUpdate
_CCDHComputeKey
_CCDHCreate
_CCDHGenerateKey
_CCDHParametersCreateFromData
_CCDHParametersCreateFromPKCS3
_CCDHParametersPKCS3EncodeLength
_CCDHParametersPKCS3Encode
_CCDHParametersRelease
_CCDHRelease
_CCDesCBCCksum
_CCDesIsWeakKey
_CCDesSetOddParity
_CCDigest
_CCDigestCreate
_CCDigestCreateByOID
_CCDigestDestroy
_CCDigestFinal
_CCDigestGetBlockSize
_CCDigestGetBlockSizeFromRef
_CCDigestGetOutputSize
_CCDigestOutputSize
_CCDigestGetOutputSizeFromRef
_CCDigestInit
_CCDigestOID
_CCDigestOIDLen
_CCDigestReset
_CCDigestUpdate
_CCECCryptorComputeSharedSecret
_CCECCryptorCreateFromData
_CCECCryptorExportKey
_CCECCryptorExportPublicKey
_CCECCryptorGeneratePair
_CCECCryptorGetKeyComponents
_CCECCryptorImportKey
_CCECCryptorImportPublicKey
_CCECCryptorRelease
_CCECCryptorSignHash
_CCECCryptorUnwrapKey
_CCECCryptorVerifyHash
_CCECCryptorWrapKey
_CCECGetKeySize
_CCECGetKeyType
_CCHmac
_CCHmacCreate
_CCHmacDestroy
_CCHmacFinal
_CCHmacInit
_CCHmacOutputSize
_CCHmacOutputSizeFromRef
_CCHmacUpdate
_CCKeyDerivationPBKDF
_CCRNGCreate
_CCRNGRelease
_CCRSACryptorCreateFromData
_CCRSACryptorCreatePairFromData
_CCRSACryptorCrypt
_CCRSACryptorDecrypt
_CCRSACryptorEncrypt
_CCRSACryptorExport
_CCRSACryptorGeneratePair
_CCRSACryptorImport
_CCRSACryptorRelease
_CCRSACryptorSign
_CCRSACryptorVerify
_CCRSAGetKeyComponents
_CCRSAGetKeySize
_CCRSAGetKeyType
_CCRandomCopyBytes
_CCSymmetricKeyUnwrap
_CCSymmetricKeyWrap
_CCSymmetricUnwrappedSize
_CCSymmetricWrappedSize
_CC_MD2
_CC_MD2_Final
_CC_MD2_Init
_CC_MD2_Update
_CC_MD4
_CC_MD4_Final
_CC_MD4_Init
_CC_MD4_Update
_CC_MD5
_CC_MD5_Final
_CC_MD5_Init
_CC_MD5_Update
_CC_RC4
_CC_RC4_set_key
_CC_SHA1
_CC_SHA1_Final
_CC_SHA1_Init
_CC_SHA1_Update
_CC_SHA224
_CC_SHA224_Final
_CC_SHA224_Init
_CC_SHA224_Update
_CC_SHA256
_CC_SHA256_Final
_CC_SHA256_Init
_CC_SHA256_Update
_CC_SHA384
_CC_SHA384_Final
_CC_SHA384_Init
_CC_SHA384_Update
_CC_SHA512
_CC_SHA512_Final
_CC_SHA512_Init
_CC_SHA512_Update
_CCrfc3394_iv
_CCrfc3394_ivLen
_aes_decrypt_cbc
_aes_decrypt_key128
_aes_decrypt_key256
_aes_encrypt_cbc
_aes_encrypt_key128
_aes_encrypt_key256
_ccDRBGGetRngState
_ccDevRandomGetRngState
_kCCRandomDefault
_kCCRandomDevRandom
_kCCDHRFC2409Group2
_kCCDHRFC3526Group5
_CCDigestBlockSize
_MD5Final


Deleted Source/GladmanAES/README.

1
2
3
4
5
6
This AES implementation is based on the Gladman implementation in xnu-863. 

The C files in this directory have been modified to produce no object code
unless the preprocessor symbol UseGladmanAES is defined (in aesopt.h).  If the
symbol is not defined, there some other AES implementation (such as AESedp)
must be supplied elsewhere in the build.
<
<
<
<
<
<












Deleted Source/GladmanAES/aescrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*
 ---------------------------------------------------------------------------
 Copyright (c) 2003, Dr Brian Gladman, Worcester, UK.   All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue 28/01/2004

 This file contains the code for implementing encryption and decryption
 for AES (Rijndael) for block and key sizes of 16, 24 and 32 bytes. It
 can optionally be replaced by code written in assembler using NASM. For
 further details see the file aesopt.h
*/

#include <CommonCrypto/aesopt.h>
#include "aestab.h"
#include <strings.h>

/*	Produce object code iff UseGladmanAES is defined.  Otherwise, suppress
	use of this module, because some other AES implementation is being used.
*/
#if defined UseGladmanAES

#if defined(__cplusplus)
extern "C"
{
#endif

#define ki(y,x,k,c) (s(y,c) = s(x, c) ^ (k)[c])
#define xo(y,x,c) (s(y,c) ^= s(x, c))
#define si(y,x,c)   (s(y,c) = word_in(x, c))
#define so(y,x,c)   word_out(y, c, s(x,c))

#if defined(ARRAYS)
#define locals(y,x)     x[4],y[4]
#else
#define locals(y,x)     x##0,x##1,x##2,x##3,y##0,y##1,y##2,y##3
#endif

#define dtables(tab)     const aes_32t *tab##0, *tab##1, *tab##2, *tab##3
#define itables(tab)     tab##0 = tab[0]; tab##1 = tab[1]; tab##2 = tab[2]; tab##3 = tab[3]

#define l_copy(y, x)    s(y,0) = s(x,0); s(y,1) = s(x,1); \
                        s(y,2) = s(x,2); s(y,3) = s(x,3);

#define key_in(y,x,k)   ki(y,x,k,0); ki(y,x,k,1); ki(y,x,k,2); ki(y,x,k,3)
#define cbc(y,x)        xo(y,x,0); xo(y,x,1); xo(y,x,2); xo(y,x,3)
#define state_in(y,x)   si(y,x,0); si(y,x,1); si(y,x,2); si(y,x,3)
#define state_out(y,x)  so(y,x,0); so(y,x,1); so(y,x,2); so(y,x,3)
#define round(rm,y,x,k) rm(y,x,k,0); rm(y,x,k,1); rm(y,x,k,2); rm(y,x,k,3)

#if defined(ENCRYPTION) && !defined(AES_ASM)

/* Visual C++ .Net v7.1 provides the fastest encryption code when using
   Pentium optimiation with small code but this is poor for decryption
   so we need to control this with the following VC++ pragmas
*/

#if defined(_MSC_VER)
#pragma optimize( "s", on )
#endif

/* Given the column (c) of the output state variable, the following
   macros give the input state variables which are needed in its
   computation for each row (r) of the state. All the alternative
   macros give the same end values but expand into different ways
   of calculating these values.  In particular the complex macro
   used for dynamically variable block sizes is designed to expand
   to a compile time constant whenever possible but will expand to
   conditional clauses on some branches (I am grateful to Frank
   Yellin for this construction)
*/

#define fwd_var(x,r,c)\
 ( r == 0 ? ( c == 0 ? s(x,0) : c == 1 ? s(x,1) : c == 2 ? s(x,2) : s(x,3))\
 : r == 1 ? ( c == 0 ? s(x,1) : c == 1 ? s(x,2) : c == 2 ? s(x,3) : s(x,0))\
 : r == 2 ? ( c == 0 ? s(x,2) : c == 1 ? s(x,3) : c == 2 ? s(x,0) : s(x,1))\
 :          ( c == 0 ? s(x,3) : c == 1 ? s(x,0) : c == 2 ? s(x,1) : s(x,2)))

#if defined(FT4_SET)
#undef  dec_fmvars
#  if defined(ENC_ROUND_CACHE_TABLES)
#define fwd_rnd(y,x,k,c)    (s(y,c) = (k)[c] ^ four_cached_tables(x,t_fn,fwd_var,rf1,c))
#  else
#define fwd_rnd(y,x,k,c)    (s(y,c) = (k)[c] ^ four_tables(x,t_fn,fwd_var,rf1,c))
#  endif
#elif defined(FT1_SET)
#undef  dec_fmvars
#define fwd_rnd(y,x,k,c)    (s(y,c) = (k)[c] ^ one_table(x,upr,t_fn,fwd_var,rf1,c))
#else
#define fwd_rnd(y,x,k,c)    (s(y,c) = (k)[c] ^ fwd_mcol(no_table(x,t_sbox,fwd_var,rf1,c)))
#endif

#if defined(FL4_SET)
#  if defined(LAST_ENC_ROUND_CACHE_TABLES)
#define fwd_lrnd(y,x,k,c)   (s(y,c) = (k)[c] ^ four_cached_tables(x,t_fl,fwd_var,rf1,c))
#  else
#define fwd_lrnd(y,x,k,c)   (s(y,c) = (k)[c] ^ four_tables(x,t_fl,fwd_var,rf1,c))
#  endif
#elif defined(FL1_SET)
#define fwd_lrnd(y,x,k,c)   (s(y,c) = (k)[c] ^ one_table(x,ups,t_fl,fwd_var,rf1,c))
#else
#define fwd_lrnd(y,x,k,c)   (s(y,c) = (k)[c] ^ no_table(x,t_sbox,fwd_var,rf1,c))
#endif

aes_rval aes_encrypt_cbc(const unsigned char *in, const unsigned char *in_iv, unsigned int num_blk,
					 unsigned char *out, aes_encrypt_ctx cx[1])
{   aes_32t         locals(b0, b1);
    const aes_32t   *kp;
    const aes_32t   *kptr = cx->ks;
	#ifdef _APPLE_COMMON_CRYPTO_
	int				cbcEnable = (cx->cbcEnable || in_iv) ? 1 : 0;
	#endif
	
#if defined(ENC_ROUND_CACHE_TABLES)
	dtables(t_fn);
#endif
#if defined(LAST_ENC_ROUND_CACHE_TABLES)
	dtables(t_fl);
#endif

#if defined( dec_fmvars )
    dec_fmvars; /* declare variables for fwd_mcol() if needed */
#endif

#if defined( AES_ERR_CHK )
    if( cx->rn != 10 && cx->rn != 12 && cx->rn != 14 )
        return aes_error;
#endif

	// Load IV into b0.
	#ifdef		_APPLE_COMMON_CRYPTO_
	if(in_iv) {
		state_in(b0, in_iv);
	}
	else {
		state_in(b0, cx->chainBuf);
	}
	#else
	state_in(b0, in_iv);
	#endif	/* _APPLE_COMMON_CRYPTO_ */
	
	for (;num_blk; in += AES_BLOCK_SIZE, out += AES_BLOCK_SIZE, --num_blk)
	{
		kp = kptr;
#if 0
		// Read the plaintext into b1
		state_in(b1, in);
		#ifdef _APPLE_COMMON_CRYPTO_
		if(cbcEnable) {
		#endif
			// Do the CBC with b0 which is either the iv or the ciphertext of the 
			// previous block.
			cbc(b1, b0);
		#ifdef _APPLE_COMMON_CRYPTO_
		}
		#endif

		// Xor b1 with the key schedule to get things started.
		key_in(b0, b1, kp);
#else
		#ifdef _APPLE_COMMON_CRYPTO_
		if(cbcEnable) {
		#endif
			// Since xor is associative we mess with the ordering here to get 
			// the loads started early
			key_in(b1, b0, kp);  // Xor b0(IV) with the key schedule and assign to b1
			state_in(b0, in);    // Load block into b0
			cbc(b0, b1);         // Xor b0 with b1 and store in b0
		#ifdef _APPLE_COMMON_CRYPTO_
		}
		else {
			// Read the plaintext into b1
			state_in(b1, in);
			key_in(b0, b1, kp);
		}
		#endif	/* _APPLE_COMMON_CRYPTO_ */
#endif	/* 0 */

#if defined(ENC_ROUND_CACHE_TABLES)
		itables(t_fn);
#endif

#if (ENC_UNROLL == FULL)

		switch(cx->rn)
		{
		case 14:
			round(fwd_rnd,  b1, b0, kp + 1 * N_COLS);
			round(fwd_rnd,  b0, b1, kp + 2 * N_COLS);
			kp += 2 * N_COLS;
		case 12:
			round(fwd_rnd,  b1, b0, kp + 1 * N_COLS);
			round(fwd_rnd,  b0, b1, kp + 2 * N_COLS);
			kp += 2 * N_COLS;
		case 10:
		default:
			round(fwd_rnd,  b1, b0, kp + 1 * N_COLS);
			round(fwd_rnd,  b0, b1, kp + 2 * N_COLS);
			round(fwd_rnd,  b1, b0, kp + 3 * N_COLS);
			round(fwd_rnd,  b0, b1, kp + 4 * N_COLS);
			round(fwd_rnd,  b1, b0, kp + 5 * N_COLS);
			round(fwd_rnd,  b0, b1, kp + 6 * N_COLS);
			round(fwd_rnd,  b1, b0, kp + 7 * N_COLS);
			round(fwd_rnd,  b0, b1, kp + 8 * N_COLS);
			round(fwd_rnd,  b1, b0, kp + 9 * N_COLS);
#if defined(LAST_ENC_ROUND_CACHE_TABLES)
			itables(t_fl);
#endif
			round(fwd_lrnd, b0, b1, kp +10 * N_COLS);
		}

#else

		{   aes_32t    rnd;
#if (ENC_UNROLL == PARTIAL)
			for(rnd = 0; rnd < (cx->rn >> 1) - 1; ++rnd)
			{
				kp += N_COLS;
				round(fwd_rnd, b1, b0, kp);
				kp += N_COLS;
				round(fwd_rnd, b0, b1, kp);
			}
			kp += N_COLS;
			round(fwd_rnd,  b1, b0, kp);
#else
			for(rnd = 0; rnd < cx->rn - 1; ++rnd)
			{
				kp += N_COLS;
				round(fwd_rnd, b1, b0, kp);
				l_copy(b0, b1);
			}
#endif
#if defined(LAST_ENC_ROUND_CACHE_TABLES)
			itables(t_fl);
#endif
			kp += N_COLS;
			round(fwd_lrnd, b0, b1, kp);
		}
#endif
	
		state_out(out, b0);
	}
	
	#ifdef _APPLE_COMMON_CRYPTO_
	if(cbcEnable) {
		state_out(cx->chainBuf, b0);
	}
	#endif

#if defined( AES_ERR_CHK )
    return aes_good;
#endif
}

#endif

#if defined(DECRYPTION) && !defined(AES_ASM)

/* Visual C++ .Net v7.1 provides the fastest encryption code when using
   Pentium optimiation with small code but this is poor for decryption
   so we need to control this with the following VC++ pragmas
*/

#if defined(_MSC_VER)
#pragma optimize( "t", on )
#endif

/* Given the column (c) of the output state variable, the following
   macros give the input state variables which are needed in its
   computation for each row (r) of the state. All the alternative
   macros give the same end values but expand into different ways
   of calculating these values.  In particular the complex macro
   used for dynamically variable block sizes is designed to expand
   to a compile time constant whenever possible but will expand to
   conditional clauses on some branches (I am grateful to Frank
   Yellin for this construction)
*/

#define inv_var(x,r,c)\
 ( r == 0 ? ( c == 0 ? s(x,0) : c == 1 ? s(x,1) : c == 2 ? s(x,2) : s(x,3))\
 : r == 1 ? ( c == 0 ? s(x,3) : c == 1 ? s(x,0) : c == 2 ? s(x,1) : s(x,2))\
 : r == 2 ? ( c == 0 ? s(x,2) : c == 1 ? s(x,3) : c == 2 ? s(x,0) : s(x,1))\
 :          ( c == 0 ? s(x,1) : c == 1 ? s(x,2) : c == 2 ? s(x,3) : s(x,0)))

#if defined(IT4_SET)
#undef  dec_imvars
#  if defined(DEC_ROUND_CACHE_TABLES)
#define inv_rnd(y,x,k,c)    (s(y,c) = (k)[c] ^ four_cached_tables(x,t_in,inv_var,rf1,c))
#  else
#define inv_rnd(y,x,k,c)    (s(y,c) = (k)[c] ^ four_tables(x,t_in,inv_var,rf1,c))
#  endif
#elif defined(IT1_SET)
#undef  dec_imvars
#define inv_rnd(y,x,k,c)    (s(y,c) = (k)[c] ^ one_table(x,upr,t_in,inv_var,rf1,c))
#else
#define inv_rnd(y,x,k,c)    (s(y,c) = inv_mcol((k)[c] ^ no_table(x,t_ibox,inv_var,rf1,c)))
#endif

#if defined(IL4_SET)
#  if defined(LAST_DEC_ROUND_CACHE_TABLES)
#define inv_lrnd(y,x,k,c)   (s(y,c) = (k)[c] ^ four_cached_tables(x,t_il,inv_var,rf1,c))
#  else
#define inv_lrnd(y,x,k,c)   (s(y,c) = (k)[c] ^ four_tables(x,t_il,inv_var,rf1,c))
#  endif
#elif defined(IL1_SET)
#define inv_lrnd(y,x,k,c)   (s(y,c) = (k)[c] ^ one_table(x,ups,t_il,inv_var,rf1,c))
#else
#define inv_lrnd(y,x,k,c)   (s(y,c) = (k)[c] ^ no_table(x,t_ibox,inv_var,rf1,c))
#endif


aes_rval aes_decrypt_cbc(const unsigned char *in, const unsigned char *in_iv, unsigned int num_blk,
					 unsigned char *out, aes_decrypt_ctx cx[1])
{   aes_32t        locals(b0, b1);
    const aes_32t *kptr = cx->ks + cx->rn * N_COLS;
	const aes_32t *kp;
#if defined(DEC_ROUND_CACHE_TABLES)
	dtables(t_in);
#endif
#if defined(LAST_DEC_ROUND_CACHE_TABLES)
	dtables(t_il);
#endif
	#ifdef		_APPLE_COMMON_CRYPTO_
	int cbcEnable = (cx->cbcEnable || in_iv) ? 1 : 0;
	unsigned char lastIv[AES_BLOCK_SIZE];
	
	/* fix a compiler warning... */
	b00 = 0; b01 = 0; b02=0; b03 = 0;
	#endif
	
#if defined( dec_imvars )
    dec_imvars; /* declare variables for inv_mcol() if needed */
#endif
	
#if defined( AES_ERR_CHK )
    if( cx->rn != 10 && cx->rn != 12 && cx->rn != 14 )
        return aes_error;
#endif

#if defined(DEC_ROUND_CACHE_TABLES)
	itables(t_in);
#endif	
	
	in += AES_BLOCK_SIZE * (num_blk - 1);
	out += AES_BLOCK_SIZE * (num_blk - 1);
	// Load the last block's ciphertext into b1
	state_in(b1, in);

	#ifdef	_APPLE_COMMON_CRYPTO_
	/* save that last ciphertext block for next op's chain */
	if(cbcEnable & (num_blk != 0)) {
		memmove(lastIv, in, AES_BLOCK_SIZE);
	}
	#endif
	
	for (;num_blk; out -= AES_BLOCK_SIZE, --num_blk)
	{
		kp = kptr;
		// Do the xor part of state_in, where b1 is the previous block's ciphertext.
		key_in(b0, b1, kp);

#if (DEC_UNROLL == FULL)
	
		switch(cx->rn)
		{
		case 14:
			round(inv_rnd,  b1, b0, kp -  1 * N_COLS);
			round(inv_rnd,  b0, b1, kp -  2 * N_COLS);
			kp -= 2 * N_COLS;
		case 12:
			round(inv_rnd,  b1, b0, kp -  1 * N_COLS);
			round(inv_rnd,  b0, b1, kp -  2 * N_COLS);
			kp -= 2 * N_COLS;
		case 10:
		default:
			round(inv_rnd,  b1, b0, kp -  1 * N_COLS);
			round(inv_rnd,  b0, b1, kp -  2 * N_COLS);
			round(inv_rnd,  b1, b0, kp -  3 * N_COLS);
			round(inv_rnd,  b0, b1, kp -  4 * N_COLS);
			round(inv_rnd,  b1, b0, kp -  5 * N_COLS);
			round(inv_rnd,  b0, b1, kp -  6 * N_COLS);
			round(inv_rnd,  b1, b0, kp -  7 * N_COLS);
			round(inv_rnd,  b0, b1, kp -  8 * N_COLS);
			round(inv_rnd,  b1, b0, kp -  9 * N_COLS);
#if defined(LAST_DEC_ROUND_CACHE_TABLES)
			itables(t_il);
#endif	
			round(inv_lrnd, b0, b1, kp - 10 * N_COLS);
		}

#else
	
		{   aes_32t    rnd;
#if (DEC_UNROLL == PARTIAL)
			for(rnd = 0; rnd < (cx->rn >> 1) - 1; ++rnd)
			{
				kp -= N_COLS;
				round(inv_rnd, b1, b0, kp);
				kp -= N_COLS;
				round(inv_rnd, b0, b1, kp);
			}
			kp -= N_COLS;
			round(inv_rnd, b1, b0, kp);
#else
			for(rnd = 0; rnd < cx->rn - 1; ++rnd)
			{
				kp -= N_COLS;
				round(inv_rnd, b1, b0, kp);
				l_copy(b0, b1);
			}
#endif
#if defined(LAST_DEC_ROUND_CACHE_TABLES)
			itables(t_il);
#endif	
			kp -= N_COLS;
			round(inv_lrnd, b0, b1, kp);
		}
#endif

		#ifdef	_APPLE_COMMON_CRYPTO_
		if(cbcEnable) {
			if (num_blk == 1)
			{
				// We are doing the first block so we need the IV rather than the previous
				// block for CBC (there is no previous block)
				if(in_iv) {
					state_in(b1, in_iv);
				}
				else {
					state_in(b1, cx->chainBuf);
				}
			}
			else
			{
				in -= AES_BLOCK_SIZE;
				state_in(b1, in);
			}

			// Do the CBC with b1 which is either the IV or the ciphertext of 
			// the previous block.
			cbc(b0, b1);
		}
		else {
			if (num_blk != 1) {
				/* skip this the last time through */
				in -= AES_BLOCK_SIZE;
				state_in(b1, in);
			}
		}
		#endif	/* _APPLE_COMMON_CRYPTO_ */
		state_out(out, b0);
	}

	#ifdef	_APPLE_COMMON_CRYPTO_
	/* save last ciphertext block for next op's chain */
	if(cbcEnable) {
		memmove(cx->chainBuf, lastIv, AES_BLOCK_SIZE);
	}
	#endif
	
#if defined( AES_ERR_CHK )
    return aes_good;
#endif
}

#endif

#if defined(__cplusplus)
}
#endif

#endif	// defined UseGladmanAES
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/GladmanAES/aeskey.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/*
 ---------------------------------------------------------------------------
 Copyright (c) 2003, Dr Brian Gladman, Worcester, UK.   All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue Date: 26/08/2003

 This file contains the code for implementing the key schedule for AES
 (Rijndael) for block and key sizes of 16, 24, and 32 bytes. See aesopt.h
 for further details including optimisation.
*/

#include <CommonCrypto/aesopt.h>
#include "aestab.h"
#include <string.h>

/*	Produce object code iff UseGladmanAES is defined.  Otherwise, suppress
	use of this module, because some other AES implementation is being used.
*/
#if defined UseGladmanAES

#if defined(__cplusplus)
extern "C"
{
#endif

/* Initialise the key schedule from the user supplied key. The key
   length can be specified in bytes, with legal values of 16, 24
   and 32, or in bits, with legal values of 128, 192 and 256. These
   values correspond with Nk values of 4, 6 and 8 respectively.

   The following macros implement a single cycle in the key
   schedule generation process. The number of cycles needed
   for each cx->n_col and nk value is:

    nk =             4  5  6  7  8
    ------------------------------
    cx->n_col = 4   10  9  8  7  7
    cx->n_col = 5   14 11 10  9  9
    cx->n_col = 6   19 15 12 11 11
    cx->n_col = 7   21 19 16 13 14
    cx->n_col = 8   29 23 19 17 14
*/

#define ke4(k,i) \
{   k[4*(i)+4] = ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; k[4*(i)+5] = ss[1] ^= ss[0]; \
    k[4*(i)+6] = ss[2] ^= ss[1]; k[4*(i)+7] = ss[3] ^= ss[2]; \
}
#define kel4(k,i) \
{   k[4*(i)+4] = ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; k[4*(i)+5] = ss[1] ^= ss[0]; \
    k[4*(i)+6] = ss[2] ^= ss[1]; k[4*(i)+7] = ss[3] ^= ss[2]; \
}

#define ke6(k,i) \
{   k[6*(i)+ 6] = ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; k[6*(i)+ 7] = ss[1] ^= ss[0]; \
    k[6*(i)+ 8] = ss[2] ^= ss[1]; k[6*(i)+ 9] = ss[3] ^= ss[2]; \
    k[6*(i)+10] = ss[4] ^= ss[3]; k[6*(i)+11] = ss[5] ^= ss[4]; \
}
#define kel6(k,i) \
{   k[6*(i)+ 6] = ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; k[6*(i)+ 7] = ss[1] ^= ss[0]; \
    k[6*(i)+ 8] = ss[2] ^= ss[1]; k[6*(i)+ 9] = ss[3] ^= ss[2]; \
}

#define ke8(k,i) \
{   k[8*(i)+ 8] = ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; k[8*(i)+ 9] = ss[1] ^= ss[0]; \
    k[8*(i)+10] = ss[2] ^= ss[1]; k[8*(i)+11] = ss[3] ^= ss[2]; \
    k[8*(i)+12] = ss[4] ^= ls_box(ss[3],0); k[8*(i)+13] = ss[5] ^= ss[4]; \
    k[8*(i)+14] = ss[6] ^= ss[5]; k[8*(i)+15] = ss[7] ^= ss[6]; \
}
#define kel8(k,i) \
{   k[8*(i)+ 8] = ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; k[8*(i)+ 9] = ss[1] ^= ss[0]; \
    k[8*(i)+10] = ss[2] ^= ss[1]; k[8*(i)+11] = ss[3] ^= ss[2]; \
}

#if defined(ENCRYPTION_KEY_SCHEDULE)

#if defined(AES_128) || defined(AES_VAR)

aes_rval aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1])
{   aes_32t    ss[4];

    cx->ks[0] = ss[0] = word_in(key, 0);
    cx->ks[1] = ss[1] = word_in(key, 1);
    cx->ks[2] = ss[2] = word_in(key, 2);
    cx->ks[3] = ss[3] = word_in(key, 3);

#if ENC_UNROLL == NONE
    {   aes_32t i;

        for(i = 0; i < ((11 * N_COLS - 5) / 4); ++i)
            ke4(cx->ks, i);
    }
#else
    ke4(cx->ks, 0);  ke4(cx->ks, 1);
    ke4(cx->ks, 2);  ke4(cx->ks, 3);
    ke4(cx->ks, 4);  ke4(cx->ks, 5);
    ke4(cx->ks, 6);  ke4(cx->ks, 7);
    ke4(cx->ks, 8);
#endif
    kel4(cx->ks, 9);
    cx->rn = 10;
	#if CC_AES_USE_HARDWARE
	bcopy(key, cx->keyBytes, 16);
	cx->keyLength = 16;
	#endif
#if defined( AES_ERR_CHK )
    return aes_good;
#endif
}

#endif

#if defined(AES_192) || defined(AES_VAR)

aes_rval aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1])
{   aes_32t    ss[6];

    cx->ks[0] = ss[0] = word_in(key, 0);
    cx->ks[1] = ss[1] = word_in(key, 1);
    cx->ks[2] = ss[2] = word_in(key, 2);
    cx->ks[3] = ss[3] = word_in(key, 3);
    cx->ks[4] = ss[4] = word_in(key, 4);
    cx->ks[5] = ss[5] = word_in(key, 5);

#if ENC_UNROLL == NONE
    {   aes_32t i;

        for(i = 0; i < (13 * N_COLS - 7) / 6; ++i)
            ke6(cx->ks, i);
    }
#else
    ke6(cx->ks, 0);  ke6(cx->ks, 1);
    ke6(cx->ks, 2);  ke6(cx->ks, 3);
    ke6(cx->ks, 4);  ke6(cx->ks, 5);
    ke6(cx->ks, 6);
#endif
    kel6(cx->ks, 7);
    cx->rn = 12;
	#if CC_AES_USE_HARDWARE
	bcopy(key, cx->keyBytes, 24);
	cx->keyLength = 24;
	#endif
#if defined( AES_ERR_CHK )
    return aes_good;
#endif
}

#endif

#if defined(AES_256) || defined(AES_VAR)

aes_rval aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1])
{   aes_32t    ss[8];

    cx->ks[0] = ss[0] = word_in(key, 0);
    cx->ks[1] = ss[1] = word_in(key, 1);
    cx->ks[2] = ss[2] = word_in(key, 2);
    cx->ks[3] = ss[3] = word_in(key, 3);
    cx->ks[4] = ss[4] = word_in(key, 4);
    cx->ks[5] = ss[5] = word_in(key, 5);
    cx->ks[6] = ss[6] = word_in(key, 6);
    cx->ks[7] = ss[7] = word_in(key, 7);

#if ENC_UNROLL == NONE
    {   aes_32t i;

        for(i = 0; i < (15 * N_COLS - 9) / 8; ++i)
            ke8(cx->ks,  i);
    }
#else
    ke8(cx->ks, 0); ke8(cx->ks, 1);
    ke8(cx->ks, 2); ke8(cx->ks, 3);
    ke8(cx->ks, 4); ke8(cx->ks, 5);
#endif
    kel8(cx->ks, 6);
    cx->rn = 14;
	#if CC_AES_USE_HARDWARE
	bcopy(key, cx->keyBytes, 32);
	cx->keyLength = 32;
	#endif
#if defined( AES_ERR_CHK )
    return aes_good;
#endif
}

#endif

#if defined(AES_VAR)

aes_rval aes_encrypt_key(const unsigned char *key, int key_len, aes_encrypt_ctx cx[1])
{
    switch(key_len)
    {
#if defined( AES_ERR_CHK )
    case 16: case 128: return aes_encrypt_key128(key, cx);
    case 24: case 192: return aes_encrypt_key192(key, cx);
    case 32: case 256: return aes_encrypt_key256(key, cx);
    default: return aes_error;
#else
    case 16: case 128: aes_encrypt_key128(key, cx); return;
    case 24: case 192: aes_encrypt_key192(key, cx); return;
    case 32: case 256: aes_encrypt_key256(key, cx); return;
#endif
    }
}

#endif

#endif

#if defined(DECRYPTION_KEY_SCHEDULE)

#if DEC_ROUND == NO_TABLES
#define ff(x)   (x)
#else
#define ff(x)   inv_mcol(x)
#if defined( dec_imvars )
#define d_vars  dec_imvars
#endif
#endif

#if 1
#define kdf4(k,i) \
{   ss[0] = ss[0] ^ ss[2] ^ ss[1] ^ ss[3]; ss[1] = ss[1] ^ ss[3]; ss[2] = ss[2] ^ ss[3]; ss[3] = ss[3]; \
    ss[4] = ls_box(ss[(i+3) % 4], 3) ^ t_use(r,c)[i]; ss[i % 4] ^= ss[4]; \
    ss[4] ^= k[4*(i)];   k[4*(i)+4] = ff(ss[4]); ss[4] ^= k[4*(i)+1]; k[4*(i)+5] = ff(ss[4]); \
    ss[4] ^= k[4*(i)+2]; k[4*(i)+6] = ff(ss[4]); ss[4] ^= k[4*(i)+3]; k[4*(i)+7] = ff(ss[4]); \
}
#define kd4(k,i) \
{   ss[4] = ls_box(ss[(i+3) % 4], 3) ^ t_use(r,c)[i]; ss[i % 4] ^= ss[4]; ss[4] = ff(ss[4]); \
    k[4*(i)+4] = ss[4] ^= k[4*(i)]; k[4*(i)+5] = ss[4] ^= k[4*(i)+1]; \
    k[4*(i)+6] = ss[4] ^= k[4*(i)+2]; k[4*(i)+7] = ss[4] ^= k[4*(i)+3]; \
}
#define kdl4(k,i) \
{   ss[4] = ls_box(ss[(i+3) % 4], 3) ^ t_use(r,c)[i]; ss[i % 4] ^= ss[4]; \
    k[4*(i)+4] = (ss[0] ^= ss[1]) ^ ss[2] ^ ss[3]; k[4*(i)+5] = ss[1] ^ ss[3]; \
    k[4*(i)+6] = ss[0]; k[4*(i)+7] = ss[1]; \
}
#else
#define kdf4(k,i) \
{   ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; k[4*(i)+ 4] = ff(ss[0]); ss[1] ^= ss[0]; k[4*(i)+ 5] = ff(ss[1]); \
    ss[2] ^= ss[1]; k[4*(i)+ 6] = ff(ss[2]); ss[3] ^= ss[2]; k[4*(i)+ 7] = ff(ss[3]); \
}
#define kd4(k,i) \
{   ss[4] = ls_box(ss[3],3) ^ t_use(r,c)[i]; \
    ss[0] ^= ss[4]; ss[4] = ff(ss[4]); k[4*(i)+ 4] = ss[4] ^= k[4*(i)]; \
    ss[1] ^= ss[0]; k[4*(i)+ 5] = ss[4] ^= k[4*(i)+ 1]; \
    ss[2] ^= ss[1]; k[4*(i)+ 6] = ss[4] ^= k[4*(i)+ 2]; \
    ss[3] ^= ss[2]; k[4*(i)+ 7] = ss[4] ^= k[4*(i)+ 3]; \
}
#define kdl4(k,i) \
{   ss[0] ^= ls_box(ss[3],3) ^ t_use(r,c)[i]; k[4*(i)+ 4] = ss[0]; ss[1] ^= ss[0]; k[4*(i)+ 5] = ss[1]; \
    ss[2] ^= ss[1]; k[4*(i)+ 6] = ss[2]; ss[3] ^= ss[2]; k[4*(i)+ 7] = ss[3]; \
}
#endif

#define kdf6(k,i) \
{   ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; k[6*(i)+ 6] = ff(ss[0]); ss[1] ^= ss[0]; k[6*(i)+ 7] = ff(ss[1]); \
    ss[2] ^= ss[1]; k[6*(i)+ 8] = ff(ss[2]); ss[3] ^= ss[2]; k[6*(i)+ 9] = ff(ss[3]); \
    ss[4] ^= ss[3]; k[6*(i)+10] = ff(ss[4]); ss[5] ^= ss[4]; k[6*(i)+11] = ff(ss[5]); \
}
#define kd6(k,i) \
{   ss[6] = ls_box(ss[5],3) ^ t_use(r,c)[i]; \
    ss[0] ^= ss[6]; ss[6] = ff(ss[6]); k[6*(i)+ 6] = ss[6] ^= k[6*(i)]; \
    ss[1] ^= ss[0]; k[6*(i)+ 7] = ss[6] ^= k[6*(i)+ 1]; \
    ss[2] ^= ss[1]; k[6*(i)+ 8] = ss[6] ^= k[6*(i)+ 2]; \
    ss[3] ^= ss[2]; k[6*(i)+ 9] = ss[6] ^= k[6*(i)+ 3]; \
    ss[4] ^= ss[3]; k[6*(i)+10] = ss[6] ^= k[6*(i)+ 4]; \
    ss[5] ^= ss[4]; k[6*(i)+11] = ss[6] ^= k[6*(i)+ 5]; \
}
#define kdl6(k,i) \
{   ss[0] ^= ls_box(ss[5],3) ^ t_use(r,c)[i]; k[6*(i)+ 6] = ss[0]; ss[1] ^= ss[0]; k[6*(i)+ 7] = ss[1]; \
    ss[2] ^= ss[1]; k[6*(i)+ 8] = ss[2]; ss[3] ^= ss[2]; k[6*(i)+ 9] = ss[3]; \
}

#define kdf8(k,i) \
{   ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; k[8*(i)+ 8] = ff(ss[0]); ss[1] ^= ss[0]; k[8*(i)+ 9] = ff(ss[1]); \
    ss[2] ^= ss[1]; k[8*(i)+10] = ff(ss[2]); ss[3] ^= ss[2]; k[8*(i)+11] = ff(ss[3]); \
    ss[4] ^= ls_box(ss[3],0); k[8*(i)+12] = ff(ss[4]); ss[5] ^= ss[4]; k[8*(i)+13] = ff(ss[5]); \
    ss[6] ^= ss[5]; k[8*(i)+14] = ff(ss[6]); ss[7] ^= ss[6]; k[8*(i)+15] = ff(ss[7]); \
}
#define kd8(k,i) \
{   aes_32t g = ls_box(ss[7],3) ^ t_use(r,c)[i]; \
    ss[0] ^= g; g = ff(g); k[8*(i)+ 8] = g ^= k[8*(i)]; \
    ss[1] ^= ss[0]; k[8*(i)+ 9] = g ^= k[8*(i)+ 1]; \
    ss[2] ^= ss[1]; k[8*(i)+10] = g ^= k[8*(i)+ 2]; \
    ss[3] ^= ss[2]; k[8*(i)+11] = g ^= k[8*(i)+ 3]; \
    g = ls_box(ss[3],0); \
    ss[4] ^= g; g = ff(g); k[8*(i)+12] = g ^= k[8*(i)+ 4]; \
    ss[5] ^= ss[4]; k[8*(i)+13] = g ^= k[8*(i)+ 5]; \
    ss[6] ^= ss[5]; k[8*(i)+14] = g ^= k[8*(i)+ 6]; \
    ss[7] ^= ss[6]; k[8*(i)+15] = g ^= k[8*(i)+ 7]; \
}
#define kdl8(k,i) \
{   ss[0] ^= ls_box(ss[7],3) ^ t_use(r,c)[i]; k[8*(i)+ 8] = ss[0]; ss[1] ^= ss[0]; k[8*(i)+ 9] = ss[1]; \
    ss[2] ^= ss[1]; k[8*(i)+10] = ss[2]; ss[3] ^= ss[2]; k[8*(i)+11] = ss[3]; \
}

#if defined(AES_128) || defined(AES_VAR)

aes_rval aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1])
{   aes_32t    ss[5];
#if defined( d_vars )
        d_vars;
#endif
    cx->ks[0] = ss[0] = word_in(key, 0);
    cx->ks[1] = ss[1] = word_in(key, 1);
    cx->ks[2] = ss[2] = word_in(key, 2);
    cx->ks[3] = ss[3] = word_in(key, 3);

#if DEC_UNROLL == NONE
    {   aes_32t i;

        for(i = 0; i < (11 * N_COLS - 5) / 4; ++i)
            ke4(cx->ks, i);
        kel4(cx->ks, 9);
#if !(DEC_ROUND == NO_TABLES)
        for(i = N_COLS; i < 10 * N_COLS; ++i)
            cx->ks[i] = inv_mcol(cx->ks[i]);
#endif
    }
#else
    kdf4(cx->ks, 0);  kd4(cx->ks, 1);
     kd4(cx->ks, 2);  kd4(cx->ks, 3);
     kd4(cx->ks, 4);  kd4(cx->ks, 5);
     kd4(cx->ks, 6);  kd4(cx->ks, 7);
     kd4(cx->ks, 8); kdl4(cx->ks, 9);
#endif
    cx->rn = 10;
	#if CC_AES_USE_HARDWARE
	bcopy(key, cx->keyBytes, 16);
	cx->keyLength = 16;
	#endif
#if defined( AES_ERR_CHK )
    return aes_good;
#endif
}

#endif

#if defined(AES_192) || defined(AES_VAR)

aes_rval aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1])
{   aes_32t    ss[7];
#if defined( d_vars )
        d_vars;
#endif
    cx->ks[0] = ss[0] = word_in(key, 0);
    cx->ks[1] = ss[1] = word_in(key, 1);
    cx->ks[2] = ss[2] = word_in(key, 2);
    cx->ks[3] = ss[3] = word_in(key, 3);

#if DEC_UNROLL == NONE
    cx->ks[4] = ss[4] = word_in(key, 4);
    cx->ks[5] = ss[5] = word_in(key, 5);
    {   aes_32t i;

        for(i = 0; i < (13 * N_COLS - 7) / 6; ++i)
            ke6(cx->ks, i);
        kel6(cx->ks, 7);
#if !(DEC_ROUND == NO_TABLES)
        for(i = N_COLS; i < 12 * N_COLS; ++i)
            cx->ks[i] = inv_mcol(cx->ks[i]);
#endif
    }
#else
    cx->ks[4] = ff(ss[4] = word_in(key, 4));
    cx->ks[5] = ff(ss[5] = word_in(key, 5));
    kdf6(cx->ks, 0); kd6(cx->ks, 1);
    kd6(cx->ks, 2);  kd6(cx->ks, 3);
    kd6(cx->ks, 4);  kd6(cx->ks, 5);
    kd6(cx->ks, 6); kdl6(cx->ks, 7);
#endif
    cx->rn = 12;
	#if CC_AES_USE_HARDWARE
	bcopy(key, cx->keyBytes, 24);
	cx->keyLength = 24;
	#endif
#if defined( AES_ERR_CHK )
    return aes_good;
#endif
}

#endif

#if defined(AES_256) || defined(AES_VAR)

aes_rval aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1])
{   aes_32t    ss[8];
#if defined( d_vars )
        d_vars;
#endif
    cx->ks[0] = ss[0] = word_in(key, 0);
    cx->ks[1] = ss[1] = word_in(key, 1);
    cx->ks[2] = ss[2] = word_in(key, 2);
    cx->ks[3] = ss[3] = word_in(key, 3);

#if DEC_UNROLL == NONE
    cx->ks[4] = ss[4] = word_in(key, 4);
    cx->ks[5] = ss[5] = word_in(key, 5);
    cx->ks[6] = ss[6] = word_in(key, 6);
    cx->ks[7] = ss[7] = word_in(key, 7);
    {   aes_32t i;

        for(i = 0; i < (15 * N_COLS - 9) / 8; ++i)
            ke8(cx->ks,  i);
        kel8(cx->ks,  i);
#if !(DEC_ROUND == NO_TABLES)
        for(i = N_COLS; i < 14 * N_COLS; ++i)
            cx->ks[i] = inv_mcol(cx->ks[i]);

#endif
    }
#else
    cx->ks[4] = ff(ss[4] = word_in(key, 4));
    cx->ks[5] = ff(ss[5] = word_in(key, 5));
    cx->ks[6] = ff(ss[6] = word_in(key, 6));
    cx->ks[7] = ff(ss[7] = word_in(key, 7));
    kdf8(cx->ks, 0); kd8(cx->ks, 1);
    kd8(cx->ks, 2);  kd8(cx->ks, 3);
    kd8(cx->ks, 4);  kd8(cx->ks, 5);
    kdl8(cx->ks, 6);
#endif
    cx->rn = 14;
	#if CC_AES_USE_HARDWARE
	bcopy(key, cx->keyBytes, 32);
	cx->keyLength = 32;
	#endif
#if defined( AES_ERR_CHK )
    return aes_good;
#endif
}

#endif

#if defined(AES_VAR)

aes_rval aes_decrypt_key(const unsigned char *key, int key_len, aes_decrypt_ctx cx[1])
{
    switch(key_len)
    {
#if defined( AES_ERR_CHK )
    case 16: case 128: return aes_decrypt_key128(key, cx);
    case 24: case 192: return aes_decrypt_key192(key, cx);
    case 32: case 256: return aes_decrypt_key256(key, cx);
    default: return aes_error;
#else
    case 16: case 128: aes_decrypt_key128(key, cx); return;
    case 24: case 192: aes_decrypt_key192(key, cx); return;
    case 32: case 256: aes_decrypt_key256(key, cx); return;
#endif
    }
}

#endif

#endif


#if defined(__cplusplus)
}
#endif

#endif	// defined UseGladmanAES
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/GladmanAES/aestab.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*
 ---------------------------------------------------------------------------
 Copyright (c) 2003, Dr Brian Gladman, Worcester, UK.   All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue 28/01/2004

*/

#if defined(__cplusplus)
extern "C"
{
#endif

#define DO_TABLES

#include <CommonCrypto/aesopt.h>

/*	Produce object code iff UseGladmanAES is defined.  Otherwise, suppress
	use of this module, because some other AES implementation is being used.
*/
#if defined UseGladmanAES

#if defined(FIXED_TABLES)

#define sb_data(w) {\
    w(0x63), w(0x7c), w(0x77), w(0x7b), w(0xf2), w(0x6b), w(0x6f), w(0xc5),\
    w(0x30), w(0x01), w(0x67), w(0x2b), w(0xfe), w(0xd7), w(0xab), w(0x76),\
    w(0xca), w(0x82), w(0xc9), w(0x7d), w(0xfa), w(0x59), w(0x47), w(0xf0),\
    w(0xad), w(0xd4), w(0xa2), w(0xaf), w(0x9c), w(0xa4), w(0x72), w(0xc0),\
    w(0xb7), w(0xfd), w(0x93), w(0x26), w(0x36), w(0x3f), w(0xf7), w(0xcc),\
    w(0x34), w(0xa5), w(0xe5), w(0xf1), w(0x71), w(0xd8), w(0x31), w(0x15),\
    w(0x04), w(0xc7), w(0x23), w(0xc3), w(0x18), w(0x96), w(0x05), w(0x9a),\
    w(0x07), w(0x12), w(0x80), w(0xe2), w(0xeb), w(0x27), w(0xb2), w(0x75),\
    w(0x09), w(0x83), w(0x2c), w(0x1a), w(0x1b), w(0x6e), w(0x5a), w(0xa0),\
    w(0x52), w(0x3b), w(0xd6), w(0xb3), w(0x29), w(0xe3), w(0x2f), w(0x84),\
    w(0x53), w(0xd1), w(0x00), w(0xed), w(0x20), w(0xfc), w(0xb1), w(0x5b),\
    w(0x6a), w(0xcb), w(0xbe), w(0x39), w(0x4a), w(0x4c), w(0x58), w(0xcf),\
    w(0xd0), w(0xef), w(0xaa), w(0xfb), w(0x43), w(0x4d), w(0x33), w(0x85),\
    w(0x45), w(0xf9), w(0x02), w(0x7f), w(0x50), w(0x3c), w(0x9f), w(0xa8),\
    w(0x51), w(0xa3), w(0x40), w(0x8f), w(0x92), w(0x9d), w(0x38), w(0xf5),\
    w(0xbc), w(0xb6), w(0xda), w(0x21), w(0x10), w(0xff), w(0xf3), w(0xd2),\
    w(0xcd), w(0x0c), w(0x13), w(0xec), w(0x5f), w(0x97), w(0x44), w(0x17),\
    w(0xc4), w(0xa7), w(0x7e), w(0x3d), w(0x64), w(0x5d), w(0x19), w(0x73),\
    w(0x60), w(0x81), w(0x4f), w(0xdc), w(0x22), w(0x2a), w(0x90), w(0x88),\
    w(0x46), w(0xee), w(0xb8), w(0x14), w(0xde), w(0x5e), w(0x0b), w(0xdb),\
    w(0xe0), w(0x32), w(0x3a), w(0x0a), w(0x49), w(0x06), w(0x24), w(0x5c),\
    w(0xc2), w(0xd3), w(0xac), w(0x62), w(0x91), w(0x95), w(0xe4), w(0x79),\
    w(0xe7), w(0xc8), w(0x37), w(0x6d), w(0x8d), w(0xd5), w(0x4e), w(0xa9),\
    w(0x6c), w(0x56), w(0xf4), w(0xea), w(0x65), w(0x7a), w(0xae), w(0x08),\
    w(0xba), w(0x78), w(0x25), w(0x2e), w(0x1c), w(0xa6), w(0xb4), w(0xc6),\
    w(0xe8), w(0xdd), w(0x74), w(0x1f), w(0x4b), w(0xbd), w(0x8b), w(0x8a),\
    w(0x70), w(0x3e), w(0xb5), w(0x66), w(0x48), w(0x03), w(0xf6), w(0x0e),\
    w(0x61), w(0x35), w(0x57), w(0xb9), w(0x86), w(0xc1), w(0x1d), w(0x9e),\
    w(0xe1), w(0xf8), w(0x98), w(0x11), w(0x69), w(0xd9), w(0x8e), w(0x94),\
    w(0x9b), w(0x1e), w(0x87), w(0xe9), w(0xce), w(0x55), w(0x28), w(0xdf),\
    w(0x8c), w(0xa1), w(0x89), w(0x0d), w(0xbf), w(0xe6), w(0x42), w(0x68),\
    w(0x41), w(0x99), w(0x2d), w(0x0f), w(0xb0), w(0x54), w(0xbb), w(0x16) }

#define isb_data(w) {\
    w(0x52), w(0x09), w(0x6a), w(0xd5), w(0x30), w(0x36), w(0xa5), w(0x38),\
    w(0xbf), w(0x40), w(0xa3), w(0x9e), w(0x81), w(0xf3), w(0xd7), w(0xfb),\
    w(0x7c), w(0xe3), w(0x39), w(0x82), w(0x9b), w(0x2f), w(0xff), w(0x87),\
    w(0x34), w(0x8e), w(0x43), w(0x44), w(0xc4), w(0xde), w(0xe9), w(0xcb),\
    w(0x54), w(0x7b), w(0x94), w(0x32), w(0xa6), w(0xc2), w(0x23), w(0x3d),\
    w(0xee), w(0x4c), w(0x95), w(0x0b), w(0x42), w(0xfa), w(0xc3), w(0x4e),\
    w(0x08), w(0x2e), w(0xa1), w(0x66), w(0x28), w(0xd9), w(0x24), w(0xb2),\
    w(0x76), w(0x5b), w(0xa2), w(0x49), w(0x6d), w(0x8b), w(0xd1), w(0x25),\
    w(0x72), w(0xf8), w(0xf6), w(0x64), w(0x86), w(0x68), w(0x98), w(0x16),\
    w(0xd4), w(0xa4), w(0x5c), w(0xcc), w(0x5d), w(0x65), w(0xb6), w(0x92),\
    w(0x6c), w(0x70), w(0x48), w(0x50), w(0xfd), w(0xed), w(0xb9), w(0xda),\
    w(0x5e), w(0x15), w(0x46), w(0x57), w(0xa7), w(0x8d), w(0x9d), w(0x84),\
    w(0x90), w(0xd8), w(0xab), w(0x00), w(0x8c), w(0xbc), w(0xd3), w(0x0a),\
    w(0xf7), w(0xe4), w(0x58), w(0x05), w(0xb8), w(0xb3), w(0x45), w(0x06),\
    w(0xd0), w(0x2c), w(0x1e), w(0x8f), w(0xca), w(0x3f), w(0x0f), w(0x02),\
    w(0xc1), w(0xaf), w(0xbd), w(0x03), w(0x01), w(0x13), w(0x8a), w(0x6b),\
    w(0x3a), w(0x91), w(0x11), w(0x41), w(0x4f), w(0x67), w(0xdc), w(0xea),\
    w(0x97), w(0xf2), w(0xcf), w(0xce), w(0xf0), w(0xb4), w(0xe6), w(0x73),\
    w(0x96), w(0xac), w(0x74), w(0x22), w(0xe7), w(0xad), w(0x35), w(0x85),\
    w(0xe2), w(0xf9), w(0x37), w(0xe8), w(0x1c), w(0x75), w(0xdf), w(0x6e),\
    w(0x47), w(0xf1), w(0x1a), w(0x71), w(0x1d), w(0x29), w(0xc5), w(0x89),\
    w(0x6f), w(0xb7), w(0x62), w(0x0e), w(0xaa), w(0x18), w(0xbe), w(0x1b),\
    w(0xfc), w(0x56), w(0x3e), w(0x4b), w(0xc6), w(0xd2), w(0x79), w(0x20),\
    w(0x9a), w(0xdb), w(0xc0), w(0xfe), w(0x78), w(0xcd), w(0x5a), w(0xf4),\
    w(0x1f), w(0xdd), w(0xa8), w(0x33), w(0x88), w(0x07), w(0xc7), w(0x31),\
    w(0xb1), w(0x12), w(0x10), w(0x59), w(0x27), w(0x80), w(0xec), w(0x5f),\
    w(0x60), w(0x51), w(0x7f), w(0xa9), w(0x19), w(0xb5), w(0x4a), w(0x0d),\
    w(0x2d), w(0xe5), w(0x7a), w(0x9f), w(0x93), w(0xc9), w(0x9c), w(0xef),\
    w(0xa0), w(0xe0), w(0x3b), w(0x4d), w(0xae), w(0x2a), w(0xf5), w(0xb0),\
    w(0xc8), w(0xeb), w(0xbb), w(0x3c), w(0x83), w(0x53), w(0x99), w(0x61),\
    w(0x17), w(0x2b), w(0x04), w(0x7e), w(0xba), w(0x77), w(0xd6), w(0x26),\
    w(0xe1), w(0x69), w(0x14), w(0x63), w(0x55), w(0x21), w(0x0c), w(0x7d) }

#define mm_data(w) {\
    w(0x00), w(0x01), w(0x02), w(0x03), w(0x04), w(0x05), w(0x06), w(0x07),\
    w(0x08), w(0x09), w(0x0a), w(0x0b), w(0x0c), w(0x0d), w(0x0e), w(0x0f),\
    w(0x10), w(0x11), w(0x12), w(0x13), w(0x14), w(0x15), w(0x16), w(0x17),\
    w(0x18), w(0x19), w(0x1a), w(0x1b), w(0x1c), w(0x1d), w(0x1e), w(0x1f),\
    w(0x20), w(0x21), w(0x22), w(0x23), w(0x24), w(0x25), w(0x26), w(0x27),\
    w(0x28), w(0x29), w(0x2a), w(0x2b), w(0x2c), w(0x2d), w(0x2e), w(0x2f),\
    w(0x30), w(0x31), w(0x32), w(0x33), w(0x34), w(0x35), w(0x36), w(0x37),\
    w(0x38), w(0x39), w(0x3a), w(0x3b), w(0x3c), w(0x3d), w(0x3e), w(0x3f),\
    w(0x40), w(0x41), w(0x42), w(0x43), w(0x44), w(0x45), w(0x46), w(0x47),\
    w(0x48), w(0x49), w(0x4a), w(0x4b), w(0x4c), w(0x4d), w(0x4e), w(0x4f),\
    w(0x50), w(0x51), w(0x52), w(0x53), w(0x54), w(0x55), w(0x56), w(0x57),\
    w(0x58), w(0x59), w(0x5a), w(0x5b), w(0x5c), w(0x5d), w(0x5e), w(0x5f),\
    w(0x60), w(0x61), w(0x62), w(0x63), w(0x64), w(0x65), w(0x66), w(0x67),\
    w(0x68), w(0x69), w(0x6a), w(0x6b), w(0x6c), w(0x6d), w(0x6e), w(0x6f),\
    w(0x70), w(0x71), w(0x72), w(0x73), w(0x74), w(0x75), w(0x76), w(0x77),\
    w(0x78), w(0x79), w(0x7a), w(0x7b), w(0x7c), w(0x7d), w(0x7e), w(0x7f),\
    w(0x80), w(0x81), w(0x82), w(0x83), w(0x84), w(0x85), w(0x86), w(0x87),\
    w(0x88), w(0x89), w(0x8a), w(0x8b), w(0x8c), w(0x8d), w(0x8e), w(0x8f),\
    w(0x90), w(0x91), w(0x92), w(0x93), w(0x94), w(0x95), w(0x96), w(0x97),\
    w(0x98), w(0x99), w(0x9a), w(0x9b), w(0x9c), w(0x9d), w(0x9e), w(0x9f),\
    w(0xa0), w(0xa1), w(0xa2), w(0xa3), w(0xa4), w(0xa5), w(0xa6), w(0xa7),\
    w(0xa8), w(0xa9), w(0xaa), w(0xab), w(0xac), w(0xad), w(0xae), w(0xaf),\
    w(0xb0), w(0xb1), w(0xb2), w(0xb3), w(0xb4), w(0xb5), w(0xb6), w(0xb7),\
    w(0xb8), w(0xb9), w(0xba), w(0xbb), w(0xbc), w(0xbd), w(0xbe), w(0xbf),\
    w(0xc0), w(0xc1), w(0xc2), w(0xc3), w(0xc4), w(0xc5), w(0xc6), w(0xc7),\
    w(0xc8), w(0xc9), w(0xca), w(0xcb), w(0xcc), w(0xcd), w(0xce), w(0xcf),\
    w(0xd0), w(0xd1), w(0xd2), w(0xd3), w(0xd4), w(0xd5), w(0xd6), w(0xd7),\
    w(0xd8), w(0xd9), w(0xda), w(0xdb), w(0xdc), w(0xdd), w(0xde), w(0xdf),\
    w(0xe0), w(0xe1), w(0xe2), w(0xe3), w(0xe4), w(0xe5), w(0xe6), w(0xe7),\
    w(0xe8), w(0xe9), w(0xea), w(0xeb), w(0xec), w(0xed), w(0xee), w(0xef),\
    w(0xf0), w(0xf1), w(0xf2), w(0xf3), w(0xf4), w(0xf5), w(0xf6), w(0xf7),\
    w(0xf8), w(0xf9), w(0xfa), w(0xfb), w(0xfc), w(0xfd), w(0xfe), w(0xff) }

#define rc_data(w) {\
    w(0x01), w(0x02), w(0x04), w(0x08), w(0x10),w(0x20), w(0x40), w(0x80),\
    w(0x1b), w(0x36) }

#define h0(x)   (x)

#define w0(p)   bytes2word(p, 0, 0, 0)
#define w1(p)   bytes2word(0, p, 0, 0)
#define w2(p)   bytes2word(0, 0, p, 0)
#define w3(p)   bytes2word(0, 0, 0, p)

#define u0(p)   bytes2word(f2(p), p, p, f3(p))
#define u1(p)   bytes2word(f3(p), f2(p), p, p)
#define u2(p)   bytes2word(p, f3(p), f2(p), p)
#define u3(p)   bytes2word(p, p, f3(p), f2(p))

#define v0(p)   bytes2word(fe(p), f9(p), fd(p), fb(p))
#define v1(p)   bytes2word(fb(p), fe(p), f9(p), fd(p))
#define v2(p)   bytes2word(fd(p), fb(p), fe(p), f9(p))
#define v3(p)   bytes2word(f9(p), fd(p), fb(p), fe(p))

#endif

#if defined(FIXED_TABLES) || !defined(FF_TABLES)

#define f2(x)   ((x<<1) ^ (((x>>7) & 1) * WPOLY))
#define f4(x)   ((x<<2) ^ (((x>>6) & 1) * WPOLY) ^ (((x>>6) & 2) * WPOLY))
#define f8(x)   ((x<<3) ^ (((x>>5) & 1) * WPOLY) ^ (((x>>5) & 2) * WPOLY) \
                        ^ (((x>>5) & 4) * WPOLY))
#define f3(x)   (f2(x) ^ x)
#define f9(x)   (f8(x) ^ x)
#define fb(x)   (f8(x) ^ f2(x) ^ x)
#define fd(x)   (f8(x) ^ f4(x) ^ x)
#define fe(x)   (f8(x) ^ f4(x) ^ f2(x))

#else

#define f2(x) ((x) ? pow[log[x] + 0x19] : 0)
#define f3(x) ((x) ? pow[log[x] + 0x01] : 0)
#define f9(x) ((x) ? pow[log[x] + 0xc7] : 0)
#define fb(x) ((x) ? pow[log[x] + 0x68] : 0)
#define fd(x) ((x) ? pow[log[x] + 0xee] : 0)
#define fe(x) ((x) ? pow[log[x] + 0xdf] : 0)
#define fi(x) ((x) ? pow[ 255 - log[x]] : 0)

#endif

#include "aestab.h"

#if defined(FIXED_TABLES)

/* implemented in case of wrong call for fixed tables */

void gen_tabs(void)
{
}

#else   /* dynamic table generation */

#if !defined(FF_TABLES)

/*  Generate the tables for the dynamic table option

    It will generally be sensible to use tables to compute finite
    field multiplies and inverses but where memory is scarse this
    code might sometimes be better. But it only has effect during
    initialisation so its pretty unimportant in overall terms.
*/

/*  return 2 ^ (n - 1) where n is the bit number of the highest bit
    set in x with x in the range 1 < x < 0x00000200.   This form is
    used so that locals within fi can be bytes rather than words
*/

static aes_08t hibit(const aes_32t x)
{   aes_08t r = (aes_08t)((x >> 1) | (x >> 2));

    r |= (r >> 2);
    r |= (r >> 4);
    return (r + 1) >> 1;
}

/* return the inverse of the finite field element x */

static aes_08t fi(const aes_08t x)
{   aes_08t p1 = x, p2 = BPOLY, n1 = hibit(x), n2 = 0x80, v1 = 1, v2 = 0;

    if(x < 2) return x;

    for(;;)
    {
        if(!n1) return v1;

        while(n2 >= n1)
        {
            n2 /= n1; p2 ^= p1 * n2; v2 ^= v1 * n2; n2 = hibit(p2);
        }

        if(!n2) return v2;

        while(n1 >= n2)
        {
            n1 /= n2; p1 ^= p2 * n1; v1 ^= v2 * n1; n1 = hibit(p1);
        }
    }
}

#endif

/* The forward and inverse affine transformations used in the S-box */

#define fwd_affine(x) \
    (w = (aes_32t)x, w ^= (w<<1)^(w<<2)^(w<<3)^(w<<4), 0x63^(aes_08t)(w^(w>>8)))

#define inv_affine(x) \
    (w = (aes_32t)x, w = (w<<1)^(w<<3)^(w<<6), 0x05^(aes_08t)(w^(w>>8)))

static int init = 0;

void gen_tabs(void)
{   aes_32t  i, w;

#if defined(FF_TABLES)

    aes_08t  pow[512], log[256];

    if(init) return;
    /*  log and power tables for GF(2^8) finite field with
        WPOLY as modular polynomial - the simplest primitive
        root is 0x03, used here to generate the tables
    */

    i = 0; w = 1;
    do
    {
        pow[i] = (aes_08t)w;
        pow[i + 255] = (aes_08t)w;
        log[w] = (aes_08t)i++;
        w ^=  (w << 1) ^ (w & 0x80 ? WPOLY : 0);
    }
    while (w != 1);

#else
    if(init) return;
#endif

    for(i = 0, w = 1; i < RC_LENGTH; ++i)
    {
        t_set(r,c)[i] = bytes2word(w, 0, 0, 0);
        w = f2(w);
    }

    for(i = 0; i < 256; ++i)
    {   aes_08t    b;

        b = fwd_affine(fi((aes_08t)i));
        w = bytes2word(f2(b), b, b, f3(b));

#if defined( SBX_SET )
        t_set(s,box)[i] = b;
#endif

#if defined( FT1_SET )                 /* tables for a normal encryption round */
        t_set(f,n)[i] = w;
#endif
#if defined( FT4_SET )
        t_set(f,n)[0][i] = w;
        t_set(f,n)[1][i] = upr(w,1);
        t_set(f,n)[2][i] = upr(w,2);
        t_set(f,n)[3][i] = upr(w,3);
#endif
        w = bytes2word(b, 0, 0, 0);

#if defined( FL1_SET )                 /* tables for last encryption round (may also   */
        t_set(f,l)[i] = w;        /* be used in the key schedule)                 */
#endif
#if defined( FL4_SET )
        t_set(f,l)[0][i] = w;
        t_set(f,l)[1][i] = upr(w,1);
        t_set(f,l)[2][i] = upr(w,2);
        t_set(f,l)[3][i] = upr(w,3);
#endif

#if defined( LS1_SET )                 /* table for key schedule if t_set(f,l) above is    */
        t_set(l,s)[i] = w;      /* not of the required form                     */
#endif
#if defined( LS4_SET )
        t_set(l,s)[0][i] = w;
        t_set(l,s)[1][i] = upr(w,1);
        t_set(l,s)[2][i] = upr(w,2);
        t_set(l,s)[3][i] = upr(w,3);
#endif

        b = fi(inv_affine((aes_08t)i));
        w = bytes2word(fe(b), f9(b), fd(b), fb(b));

#if defined( IM1_SET )                 /* tables for the inverse mix column operation  */
        t_set(i,m)[b] = w;
#endif
#if defined( IM4_SET )
        t_set(i,m)[0][b] = w;
        t_set(i,m)[1][b] = upr(w,1);
        t_set(i,m)[2][b] = upr(w,2);
        t_set(i,m)[3][b] = upr(w,3);
#endif

#if defined( ISB_SET )
        t_set(i,box)[i] = b;
#endif
#if defined( IT1_SET )                 /* tables for a normal decryption round */
        t_set(i,n)[i] = w;
#endif
#if defined( IT4_SET )
        t_set(i,n)[0][i] = w;
        t_set(i,n)[1][i] = upr(w,1);
        t_set(i,n)[2][i] = upr(w,2);
        t_set(i,n)[3][i] = upr(w,3);
#endif
        w = bytes2word(b, 0, 0, 0);
#if defined( IL1_SET )                 /* tables for last decryption round */
        t_set(i,l)[i] = w;
#endif
#if defined( IL4_SET )
        t_set(i,l)[0][i] = w;
        t_set(i,l)[1][i] = upr(w,1);
        t_set(i,l)[2][i] = upr(w,2);
        t_set(i,l)[3][i] = upr(w,3);
#endif
    }
    init = 1;
}

#endif

#endif	// defined UseGladmanAES

#if defined(__cplusplus)
}
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/GladmanAES/aestab.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/*
 ---------------------------------------------------------------------------
 Copyright (c) 2003, Dr Brian Gladman, Worcester, UK.   All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue 28/01/2004

 This file contains the code for declaring the tables needed to implement
 AES. The file aesopt.h is assumed to be included before this header file.
 If there are no global variables, the definitions here can be used to put
 the AES tables in a structure so that a pointer can then be added to the
 AES context to pass them to the AES routines that need them.   If this
 facility is used, the calling program has to ensure that this pointer is
 managed appropriately.  In particular, the value of the t_dec(in,it) item
 in the table structure must be set to zero in order to ensure that the
 tables are initialised. In practice the three code sequences in aeskey.c
 that control the calls to gen_tabs() and the gen_tabs() routine itself will
 have to be changed for a specific implementation. If global variables are
 available it will generally be preferable to use them with the precomputed
 FIXED_TABLES option that uses static global tables.

 The following defines can be used to control the way the tables
 are defined, initialised and used in embedded environments that
 require special features for these purposes

    the 't_dec' construction is used to declare fixed table arrays
    the 't_set' construction is used to set fixed table values
    the 't_use' construction is used to access fixed table values

    256 byte tables:

        t_xxx(s,box)    => forward S box
        t_xxx(i,box)    => inverse S box

    256 32-bit word OR 4 x 256 32-bit word tables:

        t_xxx(f,n)      => forward normal round
        t_xxx(f,l)      => forward last round
        t_xxx(i,n)      => inverse normal round
        t_xxx(i,l)      => inverse last round
        t_xxx(l,s)      => key schedule table
        t_xxx(i,m)      => key schedule table

    Other variables and tables:

        t_xxx(r,c)      => the rcon table
*/

#if !defined( _CC_AESTAB_H )
#define _CC_AESTAB_H

#define t_dec(m,n) t_##m##n
#define t_set(m,n) t_##m##n
#define t_use(m,n) t_##m##n

#if defined(FIXED_TABLES)
#define Const const
#else
#define Const
#endif

#if defined(DO_TABLES)
#define Extern
#else
#define Extern extern
#endif

#if defined(_MSC_VER) && defined(TABLE_ALIGN)
#define Align __declspec(align(TABLE_ALIGN))
#else
#define Align
#endif

#if defined(__cplusplus)
extern "C"
{
#endif

#if defined(DO_TABLES) && defined(FIXED_TABLES)
#define d_1(t,n,b,e)       Align Const t n[256]    =   b(e)
#define d_4(t,n,b,e,f,g,h) Align Const t n[4][256] = { b(e), b(f), b(g), b(h) }
Extern Align Const aes_32t t_dec(r,c)[RC_LENGTH] = rc_data(w0);
#else
#define d_1(t,n,b,e)       Extern Align Const t n[256]
#define d_4(t,n,b,e,f,g,h) Extern Align Const t n[4][256]
Extern Align Const aes_32t t_dec(r,c)[RC_LENGTH];
#endif

#if defined( SBX_SET )
    d_1(aes_08t, t_dec(s,box), sb_data, h0);
#endif
#if defined( ISB_SET )
    d_1(aes_08t, t_dec(i,box), isb_data, h0);
#endif

#if defined( FT1_SET )
    d_1(aes_32t, t_dec(f,n), sb_data, u0);
#endif
#if defined( FT4_SET )
    d_4(aes_32t, t_dec(f,n), sb_data, u0, u1, u2, u3);
#endif

#if defined( FL1_SET )
    d_1(aes_32t, t_dec(f,l), sb_data, w0);
#endif
#if defined( FL4_SET )
    d_4(aes_32t, t_dec(f,l), sb_data, w0, w1, w2, w3);
#endif

#if defined( IT1_SET )
    d_1(aes_32t, t_dec(i,n), isb_data, v0);
#endif
#if defined( IT4_SET )
    d_4(aes_32t, t_dec(i,n), isb_data, v0, v1, v2, v3);
#endif

#if defined( IL1_SET )
    d_1(aes_32t, t_dec(i,l), isb_data, w0);
#endif
#if defined( IL4_SET )
    d_4(aes_32t, t_dec(i,l), isb_data, w0, w1, w2, w3);
#endif

#if defined( LS1_SET )
#if defined( FL1_SET )
#undef  LS1_SET
#else
    d_1(aes_32t, t_dec(l,s), sb_data, w0);
#endif
#endif

#if defined( LS4_SET )
#if defined( FL4_SET )
#undef  LS4_SET
#else
    d_4(aes_32t, t_dec(l,s), sb_data, w0, w1, w2, w3);
#endif
#endif

#if defined( IM1_SET )
    d_1(aes_32t, t_dec(i,m), mm_data, v0);
#endif
#if defined( IM4_SET )
    d_4(aes_32t, t_dec(i,m), mm_data, v0, v1, v2, v3);
#endif

#if defined(__cplusplus)
}
#endif

#endif	/* _CC_AESTAB_H */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































































Deleted Source/GladmanAES/ccNewGladman.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 * ccNewGladman.c - shim between Gladman AES and CommonEncryption.
 *
 * Created 3/30/06 by Doug Mitchell. 
 */

#include <CommonCrypto/aesopt.h>

#if CC_AES_USE_HARDWARE
//Need IOKitLib.h only for IOAESTypes.h
#include <IOKit/IOKitLib.h>
#include <Kernel/IOKit/crypto/IOAESTypes.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <pthread.h>
#endif

/*	Produce object code iff UseGladmanAES is defined.  Otherwise, suppress
	use of this module, because some other AES implementation is being used.
*/
#if defined UseGladmanAES

#ifdef	_APPLE_COMMON_CRYPTO_

#include <strings.h>

int aes_cc_set_key(
	aes_cc_ctx *cx, 
	const void *rawKey, 
	aes_32t keyLength,
	int forEncrypt)
{
	if(forEncrypt) {
		switch(keyLength) {
			case 16: 
				aes_encrypt_key128((const unsigned char *)rawKey, &cx->encrypt);
				break;
			case 24: 
				aes_encrypt_key192((const unsigned char *)rawKey, &cx->encrypt);
				break;
			case 32: 
				aes_encrypt_key256((const unsigned char *)rawKey, &cx->encrypt);
				break;
			default:
				return -1;
		}
		cx->encrypt.cbcEnable = 0;
	}
	else {
		switch(keyLength) {
			case 16: 
				aes_decrypt_key128((const unsigned char *)rawKey, &cx->decrypt);
				break;
			case 24: 
				aes_decrypt_key192((const unsigned char *)rawKey, &cx->decrypt);
				break;
			case 32: 
				aes_decrypt_key256((const unsigned char *)rawKey, &cx->decrypt);
				break;
			default:
				return -1;
		}
		cx->decrypt.cbcEnable = 0;
	}
	return 0;
}

void aes_cc_set_iv(aes_cc_ctx *cx, int forEncrypt, const void *iv)
{
	if(forEncrypt) {
		if(iv == NULL) {
			cx->encrypt.cbcEnable = 0;
		}
		else {
			memmove(cx->encrypt.chainBuf, iv, AES_BLOCK_SIZE);
			cx->encrypt.cbcEnable = 1;
		}
	}
	else {
		if(iv == NULL) {
			cx->decrypt.cbcEnable = 0;
		}
		else {
			memmove(cx->decrypt.chainBuf, iv, AES_BLOCK_SIZE);
			cx->decrypt.cbcEnable = 1;
		}
	}
}

#ifndef	NULL
#define NULL ((void *)0)
#endif

#if CC_AES_USE_HARDWARE
#define CC_AES_USE_HARDWARE_THRESHOLD	(1024 / AES_BLOCK_SIZE) //In Blocks.
static int cc_aes_device = -1;
static pthread_once_t cc_aes_connect_once = PTHREAD_ONCE_INIT;
static aes_32t cc_aes_hardware_quantum = ((256*4096) / AES_BLOCK_SIZE); //In Blocks. Will be set to what hardware returns;

static void cc_aes_connect(void) 
{
	struct IOAESAcceleratorInfo aesInfo;
	
	cc_aes_device = open("/dev/aes_0", O_RDWR, 0);
	if(cc_aes_device < 0)
		return;
	if(ioctl(cc_aes_device, IOAES_GET_INFO, &aesInfo) != -1) {
		cc_aes_hardware_quantum = aesInfo.maxBytesPerCall / AES_BLOCK_SIZE;
	}
}

static aes_32t aes_cc_use_hardware(IOAESOperation operation, int keyLength, UInt8 *key, UInt8 *iv, UInt8* plainText, UInt8 *cipherText, aes_32t numBlocks)
{
	struct IOAESAcceleratorRequest aesRequest;
	aes_32t quantum = cc_aes_hardware_quantum;
	UInt8 *pt = plainText;
	UInt8 *ct = cipherText;
	aes_32t blocks = numBlocks;
	
	aesRequest.operation = operation;
	bcopy(iv, aesRequest.iv.ivBytes, AES_BLOCK_SIZE);
	aesRequest.keyData.key.keyLength = (keyLength << 3); //Hardware needs it in bits.
	bcopy(key, aesRequest.keyData.key.keyBytes, keyLength);

	while (blocks) {
		quantum = ((blocks < cc_aes_hardware_quantum) ? blocks : cc_aes_hardware_quantum);
		aesRequest.plainText = pt;
		aesRequest.cipherText = ct;
		aesRequest.textLength = quantum * AES_BLOCK_SIZE; //The hardware needs textLength in bytes.
		
		if(ioctl(cc_aes_device, IOAES_ENCRYPT_DECRYPT, &aesRequest) == -1) {
			break;
		}
		blocks -= quantum;
		pt += (quantum*AES_BLOCK_SIZE);
		ct += (quantum*AES_BLOCK_SIZE);
	}
	return (numBlocks - blocks);	
} 
#endif

void aes_cc_encrypt(aes_cc_ctx *cx, const void *blocksIn, aes_32t numBlocks, void *blocksOut)
{
	#if CC_AES_USE_HARDWARE
	if(numBlocks > CC_AES_USE_HARDWARE_THRESHOLD && !pthread_once(&cc_aes_connect_once, cc_aes_connect) && cc_aes_device >= 0) {
		aes_encrypt_ctx *cx_encrypt = &cx->encrypt;
		UInt8 *key = cx_encrypt->keyBytes;
		int keyLength = cx_encrypt->keyLength;
		UInt8 *iv = cx_encrypt->chainBuf;
		aes_32t blocks_encrypted = 0;

		blocks_encrypted = aes_cc_use_hardware(IOAESOperationEncrypt, keyLength, key, iv, (UInt8 *)blocksIn, (UInt8 *)blocksOut, numBlocks);
		if(blocks_encrypted == numBlocks) {	// Successfully completed using hardware.
			return;
		}
		//Something went wrong trying to use hardware.. fall through and use the software to do the job.
		blocksIn = (UInt8 *)blocksIn + (blocks_encrypted * AES_BLOCK_SIZE);
		blocksOut = (UInt8 *)blocksOut + (blocks_encrypted * AES_BLOCK_SIZE);
		numBlocks -= blocks_encrypted;
	}
	#endif
	aes_encrypt_cbc((const unsigned char *)blocksIn, 
		NULL,	/* IV - we set via aes_cc_set_iv */
		(unsigned)numBlocks, (unsigned char *)blocksOut, &cx->encrypt);
}

void aes_cc_decrypt(aes_cc_ctx *cx, const void *blocksIn, aes_32t numBlocks,
	void *blocksOut)
{
	#if CC_AES_USE_HARDWARE
	if(numBlocks > CC_AES_USE_HARDWARE_THRESHOLD && !pthread_once(&cc_aes_connect_once, cc_aes_connect) && cc_aes_device >= 0) {
		aes_decrypt_ctx *cx_decrypt = &cx->decrypt;
		UInt8 *key = cx_decrypt->keyBytes;
		int keyLength = cx_decrypt->keyLength;
		UInt8 *iv = cx_decrypt->chainBuf;
		aes_32t blocks_decrypted = 0;

		blocks_decrypted = aes_cc_use_hardware(IOAESOperationDecrypt, keyLength, key, iv, (UInt8 *)blocksOut, (UInt8 *)blocksIn, numBlocks);
		if(blocks_decrypted == numBlocks) {	// Successfully completed using hardware.
			return 1;
		}
		//Something went wrong trying to use hardware.. fall through and use the software to do the job.
		blocksIn = (UInt8 *)blocksIn + (blocks_decrypted * AES_BLOCK_SIZE);
		blocksOut = (UInt8 *)blocksOut + (blocks_decrypted * AES_BLOCK_SIZE);
		numBlocks -= blocks_decrypted;
	}
	#endif
	aes_decrypt_cbc((const unsigned char *)blocksIn,
		NULL,	/* IV - we set via aes_cc_set_iv */
		(unsigned)numBlocks, (unsigned char *)blocksOut, &cx->decrypt);
}

#endif	/* _APPLE_COMMON_CRYPTO_ */

#endif	// defined UseGladmanAES
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































































































































































































































































Deleted Source/RC2/ccRC2.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include "rc2.h"
#include "ccRC2.h"
#include <sys/types.h>

int rc2_cc_set_key(
	RC2_Schedule *cx, 
	const void *rawKey, 
	size_t keyLength)
{
	rc2_keyschedule(cx, rawKey, keyLength, keyLength*8);
	return 0;
}

void rc2_cc_encrypt(RC2_Schedule *cx, const void *blockIn, void *blockOut)
{
	rc2_encrypt(cx, (const unsigned char *)blockIn, (unsigned char *)blockOut);
}

void rc2_cc_decrypt(RC2_Schedule *cx, const void *blockIn, void *blockOut)
{
	rc2_decrypt(cx, (unsigned char *)blockOut, (const unsigned char *)blockIn);
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/RC2/rc2.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/**********************************************************************\ 
* To commemorate the 1996 RSA Data Security Conference, the following  * 
* code is released into the public domain by its author.  Prost!       * 
*                                                                      * 
* This cipher uses 16-bit words and little-endian byte ordering.       * 
* I wonder which processor it was optimized for?                       * 
*                                                                      * 
* Thanks to CodeView, SoftIce, and D86 for helping bring this code to  * 
* the public.                                                          * 
\**********************************************************************/ 
#include <string.h> 
#include <assert.h> 

#include "rc2.h"

/**********************************************************************\ 
* Expand a variable-length user key (between 1 and 128 bytes) to a     * 
* 64-short working rc2 key, of at most "bits" effective key bits.      * 
* The effective key bits parameter looks like an export control hack.  * 
* For normal use, it should always be set to 1024.  For convenience,   * 
* zero is accepted as an alias for 1024.                               * 
\**********************************************************************/ 
void rc2_keyschedule( RC2_Schedule *key_schedule, 
                      const unsigned char *key, 
                      unsigned len, 
                      unsigned bits ) 
        { 
        unsigned char x; 
        unsigned i; 
        /* 256-entry permutation table, probably derived somehow from pi */ 
        static const unsigned char permute[256] = { 
            217,120,249,196, 25,221,181,237, 40,233,253,121, 74,160,216,157, 
            198,126, 55,131, 43,118, 83,142, 98, 76,100,136, 68,139,251,162, 
             23,154, 89,245,135,179, 79, 19, 97, 69,109,141,  9,129,125, 50, 
            189,143, 64,235,134,183,123, 11,240,149, 33, 34, 92,107, 78,130, 
             84,214,101,147,206, 96,178, 28,115, 86,192, 20,167,140,241,220, 
             18,117,202, 31, 59,190,228,209, 66, 61,212, 48,163, 60,182, 38, 
            111,191, 14,218, 70,105,  7, 87, 39,242, 29,155,188,148, 67,  3, 
            248, 17,199,246,144,239, 62,231,  6,195,213, 47,200,102, 30,215, 
              8,232,234,222,128, 82,238,247,132,170,114,172, 53, 77,106, 42, 
            150, 26,210,113, 90, 21, 73,116, 75,159,208, 94,  4, 24,164,236, 
            194,224, 65,110, 15, 81,203,204, 36,145,175, 80,161,244,112, 57, 
            153,124, 58,133, 35,184,180,122,252,  2, 54, 91, 37, 85,151, 49, 
             45, 93,250,152,227,138,146,174,  5,223, 41, 16,103,108,186,201, 
            211,  0,230,207,225,158,168, 44, 99, 22,  1, 63, 88,226,137,169, 
             13, 56, 52, 27,171, 51,255,176,187, 72, 12, 95,185,177,205, 46, 
            197,243,219, 71,229,165,156,119, 10,166, 32,104,254,127,193,173 
        }; 
        assert(len > 0 && len <= 128); 
        assert(bits <= 1024); 
        if (!bits) 
                bits = 1024; 
        memcpy(&key_schedule->xkey, key, len); 
        /* Phase 1: Expand input key to 128 bytes */ 
        if (len < 128) { 
                i = 0; 
                x = ((unsigned char *)key_schedule->xkey)[len-1]; 
                do { 
                        x = permute[(x + ((unsigned char *)key_schedule->xkey)[i++]) & 255]; 
                        ((unsigned char *)key_schedule->xkey)[len++] = x; 
                } while (len < 128); 
        } 
        /* Phase 2 - reduce effective key size to "bits" */ 
        len = (bits+7) >> 3; 
        i = 128-len; 
        x = permute[((unsigned char *)key_schedule->xkey)[i] & (255 >> (7 & -bits))]; 
        ((unsigned char *)key_schedule->xkey)[i] = x; 
        while (i--) { 
                x = permute[ x ^ ((unsigned char *)key_schedule->xkey)[i+len] ]; 
                ((unsigned char *)key_schedule->xkey)[i] = x; 
        } 
        /* Phase 3 - copy to xkey in little-endian order */ 
        i = 63; 
        do { 
                key_schedule->xkey[i] =  ((unsigned char *)key_schedule->xkey)[2*i] + 
                          (((unsigned char *)key_schedule->xkey)[2*i+1] << 8); 
        } while (i--); 
        } 
/**********************************************************************\ 
* Encrypt an 8-byte block of plaintext using the given key.            * 
\**********************************************************************/ 
void rc2_encrypt( const RC2_Schedule *key_schedule, 
                  const unsigned char *plain, 
                  unsigned char *cipher ) 
        { 
        unsigned x76, x54, x32, x10, i; 
        x76 = (plain[7] << 8) + plain[6]; 
        x54 = (plain[5] << 8) + plain[4]; 
        x32 = (plain[3] << 8) + plain[2]; 
        x10 = (plain[1] << 8) + plain[0]; 
        for (i = 0; i < 16; i++) { 
                x10 += (x32 & ~x76) + (x54 & x76) + key_schedule->xkey[4*i+0]; 
                x10 = (x10 << 1) + (x10 >> 15 & 1); 
                x32 += (x54 & ~x10) + (x76 & x10) + key_schedule->xkey[4*i+1]; 
                x32 = (x32 << 2) + (x32 >> 14 & 3); 
                x54 += (x76 & ~x32) + (x10 & x32) + key_schedule->xkey[4*i+2]; 
                x54 = (x54 << 3) + (x54 >> 13 & 7); 
                x76 += (x10 & ~x54) + (x32 & x54) + key_schedule->xkey[4*i+3]; 
                x76 = (x76 << 5) + (x76 >> 11 & 31); 
                if (i == 4 || i == 10) { 
                        x10 += key_schedule->xkey[x76 & 63]; 
                        x32 += key_schedule->xkey[x10 & 63]; 
                        x54 += key_schedule->xkey[x32 & 63]; 
                        x76 += key_schedule->xkey[x54 & 63]; 
                } 
        } 
        cipher[0] = (unsigned char)x10; 
        cipher[1] = (unsigned char)(x10 >> 8); 
        cipher[2] = (unsigned char)x32; 
        cipher[3] = (unsigned char)(x32 >> 8); 
        cipher[4] = (unsigned char)x54; 
        cipher[5] = (unsigned char)(x54 >> 8); 
        cipher[6] = (unsigned char)x76; 
        cipher[7] = (unsigned char)(x76 >> 8); 
        } 
/**********************************************************************\ 
* Decrypt an 8-byte block of ciphertext using the given key.           * 
\**********************************************************************/ 
void rc2_decrypt( const RC2_Schedule *key_schedule, 
                  unsigned char *plain, 
                  const unsigned char *cipher ) 
        { 
        unsigned x76, x54, x32, x10, i; 
        x76 = (cipher[7] << 8) + cipher[6]; 
        x54 = (cipher[5] << 8) + cipher[4]; 
        x32 = (cipher[3] << 8) + cipher[2]; 
        x10 = (cipher[1] << 8) + cipher[0]; 
        i = 15; 
        do { 
                x76 &= 65535; 
                x76 = (x76 << 11) + (x76 >> 5); 
                x76 -= (x10 & ~x54) + (x32 & x54) + key_schedule->xkey[4*i+3]; 
                x54 &= 65535; 
                x54 = (x54 << 13) + (x54 >> 3); 
                x54 -= (x76 & ~x32) + (x10 & x32) + key_schedule->xkey[4*i+2]; 
                x32 &= 65535; 
                x32 = (x32 << 14) + (x32 >> 2); 
                x32 -= (x54 & ~x10) + (x76 & x10) + key_schedule->xkey[4*i+1]; 
                x10 &= 65535; 
                x10 = (x10 << 15) + (x10 >> 1); 
                x10 -= (x32 & ~x76) + (x54 & x76) + key_schedule->xkey[4*i+0]; 
                if (i == 5 || i == 11) { 
                        x76 -= key_schedule->xkey[x54 & 63]; 
                        x54 -= key_schedule->xkey[x32 & 63]; 
                        x32 -= key_schedule->xkey[x10 & 63]; 
                        x10 -= key_schedule->xkey[x76 & 63]; 
                } 
        } while (i--); 
        plain[0] = (unsigned char)x10; 
        plain[1] = (unsigned char)(x10 >> 8); 
        plain[2] = (unsigned char)x32; 
        plain[3] = (unsigned char)(x32 >> 8); 
        plain[4] = (unsigned char)x54; 
        plain[5] = (unsigned char)(x54 >> 8); 
        plain[6] = (unsigned char)x76; 
        plain[7] = (unsigned char)(x76 >> 8); 
        } 

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































































































Deleted Source/ccOpenssl/des.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/* crypto/des/des.h */
/* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#ifndef HEADER_NEW_DES_H
#define HEADER_NEW_DES_H

#ifdef OPENSSL_NO_DES
#error DES is disabled.
#endif

#include <CommonCrypto/CommonCryptoPriv.h>
#include <CommonCrypto/opensslDES.h>
#include <ccOpenssl/opensslconf.h> 
#include <ccOpenssl/e_os2.h>	/* OPENSSL_EXTERN */

#ifdef	_APPLE_COMMON_CRYPTO_
/* avoid symbol collision with libSystem & libcrypto */
#define DES_encrypt1			CC_DES_encrypt1
#define DES_set_key_unchecked	CC_DES_set_key_unchecked
#endif	/* _APPLE_COMMON_CRYPTO_ */

#ifdef OPENSSL_BUILD_SHLIBCRYPTO
# undef OPENSSL_EXTERN
# define OPENSSL_EXTERN OPENSSL_EXPORT
#endif

#ifdef  __cplusplus
extern "C" {
#endif

#ifndef OPENSSL_DISABLE_OLD_DES_SUPPORT
# ifndef OPENSSL_ENABLE_OLD_DES_SUPPORT
#  define OPENSSL_ENABLE_OLD_DES_SUPPORT
# endif
#endif

#ifdef OPENSSL_ENABLE_OLD_DES_SUPPORT
# include <openssl/des_old.h>
#endif

#define DES_KEY_SZ 	(sizeof(DES_cblock))
#define DES_SCHEDULE_SZ (sizeof(DES_key_schedule))

#define DES_ENCRYPT	1
#define DES_DECRYPT	0

#define DES_CBC_MODE	0
#define DES_PCBC_MODE	1

#define DES_ecb2_encrypt(i,o,k1,k2,e) \
	DES_ecb3_encrypt((i),(o),(k1),(k2),(k1),(e))

#define DES_ede2_cbc_encrypt(i,o,l,k1,k2,iv,e) \
	DES_ede3_cbc_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(e))

#define DES_ede2_cfb64_encrypt(i,o,l,k1,k2,iv,n,e) \
	DES_ede3_cfb64_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(n),(e))

#define DES_ede2_ofb64_encrypt(i,o,l,k1,k2,iv,n) \
	DES_ede3_ofb64_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(n))

OPENSSL_DECLARE_GLOBAL(int,DES_check_key);	/* defaults to false */
#define DES_check_key OPENSSL_GLOBAL_REF(DES_check_key)
OPENSSL_DECLARE_GLOBAL(int,DES_rw_mode);	/* defaults to DES_PCBC_MODE */
#define DES_rw_mode OPENSSL_GLOBAL_REF(DES_rw_mode)

#ifndef	_APPLE_COMMON_CRYPTO_
const char *DES_options(void);
void DES_ecb3_encrypt(const_DES_cblock *input, DES_cblock *output,
		      DES_key_schedule *ks1,DES_key_schedule *ks2,
		      DES_key_schedule *ks3, int enc);
DES_LONG DES_cbc_cksum(const unsigned char *input,DES_cblock *output,
		       long length,DES_key_schedule *schedule,
		       const_DES_cblock *ivec);
/* DES_cbc_encrypt does not update the IV!  Use DES_ncbc_encrypt instead. */
void DES_cbc_encrypt(const unsigned char *input,unsigned char *output,
		     long length,DES_key_schedule *schedule,DES_cblock *ivec,
		     int enc);
void DES_ncbc_encrypt(const unsigned char *input,unsigned char *output,
		      long length,DES_key_schedule *schedule,DES_cblock *ivec,
		      int enc);
void DES_xcbc_encrypt(const unsigned char *input,unsigned char *output,
		      long length,DES_key_schedule *schedule,DES_cblock *ivec,
		      const_DES_cblock *inw,const_DES_cblock *outw,int enc);
void DES_cfb_encrypt(const unsigned char *in,unsigned char *out,int numbits,
		     long length,DES_key_schedule *schedule,DES_cblock *ivec,
		     int enc);
void DES_ecb_encrypt(const_DES_cblock *input,DES_cblock *output,
		     DES_key_schedule *ks,int enc);
#endif	/* _APPLE_COMMON_CRYPTO_ */

/* 	This is the DES encryption function that gets called by just about
	every other DES routine in the library.  You should not use this
	function except to implement 'modes' of DES.  I say this because the
	functions that call this routine do the conversion from 'char *' to
	long, and this needs to be done to make sure 'non-aligned' memory
	access do not occur.  The characters are loaded 'little endian'.
	Data is a pointer to 2 unsigned long's and ks is the
	DES_key_schedule to use.  enc, is non zero specifies encryption,
	zero if decryption. */
void DES_encrypt1(DES_LONG *data,DES_key_schedule *ks, int enc);

#ifndef	_APPLE_COMMON_CRYPTO_
/* 	This functions is the same as DES_encrypt1() except that the DES
	initial permutation (IP) and final permutation (FP) have been left
	out.  As for DES_encrypt1(), you should not use this function.
	It is used by the routines in the library that implement triple DES.
	IP() DES_encrypt2() DES_encrypt2() DES_encrypt2() FP() is the same
	as DES_encrypt1() DES_encrypt1() DES_encrypt1() except faster :-). */
void DES_encrypt2(DES_LONG *data,DES_key_schedule *ks, int enc);

void DES_encrypt3(DES_LONG *data, DES_key_schedule *ks1,
		  DES_key_schedule *ks2, DES_key_schedule *ks3);
void DES_decrypt3(DES_LONG *data, DES_key_schedule *ks1,
		  DES_key_schedule *ks2, DES_key_schedule *ks3);
void DES_ede3_cbc_encrypt(const unsigned char *input,unsigned char *output, 
			  long length,
			  DES_key_schedule *ks1,DES_key_schedule *ks2,
			  DES_key_schedule *ks3,DES_cblock *ivec,int enc);
void DES_ede3_cbcm_encrypt(const unsigned char *in,unsigned char *out,
			   long length,
			   DES_key_schedule *ks1,DES_key_schedule *ks2,
			   DES_key_schedule *ks3,
			   DES_cblock *ivec1,DES_cblock *ivec2,
			   int enc);
void DES_ede3_cfb64_encrypt(const unsigned char *in,unsigned char *out,
			    long length,DES_key_schedule *ks1,
			    DES_key_schedule *ks2,DES_key_schedule *ks3,
			    DES_cblock *ivec,int *num,int enc);
void DES_ede3_ofb64_encrypt(const unsigned char *in,unsigned char *out,
			    long length,DES_key_schedule *ks1,
			    DES_key_schedule *ks2,DES_key_schedule *ks3,
			    DES_cblock *ivec,int *num);

void DES_xwhite_in2out(const_DES_cblock *DES_key,const_DES_cblock *in_white,
		       DES_cblock *out_white);

int DES_enc_read(int fd,void *buf,int len,DES_key_schedule *sched,
		 DES_cblock *iv);
int DES_enc_write(int fd,const void *buf,int len,DES_key_schedule *sched,
		  DES_cblock *iv);
char *DES_fcrypt(const char *buf,const char *salt, char *ret);
char *DES_crypt(const char *buf,const char *salt);
void DES_ofb_encrypt(const unsigned char *in,unsigned char *out,int numbits,
		     long length,DES_key_schedule *schedule,DES_cblock *ivec);
void DES_pcbc_encrypt(const unsigned char *input,unsigned char *output,
		      long length,DES_key_schedule *schedule,DES_cblock *ivec,
		      int enc);
DES_LONG DES_quad_cksum(const unsigned char *input,DES_cblock output[],
			long length,int out_count,DES_cblock *seed);
int DES_random_key(DES_cblock *ret);
void DES_set_odd_parity(DES_cblock *key);
int DES_check_key_parity(const_DES_cblock *key);
int DES_is_weak_key(const_DES_cblock *key);
/* DES_set_key (= set_key = DES_key_sched = key_sched) calls
 * DES_set_key_checked if global variable DES_check_key is set,
 * DES_set_key_unchecked otherwise. */
int DES_set_key(const_DES_cblock *key,DES_key_schedule *schedule);
int DES_key_sched(const_DES_cblock *key,DES_key_schedule *schedule);
int DES_set_key_checked(const_DES_cblock *key,DES_key_schedule *schedule);
#endif	/* _APPLE_COMMON_CRYPTO_ */

void DES_set_key_unchecked(const_DES_cblock *key,DES_key_schedule *schedule);

#ifndef	_APPLE_COMMON_CRYPTO_
void DES_string_to_key(const char *str,DES_cblock *key);
void DES_string_to_2keys(const char *str,DES_cblock *key1,DES_cblock *key2);
void DES_cfb64_encrypt(const unsigned char *in,unsigned char *out,long length,
		       DES_key_schedule *schedule,DES_cblock *ivec,int *num,
		       int enc);
void DES_ofb64_encrypt(const unsigned char *in,unsigned char *out,long length,
		       DES_key_schedule *schedule,DES_cblock *ivec,int *num);

int DES_read_password(DES_cblock *key, const char *prompt, int verify);
int DES_read_2passwords(DES_cblock *key1, DES_cblock *key2, const char *prompt,
	int verify);

#define DES_fixup_key_parity DES_set_odd_parity

#endif	/* _APPLE_COMMON_CRYPTO_ */
#ifdef  __cplusplus
}
#endif

#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































Deleted Source/ccOpenssl/des_enc.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/* crypto/des/des_enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include "ccOpenssl/des_locl.h"

void DES_encrypt1(DES_LONG *data, DES_key_schedule *ks, int enc)
	{
	register DES_LONG l,r,t,u;
#ifdef DES_PTR
	register const unsigned char *des_SP=(const unsigned char *)DES_SPtrans;
#endif
#ifndef DES_UNROLL
	register int i;
#endif
	register DES_LONG *s;

	r=data[0];
	l=data[1];

	IP(r,l);
	/* Things have been modified so that the initial rotate is
	 * done outside the loop.  This required the
	 * DES_SPtrans values in sp.h to be rotated 1 bit to the right.
	 * One perl script later and things have a 5% speed up on a sparc2.
	 * Thanks to Richard Outerbridge <71755.204@CompuServe.COM>
	 * for pointing this out. */
	/* clear the top bits on machines with 8byte longs */
	/* shift left by 2 */
	r=ROTATE(r,29)&0xffffffffL;
	l=ROTATE(l,29)&0xffffffffL;

	s=ks->ks->deslong;
	/* I don't know if it is worth the effort of loop unrolling the
	 * inner loop */
	if (enc)
		{
#ifdef DES_UNROLL
		D_ENCRYPT(l,r, 0); /*  1 */
		D_ENCRYPT(r,l, 2); /*  2 */
		D_ENCRYPT(l,r, 4); /*  3 */
		D_ENCRYPT(r,l, 6); /*  4 */
		D_ENCRYPT(l,r, 8); /*  5 */
		D_ENCRYPT(r,l,10); /*  6 */
		D_ENCRYPT(l,r,12); /*  7 */
		D_ENCRYPT(r,l,14); /*  8 */
		D_ENCRYPT(l,r,16); /*  9 */
		D_ENCRYPT(r,l,18); /*  10 */
		D_ENCRYPT(l,r,20); /*  11 */
		D_ENCRYPT(r,l,22); /*  12 */
		D_ENCRYPT(l,r,24); /*  13 */
		D_ENCRYPT(r,l,26); /*  14 */
		D_ENCRYPT(l,r,28); /*  15 */
		D_ENCRYPT(r,l,30); /*  16 */
#else
		for (i=0; i<32; i+=8)
			{
			D_ENCRYPT(l,r,i+0); /*  1 */
			D_ENCRYPT(r,l,i+2); /*  2 */
			D_ENCRYPT(l,r,i+4); /*  3 */
			D_ENCRYPT(r,l,i+6); /*  4 */
			}
#endif
		}
	else
		{
#ifdef DES_UNROLL
		D_ENCRYPT(l,r,30); /* 16 */
		D_ENCRYPT(r,l,28); /* 15 */
		D_ENCRYPT(l,r,26); /* 14 */
		D_ENCRYPT(r,l,24); /* 13 */
		D_ENCRYPT(l,r,22); /* 12 */
		D_ENCRYPT(r,l,20); /* 11 */
		D_ENCRYPT(l,r,18); /* 10 */
		D_ENCRYPT(r,l,16); /*  9 */
		D_ENCRYPT(l,r,14); /*  8 */
		D_ENCRYPT(r,l,12); /*  7 */
		D_ENCRYPT(l,r,10); /*  6 */
		D_ENCRYPT(r,l, 8); /*  5 */
		D_ENCRYPT(l,r, 6); /*  4 */
		D_ENCRYPT(r,l, 4); /*  3 */
		D_ENCRYPT(l,r, 2); /*  2 */
		D_ENCRYPT(r,l, 0); /*  1 */
#else
		for (i=30; i>0; i-=8)
			{
			D_ENCRYPT(l,r,i-0); /* 16 */
			D_ENCRYPT(r,l,i-2); /* 15 */
			D_ENCRYPT(l,r,i-4); /* 14 */
			D_ENCRYPT(r,l,i-6); /* 13 */
			}
#endif
		}

	/* rotate and clear the top bits on machines with 8byte longs */
	l=ROTATE(l,3)&0xffffffffL;
	r=ROTATE(r,3)&0xffffffffL;

	FP(r,l);
	data[0]=l;
	data[1]=r;
	l=r=t=u=0;
	}

#ifndef	_APPLE_COMMON_CRYPTO_

void DES_encrypt2(DES_LONG *data, DES_key_schedule *ks, int enc)
	{
	register DES_LONG l,r,t,u;
#ifdef DES_PTR
	register const unsigned char *des_SP=(const unsigned char *)DES_SPtrans;
#endif
#ifndef DES_UNROLL
	register int i;
#endif
	register DES_LONG *s;

	r=data[0];
	l=data[1];

	/* Things have been modified so that the initial rotate is
	 * done outside the loop.  This required the
	 * DES_SPtrans values in sp.h to be rotated 1 bit to the right.
	 * One perl script later and things have a 5% speed up on a sparc2.
	 * Thanks to Richard Outerbridge <71755.204@CompuServe.COM>
	 * for pointing this out. */
	/* clear the top bits on machines with 8byte longs */
	r=ROTATE(r,29)&0xffffffffL;
	l=ROTATE(l,29)&0xffffffffL;

	s=ks->ks->deslong;
	/* I don't know if it is worth the effort of loop unrolling the
	 * inner loop */
	if (enc)
		{
#ifdef DES_UNROLL
		D_ENCRYPT(l,r, 0); /*  1 */
		D_ENCRYPT(r,l, 2); /*  2 */
		D_ENCRYPT(l,r, 4); /*  3 */
		D_ENCRYPT(r,l, 6); /*  4 */
		D_ENCRYPT(l,r, 8); /*  5 */
		D_ENCRYPT(r,l,10); /*  6 */
		D_ENCRYPT(l,r,12); /*  7 */
		D_ENCRYPT(r,l,14); /*  8 */
		D_ENCRYPT(l,r,16); /*  9 */
		D_ENCRYPT(r,l,18); /*  10 */
		D_ENCRYPT(l,r,20); /*  11 */
		D_ENCRYPT(r,l,22); /*  12 */
		D_ENCRYPT(l,r,24); /*  13 */
		D_ENCRYPT(r,l,26); /*  14 */
		D_ENCRYPT(l,r,28); /*  15 */
		D_ENCRYPT(r,l,30); /*  16 */
#else
		for (i=0; i<32; i+=8)
			{
			D_ENCRYPT(l,r,i+0); /*  1 */
			D_ENCRYPT(r,l,i+2); /*  2 */
			D_ENCRYPT(l,r,i+4); /*  3 */
			D_ENCRYPT(r,l,i+6); /*  4 */
			}
#endif
		}
	else
		{
#ifdef DES_UNROLL
		D_ENCRYPT(l,r,30); /* 16 */
		D_ENCRYPT(r,l,28); /* 15 */
		D_ENCRYPT(l,r,26); /* 14 */
		D_ENCRYPT(r,l,24); /* 13 */
		D_ENCRYPT(l,r,22); /* 12 */
		D_ENCRYPT(r,l,20); /* 11 */
		D_ENCRYPT(l,r,18); /* 10 */
		D_ENCRYPT(r,l,16); /*  9 */
		D_ENCRYPT(l,r,14); /*  8 */
		D_ENCRYPT(r,l,12); /*  7 */
		D_ENCRYPT(l,r,10); /*  6 */
		D_ENCRYPT(r,l, 8); /*  5 */
		D_ENCRYPT(l,r, 6); /*  4 */
		D_ENCRYPT(r,l, 4); /*  3 */
		D_ENCRYPT(l,r, 2); /*  2 */
		D_ENCRYPT(r,l, 0); /*  1 */
#else
		for (i=30; i>0; i-=8)
			{
			D_ENCRYPT(l,r,i-0); /* 16 */
			D_ENCRYPT(r,l,i-2); /* 15 */
			D_ENCRYPT(l,r,i-4); /* 14 */
			D_ENCRYPT(r,l,i-6); /* 13 */
			}
#endif
		}
	/* rotate and clear the top bits on machines with 8byte longs */
	data[0]=ROTATE(l,3)&0xffffffffL;
	data[1]=ROTATE(r,3)&0xffffffffL;
	l=r=t=u=0;
	}

void DES_encrypt3(DES_LONG *data, DES_key_schedule *ks1,
		  DES_key_schedule *ks2, DES_key_schedule *ks3)
	{
	register DES_LONG l,r;

	l=data[0];
	r=data[1];
	IP(l,r);
	data[0]=l;
	data[1]=r;
	DES_encrypt2((DES_LONG *)data,ks1,DES_ENCRYPT);
	DES_encrypt2((DES_LONG *)data,ks2,DES_DECRYPT);
	DES_encrypt2((DES_LONG *)data,ks3,DES_ENCRYPT);
	l=data[0];
	r=data[1];
	FP(r,l);
	data[0]=l;
	data[1]=r;
	}

void DES_decrypt3(DES_LONG *data, DES_key_schedule *ks1,
		  DES_key_schedule *ks2, DES_key_schedule *ks3)
	{
	register DES_LONG l,r;

	l=data[0];
	r=data[1];
	IP(l,r);
	data[0]=l;
	data[1]=r;
	DES_encrypt2((DES_LONG *)data,ks3,DES_DECRYPT);
	DES_encrypt2((DES_LONG *)data,ks2,DES_ENCRYPT);
	DES_encrypt2((DES_LONG *)data,ks1,DES_DECRYPT);
	l=data[0];
	r=data[1];
	FP(r,l);
	data[0]=l;
	data[1]=r;
	}

#ifndef DES_DEFAULT_OPTIONS

#undef CBC_ENC_C__DONT_UPDATE_IV
#include "ncbc_enc.c" /* DES_ncbc_encrypt */

void DES_ede3_cbc_encrypt(const unsigned char *input, unsigned char *output,
			  long length, DES_key_schedule *ks1,
			  DES_key_schedule *ks2, DES_key_schedule *ks3,
			  DES_cblock *ivec, int enc)
	{
	register DES_LONG tin0,tin1;
	register DES_LONG tout0,tout1,xor0,xor1;
	register const unsigned char *in;
	unsigned char *out;
	register long l=length;
	DES_LONG tin[2];
	unsigned char *iv;

	in=input;
	out=output;
	iv = &(*ivec)[0];

	if (enc)
		{
		c2l(iv,tout0);
		c2l(iv,tout1);
		for (l-=8; l>=0; l-=8)
			{
			c2l(in,tin0);
			c2l(in,tin1);
			tin0^=tout0;
			tin1^=tout1;

			tin[0]=tin0;
			tin[1]=tin1;
			DES_encrypt3((DES_LONG *)tin,ks1,ks2,ks3);
			tout0=tin[0];
			tout1=tin[1];

			l2c(tout0,out);
			l2c(tout1,out);
			}
		if (l != -8)
			{
			c2ln(in,tin0,tin1,l+8);
			tin0^=tout0;
			tin1^=tout1;

			tin[0]=tin0;
			tin[1]=tin1;
			DES_encrypt3((DES_LONG *)tin,ks1,ks2,ks3);
			tout0=tin[0];
			tout1=tin[1];

			l2c(tout0,out);
			l2c(tout1,out);
			}
		iv = &(*ivec)[0];
		l2c(tout0,iv);
		l2c(tout1,iv);
		}
	else
		{
		register DES_LONG t0,t1;

		c2l(iv,xor0);
		c2l(iv,xor1);
		for (l-=8; l>=0; l-=8)
			{
			c2l(in,tin0);
			c2l(in,tin1);

			t0=tin0;
			t1=tin1;

			tin[0]=tin0;
			tin[1]=tin1;
			DES_decrypt3((DES_LONG *)tin,ks1,ks2,ks3);
			tout0=tin[0];
			tout1=tin[1];

			tout0^=xor0;
			tout1^=xor1;
			l2c(tout0,out);
			l2c(tout1,out);
			xor0=t0;
			xor1=t1;
			}
		if (l != -8)
			{
			c2l(in,tin0);
			c2l(in,tin1);
			
			t0=tin0;
			t1=tin1;

			tin[0]=tin0;
			tin[1]=tin1;
			DES_decrypt3((DES_LONG *)tin,ks1,ks2,ks3);
			tout0=tin[0];
			tout1=tin[1];
		
			tout0^=xor0;
			tout1^=xor1;
			l2cn(tout0,tout1,out,l+8);
			xor0=t0;
			xor1=t1;
			}

		iv = &(*ivec)[0];
		l2c(xor0,iv);
		l2c(xor1,iv);
		}
	tin0=tin1=tout0=tout1=xor0=xor1=0;
	tin[0]=tin[1]=0;
	}

#endif	/* _APPLE_COMMON_CRYPTO_ */
#endif /* DES_DEFAULT_OPTIONS */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/ccOpenssl/des_locl.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
/* crypto/des/des_locl.h */
/* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#ifndef HEADER_DES_LOCL_H
#define HEADER_DES_LOCL_H

#include <CommonCrypto/CommonCryptoPriv.h>
#include <ccOpenssl/e_os2.h>

#if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN16)
#ifndef OPENSSL_SYS_MSDOS
#define OPENSSL_SYS_MSDOS
#endif
#endif

#include <stdio.h>
#include <stdlib.h>

/* building in CommonCrypto */
#define DES_DEFAULT_OPTIONS

#ifndef OPENSSL_SYS_MSDOS
#if !defined(OPENSSL_SYS_VMS) || defined(__DECC)
#ifdef OPENSSL_UNISTD
# include OPENSSL_UNISTD
#else
# include <unistd.h>
#endif
#include <math.h>
#endif
#endif

#include <ccOpenssl/des.h>

#ifdef OPENSSL_SYS_MSDOS		/* Visual C++ 2.1 (Windows NT/95) */
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <io.h>
#endif

#if defined(__STDC__) || defined(OPENSSL_SYS_VMS) || defined(M_XENIX) || defined(OPENSSL_SYS_MSDOS)
#include <string.h>
#endif

#ifdef OPENSSL_BUILD_SHLIBCRYPTO
# undef OPENSSL_EXTERN
# define OPENSSL_EXTERN OPENSSL_EXPORT
#endif

#define ITERATIONS 16
#define HALF_ITERATIONS 8

/* used in des_read and des_write */
#define MAXWRITE	(1024*16)
#define BSIZE		(MAXWRITE+4)

#define c2l(c,l)	(l =((DES_LONG)(*((c)++)))    , \
			 l|=((DES_LONG)(*((c)++)))<< 8L, \
			 l|=((DES_LONG)(*((c)++)))<<16L, \
			 l|=((DES_LONG)(*((c)++)))<<24L)

/* NOTE - c is not incremented as per c2l */
#define c2ln(c,l1,l2,n)	{ \
			c+=n; \
			l1=l2=0; \
			switch (n) { \
			case 8: l2 =((DES_LONG)(*(--(c))))<<24L; \
			case 7: l2|=((DES_LONG)(*(--(c))))<<16L; \
			case 6: l2|=((DES_LONG)(*(--(c))))<< 8L; \
			case 5: l2|=((DES_LONG)(*(--(c))));     \
			case 4: l1 =((DES_LONG)(*(--(c))))<<24L; \
			case 3: l1|=((DES_LONG)(*(--(c))))<<16L; \
			case 2: l1|=((DES_LONG)(*(--(c))))<< 8L; \
			case 1: l1|=((DES_LONG)(*(--(c))));     \
				} \
			}

#define l2c(l,c)	(*((c)++)=(unsigned char)(((l)     )&0xff), \
			 *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \
			 *((c)++)=(unsigned char)(((l)>>16L)&0xff), \
			 *((c)++)=(unsigned char)(((l)>>24L)&0xff))

/* replacements for htonl and ntohl since I have no idea what to do
 * when faced with machines with 8 byte longs. */
#define HDRSIZE 4

#define n2l(c,l)	(l =((DES_LONG)(*((c)++)))<<24L, \
			 l|=((DES_LONG)(*((c)++)))<<16L, \
			 l|=((DES_LONG)(*((c)++)))<< 8L, \
			 l|=((DES_LONG)(*((c)++))))

#define l2n(l,c)	(*((c)++)=(unsigned char)(((l)>>24L)&0xff), \
			 *((c)++)=(unsigned char)(((l)>>16L)&0xff), \
			 *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \
			 *((c)++)=(unsigned char)(((l)     )&0xff))

/* NOTE - c is not incremented as per l2c */
#define l2cn(l1,l2,c,n)	{ \
			c+=n; \
			switch (n) { \
			case 8: *(--(c))=(unsigned char)(((l2)>>24L)&0xff); \
			case 7: *(--(c))=(unsigned char)(((l2)>>16L)&0xff); \
			case 6: *(--(c))=(unsigned char)(((l2)>> 8L)&0xff); \
			case 5: *(--(c))=(unsigned char)(((l2)     )&0xff); \
			case 4: *(--(c))=(unsigned char)(((l1)>>24L)&0xff); \
			case 3: *(--(c))=(unsigned char)(((l1)>>16L)&0xff); \
			case 2: *(--(c))=(unsigned char)(((l1)>> 8L)&0xff); \
			case 1: *(--(c))=(unsigned char)(((l1)     )&0xff); \
				} \
			}

#if defined(OPENSSL_SYS_WIN32) && defined(_MSC_VER)
#define	ROTATE(a,n)	(_lrotr(a,n))
#elif defined(__GNUC__) && __GNUC__>=2 && !defined(__STRICT_ANSI__) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) && !defined(PEDANTIC)
# if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)
#  define ROTATE(a,n)	({ register unsigned int ret;	\
				asm ("rorl %1,%0"	\
					: "=r"(ret)	\
					: "I"(n),"0"((unsigned int)a)	\
					: "cc");	\
			   ret;				\
			})
# endif
#endif
#ifndef ROTATE
#define	ROTATE(a,n)	(((a)>>(n))+((a)<<(32-(n))))
#endif

/* Don't worry about the LOAD_DATA() stuff, that is used by
 * fcrypt() to add it's little bit to the front */

#ifdef DES_FCRYPT

#define LOAD_DATA_tmp(R,S,u,t,E0,E1) \
	{ DES_LONG tmp; LOAD_DATA(R,S,u,t,E0,E1,tmp); }

#define LOAD_DATA(R,S,u,t,E0,E1,tmp) \
	t=R^(R>>16L); \
	u=t&E0; t&=E1; \
	tmp=(u<<16); u^=R^s[S  ]; u^=tmp; \
	tmp=(t<<16); t^=R^s[S+1]; t^=tmp
#else
#define LOAD_DATA_tmp(a,b,c,d,e,f) LOAD_DATA(a,b,c,d,e,f,g)
#define LOAD_DATA(R,S,u,t,E0,E1,tmp) \
	u=R^s[S  ]; \
	t=R^s[S+1]
#endif

/* The changes to this macro may help or hinder, depending on the
 * compiler and the architecture.  gcc2 always seems to do well :-).
 * Inspired by Dana How <how@isl.stanford.edu>
 * DO NOT use the alternative version on machines with 8 byte longs.
 * It does not seem to work on the Alpha, even when DES_LONG is 4
 * bytes, probably an issue of accessing non-word aligned objects :-( */
#ifdef DES_PTR

/* It recently occurred to me that 0^0^0^0^0^0^0 == 0, so there
 * is no reason to not xor all the sub items together.  This potentially
 * saves a register since things can be xored directly into L */

#if defined(DES_RISC1) || defined(DES_RISC2)
#ifdef DES_RISC1
#define D_ENCRYPT(LL,R,S) { \
	unsigned int u1,u2,u3; \
	LOAD_DATA(R,S,u,t,E0,E1,u1); \
	u2=(int)u>>8L; \
	u1=(int)u&0xfc; \
	u2&=0xfc; \
	t=ROTATE(t,4); \
	u>>=16L; \
	LL^= *(const DES_LONG *)(des_SP      +u1); \
	LL^= *(const DES_LONG *)(des_SP+0x200+u2); \
	u3=(int)(u>>8L); \
	u1=(int)u&0xfc; \
	u3&=0xfc; \
	LL^= *(const DES_LONG *)(des_SP+0x400+u1); \
	LL^= *(const DES_LONG *)(des_SP+0x600+u3); \
	u2=(int)t>>8L; \
	u1=(int)t&0xfc; \
	u2&=0xfc; \
	t>>=16L; \
	LL^= *(const DES_LONG *)(des_SP+0x100+u1); \
	LL^= *(const DES_LONG *)(des_SP+0x300+u2); \
	u3=(int)t>>8L; \
	u1=(int)t&0xfc; \
	u3&=0xfc; \
	LL^= *(const DES_LONG *)(des_SP+0x500+u1); \
	LL^= *(const DES_LONG *)(des_SP+0x700+u3); }
#endif
#ifdef DES_RISC2
#define D_ENCRYPT(LL,R,S) { \
	unsigned int u1,u2,s1,s2; \
	LOAD_DATA(R,S,u,t,E0,E1,u1); \
	u2=(int)u>>8L; \
	u1=(int)u&0xfc; \
	u2&=0xfc; \
	t=ROTATE(t,4); \
	LL^= *(const DES_LONG *)(des_SP      +u1); \
	LL^= *(const DES_LONG *)(des_SP+0x200+u2); \
	s1=(int)(u>>16L); \
	s2=(int)(u>>24L); \
	s1&=0xfc; \
	s2&=0xfc; \
	LL^= *(const DES_LONG *)(des_SP+0x400+s1); \
	LL^= *(const DES_LONG *)(des_SP+0x600+s2); \
	u2=(int)t>>8L; \
	u1=(int)t&0xfc; \
	u2&=0xfc; \
	LL^= *(const DES_LONG *)(des_SP+0x100+u1); \
	LL^= *(const DES_LONG *)(des_SP+0x300+u2); \
	s1=(int)(t>>16L); \
	s2=(int)(t>>24L); \
	s1&=0xfc; \
	s2&=0xfc; \
	LL^= *(const DES_LONG *)(des_SP+0x500+s1); \
	LL^= *(const DES_LONG *)(des_SP+0x700+s2); }
#endif
#else
#define D_ENCRYPT(LL,R,S) { \
	LOAD_DATA_tmp(R,S,u,t,E0,E1); \
	t=ROTATE(t,4); \
	LL^= \
	*(const DES_LONG *)(des_SP      +((u     )&0xfc))^ \
	*(const DES_LONG *)(des_SP+0x200+((u>> 8L)&0xfc))^ \
	*(const DES_LONG *)(des_SP+0x400+((u>>16L)&0xfc))^ \
	*(const DES_LONG *)(des_SP+0x600+((u>>24L)&0xfc))^ \
	*(const DES_LONG *)(des_SP+0x100+((t     )&0xfc))^ \
	*(const DES_LONG *)(des_SP+0x300+((t>> 8L)&0xfc))^ \
	*(const DES_LONG *)(des_SP+0x500+((t>>16L)&0xfc))^ \
	*(const DES_LONG *)(des_SP+0x700+((t>>24L)&0xfc)); }
#endif

#else /* original version */

#if defined(DES_RISC1) || defined(DES_RISC2)
#ifdef DES_RISC1
#define D_ENCRYPT(LL,R,S) {\
	unsigned int u1,u2,u3; \
	LOAD_DATA(R,S,u,t,E0,E1,u1); \
	u>>=2L; \
	t=ROTATE(t,6); \
	u2=(int)u>>8L; \
	u1=(int)u&0x3f; \
	u2&=0x3f; \
	u>>=16L; \
	LL^=DES_SPtrans[0][u1]; \
	LL^=DES_SPtrans[2][u2]; \
	u3=(int)u>>8L; \
	u1=(int)u&0x3f; \
	u3&=0x3f; \
	LL^=DES_SPtrans[4][u1]; \
	LL^=DES_SPtrans[6][u3]; \
	u2=(int)t>>8L; \
	u1=(int)t&0x3f; \
	u2&=0x3f; \
	t>>=16L; \
	LL^=DES_SPtrans[1][u1]; \
	LL^=DES_SPtrans[3][u2]; \
	u3=(int)t>>8L; \
	u1=(int)t&0x3f; \
	u3&=0x3f; \
	LL^=DES_SPtrans[5][u1]; \
	LL^=DES_SPtrans[7][u3]; }
#endif
#ifdef DES_RISC2
#define D_ENCRYPT(LL,R,S) {\
	unsigned int u1,u2,s1,s2; \
	LOAD_DATA(R,S,u,t,E0,E1,u1); \
	u>>=2L; \
	t=ROTATE(t,6); \
	u2=(int)u>>8L; \
	u1=(int)u&0x3f; \
	u2&=0x3f; \
	LL^=DES_SPtrans[0][u1]; \
	LL^=DES_SPtrans[2][u2]; \
	s1=(int)u>>16L; \
	s2=(int)u>>24L; \
	s1&=0x3f; \
	s2&=0x3f; \
	LL^=DES_SPtrans[4][s1]; \
	LL^=DES_SPtrans[6][s2]; \
	u2=(int)t>>8L; \
	u1=(int)t&0x3f; \
	u2&=0x3f; \
	LL^=DES_SPtrans[1][u1]; \
	LL^=DES_SPtrans[3][u2]; \
	s1=(int)t>>16; \
	s2=(int)t>>24L; \
	s1&=0x3f; \
	s2&=0x3f; \
	LL^=DES_SPtrans[5][s1]; \
	LL^=DES_SPtrans[7][s2]; }
#endif

#else

#define D_ENCRYPT(LL,R,S) {\
	LOAD_DATA_tmp(R,S,u,t,E0,E1); \
	t=ROTATE(t,4); \
	LL^=\
		DES_SPtrans[0][(u>> 2L)&0x3f]^ \
		DES_SPtrans[2][(u>>10L)&0x3f]^ \
		DES_SPtrans[4][(u>>18L)&0x3f]^ \
		DES_SPtrans[6][(u>>26L)&0x3f]^ \
		DES_SPtrans[1][(t>> 2L)&0x3f]^ \
		DES_SPtrans[3][(t>>10L)&0x3f]^ \
		DES_SPtrans[5][(t>>18L)&0x3f]^ \
		DES_SPtrans[7][(t>>26L)&0x3f]; }
#endif
#endif

	/* IP and FP
	 * The problem is more of a geometric problem that random bit fiddling.
	 0  1  2  3  4  5  6  7      62 54 46 38 30 22 14  6
	 8  9 10 11 12 13 14 15      60 52 44 36 28 20 12  4
	16 17 18 19 20 21 22 23      58 50 42 34 26 18 10  2
	24 25 26 27 28 29 30 31  to  56 48 40 32 24 16  8  0

	32 33 34 35 36 37 38 39      63 55 47 39 31 23 15  7
	40 41 42 43 44 45 46 47      61 53 45 37 29 21 13  5
	48 49 50 51 52 53 54 55      59 51 43 35 27 19 11  3
	56 57 58 59 60 61 62 63      57 49 41 33 25 17  9  1

	The output has been subject to swaps of the form
	0 1 -> 3 1 but the odd and even bits have been put into
	2 3    2 0
	different words.  The main trick is to remember that
	t=((l>>size)^r)&(mask);
	r^=t;
	l^=(t<<size);
	can be used to swap and move bits between words.

	So l =  0  1  2  3  r = 16 17 18 19
	        4  5  6  7      20 21 22 23
	        8  9 10 11      24 25 26 27
	       12 13 14 15      28 29 30 31
	becomes (for size == 2 and mask == 0x3333)
	   t =   2^16  3^17 -- --   l =  0  1 16 17  r =  2  3 18 19
		 6^20  7^21 -- --        4  5 20 21       6  7 22 23
		10^24 11^25 -- --        8  9 24 25      10 11 24 25
		14^28 15^29 -- --       12 13 28 29      14 15 28 29

	Thanks for hints from Richard Outerbridge - he told me IP&FP
	could be done in 15 xor, 10 shifts and 5 ands.
	When I finally started to think of the problem in 2D
	I first got ~42 operations without xors.  When I remembered
	how to use xors :-) I got it to its final state.
	*/
#define PERM_OP(a,b,t,n,m) ((t)=((((a)>>(n))^(b))&(m)),\
	(b)^=(t),\
	(a)^=((t)<<(n)))

#define IP(l,r) \
	{ \
	register DES_LONG tt; \
	PERM_OP(r,l,tt, 4,0x0f0f0f0fL); \
	PERM_OP(l,r,tt,16,0x0000ffffL); \
	PERM_OP(r,l,tt, 2,0x33333333L); \
	PERM_OP(l,r,tt, 8,0x00ff00ffL); \
	PERM_OP(r,l,tt, 1,0x55555555L); \
	}

#define FP(l,r) \
	{ \
	register DES_LONG tt; \
	PERM_OP(l,r,tt, 1,0x55555555L); \
	PERM_OP(r,l,tt, 8,0x00ff00ffL); \
	PERM_OP(l,r,tt, 2,0x33333333L); \
	PERM_OP(r,l,tt,16,0x0000ffffL); \
	PERM_OP(l,r,tt, 4,0x0f0f0f0fL); \
	}

#ifdef	_APPLE_COMMON_CRYPTO_
/* avoid symbol collision with libSystem & libcrypto */
#define DES_SPtrans CC_DES_SPtrans
#endif	/* _APPLE_COMMON_CRYPTO_ */

OPENSSL_EXTERN const DES_LONG DES_SPtrans[8][64];

void fcrypt_body(DES_LONG *out,DES_key_schedule *ks,
		 DES_LONG Eswap0, DES_LONG Eswap1);
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/ccOpenssl/e_os2.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/* e_os2.h */
/* ====================================================================
 * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    openssl-core@openssl.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */


#ifndef HEADER_E_OS2_H
#define HEADER_E_OS2_H

#include <CommonCrypto/CommonCryptoPriv.h>
#include <ccOpenssl/opensslconf.h>

#ifdef  __cplusplus
extern "C" {
#endif

/******************************************************************************
 * Detect operating systems.  This probably needs completing.
 * The result is that at least one OPENSSL_SYS_os macro should be defined.
 * However, if none is defined, Unix is assumed.
 **/

#define OPENSSL_SYS_UNIX

/* ----------------------- Macintosh, before MacOS X ----------------------- */
#if defined(__MWERKS__) && defined(macintosh) || defined(OPENSSL_SYSNAME_MAC)
# undef OPENSSL_SYS_UNIX
# define OPENSSL_SYS_MACINTOSH_CLASSIC
#endif

/* ---------------------- Microsoft operating systems ---------------------- */

/* The 16 bit environments are pretty straightforward */
#if defined(OPENSSL_SYSNAME_WIN16) || defined(OPENSSL_SYSNAME_MSDOS)
# undef OPENSSL_SYS_UNIX
# define OPENSSL_SYS_MSDOS
#endif
#if defined(OPENSSL_SYSNAME_WIN16)
# undef OPENSSL_SYS_UNIX
# define OPENSSL_SYS_WIN16
#endif

/* For 32 bit environment, there seems to be the CygWin environment and then
   all the others that try to do the same thing Microsoft does... */
#if defined(OPENSSL_SYSNAME_UWIN)
# undef OPENSSL_SYS_UNIX
# define OPENSSL_SYS_WIN32_UWIN
#else
# if defined(__CYGWIN32__) || defined(OPENSSL_SYSNAME_CYGWIN32)
#  undef OPENSSL_SYS_UNIX
#  define OPENSSL_SYS_WIN32_CYGWIN
# else
#  if defined(_WIN32) || defined(OPENSSL_SYSNAME_WIN32)
#   undef OPENSSL_SYS_UNIX
#   define OPENSSL_SYS_WIN32
#  endif
#  if defined(OPENSSL_SYSNAME_WINNT)
#   undef OPENSSL_SYS_UNIX
#   define OPENSSL_SYS_WINNT
#  endif
#  if defined(OPENSSL_SYSNAME_WINCE)
#   undef OPENSSL_SYS_UNIX
#   define OPENSSL_SYS_WINCE
#  endif
# endif
#endif

/* Anything that tries to look like Microsoft is "Windows" */
#if defined(OPENSSL_SYS_WIN16) || defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WINNT) || defined(OPENSSL_SYS_WINCE)
# undef OPENSSL_SYS_UNIX
# define OPENSSL_SYS_WINDOWS
# ifndef OPENSSL_SYS_MSDOS
#  define OPENSSL_SYS_MSDOS
# endif
#endif

/* DLL settings.  This part is a bit tough, because it's up to the application
   implementor how he or she will link the application, so it requires some
   macro to be used. */
#ifdef OPENSSL_SYS_WINDOWS
# ifndef OPENSSL_OPT_WINDLL
#  if defined(_WINDLL) /* This is used when building OpenSSL to indicate that
                          DLL linkage should be used */
#   define OPENSSL_OPT_WINDLL
#  endif
# endif
#endif

/* -------------------------------- OpenVMS -------------------------------- */
#if defined(__VMS) || defined(VMS) || defined(OPENSSL_SYSNAME_VMS)
# undef OPENSSL_SYS_UNIX
# define OPENSSL_SYS_VMS
# if defined(__DECC)
#  define OPENSSL_SYS_VMS_DECC
# elif defined(__DECCXX)
#  define OPENSSL_SYS_VMS_DECC
#  define OPENSSL_SYS_VMS_DECCXX
# else
#  define OPENSSL_SYS_VMS_NODECC
# endif
#endif

/* --------------------------------- OS/2 ---------------------------------- */
#if defined(__EMX__) || defined(__OS2__)
# undef OPENSSL_SYS_UNIX
# define OPENSSL_SYS_OS2
#endif

/* --------------------------------- Unix ---------------------------------- */
#ifdef OPENSSL_SYS_UNIX
# if defined(linux) || defined(__linux__) || defined(OPENSSL_SYSNAME_LINUX)
#  define OPENSSL_SYS_LINUX
# endif
# ifdef OPENSSL_SYSNAME_MPE
#  define OPENSSL_SYS_MPE
# endif
# ifdef OPENSSL_SYSNAME_SNI
#  define OPENSSL_SYS_SNI
# endif
# ifdef OPENSSL_SYSNAME_ULTRASPARC
#  define OPENSSL_SYS_ULTRASPARC
# endif
# ifdef OPENSSL_SYSNAME_NEWS4
#  define OPENSSL_SYS_NEWS4
# endif
# ifdef OPENSSL_SYSNAME_MACOSX
#  define OPENSSL_SYS_MACOSX
# endif
# ifdef OPENSSL_SYSNAME_MACOSX_RHAPSODY
#  define OPENSSL_SYS_MACOSX_RHAPSODY
#  define OPENSSL_SYS_MACOSX
# endif
# ifdef OPENSSL_SYSNAME_SUNOS
#  define OPENSSL_SYS_SUNOS
#endif
# if defined(_CRAY) || defined(OPENSSL_SYSNAME_CRAY)
#  define OPENSSL_SYS_CRAY
# endif
# if defined(_AIX) || defined(OPENSSL_SYSNAME_AIX)
#  define OPENSSL_SYS_AIX
# endif
#endif

/* ------------------------------- VxWorks --------------------------------- */
#ifdef OPENSSL_SYSNAME_VXWORKS
# define OPENSSL_SYS_VXWORKS
#endif

/**
 * That's it for OS-specific stuff
 *****************************************************************************/


/* Specials for I/O an exit */
#ifdef OPENSSL_SYS_MSDOS
# define OPENSSL_UNISTD_IO <io.h>
# define OPENSSL_DECLARE_EXIT extern void exit(int);
#else
# define OPENSSL_UNISTD_IO OPENSSL_UNISTD
# define OPENSSL_DECLARE_EXIT /* declared in unistd.h */
#endif

/* Definitions of OPENSSL_GLOBAL and OPENSSL_EXTERN, to define and declare
   certain global symbols that, with some compilers under VMS, have to be
   defined and declared explicitely with globaldef and globalref.
   Definitions of OPENSSL_EXPORT and OPENSSL_IMPORT, to define and declare
   DLL exports and imports for compilers under Win32.  These are a little
   more complicated to use.  Basically, for any library that exports some
   global variables, the following code must be present in the header file
   that declares them, before OPENSSL_EXTERN is used:

   #ifdef SOME_BUILD_FLAG_MACRO
   # undef OPENSSL_EXTERN
   # define OPENSSL_EXTERN OPENSSL_EXPORT
   #endif

   The default is to have OPENSSL_EXPORT, OPENSSL_IMPORT and OPENSSL_GLOBAL
   have some generally sensible values, and for OPENSSL_EXTERN to have the
   value OPENSSL_IMPORT.
*/

#if defined(OPENSSL_SYS_VMS_NODECC)
# define OPENSSL_EXPORT globalref
# define OPENSSL_IMPORT globalref
# define OPENSSL_GLOBAL globaldef
#elif defined(OPENSSL_SYS_WINDOWS) && defined(OPENSSL_OPT_WINDLL)
# define OPENSSL_EXPORT extern _declspec(dllexport)
# define OPENSSL_IMPORT extern _declspec(dllimport)
# define OPENSSL_GLOBAL
#else
# define OPENSSL_EXPORT extern
# define OPENSSL_IMPORT extern
# define OPENSSL_GLOBAL
#endif
#define OPENSSL_EXTERN OPENSSL_IMPORT

/* Macros to allow global variables to be reached through function calls when
   required (if a shared library version requvres it, for example.
   The way it's done allows definitions like this:

	// in foobar.c
	OPENSSL_IMPLEMENT_GLOBAL(int,foobar) = 0;
	// in foobar.h
	OPENSSL_DECLARE_GLOBAL(int,foobar);
	#define foobar OPENSSL_GLOBAL_REF(foobar)
*/
#ifdef OPENSSL_EXPORT_VAR_AS_FUNCTION
# define OPENSSL_IMPLEMENT_GLOBAL(type,name) static type _hide_##name; \
        type *_shadow_##name(void) { return &_hide_##name; } \
        static type _hide_##name
# define OPENSSL_DECLARE_GLOBAL(type,name) type *_shadow_##name(void)
# define OPENSSL_GLOBAL_REF(name) (*(_shadow_##name()))
#else
# define OPENSSL_IMPLEMENT_GLOBAL(type,name) OPENSSL_GLOBAL type _shadow_##name
# define OPENSSL_DECLARE_GLOBAL(type,name) OPENSSL_EXPORT type _shadow_##name
# define OPENSSL_GLOBAL_REF(name) _shadow_##name
#endif

#ifdef  __cplusplus
}
#endif
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































Deleted Source/ccOpenssl/opensslDES.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
/* crypto/des/des_enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

/* 
 * This is pared-down version of openssl's des_enc.c, shorn of 
 * everything except the bare-bones single-block encrypt/decrypt
 * routine DES_encrypt1(). Plus it has the shim code needed to
 * use this function in CommonEncryption. 
 */
 
#include <CommonCrypto/opensslDES.h>
#include "ccOpenssl/des_locl.h"
#include <strings.h>
#include "spr.h"

/* CommonCrypto shim */

int osDesSetkey(DES_key_schedule *dinst, char *key, size_t keyLength,
	int forEencrypt)
{
	DES_cblock cblock;
	memmove(&cblock, key, 8);
	DES_set_key_unchecked(&cblock, dinst);
	return 0;
}

void osDesEncrypt(DES_key_schedule *ks, 
	const_DES_cblock *input, 
	DES_cblock *output)
{
	/* copied from openssl's DES_ecb_encrypt() */
	register DES_LONG l;
	DES_LONG ll[2];
	const unsigned char *in = &(*input)[0];
	unsigned char *out = &(*output)[0];

	c2l(in,l); ll[0]=l;
	c2l(in,l); ll[1]=l;
	DES_encrypt1(ll,ks,1);
	l=ll[0]; l2c(l,out);
	l=ll[1]; l2c(l,out);
	l=ll[0]=ll[1]=0;
}

void osDesDecrypt(DES_key_schedule *ks, 
	const_DES_cblock *input, 
	DES_cblock *output)
{
	/* copied from openssl's DES_ecb_encrypt() */
	register DES_LONG l;
	DES_LONG ll[2];
	const unsigned char *in = &(*input)[0];
	unsigned char *out = &(*output)[0];

	c2l(in,l); ll[0]=l;
	c2l(in,l); ll[1]=l;
	DES_encrypt1(ll,ks,0);
	l=ll[0]; l2c(l,out);
	l=ll[1]; l2c(l,out);
	l=ll[0]=ll[1]=0;
}

int osDes3Setkey(DES3_Schedule *dinst, char *key, size_t keyLength,
	int forEencrypt)
{
	DES_cblock cblock;
	memmove(&cblock, key, 8);
	DES_set_key_unchecked(&cblock, &dinst->ks[0]);
	memmove(&cblock, key+8, 8);
	DES_set_key_unchecked(&cblock, &dinst->ks[1]);
	memmove(&cblock, key+16, 8);
	DES_set_key_unchecked(&cblock, &dinst->ks[2]);
	return 0;

}

void osDes3Encrypt(DES3_Schedule *ks, 
	const_DES_cblock *input, 
	DES_cblock *output)
{
	register DES_LONG l;
	DES_LONG ll[2];
	const unsigned char *in = &(*input)[0];
	unsigned char *out = &(*output)[0];

	c2l(in,l); ll[0]=l;
	c2l(in,l); ll[1]=l;
	DES_encrypt1(ll,&ks->ks[0],1);
	DES_encrypt1(ll,&ks->ks[1],0);
	DES_encrypt1(ll,&ks->ks[2],1);
	l=ll[0]; l2c(l,out);
	l=ll[1]; l2c(l,out);
	l=ll[0]=ll[1]=0;
}

void osDes3Decrypt(DES3_Schedule *ks, 
	const_DES_cblock *input, 
	DES_cblock *output)
{
	register DES_LONG l;
	DES_LONG ll[2];
	const unsigned char *in = &(*input)[0];
	unsigned char *out = &(*output)[0];

	c2l(in,l); ll[0]=l;
	c2l(in,l); ll[1]=l;
	DES_encrypt1(ll,&ks->ks[2],0);
	DES_encrypt1(ll,&ks->ks[1],1);
	DES_encrypt1(ll,&ks->ks[0],0);
	l=ll[0]; l2c(l,out);
	l=ll[1]; l2c(l,out);
	l=ll[0]=ll[1]=0;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































Deleted Source/ccOpenssl/opensslconf.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/* MacOS/opensslconf.h */

#include <CommonCrypto/CommonCryptoPriv.h>

#if !(defined(VMS) || defined(__VMS)) /* VMS uses logical names instead */
#if defined(HEADER_CRYPTLIB_H) && !defined(OPENSSLDIR)
#define OPENSSLDIR "/usr/local/ssl"
#endif
#endif

#if defined(HEADER_IDEA_H) && !defined(IDEA_INT)
#define IDEA_INT unsigned int
#endif

#if defined(HEADER_MD2_H) && !defined(MD2_INT)
#define MD2_INT unsigned int
#endif

#if defined(HEADER_RC2_H) && !defined(RC2_INT)
/* I need to put in a mod for the alpha - eay */
#define RC2_INT unsigned int
#endif

#if defined(HEADER_RC4_H)
#if !defined(RC4_INT)
/* using int types make the structure larger but make the code faster
 * on most boxes I have tested - up to %20 faster. */
/*
 * I don't know what does "most" mean, but declaring "int" is a must on:
 * - Intel P6 because partial register stalls are very expensive;
 * - elder Alpha because it lacks byte load/store instructions;
 */
#define RC4_INT unsigned char
#endif
#if !defined(RC4_CHUNK)
/*
 * This enables code handling data aligned at natural CPU word
 * boundary. See crypto/rc4/rc4_enc.c for further details.
 */
#define RC4_CHUNK unsigned long
#endif
#endif

#if defined(HEADER_DES_H) && !defined(DES_LONG)
/* If this is set to 'unsigned int' on a DEC Alpha, this gives about a
 * %20 speed up (longs are 8 bytes, int's are 4). */
#ifndef DES_LONG
#define DES_LONG unsigned long
#endif
#endif

#if defined(HEADER_BN_H) && !defined(CONFIG_HEADER_BN_H)
#define CONFIG_HEADER_BN_H
#if __option(longlong)
#  define BN_LLONG
#else
#  undef BN_LLONG
#endif

/* Should we define BN_DIV2W here? */

/* Only one for the following should be defined */
/* The prime number generation stuff may not work when
 * EIGHT_BIT but I don't care since I've only used this mode
 * for debuging the bignum libraries */
#undef SIXTY_FOUR_BIT_LONG
#undef SIXTY_FOUR_BIT
#define THIRTY_TWO_BIT
#undef SIXTEEN_BIT
#undef EIGHT_BIT
#endif

#if defined(HEADER_RC4_LOCL_H) && !defined(CONFIG_HEADER_RC4_LOCL_H)
#define CONFIG_HEADER_RC4_LOCL_H
/* if this is defined data[i] is used instead of *data, this is a %20
 * speedup on x86 */
#undef RC4_INDEX
#endif

#if defined(HEADER_BF_LOCL_H) && !defined(CONFIG_HEADER_BF_LOCL_H)
#define CONFIG_HEADER_BF_LOCL_H
#define BF_PTR
#endif /* HEADER_BF_LOCL_H */

#if defined(HEADER_DES_LOCL_H) && !defined(CONFIG_HEADER_DES_LOCL_H)
#define CONFIG_HEADER_DES_LOCL_H
/* the following is tweaked from a config script, that is why it is a
 * protected undef/define */
#ifndef DES_PTR
#define DES_PTR
#endif

/* This helps C compiler generate the correct code for multiple functional
 * units.  It reduces register dependancies at the expense of 2 more
 * registers */
#ifndef DES_RISC1
#define DES_RISC1
#endif

#ifndef DES_RISC2
#undef DES_RISC2
#endif

#if defined(DES_RISC1) && defined(DES_RISC2)
YOU SHOULD NOT HAVE BOTH DES_RISC1 AND DES_RISC2 DEFINED!!!!!
#endif

/* Unroll the inner loop, this sometimes helps, sometimes hinders.
 * Very mucy CPU dependant */
#ifndef DES_UNROLL
#define DES_UNROLL
#endif

#endif /* HEADER_DES_LOCL_H */

#ifndef __POWERPC__
#define MD32_XARRAY
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































Deleted Source/ccOpenssl/set_key.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/* crypto/des/set_key.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

/* set_key.c v 1.4 eay 24/9/91
 * 1.4 Speed up by 400% :-)
 * 1.3 added register declarations.
 * 1.2 unrolled make_key_sched a bit more
 * 1.1 added norm_expand_bits
 * 1.0 First working version
 */
#include "ccOpenssl/des_locl.h"

// OPENSSL_IMPLEMENT_GLOBAL(int,DES_check_key) = 0;	/* defaults to false */

#ifndef	_APPLE_COMMON_CRYPTO_

static const unsigned char odd_parity[256]={
  1,  1,  2,  2,  4,  4,  7,  7,  8,  8, 11, 11, 13, 13, 14, 14,
 16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31,
 32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47,
 49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62,
 64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79,
 81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94,
 97, 97, 98, 98,100,100,103,103,104,104,107,107,109,109,110,110,
112,112,115,115,117,117,118,118,121,121,122,122,124,124,127,127,
128,128,131,131,133,133,134,134,137,137,138,138,140,140,143,143,
145,145,146,146,148,148,151,151,152,152,155,155,157,157,158,158,
161,161,162,162,164,164,167,167,168,168,171,171,173,173,174,174,
176,176,179,179,181,181,182,182,185,185,186,186,188,188,191,191,
193,193,194,194,196,196,199,199,200,200,203,203,205,205,206,206,
208,208,211,211,213,213,214,214,217,217,218,218,220,220,223,223,
224,224,227,227,229,229,230,230,233,233,234,234,236,236,239,239,
241,241,242,242,244,244,247,247,248,248,251,251,253,253,254,254};

void DES_set_odd_parity(DES_cblock *key)
	{
	int i;

	for (i=0; i<DES_KEY_SZ; i++)
		(*key)[i]=odd_parity[(*key)[i]];
	}

int DES_check_key_parity(const_DES_cblock *key)
	{
	int i;

	for (i=0; i<DES_KEY_SZ; i++)
		{
		if ((*key)[i] != odd_parity[(*key)[i]])
			return(0);
		}
	return(1);
	}

/* Weak and semi week keys as take from
 * %A D.W. Davies
 * %A W.L. Price
 * %T Security for Computer Networks
 * %I John Wiley & Sons
 * %D 1984
 * Many thanks to smb@ulysses.att.com (Steven Bellovin) for the reference
 * (and actual cblock values).
 */
#define NUM_WEAK_KEY	16
static DES_cblock weak_keys[NUM_WEAK_KEY]={
	/* weak keys */
	{0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01},
	{0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE},
	{0x1F,0x1F,0x1F,0x1F,0x0E,0x0E,0x0E,0x0E},
	{0xE0,0xE0,0xE0,0xE0,0xF1,0xF1,0xF1,0xF1},
	/* semi-weak keys */
	{0x01,0xFE,0x01,0xFE,0x01,0xFE,0x01,0xFE},
	{0xFE,0x01,0xFE,0x01,0xFE,0x01,0xFE,0x01},
	{0x1F,0xE0,0x1F,0xE0,0x0E,0xF1,0x0E,0xF1},
	{0xE0,0x1F,0xE0,0x1F,0xF1,0x0E,0xF1,0x0E},
	{0x01,0xE0,0x01,0xE0,0x01,0xF1,0x01,0xF1},
	{0xE0,0x01,0xE0,0x01,0xF1,0x01,0xF1,0x01},
	{0x1F,0xFE,0x1F,0xFE,0x0E,0xFE,0x0E,0xFE},
	{0xFE,0x1F,0xFE,0x1F,0xFE,0x0E,0xFE,0x0E},
	{0x01,0x1F,0x01,0x1F,0x01,0x0E,0x01,0x0E},
	{0x1F,0x01,0x1F,0x01,0x0E,0x01,0x0E,0x01},
	{0xE0,0xFE,0xE0,0xFE,0xF1,0xFE,0xF1,0xFE},
	{0xFE,0xE0,0xFE,0xE0,0xFE,0xF1,0xFE,0xF1}};

int DES_is_weak_key(const_DES_cblock *key)
	{
	int i;

	for (i=0; i<NUM_WEAK_KEY; i++)
		/* Added == 0 to comparison, I obviously don't run
		 * this section very often :-(, thanks to
		 * engineering@MorningStar.Com for the fix
		 * eay 93/06/29
		 * Another problem, I was comparing only the first 4
		 * bytes, 97/03/18 */
		if (memcmp(weak_keys[i],key,sizeof(DES_cblock)) == 0) return(1);
	return(0);
	}

#endif	/* _APPLE_COMMON_CRYPTO_ */

/* NOW DEFINED IN des_local.h
 * See ecb_encrypt.c for a pseudo description of these macros. 
 * #define PERM_OP(a,b,t,n,m) ((t)=((((a)>>(n))^(b))&(m)),\
 * 	(b)^=(t),\
 * 	(a)=((a)^((t)<<(n))))
 */

#define HPERM_OP(a,t,n,m) ((t)=((((a)<<(16-(n)))^(a))&(m)),\
	(a)=(a)^(t)^(t>>(16-(n))))

static const DES_LONG des_skb[8][64]={
	{
	/* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
	0x00000000L,0x00000010L,0x20000000L,0x20000010L,
	0x00010000L,0x00010010L,0x20010000L,0x20010010L,
	0x00000800L,0x00000810L,0x20000800L,0x20000810L,
	0x00010800L,0x00010810L,0x20010800L,0x20010810L,
	0x00000020L,0x00000030L,0x20000020L,0x20000030L,
	0x00010020L,0x00010030L,0x20010020L,0x20010030L,
	0x00000820L,0x00000830L,0x20000820L,0x20000830L,
	0x00010820L,0x00010830L,0x20010820L,0x20010830L,
	0x00080000L,0x00080010L,0x20080000L,0x20080010L,
	0x00090000L,0x00090010L,0x20090000L,0x20090010L,
	0x00080800L,0x00080810L,0x20080800L,0x20080810L,
	0x00090800L,0x00090810L,0x20090800L,0x20090810L,
	0x00080020L,0x00080030L,0x20080020L,0x20080030L,
	0x00090020L,0x00090030L,0x20090020L,0x20090030L,
	0x00080820L,0x00080830L,0x20080820L,0x20080830L,
	0x00090820L,0x00090830L,0x20090820L,0x20090830L,
	},{
	/* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
	0x00000000L,0x02000000L,0x00002000L,0x02002000L,
	0x00200000L,0x02200000L,0x00202000L,0x02202000L,
	0x00000004L,0x02000004L,0x00002004L,0x02002004L,
	0x00200004L,0x02200004L,0x00202004L,0x02202004L,
	0x00000400L,0x02000400L,0x00002400L,0x02002400L,
	0x00200400L,0x02200400L,0x00202400L,0x02202400L,
	0x00000404L,0x02000404L,0x00002404L,0x02002404L,
	0x00200404L,0x02200404L,0x00202404L,0x02202404L,
	0x10000000L,0x12000000L,0x10002000L,0x12002000L,
	0x10200000L,0x12200000L,0x10202000L,0x12202000L,
	0x10000004L,0x12000004L,0x10002004L,0x12002004L,
	0x10200004L,0x12200004L,0x10202004L,0x12202004L,
	0x10000400L,0x12000400L,0x10002400L,0x12002400L,
	0x10200400L,0x12200400L,0x10202400L,0x12202400L,
	0x10000404L,0x12000404L,0x10002404L,0x12002404L,
	0x10200404L,0x12200404L,0x10202404L,0x12202404L,
	},{
	/* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
	0x00000000L,0x00000001L,0x00040000L,0x00040001L,
	0x01000000L,0x01000001L,0x01040000L,0x01040001L,
	0x00000002L,0x00000003L,0x00040002L,0x00040003L,
	0x01000002L,0x01000003L,0x01040002L,0x01040003L,
	0x00000200L,0x00000201L,0x00040200L,0x00040201L,
	0x01000200L,0x01000201L,0x01040200L,0x01040201L,
	0x00000202L,0x00000203L,0x00040202L,0x00040203L,
	0x01000202L,0x01000203L,0x01040202L,0x01040203L,
	0x08000000L,0x08000001L,0x08040000L,0x08040001L,
	0x09000000L,0x09000001L,0x09040000L,0x09040001L,
	0x08000002L,0x08000003L,0x08040002L,0x08040003L,
	0x09000002L,0x09000003L,0x09040002L,0x09040003L,
	0x08000200L,0x08000201L,0x08040200L,0x08040201L,
	0x09000200L,0x09000201L,0x09040200L,0x09040201L,
	0x08000202L,0x08000203L,0x08040202L,0x08040203L,
	0x09000202L,0x09000203L,0x09040202L,0x09040203L,
	},{
	/* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
	0x00000000L,0x00100000L,0x00000100L,0x00100100L,
	0x00000008L,0x00100008L,0x00000108L,0x00100108L,
	0x00001000L,0x00101000L,0x00001100L,0x00101100L,
	0x00001008L,0x00101008L,0x00001108L,0x00101108L,
	0x04000000L,0x04100000L,0x04000100L,0x04100100L,
	0x04000008L,0x04100008L,0x04000108L,0x04100108L,
	0x04001000L,0x04101000L,0x04001100L,0x04101100L,
	0x04001008L,0x04101008L,0x04001108L,0x04101108L,
	0x00020000L,0x00120000L,0x00020100L,0x00120100L,
	0x00020008L,0x00120008L,0x00020108L,0x00120108L,
	0x00021000L,0x00121000L,0x00021100L,0x00121100L,
	0x00021008L,0x00121008L,0x00021108L,0x00121108L,
	0x04020000L,0x04120000L,0x04020100L,0x04120100L,
	0x04020008L,0x04120008L,0x04020108L,0x04120108L,
	0x04021000L,0x04121000L,0x04021100L,0x04121100L,
	0x04021008L,0x04121008L,0x04021108L,0x04121108L,
	},{
	/* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
	0x00000000L,0x10000000L,0x00010000L,0x10010000L,
	0x00000004L,0x10000004L,0x00010004L,0x10010004L,
	0x20000000L,0x30000000L,0x20010000L,0x30010000L,
	0x20000004L,0x30000004L,0x20010004L,0x30010004L,
	0x00100000L,0x10100000L,0x00110000L,0x10110000L,
	0x00100004L,0x10100004L,0x00110004L,0x10110004L,
	0x20100000L,0x30100000L,0x20110000L,0x30110000L,
	0x20100004L,0x30100004L,0x20110004L,0x30110004L,
	0x00001000L,0x10001000L,0x00011000L,0x10011000L,
	0x00001004L,0x10001004L,0x00011004L,0x10011004L,
	0x20001000L,0x30001000L,0x20011000L,0x30011000L,
	0x20001004L,0x30001004L,0x20011004L,0x30011004L,
	0x00101000L,0x10101000L,0x00111000L,0x10111000L,
	0x00101004L,0x10101004L,0x00111004L,0x10111004L,
	0x20101000L,0x30101000L,0x20111000L,0x30111000L,
	0x20101004L,0x30101004L,0x20111004L,0x30111004L,
	},{
	/* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
	0x00000000L,0x08000000L,0x00000008L,0x08000008L,
	0x00000400L,0x08000400L,0x00000408L,0x08000408L,
	0x00020000L,0x08020000L,0x00020008L,0x08020008L,
	0x00020400L,0x08020400L,0x00020408L,0x08020408L,
	0x00000001L,0x08000001L,0x00000009L,0x08000009L,
	0x00000401L,0x08000401L,0x00000409L,0x08000409L,
	0x00020001L,0x08020001L,0x00020009L,0x08020009L,
	0x00020401L,0x08020401L,0x00020409L,0x08020409L,
	0x02000000L,0x0A000000L,0x02000008L,0x0A000008L,
	0x02000400L,0x0A000400L,0x02000408L,0x0A000408L,
	0x02020000L,0x0A020000L,0x02020008L,0x0A020008L,
	0x02020400L,0x0A020400L,0x02020408L,0x0A020408L,
	0x02000001L,0x0A000001L,0x02000009L,0x0A000009L,
	0x02000401L,0x0A000401L,0x02000409L,0x0A000409L,
	0x02020001L,0x0A020001L,0x02020009L,0x0A020009L,
	0x02020401L,0x0A020401L,0x02020409L,0x0A020409L,
	},{
	/* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
	0x00000000L,0x00000100L,0x00080000L,0x00080100L,
	0x01000000L,0x01000100L,0x01080000L,0x01080100L,
	0x00000010L,0x00000110L,0x00080010L,0x00080110L,
	0x01000010L,0x01000110L,0x01080010L,0x01080110L,
	0x00200000L,0x00200100L,0x00280000L,0x00280100L,
	0x01200000L,0x01200100L,0x01280000L,0x01280100L,
	0x00200010L,0x00200110L,0x00280010L,0x00280110L,
	0x01200010L,0x01200110L,0x01280010L,0x01280110L,
	0x00000200L,0x00000300L,0x00080200L,0x00080300L,
	0x01000200L,0x01000300L,0x01080200L,0x01080300L,
	0x00000210L,0x00000310L,0x00080210L,0x00080310L,
	0x01000210L,0x01000310L,0x01080210L,0x01080310L,
	0x00200200L,0x00200300L,0x00280200L,0x00280300L,
	0x01200200L,0x01200300L,0x01280200L,0x01280300L,
	0x00200210L,0x00200310L,0x00280210L,0x00280310L,
	0x01200210L,0x01200310L,0x01280210L,0x01280310L,
	},{
	/* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
	0x00000000L,0x04000000L,0x00040000L,0x04040000L,
	0x00000002L,0x04000002L,0x00040002L,0x04040002L,
	0x00002000L,0x04002000L,0x00042000L,0x04042000L,
	0x00002002L,0x04002002L,0x00042002L,0x04042002L,
	0x00000020L,0x04000020L,0x00040020L,0x04040020L,
	0x00000022L,0x04000022L,0x00040022L,0x04040022L,
	0x00002020L,0x04002020L,0x00042020L,0x04042020L,
	0x00002022L,0x04002022L,0x00042022L,0x04042022L,
	0x00000800L,0x04000800L,0x00040800L,0x04040800L,
	0x00000802L,0x04000802L,0x00040802L,0x04040802L,
	0x00002800L,0x04002800L,0x00042800L,0x04042800L,
	0x00002802L,0x04002802L,0x00042802L,0x04042802L,
	0x00000820L,0x04000820L,0x00040820L,0x04040820L,
	0x00000822L,0x04000822L,0x00040822L,0x04040822L,
	0x00002820L,0x04002820L,0x00042820L,0x04042820L,
	0x00002822L,0x04002822L,0x00042822L,0x04042822L,
	}};

#ifndef	_APPLE_COMMON_CRYPTO_
int DES_set_key(const_DES_cblock *key, DES_key_schedule *schedule)
	{
	if (DES_check_key)
		{
		return DES_set_key_checked(key, schedule);
		}
	else
		{
		DES_set_key_unchecked(key, schedule);
		return 0;
		}
	}

/* return 0 if key parity is odd (correct),
 * return -1 if key parity error,
 * return -2 if illegal weak key.
 */
int DES_set_key_checked(const_DES_cblock *key, DES_key_schedule *schedule)
	{
	if (!DES_check_key_parity(key))
		return(-1);
	if (DES_is_weak_key(key))
		return(-2);
	DES_set_key_unchecked(key, schedule);
	return 0;
	}

#endif	/* APPLE_COMMON_CRYPTO */

void DES_set_key_unchecked(const_DES_cblock *key, DES_key_schedule *schedule)
	{
	static int shifts2[16]={0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0};
	register DES_LONG c,d,t,s,t2;
	register const unsigned char *in;
	register DES_LONG *k;
	register int i;

#ifdef OPENBSD_DEV_CRYPTO
	memcpy(schedule->key,key,sizeof schedule->key);
	schedule->session=NULL;
#endif
	k = &schedule->ks->deslong[0];
	in = &(*key)[0];

	c2l(in,c);
	c2l(in,d);

	/* do PC1 in 47 simple operations :-)
	 * Thanks to John Fletcher (john_fletcher@lccmail.ocf.llnl.gov)
	 * for the inspiration. :-) */
	PERM_OP (d,c,t,4,0x0f0f0f0fL);
	HPERM_OP(c,t,-2,0xcccc0000L);
	HPERM_OP(d,t,-2,0xcccc0000L);
	PERM_OP (d,c,t,1,0x55555555L);
	PERM_OP (c,d,t,8,0x00ff00ffL);
	PERM_OP (d,c,t,1,0x55555555L);
	d=	(((d&0x000000ffL)<<16L)| (d&0x0000ff00L)     |
		 ((d&0x00ff0000L)>>16L)|((c&0xf0000000L)>>4L));
	c&=0x0fffffffL;

	for (i=0; i<ITERATIONS; i++)
		{
		if (shifts2[i])
			{ c=((c>>2L)|(c<<26L)); d=((d>>2L)|(d<<26L)); }
		else
			{ c=((c>>1L)|(c<<27L)); d=((d>>1L)|(d<<27L)); }
		c&=0x0fffffffL;
		d&=0x0fffffffL;
		/* could be a few less shifts but I am to lazy at this
		 * point in time to investigate */
		s=	des_skb[0][ (c    )&0x3f                ]|
			des_skb[1][((c>> 6L)&0x03)|((c>> 7L)&0x3c)]|
			des_skb[2][((c>>13L)&0x0f)|((c>>14L)&0x30)]|
			des_skb[3][((c>>20L)&0x01)|((c>>21L)&0x06) |
						  ((c>>22L)&0x38)];
		t=	des_skb[4][ (d    )&0x3f                ]|
			des_skb[5][((d>> 7L)&0x03)|((d>> 8L)&0x3c)]|
			des_skb[6][ (d>>15L)&0x3f                ]|
			des_skb[7][((d>>21L)&0x0f)|((d>>22L)&0x30)];

		/* table contained 0213 4657 */
		t2=((t<<16L)|(s&0x0000ffffL))&0xffffffffL;
		*(k++)=ROTATE(t2,30)&0xffffffffL;

		t2=((s>>16L)|(t&0xffff0000L));
		*(k++)=ROTATE(t2,26)&0xffffffffL;
		}
	}

#ifndef	_APPLE_COMMON_CRYPTO_
int DES_key_sched(const_DES_cblock *key, DES_key_schedule *schedule)
	{
	return(DES_set_key(key,schedule));
	}
#endif	/* _APPLE_COMMON_CRYPTO_ */

/*
#undef des_fixup_key_parity
void des_fixup_key_parity(des_cblock *key)
	{
	des_set_odd_parity(key);
	}
*/
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/ccOpenssl/spr.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/* crypto/des/spr.h */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include <CommonCrypto/CommonCryptoPriv.h>
#ifdef	_APPLE_COMMON_CRYPTO_
/* avoid symbol collision with libSystem & libcrypto */
#define DES_SPtrans CC_DES_SPtrans
#endif	/* _APPLE_COMMON_CRYPTO_ */

const DES_LONG DES_SPtrans[8][64]={
{
/* nibble 0 */
0x02080800L, 0x00080000L, 0x02000002L, 0x02080802L,
0x02000000L, 0x00080802L, 0x00080002L, 0x02000002L,
0x00080802L, 0x02080800L, 0x02080000L, 0x00000802L,
0x02000802L, 0x02000000L, 0x00000000L, 0x00080002L,
0x00080000L, 0x00000002L, 0x02000800L, 0x00080800L,
0x02080802L, 0x02080000L, 0x00000802L, 0x02000800L,
0x00000002L, 0x00000800L, 0x00080800L, 0x02080002L,
0x00000800L, 0x02000802L, 0x02080002L, 0x00000000L,
0x00000000L, 0x02080802L, 0x02000800L, 0x00080002L,
0x02080800L, 0x00080000L, 0x00000802L, 0x02000800L,
0x02080002L, 0x00000800L, 0x00080800L, 0x02000002L,
0x00080802L, 0x00000002L, 0x02000002L, 0x02080000L,
0x02080802L, 0x00080800L, 0x02080000L, 0x02000802L,
0x02000000L, 0x00000802L, 0x00080002L, 0x00000000L,
0x00080000L, 0x02000000L, 0x02000802L, 0x02080800L,
0x00000002L, 0x02080002L, 0x00000800L, 0x00080802L,
},{
/* nibble 1 */
0x40108010L, 0x00000000L, 0x00108000L, 0x40100000L,
0x40000010L, 0x00008010L, 0x40008000L, 0x00108000L,
0x00008000L, 0x40100010L, 0x00000010L, 0x40008000L,
0x00100010L, 0x40108000L, 0x40100000L, 0x00000010L,
0x00100000L, 0x40008010L, 0x40100010L, 0x00008000L,
0x00108010L, 0x40000000L, 0x00000000L, 0x00100010L,
0x40008010L, 0x00108010L, 0x40108000L, 0x40000010L,
0x40000000L, 0x00100000L, 0x00008010L, 0x40108010L,
0x00100010L, 0x40108000L, 0x40008000L, 0x00108010L,
0x40108010L, 0x00100010L, 0x40000010L, 0x00000000L,
0x40000000L, 0x00008010L, 0x00100000L, 0x40100010L,
0x00008000L, 0x40000000L, 0x00108010L, 0x40008010L,
0x40108000L, 0x00008000L, 0x00000000L, 0x40000010L,
0x00000010L, 0x40108010L, 0x00108000L, 0x40100000L,
0x40100010L, 0x00100000L, 0x00008010L, 0x40008000L,
0x40008010L, 0x00000010L, 0x40100000L, 0x00108000L,
},{
/* nibble 2 */
0x04000001L, 0x04040100L, 0x00000100L, 0x04000101L,
0x00040001L, 0x04000000L, 0x04000101L, 0x00040100L,
0x04000100L, 0x00040000L, 0x04040000L, 0x00000001L,
0x04040101L, 0x00000101L, 0x00000001L, 0x04040001L,
0x00000000L, 0x00040001L, 0x04040100L, 0x00000100L,
0x00000101L, 0x04040101L, 0x00040000L, 0x04000001L,
0x04040001L, 0x04000100L, 0x00040101L, 0x04040000L,
0x00040100L, 0x00000000L, 0x04000000L, 0x00040101L,
0x04040100L, 0x00000100L, 0x00000001L, 0x00040000L,
0x00000101L, 0x00040001L, 0x04040000L, 0x04000101L,
0x00000000L, 0x04040100L, 0x00040100L, 0x04040001L,
0x00040001L, 0x04000000L, 0x04040101L, 0x00000001L,
0x00040101L, 0x04000001L, 0x04000000L, 0x04040101L,
0x00040000L, 0x04000100L, 0x04000101L, 0x00040100L,
0x04000100L, 0x00000000L, 0x04040001L, 0x00000101L,
0x04000001L, 0x00040101L, 0x00000100L, 0x04040000L,
},{
/* nibble 3 */
0x00401008L, 0x10001000L, 0x00000008L, 0x10401008L,
0x00000000L, 0x10400000L, 0x10001008L, 0x00400008L,
0x10401000L, 0x10000008L, 0x10000000L, 0x00001008L,
0x10000008L, 0x00401008L, 0x00400000L, 0x10000000L,
0x10400008L, 0x00401000L, 0x00001000L, 0x00000008L,
0x00401000L, 0x10001008L, 0x10400000L, 0x00001000L,
0x00001008L, 0x00000000L, 0x00400008L, 0x10401000L,
0x10001000L, 0x10400008L, 0x10401008L, 0x00400000L,
0x10400008L, 0x00001008L, 0x00400000L, 0x10000008L,
0x00401000L, 0x10001000L, 0x00000008L, 0x10400000L,
0x10001008L, 0x00000000L, 0x00001000L, 0x00400008L,
0x00000000L, 0x10400008L, 0x10401000L, 0x00001000L,
0x10000000L, 0x10401008L, 0x00401008L, 0x00400000L,
0x10401008L, 0x00000008L, 0x10001000L, 0x00401008L,
0x00400008L, 0x00401000L, 0x10400000L, 0x10001008L,
0x00001008L, 0x10000000L, 0x10000008L, 0x10401000L,
},{
/* nibble 4 */
0x08000000L, 0x00010000L, 0x00000400L, 0x08010420L,
0x08010020L, 0x08000400L, 0x00010420L, 0x08010000L,
0x00010000L, 0x00000020L, 0x08000020L, 0x00010400L,
0x08000420L, 0x08010020L, 0x08010400L, 0x00000000L,
0x00010400L, 0x08000000L, 0x00010020L, 0x00000420L,
0x08000400L, 0x00010420L, 0x00000000L, 0x08000020L,
0x00000020L, 0x08000420L, 0x08010420L, 0x00010020L,
0x08010000L, 0x00000400L, 0x00000420L, 0x08010400L,
0x08010400L, 0x08000420L, 0x00010020L, 0x08010000L,
0x00010000L, 0x00000020L, 0x08000020L, 0x08000400L,
0x08000000L, 0x00010400L, 0x08010420L, 0x00000000L,
0x00010420L, 0x08000000L, 0x00000400L, 0x00010020L,
0x08000420L, 0x00000400L, 0x00000000L, 0x08010420L,
0x08010020L, 0x08010400L, 0x00000420L, 0x00010000L,
0x00010400L, 0x08010020L, 0x08000400L, 0x00000420L,
0x00000020L, 0x00010420L, 0x08010000L, 0x08000020L,
},{
/* nibble 5 */
0x80000040L, 0x00200040L, 0x00000000L, 0x80202000L,
0x00200040L, 0x00002000L, 0x80002040L, 0x00200000L,
0x00002040L, 0x80202040L, 0x00202000L, 0x80000000L,
0x80002000L, 0x80000040L, 0x80200000L, 0x00202040L,
0x00200000L, 0x80002040L, 0x80200040L, 0x00000000L,
0x00002000L, 0x00000040L, 0x80202000L, 0x80200040L,
0x80202040L, 0x80200000L, 0x80000000L, 0x00002040L,
0x00000040L, 0x00202000L, 0x00202040L, 0x80002000L,
0x00002040L, 0x80000000L, 0x80002000L, 0x00202040L,
0x80202000L, 0x00200040L, 0x00000000L, 0x80002000L,
0x80000000L, 0x00002000L, 0x80200040L, 0x00200000L,
0x00200040L, 0x80202040L, 0x00202000L, 0x00000040L,
0x80202040L, 0x00202000L, 0x00200000L, 0x80002040L,
0x80000040L, 0x80200000L, 0x00202040L, 0x00000000L,
0x00002000L, 0x80000040L, 0x80002040L, 0x80202000L,
0x80200000L, 0x00002040L, 0x00000040L, 0x80200040L,
},{
/* nibble 6 */
0x00004000L, 0x00000200L, 0x01000200L, 0x01000004L,
0x01004204L, 0x00004004L, 0x00004200L, 0x00000000L,
0x01000000L, 0x01000204L, 0x00000204L, 0x01004000L,
0x00000004L, 0x01004200L, 0x01004000L, 0x00000204L,
0x01000204L, 0x00004000L, 0x00004004L, 0x01004204L,
0x00000000L, 0x01000200L, 0x01000004L, 0x00004200L,
0x01004004L, 0x00004204L, 0x01004200L, 0x00000004L,
0x00004204L, 0x01004004L, 0x00000200L, 0x01000000L,
0x00004204L, 0x01004000L, 0x01004004L, 0x00000204L,
0x00004000L, 0x00000200L, 0x01000000L, 0x01004004L,
0x01000204L, 0x00004204L, 0x00004200L, 0x00000000L,
0x00000200L, 0x01000004L, 0x00000004L, 0x01000200L,
0x00000000L, 0x01000204L, 0x01000200L, 0x00004200L,
0x00000204L, 0x00004000L, 0x01004204L, 0x01000000L,
0x01004200L, 0x00000004L, 0x00004004L, 0x01004204L,
0x01000004L, 0x01004200L, 0x01004000L, 0x00004004L,
},{
/* nibble 7 */
0x20800080L, 0x20820000L, 0x00020080L, 0x00000000L,
0x20020000L, 0x00800080L, 0x20800000L, 0x20820080L,
0x00000080L, 0x20000000L, 0x00820000L, 0x00020080L,
0x00820080L, 0x20020080L, 0x20000080L, 0x20800000L,
0x00020000L, 0x00820080L, 0x00800080L, 0x20020000L,
0x20820080L, 0x20000080L, 0x00000000L, 0x00820000L,
0x20000000L, 0x00800000L, 0x20020080L, 0x20800080L,
0x00800000L, 0x00020000L, 0x20820000L, 0x00000080L,
0x00800000L, 0x00020000L, 0x20000080L, 0x20820080L,
0x00020080L, 0x20000000L, 0x00000000L, 0x00820000L,
0x20800080L, 0x20020080L, 0x20020000L, 0x00800080L,
0x20820000L, 0x00000080L, 0x00800080L, 0x20020000L,
0x20820080L, 0x00800000L, 0x20800000L, 0x20000080L,
0x00820000L, 0x00020080L, 0x20020080L, 0x20800000L,
0x00000080L, 0x20820000L, 0x00820080L, 0x00000000L,
0x20000000L, 0x20800080L, 0x00020000L, 0x00820080L,
}};
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































































































































































































































































































Added Source/ccUtilities/byteBuffer.c.























































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/*                                                                              
 * Copyright (c) 2011 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  printByteBuffer.c
 *  byteutils
 */

#include "ccMemory.h"
#include "byteBuffer.h"

void printBytes(uint8_t *buff, size_t len, char *name)
{
	int i;
	printf("Dumping %d bytes from %s\n", (int) len, name);
	for(i=0; i<len; i++) {
		if(i > 0 && !(i%8)) putchar(' ');
		if(i > 0 && !(i%64)) putchar('\n');
		printf("%02x", buff[i]);
	}
	putchar('\n');
}

void printByteBuffer(byteBuffer bb, char *name)
{
    printBytes(bb->bytes, bb->len, name);
}


byteBuffer
mallocByteBuffer(size_t len)
{
	byteBuffer retval;
	if((retval = (byteBuffer) CC_XMALLOC(sizeof(byteBufferStruct) + len + 1)) == NULL) return NULL;
    retval->len = len;
    retval->size = sizeof(byteBufferStruct) + len + 1;
    retval->bytes = (uint8_t *) (retval + 1) ; /* just past the byteBuffer in malloc'ed space */
    return retval;
}

void
freeByteBuffer(byteBuffer b)
{
    CC_XFREE(b, b->size);
}


/* utility function to convert hex character representation to their nibble (4 bit) values */
static uint8_t
nibbleFromChar(char c)
{
	if(c >= '0' && c <= '9') return c - '0';
	if(c >= 'a' && c <= 'f') return c - 'a' + 10;
	if(c >= 'A' && c <= 'F') return c - 'A' + 10;
	return 255;
}

/* Convert a string of characters representing a hex buffer into a series of bytes of that real value */
byteBuffer
hexStringToBytes(char *inhex)
{
	byteBuffer retval;
	uint8_t *p;
	int len, i;
	
	len = (int) strlen(inhex) / 2;
	if((retval = mallocByteBuffer(len)) == NULL) return NULL;
    
	for(i=0, p = (uint8_t *) inhex; i<len; i++) {
		retval->bytes[i] = (nibbleFromChar(*p) << 4) | nibbleFromChar(*(p+1));
		p += 2;
	}
    retval->bytes[len] = 0;
	return retval;
}

byteBuffer
bytesToBytes(void *bytes, size_t len)
{
    byteBuffer retval = mallocByteBuffer(len);
    CC_XMEMCPY(retval->bytes, bytes, len);
    return retval;
}

int
bytesAreEqual(byteBuffer b1, byteBuffer b2)
{
    if(b1->len != b2->len) return 0;
    return (CC_XMEMCMP(b1->bytes, b2->bytes, b1->len) == 0);
}


static char byteMap[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
static int byteMapLen = sizeof(byteMap);

/* Utility function to convert nibbles (4 bit values) into a hex character representation */
static char
nibbleToChar(uint8_t nibble)
{
	if(nibble < byteMapLen) return byteMap[nibble];
	return '*';
}

/* Convert a buffer of binary values into a hex string representation */
char
*bytesToHexString(byteBuffer bb)
{
	char *retval;
	int i;
	
	retval = CC_XMALLOC(bb->len*2 + 1);
	for(i=0; i<bb->len; i++) {
		retval[i*2] = nibbleToChar(bb->bytes[i] >> 4);
		retval[i*2+1] = nibbleToChar(bb->bytes[i] & 0x0f);
	}
    retval[bb->len*2] = 0;
	return retval;
}

Added Source/ccUtilities/byteBuffer.h.





































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*                                                                              
 * Copyright (c) 2011 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
*/

/*
 *  printByteBuffer.h
 *  byteutils
 *
 */

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#ifndef _BYTEBUFFER_H_
#define _BYTEBUFFER_H_

typedef struct byte_buf {
    size_t  len;
    size_t  size;
    uint8_t  *bytes;
} byteBufferStruct, *byteBuffer;

void printByteBuffer(byteBuffer bb, char *name);

void printBytes(uint8_t *buff, size_t len, char *name);

byteBuffer
mallocByteBuffer(size_t len);

void
freeByteBuffer(byteBuffer b);

byteBuffer
hexStringToBytes(char *inhex);

byteBuffer
bytesToBytes(void *bytes, size_t len);

int
bytesAreEqual(byteBuffer b1, byteBuffer b2);

char
*bytesToHexString(byteBuffer bytes);

#endif /* _BYTEBUFFER_H_ */

Added Source/ccUtilities/ccErrors.h.











































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/*                                                                              
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ccErrors.h
 *  CommonCrypto
 */

#include "CommonCryptor.h"
#ifndef CCERRORS_H
#define CCERRORS_H

#define CONTEXT_SIZE_CHK(CCCTX,DIGESTDI) (sizeof(CCCTX) < ccdigest_di_size(DIGESTDI))
#define CC_NONULLPARM(X) if(NULL==(X)) return kCCParamError

#endif /* CCERRORS_H */

Added Source/ccUtilities/ccMemory.h.

















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*                                                                              
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ccMemory.h
 *  CommonCrypto
 */

#ifndef CCMEMORY_H
#define CCMEMORY_H

#ifdef KERNEL
#define	CC_XMALLOC(s)  OSMalloc((s), CC_OSMallocTag)
#define	CC_XFREE(p, s) OSFree((p), (s), CC_OSMallocTag)
#else /* KERNEL */
#include <stdlib.h>
#include <string.h>

#define CC_XMALLOC(s)  malloc(s)
#define CC_XCALLOC(c, s) calloc((c), (s))
#define CC_XREALLOC(p, s) realloc((p), (s))
#define CC_XFREE(p, s)    free(p)
#define CC_XMEMCPY(s1, s2, n) memcpy((s1), (s2), (n))
#define CC_XMEMCMP(s1, s2, n) memcmp((s1), (s2), (n))
#define CC_XMEMSET(s1, s2, n) memset((s1), (s2), (n))
#define CC_XZEROMEM(p, n)	memset((p), 0, (n))
#define CC_XSTRCMP(s1, s2) strcmp((s1), (s2))
#define CC_XSTORE32H(x, y) do {						\
(y)[0] = (unsigned char)(((x)>>24)&255);			\
(y)[1] = (unsigned char)(((x)>>16)&255);			\
(y)[2] = (unsigned char)(((x)>>8)&255);				\
(y)[3] = (unsigned char)((x)&255);				\
} while(0)
#define CC_XSTORE64H(x, y)                                                                     \
{ (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255);     \
(y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255);     \
(y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255);     \
(y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }



#define CC_XQSORT(base, nelement, width, comparfunc) qsort((base), (nelement), (width), (comparfunc))

#define CC_XALIGNED(PTR,NBYTE) (!(((size_t)(PTR))%(NBYTE)))

#define CC_XMIN(X,Y) (((X) < (Y)) ? (X): (Y))
#endif




#endif /* CCMEMORY_H */

Changes to Source/ccUtilities/ccdebug.c.

19
20
21
22
23
24
25
26
27
28

29
30
31
32
33
34
35


36

37
38
39
40
41
42
43
44
45
46


47
48
49
50
51
52
53

54
55

56
57
58
59
60
61
62
63
64
65

66
67
68

 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ccdebug.c - CommonCrypto debug macros
 *  MacTomCrypt
 *
 */


#include "ccdebug.h"
#include <stdlib.h>
#include <asl.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>




static char *std_log_prefix = "###CommonCrypto Function: %s - %s";
static const char *std_ident = "CommonCrypto";
static const char *std_facility = "CipherSuite";
static uint32_t	std_options = 0;

static aslclient aslhandle = NULL;
static aslmsg msgptr = NULL;

static void
ccdebug_init() {


	char *ccEnvStdErr = getenv("CC_STDERR");
	
	if(ccEnvStdErr != NULL && strncmp(ccEnvStdErr, "yes", 3) == 0) std_options |= ASL_OPT_STDERR;
	aslhandle = asl_open(std_ident, std_facility, std_options);

	msgptr = asl_new(ASL_TYPE_MSG);
	asl_set(msgptr, ASL_KEY_FACILITY, "com.apple.infosec");

}
	

	
void
ccdebug_imp(int level, char *funcname, char *format, ...) {
	va_list argp;
	char fmtbuffer[256];

	if(aslhandle == NULL) ccdebug_init();
	
	sprintf(fmtbuffer, std_log_prefix, funcname, format);
	va_start(argp, format);

	asl_vlog(aslhandle, msgptr, level, fmtbuffer, argp);
	va_end(argp);
}








<


>







>
>

>
|


|






>
>
|
|
|
|
<
|
|
>


>
|



|

|

<

>



>
19
20
21
22
23
24
25

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

56
57
58
59
60
61
62
63
64
65
66
67
68
69

70
71
72
73
74
75
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ccdebug.c - CommonCrypto debug macros

 *
 */


#include "ccdebug.h"
#include <stdlib.h>
#include <asl.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <dispatch/dispatch.h>
#include <dispatch/queue.h>


static char *std_log_prefix = "###CommonCrypto : %s - %s";
static const char *std_ident = "CommonCrypto";
static const char *std_facility = "CipherSuite";
static uint32_t	 std_options = 0;

static aslclient aslhandle = NULL;
static aslmsg msgptr = NULL;

static void
ccdebug_init() {
    static dispatch_once_t init;
    dispatch_once(&init, ^{
        char *ccEnvStdErr = getenv("CC_STDERR");
        
        if(ccEnvStdErr != NULL && strncmp(ccEnvStdErr, "yes", 3) == 0) std_options |= ASL_OPT_STDERR;
        aslhandle = asl_open(std_ident, std_facility, std_options);

        msgptr = asl_new(ASL_TYPE_MSG);
        asl_set(msgptr, ASL_KEY_FACILITY, "com.apple.platformsec");
    });
}
	
#define LINESIZE 256

void
ccdebug_imp(int level, char *funcname, char *format, ...) {
	va_list argp;
	char fmtbuffer[LINESIZE];

	ccdebug_init();
	

	va_start(argp, format);
	snprintf(fmtbuffer, LINESIZE, std_log_prefix, funcname, format);
	asl_vlog(aslhandle, msgptr, level, fmtbuffer, argp);
	va_end(argp);
}

Changes to Source/ccUtilities/ccdebug.h.

1
2
3
4
5
6
7
8
9
/* 
 * Copyright (c) 2004 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
|
|







1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
19
20
21
22
23
24
25
26
27
28






































29
30
31
32
33
34
35
36
37
38
39
40


41
42

43
44


 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ccdebug.h - CommonCrypto debug macros
 *  MacTomCrypt
 *
 */







































#include <asl.h>
#include <stdarg.h>

#define CC_DEBUG_FAILURE		ASL_LEVEL_EMERG
#define CC_DEBUG_BUG			ASL_LEVEL_ERR
#define CC_DEBUG					ASL_LEVEL_DEBUG

void ccdebug_imp(int level, char *funcname, char *format, ...);

#ifdef DEBUG
#define ccdebug(lvl,fmt,...) ccdebug_imp(lvl, __PRETTY_FUNCTION__, fmt, __VA_ARGS__)


#else
#define ccdebug(lvl,fmt,...) {}

#endif










<


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>






|



|
|
>
>

|
>
|

>
>
19
20
21
22
23
24
25

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ccdebug.h - CommonCrypto debug macros

 *
 */

#if defined(COMMON_DIGEST_FUNCTIONS) || defined(COMMON_CMAC_FUNCTIONS) || defined(COMMON_GCM_FUNCTIONS) \
    || defined (COMMON_AESSHOEFLY_FUNCTIONS) || defined(COMMON_CASTSHOEFLY_FUNCTIONS) \
    || defined (COMMON_CRYPTOR_FUNCTIONS) || defined(COMMON_HMAC_FUNCTIONS) \
    || defined(COMMON_KEYDERIVATION_FUNCTIONS) || defined(COMMON_SYMMETRIC_KEYWRAP_FUNCTIONS) \
    || defined(COMMON_RSA_FUNCTIONS) || defined(COMMON_EC_FUNCTIONS) || defined(COMMON_DH_FUNCTIONS) \
    || defined(COMMON_BIGNUM_FUNCTIONS) || defined(COMMON_RANDOM_FUNCTIONS)

#define DIAGNOSTIC
#endif

#ifdef KERNEL
#include <stdarg.h>

#define	CC_DEBUG		 1
#define	CC_DEBUG_BUG		2
#define	CC_DEBUG_FAILURE	3

#if DIAGNOSTIC
#define CC_DEBUG_LOG(lvl, fmt, ...) do {				      \
	const char *lvl_type[] = { "INVALID", "DEBUG", "ERROR", "FAILURE" };  \
	char fmtbuffer[256]; 						      \
	int l = lvl;							      \
									      \
	if (l < 0 || l > 3) l = 0;					      \
	snprintf(fmtbuffer, sizeof(fmtbuffer),				      \
	    "CommonCrypto Function: %s:%d (%s) - %s", __FILE__, __LINE__,     \
	    lvl_type[l], fmt);					              \
	printf(fmtbuffer, __VA_ARGS__);		      			      \
} while (0)

#else

#define CC_DEBUG_LOG(lvl,fmt,...) {}

#endif /* DIAGNOSTIC */

#else

#include <asl.h>
#include <stdarg.h>

#define CC_DEBUG_FAILURE		ASL_LEVEL_EMERG
#define CC_DEBUG_BUG			ASL_LEVEL_ERR
#define CC_DEBUG			ASL_LEVEL_ERR

void ccdebug_imp(int level, char *funcname, char *format, ...);

#ifdef DIAGNOSTIC

#define CC_DEBUG_LOG(lvl,...) ccdebug_imp(lvl, __FUNCTION__, __VA_ARGS__)

#else

#define CC_DEBUG_LOG(lvl,...) {}
#endif /* DEBUG */

#endif /* KERNEL */

Added Source/descriptors/corecryptoSymmetricBridge.c.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/*                                                                              
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include "corecryptoSymmetricBridge.h"
#include "ccMemory.h"
#include <corecrypto/ccrc4.h>

static void *noMode(void) { return NULL; }

// RC4 as a mode trick ...

void rc4ModeInit(const struct ccmode_ofb *ofb, void *ctx,
             unsigned long key_len, const void *key,
             const void *iv)
{
    ccrc4_eay.init(ctx, key_len, key);
}

void rc4crypt(void *ctx, unsigned long nbytes, const void *in, void *out)
{
    ccrc4_eay.crypt(ctx, nbytes, in, out);
}

typedef struct eay_rc4_key_st
{
	uint32_t x,y;
	uint32_t data[256];
} eay_RC4_KEY;

struct ccmode_ofb rc4mode = {
    .size = sizeof(eay_RC4_KEY),
    .block_size = 1,
    .init = rc4ModeInit,
    .ofb = rc4crypt,
};



struct ccmode_ofb *cc_rc4_crypt_mode(void)
{
    return &rc4mode;
}


// 2 dimensional array of various mode/cipher contexts
// encrypt/decrypt x algorithm matching the list in CommonCryptor.h

modeList ccmodeList[7][2] = {
    { // AES
        { ccaes_ecb_encrypt_mode, ccaes_cbc_encrypt_mode, ccaes_cfb_encrypt_mode, ccaes_cfb8_encrypt_mode, ccaes_ctr_crypt_mode, ccaes_ofb_crypt_mode, ccaes_xts_encrypt_mode, ccaes_gcm_encrypt_mode },
        { ccaes_ecb_decrypt_mode, ccaes_cbc_decrypt_mode, ccaes_cfb_decrypt_mode, ccaes_cfb8_decrypt_mode, ccaes_ctr_crypt_mode, ccaes_ofb_crypt_mode, ccaes_xts_decrypt_mode, ccaes_gcm_decrypt_mode }
    },
    
    { // DES
        { ccdes_ecb_encrypt_mode, ccdes_cbc_encrypt_mode, ccdes_cfb_encrypt_mode, ccdes_cfb8_encrypt_mode, ccdes_ctr_crypt_mode, ccdes_ofb_crypt_mode, noMode, noMode },
        { ccdes_ecb_decrypt_mode, ccdes_cbc_decrypt_mode, ccdes_cfb_decrypt_mode, ccdes_cfb8_decrypt_mode, ccdes_ctr_crypt_mode, ccdes_ofb_crypt_mode, noMode, noMode }
    },
    
    { // DES3
        { ccdes3_ecb_encrypt_mode, ccdes3_cbc_encrypt_mode, ccdes3_cfb_encrypt_mode, ccdes3_cfb8_encrypt_mode, ccdes3_ctr_crypt_mode, ccdes3_ofb_crypt_mode, noMode, noMode },
        { ccdes3_ecb_decrypt_mode, ccdes3_cbc_decrypt_mode, ccdes3_cfb_decrypt_mode, ccdes3_cfb8_decrypt_mode, ccdes3_ctr_crypt_mode, ccdes3_ofb_crypt_mode, noMode, noMode }
    },
    
    { // CAST
        { cccast_ecb_encrypt_mode, cccast_cbc_encrypt_mode, cccast_cfb_encrypt_mode, cccast_cfb8_encrypt_mode, cccast_ctr_crypt_mode, cccast_ofb_crypt_mode, noMode, noMode },
        { cccast_ecb_decrypt_mode, cccast_cbc_decrypt_mode, cccast_cfb_decrypt_mode, cccast_cfb8_decrypt_mode, cccast_ctr_crypt_mode, cccast_ofb_crypt_mode, noMode, noMode }
    },
    
    { // RC4 - hijack OFB to put in streaming cipher descriptor
        { noMode, noMode, noMode, noMode, noMode, cc_rc4_crypt_mode, noMode, noMode },
        { noMode, noMode, noMode, noMode, noMode, cc_rc4_crypt_mode, noMode, noMode }
    },

    
    { // RC2
        { ccrc2_ecb_encrypt_mode, ccrc2_cbc_encrypt_mode, ccrc2_cfb_encrypt_mode, ccrc2_cfb8_encrypt_mode, ccrc2_ctr_crypt_mode, ccrc2_ofb_crypt_mode, noMode, noMode },
        { ccrc2_ecb_decrypt_mode, ccrc2_cbc_decrypt_mode, ccrc2_cfb_decrypt_mode, ccrc2_cfb8_decrypt_mode, ccrc2_ctr_crypt_mode, ccrc2_ofb_crypt_mode, noMode, noMode }
    },

    { // Blowfish
        { ccblowfish_ecb_encrypt_mode, ccblowfish_cbc_encrypt_mode, ccblowfish_cfb_encrypt_mode, ccblowfish_cfb8_encrypt_mode, ccblowfish_ctr_crypt_mode, ccblowfish_ofb_crypt_mode, noMode, noMode },
        { ccblowfish_ecb_decrypt_mode, ccblowfish_cbc_decrypt_mode, ccblowfish_cfb_decrypt_mode, ccblowfish_cfb8_decrypt_mode, ccblowfish_ctr_crypt_mode, ccblowfish_ofb_crypt_mode, noMode, noMode }
    },
};


// Thunks
//ECB

static size_t ccecb_mode_get_ctx_size(corecryptoMode modeObject) { return modeObject.ecb->size; }
static size_t ccecb_mode_get_block_size(corecryptoMode modeObject) { return modeObject.ecb->block_size; }
static void ccecb_mode_setup(corecryptoMode modeObj, const void *IV,
                             const void *key, size_t keylen, const void *tweak,
                             int tweaklen, int options, modeCtx ctx)
{
    modeObj.ecb->init(modeObj.ecb, ctx.ecb, keylen, key);
}

static void ccecb_mode_crypt(corecryptoMode modeObj, const void *in, void *out, size_t len, modeCtx ctx)
{
    modeObj.ecb->ecb(ctx.ecb, len / ccecb_mode_get_block_size(modeObj), in, out);
}

cc2CCModeDescriptor ccecb_mode = {
    .mode_get_ctx_size = ccecb_mode_get_ctx_size,
    .mode_get_block_size = ccecb_mode_get_block_size,
    .mode_setup = ccecb_mode_setup,
    .mode_encrypt = ccecb_mode_crypt,
    .mode_decrypt = ccecb_mode_crypt,
    .mode_encrypt_tweaked = NULL,
    .mode_decrypt_tweaked = NULL,
    .mode_done = NULL,
    .mode_setiv = NULL,
    .mode_getiv = NULL
};

// CBC

static size_t cccbc_mode_get_ctx_size(corecryptoMode modeObject) { return modeObject.cbc->size + 16; }
static size_t cccbc_mode_get_block_size(corecryptoMode modeObject) { return modeObject.cbc->block_size; }
static void cccbc_mode_setup(corecryptoMode modeObj, const void *iv,
                             const void *key, size_t keylen, const void *tweak,
                             size_t tweaklen, int options, modeCtx ctx)
{
    CC_XMEMCPY(ctx.cbc->iv, iv, modeObj.cbc->block_size);
    modeObj.cbc->init(modeObj.cbc, &ctx.cbc->cbc, keylen, key);
}

static void cccbc_mode_crypt(corecryptoMode modeObj, const void *in, void *out, size_t len, modeCtx ctx)
{
    modeObj.cbc->cbc(&ctx.cbc->cbc, ctx.cbc->iv, len / cccbc_mode_get_block_size(modeObj), in, out);
}

static int cccbc_getiv(corecryptoMode modeObj, void *iv, uint32_t *len, modeCtx ctx)
{
    if(*len < cccbc_mode_get_block_size(modeObj)) {
        *len = cccbc_mode_get_block_size(modeObj);
        return -1;
    }
    uint8_t tmp[cccbc_mode_get_block_size(modeObj)];
    CC_XMEMCPY(iv, ctx.cbc->iv, *len = cccbc_mode_get_block_size(modeObj));
    return 0;
}

static int cccbc_setiv(corecryptoMode modeObj, const void *iv, uint32_t len, modeCtx ctx)
{
    uint8_t tmp[cccbc_mode_get_block_size(modeObj)];
    if(len != cccbc_mode_get_block_size(modeObj)) return -1;
    CC_XMEMCPY(ctx.cbc->iv, iv, cccbc_mode_get_block_size(modeObj));
    return 0;
}

cc2CCModeDescriptor cccbc_mode = {
    .mode_get_ctx_size = cccbc_mode_get_ctx_size,
    .mode_get_block_size = cccbc_mode_get_block_size,
    .mode_setup = cccbc_mode_setup,
    .mode_encrypt = cccbc_mode_crypt,
    .mode_decrypt = cccbc_mode_crypt,
    .mode_encrypt_tweaked = NULL,
    .mode_decrypt_tweaked = NULL,
    .mode_done = NULL,
    .mode_setiv = cccbc_setiv,
    .mode_getiv = cccbc_getiv
};

// CFB

static size_t cccfb_mode_get_ctx_size(corecryptoMode modeObject) { return modeObject.cfb->size; }
static size_t cccfb_mode_get_block_size(corecryptoMode modeObject) { return modeObject.cfb->block_size; }
static void cccfb_mode_setup(corecryptoMode modeObj, const void *iv,
                             const void *key, size_t keylen, const void *tweak,
                             size_t tweaklen, int options, modeCtx ctx)
{
    modeObj.cfb->init(modeObj.cfb, ctx.cfb, keylen, key, iv);
}

static void cccfb_mode_crypt(corecryptoMode modeObj, const void *in, void *out, size_t len, modeCtx ctx)
{
    modeObj.cfb->cfb(ctx.cfb, len / cccfb_mode_get_block_size(modeObj), in, out);
}

cc2CCModeDescriptor cccfb_mode = {
    .mode_get_ctx_size = cccfb_mode_get_ctx_size,
    .mode_get_block_size = cccfb_mode_get_block_size,
    .mode_setup = cccfb_mode_setup,
    .mode_encrypt = cccfb_mode_crypt,
    .mode_decrypt = cccfb_mode_crypt,
    .mode_encrypt_tweaked = NULL,
    .mode_decrypt_tweaked = NULL,
    .mode_done = NULL,
    .mode_setiv = NULL,
    .mode_getiv = NULL
};


// CFB8

static size_t cccfb8_mode_get_ctx_size(corecryptoMode modeObject) { return modeObject.cfb8->size; }
static size_t cccfb8_mode_get_block_size(corecryptoMode modeObject) { return modeObject.cfb8->block_size; }
static void cccfb8_mode_setup(corecryptoMode modeObj, const void *iv,
                              const void *key, size_t keylen, const void *tweak,
                              size_t tweaklen, int options, modeCtx ctx)
{
    modeObj.cfb8->init(modeObj.cfb8, ctx.cfb8, keylen, key, iv);
}

static void cccfb8_mode_crypt(corecryptoMode modeObj, const void *in, void *out, size_t len, modeCtx ctx)
{
    modeObj.cfb8->cfb8(ctx.cfb8, len / cccfb8_mode_get_block_size(modeObj), in, out);
}

cc2CCModeDescriptor cccfb8_mode = {
    .mode_get_ctx_size = cccfb8_mode_get_ctx_size,
    .mode_get_block_size = cccfb8_mode_get_block_size,
    .mode_setup = cccfb8_mode_setup,
    .mode_encrypt = cccfb8_mode_crypt,
    .mode_decrypt = cccfb8_mode_crypt,
    .mode_encrypt_tweaked = NULL,
    .mode_decrypt_tweaked = NULL,
    .mode_done = NULL,
    .mode_setiv = NULL,
    .mode_getiv = NULL
};

// CTR

static size_t ccctr_mode_get_ctx_size(corecryptoMode modeObject) { return modeObject.ctr->size; }
static size_t ccctr_mode_get_block_size(corecryptoMode modeObject) { return modeObject.ctr->block_size; }
static void ccctr_mode_setup(corecryptoMode modeObj, const void *iv,
                             const void *key, size_t keylen, const void *tweak,
                             size_t tweaklen, int options, modeCtx ctx)
{
    modeObj.ctr->init(modeObj.ctr, ctx.ctr, keylen, key, iv);
}

static void ccctr_mode_crypt(corecryptoMode modeObj, const void *in, void *out, size_t len, modeCtx ctx)
{
    modeObj.ctr->ctr(ctx.ctr, len / ccctr_mode_get_block_size(modeObj), in, out);
}

cc2CCModeDescriptor ccctr_mode = {
    .mode_get_ctx_size = ccctr_mode_get_ctx_size,
    .mode_get_block_size = ccctr_mode_get_block_size,
    .mode_setup = ccctr_mode_setup,
    .mode_encrypt = ccctr_mode_crypt,
    .mode_decrypt = ccctr_mode_crypt,
    .mode_encrypt_tweaked = NULL,
    .mode_decrypt_tweaked = NULL,
    .mode_done = NULL,
    .mode_setiv = NULL,
    .mode_getiv = NULL
};

// OFB

static size_t ccofb_mode_get_ctx_size(corecryptoMode modeObject) { return modeObject.ofb->size; }
static size_t ccofb_mode_get_block_size(corecryptoMode modeObject) { return modeObject.ofb->block_size; }
static void ccofb_mode_setup(corecryptoMode modeObj, const void *iv,
                             const void *key, size_t keylen, const void *tweak,
                             size_t tweaklen, int options, modeCtx ctx)
{
    modeObj.ofb->init(modeObj.ofb, ctx.ofb, keylen, key, iv);
}

static void ccofb_mode_crypt(corecryptoMode modeObj, const void *in, void *out, size_t len, modeCtx ctx)
{
    modeObj.ofb->ofb(ctx.ofb, len / ccofb_mode_get_block_size(modeObj), in, out);
}

cc2CCModeDescriptor ccofb_mode = {
    .mode_get_ctx_size = ccofb_mode_get_ctx_size,
    .mode_get_block_size = ccofb_mode_get_block_size,
    .mode_setup = ccofb_mode_setup,
    .mode_encrypt = ccofb_mode_crypt,
    .mode_decrypt = ccofb_mode_crypt,
    .mode_encrypt_tweaked = NULL,
    .mode_decrypt_tweaked = NULL,
    .mode_done = NULL,
    .mode_setiv = NULL,
    .mode_getiv = NULL
};

// XTS
/* For now we always schedule both encrypt and decrypt contexts for AES-XTS.  Original CommonCrypto support
 * allowed a "both" (kCCEncrypt and kCCDecrypt) capability used for AES-XTS block I/O.  The initialization 
 * and correct mode objext and context passing are done at the CommonCryptor layer.
 */


static size_t ccxts_mode_get_ctx_size(corecryptoMode modeObject) { return modeObject.xts->size; }
static size_t ccxts_mode_get_block_size(corecryptoMode modeObject) { return modeObject.xts->block_size; }
static void ccxts_mode_setup(corecryptoMode modeObj, const void *iv,
                             const void *key, size_t keylen, const void *tweak,
                             size_t tweaklen, int options, modeCtx ctx)
{
    modeObj.xts->init(modeObj.xts, ctx.xts, keylen, key, tweak);
}

#ifdef UNUSED_INTERFACE
static void ccxts_mode_crypt(corecryptoMode modeObj, const void *in, void *out, size_t len, modeCtx ctx)
{
    modeObj.xts->xts(ctx.xts, len / ccxts_mode_get_block_size(modeObj), in, out);
}

static int ccxts_setiv(corecryptoMode modeObj, const void *iv, uint32_t len, modeCtx ctx)
{
    if(len != modeObj.xts->block_size) return -1;
    modeObj.xts->set_tweak(ctx.xts, iv);
    return 0;
}

static int ccxts_getiv(corecryptoMode modeObj, void *iv, uint32_t *len, modeCtx ctx)
{
    if(*len < modeObj.xts->block_size) {
        *len = modeObj.xts->block_size;
        return -1;
    }
    CC_XMEMCPY(iv, modeObj.xts->xts(ctx.xts, 0, NULL, NULL), *len = modeObj.xts->block_size);
    return 0;
}
#endif

/*
 * These match what we had in libtomcrypt - they really are "this is a logical block" routines, so need
 * to handle partial blocks - so we use corecrypto's xts pad routines in every case.
 */

static void ccxts_mode_encrypt_tweak(corecryptoMode modeObj, const void *in, void *out, size_t len, const void *iv, modeCtx ctx)
{
    ccxts_tweak_decl(ccxts_context_size(modeObj.xts), tweak);
    modeObj.xts->set_tweak(ctx.xts, tweak, iv);
    ccpad_xts_encrypt(modeObj.xts, ctx.xts, tweak, len, in, out);
}

static void ccxts_mode_decrypt_tweak(corecryptoMode modeObj, const void *in, void *out, size_t len, const void *iv, modeCtx ctx)
{
    ccxts_tweak_decl(ccxts_context_size(modeObj.xts), tweak);
    modeObj.xts->set_tweak(ctx.xts, tweak, iv);
    ccpad_xts_decrypt(modeObj.xts, ctx.xts, tweak, len, in, out);
}


cc2CCModeDescriptor ccxts_mode = {
    .mode_get_ctx_size = ccxts_mode_get_ctx_size,
    .mode_get_block_size = ccxts_mode_get_block_size,
    .mode_setup = ccxts_mode_setup,
    .mode_encrypt = NULL,
    .mode_decrypt = NULL,
    .mode_encrypt_tweaked = ccxts_mode_encrypt_tweak,
    .mode_decrypt_tweaked = ccxts_mode_decrypt_tweak,
    .mode_done = NULL,
    .mode_setiv = NULL,
    .mode_getiv = NULL
};

// GCM

static size_t ccgcm_mode_get_ctx_size(corecryptoMode modeObject) { return modeObject.gcm->size; }
static size_t ccgcm_mode_get_block_size(corecryptoMode modeObject) { return modeObject.gcm->block_size; }
static void ccgcm_mode_setup(corecryptoMode modeObj, const void *iv,
                             const void *key, size_t keylen, const void *tweak,
                             size_t tweaklen, int options, modeCtx ctx)
{
    modeObj.gcm->init(modeObj.gcm, ctx.gcm, keylen, key);
}

static void ccgcm_mode_crypt(corecryptoMode modeObj, const void *in, void *out, size_t len, modeCtx ctx)
{
    modeObj.gcm->gcm(ctx.gcm, len, in, out);
}

static int ccgcm_setiv(corecryptoMode modeObj, const void *iv, uint32_t len, modeCtx ctx)
{
    modeObj.gcm->set_iv(ctx.gcm, len, iv);
    return 0;
}


cc2CCModeDescriptor ccgcm_mode = {
    .mode_get_ctx_size = ccgcm_mode_get_ctx_size,
    .mode_get_block_size = ccgcm_mode_get_block_size,
    .mode_setup = ccgcm_mode_setup,
    .mode_encrypt = ccgcm_mode_crypt,
    .mode_decrypt = ccgcm_mode_crypt,
    .mode_encrypt_tweaked = NULL,
    .mode_decrypt_tweaked = NULL,
    .mode_done = NULL,
    .mode_setiv = ccgcm_setiv,
    .mode_getiv = NULL
};

// Padding

static int ccpkcs7_encrypt_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *cipherText, size_t *moved)
{
    ccpad_pkcs7_encrypt(modeObj.cbc, &ctx.cbc->cbc, ctx.cbc->iv, len, buff, cipherText);
    *moved = modeptr->mode_get_block_size(modeObj);
    return 0;
}
static int ccpkcs7_decrypt_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *plainText, size_t *moved)
{
    *moved = ccpad_pkcs7_decrypt(modeObj.cbc, &ctx.cbc->cbc, ctx.cbc->iv, len, buff, plainText);
    return 0;
}


static int ccpkcs7_encrypt_ecb_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *cipherText, size_t *moved)
{
    ccpad_pkcs7_ecb_encrypt(modeObj.ecb, ctx.ecb, len, buff, cipherText);
    *moved = modeptr->mode_get_block_size(modeObj);
    return 0;
}
static int ccpkcs7_decrypt_ecb_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *plainText, size_t *moved)
{
    *moved = ccpad_pkcs7_ecb_decrypt(modeObj.ecb, ctx.ecb, len, buff, plainText);
    return 0;
}


/*
 * Maximum space needed for padding.
 */

#define MAXBLOCKSIZE_PKCS7 128

static size_t ccpkcs7_padlen(int encrypt, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, char *buffp)
{
    int retval = 0;
    size_t blocksize = modeptr->mode_get_block_size(modeObj);
    
    /* We're going to return blocksize for unpad as a "maximum needed".  Otherwise we're going to have to decrypt the last block to get the number */
    return blocksize;
}

/*
 * How many bytes to reserve to enable padding - this is pre-encrypt/decrypt bytes.
 */

static size_t ccpkcs7_reserve(int encrypt, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj)
{
    if(encrypt) {
		return 0;
    } else {
    	return modeptr->mode_get_block_size(modeObj);
    }
}

cc2CCPaddingDescriptor ccpkcs7_pad = {
    .encrypt_pad = ccpkcs7_encrypt_pad,
    .decrypt_pad = ccpkcs7_decrypt_pad,
    .padlen = ccpkcs7_padlen,
    .padreserve = ccpkcs7_reserve,
};

cc2CCPaddingDescriptor ccpkcs7_ecb_pad = {
    .encrypt_pad = ccpkcs7_encrypt_ecb_pad,
    .decrypt_pad = ccpkcs7_decrypt_ecb_pad,
    .padlen = ccpkcs7_padlen,
    .padreserve = ccpkcs7_reserve,
};


static int cccts1_encrypt_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *cipherText, size_t *moved)
{
    ccpad_cts1_encrypt(modeObj.cbc, &ctx.cbc->cbc, ctx.cbc->iv, len, buff, cipherText);
    *moved = len;
    return 0;
}
static int cccts1_decrypt_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *plainText, size_t *moved)
{
    ccpad_cts1_decrypt(modeObj.cbc, &ctx.cbc->cbc, ctx.cbc->iv, len, buff, plainText);
    *moved = len;
    return 0;
}

static int cccts2_encrypt_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *cipherText, size_t *moved)
{
    ccpad_cts2_encrypt(modeObj.cbc, &ctx.cbc->cbc, ctx.cbc->iv, len, buff, cipherText);
    *moved = len;
    return 0;
}
static int cccts2_decrypt_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *plainText, size_t *moved)
{
    ccpad_cts2_decrypt(modeObj.cbc, &ctx.cbc->cbc, ctx.cbc->iv, len, buff, plainText);
    *moved = len;
    return 0;
}


static int cccts3_encrypt_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *cipherText, size_t *moved)
{
    ccpad_cts3_encrypt(modeObj.cbc, &ctx.cbc->cbc, ctx.cbc->iv, len, buff, cipherText);
    *moved = len;
    return 0;
}
static int cccts3_decrypt_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *plainText, size_t *moved)
{
    ccpad_cts3_decrypt(modeObj.cbc, &ctx.cbc->cbc, ctx.cbc->iv, len, buff, plainText);
    *moved = len;
    return 0;
}



/*
 * Maximum space needed for padding.
 */

#define MAXBLOCKSIZE_PKCS7 128

static size_t ccctsX_padlen(int encrypt, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, char *buffp)
{
	return 0;
}

/*
 * How many bytes to reserve to enable padding - this is pre-encrypt/decrypt bytes.
 */

static size_t ccctsX_reserve(int encrypt, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj)
{
    return modeptr->mode_get_block_size(modeObj) * 2;
}

cc2CCPaddingDescriptor cccts1_pad = {
    .encrypt_pad = cccts1_encrypt_pad,
    .decrypt_pad = cccts1_decrypt_pad,
    .padlen = ccctsX_padlen,
    .padreserve = ccctsX_reserve,
};

cc2CCPaddingDescriptor cccts2_pad = {
    .encrypt_pad = cccts2_encrypt_pad,
    .decrypt_pad = cccts2_decrypt_pad,
    .padlen = ccctsX_padlen,
    .padreserve = ccctsX_reserve,
};


cc2CCPaddingDescriptor cccts3_pad = {
    .encrypt_pad = cccts3_encrypt_pad,
    .decrypt_pad = cccts3_decrypt_pad,
    .padlen = ccctsX_padlen,
    .padreserve = ccctsX_reserve,
};


static int ccnopad_encrypt_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *cipherText, size_t *moved)
{
    *moved = 0;
    return 0;
}
static int ccnopad_decrypt_pad(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, size_t len, void *plainText, size_t *moved)
{
    *moved = 0;
    return 0;
}

/*
 * Maximum space needed for padding.
 */

static size_t ccnopad_padlen(int encrypt, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, char *buffp)
{
	return 0;
}

/*
 * How many bytes to reserve to enable padding - this is pre-encrypt/decrypt bytes.
 */

static size_t ccnopad_reserve(int encrypt, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj)
{
    return 0;
}

cc2CCPaddingDescriptor ccnopad_pad = {
    .encrypt_pad = ccnopad_encrypt_pad,
    .decrypt_pad = ccnopad_decrypt_pad,
    .padlen = ccnopad_padlen,
    .padreserve = ccnopad_reserve,
};


Added Source/descriptors/corecryptoSymmetricBridge.h.



























































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*                                                                              
 * Copyright (c) 2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef CommonCrypto_corecryptoSymmetricBridge_h
#define CommonCrypto_corecryptoSymmetricBridge_h

#include <stdbool.h>
#include <corecrypto/ccmode.h>
#include <corecrypto/ccmode_impl.h>
#include <corecrypto/ccaes.h>
#include <corecrypto/ccdes.h>
#include <corecrypto/cccast.h>
#include <corecrypto/ccrc2.h>
#include <corecrypto/ccblowfish.h>
#include <corecrypto/ccpad.h>

typedef union {
    struct ccmode_ecb *ecb;
    struct ccmode_cbc *cbc;
    struct ccmode_cfb *cfb;
    struct ccmode_cfb8 *cfb8;
    struct ccmode_ctr *ctr;
    struct ccmode_ofb *ofb;
    struct ccmode_xts *xts;
    struct ccmode_gcm *gcm;
} corecryptoMode;

typedef struct ccmode_ecb* (*ecb_p) (void);
typedef struct ccmode_cbc* (*cbc_p) (void);
typedef struct ccmode_cfb* (*cfb_p) (void);
typedef struct ccmode_cfb8* (*cfb8_p) (void);
typedef struct ccmode_ctr* (*ctr_p) (void);
typedef struct ccmode_ofb* (*ofb_p) (void);
typedef struct ccmode_xts* (*xts_p) (void);
typedef struct ccmode_gcm* (*gcm_p) (void);



typedef struct modes_t {
    ecb_p   ecb;
    cbc_p   cbc;
    cfb_p   cfb;
    cfb8_p  cfb8;
    ctr_p   ctr;
    ofb_p   ofb;
    xts_p   xts;
    gcm_p   gcm;
} modeList;

modeList ccmodeList[7][2];

typedef struct cbc_with_iv_t {
    uint8_t iv[16];
    cccbc_ctx cbc;
} cbc_iv_ctx;

typedef union {
    void *data;
    ccecb_ctx *ecb;
    cbc_iv_ctx *cbc;
    cccfb_ctx *cfb;
    cccfb8_ctx *cfb8;
    ccctr_ctx *ctr;
    ccofb_ctx *ofb;
    ccxts_ctx *xts;
    ccgcm_ctx *gcm;
} modeCtx;


#pragma mark Modes

/** Setup the mode
 @param cipher		The index of the LTC Cipher - must be registered
 @param IV		The initial vector
 @param key		The input symmetric key
 @param keylen		The length of the input key (octets)
 @param tweak		The input tweak or salt
 @param tweaklen	The length of the tweak or salt (if variable)
 (octets)
 @param options		Mask for any mode options
 @param ctx		[out] The destination of the mode context
 */

typedef void (*ccmode_setup_p)(corecryptoMode modeObj, const void *iv,
                            const void *key, size_t keylen, const void *tweak,
                            size_t tweaklen, int options, modeCtx ctx);
/** Encrypt a block
 @param pt		The plaintext
 @param ct		[out] The ciphertext
 @param len		the length of data (in == out) octets
 @param ctx		The mode context
 @return # bytes encrypted
 */

typedef void (*ccmode_encrypt_p)(corecryptoMode modeObj, const void *pt, void *ct, size_t len, modeCtx ctx);

/** Decrypt a block
 @param ct		The ciphertext
 @param pt		[out] The plaintext
 @param len		the length of data (in == out) octets
 @param ctx		The mode context
 @return # bytes encrypted
 */
typedef void (*ccmode_decrypt_p)(corecryptoMode modeObj, const void *ct, void *pt, size_t len, modeCtx ctx);

/** Encrypt a block with a tweak (XTS mode currently)
 @param pt		The plaintext
 @param ct		[out] The ciphertext
 @param len		the length of data (in == out) octets
 @param tweak		The 128--bit encryption tweak (e.g. sector
 number)
 @param ctx		The mode context
 @return # bytes encrypted
 */
typedef void (*ccmode_encrypt_tweaked_p)(corecryptoMode modeObj, const void *pt, size_t len,
                                      void *ct, const void *tweak, modeCtx ctx);
/** Decrypt a block with a tweak (XTS mode currently)
 @param ct		The ciphertext
 @param pt		[out] The plaintext
 @param len		the length of data (in == out) octets
 @param ctx		The mode context
 @return # bytes encrypted
 */
typedef void (*ccmode_decrypt_tweaked_p)(corecryptoMode modeObj, const void *ct, size_t len,
                                      void *pt, const void *tweak, modeCtx ctx);
/** Terminate the mode
 @param ctx		[out] The mode context
 */
typedef int (*ccmode_done_p)(corecryptoMode modeObj, modeCtx ctx);
/** Set an Initial Vector
 @param IV		The initial vector
 @param len		The length of the initial vector
 @param ctx		The mode context
 */
typedef int (*ccmode_setiv_p)(corecryptoMode modeObj, const void *iv, uint32_t len, modeCtx ctx);
/** Get an Initial Vector
 @param IV		[out] The initial vector
 @param len		The length of the initial vector
 @param ctx		The mode context
 */
typedef int (*ccmode_getiv_p)(corecryptoMode modeObj, void *iv, uint32_t *len, modeCtx ctx);

/** Get the mode context size
 @param modeObj a pointer to the mode object.
 @return the size of the context
 */
typedef size_t (*ccmode_get_ctx_size)(corecryptoMode modeObj);

/** Get the mode block size
 @param modeObj a pointer to the mode object.
 @return the size of the block
 */
typedef size_t (*ccmode_get_block_size)(corecryptoMode modeObj);

typedef struct cc2CCModeDescriptor_t {
//    ccBufStrat              bufStrat;
    ccmode_get_ctx_size     mode_get_ctx_size;
    ccmode_get_block_size   mode_get_block_size;
	ccmode_setup_p          mode_setup;
	ccmode_encrypt_p        mode_encrypt;
	ccmode_decrypt_p        mode_decrypt;
	ccmode_encrypt_tweaked_p mode_encrypt_tweaked;
	ccmode_decrypt_tweaked_p mode_decrypt_tweaked;
	ccmode_done_p           mode_done;
	ccmode_setiv_p          mode_setiv;
	ccmode_getiv_p          mode_getiv;
} cc2CCModeDescriptor, *cc2CCModeDescriptorPtr;


cc2CCModeDescriptor ccecb_mode;
cc2CCModeDescriptor cccbc_mode;
cc2CCModeDescriptor cccfb_mode;
cc2CCModeDescriptor cccfb8_mode;
cc2CCModeDescriptor ccctr_mode;
cc2CCModeDescriptor ccofb_mode;
cc2CCModeDescriptor ccxts_mode;
cc2CCModeDescriptor ccgcm_mode;


// Buffer and Padding Handling

/*
 * Fill out the padding for a buffer.  The blocksize and starting points are
 * used to determine how much needs to be padded.  If startpoint is 0
 * then a full new buffer is added.  Blocksize cannot be greater than 256.
 */

typedef int (*cc_encrypt_pad_p)(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, uint32_t startpoint, void *cipherText, size_t *moved);
typedef int (*cc_decrypt_pad_p)(modeCtx ctx, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, void *buff, uint32_t startpoint, void *plainText, size_t *moved);

/*
 * Maximum space needed for padding.
 */

typedef size_t (*ccpadlen_p) (int encrypt, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj, char *buffp);

/*
 * How many bytes to reserve to enable padding - this is pre-encrypt/decrypt bytes.
 */

typedef size_t (*ccreserve_p) (int encrypt, cc2CCModeDescriptorPtr modeptr, corecryptoMode modeObj);

typedef struct cc2CCPaddingDescriptor_t {
    cc_encrypt_pad_p    encrypt_pad;
    cc_decrypt_pad_p    decrypt_pad;
    ccpadlen_p          padlen;
    ccreserve_p         padreserve;
} cc2CCPaddingDescriptor, *cc2CCPaddingDescriptorPtr;

cc2CCPaddingDescriptor ccnopad_pad;
cc2CCPaddingDescriptor cccts1_pad;
cc2CCPaddingDescriptor cccts2_pad;
cc2CCPaddingDescriptor cccts3_pad;
cc2CCPaddingDescriptor ccpkcs7_pad;
cc2CCPaddingDescriptor ccpkcs7_ecb_pad;

#endif

Added Source/descriptors/digestDescriptors/ccDigestDescriptors.h.





















>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
#include "ccDescriptors.h"

#ifndef _CC_DIGESTDESCRIPTORS_H
#define _CC_DIGESTDESCRIPTORS_H

#define CCCTX_SIZE(DI) ((DI)->state_size + sizeof(uint64_t) + (DI)->block_size + sizeof(int))



#endif /* _CC_DIGESTDESCRIPTORS_H */

Added Source/descriptors/digestDescriptors/ccvngneonsha1Descriptor/ccvngneonsha1Desc.c.

























































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#if defined(__ARM_ARCH_7A__)
#include "ccvngneonsha1Desc.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "CommonDigest.h"

const ccDescriptor cc_vngneonsha1_desc =
{
    .implementation_info = &cc_sha1_impinfo,
	.dtype.digest.hashsize = CC_SHA1_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA1_BLOCK_BYTES,
    .dtype.digest.digest_info = &cc_vngneonsha1_di,
	.dtype.digest.init = &cc_vngneon_sha1_init,
	.dtype.digest.process = &cc_vngneon_sha1_process,
	.dtype.digest.done = &cc_vngneon_sha1_done,
};


int 
cc_vngneon_sha1_init(cc_sha1_ctx *md_ctx) {
    ccdigest_init(cc_vngneonsha1_di, md_ctx);
    return CRYPT_OK;
}

int 
cc_vngneon_sha1_process(cc_sha1_ctx *md_ctx, const unsigned char *in,
                   unsigned long inlen) {
    ccdigest_update(cc_vngneonsha1_di, md_ctx, inlen, in);
    return CRYPT_OK;
}    

int cc_vngneon_sha1_done(cc_sha1_ctx *md_ctx, unsigned char *hash) {
    ccdigest_final(cc_vngneonsha1_di, md_ctx, hash);
    return CRYPT_OK;
}
#endif

Added Source/descriptors/digestDescriptors/ccvngneonsha1Descriptor/ccvngneonsha1Desc.h.









































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#if defined(__ARM_ARCH_7A__)
#define CCSHA1_VNG_ARMV7NEON
#include <corecrypto/ccsha1.h>

static const struct ccdigest_info *cc_vngneonsha1_di=&ccsha1_vng_armv7neon_di;
typedef void  cc_sha1_ctx;


int cc_vngneon_sha1_init(cc_sha1_ctx *md_ctx);
int cc_vngneon_sha1_process(cc_sha1_ctx *md_ctx, const unsigned char *in,
                    unsigned long inlen);
int cc_vngneon_sha1_done(cc_sha1_ctx *md_ctx, unsigned char *hash);
#endif

Added Source/descriptors/digestDescriptors/ltc_hashcommon.h.





































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */

#ifndef LTC_HASHCOMMON_H_
#define LTC_HASHCOMMON_H_

/* a simple macro for making hash "process" functions */
#define LTC_HASH_PROCESS(func_name, compress_name, state_var, field, block_size) \
int func_name (state_var *ctx, const unsigned char *in, unsigned long inlen) \
{                                                                             \
unsigned long n;                                                          \
int           err;                                                        \
\
\
LTC_ARGCHK(ctx != NULL);                                                   \
LTC_ARGCHK(in != NULL);                                                   \
\
\
if (ctx->curlen > sizeof(ctx->buf)) {                             	      \
return CRYPT_INVALID_ARG;					      \
}									      \
if ((ctx->length + inlen) < ctx->length) {				      \
return CRYPT_HASH_OVERFLOW;					      \
}									      \
while (inlen > 0) {							      \
if (ctx->curlen == 0 && inlen >= block_size) {			      \
if ((err = compress_name (ctx, in)) != CRYPT_OK) {		      \
return err;						      \
}								      \
ctx->length    += block_size * 8;				      \
in             += block_size;				      \
inlen          -= block_size;				      \
} else {							      \
n = MIN(inlen, (block_size - ctx->curlen));			      \
memcpy(ctx->buf + ctx->curlen, in, (size_t)n);		      \
ctx->curlen += n;						      \
in             += n;						      \
inlen          -= n;						      \
if (ctx->curlen == block_size) {				      \
if ((err = compress_name (ctx, ctx->buf)) != CRYPT_OK) {	      \
return err;						      \
}								      \
ctx->length += 8*block_size;				      \
ctx->curlen = 0;						      \
}								      \
}								      \
} 									      \
return CRYPT_OK;							      \
}

#endif /* LTC_HASHCOMMON_H_ */

Added Source/descriptors/digestDescriptors/ltc_md2_descriptor/ltc_md2.c.













































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */

#include <stdio.h>
#include "ltc_md2.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"

/**
 @param ltc_md2.c
 LTC_MD2 (RFC 1319) hash function implementation by Tom St Denis 
 */


const ccDescriptor ltc_md2_desc = {
    .implementation_info = &cc_md2_impinfo,
	.dtype.digest.hashsize = CC_MD2_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_MD2_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_md2_init,
	.dtype.digest.process = &ltc_md2_process,
	.dtype.digest.done = &ltc_md2_done,
};

static const unsigned char PI_SUBST[256] = {
    41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6,
    19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188,
    76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24,
    138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251,
    245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63,
    148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50,
    39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165,
    181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210,
    150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157,
    112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27,
    96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
    85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197,
    234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65,
    129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123,
    8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233,
    203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228,
    166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237,
    31, 26, 219, 153, 141, 51, 159, 17, 131, 20
};

/* adds 16 bytes to the checksum */
static void md2_update_chksum(ltc_md2_ctx *ctx)
{
    int j;
    unsigned char L;

    LTC_ARGCHKVD(ctx != NULL);
    
    L = ctx->chksum[15];
    for (j = 0; j < 16; j++) {
        
        /* caution, the RFC says its "C[j] = S[M[i*16+j] xor L]" but the
	 * reference source code [and test vectors] say otherwise.
         */
        L = (ctx->chksum[j] ^= PI_SUBST[(int)(ctx->buf[j] ^ L)] & 255);
    }
}

static void md2_compress(ltc_md2_ctx *ctx)
{
    int j, k;
    unsigned char t;

    LTC_ARGCHKVD(ctx != NULL);

    /* copy block */
    for (j = 0; j < 16; j++) {
        ctx->X[16+j] = ctx->buf[j];
        ctx->X[32+j] = ctx->X[j] ^ ctx->X[16+j];
    }
    
    t = (unsigned char)0;
    
    /* do 18 rounds */
    for (j = 0; j < 18; j++) {
        for (k = 0; k < 48; k++) {
            t = (ctx->X[k] ^= PI_SUBST[(int)(t & 255)]);
        }
        t = (t + (unsigned char)j) & 255;
    }
}

/**
 Initialize the hash state
 @param md   The hash state you wish to initialize
 @return CRYPT_OK if successful
 */
int ltc_md2_init(ltc_md2_ctx *ctx)
{
    
    LTC_ARGCHK(ctx != NULL);

    /* LTC_MD2 uses a zero'ed state... */
    CC_XZEROMEM(ctx->X, sizeof(ctx->X));
    CC_XZEROMEM(ctx->chksum, sizeof(ctx->chksum));
    CC_XZEROMEM(ctx->buf, sizeof(ctx->buf));
    ctx->curlen = 0;
    return CRYPT_OK;
}

/**
 Process a block of memory though the hash
 @param md     The hash state
 @param in     The data to hash
 @param inlen  The length of the data (octets)
 @return CRYPT_OK if successful
 */
int ltc_md2_process(ltc_md2_ctx *ctx, const unsigned char *in,
    unsigned long inlen)
{
    unsigned long n;

    LTC_ARGCHK(ctx != NULL);
    LTC_ARGCHK(in != NULL);

    if (ctx->curlen > sizeof(ctx->buf)) {                            
        return CRYPT_INVALID_ARG; 
    }                            

    while (inlen > 0) {
        n = MIN(inlen, (16 - ctx->curlen));
        CC_XMEMCPY(ctx->buf + ctx->curlen, in, (size_t)n);
        ctx->curlen += n;
        in             += n;
        inlen          -= n;
        
        /* is 16 bytes full? */
        if (ctx->curlen == 16) {
            md2_compress(ctx);
            md2_update_chksum(ctx);
            ctx->curlen = 0;
        }
    }
    return CRYPT_OK;
}

/**
 Terminate the hash to get the digest
 @param md  The hash state
 @param out [out] The destination of the hash (16 bytes)
 @return CRYPT_OK if successful
 */
int ltc_md2_done(ltc_md2_ctx *ctx, unsigned char *out)
{
    unsigned long i, k;
    
    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);
        
    if (ctx->curlen >= sizeof(ctx->buf)) {
        return CRYPT_INVALID_ARG;
    }
    
    
    /* pad the message */
    k = 16 - ctx->curlen;
    for (i = ctx->curlen; i < 16; i++) {
        ctx->buf[i] = (unsigned char)k;
    }
    
    /* hash and update */
    md2_compress(ctx);
    md2_update_chksum(ctx);
    
    /* hash checksum */
    CC_XMEMCPY(ctx->buf, ctx->chksum, 16);
    md2_compress(ctx);
    
    /* output is lower 16 bytes of X */
    CC_XMEMCPY(out, ctx->X, 16);
    
#ifdef LTC_CLEAN_STACK
    CC_XZEROMEM(ctx, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
 Self-test the hash
 @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
 */  
int ltc_md2_test(void)
{
#ifndef LTC_TEST
    return CRYPT_NOP;
#else    
    static const struct {
        const char *msg;
        unsigned char md[16];
    } tests[] = {
        { "",
            {0x83,0x50,0xe5,0xa3,0xe2,0x4c,0x15,0x3d,
                0xf2,0x27,0x5c,0x9f,0x80,0x69,0x27,0x73
            }
        },
        { "a",
            {0x32,0xec,0x01,0xec,0x4a,0x6d,0xac,0x72,
                0xc0,0xab,0x96,0xfb,0x34,0xc0,0xb5,0xd1
            }
        },
        { "message digest",
            {0xab,0x4f,0x49,0x6b,0xfb,0x2a,0x53,0x0b,
                0x21,0x9f,0xf3,0x30,0x31,0xfe,0x06,0xb0
            }
        },
        { "abcdefghijklmnopqrstuvwxyz",
            {0x4e,0x8d,0xdf,0xf3,0x65,0x02,0x92,0xab,
                0x5a,0x41,0x08,0xc3,0xaa,0x47,0x94,0x0b
            }
        },
        { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
            {0xda,0x33,0xde,0xf2,0xa4,0x2d,0xf1,0x39,
                0x75,0x35,0x28,0x46,0xc3,0x03,0x38,0xcd
            }
        },
        { "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
            {0xd5,0x97,0x6f,0x79,0xd8,0x3d,0x3a,0x0d,
                0xc9,0x80,0x6c,0x3c,0x66,0xf3,0xef,0xd8
            }
        }
    };
    int i;
    ltc_hash_state md;
    unsigned char buf[16];
    
    for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
        ltc_md2_init(&md);
        ltc_md2_process(&md, (const unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
        ltc_md2_done(&md, buf);
        if (LTC_XMEMCMP(buf, tests[i].md, 16) != 0) {
            return CRYPT_FAIL_TESTVECTOR;
        }
    }
    return CRYPT_OK;        
#endif /* LTC_TEST */
}

Added Source/descriptors/digestDescriptors/ltc_md2_descriptor/ltc_md2.h.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_md2.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#ifndef _LTC_MD2_H_
#define _LTC_MD2_H_

#define	LTC_MD2_HASHSIZE	16
#define	LTC_MD2_BLOCKSIZE	16

typedef struct ltc_md2_state {
    unsigned long curlen;
    unsigned char buf[LTC_MD2_BLOCKSIZE];
    unsigned char chksum[16];
    unsigned char X[48];
    unsigned char paddingB[16];
} ltc_md2_ctx;

int ltc_md2_init(ltc_md2_ctx *md);
int ltc_md2_process(ltc_md2_ctx *md, const unsigned char *in,
    unsigned long inlen);
int ltc_md2_done(ltc_md2_ctx *md, unsigned char *hash);
int ltc_md2_test(void);

#endif /* _LTC_MD2_H_ */

Added Source/descriptors/digestDescriptors/ltc_md4_descriptor/ltc_md4.c.

















































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <stdio.h>
#include "ltc_md4.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"

/**
   @param ltc_md4.c
   Submitted by Dobes Vandermeer  (dobes@smartt.com) 
*/


const ccDescriptor ltc_md4_desc =
{
    .implementation_info = &cc_md4_impinfo,
	.dtype.digest.hashsize = CC_MD4_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_MD4_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_md4_init,
	.dtype.digest.process = &ltc_md4_process,
	.dtype.digest.done = &ltc_md4_done,
};


#define S11 3
#define S12 7
#define S13 11
#define S14 19
#define S21 3
#define S22 5
#define S23 9
#define S24 13
#define S31 3
#define S32 9
#define S33 11
#define S34 15

/* F, G and H are basic LTC_MD4 functions. */
#define F(x, y, z) (z ^ (x & (y ^ z)))
#define G(x, y, z) ((x & y) | (z & (x | y)))
#define H(x, y, z) ((x) ^ (y) ^ (z))

/* ROTATE_LEFT rotates x left n bits. */
#define ROTATE_LEFT(x, n) LTC_ROLc(x, n)

/* FF, GG and HH are transformations for rounds 1, 2 and 3 */ 
/* Rotation is separate from addition to prevent recomputation */ 

#define FF(a, b, c, d, x, s) { \
    (a) += F ((b), (c), (d)) + (x); \
    (a) = ROTATE_LEFT ((a), (s)); \
  }
#define GG(a, b, c, d, x, s) { \
    (a) += G ((b), (c), (d)) + (x) + 0x5a827999UL; \
    (a) = ROTATE_LEFT ((a), (s)); \
  }
#define HH(a, b, c, d, x, s) { \
    (a) += H ((b), (c), (d)) + (x) + 0x6ed9eba1UL; \
    (a) = ROTATE_LEFT ((a), (s)); \
  }

#ifdef LTC_CLEAN_STACK
static int _md4_compress(ltc_md4_ctx *ctx, const unsigned char *buf)
#else
static int  md4_compress(ltc_md4_ctx *ctx, const unsigned char *buf)
#endif
{
    ulong32 x[16], a, b, c, d;
    int i;
    
    /* copy state */
    a = ctx->state[0];
    b = ctx->state[1];
    c = ctx->state[2];
    d = ctx->state[3];

    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LTC_LOAD32L(x[i], buf + (4*i));
    }
 
    /* Round 1 */ 
    FF (a, b, c, d, x[ 0], S11); /* 1 */ 
    FF (d, a, b, c, x[ 1], S12); /* 2 */ 
    FF (c, d, a, b, x[ 2], S13); /* 3 */ 
    FF (b, c, d, a, x[ 3], S14); /* 4 */ 
    FF (a, b, c, d, x[ 4], S11); /* 5 */ 
    FF (d, a, b, c, x[ 5], S12); /* 6 */ 
    FF (c, d, a, b, x[ 6], S13); /* 7 */ 
    FF (b, c, d, a, x[ 7], S14); /* 8 */ 
    FF (a, b, c, d, x[ 8], S11); /* 9 */ 
    FF (d, a, b, c, x[ 9], S12); /* 10 */
    FF (c, d, a, b, x[10], S13); /* 11 */ 
    FF (b, c, d, a, x[11], S14); /* 12 */
    FF (a, b, c, d, x[12], S11); /* 13 */
    FF (d, a, b, c, x[13], S12); /* 14 */ 
    FF (c, d, a, b, x[14], S13); /* 15 */ 
    FF (b, c, d, a, x[15], S14); /* 16 */ 
    
    /* Round 2 */ 
    GG (a, b, c, d, x[ 0], S21); /* 17 */ 
    GG (d, a, b, c, x[ 4], S22); /* 18 */ 
    GG (c, d, a, b, x[ 8], S23); /* 19 */ 
    GG (b, c, d, a, x[12], S24); /* 20 */ 
    GG (a, b, c, d, x[ 1], S21); /* 21 */ 
    GG (d, a, b, c, x[ 5], S22); /* 22 */ 
    GG (c, d, a, b, x[ 9], S23); /* 23 */ 
    GG (b, c, d, a, x[13], S24); /* 24 */ 
    GG (a, b, c, d, x[ 2], S21); /* 25 */ 
    GG (d, a, b, c, x[ 6], S22); /* 26 */ 
    GG (c, d, a, b, x[10], S23); /* 27 */ 
    GG (b, c, d, a, x[14], S24); /* 28 */ 
    GG (a, b, c, d, x[ 3], S21); /* 29 */ 
    GG (d, a, b, c, x[ 7], S22); /* 30 */ 
    GG (c, d, a, b, x[11], S23); /* 31 */ 
    GG (b, c, d, a, x[15], S24); /* 32 */ 
    
    /* Round 3 */
    HH (a, b, c, d, x[ 0], S31); /* 33 */ 
    HH (d, a, b, c, x[ 8], S32); /* 34 */ 
    HH (c, d, a, b, x[ 4], S33); /* 35 */ 
    HH (b, c, d, a, x[12], S34); /* 36 */ 
    HH (a, b, c, d, x[ 2], S31); /* 37 */ 
    HH (d, a, b, c, x[10], S32); /* 38 */ 
    HH (c, d, a, b, x[ 6], S33); /* 39 */ 
    HH (b, c, d, a, x[14], S34); /* 40 */ 
    HH (a, b, c, d, x[ 1], S31); /* 41 */ 
    HH (d, a, b, c, x[ 9], S32); /* 42 */ 
    HH (c, d, a, b, x[ 5], S33); /* 43 */ 
    HH (b, c, d, a, x[13], S34); /* 44 */ 
    HH (a, b, c, d, x[ 3], S31); /* 45 */ 
    HH (d, a, b, c, x[11], S32); /* 46 */ 
    HH (c, d, a, b, x[ 7], S33); /* 47 */ 
    HH (b, c, d, a, x[15], S34); /* 48 */ 
    

    /* Update our state */
    ctx->state[0] = ctx->state[0] + a;
    ctx->state[1] = ctx->state[1] + b;
    ctx->state[2] = ctx->state[2] + c;
    ctx->state[3] = ctx->state[3] + d;

    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int md4_compress(ltc_md4_ctx *ctx, const unsigned char *buf)
{
   int err;
   err = _md4_compress(ctx, buf);

   ltc_burn_stack(sizeof(ulong32) * 20 + sizeof(int));
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_md4_init(ltc_md4_ctx *ctx)
{
   LTC_ARGCHK(ctx != NULL);

   ctx->state[0] = 0x67452301UL;
   ctx->state[1] = 0xefcdab89UL;
   ctx->state[2] = 0x98badcfeUL;
   ctx->state[3] = 0x10325476UL;
   ctx->length  = 0;
   ctx->curlen  = 0;
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
LTC_HASH_PROCESS(ltc_md4_process, md4_compress, ltc_md4_ctx, md4, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (16 bytes)
   @return CRYPT_OK if successful
*/
int ltc_md4_done(ltc_md4_ctx *ctx, unsigned char *out)
{
    int i;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);
    

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }

    /* increase the length of the message */
    ctx->length += ctx->curlen * 8;

    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 56) {
        while (ctx->curlen < 64) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        md4_compress(ctx, ctx->buf);
        ctx->curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (ctx->curlen < 56) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64L(ctx->length, ctx->buf+56);
    md4_compress(ctx, ctx->buf);

    /* copy output */
    for (i = 0; i < 4; i++) {
        LTC_STORE32L(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(md, sizeof(ltc_hash_state));
#endif 
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int ltc_md4_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
    static const struct md4_test_case {
        const char *input;
        unsigned char digest[16];
    } cases[] = {
        { "", 
          {0x31, 0xd6, 0xcf, 0xe0, 0xd1, 0x6a, 0xe9, 0x31,
           0xb7, 0x3c, 0x59, 0xd7, 0xe0, 0xc0, 0x89, 0xc0} },
        { "a",
          {0xbd, 0xe5, 0x2c, 0xb3, 0x1d, 0xe3, 0x3e, 0x46,
           0x24, 0x5e, 0x05, 0xfb, 0xdb, 0xd6, 0xfb, 0x24} },
        { "abc",
          {0xa4, 0x48, 0x01, 0x7a, 0xaf, 0x21, 0xd8, 0x52, 
           0x5f, 0xc1, 0x0a, 0xe8, 0x7a, 0xa6, 0x72, 0x9d} },
        { "message digest", 
          {0xd9, 0x13, 0x0a, 0x81, 0x64, 0x54, 0x9f, 0xe8, 
           0x18, 0x87, 0x48, 0x06, 0xe1, 0xc7, 0x01, 0x4b} },
        { "abcdefghijklmnopqrstuvwxyz", 
          {0xd7, 0x9e, 0x1c, 0x30, 0x8a, 0xa5, 0xbb, 0xcd, 
           0xee, 0xa8, 0xed, 0x63, 0xdf, 0x41, 0x2d, 0xa9} },
        { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 
          {0x04, 0x3f, 0x85, 0x82, 0xf2, 0x41, 0xdb, 0x35, 
           0x1c, 0xe6, 0x27, 0xe1, 0x53, 0xe7, 0xf0, 0xe4} },
        { "12345678901234567890123456789012345678901234567890123456789012345678901234567890", 
          {0xe3, 0x3b, 0x4d, 0xdc, 0x9c, 0x38, 0xf2, 0x19, 
           0x9c, 0x3e, 0x7b, 0x16, 0x4f, 0xcc, 0x05, 0x36} },
    };
    int i;
    ltc_hash_state md;
    unsigned char digest[16];

    for(i = 0; i < (int)(sizeof(cases) / sizeof(cases[0])); i++) {
        ltc_md4_init(&md);
        ltc_md4_process(&md, (const unsigned char *)cases[i].input, (unsigned long)strlen(cases[i].input));
        ltc_md4_done(&md, digest);
        if (LTC_XMEMCMP(digest, cases[i].digest, 16) != 0) {
           return CRYPT_FAIL_TESTVECTOR;
        }

    }
    return CRYPT_OK;
  #endif
}

Added Source/descriptors/digestDescriptors/ltc_md4_descriptor/ltc_md4.h.













































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_md4.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>

#ifndef _LTC_MD4_H_
#define _LTC_MD4_H_

#define	LTC_MD4_HASHSIZE	16
#define	LTC_MD4_BLOCKSIZE	64

typedef struct ltc_md4_state {
    uint32_t state[4];
    uint64_t length;
    unsigned char buf[LTC_MD4_BLOCKSIZE];
    uint32_t	curlen;
} ltc_md4_ctx;

int ltc_md4_init(ltc_md4_ctx *ctx);
int ltc_md4_process(ltc_md4_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int ltc_md4_done(ltc_md4_ctx *ctx, unsigned char *hash);
int ltc_md4_test(void);

#endif /* _LTC_MD4_H_ */

Added Source/descriptors/digestDescriptors/ltc_md5_descriptor/ltc_md5.c.











































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <stdio.h>
#include "ltc_md5.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"

/**
  @file ltc_md5.c
  LTC_MD5 hash function by Tom St Denis 
*/

const ccDescriptor ltc_md5_desc =
{
    .implementation_info = &cc_md5_impinfo,
	.dtype.digest.hashsize = CC_MD5_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_MD5_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_md5_init,
	.dtype.digest.process = &ltc_md5_process,
	.dtype.digest.done = &ltc_md5_done,
};


#define F(x,y,z)  (z ^ (x & (y ^ z)))
#define G(x,y,z)  (y ^ (z & (y ^ x)))
#define H(x,y,z)  (x^y^z)
#define I(x,y,z)  (y^(x|(~z)))

#ifdef LTC_SMALL_CODE

#define FF(a,b,c,d,M,s,t) \
    a = (a + F(b,c,d) + M + t); a = ROL(a, s) + b;

#define GG(a,b,c,d,M,s,t) \
    a = (a + G(b,c,d) + M + t); a = ROL(a, s) + b;

#define HH(a,b,c,d,M,s,t) \
    a = (a + H(b,c,d) + M + t); a = ROL(a, s) + b;

#define II(a,b,c,d,M,s,t) \
    a = (a + I(b,c,d) + M + t); a = ROL(a, s) + b;

static const unsigned char Worder[64] = {
   0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
   1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,
   5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,
   0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9
};

static const unsigned char Rorder[64] = {
   7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,
   5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,
   4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,
   6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21
};

static const ulong32 Korder[64] = {
0xd76aa478UL, 0xe8c7b756UL, 0x242070dbUL, 0xc1bdceeeUL, 0xf57c0fafUL, 0x4787c62aUL, 0xa8304613UL, 0xfd469501UL,
0x698098d8UL, 0x8b44f7afUL, 0xffff5bb1UL, 0x895cd7beUL, 0x6b901122UL, 0xfd987193UL, 0xa679438eUL, 0x49b40821UL,
0xf61e2562UL, 0xc040b340UL, 0x265e5a51UL, 0xe9b6c7aaUL, 0xd62f105dUL, 0x02441453UL, 0xd8a1e681UL, 0xe7d3fbc8UL,
0x21e1cde6UL, 0xc33707d6UL, 0xf4d50d87UL, 0x455a14edUL, 0xa9e3e905UL, 0xfcefa3f8UL, 0x676f02d9UL, 0x8d2a4c8aUL,
0xfffa3942UL, 0x8771f681UL, 0x6d9d6122UL, 0xfde5380cUL, 0xa4beea44UL, 0x4bdecfa9UL, 0xf6bb4b60UL, 0xbebfbc70UL,
0x289b7ec6UL, 0xeaa127faUL, 0xd4ef3085UL, 0x04881d05UL, 0xd9d4d039UL, 0xe6db99e5UL, 0x1fa27cf8UL, 0xc4ac5665UL,
0xf4292244UL, 0x432aff97UL, 0xab9423a7UL, 0xfc93a039UL, 0x655b59c3UL, 0x8f0ccc92UL, 0xffeff47dUL, 0x85845dd1UL,
0x6fa87e4fUL, 0xfe2ce6e0UL, 0xa3014314UL, 0x4e0811a1UL, 0xf7537e82UL, 0xbd3af235UL, 0x2ad7d2bbUL, 0xeb86d391UL
};

#else

#define FF(a,b,c,d,M,s,t) \
    a = (a + F(b,c,d) + M + t); a = LTC_ROLc(a, s) + b;

#define GG(a,b,c,d,M,s,t) \
    a = (a + G(b,c,d) + M + t); a = LTC_ROLc(a, s) + b;

#define HH(a,b,c,d,M,s,t) \
    a = (a + H(b,c,d) + M + t); a = LTC_ROLc(a, s) + b;

#define II(a,b,c,d,M,s,t) \
    a = (a + I(b,c,d) + M + t); a = LTC_ROLc(a, s) + b;


#endif   

#ifdef LTC_CLEAN_STACK
static int _md5_compress(ltc_md5_ctx *ctx, const unsigned char *buf)
#else
static int  md5_compress(ltc_md5_ctx *ctx, const unsigned char *buf)
#endif
{
    ulong32 i, W[16], a, b, c, d;
#ifdef LTC_SMALL_CODE
    ulong32 t;
#endif

    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LTC_LOAD32L(W[i], buf + (4*i));
    }
 
    /* copy state */
    a = ctx->state[0];
    b = ctx->state[1];
    c = ctx->state[2];
    d = ctx->state[3];

#ifdef LTC_SMALL_CODE
    for (i = 0; i < 16; ++i) {
        FF(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 32; ++i) {
        GG(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 48; ++i) {
        HH(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 64; ++i) {
        II(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

#else
    FF(a,b,c,d,W[0],7,0xd76aa478UL)
    FF(d,a,b,c,W[1],12,0xe8c7b756UL)
    FF(c,d,a,b,W[2],17,0x242070dbUL)
    FF(b,c,d,a,W[3],22,0xc1bdceeeUL)
    FF(a,b,c,d,W[4],7,0xf57c0fafUL)
    FF(d,a,b,c,W[5],12,0x4787c62aUL)
    FF(c,d,a,b,W[6],17,0xa8304613UL)
    FF(b,c,d,a,W[7],22,0xfd469501UL)
    FF(a,b,c,d,W[8],7,0x698098d8UL)
    FF(d,a,b,c,W[9],12,0x8b44f7afUL)
    FF(c,d,a,b,W[10],17,0xffff5bb1UL)
    FF(b,c,d,a,W[11],22,0x895cd7beUL)
    FF(a,b,c,d,W[12],7,0x6b901122UL)
    FF(d,a,b,c,W[13],12,0xfd987193UL)
    FF(c,d,a,b,W[14],17,0xa679438eUL)
    FF(b,c,d,a,W[15],22,0x49b40821UL)
    GG(a,b,c,d,W[1],5,0xf61e2562UL)
    GG(d,a,b,c,W[6],9,0xc040b340UL)
    GG(c,d,a,b,W[11],14,0x265e5a51UL)
    GG(b,c,d,a,W[0],20,0xe9b6c7aaUL)
    GG(a,b,c,d,W[5],5,0xd62f105dUL)
    GG(d,a,b,c,W[10],9,0x02441453UL)
    GG(c,d,a,b,W[15],14,0xd8a1e681UL)
    GG(b,c,d,a,W[4],20,0xe7d3fbc8UL)
    GG(a,b,c,d,W[9],5,0x21e1cde6UL)
    GG(d,a,b,c,W[14],9,0xc33707d6UL)
    GG(c,d,a,b,W[3],14,0xf4d50d87UL)
    GG(b,c,d,a,W[8],20,0x455a14edUL)
    GG(a,b,c,d,W[13],5,0xa9e3e905UL)
    GG(d,a,b,c,W[2],9,0xfcefa3f8UL)
    GG(c,d,a,b,W[7],14,0x676f02d9UL)
    GG(b,c,d,a,W[12],20,0x8d2a4c8aUL)
    HH(a,b,c,d,W[5],4,0xfffa3942UL)
    HH(d,a,b,c,W[8],11,0x8771f681UL)
    HH(c,d,a,b,W[11],16,0x6d9d6122UL)
    HH(b,c,d,a,W[14],23,0xfde5380cUL)
    HH(a,b,c,d,W[1],4,0xa4beea44UL)
    HH(d,a,b,c,W[4],11,0x4bdecfa9UL)
    HH(c,d,a,b,W[7],16,0xf6bb4b60UL)
    HH(b,c,d,a,W[10],23,0xbebfbc70UL)
    HH(a,b,c,d,W[13],4,0x289b7ec6UL)
    HH(d,a,b,c,W[0],11,0xeaa127faUL)
    HH(c,d,a,b,W[3],16,0xd4ef3085UL)
    HH(b,c,d,a,W[6],23,0x04881d05UL)
    HH(a,b,c,d,W[9],4,0xd9d4d039UL)
    HH(d,a,b,c,W[12],11,0xe6db99e5UL)
    HH(c,d,a,b,W[15],16,0x1fa27cf8UL)
    HH(b,c,d,a,W[2],23,0xc4ac5665UL)
    II(a,b,c,d,W[0],6,0xf4292244UL)
    II(d,a,b,c,W[7],10,0x432aff97UL)
    II(c,d,a,b,W[14],15,0xab9423a7UL)
    II(b,c,d,a,W[5],21,0xfc93a039UL)
    II(a,b,c,d,W[12],6,0x655b59c3UL)
    II(d,a,b,c,W[3],10,0x8f0ccc92UL)
    II(c,d,a,b,W[10],15,0xffeff47dUL)
    II(b,c,d,a,W[1],21,0x85845dd1UL)
    II(a,b,c,d,W[8],6,0x6fa87e4fUL)
    II(d,a,b,c,W[15],10,0xfe2ce6e0UL)
    II(c,d,a,b,W[6],15,0xa3014314UL)
    II(b,c,d,a,W[13],21,0x4e0811a1UL)
    II(a,b,c,d,W[4],6,0xf7537e82UL)
    II(d,a,b,c,W[11],10,0xbd3af235UL)
    II(c,d,a,b,W[2],15,0x2ad7d2bbUL)
    II(b,c,d,a,W[9],21,0xeb86d391UL)
#endif

    ctx->state[0] = ctx->state[0] + a;
    ctx->state[1] = ctx->state[1] + b;
    ctx->state[2] = ctx->state[2] + c;
    ctx->state[3] = ctx->state[3] + d;

    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int md5_compress(ltc_md5_ctx *ctx, const unsigned char *buf)
{
   int err;
   err = _md5_compress(ctx, buf);

   // ltc_burn_stack(sizeof(ulong32) * 21);
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_md5_init(ltc_md5_ctx *ctx)
{

   LTC_ARGCHK(ctx != NULL);

   ctx->state[0] = 0x67452301UL;
   ctx->state[1] = 0xefcdab89UL;
   ctx->state[2] = 0x98badcfeUL;
   ctx->state[3] = 0x10325476UL;
   ctx->curlen = 0;
   ctx->length = 0;

   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
// LTC_HASH_PROCESS(ltc_md5_process, md5_compress, ltc_md5_ctx, md5, 64)
int ltc_md5_process(ltc_md5_ctx *ctx, const unsigned char *in, unsigned long inlen)
{
    unsigned long n; 
    int err;
    int fullblocks, remainder, processed;
    
    LTC_ARGCHK(ctx != NULL); 
    LTC_ARGCHK(in != NULL);
    
    if (ctx->curlen > sizeof(ctx->buf)) {
        return CRYPT_INVALID_ARG;
    } 
    if ((ctx->length + inlen) < ctx->length) { 
        return CRYPT_HASH_OVERFLOW; 
    }    
    
    while (inlen > 0) { 
        if (ctx->curlen == 0 && inlen >= LTC_MD5_BLOCKSIZE) {
            if ((err = md5_compress(ctx, in)) != CRYPT_OK) {
                return err;
            }
            ctx->length += LTC_MD5_BLOCKSIZE * 8; 
            in += LTC_MD5_BLOCKSIZE;
            inlen -= LTC_MD5_BLOCKSIZE; 
        } else {
            n = MIN(inlen, (LTC_MD5_BLOCKSIZE - ctx->curlen)); 
            CC_XMEMCPY(ctx->buf + ctx->curlen, in, n); 
            ctx->curlen += n; in += n; inlen -= n; 
            if (ctx->curlen == LTC_MD5_BLOCKSIZE) {
                if ((err = md5_compress(ctx, ctx->buf)) != CRYPT_OK) {
                    return err;
                }
                ctx->length += 8*LTC_MD5_BLOCKSIZE;
                ctx->curlen = 0; 
            } 
        } 
    }
    
    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (16 bytes)
   @return CRYPT_OK if successful
*/
int ltc_md5_done(ltc_md5_ctx *ctx, unsigned char *out)
{
    int i;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    ctx->length += ctx->curlen * 8;

    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 56) {
        while (ctx->curlen < 64) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        md5_compress(ctx, ctx->buf);
        ctx->curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (ctx->curlen < 56) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64L(ctx->length, ctx->buf+56);
    md5_compress(ctx, ctx->buf);

    /* copy output */
    for (i = 0; i < 4; i++) {
        LTC_STORE32L(ctx->state[i], out+(4*i));
    }
    ctx->curlen = 0;
    return CRYPT_OK;
}

Added Source/descriptors/digestDescriptors/ltc_md5_descriptor/ltc_md5.h.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_md5.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>
#ifndef _LTC_MD5_H_
#define _LTC_MD5_H_

#define LTC_MD5_HASHSIZE	16
#define LTC_MD5_BLOCKSIZE	64

typedef struct ltc_md5_state {
    uint32_t state[4];
    uint64_t length;
    unsigned char buf[LTC_MD5_BLOCKSIZE];
    uint32_t curlen;
} ltc_md5_ctx;

int ltc_md5_init(ltc_md5_ctx *ctx);
int ltc_md5_process(ltc_md5_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int ltc_md5_done(ltc_md5_ctx *ctx, unsigned char *hash);
int ltc_md5_test(void);

#endif /* _LTC_MD5_H_ */

Added Source/descriptors/digestDescriptors/ltc_md5_descriptor/ltc_md5/ltc_md5.c.

































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file ltc_md5.c
  LTC_MD5 hash function by Tom St Denis 
*/

#ifdef LTC_MD5

cc_implementation_info ltc_md5_impinfo = {
    .suiteMask = CC_COMPATIBILITY_SUITE,
    .name = "md5",
    .classification_id = digest,
    .identifier = LTC_MD5_ID,
};

const struct ltc_hash_descriptor ltc_md5_desc =
{
    .implementation_info = &ltc_md5_impinfo,
	.hashsize = LTC_MD5_HASHSIZE,
	.blocksize = LTC_MD5_BLOCKSIZE,
	.OID = { 1, 2, 840, 113549, 2, 5, },
	.OIDlen = 6,
	.init = &ltc_md5_init,
	.process = &ltc_md5_process,
	.done = &ltc_md5_done,
	.test = &ltc_md5_test,
	.hmac_block = NULL
};

#define F(x,y,z)  (z ^ (x & (y ^ z)))
#define G(x,y,z)  (y ^ (z & (y ^ x)))
#define H(x,y,z)  (x^y^z)
#define I(x,y,z)  (y^(x|(~z)))

#ifdef LTC_SMALL_CODE

#define FF(a,b,c,d,M,s,t) \
    a = (a + F(b,c,d) + M + t); a = ROL(a, s) + b;

#define GG(a,b,c,d,M,s,t) \
    a = (a + G(b,c,d) + M + t); a = ROL(a, s) + b;

#define HH(a,b,c,d,M,s,t) \
    a = (a + H(b,c,d) + M + t); a = ROL(a, s) + b;

#define II(a,b,c,d,M,s,t) \
    a = (a + I(b,c,d) + M + t); a = ROL(a, s) + b;

static const unsigned char Worder[64] = {
   0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
   1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,
   5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,
   0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9
};

static const unsigned char Rorder[64] = {
   7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,
   5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,
   4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,
   6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21
};

static const ulong32 Korder[64] = {
0xd76aa478UL, 0xe8c7b756UL, 0x242070dbUL, 0xc1bdceeeUL, 0xf57c0fafUL, 0x4787c62aUL, 0xa8304613UL, 0xfd469501UL,
0x698098d8UL, 0x8b44f7afUL, 0xffff5bb1UL, 0x895cd7beUL, 0x6b901122UL, 0xfd987193UL, 0xa679438eUL, 0x49b40821UL,
0xf61e2562UL, 0xc040b340UL, 0x265e5a51UL, 0xe9b6c7aaUL, 0xd62f105dUL, 0x02441453UL, 0xd8a1e681UL, 0xe7d3fbc8UL,
0x21e1cde6UL, 0xc33707d6UL, 0xf4d50d87UL, 0x455a14edUL, 0xa9e3e905UL, 0xfcefa3f8UL, 0x676f02d9UL, 0x8d2a4c8aUL,
0xfffa3942UL, 0x8771f681UL, 0x6d9d6122UL, 0xfde5380cUL, 0xa4beea44UL, 0x4bdecfa9UL, 0xf6bb4b60UL, 0xbebfbc70UL,
0x289b7ec6UL, 0xeaa127faUL, 0xd4ef3085UL, 0x04881d05UL, 0xd9d4d039UL, 0xe6db99e5UL, 0x1fa27cf8UL, 0xc4ac5665UL,
0xf4292244UL, 0x432aff97UL, 0xab9423a7UL, 0xfc93a039UL, 0x655b59c3UL, 0x8f0ccc92UL, 0xffeff47dUL, 0x85845dd1UL,
0x6fa87e4fUL, 0xfe2ce6e0UL, 0xa3014314UL, 0x4e0811a1UL, 0xf7537e82UL, 0xbd3af235UL, 0x2ad7d2bbUL, 0xeb86d391UL
};

#else

#define FF(a,b,c,d,M,s,t) \
    a = (a + F(b,c,d) + M + t); a = LTC_ROLc(a, s) + b;

#define GG(a,b,c,d,M,s,t) \
    a = (a + G(b,c,d) + M + t); a = LTC_ROLc(a, s) + b;

#define HH(a,b,c,d,M,s,t) \
    a = (a + H(b,c,d) + M + t); a = LTC_ROLc(a, s) + b;

#define II(a,b,c,d,M,s,t) \
    a = (a + I(b,c,d) + M + t); a = LTC_ROLc(a, s) + b;


#endif   

#ifdef LTC_CLEAN_STACK
static int _md5_compress(ltc_hstate_ptr md, const unsigned char *buf)
#else
static int  md5_compress(ltc_hstate_ptr md, const unsigned char *buf)
#endif
{
    ulong32 i, W[16], a, b, c, d;
#ifdef LTC_SMALL_CODE
    ulong32 t;
#endif
    ltc_md5_ctx *ctx; 

    ctx = &md->md5;

    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LTC_LOAD32L(W[i], buf + (4*i));
    }
 
    /* copy state */
    a = ctx->state[0];
    b = ctx->state[1];
    c = ctx->state[2];
    d = ctx->state[3];

#ifdef LTC_SMALL_CODE
    for (i = 0; i < 16; ++i) {
        FF(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 32; ++i) {
        GG(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 48; ++i) {
        HH(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 64; ++i) {
        II(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

#else
    FF(a,b,c,d,W[0],7,0xd76aa478UL)
    FF(d,a,b,c,W[1],12,0xe8c7b756UL)
    FF(c,d,a,b,W[2],17,0x242070dbUL)
    FF(b,c,d,a,W[3],22,0xc1bdceeeUL)
    FF(a,b,c,d,W[4],7,0xf57c0fafUL)
    FF(d,a,b,c,W[5],12,0x4787c62aUL)
    FF(c,d,a,b,W[6],17,0xa8304613UL)
    FF(b,c,d,a,W[7],22,0xfd469501UL)
    FF(a,b,c,d,W[8],7,0x698098d8UL)
    FF(d,a,b,c,W[9],12,0x8b44f7afUL)
    FF(c,d,a,b,W[10],17,0xffff5bb1UL)
    FF(b,c,d,a,W[11],22,0x895cd7beUL)
    FF(a,b,c,d,W[12],7,0x6b901122UL)
    FF(d,a,b,c,W[13],12,0xfd987193UL)
    FF(c,d,a,b,W[14],17,0xa679438eUL)
    FF(b,c,d,a,W[15],22,0x49b40821UL)
    GG(a,b,c,d,W[1],5,0xf61e2562UL)
    GG(d,a,b,c,W[6],9,0xc040b340UL)
    GG(c,d,a,b,W[11],14,0x265e5a51UL)
    GG(b,c,d,a,W[0],20,0xe9b6c7aaUL)
    GG(a,b,c,d,W[5],5,0xd62f105dUL)
    GG(d,a,b,c,W[10],9,0x02441453UL)
    GG(c,d,a,b,W[15],14,0xd8a1e681UL)
    GG(b,c,d,a,W[4],20,0xe7d3fbc8UL)
    GG(a,b,c,d,W[9],5,0x21e1cde6UL)
    GG(d,a,b,c,W[14],9,0xc33707d6UL)
    GG(c,d,a,b,W[3],14,0xf4d50d87UL)
    GG(b,c,d,a,W[8],20,0x455a14edUL)
    GG(a,b,c,d,W[13],5,0xa9e3e905UL)
    GG(d,a,b,c,W[2],9,0xfcefa3f8UL)
    GG(c,d,a,b,W[7],14,0x676f02d9UL)
    GG(b,c,d,a,W[12],20,0x8d2a4c8aUL)
    HH(a,b,c,d,W[5],4,0xfffa3942UL)
    HH(d,a,b,c,W[8],11,0x8771f681UL)
    HH(c,d,a,b,W[11],16,0x6d9d6122UL)
    HH(b,c,d,a,W[14],23,0xfde5380cUL)
    HH(a,b,c,d,W[1],4,0xa4beea44UL)
    HH(d,a,b,c,W[4],11,0x4bdecfa9UL)
    HH(c,d,a,b,W[7],16,0xf6bb4b60UL)
    HH(b,c,d,a,W[10],23,0xbebfbc70UL)
    HH(a,b,c,d,W[13],4,0x289b7ec6UL)
    HH(d,a,b,c,W[0],11,0xeaa127faUL)
    HH(c,d,a,b,W[3],16,0xd4ef3085UL)
    HH(b,c,d,a,W[6],23,0x04881d05UL)
    HH(a,b,c,d,W[9],4,0xd9d4d039UL)
    HH(d,a,b,c,W[12],11,0xe6db99e5UL)
    HH(c,d,a,b,W[15],16,0x1fa27cf8UL)
    HH(b,c,d,a,W[2],23,0xc4ac5665UL)
    II(a,b,c,d,W[0],6,0xf4292244UL)
    II(d,a,b,c,W[7],10,0x432aff97UL)
    II(c,d,a,b,W[14],15,0xab9423a7UL)
    II(b,c,d,a,W[5],21,0xfc93a039UL)
    II(a,b,c,d,W[12],6,0x655b59c3UL)
    II(d,a,b,c,W[3],10,0x8f0ccc92UL)
    II(c,d,a,b,W[10],15,0xffeff47dUL)
    II(b,c,d,a,W[1],21,0x85845dd1UL)
    II(a,b,c,d,W[8],6,0x6fa87e4fUL)
    II(d,a,b,c,W[15],10,0xfe2ce6e0UL)
    II(c,d,a,b,W[6],15,0xa3014314UL)
    II(b,c,d,a,W[13],21,0x4e0811a1UL)
    II(a,b,c,d,W[4],6,0xf7537e82UL)
    II(d,a,b,c,W[11],10,0xbd3af235UL)
    II(c,d,a,b,W[2],15,0x2ad7d2bbUL)
    II(b,c,d,a,W[9],21,0xeb86d391UL)
#endif

    ctx->state[0] = ctx->state[0] + a;
    ctx->state[1] = ctx->state[1] + b;
    ctx->state[2] = ctx->state[2] + c;
    ctx->state[3] = ctx->state[3] + d;

    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int md5_compress(ltc_hstate_ptr md, const unsigned char *buf)
{
   int err;
   err = _md5_compress(md, buf);

   ltc_burn_stack(sizeof(ulong32) * 21);
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_md5_init(ltc_hstate_ptr md)
{
   ltc_md5_ctx *ctx;

   LTC_ARGCHK(md != NULL);

   ctx = &md->md5;

   ctx->state[0] = 0x67452301UL;
   ctx->state[1] = 0xefcdab89UL;
   ctx->state[2] = 0x98badcfeUL;
   ctx->state[3] = 0x10325476UL;
   ctx->curlen = 0;
   ctx->length = 0;

   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
LTC_HASH_PROCESS(ltc_md5_process, md5_compress, ltc_md5_ctx, md5, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (16 bytes)
   @return CRYPT_OK if successful
*/
int ltc_md5_done(ltc_hstate_ptr md, unsigned char *out)
{
    int i;
    ltc_md5_ctx *ctx;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    ctx = &md->md5;

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    ctx->length += ctx->curlen * 8;

    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 56) {
        while (ctx->curlen < 64) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        md5_compress(md, ctx->buf);
        ctx->curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (ctx->curlen < 56) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64L(ctx->length, ctx->buf+56);
    md5_compress(md, ctx->buf);

    /* copy output */
    for (i = 0; i < 4; i++) {
        LTC_STORE32L(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(md, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  ltc_md5_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      const char *msg;
      unsigned char hash[16];
  } tests[] = {
    { "",
      { 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 
        0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e } },
    { "a",
      {0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8, 
       0x31, 0xc3, 0x99, 0xe2, 0x69, 0x77, 0x26, 0x61 } },
    { "abc",
      { 0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0, 
        0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72 } },
    { "message digest", 
      { 0xf9, 0x6b, 0x69, 0x7d, 0x7c, 0xb7, 0x93, 0x8d, 
        0x52, 0x5a, 0x2f, 0x31, 0xaa, 0xf1, 0x61, 0xd0 } }, 
    { "abcdefghijklmnopqrstuvwxyz",
      { 0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 
        0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b } },
    { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
      { 0xd1, 0x74, 0xab, 0x98, 0xd2, 0x77, 0xd9, 0xf5, 
        0xa5, 0x61, 0x1c, 0x2c, 0x9f, 0x41, 0x9d, 0x9f } },
    { "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
      { 0x57, 0xed, 0xf4, 0xa2, 0x2b, 0xe3, 0xc9, 0x55, 
        0xac, 0x49, 0xda, 0x2e, 0x21, 0x07, 0xb6, 0x7a } }, 
    { NULL, { 0 } }
  };

  int i;
  unsigned char tmp[16];
  ltc_hash_state md;

  for (i = 0; tests[i].msg != NULL; i++) {
      ltc_md5_init(&md);
      ltc_md5_process(&md, (const unsigned char *)tests[i].msg, (unsigned long)strlen(tests[i].msg));
      ltc_md5_done(&md, tmp);
      if (LTC_XMEMCMP(tmp, tests[i].hash, 16) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
 #endif
}

#endif /* LTC_MD5 */

Added Source/descriptors/digestDescriptors/ltc_md5_descriptor/ltc_md5/ltc_md5.h.









































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_md5.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#ifndef _LTC_MD5_H_
#define _LTC_MD5_H_

#define LTC_MD5_HASHSIZE	16
#define LTC_MD5_BLOCKSIZE	64

typedef struct ltc_md5_state {
    ulong64 length;
    ulong32 state[4], curlen;
    unsigned char buf[LTC_MD5_BLOCKSIZE];
} ltc_md5_ctx;

int ltc_md5_init(ltc_hstate_ptr md);
int ltc_md5_process(ltc_hstate_ptr md, const unsigned char *in,
    unsigned long inlen);
int ltc_md5_done(ltc_hstate_ptr md, unsigned char *hash);
int ltc_md5_test(void);
extern const struct ltc_hash_descriptor ltc_md5_desc;

#endif /* _LTC_MD5_H_ */

Added Source/descriptors/digestDescriptors/ltc_rmd_descriptor/ltc_rmd128.c.





























































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <stdio.h>
#include "ltc_rmd128.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"
#include "CommonDigestSPI.h"

/**
   @param ltc_rmd128.c
   RMD128 Hash function
*/   

/* Implementation of LTC_RIPEMD-128 based on the source by Antoon Bosselaers,
 * ESAT-COSIC
 *
 * This source has been radically overhauled to be portable and work within
 * the LibTomCrypt API by Tom St Denis
 */

const ccDescriptor ltc_rmd128_desc = {
    .implementation_info = &cc_rmd128_impinfo,
	.dtype.digest.hashsize = CC_RMD128_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_RMD128_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_rmd128_init,
	.dtype.digest.process = &ltc_rmd128_process,
	.dtype.digest.done = &ltc_rmd128_done,
};


/* the four basic functions F(), G() and H() */
#define F(x, y, z)        ((x) ^ (y) ^ (z)) 
#define G(x, y, z)        (((x) & (y)) | (~(x) & (z))) 
#define H(x, y, z)        (((x) | ~(y)) ^ (z))
#define I(x, y, z)        (((x) & (z)) | ((y) & ~(z))) 
  
/* the eight basic operations FF() through III() */
#define FF(a, b, c, d, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = LTC_ROLc((a), (s));

#define GG(a, b, c, d, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
      (a) = LTC_ROLc((a), (s));

#define HH(a, b, c, d, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
      (a) = LTC_ROLc((a), (s));

#define II(a, b, c, d, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
      (a) = LTC_ROLc((a), (s));

#define FFF(a, b, c, d, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = LTC_ROLc((a), (s));

#define GGG(a, b, c, d, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x6d703ef3UL;\
      (a) = LTC_ROLc((a), (s));

#define HHH(a, b, c, d, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x5c4dd124UL;\
      (a) = LTC_ROLc((a), (s));

#define III(a, b, c, d, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x50a28be6UL;\
      (a) = LTC_ROLc((a), (s));

#ifdef LTC_CLEAN_STACK
static int _rmd128_compress(ltc_rmd128_ctx *ctx, const unsigned char *buf)
#else
static int  rmd128_compress(ltc_rmd128_ctx *ctx, const unsigned char *buf)
#endif
{
   ulong32 aa,bb,cc,dd,aaa,bbb,ccc,ddd,X[16];
   int i;   
   
   /* load words X */
   for (i = 0; i < 16; i++){
      LTC_LOAD32L(X[i], buf + (4 * i));
   }

   /* load state */
   aa = aaa = ctx->state[0];
   bb = bbb = ctx->state[1];
   cc = ccc = ctx->state[2];
   dd = ddd = ctx->state[3];

   /* round 1 */
   FF(aa, bb, cc, dd, X[ 0], 11);
   FF(dd, aa, bb, cc, X[ 1], 14);
   FF(cc, dd, aa, bb, X[ 2], 15);
   FF(bb, cc, dd, aa, X[ 3], 12);
   FF(aa, bb, cc, dd, X[ 4],  5);
   FF(dd, aa, bb, cc, X[ 5],  8);
   FF(cc, dd, aa, bb, X[ 6],  7);
   FF(bb, cc, dd, aa, X[ 7],  9);
   FF(aa, bb, cc, dd, X[ 8], 11);
   FF(dd, aa, bb, cc, X[ 9], 13);
   FF(cc, dd, aa, bb, X[10], 14);
   FF(bb, cc, dd, aa, X[11], 15);
   FF(aa, bb, cc, dd, X[12],  6);
   FF(dd, aa, bb, cc, X[13],  7);
   FF(cc, dd, aa, bb, X[14],  9);
   FF(bb, cc, dd, aa, X[15],  8);
                             
   /* round 2 */
   GG(aa, bb, cc, dd, X[ 7],  7);
   GG(dd, aa, bb, cc, X[ 4],  6);
   GG(cc, dd, aa, bb, X[13],  8);
   GG(bb, cc, dd, aa, X[ 1], 13);
   GG(aa, bb, cc, dd, X[10], 11);
   GG(dd, aa, bb, cc, X[ 6],  9);
   GG(cc, dd, aa, bb, X[15],  7);
   GG(bb, cc, dd, aa, X[ 3], 15);
   GG(aa, bb, cc, dd, X[12],  7);
   GG(dd, aa, bb, cc, X[ 0], 12);
   GG(cc, dd, aa, bb, X[ 9], 15);
   GG(bb, cc, dd, aa, X[ 5],  9);
   GG(aa, bb, cc, dd, X[ 2], 11);
   GG(dd, aa, bb, cc, X[14],  7);
   GG(cc, dd, aa, bb, X[11], 13);
   GG(bb, cc, dd, aa, X[ 8], 12);

   /* round 3 */
   HH(aa, bb, cc, dd, X[ 3], 11);
   HH(dd, aa, bb, cc, X[10], 13);
   HH(cc, dd, aa, bb, X[14],  6);
   HH(bb, cc, dd, aa, X[ 4],  7);
   HH(aa, bb, cc, dd, X[ 9], 14);
   HH(dd, aa, bb, cc, X[15],  9);
   HH(cc, dd, aa, bb, X[ 8], 13);
   HH(bb, cc, dd, aa, X[ 1], 15);
   HH(aa, bb, cc, dd, X[ 2], 14);
   HH(dd, aa, bb, cc, X[ 7],  8);
   HH(cc, dd, aa, bb, X[ 0], 13);
   HH(bb, cc, dd, aa, X[ 6],  6);
   HH(aa, bb, cc, dd, X[13],  5);
   HH(dd, aa, bb, cc, X[11], 12);
   HH(cc, dd, aa, bb, X[ 5],  7);
   HH(bb, cc, dd, aa, X[12],  5);

   /* round 4 */
   II(aa, bb, cc, dd, X[ 1], 11);
   II(dd, aa, bb, cc, X[ 9], 12);
   II(cc, dd, aa, bb, X[11], 14);
   II(bb, cc, dd, aa, X[10], 15);
   II(aa, bb, cc, dd, X[ 0], 14);
   II(dd, aa, bb, cc, X[ 8], 15);
   II(cc, dd, aa, bb, X[12],  9);
   II(bb, cc, dd, aa, X[ 4],  8);
   II(aa, bb, cc, dd, X[13],  9);
   II(dd, aa, bb, cc, X[ 3], 14);
   II(cc, dd, aa, bb, X[ 7],  5);
   II(bb, cc, dd, aa, X[15],  6);
   II(aa, bb, cc, dd, X[14],  8);
   II(dd, aa, bb, cc, X[ 5],  6);
   II(cc, dd, aa, bb, X[ 6],  5);
   II(bb, cc, dd, aa, X[ 2], 12);

   /* parallel round 1 */
   III(aaa, bbb, ccc, ddd, X[ 5],  8); 
   III(ddd, aaa, bbb, ccc, X[14],  9);
   III(ccc, ddd, aaa, bbb, X[ 7],  9);
   III(bbb, ccc, ddd, aaa, X[ 0], 11);
   III(aaa, bbb, ccc, ddd, X[ 9], 13);
   III(ddd, aaa, bbb, ccc, X[ 2], 15);
   III(ccc, ddd, aaa, bbb, X[11], 15);
   III(bbb, ccc, ddd, aaa, X[ 4],  5);
   III(aaa, bbb, ccc, ddd, X[13],  7);
   III(ddd, aaa, bbb, ccc, X[ 6],  7);
   III(ccc, ddd, aaa, bbb, X[15],  8);
   III(bbb, ccc, ddd, aaa, X[ 8], 11);
   III(aaa, bbb, ccc, ddd, X[ 1], 14);
   III(ddd, aaa, bbb, ccc, X[10], 14);
   III(ccc, ddd, aaa, bbb, X[ 3], 12);
   III(bbb, ccc, ddd, aaa, X[12],  6);

   /* parallel round 2 */
   HHH(aaa, bbb, ccc, ddd, X[ 6],  9);
   HHH(ddd, aaa, bbb, ccc, X[11], 13);
   HHH(ccc, ddd, aaa, bbb, X[ 3], 15);
   HHH(bbb, ccc, ddd, aaa, X[ 7],  7);
   HHH(aaa, bbb, ccc, ddd, X[ 0], 12);
   HHH(ddd, aaa, bbb, ccc, X[13],  8);
   HHH(ccc, ddd, aaa, bbb, X[ 5],  9);
   HHH(bbb, ccc, ddd, aaa, X[10], 11);
   HHH(aaa, bbb, ccc, ddd, X[14],  7);
   HHH(ddd, aaa, bbb, ccc, X[15],  7);
   HHH(ccc, ddd, aaa, bbb, X[ 8], 12);
   HHH(bbb, ccc, ddd, aaa, X[12],  7);
   HHH(aaa, bbb, ccc, ddd, X[ 4],  6);
   HHH(ddd, aaa, bbb, ccc, X[ 9], 15);
   HHH(ccc, ddd, aaa, bbb, X[ 1], 13);
   HHH(bbb, ccc, ddd, aaa, X[ 2], 11);

   /* parallel round 3 */   
   GGG(aaa, bbb, ccc, ddd, X[15],  9);
   GGG(ddd, aaa, bbb, ccc, X[ 5],  7);
   GGG(ccc, ddd, aaa, bbb, X[ 1], 15);
   GGG(bbb, ccc, ddd, aaa, X[ 3], 11);
   GGG(aaa, bbb, ccc, ddd, X[ 7],  8);
   GGG(ddd, aaa, bbb, ccc, X[14],  6);
   GGG(ccc, ddd, aaa, bbb, X[ 6],  6);
   GGG(bbb, ccc, ddd, aaa, X[ 9], 14);
   GGG(aaa, bbb, ccc, ddd, X[11], 12);
   GGG(ddd, aaa, bbb, ccc, X[ 8], 13);
   GGG(ccc, ddd, aaa, bbb, X[12],  5);
   GGG(bbb, ccc, ddd, aaa, X[ 2], 14);
   GGG(aaa, bbb, ccc, ddd, X[10], 13);
   GGG(ddd, aaa, bbb, ccc, X[ 0], 13);
   GGG(ccc, ddd, aaa, bbb, X[ 4],  7);
   GGG(bbb, ccc, ddd, aaa, X[13],  5);

   /* parallel round 4 */
   FFF(aaa, bbb, ccc, ddd, X[ 8], 15);
   FFF(ddd, aaa, bbb, ccc, X[ 6],  5);
   FFF(ccc, ddd, aaa, bbb, X[ 4],  8);
   FFF(bbb, ccc, ddd, aaa, X[ 1], 11);
   FFF(aaa, bbb, ccc, ddd, X[ 3], 14);
   FFF(ddd, aaa, bbb, ccc, X[11], 14);
   FFF(ccc, ddd, aaa, bbb, X[15],  6);
   FFF(bbb, ccc, ddd, aaa, X[ 0], 14);
   FFF(aaa, bbb, ccc, ddd, X[ 5],  6);
   FFF(ddd, aaa, bbb, ccc, X[12],  9);
   FFF(ccc, ddd, aaa, bbb, X[ 2], 12);
   FFF(bbb, ccc, ddd, aaa, X[13],  9);
   FFF(aaa, bbb, ccc, ddd, X[ 9], 12);
   FFF(ddd, aaa, bbb, ccc, X[ 7],  5);
   FFF(ccc, ddd, aaa, bbb, X[10], 15);
   FFF(bbb, ccc, ddd, aaa, X[14],  8);

   /* combine results */
   ddd += cc + ctx->state[1];               /* final result for MDbuf[0] */
   ctx->state[1] = ctx->state[2] + dd + aaa;
   ctx->state[2] = ctx->state[3] + aa + bbb;
   ctx->state[3] = ctx->state[0] + bb + ccc;
   ctx->state[0] = ddd;

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int rmd128_compress(ltc_rmd128_ctx *ctx, const unsigned char *buf)
{
   int err;
   err = _rmd128_compress(md, buf);

   ltc_burn_stack(sizeof(ulong32) * 24 + sizeof(int));
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_rmd128_init(ltc_rmd128_ctx *ctx)
{
   LTC_ARGCHK(ctx != NULL);

   ctx->state[0] = 0x67452301UL;
   ctx->state[1] = 0xefcdab89UL;
   ctx->state[2] = 0x98badcfeUL;
   ctx->state[3] = 0x10325476UL;
   ctx->curlen   = 0;
   ctx->length   = 0;
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
LTC_HASH_PROCESS(ltc_rmd128_process, rmd128_compress, ltc_rmd128_ctx, rmd128, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (16 bytes)
   @return CRYPT_OK if successful
*/
int ltc_rmd128_done(ltc_rmd128_ctx *ctx, unsigned char *out)
{
    int i;
    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    ctx->length += ctx->curlen * 8;

    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 56) {
        while (ctx->curlen < 64) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        rmd128_compress(ctx, ctx->buf);
        ctx->curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (ctx->curlen < 56) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64L(ctx->length, ctx->buf+56);
    rmd128_compress(ctx, ctx->buf);

    /* copy output */
    for (i = 0; i < 4; i++) {
        LTC_STORE32L(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(md, sizeof(ltc_hash_state));
#endif
   return CRYPT_OK;  
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int ltc_rmd128_test(void)
{
#ifndef LTC_TEST
   return CRYPT_NOP;
#else
   static const struct {
        const char *msg;
        unsigned char md[16];
   } tests[] = {
   { "",
     { 0xcd, 0xf2, 0x62, 0x13, 0xa1, 0x50, 0xdc, 0x3e,
       0xcb, 0x61, 0x0f, 0x18, 0xf6, 0xb3, 0x8b, 0x46 }
   },
   { "a",
     { 0x86, 0xbe, 0x7a, 0xfa, 0x33, 0x9d, 0x0f, 0xc7,
       0xcf, 0xc7, 0x85, 0xe7, 0x2f, 0x57, 0x8d, 0x33 }
   },
   { "abc",
     { 0xc1, 0x4a, 0x12, 0x19, 0x9c, 0x66, 0xe4, 0xba,
       0x84, 0x63, 0x6b, 0x0f, 0x69, 0x14, 0x4c, 0x77 }
   },
   { "message digest",
     { 0x9e, 0x32, 0x7b, 0x3d, 0x6e, 0x52, 0x30, 0x62,
       0xaf, 0xc1, 0x13, 0x2d, 0x7d, 0xf9, 0xd1, 0xb8 }
   },
   { "abcdefghijklmnopqrstuvwxyz",
     { 0xfd, 0x2a, 0xa6, 0x07, 0xf7, 0x1d, 0xc8, 0xf5,
       0x10, 0x71, 0x49, 0x22, 0xb3, 0x71, 0x83, 0x4e }
   },
   { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
     { 0xd1, 0xe9, 0x59, 0xeb, 0x17, 0x9c, 0x91, 0x1f,
       0xae, 0xa4, 0x62, 0x4c, 0x60, 0xc5, 0xc7, 0x02 }
   }
   };
   int x;
   unsigned char buf[16];
   ltc_hash_state md;

   for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
       ltc_rmd128_init(&md);
       ltc_rmd128_process(&md, (const unsigned char *)tests[x].msg, strlen(tests[x].msg));
       ltc_rmd128_done(&md, buf);
       if (LTC_XMEMCMP(buf, tests[x].md, 16) != 0) {
       #if 0
          printf("Failed test %d\n", x);
       #endif
          return CRYPT_FAIL_TESTVECTOR;
       }
   }
   return CRYPT_OK;
#endif
}

Added Source/descriptors/digestDescriptors/ltc_rmd_descriptor/ltc_rmd128.h.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_rmd128.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>

#ifndef _LTC_RMD128_H_
#define _LTC_RMD128_H_

#define	LTC_RMD128_HASHSIZE	16
#define	LTC_RMD128_BLOCKSIZE	64

typedef struct ltc_rmd128_state {
    uint64_t length;
    uint32_t state[4];
    uint32_t curlen;
    unsigned char buf[LTC_RMD128_BLOCKSIZE];
} ltc_rmd128_ctx;

int ltc_rmd128_init(ltc_rmd128_ctx *ctx);
int ltc_rmd128_process(ltc_rmd128_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int ltc_rmd128_done(ltc_rmd128_ctx *ctx, unsigned char *hash);

#endif /* _LTC_RMD128_H_ */

Added Source/descriptors/digestDescriptors/ltc_rmd_descriptor/ltc_rmd160.c.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <stdio.h>
#include "ltc_rmd160.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"
#include "CommonDigestSPI.h"

/**
   @file ltc_rmd160.c
   RMD160 hash function
*/   

/* Implementation of LTC_RIPEMD-160 based on the source by Antoon Bosselaers,
 * ESAT-COSIC
 *
 * This source has been radically overhauled to be portable and work within
 * the LibTomCrypt API by Tom St Denis
 */

const ccDescriptor ltc_rmd160_desc = {
    .implementation_info = &cc_rmd160_impinfo,
	.dtype.digest.hashsize = CC_RMD160_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_RMD160_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_rmd160_init,
	.dtype.digest.process = &ltc_rmd160_process,
	.dtype.digest.done = &ltc_rmd160_done,
};


/* the five basic functions F(), G() and H() */
#define F(x, y, z)        ((x) ^ (y) ^ (z)) 
#define G(x, y, z)        (((x) & (y)) | (~(x) & (z))) 
#define H(x, y, z)        (((x) | ~(y)) ^ (z))
#define I(x, y, z)        (((x) & (z)) | ((y) & ~(z))) 
#define J(x, y, z)        ((x) ^ ((y) | ~(z)))
  
/* the ten basic operations FF() through III() */
#define FF(a, b, c, d, e, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define GG(a, b, c, d, e, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define HH(a, b, c, d, e, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define II(a, b, c, d, e, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define JJ(a, b, c, d, e, x, s)        \
      (a) += J((b), (c), (d)) + (x) + 0xa953fd4eUL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define FFF(a, b, c, d, e, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define GGG(a, b, c, d, e, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define HHH(a, b, c, d, e, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6d703ef3UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define III(a, b, c, d, e, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x5c4dd124UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define JJJ(a, b, c, d, e, x, s)        \
      (a) += J((b), (c), (d)) + (x) + 0x50a28be6UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);


#ifdef LTC_CLEAN_STACK
static int _rmd160_compress(ltc_rmd160_ctx *ctx, const unsigned char *buf)
#else
static int  rmd160_compress(ltc_rmd160_ctx *ctx, const unsigned char *buf)
#endif
{
   ulong32 aa,bb,cc,dd,ee,aaa,bbb,ccc,ddd,eee,X[16];
   int i;

   /* load words X */
   for (i = 0; i < 16; i++){
      LTC_LOAD32L(X[i], buf + (4 * i));
   }

   /* load state */
   aa = aaa = ctx->state[0];
   bb = bbb = ctx->state[1];
   cc = ccc = ctx->state[2];
   dd = ddd = ctx->state[3];
   ee = eee = ctx->state[4];

   /* round 1 */
   FF(aa, bb, cc, dd, ee, X[ 0], 11);
   FF(ee, aa, bb, cc, dd, X[ 1], 14);
   FF(dd, ee, aa, bb, cc, X[ 2], 15);
   FF(cc, dd, ee, aa, bb, X[ 3], 12);
   FF(bb, cc, dd, ee, aa, X[ 4],  5);
   FF(aa, bb, cc, dd, ee, X[ 5],  8);
   FF(ee, aa, bb, cc, dd, X[ 6],  7);
   FF(dd, ee, aa, bb, cc, X[ 7],  9);
   FF(cc, dd, ee, aa, bb, X[ 8], 11);
   FF(bb, cc, dd, ee, aa, X[ 9], 13);
   FF(aa, bb, cc, dd, ee, X[10], 14);
   FF(ee, aa, bb, cc, dd, X[11], 15);
   FF(dd, ee, aa, bb, cc, X[12],  6);
   FF(cc, dd, ee, aa, bb, X[13],  7);
   FF(bb, cc, dd, ee, aa, X[14],  9);
   FF(aa, bb, cc, dd, ee, X[15],  8);
                             
   /* round 2 */
   GG(ee, aa, bb, cc, dd, X[ 7],  7);
   GG(dd, ee, aa, bb, cc, X[ 4],  6);
   GG(cc, dd, ee, aa, bb, X[13],  8);
   GG(bb, cc, dd, ee, aa, X[ 1], 13);
   GG(aa, bb, cc, dd, ee, X[10], 11);
   GG(ee, aa, bb, cc, dd, X[ 6],  9);
   GG(dd, ee, aa, bb, cc, X[15],  7);
   GG(cc, dd, ee, aa, bb, X[ 3], 15);
   GG(bb, cc, dd, ee, aa, X[12],  7);
   GG(aa, bb, cc, dd, ee, X[ 0], 12);
   GG(ee, aa, bb, cc, dd, X[ 9], 15);
   GG(dd, ee, aa, bb, cc, X[ 5],  9);
   GG(cc, dd, ee, aa, bb, X[ 2], 11);
   GG(bb, cc, dd, ee, aa, X[14],  7);
   GG(aa, bb, cc, dd, ee, X[11], 13);
   GG(ee, aa, bb, cc, dd, X[ 8], 12);

   /* round 3 */
   HH(dd, ee, aa, bb, cc, X[ 3], 11);
   HH(cc, dd, ee, aa, bb, X[10], 13);
   HH(bb, cc, dd, ee, aa, X[14],  6);
   HH(aa, bb, cc, dd, ee, X[ 4],  7);
   HH(ee, aa, bb, cc, dd, X[ 9], 14);
   HH(dd, ee, aa, bb, cc, X[15],  9);
   HH(cc, dd, ee, aa, bb, X[ 8], 13);
   HH(bb, cc, dd, ee, aa, X[ 1], 15);
   HH(aa, bb, cc, dd, ee, X[ 2], 14);
   HH(ee, aa, bb, cc, dd, X[ 7],  8);
   HH(dd, ee, aa, bb, cc, X[ 0], 13);
   HH(cc, dd, ee, aa, bb, X[ 6],  6);
   HH(bb, cc, dd, ee, aa, X[13],  5);
   HH(aa, bb, cc, dd, ee, X[11], 12);
   HH(ee, aa, bb, cc, dd, X[ 5],  7);
   HH(dd, ee, aa, bb, cc, X[12],  5);

   /* round 4 */
   II(cc, dd, ee, aa, bb, X[ 1], 11);
   II(bb, cc, dd, ee, aa, X[ 9], 12);
   II(aa, bb, cc, dd, ee, X[11], 14);
   II(ee, aa, bb, cc, dd, X[10], 15);
   II(dd, ee, aa, bb, cc, X[ 0], 14);
   II(cc, dd, ee, aa, bb, X[ 8], 15);
   II(bb, cc, dd, ee, aa, X[12],  9);
   II(aa, bb, cc, dd, ee, X[ 4],  8);
   II(ee, aa, bb, cc, dd, X[13],  9);
   II(dd, ee, aa, bb, cc, X[ 3], 14);
   II(cc, dd, ee, aa, bb, X[ 7],  5);
   II(bb, cc, dd, ee, aa, X[15],  6);
   II(aa, bb, cc, dd, ee, X[14],  8);
   II(ee, aa, bb, cc, dd, X[ 5],  6);
   II(dd, ee, aa, bb, cc, X[ 6],  5);
   II(cc, dd, ee, aa, bb, X[ 2], 12);

   /* round 5 */
   JJ(bb, cc, dd, ee, aa, X[ 4],  9);
   JJ(aa, bb, cc, dd, ee, X[ 0], 15);
   JJ(ee, aa, bb, cc, dd, X[ 5],  5);
   JJ(dd, ee, aa, bb, cc, X[ 9], 11);
   JJ(cc, dd, ee, aa, bb, X[ 7],  6);
   JJ(bb, cc, dd, ee, aa, X[12],  8);
   JJ(aa, bb, cc, dd, ee, X[ 2], 13);
   JJ(ee, aa, bb, cc, dd, X[10], 12);
   JJ(dd, ee, aa, bb, cc, X[14],  5);
   JJ(cc, dd, ee, aa, bb, X[ 1], 12);
   JJ(bb, cc, dd, ee, aa, X[ 3], 13);
   JJ(aa, bb, cc, dd, ee, X[ 8], 14);
   JJ(ee, aa, bb, cc, dd, X[11], 11);
   JJ(dd, ee, aa, bb, cc, X[ 6],  8);
   JJ(cc, dd, ee, aa, bb, X[15],  5);
   JJ(bb, cc, dd, ee, aa, X[13],  6);

   /* parallel round 1 */
   JJJ(aaa, bbb, ccc, ddd, eee, X[ 5],  8);
   JJJ(eee, aaa, bbb, ccc, ddd, X[14],  9);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 7],  9);
   JJJ(ccc, ddd, eee, aaa, bbb, X[ 0], 11);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 9], 13);
   JJJ(aaa, bbb, ccc, ddd, eee, X[ 2], 15);
   JJJ(eee, aaa, bbb, ccc, ddd, X[11], 15);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 4],  5);
   JJJ(ccc, ddd, eee, aaa, bbb, X[13],  7);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 6],  7);
   JJJ(aaa, bbb, ccc, ddd, eee, X[15],  8);
   JJJ(eee, aaa, bbb, ccc, ddd, X[ 8], 11);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 1], 14);
   JJJ(ccc, ddd, eee, aaa, bbb, X[10], 14);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 3], 12);
   JJJ(aaa, bbb, ccc, ddd, eee, X[12],  6);

   /* parallel round 2 */
   III(eee, aaa, bbb, ccc, ddd, X[ 6],  9); 
   III(ddd, eee, aaa, bbb, ccc, X[11], 13);
   III(ccc, ddd, eee, aaa, bbb, X[ 3], 15);
   III(bbb, ccc, ddd, eee, aaa, X[ 7],  7);
   III(aaa, bbb, ccc, ddd, eee, X[ 0], 12);
   III(eee, aaa, bbb, ccc, ddd, X[13],  8);
   III(ddd, eee, aaa, bbb, ccc, X[ 5],  9);
   III(ccc, ddd, eee, aaa, bbb, X[10], 11);
   III(bbb, ccc, ddd, eee, aaa, X[14],  7);
   III(aaa, bbb, ccc, ddd, eee, X[15],  7);
   III(eee, aaa, bbb, ccc, ddd, X[ 8], 12);
   III(ddd, eee, aaa, bbb, ccc, X[12],  7);
   III(ccc, ddd, eee, aaa, bbb, X[ 4],  6);
   III(bbb, ccc, ddd, eee, aaa, X[ 9], 15);
   III(aaa, bbb, ccc, ddd, eee, X[ 1], 13);
   III(eee, aaa, bbb, ccc, ddd, X[ 2], 11);

   /* parallel round 3 */
   HHH(ddd, eee, aaa, bbb, ccc, X[15],  9);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 5],  7);
   HHH(bbb, ccc, ddd, eee, aaa, X[ 1], 15);
   HHH(aaa, bbb, ccc, ddd, eee, X[ 3], 11);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 7],  8);
   HHH(ddd, eee, aaa, bbb, ccc, X[14],  6);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 6],  6);
   HHH(bbb, ccc, ddd, eee, aaa, X[ 9], 14);
   HHH(aaa, bbb, ccc, ddd, eee, X[11], 12);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 8], 13);
   HHH(ddd, eee, aaa, bbb, ccc, X[12],  5);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 2], 14);
   HHH(bbb, ccc, ddd, eee, aaa, X[10], 13);
   HHH(aaa, bbb, ccc, ddd, eee, X[ 0], 13);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 4],  7);
   HHH(ddd, eee, aaa, bbb, ccc, X[13],  5);

   /* parallel round 4 */   
   GGG(ccc, ddd, eee, aaa, bbb, X[ 8], 15);
   GGG(bbb, ccc, ddd, eee, aaa, X[ 6],  5);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 4],  8);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 1], 11);
   GGG(ddd, eee, aaa, bbb, ccc, X[ 3], 14);
   GGG(ccc, ddd, eee, aaa, bbb, X[11], 14);
   GGG(bbb, ccc, ddd, eee, aaa, X[15],  6);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 0], 14);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 5],  6);
   GGG(ddd, eee, aaa, bbb, ccc, X[12],  9);
   GGG(ccc, ddd, eee, aaa, bbb, X[ 2], 12);
   GGG(bbb, ccc, ddd, eee, aaa, X[13],  9);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 9], 12);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 7],  5);
   GGG(ddd, eee, aaa, bbb, ccc, X[10], 15);
   GGG(ccc, ddd, eee, aaa, bbb, X[14],  8);

   /* parallel round 5 */
   FFF(bbb, ccc, ddd, eee, aaa, X[12] ,  8);
   FFF(aaa, bbb, ccc, ddd, eee, X[15] ,  5);
   FFF(eee, aaa, bbb, ccc, ddd, X[10] , 12);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 4] ,  9);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 1] , 12);
   FFF(bbb, ccc, ddd, eee, aaa, X[ 5] ,  5);
   FFF(aaa, bbb, ccc, ddd, eee, X[ 8] , 14);
   FFF(eee, aaa, bbb, ccc, ddd, X[ 7] ,  6);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 6] ,  8);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 2] , 13);
   FFF(bbb, ccc, ddd, eee, aaa, X[13] ,  6);
   FFF(aaa, bbb, ccc, ddd, eee, X[14] ,  5);
   FFF(eee, aaa, bbb, ccc, ddd, X[ 0] , 15);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 3] , 13);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 9] , 11);
   FFF(bbb, ccc, ddd, eee, aaa, X[11] , 11);

   /* combine results */
   ddd += cc + ctx->state[1];               /* final result for ctx->state[0] */
   ctx->state[1] = ctx->state[2] + dd + eee;
   ctx->state[2] = ctx->state[3] + ee + aaa;
   ctx->state[3] = ctx->state[4] + aa + bbb;
   ctx->state[4] = ctx->state[0] + bb + ccc;
   ctx->state[0] = ddd;

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int rmd160_compress(ltc_rmd160_ctx *ctx, const unsigned char *buf)
{
   int err;
   err = _rmd160_compress(md, buf);

   ltc_burn_stack(sizeof(ulong32) * 26 + sizeof(int));
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_rmd160_init(ltc_rmd160_ctx *ctx)
{
   LTC_ARGCHK(ctx != NULL);

   ctx->state[0] = 0x67452301UL;
   ctx->state[1] = 0xefcdab89UL;
   ctx->state[2] = 0x98badcfeUL;
   ctx->state[3] = 0x10325476UL;
   ctx->state[4] = 0xc3d2e1f0UL;
   ctx->curlen   = 0;
   ctx->length   = 0;

   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
LTC_HASH_PROCESS(ltc_rmd160_process, rmd160_compress, ltc_rmd160_ctx, rmd160, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (20 bytes)
   @return CRYPT_OK if successful
*/
int ltc_rmd160_done(ltc_rmd160_ctx *ctx, unsigned char *out)
{
    int i;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    ctx->length += ctx->curlen * 8;

    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 56) {
        while (ctx->curlen < 64) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        rmd160_compress(ctx, ctx->buf);
        ctx->curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (ctx->curlen < 56) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64L(ctx->length, ctx->buf+56);
    rmd160_compress(ctx, ctx->buf);

    /* copy output */
    for (i = 0; i < 5; i++) {
        LTC_STORE32L(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(md, sizeof(ltc_hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int ltc_rmd160_test(void)
{
#ifndef LTC_TEST
   return CRYPT_NOP;
#else
   static const struct {
        const char *msg;
        unsigned char md[20];
   } tests[] = {
   { "",
     { 0x9c, 0x11, 0x85, 0xa5, 0xc5, 0xe9, 0xfc, 0x54, 0x61, 0x28,
       0x08, 0x97, 0x7e, 0xe8, 0xf5, 0x48, 0xb2, 0x25, 0x8d, 0x31 }
   },
   { "a",
     { 0x0b, 0xdc, 0x9d, 0x2d, 0x25, 0x6b, 0x3e, 0xe9, 0xda, 0xae,
       0x34, 0x7b, 0xe6, 0xf4, 0xdc, 0x83, 0x5a, 0x46, 0x7f, 0xfe }
   },
   { "abc",
     { 0x8e, 0xb2, 0x08, 0xf7, 0xe0, 0x5d, 0x98, 0x7a, 0x9b, 0x04,
       0x4a, 0x8e, 0x98, 0xc6, 0xb0, 0x87, 0xf1, 0x5a, 0x0b, 0xfc }
   },
   { "message digest",
     { 0x5d, 0x06, 0x89, 0xef, 0x49, 0xd2, 0xfa, 0xe5, 0x72, 0xb8,
       0x81, 0xb1, 0x23, 0xa8, 0x5f, 0xfa, 0x21, 0x59, 0x5f, 0x36 }
   },
   { "abcdefghijklmnopqrstuvwxyz",
     { 0xf7, 0x1c, 0x27, 0x10, 0x9c, 0x69, 0x2c, 0x1b, 0x56, 0xbb,
       0xdc, 0xeb, 0x5b, 0x9d, 0x28, 0x65, 0xb3, 0x70, 0x8d, 0xbc }
   },
   { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
     { 0x12, 0xa0, 0x53, 0x38, 0x4a, 0x9c, 0x0c, 0x88, 0xe4, 0x05,
       0xa0, 0x6c, 0x27, 0xdc, 0xf4, 0x9a, 0xda, 0x62, 0xeb, 0x2b }
   }
   };
   int x;
   unsigned char buf[20];
   ltc_hash_state md;

   for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
       ltc_rmd160_init(&md);
       ltc_rmd160_process(&md, (const unsigned char *)tests[x].msg,
	   strlen(tests[x].msg));
       ltc_rmd160_done(&md, buf);
       if (LTC_XMEMCMP(buf, tests[x].md, 20) != 0) {
#if 0
          printf("Failed test %d\n", x);
#endif
          return CRYPT_FAIL_TESTVECTOR;
       }
   }
   return CRYPT_OK;
#endif
}

Added Source/descriptors/digestDescriptors/ltc_rmd_descriptor/ltc_rmd160.h.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_rmd160.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>

#ifndef _LTC_RMD160_H_
#define _LTC_RMD160_H_

#define	LTC_RMD160_HASHSIZE	20
#define	LTC_RMD160_BLOCKSIZE	64

typedef struct ltc_rmd160_state {
    uint64_t length;
    uint32_t state[5];
    uint32_t curlen;
    unsigned char buf[LTC_RMD160_BLOCKSIZE];
} ltc_rmd160_ctx;

int ltc_rmd160_init(ltc_rmd160_ctx *ctx);
int ltc_rmd160_process(ltc_rmd160_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int ltc_rmd160_done(ltc_rmd160_ctx *ctx, unsigned char *hash);

#endif /* _LTC_RMD160_H_ */

Added Source/descriptors/digestDescriptors/ltc_rmd_descriptor/ltc_rmd256.c.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <stdio.h>
#include "ltc_rmd256.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"
#include "CommonDigestSPI.h"

/**
   @param ltc_rmd256.c
   RLTC_MD256 Hash function
*/

const ccDescriptor ltc_rmd256_desc = {
    .implementation_info = &cc_rmd256_impinfo,
	.dtype.digest.hashsize = CC_RMD256_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_RMD256_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_rmd256_init,
	.dtype.digest.process = &ltc_rmd256_process,
	.dtype.digest.done = &ltc_rmd256_done,
};


/* the four basic functions F(), G() and H() */
#define F(x, y, z)        ((x) ^ (y) ^ (z))
#define G(x, y, z)        (((x) & (y)) | (~(x) & (z)))
#define H(x, y, z)        (((x) | ~(y)) ^ (z))
#define I(x, y, z)        (((x) & (z)) | ((y) & ~(z)))

/* the eight basic operations FF() through III() */
#define FF(a, b, c, d, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = LTC_ROLc((a), (s));

#define GG(a, b, c, d, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
      (a) = LTC_ROLc((a), (s));

#define HH(a, b, c, d, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
      (a) = LTC_ROLc((a), (s));

#define II(a, b, c, d, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
      (a) = LTC_ROLc((a), (s));

#define FFF(a, b, c, d, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = LTC_ROLc((a), (s));

#define GGG(a, b, c, d, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x6d703ef3UL;\
      (a) = LTC_ROLc((a), (s));

#define HHH(a, b, c, d, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x5c4dd124UL;\
      (a) = LTC_ROLc((a), (s));

#define III(a, b, c, d, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x50a28be6UL;\
      (a) = LTC_ROLc((a), (s));

#ifdef LTC_CLEAN_STACK
static int _rmd256_compress(ltc_rmd256_ctx *ctx, const unsigned char *buf)
#else
static int  rmd256_compress(ltc_rmd256_ctx *ctx, const unsigned char *buf)
#endif
{
   ulong32 aa,bb,cc,dd,aaa,bbb,ccc,ddd,tmp,X[16];
   int i;   

   /* load words X */
   for (i = 0; i < 16; i++){
      LTC_LOAD32L(X[i], buf + (4 * i));
   }

   /* load state */
   aa = ctx->state[0];
   bb = ctx->state[1];
   cc = ctx->state[2];
   dd = ctx->state[3];
   aaa = ctx->state[4];
   bbb = ctx->state[5];
   ccc = ctx->state[6];
   ddd = ctx->state[7];

   /* round 1 */
   FF(aa, bb, cc, dd, X[ 0], 11);
   FF(dd, aa, bb, cc, X[ 1], 14);
   FF(cc, dd, aa, bb, X[ 2], 15);
   FF(bb, cc, dd, aa, X[ 3], 12);
   FF(aa, bb, cc, dd, X[ 4],  5);
   FF(dd, aa, bb, cc, X[ 5],  8);
   FF(cc, dd, aa, bb, X[ 6],  7);
   FF(bb, cc, dd, aa, X[ 7],  9);
   FF(aa, bb, cc, dd, X[ 8], 11);
   FF(dd, aa, bb, cc, X[ 9], 13);
   FF(cc, dd, aa, bb, X[10], 14);
   FF(bb, cc, dd, aa, X[11], 15);
   FF(aa, bb, cc, dd, X[12],  6);
   FF(dd, aa, bb, cc, X[13],  7);
   FF(cc, dd, aa, bb, X[14],  9);
   FF(bb, cc, dd, aa, X[15],  8);

   /* parallel round 1 */
   III(aaa, bbb, ccc, ddd, X[ 5],  8);
   III(ddd, aaa, bbb, ccc, X[14],  9);
   III(ccc, ddd, aaa, bbb, X[ 7],  9);
   III(bbb, ccc, ddd, aaa, X[ 0], 11);
   III(aaa, bbb, ccc, ddd, X[ 9], 13);
   III(ddd, aaa, bbb, ccc, X[ 2], 15);
   III(ccc, ddd, aaa, bbb, X[11], 15);
   III(bbb, ccc, ddd, aaa, X[ 4],  5);
   III(aaa, bbb, ccc, ddd, X[13],  7);
   III(ddd, aaa, bbb, ccc, X[ 6],  7);
   III(ccc, ddd, aaa, bbb, X[15],  8);
   III(bbb, ccc, ddd, aaa, X[ 8], 11);
   III(aaa, bbb, ccc, ddd, X[ 1], 14);
   III(ddd, aaa, bbb, ccc, X[10], 14);
   III(ccc, ddd, aaa, bbb, X[ 3], 12);
   III(bbb, ccc, ddd, aaa, X[12],  6);

   tmp = aa; aa = aaa; aaa = tmp;

   /* round 2 */
   GG(aa, bb, cc, dd, X[ 7],  7);
   GG(dd, aa, bb, cc, X[ 4],  6);
   GG(cc, dd, aa, bb, X[13],  8);
   GG(bb, cc, dd, aa, X[ 1], 13);
   GG(aa, bb, cc, dd, X[10], 11);
   GG(dd, aa, bb, cc, X[ 6],  9);
   GG(cc, dd, aa, bb, X[15],  7);
   GG(bb, cc, dd, aa, X[ 3], 15);
   GG(aa, bb, cc, dd, X[12],  7);
   GG(dd, aa, bb, cc, X[ 0], 12);
   GG(cc, dd, aa, bb, X[ 9], 15);
   GG(bb, cc, dd, aa, X[ 5],  9);
   GG(aa, bb, cc, dd, X[ 2], 11);
   GG(dd, aa, bb, cc, X[14],  7);
   GG(cc, dd, aa, bb, X[11], 13);
   GG(bb, cc, dd, aa, X[ 8], 12);

   /* parallel round 2 */
   HHH(aaa, bbb, ccc, ddd, X[ 6],  9);
   HHH(ddd, aaa, bbb, ccc, X[11], 13);
   HHH(ccc, ddd, aaa, bbb, X[ 3], 15);
   HHH(bbb, ccc, ddd, aaa, X[ 7],  7);
   HHH(aaa, bbb, ccc, ddd, X[ 0], 12);
   HHH(ddd, aaa, bbb, ccc, X[13],  8);
   HHH(ccc, ddd, aaa, bbb, X[ 5],  9);
   HHH(bbb, ccc, ddd, aaa, X[10], 11);
   HHH(aaa, bbb, ccc, ddd, X[14],  7);
   HHH(ddd, aaa, bbb, ccc, X[15],  7);
   HHH(ccc, ddd, aaa, bbb, X[ 8], 12);
   HHH(bbb, ccc, ddd, aaa, X[12],  7);
   HHH(aaa, bbb, ccc, ddd, X[ 4],  6);
   HHH(ddd, aaa, bbb, ccc, X[ 9], 15);
   HHH(ccc, ddd, aaa, bbb, X[ 1], 13);
   HHH(bbb, ccc, ddd, aaa, X[ 2], 11);

   tmp = bb; bb = bbb; bbb = tmp;

   /* round 3 */
   HH(aa, bb, cc, dd, X[ 3], 11);
   HH(dd, aa, bb, cc, X[10], 13);
   HH(cc, dd, aa, bb, X[14],  6);
   HH(bb, cc, dd, aa, X[ 4],  7);
   HH(aa, bb, cc, dd, X[ 9], 14);
   HH(dd, aa, bb, cc, X[15],  9);
   HH(cc, dd, aa, bb, X[ 8], 13);
   HH(bb, cc, dd, aa, X[ 1], 15);
   HH(aa, bb, cc, dd, X[ 2], 14);
   HH(dd, aa, bb, cc, X[ 7],  8);
   HH(cc, dd, aa, bb, X[ 0], 13);
   HH(bb, cc, dd, aa, X[ 6],  6);
   HH(aa, bb, cc, dd, X[13],  5);
   HH(dd, aa, bb, cc, X[11], 12);
   HH(cc, dd, aa, bb, X[ 5],  7);
   HH(bb, cc, dd, aa, X[12],  5);

   /* parallel round 3 */
   GGG(aaa, bbb, ccc, ddd, X[15],  9);
   GGG(ddd, aaa, bbb, ccc, X[ 5],  7);
   GGG(ccc, ddd, aaa, bbb, X[ 1], 15);
   GGG(bbb, ccc, ddd, aaa, X[ 3], 11);
   GGG(aaa, bbb, ccc, ddd, X[ 7],  8);
   GGG(ddd, aaa, bbb, ccc, X[14],  6);
   GGG(ccc, ddd, aaa, bbb, X[ 6],  6);
   GGG(bbb, ccc, ddd, aaa, X[ 9], 14);
   GGG(aaa, bbb, ccc, ddd, X[11], 12);
   GGG(ddd, aaa, bbb, ccc, X[ 8], 13);
   GGG(ccc, ddd, aaa, bbb, X[12],  5);
   GGG(bbb, ccc, ddd, aaa, X[ 2], 14);
   GGG(aaa, bbb, ccc, ddd, X[10], 13);
   GGG(ddd, aaa, bbb, ccc, X[ 0], 13);
   GGG(ccc, ddd, aaa, bbb, X[ 4],  7);
   GGG(bbb, ccc, ddd, aaa, X[13],  5);

   tmp = cc; cc = ccc; ccc = tmp;

   /* round 4 */
   II(aa, bb, cc, dd, X[ 1], 11);
   II(dd, aa, bb, cc, X[ 9], 12);
   II(cc, dd, aa, bb, X[11], 14);
   II(bb, cc, dd, aa, X[10], 15);
   II(aa, bb, cc, dd, X[ 0], 14);
   II(dd, aa, bb, cc, X[ 8], 15);
   II(cc, dd, aa, bb, X[12],  9);
   II(bb, cc, dd, aa, X[ 4],  8);
   II(aa, bb, cc, dd, X[13],  9);
   II(dd, aa, bb, cc, X[ 3], 14);
   II(cc, dd, aa, bb, X[ 7],  5);
   II(bb, cc, dd, aa, X[15],  6);
   II(aa, bb, cc, dd, X[14],  8);
   II(dd, aa, bb, cc, X[ 5],  6);
   II(cc, dd, aa, bb, X[ 6],  5);
   II(bb, cc, dd, aa, X[ 2], 12);

   /* parallel round 4 */
   FFF(aaa, bbb, ccc, ddd, X[ 8], 15);
   FFF(ddd, aaa, bbb, ccc, X[ 6],  5);
   FFF(ccc, ddd, aaa, bbb, X[ 4],  8);
   FFF(bbb, ccc, ddd, aaa, X[ 1], 11);
   FFF(aaa, bbb, ccc, ddd, X[ 3], 14);
   FFF(ddd, aaa, bbb, ccc, X[11], 14);
   FFF(ccc, ddd, aaa, bbb, X[15],  6);
   FFF(bbb, ccc, ddd, aaa, X[ 0], 14);
   FFF(aaa, bbb, ccc, ddd, X[ 5],  6);
   FFF(ddd, aaa, bbb, ccc, X[12],  9);
   FFF(ccc, ddd, aaa, bbb, X[ 2], 12);
   FFF(bbb, ccc, ddd, aaa, X[13],  9);
   FFF(aaa, bbb, ccc, ddd, X[ 9], 12);
   FFF(ddd, aaa, bbb, ccc, X[ 7],  5);
   FFF(ccc, ddd, aaa, bbb, X[10], 15);
   FFF(bbb, ccc, ddd, aaa, X[14],  8);

   tmp = dd; dd = ddd; ddd = tmp;

   /* combine results */
   ctx->state[0] += aa;
   ctx->state[1] += bb;
   ctx->state[2] += cc;
   ctx->state[3] += dd;
   ctx->state[4] += aaa;
   ctx->state[5] += bbb;
   ctx->state[6] += ccc;
   ctx->state[7] += ddd;

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int rmd256_compress(ltc_rmd256_ctx *ctx, const unsigned char *buf)
{
   int err;
   err = _rmd256_compress(md, buf);

   ltc_burn_stack(sizeof(ulong32) * 25 + sizeof(int));
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_rmd256_init(ltc_rmd256_ctx *ctx)
{
   LTC_ARGCHK(ctx != NULL);

   ctx->state[0] = 0x67452301UL;
   ctx->state[1] = 0xefcdab89UL;
   ctx->state[2] = 0x98badcfeUL;
   ctx->state[3] = 0x10325476UL;
   ctx->state[4] = 0x76543210UL;
   ctx->state[5] = 0xfedcba98UL;
   ctx->state[6] = 0x89abcdefUL;
   ctx->state[7] = 0x01234567UL;
   ctx->curlen   = 0;
   ctx->length   = 0;

   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
LTC_HASH_PROCESS(ltc_rmd256_process, rmd256_compress, ltc_rmd256_ctx, rmd256, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (16 bytes)
   @return CRYPT_OK if successful
*/
int ltc_rmd256_done(ltc_rmd256_ctx *ctx, unsigned char *out)
{
    int i;
    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    ctx->length += ctx->curlen * 8;

    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 56) {
        while (ctx->curlen < 64) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        rmd256_compress(ctx, ctx->buf);
        ctx->curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (ctx->curlen < 56) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64L(ctx->length, ctx->buf+56);
    rmd256_compress(ctx, ctx->buf);

    /* copy output */
    for (i = 0; i < 8; i++) {
        LTC_STORE32L(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(md, sizeof(hash_state));
#endif
   return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int ltc_rmd256_test(void)
{
#ifndef LTC_TEST
   return CRYPT_NOP;
#else
   static const struct {
        const char *msg;
        unsigned char md[32];
   } tests[] = {
   { "",
     { 0x02, 0xba, 0x4c, 0x4e, 0x5f, 0x8e, 0xcd, 0x18,
       0x77, 0xfc, 0x52, 0xd6, 0x4d, 0x30, 0xe3, 0x7a,
       0x2d, 0x97, 0x74, 0xfb, 0x1e, 0x5d, 0x02, 0x63,
       0x80, 0xae, 0x01, 0x68, 0xe3, 0xc5, 0x52, 0x2d }
   },
   { "a",
     { 0xf9, 0x33, 0x3e, 0x45, 0xd8, 0x57, 0xf5, 0xd9,
       0x0a, 0x91, 0xba, 0xb7, 0x0a, 0x1e, 0xba, 0x0c,
       0xfb, 0x1b, 0xe4, 0xb0, 0x78, 0x3c, 0x9a, 0xcf,
       0xcd, 0x88, 0x3a, 0x91, 0x34, 0x69, 0x29, 0x25 }
   },
   { "abc",
     { 0xaf, 0xbd, 0x6e, 0x22, 0x8b, 0x9d, 0x8c, 0xbb,
       0xce, 0xf5, 0xca, 0x2d, 0x03, 0xe6, 0xdb, 0xa1,
       0x0a, 0xc0, 0xbc, 0x7d, 0xcb, 0xe4, 0x68, 0x0e,
       0x1e, 0x42, 0xd2, 0xe9, 0x75, 0x45, 0x9b, 0x65 }
   },
   { "message digest",
     { 0x87, 0xe9, 0x71, 0x75, 0x9a, 0x1c, 0xe4, 0x7a,
       0x51, 0x4d, 0x5c, 0x91, 0x4c, 0x39, 0x2c, 0x90,
       0x18, 0xc7, 0xc4, 0x6b, 0xc1, 0x44, 0x65, 0x55,
       0x4a, 0xfc, 0xdf, 0x54, 0xa5, 0x07, 0x0c, 0x0e }
   },
   { "abcdefghijklmnopqrstuvwxyz",
     { 0x64, 0x9d, 0x30, 0x34, 0x75, 0x1e, 0xa2, 0x16,
       0x77, 0x6b, 0xf9, 0xa1, 0x8a, 0xcc, 0x81, 0xbc,
       0x78, 0x96, 0x11, 0x8a, 0x51, 0x97, 0x96, 0x87,
       0x82, 0xdd, 0x1f, 0xd9, 0x7d, 0x8d, 0x51, 0x33 }
   },
   { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
     { 0x57, 0x40, 0xa4, 0x08, 0xac, 0x16, 0xb7, 0x20,
       0xb8, 0x44, 0x24, 0xae, 0x93, 0x1c, 0xbb, 0x1f,
       0xe3, 0x63, 0xd1, 0xd0, 0xbf, 0x40, 0x17, 0xf1,
       0xa8, 0x9f, 0x7e, 0xa6, 0xde, 0x77, 0xa0, 0xb8 }
   }
   };
   int x;
   unsigned char buf[32];
   ltc_hash_state md;

   for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
       ltc_rmd256_init(&md);
       ltc_rmd256_process(&md, (const unsigned char *)tests[x].msg,
	   strlen(tests[x].msg));
       ltc_rmd256_done(&md, buf);
       if (LTC_XMEMCMP(buf, tests[x].md, 32) != 0) {
       #if 0
          printf("Failed test %d\n", x);
       #endif
          return CRYPT_FAIL_TESTVECTOR;
       }
   }
   return CRYPT_OK;
#endif
}

Added Source/descriptors/digestDescriptors/ltc_rmd_descriptor/ltc_rmd256.h.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_rmd256.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>

#ifndef _LTC_RMD256_H_
#define _LTC_RMD256_H_

#define	LTC_RMD256_HASHSIZE	32
#define	LTC_RMD256_BLOCKSIZE	64

typedef struct ltc_rmd256_state {
    uint64_t length;
    uint32_t state[8];
    uint32_t curlen;
    unsigned char buf[LTC_RMD256_BLOCKSIZE];
} ltc_rmd256_ctx;

int ltc_rmd256_init(ltc_rmd256_ctx *ctx);
int ltc_rmd256_process(ltc_rmd256_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int ltc_rmd256_done(ltc_rmd256_ctx *ctx, unsigned char *hash);

#endif /* _LTC_RMD256_H_ */

Added Source/descriptors/digestDescriptors/ltc_rmd_descriptor/ltc_rmd320.c.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <stdio.h>
#include "ltc_rmd320.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"
#include "CommonDigestSPI.h"

/**
   @file ltc_rmd320.c
   RMD320 hash function
*/

const ccDescriptor ltc_rmd320_desc = {
    .implementation_info = &cc_rmd320_impinfo,
	.dtype.digest.hashsize = CC_RMD320_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_RMD320_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_rmd320_init,
	.dtype.digest.process = &ltc_rmd320_process,
	.dtype.digest.done = &ltc_rmd320_done,
};


/* the five basic functions F(), G() and H() */
#define F(x, y, z)        ((x) ^ (y) ^ (z))
#define G(x, y, z)        (((x) & (y)) | (~(x) & (z)))
#define H(x, y, z)        (((x) | ~(y)) ^ (z))
#define I(x, y, z)        (((x) & (z)) | ((y) & ~(z)))
#define J(x, y, z)        ((x) ^ ((y) | ~(z)))

/* the ten basic operations FF() through III() */
#define FF(a, b, c, d, e, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define GG(a, b, c, d, e, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define HH(a, b, c, d, e, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define II(a, b, c, d, e, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define JJ(a, b, c, d, e, x, s)        \
      (a) += J((b), (c), (d)) + (x) + 0xa953fd4eUL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define FFF(a, b, c, d, e, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define GGG(a, b, c, d, e, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define HHH(a, b, c, d, e, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6d703ef3UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define III(a, b, c, d, e, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x5c4dd124UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);

#define JJJ(a, b, c, d, e, x, s)        \
      (a) += J((b), (c), (d)) + (x) + 0x50a28be6UL;\
      (a) = LTC_ROLc((a), (s)) + (e);\
      (c) = LTC_ROLc((c), 10);


#ifdef LTC_CLEAN_STACK
static int _rmd320_compress(ltc_rmd320_ctx *ctx, const unsigned char *buf)
#else
static int  rmd320_compress(ltc_rmd320_ctx *ctx, const unsigned char *buf)
#endif
{
   ulong32 aa,bb,cc,dd,ee,aaa,bbb,ccc,ddd,eee,tmp,X[16];
   int i;

   /* load words X */
   for (i = 0; i < 16; i++){
      LTC_LOAD32L(X[i], buf + (4 * i));
   }

   /* load state */
   aa = ctx->state[0];
   bb = ctx->state[1];
   cc = ctx->state[2];
   dd = ctx->state[3];
   ee = ctx->state[4];
   aaa = ctx->state[5];
   bbb = ctx->state[6];
   ccc = ctx->state[7];
   ddd = ctx->state[8];
   eee = ctx->state[9];

   /* round 1 */
   FF(aa, bb, cc, dd, ee, X[ 0], 11);
   FF(ee, aa, bb, cc, dd, X[ 1], 14);
   FF(dd, ee, aa, bb, cc, X[ 2], 15);
   FF(cc, dd, ee, aa, bb, X[ 3], 12);
   FF(bb, cc, dd, ee, aa, X[ 4],  5);
   FF(aa, bb, cc, dd, ee, X[ 5],  8);
   FF(ee, aa, bb, cc, dd, X[ 6],  7);
   FF(dd, ee, aa, bb, cc, X[ 7],  9);
   FF(cc, dd, ee, aa, bb, X[ 8], 11);
   FF(bb, cc, dd, ee, aa, X[ 9], 13);
   FF(aa, bb, cc, dd, ee, X[10], 14);
   FF(ee, aa, bb, cc, dd, X[11], 15);
   FF(dd, ee, aa, bb, cc, X[12],  6);
   FF(cc, dd, ee, aa, bb, X[13],  7);
   FF(bb, cc, dd, ee, aa, X[14],  9);
   FF(aa, bb, cc, dd, ee, X[15],  8);

   /* parallel round 1 */
   JJJ(aaa, bbb, ccc, ddd, eee, X[ 5],  8);
   JJJ(eee, aaa, bbb, ccc, ddd, X[14],  9);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 7],  9);
   JJJ(ccc, ddd, eee, aaa, bbb, X[ 0], 11);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 9], 13);
   JJJ(aaa, bbb, ccc, ddd, eee, X[ 2], 15);
   JJJ(eee, aaa, bbb, ccc, ddd, X[11], 15);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 4],  5);
   JJJ(ccc, ddd, eee, aaa, bbb, X[13],  7);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 6],  7);
   JJJ(aaa, bbb, ccc, ddd, eee, X[15],  8);
   JJJ(eee, aaa, bbb, ccc, ddd, X[ 8], 11);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 1], 14);
   JJJ(ccc, ddd, eee, aaa, bbb, X[10], 14);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 3], 12);
   JJJ(aaa, bbb, ccc, ddd, eee, X[12],  6);

   tmp = aa; aa = aaa; aaa = tmp;

   /* round 2 */
   GG(ee, aa, bb, cc, dd, X[ 7],  7);
   GG(dd, ee, aa, bb, cc, X[ 4],  6);
   GG(cc, dd, ee, aa, bb, X[13],  8);
   GG(bb, cc, dd, ee, aa, X[ 1], 13);
   GG(aa, bb, cc, dd, ee, X[10], 11);
   GG(ee, aa, bb, cc, dd, X[ 6],  9);
   GG(dd, ee, aa, bb, cc, X[15],  7);
   GG(cc, dd, ee, aa, bb, X[ 3], 15);
   GG(bb, cc, dd, ee, aa, X[12],  7);
   GG(aa, bb, cc, dd, ee, X[ 0], 12);
   GG(ee, aa, bb, cc, dd, X[ 9], 15);
   GG(dd, ee, aa, bb, cc, X[ 5],  9);
   GG(cc, dd, ee, aa, bb, X[ 2], 11);
   GG(bb, cc, dd, ee, aa, X[14],  7);
   GG(aa, bb, cc, dd, ee, X[11], 13);
   GG(ee, aa, bb, cc, dd, X[ 8], 12);

   /* parallel round 2 */
   III(eee, aaa, bbb, ccc, ddd, X[ 6],  9);
   III(ddd, eee, aaa, bbb, ccc, X[11], 13);
   III(ccc, ddd, eee, aaa, bbb, X[ 3], 15);
   III(bbb, ccc, ddd, eee, aaa, X[ 7],  7);
   III(aaa, bbb, ccc, ddd, eee, X[ 0], 12);
   III(eee, aaa, bbb, ccc, ddd, X[13],  8);
   III(ddd, eee, aaa, bbb, ccc, X[ 5],  9);
   III(ccc, ddd, eee, aaa, bbb, X[10], 11);
   III(bbb, ccc, ddd, eee, aaa, X[14],  7);
   III(aaa, bbb, ccc, ddd, eee, X[15],  7);
   III(eee, aaa, bbb, ccc, ddd, X[ 8], 12);
   III(ddd, eee, aaa, bbb, ccc, X[12],  7);
   III(ccc, ddd, eee, aaa, bbb, X[ 4],  6);
   III(bbb, ccc, ddd, eee, aaa, X[ 9], 15);
   III(aaa, bbb, ccc, ddd, eee, X[ 1], 13);
   III(eee, aaa, bbb, ccc, ddd, X[ 2], 11);

   tmp = bb; bb = bbb; bbb = tmp;

   /* round 3 */
   HH(dd, ee, aa, bb, cc, X[ 3], 11);
   HH(cc, dd, ee, aa, bb, X[10], 13);
   HH(bb, cc, dd, ee, aa, X[14],  6);
   HH(aa, bb, cc, dd, ee, X[ 4],  7);
   HH(ee, aa, bb, cc, dd, X[ 9], 14);
   HH(dd, ee, aa, bb, cc, X[15],  9);
   HH(cc, dd, ee, aa, bb, X[ 8], 13);
   HH(bb, cc, dd, ee, aa, X[ 1], 15);
   HH(aa, bb, cc, dd, ee, X[ 2], 14);
   HH(ee, aa, bb, cc, dd, X[ 7],  8);
   HH(dd, ee, aa, bb, cc, X[ 0], 13);
   HH(cc, dd, ee, aa, bb, X[ 6],  6);
   HH(bb, cc, dd, ee, aa, X[13],  5);
   HH(aa, bb, cc, dd, ee, X[11], 12);
   HH(ee, aa, bb, cc, dd, X[ 5],  7);
   HH(dd, ee, aa, bb, cc, X[12],  5);

   /* parallel round 3 */
   HHH(ddd, eee, aaa, bbb, ccc, X[15],  9);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 5],  7);
   HHH(bbb, ccc, ddd, eee, aaa, X[ 1], 15);
   HHH(aaa, bbb, ccc, ddd, eee, X[ 3], 11);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 7],  8);
   HHH(ddd, eee, aaa, bbb, ccc, X[14],  6);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 6],  6);
   HHH(bbb, ccc, ddd, eee, aaa, X[ 9], 14);
   HHH(aaa, bbb, ccc, ddd, eee, X[11], 12);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 8], 13);
   HHH(ddd, eee, aaa, bbb, ccc, X[12],  5);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 2], 14);
   HHH(bbb, ccc, ddd, eee, aaa, X[10], 13);
   HHH(aaa, bbb, ccc, ddd, eee, X[ 0], 13);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 4],  7);
   HHH(ddd, eee, aaa, bbb, ccc, X[13],  5);

   tmp = cc; cc = ccc; ccc = tmp;

   /* round 4 */
   II(cc, dd, ee, aa, bb, X[ 1], 11);
   II(bb, cc, dd, ee, aa, X[ 9], 12);
   II(aa, bb, cc, dd, ee, X[11], 14);
   II(ee, aa, bb, cc, dd, X[10], 15);
   II(dd, ee, aa, bb, cc, X[ 0], 14);
   II(cc, dd, ee, aa, bb, X[ 8], 15);
   II(bb, cc, dd, ee, aa, X[12],  9);
   II(aa, bb, cc, dd, ee, X[ 4],  8);
   II(ee, aa, bb, cc, dd, X[13],  9);
   II(dd, ee, aa, bb, cc, X[ 3], 14);
   II(cc, dd, ee, aa, bb, X[ 7],  5);
   II(bb, cc, dd, ee, aa, X[15],  6);
   II(aa, bb, cc, dd, ee, X[14],  8);
   II(ee, aa, bb, cc, dd, X[ 5],  6);
   II(dd, ee, aa, bb, cc, X[ 6],  5);
   II(cc, dd, ee, aa, bb, X[ 2], 12);

   /* parallel round 4 */
   GGG(ccc, ddd, eee, aaa, bbb, X[ 8], 15);
   GGG(bbb, ccc, ddd, eee, aaa, X[ 6],  5);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 4],  8);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 1], 11);
   GGG(ddd, eee, aaa, bbb, ccc, X[ 3], 14);
   GGG(ccc, ddd, eee, aaa, bbb, X[11], 14);
   GGG(bbb, ccc, ddd, eee, aaa, X[15],  6);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 0], 14);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 5],  6);
   GGG(ddd, eee, aaa, bbb, ccc, X[12],  9);
   GGG(ccc, ddd, eee, aaa, bbb, X[ 2], 12);
   GGG(bbb, ccc, ddd, eee, aaa, X[13],  9);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 9], 12);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 7],  5);
   GGG(ddd, eee, aaa, bbb, ccc, X[10], 15);
   GGG(ccc, ddd, eee, aaa, bbb, X[14],  8);

   tmp = dd; dd = ddd; ddd = tmp;

   /* round 5 */
   JJ(bb, cc, dd, ee, aa, X[ 4],  9);
   JJ(aa, bb, cc, dd, ee, X[ 0], 15);
   JJ(ee, aa, bb, cc, dd, X[ 5],  5);
   JJ(dd, ee, aa, bb, cc, X[ 9], 11);
   JJ(cc, dd, ee, aa, bb, X[ 7],  6);
   JJ(bb, cc, dd, ee, aa, X[12],  8);
   JJ(aa, bb, cc, dd, ee, X[ 2], 13);
   JJ(ee, aa, bb, cc, dd, X[10], 12);
   JJ(dd, ee, aa, bb, cc, X[14],  5);
   JJ(cc, dd, ee, aa, bb, X[ 1], 12);
   JJ(bb, cc, dd, ee, aa, X[ 3], 13);
   JJ(aa, bb, cc, dd, ee, X[ 8], 14);
   JJ(ee, aa, bb, cc, dd, X[11], 11);
   JJ(dd, ee, aa, bb, cc, X[ 6],  8);
   JJ(cc, dd, ee, aa, bb, X[15],  5);
   JJ(bb, cc, dd, ee, aa, X[13],  6);

   /* parallel round 5 */
   FFF(bbb, ccc, ddd, eee, aaa, X[12] ,  8);
   FFF(aaa, bbb, ccc, ddd, eee, X[15] ,  5);
   FFF(eee, aaa, bbb, ccc, ddd, X[10] , 12);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 4] ,  9);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 1] , 12);
   FFF(bbb, ccc, ddd, eee, aaa, X[ 5] ,  5);
   FFF(aaa, bbb, ccc, ddd, eee, X[ 8] , 14);
   FFF(eee, aaa, bbb, ccc, ddd, X[ 7] ,  6);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 6] ,  8);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 2] , 13);
   FFF(bbb, ccc, ddd, eee, aaa, X[13] ,  6);
   FFF(aaa, bbb, ccc, ddd, eee, X[14] ,  5);
   FFF(eee, aaa, bbb, ccc, ddd, X[ 0] , 15);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 3] , 13);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 9] , 11);
   FFF(bbb, ccc, ddd, eee, aaa, X[11] , 11);

   tmp = ee; ee = eee; eee = tmp;

   /* combine results */
   ctx->state[0] += aa;
   ctx->state[1] += bb;
   ctx->state[2] += cc;
   ctx->state[3] += dd;
   ctx->state[4] += ee;
   ctx->state[5] += aaa;
   ctx->state[6] += bbb;
   ctx->state[7] += ccc;
   ctx->state[8] += ddd;
   ctx->state[9] += eee;

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int rmd320_compress(ltc_rmd320_ctx *ctx, const unsigned char *buf)
{
   int err;
   err = _rmd320_compress(md, buf);

   ltc_burn_stack(sizeof(ulong32) * 27 + sizeof(int));
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_rmd320_init(ltc_rmd320_ctx *ctx)
{
   LTC_ARGCHK(ctx != NULL);

   ctx->state[0] = 0x67452301UL;
   ctx->state[1] = 0xefcdab89UL;
   ctx->state[2] = 0x98badcfeUL;
   ctx->state[3] = 0x10325476UL;
   ctx->state[4] = 0xc3d2e1f0UL;
   ctx->state[5] = 0x76543210UL;
   ctx->state[6] = 0xfedcba98UL;
   ctx->state[7] = 0x89abcdefUL;
   ctx->state[8] = 0x01234567UL;
   ctx->state[9] = 0x3c2d1e0fUL;
   ctx->curlen   = 0;
   ctx->length   = 0;

   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
LTC_HASH_PROCESS(ltc_rmd320_process, rmd320_compress, ltc_rmd320_ctx, rmd320, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (20 bytes)
   @return CRYPT_OK if successful
*/
int ltc_rmd320_done(ltc_rmd320_ctx *ctx, unsigned char *out)
{
    int i;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    ctx->length += ctx->curlen * 8;

    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 56) {
        while (ctx->curlen < 64) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        rmd320_compress(ctx, ctx->buf);
        ctx->curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (ctx->curlen < 56) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64L(ctx->length, ctx->buf+56);
    rmd320_compress(ctx, ctx->buf);

    /* copy output */
    for (i = 0; i < 10; i++) {
        LTC_STORE32L(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(md, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int ltc_rmd320_test(void)
{
#ifndef LTC_TEST
   return CRYPT_NOP;
#else
   static const struct {
        const char *msg;
        unsigned char md[40];
   } tests[] = {
   { "",
     { 0x22, 0xd6, 0x5d, 0x56, 0x61, 0x53, 0x6c, 0xdc, 0x75, 0xc1,
       0xfd, 0xf5, 0xc6, 0xde, 0x7b, 0x41, 0xb9, 0xf2, 0x73, 0x25,
       0xeb, 0xc6, 0x1e, 0x85, 0x57, 0x17, 0x7d, 0x70, 0x5a, 0x0e,
       0xc8, 0x80, 0x15, 0x1c, 0x3a, 0x32, 0xa0, 0x08, 0x99, 0xb8 }
   },
   { "a",
     { 0xce, 0x78, 0x85, 0x06, 0x38, 0xf9, 0x26, 0x58, 0xa5, 0xa5,
       0x85, 0x09, 0x75, 0x79, 0x92, 0x6d, 0xda, 0x66, 0x7a, 0x57,
       0x16, 0x56, 0x2c, 0xfc, 0xf6, 0xfb, 0xe7, 0x7f, 0x63, 0x54,
       0x2f, 0x99, 0xb0, 0x47, 0x05, 0xd6, 0x97, 0x0d, 0xff, 0x5d }
   },
   { "abc",
     { 0xde, 0x4c, 0x01, 0xb3, 0x05, 0x4f, 0x89, 0x30, 0xa7, 0x9d,
       0x09, 0xae, 0x73, 0x8e, 0x92, 0x30, 0x1e, 0x5a, 0x17, 0x08,
       0x5b, 0xef, 0xfd, 0xc1, 0xb8, 0xd1, 0x16, 0x71, 0x3e, 0x74,
       0xf8, 0x2f, 0xa9, 0x42, 0xd6, 0x4c, 0xdb, 0xc4, 0x68, 0x2d }
   },
   { "message digest",
     { 0x3a, 0x8e, 0x28, 0x50, 0x2e, 0xd4, 0x5d, 0x42, 0x2f, 0x68,
       0x84, 0x4f, 0x9d, 0xd3, 0x16, 0xe7, 0xb9, 0x85, 0x33, 0xfa,
       0x3f, 0x2a, 0x91, 0xd2, 0x9f, 0x84, 0xd4, 0x25, 0xc8, 0x8d,
       0x6b, 0x4e, 0xff, 0x72, 0x7d, 0xf6, 0x6a, 0x7c, 0x01, 0x97 }
   },
   { "abcdefghijklmnopqrstuvwxyz",
     { 0xca, 0xbd, 0xb1, 0x81, 0x0b, 0x92, 0x47, 0x0a, 0x20, 0x93,
       0xaa, 0x6b, 0xce, 0x05, 0x95, 0x2c, 0x28, 0x34, 0x8c, 0xf4,
       0x3f, 0xf6, 0x08, 0x41, 0x97, 0x51, 0x66, 0xbb, 0x40, 0xed,
       0x23, 0x40, 0x04, 0xb8, 0x82, 0x44, 0x63, 0xe6, 0xb0, 0x09 }
   },
   { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
     { 0xd0, 0x34, 0xa7, 0x95, 0x0c, 0xf7, 0x22, 0x02, 0x1b, 0xa4,
       0xb8, 0x4d, 0xf7, 0x69, 0xa5, 0xde, 0x20, 0x60, 0xe2, 0x59,
       0xdf, 0x4c, 0x9b, 0xb4, 0xa4, 0x26, 0x8c, 0x0e, 0x93, 0x5b,
       0xbc, 0x74, 0x70, 0xa9, 0x69, 0xc9, 0xd0, 0x72, 0xa1, 0xac }
   }
   };
   int x;
   unsigned char buf[40];
   ltc_hash_state md;

   for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
       ltc_rmd320_init(&md);
       ltc_rmd320_process(&md, (const unsigned char *)tests[x].msg, strlen(tests[x].msg));
       ltc_rmd320_done(&md, buf);
       if (LTC_XMEMCMP(buf, tests[x].md, 40) != 0) {
#if 0
          printf("Failed test %d\n", x);
#endif
          return CRYPT_FAIL_TESTVECTOR;
       }
   }
   return CRYPT_OK;
#endif
}

Added Source/descriptors/digestDescriptors/ltc_rmd_descriptor/ltc_rmd320.h.











































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_rmd320.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>

#ifndef _LTC_RMD320_H_
#define _LTC_RMD320_H_

#define	LTC_RMD320_HASHSIZE	40
#define	LTC_RMD320_BLOCKSIZE	64

typedef struct ltc_rmd320_state {
    uint64_t length;
    uint32_t state[10];
    uint32_t curlen;
    unsigned char buf[LTC_RMD320_BLOCKSIZE];
} ltc_rmd320_ctx;

int ltc_rmd320_init(ltc_rmd320_ctx *ctx);
int ltc_rmd320_process(ltc_rmd320_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int ltc_rmd320_done(ltc_rmd320_ctx *ctx, unsigned char *hash);

#endif /* _LTC_RMD320_H_ */

Added Source/descriptors/digestDescriptors/ltc_sha1_descriptor/ltc_sha1.c.









































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <stdio.h>
#include "ltc_sha1.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"

/**
  @file ltc_sha1.c
  LTC_SHA1 code by Tom St Denis 
*/


const ccDescriptor ltc_sha1_desc =
{
    .implementation_info = &cc_sha1_impinfo,
	.dtype.digest.hashsize = CC_SHA1_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA1_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_sha1_init,
	.dtype.digest.process = &ltc_sha1_process,
	.dtype.digest.done = &ltc_sha1_done,
};


#define F0(x,y,z)  (z ^ (x & (y ^ z)))
#define F1(x,y,z)  (x ^ y ^ z)
#define F2(x,y,z)  ((x & y) | (z & (x | y)))
#define F3(x,y,z)  (x ^ y ^ z)

#ifdef LTC_CLEAN_STACK
static int _sha1_compress(ltc_sha1_ctx *ctx, const unsigned char *buf)
#else
static int  sha1_compress(ltc_sha1_ctx *ctx, const unsigned char *buf)
#endif
{
    ulong32 a,b,c,d,e,W[80],i;
#ifdef LTC_SMALL_CODE
    ulong32 t;
#endif

    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LTC_LOAD32H(W[i], buf + (4*i));
    }

    /* copy state */
    a = ctx->state[0];
    b = ctx->state[1];
    c = ctx->state[2];
    d = ctx->state[3];
    e = ctx->state[4];

    /* expand it */
    for (i = 16; i < 80; i++) {
        W[i] = LTC_ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); 
    }

    /* compress */
    /* round one */
    #define FF0(a,b,c,d,e,i) e = (LTC_ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = LTC_ROLc(b, 30);
    #define FF1(a,b,c,d,e,i) e = (LTC_ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = LTC_ROLc(b, 30);
    #define FF2(a,b,c,d,e,i) e = (LTC_ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = LTC_ROLc(b, 30);
    #define FF3(a,b,c,d,e,i) e = (LTC_ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = LTC_ROLc(b, 30);
 
#ifdef LTC_SMALL_CODE
 
    for (i = 0; i < 20; ) {
       FF0(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 40; ) {
       FF1(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 60; ) {
       FF2(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 80; ) {
       FF3(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }

#else

    for (i = 0; i < 20; ) {
       FF0(a,b,c,d,e,i++);
       FF0(e,a,b,c,d,i++);
       FF0(d,e,a,b,c,i++);
       FF0(c,d,e,a,b,i++);
       FF0(b,c,d,e,a,i++);
    }

    /* round two */
    for (; i < 40; )  { 
       FF1(a,b,c,d,e,i++);
       FF1(e,a,b,c,d,i++);
       FF1(d,e,a,b,c,i++);
       FF1(c,d,e,a,b,i++);
       FF1(b,c,d,e,a,i++);
    }

    /* round three */
    for (; i < 60; )  { 
       FF2(a,b,c,d,e,i++);
       FF2(e,a,b,c,d,i++);
       FF2(d,e,a,b,c,i++);
       FF2(c,d,e,a,b,i++);
       FF2(b,c,d,e,a,i++);
    }

    /* round four */
    for (; i < 80; )  { 
       FF3(a,b,c,d,e,i++);
       FF3(e,a,b,c,d,i++);
       FF3(d,e,a,b,c,i++);
       FF3(c,d,e,a,b,i++);
       FF3(b,c,d,e,a,i++);
    }
#endif

    #undef FF0
    #undef FF1
    #undef FF2
    #undef FF3

    /* store */
    ctx->state[0] = ctx->state[0] + a;
    ctx->state[1] = ctx->state[1] + b;
    ctx->state[2] = ctx->state[2] + c;
    ctx->state[3] = ctx->state[3] + d;
    ctx->state[4] = ctx->state[4] + e;

    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int sha1_compress(ltc_sha1_ctx *ctx, const unsigned char *buf)
{
   int err;
   err = _sha1_compress(ctx, buf);

   ltc_burn_stack(sizeof(ulong32) * 87);
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_sha1_init(ltc_sha1_ctx *ctx)
{
   LTC_ARGCHK(ctx != NULL);

   ctx->state[0] = 0x67452301UL;
   ctx->state[1] = 0xefcdab89UL;
   ctx->state[2] = 0x98badcfeUL;
   ctx->state[3] = 0x10325476UL;
   ctx->state[4] = 0xc3d2e1f0UL;
   ctx->curlen = 0;
   ctx->length = 0;
   
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
LTC_HASH_PROCESS(ltc_sha1_process, sha1_compress, ltc_sha1_ctx, sha1, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (20 bytes)
   @return CRYPT_OK if successful
*/
int ltc_sha1_done(ltc_sha1_ctx *ctx, unsigned char *out)
{
    int i;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }

    /* increase the length of the message */
    ctx->length += ctx->curlen * 8;

    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 56) {
        while (ctx->curlen < 64) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        sha1_compress(ctx, ctx->buf);
        ctx->curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (ctx->curlen < 56) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64H(ctx->length, ctx->buf+56);
    sha1_compress(ctx, ctx->buf);

    /* copy output */
    for (i = 0; i < 5; i++) {
        LTC_STORE32H(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(md, sizeof(ltc_hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  ltc_sha1_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      const char *msg;
      unsigned char hash[20];
  } tests[] = {
    { "abc",
      { 0xa9, 0x99, 0x3e, 0x36, 0x47, 0x06, 0x81, 0x6a,
        0xba, 0x3e, 0x25, 0x71, 0x78, 0x50, 0xc2, 0x6c,
        0x9c, 0xd0, 0xd8, 0x9d }
    },
    { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
      { 0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E,
        0xBA, 0xAE, 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5,
        0xE5, 0x46, 0x70, 0xF1 }
    }
  };

  int i;
  unsigned char tmp[20];
  ltc_hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0]));  i++) {
      ltc_sha1_init(&md);
      ltc_sha1_process(&md, (const unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
      ltc_sha1_done(&md, tmp);
      if (LTC_XMEMCMP(tmp, tests[i].hash, 20) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
  #endif
}

Added Source/descriptors/digestDescriptors/ltc_sha1_descriptor/ltc_sha1.h.



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_sha1.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>

#ifndef _LTC_SHA1_H_
#define _LTC_SHA1_H_

#define LTC_SHA1_HASHSIZE	20
#define LTC_SHA1_BLOCKSIZE	64

// Adjusted to take the same space as CC_SHA1_CTX
// The order is important on a 64 bit system so that
// the length variable is 64 bit aligned.

typedef struct ltc_sha1_state {
    uint32_t state[5];
    uint32_t curlen;
    uint64_t length;
    unsigned char buf[LTC_SHA1_BLOCKSIZE];
} ltc_sha1_ctx;

int ltc_sha1_init(ltc_sha1_ctx *ctx);
int ltc_sha1_process(ltc_sha1_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int ltc_sha1_done(ltc_sha1_ctx *ctx, unsigned char *hash);

#endif /* _LTC_SHA1_H_ */

Added Source/descriptors/digestDescriptors/ltc_sha2_descriptor/ltc_sha224.c.





















































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
/**
   @param sha224.c
   LTC_SHA-224 new NIST standard based off of LTC_SHA-256 truncated to 224 bits (Tom St Denis)
*/

const ccDescriptor ltc_sha224_desc =
{
    .implementation_info = &cc_sha224_impinfo,
	.dtype.digest.hashsize = CC_SHA224_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA224_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_sha224_init,
	.dtype.digest.process = &ltc_sha256_process,
	.dtype.digest.done = &ltc_sha224_done,
};


/* init the sha256 er... sha224 state ;-) */
/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_sha224_init(ltc_sha256_ctx *ctx)
{
    LTC_ARGCHK(ctx != NULL);

    ctx->length = 0;
    ctx->state[0] = 0xc1059ed8UL;
    ctx->state[1] = 0x367cd507UL;
    ctx->state[2] = 0x3070dd17UL;
    ctx->state[3] = 0xf70e5939UL;
    ctx->state[4] = 0xffc00b31UL;
    ctx->state[5] = 0x68581511UL;
    ctx->state[6] = 0x64f98fa7UL;
    ctx->state[7] = 0xbefa4fa4UL;

    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (28 bytes)
   @return CRYPT_OK if successful
*/
int ltc_sha224_done(ltc_sha256_ctx *ctx, unsigned char *out)
{
    unsigned char buf[32];
    int err;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    err = ltc_sha256_done(ctx, buf);
    CC_XMEMCPY(out, buf, 28);
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(buf, sizeof(buf));
#endif 
    return err;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  ltc_sha224_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      const char *msg;
      unsigned char hash[28];
  } tests[] = {
    { "abc",
      { 0x23, 0x09, 0x7d, 0x22, 0x34, 0x05, 0xd8,
        0x22, 0x86, 0x42, 0xa4, 0x77, 0xbd, 0xa2,
        0x55, 0xb3, 0x2a, 0xad, 0xbc, 0xe4, 0xbd,
        0xa0, 0xb3, 0xf7, 0xe3, 0x6c, 0x9d, 0xa7 }
    },
    { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
      { 0x75, 0x38, 0x8b, 0x16, 0x51, 0x27, 0x76,
        0xcc, 0x5d, 0xba, 0x5d, 0xa1, 0xfd, 0x89,
        0x01, 0x50, 0xb0, 0xc6, 0x45, 0x5c, 0xb4,
        0xf5, 0x8b, 0x19, 0x52, 0x52, 0x25, 0x25 }
    },
  };

  int i;
  unsigned char tmp[28];
  ltc_hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
      ltc_sha224_init(&md);
      ltc_sha224_process(&md, (const unsigned char*)tests[i].msg,
	  (unsigned long)strlen(tests[i].msg));
      ltc_sha224_done(&md, tmp);
      if (LTC_XMEMCMP(tmp, tests[i].hash, 28) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
 #endif
}

Added Source/descriptors/digestDescriptors/ltc_sha2_descriptor/ltc_sha224.h.

































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_sha224.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#ifndef _LTC_SHA224_H_
#define _LTC_SHA224_H_

/*
 * Note that ltc_sha256 is required for ltc_sha224.
 */

#define	LTC_SHA224_HASHSIZE	28
#define	LTC_SHA224_BLOCKSIZE	64

int ltc_sha224_init(ltc_sha256_ctx *ctx);
#define ltc_sha224_process ltc_sha256_process
int ltc_sha224_done(ltc_sha256_ctx *ctx, unsigned char *hash);
int ltc_sha224_test(void);

#endif /* _LTC_SHA224_H_ */

Added Source/descriptors/digestDescriptors/ltc_sha2_descriptor/ltc_sha256.c.







































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <stdio.h>
#include "ltc_sha256.h"
#include "ltc_sha224.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"

/**
  @file ltc_sha256.c
  LTC_SHA256 by Tom St Denis 
*/

const ccDescriptor ltc_sha256_desc =
{
    .implementation_info = &cc_sha256_impinfo,
	.dtype.digest.hashsize = CC_SHA256_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA256_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_sha256_init,
	.dtype.digest.process = &ltc_sha256_process,
	.dtype.digest.done = &ltc_sha256_done,
};


#ifdef LTC_SMALL_CODE
/* the K array */
static const ulong32 K[64] = {
    0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
    0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
    0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
    0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
    0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
    0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
    0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
    0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
    0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
    0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
    0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
    0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
    0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};
#endif

/* Various logical functions */
#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
#define Maj(x,y,z)      (((x | y) & z) | (x & y)) 
#define S(x, n)         LTC_RORc((x),(n))
#define R(x, n)         (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x)       (S(x, 2) ^ S(x, 13) ^ S(x, 22))
#define Sigma1(x)       (S(x, 6) ^ S(x, 11) ^ S(x, 25))
#define Gamma0(x)       (S(x, 7) ^ S(x, 18) ^ R(x, 3))
#define Gamma1(x)       (S(x, 17) ^ S(x, 19) ^ R(x, 10))

/* compress 512-bits */
#ifdef LTC_CLEAN_STACK
static int _sha256_compress(ltc_sha256_ctx *ctx, const unsigned char *buf)
#else
static int  sha256_compress(ltc_sha256_ctx *ctx, const unsigned char *buf)
#endif
{
    ulong32 S[8], W[64], t0, t1;
#ifdef LTC_SMALL_CODE
    ulong32 t;
#endif
    int i;

    /* copy state into S */
    for (i = 0; i < 8; i++) {
        S[i] = ctx->state[i];
    }

    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LTC_LOAD32H(W[i], buf + (4*i));
    }

    /* fill W[16..63] */
    for (i = 16; i < 64; i++) {
        W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
    }        

    /* Compress */
#ifdef LTC_SMALL_CODE   
#define RND(a,b,c,d,e,f,g,h,i)                         \
     t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i];   \
     t1 = Sigma0(a) + Maj(a, b, c);                    \
     d += t0;                                          \
     h  = t0 + t1;

     for (i = 0; i < 64; ++i) {
         RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i);
         t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; 
         S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;
     }  
#else 
#define RND(a,b,c,d,e,f,g,h,i,ki)                    \
     t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i];   \
     t1 = Sigma0(a) + Maj(a, b, c);                  \
     d += t0;                                        \
     h  = t0 + t1;

    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x71374491);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcf);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba5);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25b);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,0x59f111f1);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,0x923f82a4);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,0xab1c5ed5);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,0xd807aa98);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,0x12835b01);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,0x243185be);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,0x550c7dc3);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,0x72be5d74);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,0x80deb1fe);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,0x9bdc06a7);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,0xc19bf174);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,0xe49b69c1);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,0xefbe4786);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,0x0fc19dc6);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,0x240ca1cc);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,0x2de92c6f);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,0x4a7484aa);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,0x5cb0a9dc);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,0x76f988da);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,0x983e5152);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,0xa831c66d);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,0xb00327c8);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,0xbf597fc7);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,0xc6e00bf3);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,0xd5a79147);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,0x06ca6351);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,0x14292967);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,0x27b70a85);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,0x2e1b2138);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,0x4d2c6dfc);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,0x53380d13);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,0x650a7354);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,0x766a0abb);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,0x81c2c92e);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,0x92722c85);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,0xa2bfe8a1);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,0xa81a664b);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,0xc24b8b70);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,0xc76c51a3);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,0xd192e819);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,0xd6990624);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,0xf40e3585);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,0x106aa070);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,0x19a4c116);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,0x1e376c08);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,0x2748774c);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,0x34b0bcb5);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,0x391c0cb3);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,0x4ed8aa4a);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,0x5b9cca4f);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,0x682e6ff3);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,0x748f82ee);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,0x78a5636f);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,0x84c87814);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,0x8cc70208);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,0x90befffa);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,0xa4506ceb);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);

#undef RND     
    
#endif     

    /* feedback */
    for (i = 0; i < 8; i++) {
        ctx->state[i] = ctx->state[i] + S[i];
    }
    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int sha256_compress(ltc_sha256_ctx *ctx, const unsigned char *buf)
{
    int err;
    err = _sha256_compress(ctx, buf);

    ltc_burn_stack(sizeof(ulong32) * 74);
    return err;
}
#endif

#define FULLLENGTH_MASK 0xffffffffffffffc0
#define BUFFLENGTH_MASK 0x3f

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_sha256_init(ltc_sha256_ctx *ctx)
{
    LTC_ARGCHK(ctx != NULL);
    
    ctx->length = 0;
    ctx->state[0] = 0x6A09E667UL;
    ctx->state[1] = 0xBB67AE85UL;
    ctx->state[2] = 0x3C6EF372UL;
    ctx->state[3] = 0xA54FF53AUL;
    ctx->state[4] = 0x510E527FUL;
    ctx->state[5] = 0x9B05688CUL;
    ctx->state[6] = 0x1F83D9ABUL;
    ctx->state[7] = 0x5BE0CD19UL;

    return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
// LTC_HASH_PROCESS(ltc_sha256_process, sha256_compress, ltc_sha256_ctx, sha256, 64)
int ltc_sha256_process(ltc_sha256_ctx *ctx, const unsigned char *in, unsigned long inlen)
{
    unsigned long n; 
    int err;
    int fullblocks, remainder, processed, i;
    uint64_t curlen;
    
    LTC_ARGCHK(ctx != NULL); 
    LTC_ARGCHK(in != NULL);
    
    curlen = ctx->length & BUFFLENGTH_MASK;
    
    if ((ctx->length + inlen) < ctx->length) { 
        return CRYPT_HASH_OVERFLOW; 
    }
    
    while (inlen > 0) { 
        if (curlen == 0 && inlen >= LTC_SHA256_BLOCKSIZE) {
            fullblocks = inlen / LTC_SHA256_BLOCKSIZE;
            remainder = inlen % LTC_SHA256_BLOCKSIZE;
            processed = fullblocks * LTC_SHA256_BLOCKSIZE;
            for(i=0; i< fullblocks; i++) {
            	sha256_compress (ctx, in);
                in += LTC_SHA256_BLOCKSIZE;
            }
            ctx->length += LTC_SHA256_BLOCKSIZE * 8 * fullblocks; 
            inlen -= processed; 
        } else {
            n = MIN(inlen, (LTC_SHA256_BLOCKSIZE - curlen)); 
            memcpy(ctx->buf + curlen, in, (size_t)n); 
            curlen += n; in += n; inlen -= n; 
            if (curlen == LTC_SHA256_BLOCKSIZE) {
                sha256_compress (ctx, ctx->buf);
                ctx->length += 8*LTC_SHA256_BLOCKSIZE;
                curlen = 0; 
            } 
        } 
    }
    
    ctx->length = (ctx->length & FULLLENGTH_MASK) + curlen;
    
    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (32 bytes)
   @return CRYPT_OK if successful
*/
int ltc_sha256_done(ltc_sha256_ctx *ctx, unsigned char *out)
{
    int i;
    uint64_t curlen;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    curlen = ctx->length & BUFFLENGTH_MASK;
    ctx->length &= FULLLENGTH_MASK;


    /* increase the length of the message */
    ctx->length += curlen * 8;

    /* append the '1' bit */
    ctx->buf[curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (curlen > 56) {
        while (curlen < 64) {
            ctx->buf[curlen++] = (unsigned char)0;
        }
        sha256_compress(ctx, ctx->buf);
        curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (curlen < 56) {
        ctx->buf[curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64H(ctx->length, ctx->buf+56);
    sha256_compress(ctx, ctx->buf);

    /* copy output */
    for (i = 0; i < 8; i++) {
        LTC_STORE32H(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(ctx, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  ltc_sha256_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      const char *msg;
      unsigned char hash[32];
  } tests[] = {
    { "abc",
      { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
        0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
        0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
        0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }
    },
    { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
      { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 
        0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
        0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 
        0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }
    },
  };

  int i;
  unsigned char tmp[32];
  ltc_hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
      ltc_sha256_init(&md);
      ltc_sha256_process(&md, (const unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
      ltc_sha256_done(&md, tmp);
      if (LTC_XMEMCMP(tmp, tests[i].hash, 32) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
 #endif
}

#include "ltc_sha224.c"

Added Source/descriptors/digestDescriptors/ltc_sha2_descriptor/ltc_sha256.h.









































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_sha256.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>

#ifndef _LTC_SHA256_H_
#define _LTC_SHA256_H_

#define	LTC_SHA256_HASHSIZE	32
#define	LTC_SHA256_BLOCKSIZE	64

typedef struct ltc_sha256_state {
    uint64_t length;
    uint32_t state[8];
    unsigned char buf[LTC_SHA256_BLOCKSIZE];
} ltc_sha256_ctx;

int ltc_sha256_init(ltc_sha256_ctx *ctx);
int ltc_sha256_process(ltc_sha256_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int ltc_sha256_done(ltc_sha256_ctx *ctx, unsigned char *hash);

#endif /* _LTC_SHA256_H_ */

Added Source/descriptors/digestDescriptors/ltc_sha2_descriptor/ltc_sha384.c.



































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
/** 
   @param sha384.c
   LTC_SHA384 hash included in sha512.c, Tom St Denis
*/

const ccDescriptor ltc_sha384_desc =
{
    .implementation_info = &cc_sha384_impinfo,
	.dtype.digest.hashsize = CC_SHA384_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA384_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_sha384_init,
	.dtype.digest.process = &ltc_sha512_process,
	.dtype.digest.done = &ltc_sha384_done,
};


/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_sha384_init(ltc_sha512_ctx *ctx)
{
    LTC_ARGCHK(ctx != NULL);

    ctx->curlen = 0;
    ctx->length = 0;
    ctx->state[0] = LTC_CONST64(0xcbbb9d5dc1059ed8);
    ctx->state[1] = LTC_CONST64(0x629a292a367cd507);
    ctx->state[2] = LTC_CONST64(0x9159015a3070dd17);
    ctx->state[3] = LTC_CONST64(0x152fecd8f70e5939);
    ctx->state[4] = LTC_CONST64(0x67332667ffc00b31);
    ctx->state[5] = LTC_CONST64(0x8eb44a8768581511);
    ctx->state[6] = LTC_CONST64(0xdb0c2e0d64f98fa7);
    ctx->state[7] = LTC_CONST64(0x47b5481dbefa4fa4);

    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (48 bytes)
   @return CRYPT_OK if successful
*/
int ltc_sha384_done(ltc_sha512_ctx *ctx, unsigned char *out)
{
   unsigned char buf[64];

   LTC_ARGCHK(ctx  != NULL);
   LTC_ARGCHK(out != NULL);

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }

   ltc_sha512_done(ctx, buf);
   CC_XMEMCPY(out, buf, 48);
#ifdef LTC_CLEAN_STACK
   ltc_zeromem(buf, sizeof(buf));
#endif
   return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int ltc_sha384_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      const char *msg;
      unsigned char hash[48];
  } tests[] = {
    { "abc",
      { 0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b,
        0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07,
        0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63,
        0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed,
        0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23,
        0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7 }
    },
    { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
      { 0x09, 0x33, 0x0c, 0x33, 0xf7, 0x11, 0x47, 0xe8,
        0x3d, 0x19, 0x2f, 0xc7, 0x82, 0xcd, 0x1b, 0x47,
        0x53, 0x11, 0x1b, 0x17, 0x3b, 0x3b, 0x05, 0xd2,
        0x2f, 0xa0, 0x80, 0x86, 0xe3, 0xb0, 0xf7, 0x12,
        0xfc, 0xc7, 0xc7, 0x1a, 0x55, 0x7e, 0x2d, 0xb9,
        0x66, 0xc3, 0xe9, 0xfa, 0x91, 0x74, 0x60, 0x39 }
    },
  };

  int i;
  unsigned char tmp[48];
  ltc_hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
      ltc_sha384_init(&md);
      ltc_sha384_process(&md, (const unsigned char*)tests[i].msg,
	  (unsigned long)strlen(tests[i].msg));
      ltc_sha384_done(&md, tmp);
      if (LTC_XMEMCMP(tmp, tests[i].hash, 48) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
 #endif
}

Added Source/descriptors/digestDescriptors/ltc_sha2_descriptor/ltc_sha384.h.































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_sha384.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#ifndef _LTC_SHA384_H_
#define _LTC_SHA384_H_

/*
 * Note that ltc_sha512 is required for ltc_sha384.
 */

#define	LTC_SHA384_HASHSIZE	48
#define	LTC_SHA384_BLOCKSIZE	128

int ltc_sha384_init(ltc_sha512_ctx *ctx);
#define ltc_sha384_process ltc_sha512_process
int ltc_sha384_done(ltc_sha512_ctx *ctx, unsigned char *hash);

#endif /* _LTC_SHA384_H_ */

Added Source/descriptors/digestDescriptors/ltc_sha2_descriptor/ltc_sha512.c.



































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <stdio.h>
#include "ltc_sha512.h"
#include "ltc_sha384.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"

/**
   @param ltc_sha512.c
   LTC_SHA512 by Tom St Denis 
*/

const ccDescriptor ltc_sha512_desc =
{
    .implementation_info = &cc_sha512_impinfo,
	.dtype.digest.hashsize = CC_SHA512_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA512_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &ltc_sha512_init,
	.dtype.digest.process = &ltc_sha512_process,
	.dtype.digest.done = &ltc_sha512_done,
};


/* the K array */
static const ulong64 K[80] = {
LTC_CONST64(0x428a2f98d728ae22), LTC_CONST64(0x7137449123ef65cd), 
LTC_CONST64(0xb5c0fbcfec4d3b2f), LTC_CONST64(0xe9b5dba58189dbbc),
LTC_CONST64(0x3956c25bf348b538), LTC_CONST64(0x59f111f1b605d019), 
LTC_CONST64(0x923f82a4af194f9b), LTC_CONST64(0xab1c5ed5da6d8118),
LTC_CONST64(0xd807aa98a3030242), LTC_CONST64(0x12835b0145706fbe), 
LTC_CONST64(0x243185be4ee4b28c), LTC_CONST64(0x550c7dc3d5ffb4e2),
LTC_CONST64(0x72be5d74f27b896f), LTC_CONST64(0x80deb1fe3b1696b1), 
LTC_CONST64(0x9bdc06a725c71235), LTC_CONST64(0xc19bf174cf692694),
LTC_CONST64(0xe49b69c19ef14ad2), LTC_CONST64(0xefbe4786384f25e3), 
LTC_CONST64(0x0fc19dc68b8cd5b5), LTC_CONST64(0x240ca1cc77ac9c65),
LTC_CONST64(0x2de92c6f592b0275), LTC_CONST64(0x4a7484aa6ea6e483), 
LTC_CONST64(0x5cb0a9dcbd41fbd4), LTC_CONST64(0x76f988da831153b5),
LTC_CONST64(0x983e5152ee66dfab), LTC_CONST64(0xa831c66d2db43210), 
LTC_CONST64(0xb00327c898fb213f), LTC_CONST64(0xbf597fc7beef0ee4),
LTC_CONST64(0xc6e00bf33da88fc2), LTC_CONST64(0xd5a79147930aa725), 
LTC_CONST64(0x06ca6351e003826f), LTC_CONST64(0x142929670a0e6e70),
LTC_CONST64(0x27b70a8546d22ffc), LTC_CONST64(0x2e1b21385c26c926), 
LTC_CONST64(0x4d2c6dfc5ac42aed), LTC_CONST64(0x53380d139d95b3df),
LTC_CONST64(0x650a73548baf63de), LTC_CONST64(0x766a0abb3c77b2a8), 
LTC_CONST64(0x81c2c92e47edaee6), LTC_CONST64(0x92722c851482353b),
LTC_CONST64(0xa2bfe8a14cf10364), LTC_CONST64(0xa81a664bbc423001),
LTC_CONST64(0xc24b8b70d0f89791), LTC_CONST64(0xc76c51a30654be30),
LTC_CONST64(0xd192e819d6ef5218), LTC_CONST64(0xd69906245565a910), 
LTC_CONST64(0xf40e35855771202a), LTC_CONST64(0x106aa07032bbd1b8),
LTC_CONST64(0x19a4c116b8d2d0c8), LTC_CONST64(0x1e376c085141ab53), 
LTC_CONST64(0x2748774cdf8eeb99), LTC_CONST64(0x34b0bcb5e19b48a8),
LTC_CONST64(0x391c0cb3c5c95a63), LTC_CONST64(0x4ed8aa4ae3418acb), 
LTC_CONST64(0x5b9cca4f7763e373), LTC_CONST64(0x682e6ff3d6b2b8a3),
LTC_CONST64(0x748f82ee5defb2fc), LTC_CONST64(0x78a5636f43172f60), 
LTC_CONST64(0x84c87814a1f0ab72), LTC_CONST64(0x8cc702081a6439ec),
LTC_CONST64(0x90befffa23631e28), LTC_CONST64(0xa4506cebde82bde9), 
LTC_CONST64(0xbef9a3f7b2c67915), LTC_CONST64(0xc67178f2e372532b),
LTC_CONST64(0xca273eceea26619c), LTC_CONST64(0xd186b8c721c0c207), 
LTC_CONST64(0xeada7dd6cde0eb1e), LTC_CONST64(0xf57d4f7fee6ed178),
LTC_CONST64(0x06f067aa72176fba), LTC_CONST64(0x0a637dc5a2c898a6), 
LTC_CONST64(0x113f9804bef90dae), LTC_CONST64(0x1b710b35131c471b),
LTC_CONST64(0x28db77f523047d84), LTC_CONST64(0x32caab7b40c72493), 
LTC_CONST64(0x3c9ebe0a15c9bebc), LTC_CONST64(0x431d67c49c100d4c),
LTC_CONST64(0x4cc5d4becb3e42b6), LTC_CONST64(0x597f299cfc657e2a), 
LTC_CONST64(0x5fcb6fab3ad6faec), LTC_CONST64(0x6c44198c4a475817)
};

/* Various logical functions */
#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
#define Maj(x,y,z)      (((x | y) & z) | (x & y)) 
#define S(x, n)         LTC_ROR64c(x, n)
#define R(x, n)         (((x) & LTC_CONST64(0xFFFFFFFFFFFFFFFF) )>>((ulong64)n))
#define Sigma0(x)       (S(x, 28) ^ S(x, 34) ^ S(x, 39))
#define Sigma1(x)       (S(x, 14) ^ S(x, 18) ^ S(x, 41))
#define Gamma0(x)       (S(x, 1) ^ S(x, 8) ^ R(x, 7))
#define Gamma1(x)       (S(x, 19) ^ S(x, 61) ^ R(x, 6))

/* compress 1024-bits */
#ifdef LTC_CLEAN_STACK
static int _sha512_compress(ltc_sha512_ctx *ctx, const unsigned char *buf)
#else
static int  sha512_compress(ltc_sha512_ctx *ctx, const unsigned char *buf)
#endif
{
    ulong64 S[8], W[80], t0, t1;
    int i;

    /* copy state into S */
    for (i = 0; i < 8; i++) {
        S[i] = ctx->state[i];
    }

    /* copy the state into 1024-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LTC_LOAD64H(W[i], buf + (8*i));
    }

    /* fill W[16..79] */
    for (i = 16; i < 80; i++) {
        W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
    }        

    /* Compress */
#ifdef LTC_SMALL_CODE
    for (i = 0; i < 80; i++) {
        t0 = S[7] + Sigma1(S[4]) + Ch(S[4], S[5], S[6]) + K[i] + W[i];
        t1 = Sigma0(S[0]) + Maj(S[0], S[1], S[2]);
        S[7] = S[6];
        S[6] = S[5];
        S[5] = S[4];
        S[4] = S[3] + t0;
        S[3] = S[2];
        S[2] = S[1];
        S[1] = S[0];
        S[0] = t0 + t1;
    }
#else
#define RND(a,b,c,d,e,f,g,h,i)                    \
     t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i];   \
     t1 = Sigma0(a) + Maj(a, b, c);                  \
     d += t0;                                        \
     h  = t0 + t1;

     for (i = 0; i < 80; i += 8) {
         RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i+0);
         RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],i+1);
         RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],i+2);
         RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],i+3);
         RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],i+4);
         RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],i+5);
         RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],i+6);
         RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],i+7);
     }
#endif     


    /* feedback */
    for (i = 0; i < 8; i++) {
        ctx->state[i] = ctx->state[i] + S[i];
    }

    return CRYPT_OK;
}

/* compress 1024-bits */
#ifdef LTC_CLEAN_STACK
static int sha512_compress(ltc_sha512_ctx *ctx, const unsigned char *buf)
{
    int err;
    err = _sha512_compress(md, buf);

    ltc_burn_stack(sizeof(ulong64) * 90 + sizeof(int));
    return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_sha512_init(ltc_sha512_ctx *ctx)
{
    LTC_ARGCHK(ctx != NULL);

    ctx->curlen = 0;
    ctx->length = 0;
    ctx->state[0] = LTC_CONST64(0x6a09e667f3bcc908);
    ctx->state[1] = LTC_CONST64(0xbb67ae8584caa73b);
    ctx->state[2] = LTC_CONST64(0x3c6ef372fe94f82b);
    ctx->state[3] = LTC_CONST64(0xa54ff53a5f1d36f1);
    ctx->state[4] = LTC_CONST64(0x510e527fade682d1);
    ctx->state[5] = LTC_CONST64(0x9b05688c2b3e6c1f);
    ctx->state[6] = LTC_CONST64(0x1f83d9abfb41bd6b);
    ctx->state[7] = LTC_CONST64(0x5be0cd19137e2179);
    
    return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
LTC_HASH_PROCESS(ltc_sha512_process, sha512_compress, ltc_sha512_ctx, sha512, 128)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (64 bytes)
   @return CRYPT_OK if successful
*/
int ltc_sha512_done(ltc_sha512_ctx *ctx, unsigned char *out)
{
    int i;
    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }

    /* increase the length of the message */
    ctx->length += ctx->curlen * LTC_CONST64(8);

    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 112 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 112) {
        while (ctx->curlen < 128) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        sha512_compress(ctx, ctx->buf);
        ctx->curlen = 0;
    }

    /* pad upto 120 bytes of zeroes 
     * note: that from 112 to 120 is the 64 MSB of the length.  We assume that
     * you won't hash > 2^64 bits of data... :-)
     */
    while (ctx->curlen < 120) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64H(ctx->length, ctx->buf+120);
    sha512_compress(ctx, ctx->buf);

    /* copy output */
    for (i = 0; i < 8; i++) {
        LTC_STORE64H(ctx->state[i], out+(8*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(md, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  ltc_sha512_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      const char *msg;
      unsigned char hash[64];
  } tests[] = {
    { "abc",
     { 0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba,
       0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31,
       0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2,
       0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a,
       0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8,
       0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd,
       0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e,
       0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f }
    },
    { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
     { 0x8e, 0x95, 0x9b, 0x75, 0xda, 0xe3, 0x13, 0xda,
       0x8c, 0xf4, 0xf7, 0x28, 0x14, 0xfc, 0x14, 0x3f,
       0x8f, 0x77, 0x79, 0xc6, 0xeb, 0x9f, 0x7f, 0xa1,
       0x72, 0x99, 0xae, 0xad, 0xb6, 0x88, 0x90, 0x18,
       0x50, 0x1d, 0x28, 0x9e, 0x49, 0x00, 0xf7, 0xe4,
       0x33, 0x1b, 0x99, 0xde, 0xc4, 0xb5, 0x43, 0x3a,
       0xc7, 0xd3, 0x29, 0xee, 0xb6, 0xdd, 0x26, 0x54,
       0x5e, 0x96, 0xe5, 0x5b, 0x87, 0x4b, 0xe9, 0x09 }
    },
  };

  int i;
  unsigned char tmp[64];
  ltc_hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
      ltc_sha512_init(&md);
      ltc_sha512_process(&md, (const unsigned char *)tests[i].msg,
	  (unsigned long)strlen(tests[i].msg));
      ltc_sha512_done(&md, tmp);
      if (LTC_XMEMCMP(tmp, tests[i].hash, 64) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
  #endif
}

#include "ltc_sha384.c"

Added Source/descriptors/digestDescriptors/ltc_sha2_descriptor/ltc_sha512.h.









































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_sha512.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>
#ifndef _LTC_SHA512_H_
#define _LTC_SHA512_H_

#define	LTC_SHA512_HASHSIZE	64
#define	LTC_SHA512_BLOCKSIZE	128

typedef struct ltc_sha512_state {
    uint64_t  length, curlen;
    uint64_t state[8];
    unsigned char buf[LTC_SHA512_BLOCKSIZE];
} ltc_sha512_ctx;

int ltc_sha512_init(ltc_sha512_ctx *ctx);
int ltc_sha512_process(ltc_sha512_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int ltc_sha512_done(ltc_sha512_ctx *ctx, unsigned char *hash);
int ltc_sha512_test(void);

#endif /* _LTC_SHA512_H_ */

Added Source/descriptors/digestDescriptors/vng_neon_sha1_descriptor/vng_neon_sha1.c.















































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
 
#include <arm/arch.h>

#if defined(_ARM_ARCH_7)

#include <stdio.h>
#include "vng_neon_sha1.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"

/**
  @file vng_neon_sha1.c
  original LTC_SHA1 code by Tom St Denis 
  optimized compress function by the Vector and Numerics Group
*/


const ccDescriptor vng_neon_sha1_desc =
{
    .implementation_info = &cc_sha1_impinfo,
	.dtype.digest.hashsize = CC_SHA1_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA1_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &vng_neon_sha1_init,
	.dtype.digest.process = &vng_neon_sha1_process,
	.dtype.digest.done = &vng_neon_sha1_done,
};


/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int vng_neon_sha1_init(vng_neon_sha1_ctx *ctx)
{
   LTC_ARGCHK(ctx != NULL);
   
   ctx->state[0] = 0x67452301UL;
   ctx->state[1] = 0xefcdab89UL;
   ctx->state[2] = 0x98badcfeUL;
   ctx->state[3] = 0x10325476UL;
   ctx->state[4] = 0xc3d2e1f0UL;
   ctx->curlen = 0;
   ctx->length = 0;
   
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
int vng_neon_sha1_process(vng_neon_sha1_ctx *ctx, const unsigned char *in, unsigned long inlen)
{
    unsigned long n; 
    int err;
    int fullblocks, remainder, processed;
    
    LTC_ARGCHK(ctx != NULL); 
    LTC_ARGCHK(in != NULL);
        
    if (ctx->curlen > sizeof(ctx->buf)) {
        return CRYPT_INVALID_ARG;
    } 
    if ((ctx->length + inlen) < ctx->length) { 
        return CRYPT_HASH_OVERFLOW; 
    }
    
    while (inlen > 0) { 
        if (ctx->curlen == 0 && inlen >= VNG_NEON_SHA1_BLOCKSIZE && CC_XALIGNED(in, 4)) {
            fullblocks = inlen / VNG_NEON_SHA1_BLOCKSIZE;
            remainder = inlen % VNG_NEON_SHA1_BLOCKSIZE;
            processed = fullblocks * VNG_NEON_SHA1_BLOCKSIZE;
            sha1_vng_armv7neon_compress (ctx->state, fullblocks, in);
            ctx->length += VNG_NEON_SHA1_BLOCKSIZE * 8 * fullblocks; 
            in += processed;
            inlen -= processed; 
        } else {
            n = MIN(inlen, (VNG_NEON_SHA1_BLOCKSIZE - ctx->curlen)); 
            memcpy(ctx->buf + ctx->curlen, in, (size_t)n); 
            ctx->curlen += n; in += n; inlen -= n; 
            if (ctx->curlen == VNG_NEON_SHA1_BLOCKSIZE) {
                sha1_vng_armv7neon_compress (ctx->state, 1, ctx->buf);
                ctx->length += 8*VNG_NEON_SHA1_BLOCKSIZE;
                ctx->curlen = 0; 
            } 
        } 
    }
    
    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (20 bytes)
   @return CRYPT_OK if successful
*/
int vng_neon_sha1_done(vng_neon_sha1_ctx *ctx, unsigned char *out)
{
    int i;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }

    /* increase the length of the message */
    ctx->length += ctx->curlen * 8;

    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 56) {
        while (ctx->curlen < 64) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        sha1_vng_armv7neon_compress(ctx->state, 1, ctx->buf);
        ctx->curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (ctx->curlen < 56) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64H(ctx->length, ctx->buf+56);
    sha1_vng_armv7neon_compress(ctx->state, 1, ctx->buf);

    /* copy output */
    for (i = 0; i < 5; i++) {
        LTC_STORE32H(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(md, sizeof(ltc_hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  vng_neon_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      const char *msg;
      unsigned char hash[20];
  } tests[] = {
    { "abc",
      { 0xa9, 0x99, 0x3e, 0x36, 0x47, 0x06, 0x81, 0x6a,
        0xba, 0x3e, 0x25, 0x71, 0x78, 0x50, 0xc2, 0x6c,
        0x9c, 0xd0, 0xd8, 0x9d }
    },
    { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
      { 0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E,
        0xBA, 0xAE, 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5,
        0xE5, 0x46, 0x70, 0xF1 }
    }
  };

  int i;
  unsigned char tmp[20];
  ltc_hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0]));  i++) {
      vng_neon_sha1_init(&md);
      vng_neon_sha1_process(&md, (const unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
      vng_neon_sha1_done(&md, tmp);
      if (LTC_XMEMCMP(tmp, tests[i].hash, 20) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
  #endif
}

#endif /* _ARM_ARCH_7 */

Added Source/descriptors/digestDescriptors/vng_neon_sha1_descriptor/vng_neon_sha1.h.





















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  vng_neon_sha1.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>
#include <arm/arch.h>

#if defined(_ARM_ARCH_7)

#ifndef _VNG_NEON_SHA1_H_
#define _VNG_NEON_SHA1_H_

#define VNG_NEON_SHA1_HASHSIZE	20
#define VNG_NEON_SHA1_BLOCKSIZE	64

typedef struct vng_neon_sha1_state {
    uint32_t state[5];
    uint64_t length;
    unsigned char buf[VNG_NEON_SHA1_BLOCKSIZE];
    int curlen;
} vng_neon_sha1_ctx;

int vng_neon_sha1_init(vng_neon_sha1_ctx *ctx);
int vng_neon_sha1_process(vng_neon_sha1_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int vng_neon_sha1_done(vng_neon_sha1_ctx *ctx, unsigned char *hash);
void sha1_vng_armv7neon_compress(uint32_t state[], unsigned long nblocks, unsigned char *);
#endif /* _ARM_ARCH_7 */
#endif /* _VNG_NEON_SHA1_H_ */

Added Source/descriptors/digestDescriptors/vng_neon_sha1_descriptor/vng_neon_sha1Compress.s.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
/*

	This file is copied from xnu-1776 (sha1armv7neon.s) and renamed to the current name to replace
	a buggy version (based on an earlier version I sent to murf (and eventually to Fabrice).
	It improves the sha1 performance slightly (8.3 to 7.5 cycles/byte), and also fixes a
	compiled-off vpop/vpush bug (compiled only for kernel code).

	The problem with the earlier code that murf/Fabrice was working on is that 
	the order of the 2nd and 3rd calling arguments are switched. (r1/r2).
	While the internal code uses r1 as an temp register, simply changing the order will have the
	number of blocks corrupted with temp variable.

	This is fixed by staying with the original order (r0/r1/r2) = (out/in/blocks), and
	have r1/r2 switched the 1st thing the subroutine is called.

	I ran the test to verify this fixes the bug.

	cclee	1-13-11 

	sha1armv7neon.s : this file provides optimized armv7+neon implementation of the sha1 function
	CoreOS - vector & numerics group
	cclee	10-10-10

	The implementation is based on the principle described in an Intel online article
    "Improving the Performance of the Secure Hash Algorithm (SHA-1)"
    http://software.intel.com/en-us/articles/improving-the-performance-of-the-secure-hash-algorithm-1/

	Update HASH[] by processing a one 64-byte block in MESSAGE[] can be represented by the following C function

void SHA1( int HASH[], int MESSAGE[] )
{
	int A[81], B[81], C[81], D[81], E[81];
	int W[80];
	int i, FN;

	A[0] = HASH[0]; B[0] = HASH[1]; C[0] = HASH[2]; D[0] = HASH[3]; E[0] = HASH[4];

	for ( i=0; i<80; ++i ) {
		if ( i < 16 )
			W[i] = BIG_ENDIAN_LOAD( MESSAGE[i] );
		else
		 	W[i] = ROTATE_LEFT( W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1 ); 

		FN = F( i, B[i], C[i], D[i] );
		A[i+1] = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + W[i] + K(i);
		B[i+1] = A[i];
		C[i+1] = ROTATE_LEFT( B[i], 30 );
		D[i+1] = C[i];
		E[i+1] = D[i];
	}

	HASH[0] += A[80]; HASH[1] += B[80]; HASH[2] += C[80]; HASH[3] += D[80]; HASH[4] += E[80];
} 


	For i=0:15, W[i] is simply big-endian loading of MESSAGE[i]. 
	For i=16:79, W[i] is updated according to W[i] = ROTATE_LEFT( W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1 );

    The approach (by Dean Gaudet) can be used to vectorize the computation of W[i] for i=16:79,

    1. update 4 consequtive W[i] (stored in a single 16-byte register)
    W[i  ] = (W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]) rol 1
    W[i+1] = (W[i-2] ^ W[i-7] ^ W[i-13] ^ W[i-15]) rol 1
    W[i+2] = (W[i-1] ^ W[i-6] ^ W[i-12] ^ W[i-14]) rol 1
    W[i+3] = (   0   ^ W[i-5] ^ W[i-11] ^ W[i-13]) rol 1

    2. this additional calculation unfortunately requires many additional operations
    W[i+3] ^= W[i] rol 1

    3. once we have 4 W[i] values in a Q register, we can also add four K values with one instruction
    W[i:i+3] += {K,K,K,K}

    Let W0 = {W[i] W[i+1] W[i+2] W[i+3]} be the current W-vector to be computed, 
		W4 = {W[i-4] W[i-3] W[i-2] W[i-1]} be the previous vector, and so on

    The Dean Gaudet approach can be expressed as

    1. W0 = rotate_left(left_shift(W4,32) ^ W8 ^ left_shift(concatenate(W16,W12),64) ^ W16,1);
    2. W[i+3] ^= W[i] rol 1
    3. W0 += {K,K,K,K}

    For i>=32, the Intel online article suggests that (using a basic identity (X rol 1) rol 1 = X rol 2) 
	the update equation is equivalent to

    1. W0 = rotate_left(left_shift(concatenate(W8,W4),64) ^ W16 ^ W28 ^ W32, 2); 

    Note:
    1. In total, we need 8 16-byte registers or memory for W0,W4,...,W28. W0 and W32 can be the same register or memory.
    2. The registers are used in a circular buffering mode. For example, we start with W28,W24,...,W0 
		(with W0 indicating the most recent 16-byte) 
		i=0, W28,W24,...,W0
        i=4, W24,W20,...,W28
        i=8, W20,W16,...,W24
        .
        .
        and so forth.
    3. once W-vector is computed, W+K is then computed and saved in the stack memory, this will be used later when
		updating the digests A/B/C/D/E 

	the execution flow (for 1 single 64-byte block) looks like

	W_PRECALC_00_15		// big-endian loading of 64-bytes into 4 W-vectors, compute WK=W+K, save WK in the stack memory

	W_PRECALC_16_31		// for each vector, update digests, update W (Gaudet) and WK=W+K, save WK in the stack memory

	W_PRECALC_32_79		// for each vector, update digests, update W (Intel) and WK=W+K, save WK in the stack memory 

	our implementation (allows multiple blocks per call) pipelines the loading of W/WK of a future block 
    into the last 16 rounds of its previous block:

	----------------------------------------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into 4 Q registers
    pre_calculate and store WK = W+K(0:15) in 16-byte aligned stack memory

L_loop:

    load digests a-e from ctx->state;

    for (r=0;r<16;r+=4) {
        digests a-e update and permute round r:r+3
        update W([r:r+3]%16) (Gaudet) and WK([r:r+3]%16) for the next 4th iteration 
    }

    for (r=16;r<64;r+=4) {
        digests a-e update and permute round r:r+3
        update W([r:r+3]%16) (Intel) and WK([r:r+3]%16) for the next 4th iteration 
    }

    num_block--;
    if (num_block==0)   jmp L_last_block;

    for (r=64;r<80;r+=4) {
        digests a-e update and permute round r:r+3
        load W([r:r+3]%16) (big-endian per 4 bytes) into 4 Q registers
        pre_calculate and store W+K([r:r+3]%16) in stack
    }

    ctx->states += digests a-e;

    jmp L_loop;

L_last_block:

    for (r=64;r<80;r+=4) {
        digests a-e update and permute round r:r+3
    }

    ctx->states += digests a-e;


	----------------------------------------------------------------------------------------------------------
	
*/

#include <arm/arch.h>

#if defined(_ARM_ARCH_7)

#define	OPTIMIZED	1		// defined OPTIMIZED to use our final optimized assembly code
#define	Multiple_Blocks	1	// defined Multiple_Blocks to allow performing multiple blocks sha1 computation per call
							//	i.e., change to prototype to void SHA1( int HASH[], int MESSAGE[], int num_blocks );

// symbolizing all used variables

#define	ctx			r0			// SHA1_CTX	*ctx;
#define	buf			r1			// char *MESSAGE[];
#define	num_blocks	r2			// int	num_blocks;	this is used only if Multiple_Blocks is defined.

#define K_BASE     	r3			// to point to the tables for K
#define HASH_PTR   	r4			// copy of ctx, to release r0 for other usage
#define BUFFER_PTR 	r5			// copy of buf, to release r1 for other usage

// sha1 digests a-e
#define A r6
#define B r8
#define C r9
#define D r10
#define E r11

// temp variables
#define T1 r0
#define T2 r1

// used Q registers
#define W_TMP  		q12
#define W_TMP2 		q13
#define	ZERO		q14
#define	K_VALUES	q15
#define W0  		q4
#define W4  		q5
#define W8  		q6
#define W12 		q7
#define W16 		q8
#define W20 		q9
#define W24 		q10
#define W28 		q11

// for round t (0:79), W+K was previously saved in the stack space, and can be referenced by 
#define	WK(t)	[sp, #((t&15)*4)]



	// ----------- macros for initial rounds 0:15 big-endian loading of message[] and saving W+K into stack  ---------

	.macro	W_PRECALC_00_15_0		// default : BUFFER_PTR points to the current message block 
	vld1.f32 {W_TMP},[BUFFER_PTR]!	// loading 16-byte message[] (16-byte aligned) into W_TMP
	.endm

	.macro	W_PRECALC_00_15_1		// input $0 : current 16-bytes in the circular buffer
	vrev32.8 $0, W_TMP				// byte swap W_TMP and save to $0
	.endm

	.macro	W_PRECALC_00_15_2		// $0 = W, K_VALUES = (K,K,K,K)
	vadd.s32	W_TMP, $0, K_VALUES	// W_TMP = W + K
	.endm
	
	.macro	W_PRECALC_00_15_3		// default : lr points to the 16-byte aligned memory to store W+K
	vst1.s32	{W_TMP}, [lr,:128]!	// save W[i]+K in 16-byte aligned stack memory
	.endm

	.macro	INITIAL_W_PRECALC

	vld1.s32	{K_VALUES}, [K_BASE,:128]!		// loading K values into a Q register

	// W28,W24,....,W4,W0 is used as memory in a circular buffer. They are listed in forward order from left to right.
	// The last one, e.g., W0=W[0], is the current 4 .long (4-bytes) register. W4 = W[-4]. W28 = W[-28].
	// After a circular buffer rotation, W28 = W[0], W0 = W[-4], W4 = W[-8] and so forth.

#if !OPTIMIZED

	// proliferate the code using the above 4 macros
	// at this point, lr = sp (16-bytes aligned), K_VALUES dupped with K, NUFFER_PTR points to the current message[]

	// i=0
	// circular buffer : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0						// W_TMP = (BUFFER_PTR)
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W[0] = W_TMP	
	W_PRECALC_00_15_2	W0					// W_TMP = W[0] + K[0]
	W_PRECALC_00_15_3						// (sp) = W_TMP = W[0] + K[0]

	// i=4
	// circular buffer : W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0						// W_TMP = 16(BUFFER_PTR)
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W[0] = W_TMP	
	W_PRECALC_00_15_2	W28					// W_TMP = W[0] + K[0]
	W_PRECALC_00_15_3						// 16(sp) = W_TMP = W[0] + K[0]

	// i=8
	// circular buffer : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0						// W_TMP = 32(BUFFER_PTR)
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W[0] = W_TMP
	W_PRECALC_00_15_2	W24					// W_TMP = W[0] + K[0]
	W_PRECALC_00_15_3						// 32(sp) = W_TMP = W[0] + K[0]

	// i=12
	// circular buffer : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0						// W_TMP = 48(BUFFER_PTR)
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W[0] = W_TMP	
	W_PRECALC_00_15_2	W20					// W_TMP = W[0] + K[0]
	W_PRECALC_00_15_3						// 48(sp) = W_TMP = W[0] + K[0]

#else

	// the following performs the same task, using less instructions (and slightly fewer CPU cycles)
	//the code uses W4 W8 temporarily, with no harm

	vld1.f32 {W_TMP,W_TMP2},[BUFFER_PTR]!
	vld1.f32 {W4,W8},[BUFFER_PTR]!
	vrev32.8 W0, W_TMP
	vrev32.8 W28, W_TMP2
	vrev32.8 W24, W4
	vrev32.8 W20, W8
	vadd.s32	W_TMP, W0, K_VALUES
	vadd.s32	W_TMP2, W28, K_VALUES
	vadd.s32	W4, W24, K_VALUES
	vadd.s32	W8, W20, K_VALUES
	vst1.s32	{W_TMP,W_TMP2}, [lr,:128]!	// save W[i]+K(i) in stack memory
	vst1.s32	{W4,W8}, [lr,:128]!	// save W[i]+K(i) in stack memory

#endif

	.endm		// INITIAL_W_PRECALC

	// ----------------- functions F1/F2/F3/F4 used in updating the sha1 digests -----------------------

	// F1(b,c,d) = ((((c) ^ (d)) & (b)) ^ (d))
	.macro	F1
	eor	T1, $2, $1
	and	T1, $0
	eor	T1, $2
	.endm

	// F2(b,c,d) = ((b) ^ (c) ^ (d))
	.macro	F2
	eor	T1, $1, $2
	eor	T1, $0
	.endm

	// F3(b,c,d) = (((b) & (c)) | (((b) | (c)) & (d)))
	.macro	F3
	orr T1, $0, $1
	and r12, $1, $0
	and T1, $2
	orr	T1, r12
	.endm

	#define	F4	F2					// F4 = F2

	// -------------------------------------------------------------------------------------------------

	// ------  macros for performing sha1 digest update, rotating the roles of digest registers  -------
	/*
		FN = F( i, B[i], C[i], D[i] );
		A[i+1] = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + WK[i];
		B[i+1] = A[i];
		C[i+1] = ROTATE_LEFT( B[i], 30 );
		D[i+1] = C[i];
		E[i+1] = D[i];
	*/

	.macro	RR0
	$0		$2, $3, $4			// T1 = FN = F( i, B[i], C[i], D[i] );
	ldr		r12, WK($6)			// r12 = WK[i]
	ror		$2, #2				// C[i+1] = ROTATE_LEFT( B[i], 30 );
	add		$5, r12				// E[i] + WK[i]
	ldr		r12, WK($6+1)		// r12 = WK[i+1]
	add		$4, r12				// D[i] + WK[i+1]
	add		$5, T1				// E[i] + WK[i] + FN
	.endm

	.macro	RR1
	add		$5, $5, $1, ror #27				// T2 = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + WK[i]
	add		$4, $5, ror #27			// E[i+1] + WK[i+1] + ROTATE_LEFT( A[i+1], 5 )
	$0		$1, $2, $3			// T1 = FN = F(i+1, B[i+1], C[i+1], D[i+1])
	add		$4, T1				// FN + FN + E[i+1] + ROTATE_LEFT( A[i+1], 5 ) + WK[i+1]; 
	ror		$1, #2				// C[i+1] = B[i] = ROTATE_LEFT( B[i], 30 );
	.endm
	// -------------------------------------------------------------------------------------------------

	// RR0/RR1 and F1/F2/F3 are combined (re-organize the instruction schedule to reduce stalls)
	// hence the following 6 combined macros

	.macro	RR0_F1
	ldr		r12, WK($6)
	eor 	T1, $3, $4
	ldr		T2, WK($6+1)
	and		T1, $2
	add		$5, r12
	ror		$2, #2
	eor		T1, $4
	add		$4, T2
	add		$5, T1
	.endm

	.macro	RR0_F2
	ldrd	T1,T2,WK($6)
	eor		r12, $2, $4
	ror		$2, #2
	eor		r12, $3
	add		$5, T1
	add		$4, T2
	add		$5, r12
	.endm

	.macro	RR0_F3
	ldr		r12, WK($6)
	orr		T1, $2, $3
	and		T2, $2, $3 
	ror		$2, #2
	add		$5, r12
	ldr		r12, WK($6+1)
	and		T1, $4
	orr		T1, T2
	add		$4, r12
	add		$5, T1
	.endm

	.macro	RR1_F1
	add		$5, $5, $1, ror #27
    eor 	T1, $3, $2
    and 	T1, $1
    eor 	T1, $3
	add		$4, $5, ror #27
	ror		$1, #2
	add		$4, T1
	.endm

	.macro	RR1_F2
	eor		T1, $1, $2
	add		$5, $5, $1, ror #27
	eor		T1, $3
	add		$4, T1
	add		$4, $5, ror #27
	ror		$1, #2
	.endm

	.macro	RR1_F3
	add		$5, $5, $1, ror #27
	orr		T1, $1, $2
	and		T1, $3
	and		r12, $1, $2
	orr		T1, r12
	add		$4, $5, ror #27
	ror		$1, #2
	add		$4, T1
	.endm


	// ------  rounds 16-31 compute W[0] using the vectorization approach by Dean Gaudet -------
	/*
	W[i  ] = (W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]) rol 1
    W[i+1] = (W[i-2] ^ W[i-7] ^ W[i-13] ^ W[i-15]) rol 1
    W[i+2] = (W[i-1] ^ W[i-6] ^ W[i-12] ^ W[i-14]) rol 1
    W[i+3] = (   0   ^ W[i-5] ^ W[i-11] ^ W[i-13]) rol 1

	W[i+3] ^= W[i] rol 1
	*/

	// -------------- macros for rounds 16-31 compute W (Gaudet's approach) and save W+K --------------

	.macro	W_PRECALC_16_31_0			// W_16,W_12,W_8,W_4,W
	vext.64	$4, $0, $1, #1
	veor	$4, $2						// W_8 ^ W_14	
	vext.32	W_TMP,$3,ZERO,#1
	.endm

	.macro	W_PRECALC_16_31_1	// W_16,W
	veor	W_TMP, $0				// W_3 ^ W_16
	veor	$1, W_TMP				// W_3 ^ W_16 ^ W_8 ^ W_14
	vshl.i32	W_TMP, $1, #1
	vext.32	W_TMP2,ZERO, $1, #1	
	vshr.u32	$1, #31
	.endm

	.macro	W_PRECALC_16_31_2	// W
	vorr	W_TMP, $0
	vshl.i32	$0, W_TMP2, #2
	vshr.u32	W_TMP2, #30
	.endm

	.macro	W_PRECALC_16_31_3	// W, i, K_XMM
	veor	W_TMP, W_TMP2
	veor	W_TMP, $0
	vadd.s32	W_TMP2, W_TMP, K_VALUES
	vorr	$0, W_TMP, W_TMP
	vst1.f32	{W_TMP2}, [lr,:128]!
	.endm

	// -------------- macros for rounds 32-79 compute W (Max's approach) and save W+K --------------

	.macro	W_PRECALC_32_79_0			// W_28,W_8,W_4,W
	veor		$3, $0
	vext.64		W_TMP, $1, $2, #1
	.endm

	.macro	W_PRECALC_32_79_1	// W_16,W
	veor	W_TMP, $0
	veor	W_TMP, $1
	vshr.u32	$1, W_TMP, #30
	vshl.i32	W_TMP, #2
	.endm

	.macro	W_PRECALC_32_79_2	// W
	vorr		W_TMP, $0
	.endm

	.macro	W_PRECALC_32_79_3	// W, i, K_XMM
	vadd.s32	W_TMP2, W_TMP, K_VALUES
	vorr	$0, W_TMP, W_TMP
	vst1.f32	{W_TMP2}, [lr,:128]!
	.endm

	// the main code body in early revisions --- no so optimized

#if	!OPTIMIZED
	.macro	INTERNAL
	// i=16
	// circular buffer : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_16_31_0	W0,W28,W24,W20,W16
	RR0_F1				F1,A,B,C,D,E,0
	W_PRECALC_16_31_1	W0,W16
	RR1_F1				F1,A,B,C,D,E,0
	W_PRECALC_16_31_2	W16
	RR0_F1				F1,D,E,A,B,C,2
	W_PRECALC_16_31_3	W16, 2, 0
	RR1_F1				F1,D,E,A,B,C,2

	vld1.s32	{K_VALUES}, [K_BASE,:128]!

	// i=20,
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_16_31_0	W28,W24,W20,W16,W12
	RR0_F1				F1,B,C,D,E,A,4
	W_PRECALC_16_31_1	W28,W12
	RR1_F1				F1,B,C,D,E,A,4
	W_PRECALC_16_31_2	W12
	RR0_F1				F1,E,A,B,C,D,6
	W_PRECALC_16_31_3	W12, 6, 16
	RR1_F1				F1,E,A,B,C,D,6

	// i=24,
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_16_31_0	W24,W20,W16,W12,W8
	RR0_F1				F1,C,D,E,A,B,8
	W_PRECALC_16_31_1	W24,W8
	RR1_F1				F1,C,D,E,A,B,8
	W_PRECALC_16_31_2	W8
	RR0_F1				F1,A,B,C,D,E,10
	W_PRECALC_16_31_3	W8,10,16
	RR1_F1				F1,A,B,C,D,E,10

	// i=28
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_16_31_0	W20,W16,W12,W8,W4
	RR0_F1				F1,D,E,A,B,C,12
	W_PRECALC_16_31_1	W20,W4
	RR1_F1				F1,D,E,A,B,C,12
	W_PRECALC_16_31_2	W4
	RR0_F1				F1,B,C,D,E,A,14
	W_PRECALC_16_31_3	W4,14,16
	RR1_F1				F1,B,C,D,E,A,14

	sub		lr, #0x40

	//i=32
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0_F1				F1,E,A,B,C,D,16
	W_PRECALC_32_79_1	W16,W0
	RR1_F1				F1,E,A,B,C,D,16
	W_PRECALC_32_79_2	W0
	RR0_F1				F1,C,D,E,A,B,18
	W_PRECALC_32_79_3	W0,18,16
	RR1_F1				F1,C,D,E,A,B,18

	//i=36
	// W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_32_79_0	W24,W4,W0,W28
	RR0_F2				F2,A,B,C,D,E,20
	W_PRECALC_32_79_1	W12,W28
	RR1_F2				F2,A,B,C,D,E,20
	W_PRECALC_32_79_2	W28
	RR0_F2				F2,D,E,A,B,C,22
	W_PRECALC_32_79_3	W28,22,16
	RR1_F2				F2,D,E,A,B,C,22

	vld1.s32    {K_VALUES}, [K_BASE,:128]!

	//i=40
	#undef  K_XMM
    #define K_XMM   32
	// W20,W16,W12,W8,W4,W0,W28,W24	
	W_PRECALC_32_79_0	W20,W0,W28,W24
	RR0_F2				F2,B,C,D,E,A,24
	W_PRECALC_32_79_1	W8,W24
	RR1_F2				F2,B,C,D,E,A,24
	W_PRECALC_32_79_2	W24
	RR0_F2				F2,E,A,B,C,D,26
	W_PRECALC_32_79_3	W24,26,K_XMM
	RR1_F2				F2,E,A,B,C,D,26

	//i=44
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0_F2				F2,C,D,E,A,B,28
	W_PRECALC_32_79_1	W4,W20
	RR1_F2				F2,C,D,E,A,B,28
	W_PRECALC_32_79_2	W20
	RR0_F2				F2,A,B,C,D,E,30
	W_PRECALC_32_79_3	W20,30,K_XMM
	RR1_F2				F2,A,B,C,D,E,30

	sub		lr, #0x40

	//i=48
	// W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_32_79_0	W12,W24,W20,W16
	RR0_F2				F2,D,E,A,B,C,32
	W_PRECALC_32_79_1	W0,W16
	RR1_F2				F2,D,E,A,B,C,32
	W_PRECALC_32_79_2	W16
	RR0_F2				F2,B,C,D,E,A,34
	W_PRECALC_32_79_3	W16,34,K_XMM
	RR1_F2				F2,B,C,D,E,A,34

	//i=52
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_32_79_0	W8,W20,W16,W12
	RR0_F2				F2,E,A,B,C,D,36
	W_PRECALC_32_79_1	W28,W12
	RR1_F2				F2,E,A,B,C,D,36
	W_PRECALC_32_79_2	W12
	RR0_F2				F2,C,D,E,A,B,38
	W_PRECALC_32_79_3	W12,38,K_XMM
	RR1_F2				F2,C,D,E,A,B,38

	//i=56
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_32_79_0	W4,W16,W12,W8
	RR0_F3				F3,A,B,C,D,E,40
	W_PRECALC_32_79_1	W24,W8
	RR1					F3,A,B,C,D,E,40
	W_PRECALC_32_79_2	W8
	RR0_F3				F3,D,E,A,B,C,42
	W_PRECALC_32_79_3	W8,42,K_XMM
	RR1_F3				F3,D,E,A,B,C,42

	vld1.s32    {K_VALUES}, [K_BASE,:128]!

	//i=60
	#undef	K_XMM
	#define	K_XMM	48
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_32_79_0	W0,W12,W8,W4
	RR0_F3				F3,B,C,D,E,A,44
	W_PRECALC_32_79_1	W20,W4
	RR1_F3				F3,B,C,D,E,A,44
	W_PRECALC_32_79_2	W4
	RR0_F3				F3,E,A,B,C,D,46
	W_PRECALC_32_79_3	W4,46,K_XMM
	RR1_F3				F3,E,A,B,C,D,46

	sub		lr, #0x40

	//i=64
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0_F3				F3,C,D,E,A,B,48
	W_PRECALC_32_79_1	W16,W0
	RR1_F3				F3,C,D,E,A,B,48
	W_PRECALC_32_79_2	W0
	RR0_F3				F3,A,B,C,D,E,50
	W_PRECALC_32_79_3	W0,50,K_XMM
	RR1_F3				F3,A,B,C,D,E,50

	//i=68
	// W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_32_79_0	W24,W4,W0,W28
	RR0_F3				F3,D,E,A,B,C,52
	W_PRECALC_32_79_1	W12,W28
	RR1_F3				F3,D,E,A,B,C,52
	W_PRECALC_32_79_2	W28
	RR0_F3				F3,B,C,D,E,A,54
	W_PRECALC_32_79_3	W28,54,K_XMM
	RR1_F3				F3,B,C,D,E,A,54

	//i=72
	// W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_32_79_0	W20,W0,W28,W24
	RR0_F3				F3,E,A,B,C,D,56
	W_PRECALC_32_79_1	W8,W24
	RR1_F3				F3,E,A,B,C,D,56
	W_PRECALC_32_79_2	W24
	RR0_F3				F3,C,D,E,A,B,58
	W_PRECALC_32_79_3	W24,58,K_XMM
	RR1_F3				F3,C,D,E,A,B,58

	// starting using F4	

	//i=76
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0_F2				F4,A,B,C,D,E,60
	W_PRECALC_32_79_1	W4,W20
	RR1_F2				F4,A,B,C,D,E,60
	W_PRECALC_32_79_2	W20
	RR0_F2				F4,D,E,A,B,C,62
	W_PRECALC_32_79_3	W20,62,K_XMM
	RR1_F2				F4,D,E,A,B,C,62

	sub		K_BASE, #64
	sub		lr, #0x40

	.endm
#endif		// !OPTIMIZED
	


	// macros that further combined W_PRECALC_16_31_0 with RR0 to reduce pipeline stalls
	
	.macro	W_PRECALC_16_31_0_RR0_0		// W_16,W_12,W_8,W_4,W
	vext.64	$4, $0, $1, #1
	ldr		r12, WK(0)
	eor 	T1, $7, $8
	ldr		T2, WK(1)
	vext.32	W_TMP,$3,ZERO,#1
	and		T1, $6
	add		$9, r12
	ror		$6, #2
	veor	$4, $2						// W_8 ^ W_14	
	eor		T1, $8
	add		$8, T2
	add		$9, T1
	ror		T2, $5, #27
	.endm

	.macro	W_PRECALC_16_31_0_RR0_4		// W_16,W_12,W_8,W_4,W
	vext.64	$4, $0, $1, #1
	ldr		r12, WK(4)
	eor 	T1, $7, $8
	ldr		T2, WK(5)
	vext.32	W_TMP,$3,ZERO,#1
	and		T1, $6
	add		$9, r12
	ror		$6, #2
	veor	$4, $2						// W_8 ^ W_14	
	eor		T1, $8
	add		$8, T2
	add		$9, T1
	ror		T2, $5, #27
	.endm

	.macro	W_PRECALC_16_31_0_RR0_8		// W_16,W_12,W_8,W_4,W
	vext.64	$4, $0, $1, #1
	ldr		r12, WK(8)
	eor 	T1, $7, $8
	ldr		T2, WK(9)
	vext.32	W_TMP,$3,ZERO,#1
	and		T1, $6
	add		$9, r12
	ror		$6, #2
	veor	$4, $2						// W_8 ^ W_14	
	eor		T1, $8
	add		$8, T2
	add		$9, T1
	ror		T2, $5, #27
	.endm

	.macro	W_PRECALC_16_31_0_RR0_12		// W_16,W_12,W_8,W_4,W
	vext.64	$4, $0, $1, #1
	ldr		r12, WK(12)
	eor 	T1, $7, $8
	ldr		T2, WK(13)
	vext.32	W_TMP,$3,ZERO,#1
	and		T1, $6
	add		$9, r12
	ror		$6, #2
	veor	$4, $2						// W_8 ^ W_14	
	eor		T1, $8
	add		$8, T2
	add		$9, T1
	ror		T2, $5, #27
	.endm

	// macros that further combined W_PRECALC_16_31_1 with RR1 to reduce pipeline stalls
	.macro	W_PRECALC_16_31_1_RR1	// W_16,W
	veor	W_TMP, $0				// W_3 ^ W_16
    eor 	T1, $4, $3
    and 	T1, $2
	add		T2, $6
    eor 	T1, $4
	veor	$1, W_TMP				// W_3 ^ W_16 ^ W_8 ^ W_14
	orr		$6, T2, T2
	// ror		T2, #27
	vshl.i32	W_TMP, $1, #1
	ror		$2, #2
	vext.32	W_TMP2,ZERO, $1, #1	
	add		$5, T1
	vshr.u32	$1, #31
	add		$5, T2, ror #27
	.endm

	// macros that further combined W_PRECALC_16_31_2 with RR0 to reduce pipeline stalls
	.macro	W_PRECALC_16_31_2_RR0	// W
	ldr		r12, WK($6)
	vorr	W_TMP, $0
	eor 	T1, $3, $4
	ldr		T2, WK($6+1)
	and		T1, $2
	vshl.i32	$0, W_TMP2, #2
	add		$5, r12
	ror		$2, #2
	eor		T1, $4
	add		$4, T2
	vshr.u32	W_TMP2, #30
	ror		T2, $1, #27
	add		$5, T1
	.endm

	// macros that further combined W_PRECALC_16_31_3 with RR1 to reduce pipeline stalls
	.macro	W_PRECALC_16_31_3_RR1	// W, i, K_XMM
	veor	W_TMP, W_TMP2
    eor 	T1, $3, $2
	add		T2, $5
    and 	T1, $1
	ror		$1, #2
	veor	W_TMP, $0
	orr		$5, T2, T2
	// ror		T2, #27
	vadd.s32	W_TMP2, W_TMP, K_VALUES
    eor 	T1, $3
	vorr	$0, W_TMP, W_TMP
	add		$4, T2, ror #27
	vst1.f32	{W_TMP2}, [lr,:128]!
	add		$4, T1
	.endm

	// a super macro that combines 4 macro proliferations to further reduce pipeline stalls
	// 	W_PRECALC_16_31_0_RR0_0	W0,W28,W24,W20,W16,A,B,C,D,E
	// 	W_PRECALC_16_31_1_RR1	W0,W16,A,B,C,D,E
	// 	W_PRECALC_16_31_2_RR0	W16,D,E,A,B,C,2 
	// 	W_PRECALC_16_31_3_RR1	W16,D,E,A,B,C

	.macro	SUPER_W_PRECALC_16_31_0		// W_16,W_12,W_8,W_4,W
	vext.64	$4, $0, $1, #1
	ldrd	T1, T2, WK(0)
	vext.32	W_TMP,$3,ZERO,#1
	eor 	r12, $7, $8
	veor	$4, $2						// W_8 ^ W_14	
	and		r12, $6
	veor	W_TMP, $0				// W_3 ^ W_16
	add		$9, T1
	ror		$6, #2
	eor		r12, $8
	add		$8, T2
	veor	$4, W_TMP				// W_3 ^ W_16 ^ W_8 ^ W_14
	add		$9, r12
    eor 	r12, $7, $6
	vext.32	W_TMP2,ZERO, $4, #1	
	add		$9, $9, $5, ror #27
	vshl.i32	W_TMP, $4, #1
    and 	r12, $5
	vshr.u32	$4, #31
    eor 	r12, $7
	vorr	W_TMP, $4
	ror		$5, #2
	vshl.i32	$4, W_TMP2, #2
	add		$8, r12
	vshr.u32	W_TMP2, #30
	add		$8, $9, ror #27
	ldrd	T1, T2, WK(2)
	eor 	r12, $5, $6
	veor	W_TMP, W_TMP2
	add		$7, T1
	and		r12, $9
	ror		$9, #2
	veor	W_TMP, $4
	eor		r12, $6
	add		$6, T2
	vadd.s32	W_TMP2, W_TMP, K_VALUES
	add		$7, r12
	vorr		$4, W_TMP, W_TMP
    eor 	r12, $5, $9
	add		$7, $7, $8, ror #27
    and 	r12, $8
	ror		$8, #2
    eor 	r12, $5
	add		$6, $7, ror #27
	vst1.f32	{W_TMP2}, [lr,:128]!
	add		$6, r12
	.endm

	// a super macro that combines 4 macro proliferations to further reduce pipeline stalls
	//	W_PRECALC_16_31_0_RR0_4	W28,W24,W20,W16,W12,B,C,D,E,A
	//	W_PRECALC_16_31_1_RR1	W28,W12,B,C,D,E,A
	//	W_PRECALC_16_31_2_RR0	W12,E,A,B,C,D,6
	//	W_PRECALC_16_31_3_RR1	W12,E,A,B,C,D
	.macro	SUPER_W_PRECALC_16_31_4		// W_16,W_12,W_8,W_4,W
	vext.64	$4, $0, $1, #1
	ldrd	T1, T2, WK(4)
	vext.32	W_TMP,$3,ZERO,#1
	eor 	r12, $7, $8
	veor	$4, $2						// W_8 ^ W_14	
	and		r12, $6
	veor	W_TMP, $0				// W_3 ^ W_16
	add		$9, T1
	ror		$6, #2
	eor		r12, $8
	add		$8, T2
	veor	$4, W_TMP				// W_3 ^ W_16 ^ W_8 ^ W_14
	add		$9, r12
    eor 	r12, $7, $6
	vext.32	W_TMP2,ZERO, $4, #1	
	add		$9, $9, $5, ror #27
	vshl.i32	W_TMP, $4, #1
    and 	r12, $5
	vshr.u32	$4, #31
    eor 	r12, $7
	vorr	W_TMP, $4
	ror		$5, #2
	vshl.i32	$4, W_TMP2, #2
	add		$8, r12
	vshr.u32	W_TMP2, #30
	add		$8, $9, ror #27
	ldrd	T1, T2, WK(6)
	eor 	r12, $5, $6
	veor	W_TMP, W_TMP2
	add		$7, T1
	and		r12, $9
	ror		$9, #2
	veor	W_TMP, $4
	eor		r12, $6
	add		$6, T2
	vadd.s32	W_TMP2, W_TMP, K_VALUES
	add		$7, r12
	vorr	$4, W_TMP, W_TMP
    eor 	r12, $5, $9
	add		$7, $7, $8, ror #27
    and 	r12, $8
	ror		$8, #2
    eor 	r12, $5
	add		$6, $7, ror #27
	vst1.f32	{W_TMP2}, [lr,:128]!
	add		$6, r12
	.endm

	// a super macro that combines 4 macro proliferations to further reduce pipeline stalls
	//	W_PRECALC_16_31_0_RR0_8	W24,W20,W16,W12,W8,C,D,E,A,B
	//	W_PRECALC_16_31_1_RR1	W24,W8,C,D,E,A,B
	//	W_PRECALC_16_31_2_RR0	W8,A,B,C,D,E,10
	//	W_PRECALC_16_31_3_RR1	W8,A,B,C,D,E
	.macro	SUPER_W_PRECALC_16_31_8		// W_16,W_12,W_8,W_4,W
	vext.64	$4, $0, $1, #1
	ldrd	T1, T2, WK(8)
	vext.32	W_TMP,$3,ZERO,#1
	eor 	r12, $7, $8
	veor	$4, $2						// W_8 ^ W_14	
	and		r12, $6
	veor	W_TMP, $0				// W_3 ^ W_16
	add		$9, T1
	ror		$6, #2
	eor		r12, $8
	add		$8, T2
	veor	$4, W_TMP				// W_3 ^ W_16 ^ W_8 ^ W_14
	add		$9, r12
	//ror		T2, $5, #27
    eor 	r12, $7, $6
	vext.32	W_TMP2,ZERO, $4, #1	
	add		$9, $9, $5, ror #27
	vshl.i32	W_TMP, $4, #1
    and 	r12, $5
	vshr.u32	$4, #31
    eor 	r12, $7
	vorr	W_TMP, $4
	ror		$5, #2
	vshl.i32	$4, W_TMP2, #2
	add		$8, r12
	vshr.u32	W_TMP2, #30
	add		$8, $9, ror #27
	ldrd	T1, T2, WK(10)
	eor 	r12, $5, $6
	veor	W_TMP, W_TMP2
	add		$7, T1
	and		r12, $9
	ror		$9, #2
	veor	W_TMP, $4
	eor		r12, $6
	add		$6, T2
	vadd.s32	W_TMP2, W_TMP, K_VALUES
	add		$7, r12
	vorr	$4, W_TMP, W_TMP
    eor 	r12, $5, $9
	add		$7, $7, $8, ror #27
    and 	r12, $8
	ror		$8, #2
    eor 	r12, $5
	add		$6, $7, ror #27
	vst1.f32	{W_TMP2}, [lr,:128]!
	add		$6, r12
	.endm

	// a super macro that combines 4 macro proliferations to further reduce pipeline stalls
	//	W_PRECALC_16_31_0_RR0_12	W20,W16,W12,W8,W4,D,E,A,B,C
	//	W_PRECALC_16_31_1_RR1	W20,W4,D,E,A,B,C
	//	W_PRECALC_16_31_2_RR0	W4,B,C,D,E,A,14
	//	W_PRECALC_16_31_3_RR1	W4,B,C,D,E,A
	.macro	SUPER_W_PRECALC_16_31_12		// W_16,W_12,W_8,W_4,W
	vext.64	$4, $0, $1, #1
	ldrd	T1, T2, WK(12)
	vext.32	W_TMP,$3,ZERO,#1
	eor 	r12, $7, $8
	veor	$4, $2						// W_8 ^ W_14	
	and		r12, $6
	veor	W_TMP, $0				// W_3 ^ W_16
	add		$9, T1
	ror		$6, #2
	eor		r12, $8
	add		$8, T2
	veor	$4, W_TMP				// W_3 ^ W_16 ^ W_8 ^ W_14
	add		$9, r12
	//ror		T2, $5, #27
    eor 	r12, $7, $6
	vext.32	W_TMP2,ZERO, $4, #1	
	add		$9, $9, $5, ror #27
	vshl.i32	W_TMP, $4, #1
    and 	r12, $5
	vshr.u32	$4, #31
    eor 	r12, $7
	vorr	W_TMP, $4
	ror		$5, #2
	vshl.i32	$4, W_TMP2, #2
	add		$8, r12
	vshr.u32	W_TMP2, #30
	add		$8, $9, ror #27
	ldrd	T1, T2, WK(14)
	eor 	r12, $5, $6
	veor	W_TMP, W_TMP2
	add		$7, T1
	and		r12, $9
	ror		$9, #2
	veor	W_TMP, $4
	eor		r12, $6
	add		$6, T2
	vadd.s32	W_TMP2, W_TMP, K_VALUES
	add		$7, r12
	vorr	$4, W_TMP, W_TMP
    eor 	r12, $5, $9
	add		$7, $7, $8, ror #27
    and 	r12, $8
	ror		$8, #2
    eor 	r12, $5
	add		$6, $7, ror #27
	vst1.f32	{W_TMP2}, [lr,:128]!
	add		$6, r12
	.endm

	// macros that combine W_PRECALC_32_79 with RR0/RR1 and F1/F2/F3 macros
	.macro	W_PRECALC_32_79_0_RR0_F1			// W_28,W_8,W_4,W
	ldr		r12, WK($9)
	eor 	T1, $6, $7
	ldr		T2, WK($9+1)
	veor		$3, $0
	and		T1, $5
	add		$8, r12
	ror		$5, #2
	eor		T1, $7
	add		$7, T2
	vext.64		W_TMP, $1, $2, #1
	add		$8, T1
	//ror		T2, $4, #27
	.endm

	.macro	W_PRECALC_32_79_0_RR0_F2	// W_28,W_8,W_4,W
	ldr		r12, WK($9)
	veor		$3, $0
	eor		T1, $5, $7
	ror		$5, #2
	add		$8, r12
	ldr		r12, WK($9+1)
	eor		T1, $6
	vext.64		W_TMP, $1, $2, #1
	add		$8, T1
	add		$7, r12
	.endm

	.macro	W_PRECALC_32_79_0_RR0_F3			// W_28,W_8,W_4,W
	ldr		r12, WK($9)
	veor		$3, $0
	orr		T1, $5, $6
	and		T2, $5, $6 
	add		$8, r12
	ldr		r12, WK($9+1)
	ror		$5, #2
	vext.64		W_TMP, $1, $2, #1
	and		T1, $7
	add		$7, r12
	orr		T1, T2
	add		$8, T1
	.endm

	.macro	W_PRECALC_32_79_1_RR1	// combined W_PRECALC_32_79_1 and RR1 to absorb some stalls
	veor	W_TMP, $0
	add		$7, $7, $3, ror #27
	veor	W_TMP, $1
	vshr.u32	$1, W_TMP, #30
	add		$6, $7, ror #27
	vshl.i32	W_TMP, #2
	$2		$3, $4, $5
	add		$6, T1
	ror		$3, #2
	.endm

	.macro	W_PRECALC_32_79_1_RR1_F1	// combined W_PRECALC_32_79_1 and RR1 to absorb some stalls
	veor	W_TMP, $0
	eor 	T1, $5, $4
	add		$7, $7, $3, ror #27
    and		T1, $3
	veor	W_TMP, $1
    eor		T1, $5
	vshr.u32	$1, W_TMP, #30
	add		$6, T1
	vshl.i32	W_TMP, #2
	add		$6, $7, ror #27
	ror		$3, #2
	.endm

	.macro	W_PRECALC_32_79_1_RR1_F2	// combined W_PRECALC_32_79_1 and RR1 to absorb some stalls
	veor	W_TMP, $0
	veor	W_TMP, $1
	eor 	T1, $3, $4
	add		$7, $7, $3, ror #27
    eor 	T1, $5
	ror		$3, #2
	add		$6, T1
	vshr.u32	$1, W_TMP, #30
	vshl.i32	W_TMP, #2
	add		$6, $7, ror #27
	.endm

	.macro	W_PRECALC_32_79_1_RR1_F3	// combined W_PRECALC_32_79_1 and RR1 to absorb some stalls
	veor	W_TMP, $0
	veor	W_TMP, $1
	add		$7, $7, $3, ror #27
	orr		T1, $3, $4
	and		r12, $4, $3
	and 	T1, $5
	add		$6, $7, ror #27
	orr		T1, r12
	vshr.u32	$1, W_TMP, #30
	vshl.i32	W_TMP, #2
	ror		$3, #2
	add		$6, T1
	.endm

	.macro	W_PRECALC_32_79_2_RR0_F1	// W
	ldr		r12, WK($6)
	eor 	T1, $3, $4
	ldr		T2, WK($6+1)
	and		T1, $2
	add		$5, r12
	ror		$2, #2
	eor		T1, $4
	add		$4, T2
	vorr		W_TMP, $0
	add		$5, T1
	.endm

	.macro	W_PRECALC_32_79_2_RR0_F2	// W
	ldr		r12, WK($6)
	eor		T1, $2, $4
	ror		$2, #2
	eor		T1, $3
	add		$5, r12
	ldr		r12, WK($6+1)
	vorr		W_TMP, $0
	add		$5, T1
	add		$4, r12
	.endm

	.macro	W_PRECALC_32_79_2_RR0_F3	// W
	ldr		r12, WK($6)
	orr		T1, $2, $3
	and		T2, $2, $3 
	ror		$2, #2
	add		$5, r12
	ldr		r12, WK($6+1)
	and		T1, $4
	vorr		W_TMP, $0
	orr		T1, T2
	add		$4, r12
	add		$5, T1
	.endm

	.macro	W_PRECALC_32_79_3_RR1_F1	// W, i, K_XMM
	vadd.s32	W_TMP2, W_TMP, K_VALUES
	add		$5, $5, $1, ror #27
    eor 	T1, $3, $2
	vorr	$0, W_TMP, W_TMP
    and 	T1, $1
	ror		$1, #2
	vst1.f32	{W_TMP2}, [lr,:128]!
	add		$4, $5, ror #27
    eor 	T1, $3
	add		$4, T1
	.endm

	.macro	W_PRECALC_32_79_3_RR1_F2	// W, i, K_XMM
	vadd.s32	W_TMP2, W_TMP, K_VALUES
	vorr	$0, W_TMP, W_TMP
	add		$5, $5, $1, ror #27
	eor		T1, $1, $2
	ror		$1, #2
	eor		T1, $3
	vst1.f32	{W_TMP2}, [lr,:128]!
	add		$4, T1
	add		$4, $5, ror #27
	.endm

	.macro	W_PRECALC_32_79_3_RR1_F3	// W, i, K_XMM
	vadd.s32	W_TMP2, W_TMP, K_VALUES
	vorr	$0, W_TMP, W_TMP
	orr		T1, $1, $2
	add		$5, $5, $1, ror #27
	and		T1, $3
	and		r12, $1, $2
	add		$4, $5, ror #27
	orr		T1, r12
	vst1.f32	{W_TMP2}, [lr,:128]!
	ror		$1, #2
	add		$4, T1
	.endm


	.macro	LOAD_HASH
	ldr			A, [HASH_PTR, #0]
	ldrd		B,C, [HASH_PTR, #4]
	ldrd		D,E, [HASH_PTR, #12]
	.endm



	// the main code body --- the final optimized version
#if OPTIMIZED

	// rounds 16-31 use the approach by Dean Gaudet
	.macro	INTERNAL
	// i=16
	// circular buffer : W12,W8,W4,W0,W28,W24,W20,W16
#if 1
	SUPER_W_PRECALC_16_31_0 W0,W28,W24,W20,W16,A,B,C,D,E
#else
	W_PRECALC_16_31_0_RR0_0	W0,W28,W24,W20,W16,A,B,C,D,E
	W_PRECALC_16_31_1_RR1	W0,W16,A,B,C,D,E
	W_PRECALC_16_31_2_RR0	W16,D,E,A,B,C,2 
	W_PRECALC_16_31_3_RR1	W16,D,E,A,B,C
#endif

	vld1.s32	{K_VALUES}, [K_BASE,:128]!

	// i=20,
	// W8,W4,W0,W28,W24,W20,W16,W12
#if 1
	SUPER_W_PRECALC_16_31_4	W28,W24,W20,W16,W12,B,C,D,E,A
#else
	W_PRECALC_16_31_0_RR0_4	W28,W24,W20,W16,W12,B,C,D,E,A
	W_PRECALC_16_31_1_RR1	W28,W12,B,C,D,E,A
	W_PRECALC_16_31_2_RR0	W12,E,A,B,C,D,6
	W_PRECALC_16_31_3_RR1	W12,E,A,B,C,D
#endif

	// i=24,
	// W4,W0,W28,W24,W20,W16,W12,W8
#if 1
	SUPER_W_PRECALC_16_31_8	W24,W20,W16,W12,W8,C,D,E,A,B
#else
	W_PRECALC_16_31_0_RR0_8	W24,W20,W16,W12,W8,C,D,E,A,B
	W_PRECALC_16_31_1_RR1	W24,W8,C,D,E,A,B
	W_PRECALC_16_31_2_RR0	W8,A,B,C,D,E,10
	W_PRECALC_16_31_3_RR1	W8,A,B,C,D,E
#endif

	// i=28
	// W0,W28,W24,W20,W16,W12,W8,W4
#if 1
	SUPER_W_PRECALC_16_31_12	W20,W16,W12,W8,W4,D,E,A,B,C
#else
	W_PRECALC_16_31_0_RR0_12	W20,W16,W12,W8,W4,D,E,A,B,C
	W_PRECALC_16_31_1_RR1	W20,W4,D,E,A,B,C
	W_PRECALC_16_31_2_RR0	W4,B,C,D,E,A,14
	W_PRECALC_16_31_3_RR1	W4,B,C,D,E,A
#endif

	sub		lr, #0x40

	//i=32
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0_RR0_F1	W28,W8,W4,W0,E,A,B,C,D,16
	W_PRECALC_32_79_1_RR1_F1	W16,W0,F1,E,A,B,C,D,16
	W_PRECALC_32_79_2_RR0_F1	W0,C,D,E,A,B,18
	W_PRECALC_32_79_3_RR1_F1	W0,C,D,E,A,B

	//i=36
	// W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_32_79_0_RR0_F2	W24,W4,W0,W28,A,B,C,D,E,20
	W_PRECALC_32_79_1_RR1_F2	W12,W28,F2,A,B,C,D,E,20
	W_PRECALC_32_79_2_RR0_F2	W28,D,E,A,B,C,22
	W_PRECALC_32_79_3_RR1_F2	W28,D,E,A,B,C

	vld1.s32    {K_VALUES}, [K_BASE,:128]!

	//i=40
	// W20,W16,W12,W8,W4,W0,W28,W24	
	W_PRECALC_32_79_0_RR0_F2	W20,W0,W28,W24,B,C,D,E,A,24
	W_PRECALC_32_79_1_RR1_F2	W8,W24,F2,B,C,D,E,A,24
	W_PRECALC_32_79_2_RR0_F2	W24,E,A,B,C,D,26
	W_PRECALC_32_79_3_RR1_F2	W24,E,A,B,C,D

	//i=44
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0_RR0_F2	W16,W28,W24,W20,C,D,E,A,B,28
	W_PRECALC_32_79_1_RR1_F2	W4,W20,F2,C,D,E,A,B,28
	W_PRECALC_32_79_2_RR0_F2	W20,A,B,C,D,E,30
	W_PRECALC_32_79_3_RR1_F2	W20,A,B,C,D,E

	sub		lr, #0x40

	//i=48
	// W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_32_79_0_RR0_F2	W12,W24,W20,W16,D,E,A,B,C,32
	W_PRECALC_32_79_1_RR1_F2	W0,W16,F2,D,E,A,B,C,32
	W_PRECALC_32_79_2_RR0_F2	W16,B,C,D,E,A,34
	W_PRECALC_32_79_3_RR1_F2	W16,B,C,D,E,A

	//i=52
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_32_79_0_RR0_F2	W8,W20,W16,W12,E,A,B,C,D,36
	W_PRECALC_32_79_1_RR1_F2	W28,W12,F2,E,A,B,C,D,36
	W_PRECALC_32_79_2_RR0_F2	W12,C,D,E,A,B,38
	W_PRECALC_32_79_3_RR1_F2	W12,C,D,E,A,B

	//i=56
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_32_79_0_RR0_F3	W4,W16,W12,W8,A,B,C,D,E,40
	W_PRECALC_32_79_1_RR1_F3	W24,W8,F3,A,B,C,D,E,40
	W_PRECALC_32_79_2_RR0_F3	W8,D,E,A,B,C,42
	W_PRECALC_32_79_3_RR1_F3	W8,D,E,A,B,C

	vld1.s32    {K_VALUES}, [K_BASE,:128]!

	//i=60
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_32_79_0_RR0_F3	W0,W12,W8,W4,B,C,D,E,A,44
	W_PRECALC_32_79_1_RR1_F3	W20,W4,F3,B,C,D,E,A,44
	W_PRECALC_32_79_2_RR0_F3	W4,E,A,B,C,D,46
	W_PRECALC_32_79_3_RR1_F3	W4,E,A,B,C,D

	sub		lr, #0x40

	//i=64
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0_RR0_F3	W28,W8,W4,W0,C,D,E,A,B,48
	W_PRECALC_32_79_1_RR1_F3	W16,W0,F3,C,D,E,A,B,48
	W_PRECALC_32_79_2_RR0_F3	W0,A,B,C,D,E,50
	W_PRECALC_32_79_3_RR1_F3	W0,A,B,C,D,E

	//i=68
	// W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_32_79_0_RR0_F3	W24,W4,W0,W28,D,E,A,B,C,52
	W_PRECALC_32_79_1_RR1_F3	W12,W28,F3,D,E,A,B,C,52
	W_PRECALC_32_79_2_RR0_F3	W28,B,C,D,E,A,54
	W_PRECALC_32_79_3_RR1_F3	W28,B,C,D,E,A

	//i=72
	// W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_32_79_0_RR0_F3	W20,W0,W28,W24,E,A,B,C,D,56
	W_PRECALC_32_79_1_RR1_F3	W8,W24,F3,E,A,B,C,D,56
	W_PRECALC_32_79_2_RR0_F3	W24,C,D,E,A,B,58
	W_PRECALC_32_79_3_RR1_F3	W24,C,D,E,A,B

	// starting using F4	

	//i=76
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0_RR0_F2	W16,W28,W24,W20,A,B,C,D,E,60
	W_PRECALC_32_79_1_RR1_F2	W4,W20,F4,A,B,C,D,E,60
	W_PRECALC_32_79_2_RR0_F2	W20,D,E,A,B,C,62
	W_PRECALC_32_79_3_RR1_F2	W20,D,E,A,B,C

	sub		K_BASE, #64
	sub		lr, #0x40
	.endm

#endif		// OPTIMIZED

	.macro	SOFTWARE_PIPELINING

	vld1.s32    {K_VALUES}, [K_BASE,:128]!

#if !OPTIMIZED
	// i=0
	// circular buffer : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	RR0_F2				F4,B,C,D,E,A,64
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W[0] = W_TMP	
	RR1_F2				F4,B,C,D,E,A,64
	W_PRECALC_00_15_2	W0					// W_TMP = W[0] + K[0]
	RR0_F2				F4,E,A,B,C,D,66
	W_PRECALC_00_15_3						// (sp) = W_TMP = W[0] + K[0]
	RR1_F2				F4,E,A,B,C,D,66

	// i=4
	// circular buffer : W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	RR0_F2				F4,C,D,E,A,B,68
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W[0] = W_TMP	
	RR1_F2				F4,C,D,E,A,B,68
	W_PRECALC_00_15_2	W28					// W_TMP = W[0] + K[0]
	RR0_F2				F4,A,B,C,D,E,70
	W_PRECALC_00_15_3						// 16(sp) = W_TMP = W[0] + K[0]
	RR1_F2				F4,A,B,C,D,E,70

	// i=8
	// circular buffer : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	RR0_F2				F4,D,E,A,B,C,72
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W[0] = W_TMP
	RR1_F2				F4,D,E,A,B,C,72
	W_PRECALC_00_15_2	W24					// W_TMP = W[0] + K[0]
	RR0_F2				F4,B,C,D,E,A,74
	W_PRECALC_00_15_3						// 32(sp) = W_TMP = W[0] + K[0]
	RR1_F2				F4,B,C,D,E,A,74

	// i=12
	// circular buffer : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	RR0_F2				F4,E,A,B,C,D,76
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W[0] = W_TMP	
	RR1_F2				F4,E,A,B,C,D,76
	W_PRECALC_00_15_2	W20					// W_TMP = W[0] + K[0]
	RR0_F2				F4,C,D,E,A,B,78
	W_PRECALC_00_15_3						// 48(sp) = W_TMP = W[0] + K[0]
	RR1_F2				F4,C,D,E,A,B,78
#else
	// i=0
	// circular buffer : W28,W24,W20,W16,W12,W8,W4,W0

	RR0_F2				F4,B,C,D,E,A,64
	vld1.f32 {W_TMP,W_TMP2},[BUFFER_PTR]!
	RR1_F2				F4,B,C,D,E,A,64
	vld1.f32 {W4,W8},[BUFFER_PTR]!
	RR0_F2				F4,E,A,B,C,D,66
	vrev32.8 W0, W_TMP
	RR1_F2				F4,E,A,B,C,D,66

	// i=4
	// circular buffer : W24,W20,W16,W12,W8,W4,W0,W28
	RR0_F2				F4,C,D,E,A,B,68
	vrev32.8 W28, W_TMP2
	RR1_F2				F4,C,D,E,A,B,68
	vrev32.8 W24, W4
	RR0_F2				F4,A,B,C,D,E,70
	vrev32.8 W20, W8
	RR1_F2				F4,A,B,C,D,E,70

	// i=8
	// circular buffer : W20,W16,W12,W8,W4,W0,W28,W24
	RR0_F2				F4,D,E,A,B,C,72
	vadd.s32	W_TMP, W0, K_VALUES
	RR1_F2				F4,D,E,A,B,C,72
	vadd.s32	W_TMP2, W28, K_VALUES
	RR0_F2				F4,B,C,D,E,A,74
	vadd.s32	W4, W24, K_VALUES
	RR1_F2				F4,B,C,D,E,A,74

	// i=12
	// circular buffer : W16,W12,W8,W4,W0,W28,W24,W20
	RR0_F2				F4,E,A,B,C,D,76
	vadd.s32	W8, W20, K_VALUES
	RR1_F2				F4,E,A,B,C,D,76
	vst1.s32	{W_TMP,W_TMP2}, [lr,:128]!	// save W[i]+K(i) in stack memory
	RR0_F2				F4,C,D,E,A,B,78
	vst1.s32	{W4,W8}, [lr,:128]!	// save W[i]+K(i) in stack memory
	RR1_F2				F4,C,D,E,A,B,78
#endif

	sub		lr, #0x40
	.endm

	.macro	ENDING
	//i=80
	RR0_F2				F4,B,C,D,E,A,64
	RR1_F2				F4,B,C,D,E,A,64
	RR0_F2				F4,E,A,B,C,D,66
	RR1_F2				F4,E,A,B,C,D,66

	//i=84
	RR0_F2				F4,C,D,E,A,B,68
	RR1_F2				F4,C,D,E,A,B,68
	RR0_F2				F4,A,B,C,D,E,70
	RR1_F2				F4,A,B,C,D,E,70

	//i=88
	RR0_F2				F4,D,E,A,B,C,72
	RR1_F2				F4,D,E,A,B,C,72
	RR0_F2				F4,B,C,D,E,A,74
	RR1_F2				F4,B,C,D,E,A,74

	//i=92
	RR0_F2				F4,E,A,B,C,D,76
	RR1_F2				F4,E,A,B,C,D,76
	RR0_F2				F4,C,D,E,A,B,78
	RR1_F2				F4,C,D,E,A,B,78
	.endm

	.macro UPDATE_ALL_HASH	
	ldrd				T1, T2, [HASH_PTR,#0]
	add					A, T1
	add					B, T2
	str					A, [HASH_PTR,#0]
	ldrd				T1, T2, [HASH_PTR,#8]
	add					C, T1
	add					D, T2
	strd				B, C, [HASH_PTR,#4]
	ldr					T1, [HASH_PTR,#16]
	add					E, T1
	strd				D, E, [HASH_PTR,#12]
	.endm

	.macro  SHA1_PIPELINED_MAIN_BODY
	LOAD_HASH						// load initial hashes into A,B,C,D,E
	orr		lr, sp, sp
	INITIAL_W_PRECALC
	sub		lr, #0x40
0:
	INTERNAL
#if Multiple_Blocks
	subs num_blocks, #1					// pre-decrement num_blocks by 1
	ble	1f							// if num_blocks <= 0, branch to finish off
	SOFTWARE_PIPELINING
	UPDATE_ALL_HASH
	b	0b
1:
#endif
	ENDING
	UPDATE_ALL_HASH
	.endm

	.text

	.p2align	4

#define K1 0x5a827999
#define K2 0x6ed9eba1
#define K3 0x8f1bbcdc
#define K4 0xca62c1d6

K_XMM_AR:
    .long	K1
	.long	K1
	.long	K1
	.long	K1
    .long	K2
	.long	K2
	.long	K2
	.long	K2
    .long	K3
	.long	K3
	.long	K3
	.long	K3
    .long	K4
	.long	K4
	.long	K4
	.long	K4


	.globl _sha1_vng_armv7neon_compress
	.private_extern _sha1_vng_armv7neon_compress	
_sha1_vng_armv7neon_compress:

	// due to the change of order in the 2nd and 3rd calling argument, 
	// we need to switch r1/r2 to use the original code 
	// cclee 1-13-11
	mov		r12, r1
	mov		r1, r2
	mov		r2, r12

	push	{r4-r7,lr}
	nop
	add		r7, sp, #12		// set up base pointer for debug tracing
	push	{r8-r11}

	// align sp to 16-byte boundary
	ands	r12, sp, #15	// number of bytes to align to 16-byte boundary
	addeq	r12, #16		// in case it's already 16-byte aligned and hence no where to store num_aligned_bytes
	sub		sp, r12
	str		r12, [sp]

#if	KERNEL
	vpush	{q8-q15}
#endif
	vpush	{q4-q7}
#define	stack_size (16*4)		// circular buffer W0-W3
	sub		sp, #stack_size

	veor	ZERO, ZERO

	orr		HASH_PTR, ctx, ctx
	orr		BUFFER_PTR, buf, buf
	adr		K_BASE, K_XMM_AR

	SHA1_PIPELINED_MAIN_BODY

	
	add		sp, #stack_size
	vpop	{q4-q5}
	vpop	{q6-q7}
#if	KERNEL
	vpop	{q8-q9}
	vpop	{q10-q11}
	vpop	{q12-q13}
	vpop	{q14-q15}
#endif

	// restore sp to its original alignment
	ldr		r12, [sp]
	add		sp, r12

	pop		{r8-r11}
	pop		{r4-r7,pc}

#endif	/* _ARM_ARCH_7 */

Added Source/descriptors/digestDescriptors/vng_neon_sha2_descriptor/vng_armv7neon_sha256_compress.s.













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
/*
	This file provides armv7+neon hand implementation of the following function

	void SHA256_Transform(SHA256_ctx *ctx, char *data, unsigned int num_blocks);

	which is a C function in sha2.c (from xnu).

	sha256 algorithm per block description:

		1. W(0:15) = big-endian (per 4 bytes) loading of input data (64 byte) 
		2. load 8 digests a-h from ctx->state
		3. for r = 0:15
				T1 = h + Sigma1(e) + Ch(e,f,g) + K[r] + W[r];
				d += T1;
				h = T1 + Sigma0(a) + Maj(a,b,c)
				permute a,b,c,d,e,f,g,h into h,a,b,c,d,e,f,g
		4. for r = 16:63
				W[r] = W[r-16] + sigma1(W[r-2]) + W[r-7] + sigma0(W[r-15]);
				T1 = h + Sigma1(e) + Ch(e,f,g) + K[r] + W[r];
				d += T1;
				h = T1 + Sigma0(a) + Maj(a,b,c)
				permute a,b,c,d,e,f,g,h into h,a,b,c,d,e,f,g
				
	In the assembly implementation:	
		- a circular window of message schedule W(r:r+15) is updated and stored in q0-q3
		- its corresponding W+K(r:r+15) is updated and stored in a stack space circular buffer
		- the 8 digests (a-h) will be stored in GPR or memory

	the implementation per block looks like

	----------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into q0:q3
	pre_calculate and store W+K(0:15) in stack

	load digests a-h from ctx->state;

	for (r=0;r<48;r+=4) {
		digests a-h update and permute round r:r+3
		update W([r:r+3]%16) and WK([r:r+3]%16) for the next 4th iteration 
	}

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
	}

	ctx->states += digests a-h;

	----------------------------------------------------------------------------

	our implementation (allows multiple blocks per call) pipelines the loading of W/WK of a future block 
	into the last 16 rounds of its previous block:

	----------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into q0:q3 
	pre_calculate and store W+K(0:15) in stack

L_loop:

	load digests a-h from ctx->state;

	for (r=0;r<48;r+=4) {
		digests a-h update and permute round r:r+3
		update W([r:r+3]%16) and WK([r:r+3]%16) for the next 4th iteration 
	}

	num_block--;
	if (num_block==0)	jmp L_last_block;

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
		load W([r:r+3]%16) (big-endian per 4 bytes) into q0:q3 
		pre_calculate and store W+K([r:r+3]%16) in stack
	}

	ctx->states += digests a-h;

	jmp	L_loop;

L_last_block:

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
	}

	ctx->states += digests a-h;

	------------------------------------------------------------------------

	Apple CoreOS vector & numerics
	cclee 10-12-10
*/

#include <arm/arch.h>

#if defined(_ARM_ARCH_7)

	// associate variables with registers or memory

	#define	ctx			r0
	#define data		r1
	#define	num_blocks	[sp, #64]

	#define	a			r2
	#define	b			r3
	#define	c			r4
	#define	d			r5
	#define	e			r8
	#define	f			r9
	#define	g			r10
	#define	h			r11

	#define	K			r6

	// 2 local variables
	#define	t	r12
	#define	s	lr

	// a window (16 words) of message scheule
	#define	W0	q0
	#define	W1	q1
	#define	W2	q2
	#define	W3	q3
	#define	zero	q8

	// circular buffer for WK[(r:r+15)%16]
	#define WK(r)   [sp,#(r&15)*4]

// #define Ch(x,y,z)   (((x) & (y)) ^ ((~(x)) & (z)))

	.macro Ch
	mvn		t, $0		// ~x
	and		s, $0, $1	// (x) & (y)
	and		t, t, $2	// (~(x)) & (z)
	eor		t, t, s		// t = Ch(x,y,z) = (((x) & (y)) ^ ((~(x)) & (z)))
	.endm

// #define Maj(x,y,z)  (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

	.macro	Maj
	eor		t, $1, $2		// y^z
	and		s, $1, $2		// y&z
	and		t, t, $0		// x&(y^z)
	eor		t, t, s			// t = Maj(x,y,z) = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) 
	.endm

// #define sigma0_256(x)   (S32(7,  (x)) ^ S32(18, (x)) ^ R(3 ,   (x)))

	// performs sigma0_256 on 4 words on a Q register
	// use q6/q7 as intermediate registers
	.macro	sigma0
	vshr.u32	q6, $0, #7
	vshl.i32	q7, $0, #14
	vshr.u32	$0, $0, #3
	veor		$0, q6
	veor		$0, q7
	vshr.u32	q6, #11
	vshl.i32	q7, #11
	veor		$0, q6
	veor		$0, q7
	.endm

// #define sigma1_256(x)   (S32(17, (x)) ^ S32(19, (x)) ^ R(10,   (x)))

	// performs sigma1_256 on 4 words on a Q register
	// use q6/q7 as intermediate registers
	.macro	sigma1
	vshr.u32	q6, $0, #17
	vshl.i32	q7, $0, #13
	vshr.u32	$0, $0, #10
	veor		$0, q6
	veor		$0, q7
	vshr.u32	q6, #2
	vshl.i32	q7, #2
	veor		$0, q6
	veor		$0, q7
	.endm

// #define Sigma0_256(x)   (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))

	.macro	Sigma0
	ror		t, $0, #2		// S32(2,  (x))
	ror		s, $0, #13		// S32(13,  (x))
	eor		t, t, s			// S32(2,  (x)) ^ S32(13, (x))
	ror		s, s, #9		// S32(22,  (x))
	eor		t, t, s			// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))
	.endm

// #define Sigma1_256(x)   (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))

	.macro	Sigma1
	ror		t, $0, #6		// S32(6,  (x))
	ror		s, $0, #11		// S32(11, (x))
	eor		t, t, s			// S32(6,  (x)) ^ S32(11, (x))
	ror		s, s, #14		// S32(25, (x))	
	eor		t, t, s			// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	.endm

	// per round digests update
	.macro	round
	// ror		t, $4, #6			// S32(6,  (x))
	eor		t, t, $4, ror #11	// S32(6,  (x)) ^ S32(11, (x))
	eor		t, t, $4, ror #25	// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	and		s, $4, $5			// (x) & (y)
	add		$7, t				// use h to store h+Sigma1(e)
	bic		t, $6, $4			// (~(x)) & (z)
	eor		t, t, s				// t = Ch(x,y,z) = (((x) & (y)) ^ ((~(x)) & (z)))
	ldr		s, WK($8)			//
	add		$7, t				// t = h+Sigma1(e)+Ch(e,f,g);
	ror		t, $0, #2			// S32(2,  (x))
	add		$7, s				// h = T1
	eor		t, t, $0, ror #13	// S32(2,  (x)) ^ S32(13, (x))
	add		$3, $7				// d += T1;
	eor		t, t, $0, ror #22	// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))				// t = Sigma0(a);
	add		$7, t				// h = T1 + Sigma0(a);
	eor		t, $1, $2			// y^z
	and		s, $1, $2			// y&z
	and		t, t, $0			// x&(y^z)
	eor		s, s, t				// t = Maj(x,y,z) = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
	// add		$7, s				// h = T1 + Sigma0(a) + Maj(a,b,c);			
	.endm

	// per 4 rounds digests update and permutation
	// permutation is absorbed by rotating the roles of digests a-h
	.macro	rounds
	ror		t, $4, #6
	round	$0, $1, $2, $3, $4, $5, $6, $7, 0+$8
	ror		t, $3, #6
	add		$7, s
	round	$7, $0, $1, $2, $3, $4, $5, $6, 1+$8
	ror		t, $2, #6
	add		$6, s
	round	$6, $7, $0, $1, $2, $3, $4, $5, 2+$8
	ror		t, $1, #6
	add		$5, s
	round	$5, $6, $7, $0, $1, $2, $3, $4, 3+$8
	add		$4, s
	.endm

	.macro	rounds_a
	ror		t, e, #6
	round	a, b, c, d, e, f, g, h, 0+$0
	ror		t, d, #6
	add		h, s
	round	h, a, b, c, d, e, f, g, 1+$0
	ror		t, c, #6
	add		g, s
	round	g, h, a, b, c, d, e, f, 2+$0
	ror		t, b, #6
	add		f, s
	round	f, g, h, a, b, c, d, e, 3+$0
	add		e, s
	.endm

	.macro	rounds_e
	ror		t, a, #6
	round	e, f, g, h, a, b, c, d, 0+$0
	ror		t, h, #6
	add		d, s
	round	d, e, f, g, h, a, b, c, 1+$0
	ror		t, g, #6
	add		c, s
	round	c, d, e, f, g, h, a, b, 2+$0
	ror		t, f, #6
	add		b, s
	round	b, c, d, e, f, g, h, a, 3+$0
	add		a, s
	.endm

	// update the message schedule W and W+K (4 rounds) 16 rounds ahead in the future 
	.macro	message_schedule
	vld1.32	{q5},[K,:128]!
	vext.32 q4, $0, $1, #1			// Q4 = w4:w1
	sigma0	q4						// sigma0(w4:w1)
	vadd.s32	$0, q4				// w3:w0 + sigma0(w4:w1)
	vext.32	q6, $2, $3, #1			// Q6 = w12:w9
	vadd.s32	$0, q6				// w3:w0 + sigma0(w4:w1) + w12:w9
	vext.64	q4, $3, zero, #1		// 0 0 w15:w14
	sigma1	q4						// Q4 = sigma1(0 0 w15:w14)
	vadd.s32	$0, q4				// w3:w0 + sigma0(w4:w1) + w12:w9 + sigma1(0 0 w15:w14)
	vext.64	q4, zero, $0, #1		// Q4 = (w17:w16 0 0)
	sigma1	q4						// sigma1(w17:w16 0 0)
	vadd.s32	$0, q4				// w19:w16 = w3:w0 + sigma0(w4:w1) + w12:w9 + sigma1(w17:w14)
	add		t, sp, #(($4&15)*4)
	vadd.s32	q5, $0				// W+K
	vst1.32		{q5},[t,:128]
	.endm

	// this macro is used in the last 16 rounds of a current block
	// it reads the next message (16 4-byte words), load it into 4 words W[r:r+3], computes WK[r:r+3]
	// and save into stack to prepare for next block

	.macro	update_W_WK
	vld1.s32	{$1},[data]!
	vrev32.8	$1, $1
	add		t, sp, #($0*16)
	vld1.s32	{q4},[K,:128]!
	vadd.s32	q4, $1
	vst1.32		{q4},[t]
	.endm

	.macro	Update_Digits
	ldr		t, [ctx]
	ldr		s, [ctx,#4]
	add		a, t
	add		b, s
	strd	a, b, [ctx]

	ldr		t, [ctx,#8]
	ldr		s, [ctx,#12]
	add		c, t
	add		d, s
	strd	c, d, [ctx, #8]

	ldr		t, [ctx,#16]
	ldr		s, [ctx,#20]
	add		e, t
	add		f, s
	strd	e, f, [ctx, #16]

	ldr		t, [ctx,#24]
	ldr		s, [ctx,#28]
	add		g, t
	add		h, s
	strd	g, h, [ctx, #24]
	.endm

	.macro	rounds_a_schedule_update
	eor		t, e, e, ror #5	// S32(6,  (x)) ^ S32(11, (x))
	vld1.32	{q5},[K,:128]!
	eor		t, t, e, ror #19	// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	vext.32 q4, $1, $2, #1			// Q4 = w4:w1
	and		s, e, f				// (x) & (y)
	add		h, t, ror #6				// use h to store h+Sigma1(e)
	bic		t, g, e				// (~(x)) & (z)
	vshr.u32	q6, q4, #7
	eor		t, t, s				// t = Ch(x,y,z) = (((x) & (y)) ^ ((~(x)) & (z)))
	vshl.i32	q7, q4, #14
	ldr		s, WK($0)			//
	add		h, t				// t = h+Sigma1(e)+Ch(e,f,g);
	eor		t, a, a, ror #11	// S32(2,  (x)) ^ S32(13, (x))
	add		h, s				// h = T1
	eor		t, t, a, ror #20	// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))				// t = Sigma0(a);
	add		d, h				// d += T1;
	vshr.u32	q4, q4, #3
	add		h, t, ror #2				// h = T1 + Sigma0(a);
	eor		t, b, c			// y^z
	and		s, b, c			// y&z
	veor		q4, q6
	vshr.u32	q6, #11
	and		t, t, a			// x&(y^z)
	eor		s, s, t				// t = Maj(x,y,z) = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
	eor		t, d, d, ror #5	// S32(6,  (x)) ^ S32(11, (x))
	veor		q4, q7
	vshl.i32	q7, #11


	add		h, s
	eor		t, t, d, ror #19	// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	and		s, d, e				// (x) & (y)
	add		g, t, ror #6				// use h to store h+Sigma1(e)

	bic		t, f, d				// (~(x)) & (z)
	veor		q4, q6
	veor		q4, q7
	vext.32	q6, $3, $4, #1			// Q6 = w12:w9
	vadd.s32	$1, q4				// w3:w0 + sigma0(w4:w1)
	eor		t, t, s				// t = Ch(x,y,z) = (((x) & (y)) ^ ((~(x)) & (z)))
	ldr		s, WK(1+$0)			//
	add		g, t				// t = h+Sigma1(e)+Ch(e,f,g);
	eor		t, h, h, ror #11	// S32(2,  (x)) ^ S32(13, (x))
	add		g, s				// h = T1
	eor		t, t, h, ror #20	// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))				// t = Sigma0(a);
	vadd.s32	$1, q6				// w3:w0 + sigma0(w4:w1) + w12:w9
	vext.64	q4, $4, zero, #1		// 0 0 w15:w14
	add		c, g				// d += T1;
	add		g, t, ror #2			// h = T1 + Sigma0(a);
	eor		t, a, b				// y^z
	and		s, a, b				// y&z
	and		t, t, h				// x&(y^z)
	vshr.u32	q6, q4, #17
	vshl.i32	q7, q4, #13
	vshr.u32	q4, q4, #10
	eor		s, s, t				// t = Maj(x,y,z) = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))


	veor		q4, q6
	veor		q4, q7
	vshr.u32	q6, #2
	vshl.i32	q7, #2
	veor		q4, q6
	veor		q4, q7

	eor		t, c, c, ror #5	// S32(6,  (x)) ^ S32(11, (x))
	add		g, s
	eor		t, t, c, ror #19	// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	vadd.s32	$1, q4				// w3:w0 + sigma0(w4:w1) + w12:w9 + sigma1(0 0 w15:w14)
	and		s, c, d				// (x) & (y)
	add		f, t, ror #6				// use h to store h+Sigma1(e)
	bic		t, e, c				// (~(x)) & (z)
	vext.64	q4, zero, $1, #1		// Q4 = (w17:w16 0 0)
	eor		t, t, s				// t = Ch(x,y,z) = (((x) & (y)) ^ ((~(x)) & (z)))
	ldr		s, WK(2+$0)			//
	add		f, t				// t = h+Sigma1(e)+Ch(e,f,g);
	vshr.u32	q6, q4, #17
	vshl.i32	q7, q4, #13
	vshr.u32	q4, q4, #10
	eor		t, g, g, ror #11	// S32(2,  (x)) ^ S32(13, (x))
	add		f, s				// h = T1
	eor		t, t, g, ror #20	// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))				// t = Sigma0(a);
	add		b, f				// d += T1;
	veor		q4, q6
	veor		q4, q7
	add		f, t, ror #2			// h = T1 + Sigma0(a);
	eor		t, h, a				// y^z
	and		s, h, a				// y&z
	and		t, t, g				// x&(y^z)
	vshr.u32	q6, #2
	vshl.i32	q7, #2
	eor		s, s, t				// t = Maj(x,y,z) = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

	eor		t, b, b, ror #5	// S32(6,  (x)) ^ S32(11, (x))
	add		f, s
	eor		t, t, b, ror #19	// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	veor		q4, q6
	veor		q4, q7

	vadd.s32	$1, q4				// w19:w16 = w3:w0 + sigma0(w4:w1) + w12:w9 + sigma1(w17:w14)

	and		s, b, c				// (x) & (y)
	add		e, t, ror #6				// use h to store h+Sigma1(e)
	bic		t, d, b				// (~(x)) & (z)
	vadd.s32	q5, $1				// W+K
	eor		t, t, s				// t = Ch(x,y,z) = (((x) & (y)) ^ ((~(x)) & (z)))
	ldr		s, WK(3+$0)			//
	add		e, t				// t = h+Sigma1(e)+Ch(e,f,g);
	eor		t, f, f, ror #11	// S32(2,  (x)) ^ S32(13, (x))
	add		e, s				// h = T1
	eor		t, t, f, ror #20	// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))				// t = Sigma0(a);
	add		a, e				// d += T1;
	add		e, t, ror #2				// h = T1 + Sigma0(a);
	eor		t, g, h				// y^z
	and		s, g, h				// y&z
	and		t, t, f				// x&(y^z)
	eor		s, s, t				// t = Maj(x,y,z) = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

	add		t, sp, #(($0&15)*4)
	add		e, s
	vst1.32		{q5},[t,:128]

	.endm

	.macro	rounds_e_schedule_update
	eor		t, a, a, ror #5			// S32(6,  (x)) ^ S32(11, (x))
	vld1.32	{q5},[K,:128]!
	eor		t, t, a, ror #19	// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	vext.32 q4, $1, $2, #1			// Q4 = w4:w1
	and		s, a, b				// (x) & (y)
	add		d, t, ror #6				// use h to store h+Sigma1(e)
	bic		t, c, a				// (~(x)) & (z)
	vshr.u32	q6, q4, #7
	eor		t, t, s				// t = Ch(x,y,z) = (((x) & (y)) ^ ((~(x)) & (z)))
	vshl.i32	q7, q4, #14
	ldr		s, WK($0)			//
	add		d, t				// t = h+Sigma1(e)+Ch(e,f,g);
	eor		t, e, e, ror #11	// S32(2,  (x)) ^ S32(13, (x))
	add		d, s				// h = T1
	eor		t, t, e, ror #20	// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))				// t = Sigma0(a);
	add		h, d				// d += T1;
	vshr.u32	q4, q4, #3
	add		d, t, ror #2				// h = T1 + Sigma0(a);
	eor		t, f, g				// y^z
	and		s, f, g				// y&z
	veor		q4, q6
	vshr.u32	q6, #11
	and		t, t, e				// x&(y^z)
	eor		s, s, t				// t = Maj(x,y,z) = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
	eor		t, h, h, ror #5	// S32(6,  (x)) ^ S32(11, (x))
	veor		q4, q7
	vshl.i32	q7, #11


	add		d, s
	eor		t, t, h, ror #19	// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	and		s, h, a				// (x) & (y)
	add		c, t, ror #6			// use h to store h+Sigma1(e)
	bic		t, b, h				// (~(x)) & (z)

	veor		q4, q6
	veor		q4, q7
	vext.32	q6, $3, $4, #1			// Q6 = w12:w9
	vadd.s32	$1, q4				// w3:w0 + sigma0(w4:w1)
	eor		t, t, s				// t = Ch(x,y,z) = (((x) & (y)) ^ ((~(x)) & (z)))
	ldr		s, WK(1+$0)			//
	add		c, t				// t = h+Sigma1(e)+Ch(e,f,g);
	eor		t, d, d, ror #11	// S32(2,  (x)) ^ S32(13, (x))
	add		c, s				// h = T1
	eor		t, t, d, ror #20	// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))				// t = Sigma0(a);
	vadd.s32	$1, q6				// w3:w0 + sigma0(w4:w1) + w12:w9
	vext.64	q4, $4, zero, #1		// 0 0 w15:w14
	add		g, c				// d += T1;
	add		c, t, ror #2			// h = T1 + Sigma0(a);
	eor		t, e, f				// y^z
	and		s, e, f				// y&z
	and		t, t, d				// x&(y^z)
	vshr.u32	q6, q4, #17
	vshl.i32	q7, q4, #13
	vshr.u32	q4, q4, #10
	eor		s, s, t				// t = Maj(x,y,z) = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

	veor		q4, q6
	veor		q4, q7
	vshr.u32	q6, #2
	vshl.i32	q7, #2
	veor		q4, q6
	veor		q4, q7

	eor		t, g, g, ror #5		// S32(6,  (x)) ^ S32(11, (x))
	add		c, s
	eor		t, t, g, ror #19	// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	vadd.s32	$1, q4				// w3:w0 + sigma0(w4:w1) + w12:w9 + sigma1(0 0 w15:w14)
	and		s, g, h				// (x) & (y)
	add		b, t, ror #6				// use h to store h+Sigma1(e)
	bic		t, a, g				// (~(x)) & (z)
	vext.64	q4, zero, $1, #1		// Q4 = (w17:w16 0 0)
	eor		t, t, s				// t = Ch(x,y,z) = (((x) & (y)) ^ ((~(x)) & (z)))
	ldr		s, WK(2+$0)			//
	add		b, t				// t = h+Sigma1(e)+Ch(e,f,g);
	vshr.u32	q6, q4, #17
	vshl.i32	q7, q4, #13
	vshr.u32	q4, q4, #10
	eor		t, c, c, ror #11	// S32(2,  (x)) ^ S32(13, (x))
	add		b, s				// h = T1
	eor		t, t, c, ror #20	// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))				// t = Sigma0(a);
	add		f, b				// d += T1;
	veor		q4, q6
	veor		q4, q7
	add		b, t, ror #2			// h = T1 + Sigma0(a);
	eor		t, d, e				// y^z
	and		s, d, e				// y&z
	and		t, t, c				// x&(y^z)
	vshr.u32	q6, #2
	vshl.i32	q7, #2
	eor		s, s, t				// t = Maj(x,y,z) = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

	eor		t, f, f, ror #5	// S32(6,  (x)) ^ S32(11, (x))
	add		b, s
	eor		t, t, f, ror #19	// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	veor		q4, q6
	veor		q4, q7
	vadd.s32	$1, q4				// w19:w16 = w3:w0 + sigma0(w4:w1) + w12:w9 + sigma1(w17:w14)

	and		s, f, g				// (x) & (y)
	add		a, t, ror #6			// use h to store h+Sigma1(e)
	bic		t, h, f				// (~(x)) & (z)
	vadd.s32	q5, $1				// W+K
	eor		t, t, s				// t = Ch(x,y,z) = (((x) & (y)) ^ ((~(x)) & (z)))
	ldr		s, WK(3+$0)			//
	add		a, t				// t = h+Sigma1(e)+Ch(e,f,g);
	eor		t, b, b, ror #11	// S32(2,  (x)) ^ S32(13, (x))
	add		a, s				// h = T1
	eor		t, t, b, ror #20	// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))				// t = Sigma0(a);
	add		e, a				// d += T1;
	add		a, t, ror #2				// h = T1 + Sigma0(a);
	eor		t, c, d				// y^z
	and		s, c, d				// y&z
	and		t, t, b				// x&(y^z)
	eor		s, s, t				// t = Maj(x,y,z) = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
	add		t, sp, #(($0&15)*4)
	add		a, s

	vst1.32		{q5},[t,:128]
	.endm

	.text

	.align	4
K256:
	.long 	0x428a2f98
	.long 	0x71374491
	.long	0xb5c0fbcf
	.long	0xe9b5dba5
	.long	0x3956c25b
	.long	0x59f111f1
	.long	0x923f82a4
	.long	0xab1c5ed5
    .long	0xd807aa98
	.long	0x12835b01
	.long	0x243185be 
	.long	0x550c7dc3
    .long	0x72be5d74 
	.long	0x80deb1fe 
	.long	0x9bdc06a7 
	.long	0xc19bf174
    .long	0xe49b69c1 
	.long	0xefbe4786 
	.long	0x0fc19dc6 
	.long	0x240ca1cc
    .long	0x2de92c6f 
	.long	0x4a7484aa 
	.long	0x5cb0a9dc 
	.long	0x76f988da
    .long	0x983e5152 
	.long	0xa831c66d 
	.long	0xb00327c8 
	.long	0xbf597fc7
    .long	0xc6e00bf3 
	.long	0xd5a79147 
	.long	0x06ca6351 
	.long	0x14292967
    .long	0x27b70a85 
	.long	0x2e1b2138 
	.long	0x4d2c6dfc 
	.long	0x53380d13
    .long	0x650a7354 
	.long	0x766a0abb 
	.long	0x81c2c92e 
	.long	0x92722c85
    .long	0xa2bfe8a1 
	.long	0xa81a664b 
	.long	0xc24b8b70 
	.long	0xc76c51a3
    .long	0xd192e819 
	.long	0xd6990624 
	.long	0xf40e3585 
	.long	0x106aa070
    .long	0x19a4c116 
	.long	0x1e376c08 
	.long	0x2748774c 
	.long	0x34b0bcb5
    .long	0x391c0cb3 
	.long	0x4ed8aa4a 
	.long	0x5b9cca4f 
	.long	0x682e6ff3
    .long	0x748f82ee 
	.long	0x78a5636f 
	.long	0x84c87814 
	.long	0x8cc70208
    .long	0x90befffa
	.long	0xa4506ceb
	.long	0xbef9a3f7
	.long	0xc67178f2


    .globl _vng_armv7neon_sha256_compress
    .private_extern _vng_armv7neon_sha256_compress
_vng_armv7neon_sha256_compress:

    // due to the change of order in the 2nd and 3rd calling argument,
    // we need to switch r1/r2 to use the original code
    // cclee 1-13-11
    mov     r12, r1
    mov     r1, r2
    mov     r2, r12

	// push callee-saved registers
	push	{r4-r7,lr}
	add		r7, sp, #12			// set up dtrace frame pointer
	push	{r8-r11}


	// align sp to 16-byte boundary
	ands    r12, sp, #15		// bytes to align to 16-byte boundary
	addeq	r12, #16			// if nothing, enforce to insert 16 bytes
	sub     sp, r12
	str     r12, [sp]

#if KERNEL
    vpush   {q8}
#endif
    vpush   {q0-q7}
#define stack_size (16*5)       // circular buffer W0-W3, extra 16 to save num_blocks
    sub     sp, #stack_size

	str		r2, num_blocks 

	veor	zero, zero

	// set up pointer to table K256[]
	adr		K, K256

	// load W[0:15]
	vld1.s32	{W0-W1},[data]!
	vld1.s32	{W2-W3},[data]!

	// load K[0:15] & per word byte swap
	vrev32.8	W0, W0
	vrev32.8	W1, W1
	vld1.s32	{q4-q5}, [K,:128]!
	vrev32.8	W2, W2
	vrev32.8	W3, W3
	vld1.s32	{q6-q7}, [K,:128]!

	// compute WK[0:15] and save in stack

	vadd.s32	q4, q0
	vadd.s32	q5, q1
	vadd.s32	q6, q2
	vadd.s32	q7, q3

	vstmia		sp,{q4-q7}

	// digests a-h = ctx->states;
	ldmia		ctx,{a-d,e-h}

L_loop:

	// rounds 0:47 interleaved with W/WK update for rounds 16:63
#if 1
	rounds_a_schedule_update	 0,W0,W1,W2,W3
	rounds_e_schedule_update	 4,W1,W2,W3,W0
	rounds_a_schedule_update	 8,W2,W3,W0,W1
	rounds_e_schedule_update	12,W3,W0,W1,W2
	rounds_a_schedule_update	16,W0,W1,W2,W3
	rounds_e_schedule_update	20,W1,W2,W3,W0
	rounds_a_schedule_update	24,W2,W3,W0,W1
	rounds_e_schedule_update	28,W3,W0,W1,W2
	rounds_a_schedule_update	32,W0,W1,W2,W3
	rounds_e_schedule_update	36,W1,W2,W3,W0
	rounds_a_schedule_update	40,W2,W3,W0,W1
	rounds_e_schedule_update	44,W3,W0,W1,W2
#else
	rounds_a	0
	message_schedule W0,W1,W2,W3,16
	rounds_e	4 
	message_schedule W1,W2,W3,W0,20
	rounds_a	8
	message_schedule W2,W3,W0,W1,24
	rounds_e	12 
	message_schedule W3,W0,W1,W2,28
	rounds_a	16
	message_schedule W0,W1,W2,W3,32
	rounds_e	20 
	message_schedule W1,W2,W3,W0,36
	rounds_a	24
	message_schedule W2,W3,W0,W1,40
	rounds_e	28 
	message_schedule W3,W0,W1,W2,44
	rounds_a	32
	message_schedule W0,W1,W2,W3,48
	rounds_e	36 
	message_schedule W1,W2,W3,W0,52
	rounds_a	40
	message_schedule W2,W3,W0,W1,56
	rounds_e	44 
	message_schedule W3,W0,W1,W2,60
#endif

	// revert K to the beginning of K256[]
	ldr		t, num_blocks
	sub		K, #256

	subs	t, #1						// num_blocks--
	beq		L_final_block				// if final block, wrap up final rounds
	str		t, num_blocks

	// rounds 48:63 interleaved with W/WK initialization for next block rounds 0:15 
	rounds_a	48
	update_W_WK	0, W0
	rounds_e	52 
	update_W_WK	1, W1
	rounds_a	56
	update_W_WK	2, W2
	rounds_e	60 
	update_W_WK	3, W3

	// ctx->states += digests a-h
	Update_Digits

	// digests a-h = ctx->states;
	ldmia		ctx,{a-d,e-h}

	bal		L_loop				// branch for next block

	// wrap up digest update round 48:63 for final block
L_final_block:
	rounds_a	48
	rounds_e	52 
	rounds_a	56
	rounds_e	60 

	// ctx->states += digests a-h
	Update_Digits

	// free allocated stack memory
	add		sp, #stack_size

	// if kernel, restore q0-q8
	vpop	{q0-q1}
	vpop	{q2-q3}
	vpop	{q4-q5}
	vpop	{q6-q7}
#if	KERNEL
	vpop	{q8}
#endif

	// dealign sp from the 16-byte boundary
    ldr     r12, [sp]
    add     sp, r12

	// restore callee-save registers and return
	pop	{r8-r11}
	pop	{r4-r7,pc}

#endif /* _ARM_ARCH_7 */

Added Source/descriptors/digestDescriptors/vng_neon_sha2_descriptor/vng_neon_sha224.c.



























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* Adapted from LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
/**
   @param sha224.c
   vng_neon_SHA-224 new NIST standard based off of vng_neon_SHA-256 truncated to 224 bits (Tom St Denis)
*/

const ccDescriptor vng_neon_sha224_desc =
{
    .implementation_info = &cc_sha224_impinfo,
	.dtype.digest.hashsize = CC_SHA224_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA224_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &vng_neon_sha224_init,
	.dtype.digest.process = &vng_neon_sha256_process,
	.dtype.digest.done = &vng_neon_sha224_done,
};


/* init the sha256 er... sha224 state ;-) */
/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int vng_neon_sha224_init(vng_neon_sha256_ctx *ctx)
{
    LTC_ARGCHK(ctx != NULL);

    // ctx->curlen = 0;
    ctx->length = 0;
    ctx->state[0] = 0xc1059ed8UL;
    ctx->state[1] = 0x367cd507UL;
    ctx->state[2] = 0x3070dd17UL;
    ctx->state[3] = 0xf70e5939UL;
    ctx->state[4] = 0xffc00b31UL;
    ctx->state[5] = 0x68581511UL;
    ctx->state[6] = 0x64f98fa7UL;
    ctx->state[7] = 0xbefa4fa4UL;

    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (28 bytes)
   @return CRYPT_OK if successful
*/
int vng_neon_sha224_done(vng_neon_sha256_ctx *ctx, unsigned char *out)
{
    unsigned char buf[32];
    int err;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    err = vng_neon_sha256_done(ctx, buf);
    CC_XMEMCPY(out, buf, 28);
    return err;
}

Added Source/descriptors/digestDescriptors/vng_neon_sha2_descriptor/vng_neon_sha224.h.









































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  vng_neon_sha224.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <arm/arch.h>

#if defined(_ARM_ARCH_7)

#ifndef _VNG_NEON_SHA224_H_
#define _VNG_NEON_SHA224_H_

/*
 * Note that vng_neon_sha256 is required for vng_neon_sha224.
 */

#define	VNG_NEON_SHA224_HASHSIZE	28
#define	VNG_NEON_SHA224_BLOCKSIZE	64

int vng_neon_sha224_init(vng_neon_sha256_ctx *ctx);
#define vng_neon_sha224_process vng_neon_sha256_process
int vng_neon_sha224_done(vng_neon_sha256_ctx *ctx, unsigned char *hash);

#endif /* _VNG_NEON_SHA224_H_ */
#endif /* _ARM_ARCH_7 */

Added Source/descriptors/digestDescriptors/vng_neon_sha2_descriptor/vng_neon_sha256.c.









































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <arm/arch.h>

#if defined(_ARM_ARCH_7)

#include <stdio.h>
#include "vng_neon_sha256.h"
#include "vng_neon_sha224.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"

/**
  @file vng_neon_sha256.c
  vng_neon_SHA256 by Tom St Denis 
*/

const ccDescriptor vng_neon_sha256_desc =
{
    .implementation_info = &cc_sha256_impinfo,
	.dtype.digest.hashsize = CC_SHA256_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA256_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &vng_neon_sha256_init,
	.dtype.digest.process = &vng_neon_sha256_process,
	.dtype.digest.done = &vng_neon_sha256_done,
};


#ifdef LTC_SMALL_CODE
/* the K array */
static const ulong32 K[64] = {
    0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
    0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
    0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
    0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
    0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
    0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
    0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
    0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
    0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
    0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
    0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
    0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
    0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};
#endif

/* Various logical functions */
#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
#define Maj(x,y,z)      (((x | y) & z) | (x & y)) 
#define S(x, n)         LTC_RORc((x),(n))
#define R(x, n)         (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x)       (S(x, 2) ^ S(x, 13) ^ S(x, 22))
#define Sigma1(x)       (S(x, 6) ^ S(x, 11) ^ S(x, 25))
#define Gamma0(x)       (S(x, 7) ^ S(x, 18) ^ R(x, 3))
#define Gamma1(x)       (S(x, 17) ^ S(x, 19) ^ R(x, 10))


#define FULLLENGTH_MASK 0xffffffffffffffc0
#define BUFFLENGTH_MASK 0x3f
/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int vng_neon_sha256_init(vng_neon_sha256_ctx *ctx)
{
    LTC_ARGCHK(ctx != NULL);

    ctx->length = 0;
    ctx->state[0] = 0x6A09E667UL;
    ctx->state[1] = 0xBB67AE85UL;
    ctx->state[2] = 0x3C6EF372UL;
    ctx->state[3] = 0xA54FF53AUL;
    ctx->state[4] = 0x510E527FUL;
    ctx->state[5] = 0x9B05688CUL;
    ctx->state[6] = 0x1F83D9ABUL;
    ctx->state[7] = 0x5BE0CD19UL;

    return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
int vng_neon_sha256_process(vng_neon_sha256_ctx *ctx, const unsigned char *in, unsigned long inlen)
{
    unsigned long n; 
    int err;
    int fullblocks, remainder, processed;
    uint64_t curlen;
    
    LTC_ARGCHK(ctx != NULL); 
    LTC_ARGCHK(in != NULL);
            
    curlen = ctx->length & BUFFLENGTH_MASK;
    
    if ((ctx->length + inlen) < ctx->length) { 
        return CRYPT_HASH_OVERFLOW; 
    }
    
    while (inlen > 0) { 
        if (curlen == 0 && inlen >= VNG_NEON_SHA256_BLOCKSIZE && CC_XALIGNED(in, 4)) {
            fullblocks = inlen / VNG_NEON_SHA256_BLOCKSIZE;
            remainder = inlen % VNG_NEON_SHA256_BLOCKSIZE;
            processed = fullblocks * VNG_NEON_SHA256_BLOCKSIZE;
            vng_armv7neon_sha256_compress (ctx->state, fullblocks, in);
            ctx->length += VNG_NEON_SHA256_BLOCKSIZE * 8 * fullblocks; 
            in += processed;
            inlen -= processed; 
        } else {
            n = MIN(inlen, (VNG_NEON_SHA256_BLOCKSIZE - curlen)); 
            memcpy(ctx->buf + curlen, in, (size_t)n); 
            curlen += n; in += n; inlen -= n; 
            if (curlen == VNG_NEON_SHA256_BLOCKSIZE) {
                vng_armv7neon_sha256_compress (ctx->state, 1, ctx->buf);
                ctx->length += 8*VNG_NEON_SHA256_BLOCKSIZE;
                curlen = 0; 
            } 
        } 
    }
    
    ctx->length = (ctx->length & FULLLENGTH_MASK) + curlen;
    
    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (32 bytes)
   @return CRYPT_OK if successful
*/
int vng_neon_sha256_done(vng_neon_sha256_ctx *ctx, unsigned char *out)
{
    int i;
    uint64_t curlen;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    curlen = ctx->length & BUFFLENGTH_MASK;
    ctx->length &= FULLLENGTH_MASK;

    /* increase the length of the message */
    ctx->length += curlen * 8;

    /* append the '1' bit */
    ctx->buf[curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (curlen > 56) {
        while (curlen < 64) {
            ctx->buf[curlen++] = (unsigned char)0;
        }
        vng_armv7neon_sha256_compress (ctx->state, 1, ctx->buf);

        curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (curlen < 56) {
        ctx->buf[curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64H(ctx->length, ctx->buf+56);
    vng_armv7neon_sha256_compress (ctx->state, 1, ctx->buf);

    /* copy output */
    for (i = 0; i < 8; i++) {
        LTC_STORE32H(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(ctx, sizeof(hash_state));
#endif
    return CRYPT_OK;
}


#include "vng_neon_sha224.c"

#endif /* _ARM_ARCH_7 */

Added Source/descriptors/digestDescriptors/vng_neon_sha2_descriptor/vng_neon_sha256.h.



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  vng_neon_sha256.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#include <arm/arch.h>

#if defined(_ARM_ARCH_7)
#include <stdint.h>

#ifndef _VNG_NEON_SHA256_H_
#define _VNG_NEON_SHA256_H_

#define	VNG_NEON_SHA256_HASHSIZE	32
#define	VNG_NEON_SHA256_BLOCKSIZE	64

typedef struct vng_neon_sha256_state {
    uint64_t length;
    uint32_t state[8];
    unsigned char buf[VNG_NEON_SHA256_BLOCKSIZE];
} vng_neon_sha256_ctx;

int vng_neon_sha256_init(vng_neon_sha256_ctx *ctx);
int vng_neon_sha256_process(vng_neon_sha256_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int vng_neon_sha256_done(vng_neon_sha256_ctx *ctx, unsigned char *hash);
void vng_armv7neon_sha256_compress(void *c, unsigned long num, const void *p);

#endif /* _VNG_NEON_SHA256_H_ */
#endif /* _ARM_ARCH_7 */

Added Source/descriptors/digestDescriptors/vng_x86_sha1_descriptor/vng_x86_sha1.c.



















































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
 

#if defined (__x86_64__) || defined(__i386__)		// x86_64 or i386 architectures

#include <stdio.h>
#include "vng_x86_sha1.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"

/**
  @file vng_x86_sha1.c
  original LTC_SHA1 code by Tom St Denis 
  optimized compress function by the Vector and Numerics Group
*/


const ccDescriptor vng_x86_sha1_desc =
{
    .implementation_info = &cc_sha1_impinfo,
	.dtype.digest.hashsize = CC_SHA1_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA1_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &vng_x86_sha1_init,
	.dtype.digest.process = &vng_x86_sha1_process,
	.dtype.digest.done = &vng_x86_sha1_done,
};


/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int vng_x86_sha1_init(vng_x86_sha1_ctx *ctx)
{
   LTC_ARGCHK(ctx != NULL);
   
   ctx->state[0] = 0x67452301UL;
   ctx->state[1] = 0xefcdab89UL;
   ctx->state[2] = 0x98badcfeUL;
   ctx->state[3] = 0x10325476UL;
   ctx->state[4] = 0xc3d2e1f0UL;
    CC_XZEROMEM(ctx->buf, CC_SHA1_BLOCK_BYTES);
    ctx->curlen = 0;
   ctx->length = 0;
   
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
int vng_x86_sha1_process(vng_x86_sha1_ctx *ctx, const unsigned char *in, unsigned long inlen)
{
    unsigned long n; 
    int err;
    int fullblocks, remainder, processed;
    
    LTC_ARGCHK(ctx != NULL); 
    LTC_ARGCHK(in != NULL);
        
    if (ctx->curlen > sizeof(ctx->buf)) {
        return CRYPT_INVALID_ARG;
    } 
    if ((ctx->length + inlen) < ctx->length) { 
        return CRYPT_HASH_OVERFLOW; 
    }    
    
    while (inlen > 0) { 
        if (ctx->curlen == 0 && inlen >= VNG_X86_SHA1_BLOCKSIZE && CC_XALIGNED(in, 4)) {
            fullblocks = inlen / VNG_X86_SHA1_BLOCKSIZE;
            // remainder = inlen % VNG_X86_SHA1_BLOCKSIZE;
            processed = fullblocks * VNG_X86_SHA1_BLOCKSIZE;
            sha1_x86_compress_data_order (ctx->state, in, fullblocks);
            ctx->length += processed * 8; 
            in += processed;
            inlen -= processed; 
        } else {
            n = MIN(inlen, (VNG_X86_SHA1_BLOCKSIZE - ctx->curlen)); 
            CC_XMEMCPY(ctx->buf + ctx->curlen, in, n); 
            ctx->curlen += n; in += n; inlen -= n; 
            if (ctx->curlen == VNG_X86_SHA1_BLOCKSIZE) {
                sha1_x86_compress_data_order (ctx->state, ctx->buf, 1);
                ctx->length += 8*VNG_X86_SHA1_BLOCKSIZE;
                ctx->curlen = 0; 
            } 
        } 
    }
    
    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (20 bytes)
   @return CRYPT_OK if successful
*/
int vng_x86_sha1_done(vng_x86_sha1_ctx *ctx, unsigned char *out)
{
    int i;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    if (ctx->curlen >= sizeof(ctx->buf)) {
       return CRYPT_INVALID_ARG;
    }
    
    /* increase the length of the message */
    ctx->length += ctx->curlen * 8;
    
    /* append the '1' bit */
    ctx->buf[ctx->curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (ctx->curlen > 56) {
        while (ctx->curlen < 64) {
            ctx->buf[ctx->curlen++] = (unsigned char)0;
        }
        sha1_x86_compress_data_order(ctx->state, ctx->buf, 1);
        ctx->curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (ctx->curlen < 56) {
        ctx->buf[ctx->curlen++] = (unsigned char)0;
    }

    /* store length */
    CC_XSTORE64H(ctx->length, ctx->buf+56);
    sha1_x86_compress_data_order(ctx->state, ctx->buf, 1);

    /* copy output */
    for(i=0; i<5; i++, out+=4) CC_XSTORE32H(ctx->state[i], out);
    
    return CRYPT_OK;
}
#endif /* x86 */

Added Source/descriptors/digestDescriptors/vng_x86_sha1_descriptor/vng_x86_sha1.h.































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  vng_x86_sha1.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2011 Apple Inc. All rights reserved.
 *
 */

#include <stdint.h>

#if defined (__x86_64__) || defined(__i386__)		// x86_64 or i386 architectures

#ifndef _VNG_X86_SHA1_H_
#define _VNG_X86_SHA1_H_

#define VNG_X86_SHA1_HASHSIZE	20
#define VNG_X86_SHA1_BLOCKSIZE	64

// Adjusted to take the same space as CC_SHA1_CTX
// The order is important on a 64 bit system so that
// the length variable is 64 bit aligned.

typedef struct vng_x86_sha1_state {
    uint32_t state[5];                            // 20
    uint32_t curlen;                              //  4
    uint64_t length;                              //  8
    unsigned char buf[VNG_X86_SHA1_BLOCKSIZE];    // 64
} vng_x86_sha1_ctx;

int vng_x86_sha1_init(vng_x86_sha1_ctx *ctx);
int vng_x86_sha1_process(vng_x86_sha1_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int vng_x86_sha1_done(vng_x86_sha1_ctx *ctx, unsigned char *hash);

// I think the x86 version takes the blocks as the third argument.
void sha1_x86_compress_data_order(uint32_t state[], unsigned char *, unsigned long nblocks);
#endif /* x86 */
#endif /* _VNG_X86_SHA1_H_ */

Added Source/descriptors/digestDescriptors/vng_x86_sha1_descriptor/vng_x86_sha1BE.s.































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
/* 
 * Copyright (c) 2011 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* 	sha1edp.s : this file provides optimized x86_64 and i386 implementation of the sha1 function
	CoreOS - vector and numerics group
	cclee	6-21-10
	
	The implementation is based on the principle described in an Intel online article
	"Improving the Performance of the Secure Hash Algorithm (SHA-1)"
	http://software.intel.com/en-us/articles/improving-the-performance-of-the-secure-hash-algorithm-1/


	Update HASH[] by processing a one 64-byte block in MESSAGE[] can be represented by the following C function

void SHA1( int HASH[], int MESSAGE[] )
{
    int A[81], B[81], C[81], D[81], E[81];
    int W[80];

    int i, FN;

    A[0] = HASH[0]; 
    B[0] = HASH[1];
    C[0] = HASH[2];
    D[0] = HASH[3];
    E[0] = HASH[4];

    for ( i=0; i<80; ++i )
    {
        if ( i < 16 )
            W[i] = BIG_ENDIAN_LOAD( MESSAGE[i] );
        else
            W[i] = ROTATE_LEFT( W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1 );

        FN = F( i, B[i], C[i], D[i] );

        A[i+1] = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + W[i] + K(i);
        B[i+1] = A[i];
        C[i+1] = ROTATE_LEFT( B[i], 30 );
        D[i+1] = C[i];
        E[i+1] = D[i];
    }

    HASH[0] += A[80];
    HASH[1] += B[80];
    HASH[2] += C[80];
    HASH[3] += D[80];
    HASH[4] += E[80];
} 

	For i=0:15, W[i] is simply big-endian loading of MESSAGE[i]. For i=16:79, W[i] is updated according to W[i] = ROTATE_LEFT( W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1 );

	The approach (by Dean Gaudet) can be used to vectorize the computation of W[i] for i=16:79,

	1. done on 4 consequtive W[i] values in a single XMM register
    W[i  ] = (W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]) rol 1
    W[i+1] = (W[i-2] ^ W[i-7] ^ W[i-13] ^ W[i-15]) rol 1
    W[i+2] = (W[i-1] ^ W[i-6] ^ W[i-12] ^ W[i-14]) rol 1
    W[i+3] = (   0   ^ W[i-5] ^ W[i-11] ^ W[i-13]) rol 1

    2. this additional calculation unfortunately requires many additional operations
    W[i+3] ^= W[i] rol 1

    3. once we have 4 W[i] values in XMM we can also add four K values with one instruction
    W[i:i+3] += {K,K,K,K}

	Let W0 = {W[i] W[i+1] W[i+2] W[i+3]} be the current W-vector to be computed, W4 = {W[i-4] W[i-3] W[i-2] W[i-1]} be the previous vector, and so on
	The Dean Gaudet approach can be expressed as

	1. W0 = rotate_left(left_shift(W4,32) ^ W8 ^ left_shift(concatenate(W16,W12),64) ^ W16,1);
	2. W[i+3] ^= W[i] rol 1
	3. W0 += {K,K,K,K}

	For i>=32, the Intel online article suggests that (using a basic identity (X rol 1) rol 1 = X rol 2) the update equation is equivalent to

	1. W0 = rotate_left(left_shift(concatenate(W8,W4),64) ^ W16 ^ W28 ^ W32, 2); 

	Note:
	1. In total, we need 8 16-byte registers or memory for W0,W4,...,W28. W0 and W32 can be the same register or memory.
	2. The registers are used in a circular buffering mode. For example, we start with W28,W24,...,W0 (with W0 indicating the most recent 16-byte)
		i=0, W28,W24,...,W0
		i=4, W24,W20,...,W28
		i=8, W20,W16,...,W24
		.
		.
		and so forth.
	3. 2 ssse3 instructions are used in the Intel article, pshufb and palignr.
		a. pshufb is used to simplify the BIG_ENDIAN_LOAD operation 
		b. palignr is used to simplify the computation of left_shift(concatenate(W12,W8),64)
	4. we probe __cpu_capabilities to detect ssse3 support and dispatch code with ssse3 support when available.
	   If ssse3 is not supported, a suboptimal code (pshufb and palignr workaround) is dispatched. 

*/

/* the code can be compiled into single block (64 bytes) per call mode by setting Multiple_blocks to 0 */
#define	Multiple_Blocks	1

#if defined (__x86_64__) || defined(__i386__)		// x86_64 or i386 architectures

#if defined(__x86_64__)

	// set up for x86_64
#define	stack_size	(8+16*11+16*4)					// 8 (alignedment) + x0-x10 + 4 128-bits for intermediate WK(t) storage
#define	sp			%rsp							// unifying architectural stack pointer representation
#define	ctx			%rdi							// 1st input argument, will move to HASH_PTR (%r9)
#define	buf			%rsi							// 2nd input argument, will move to BUFFER_PTR (%r10) 
#define	cnt			%r11							// will copy from the 3rd input argument (%rdx)
#define K_BASE		%r8								// an aligned pointer to point to shufb reference numbers of table of K values
#define HASH_PTR	%r9								// pointer to Hash values (A,B,C,D,E)
#define BUFFER_PTR	%r10							// pointer to input blocks 

#else	// !__x86_64__

	// set up for i386 
#define stack_size	(12+16*2+16*11+16*4)			// 12-bytes (alignment) + extra 2 + 3 (W24/W28/XMM_SHUFB_BSWAP) + 8 (xmm0-xmm7) + 4 (WK(t))
#define	sp			%esp							// unifying architectural stack pointer representation
#define HASH_PTR	stack_size+16+4(sp)				// use 1st input argument from caller function, 16 for (esi/edi/ebx/ebp)
#define BUFFER_PTR	stack_size+16+8(sp)				// use 2nd input argument from caller function 
#define cnt			stack_size+16+12(sp)			// use 3rd input argument from caller function
#define K_BASE		stack_size-4(sp)				// use for K_BASE

#endif	// __x86_64__

// symbolizing registers or stack memory with algorithmic variables	W0,W4,...,W28 + W_TMP, W_TMP2, and XMM_SHUFB_BSWAP for code with ssse3 support

#define W_TMP  	%xmm0
#define W_TMP2 	%xmm1
#define W0  	%xmm2
#define W4  	%xmm3
#define W8  	%xmm4
#define W12 	%xmm5
#define W16 	%xmm6
#define W20 	%xmm7
#if defined(__x86_64__)
#define W24 	%xmm8
#define W28 	%xmm9
#define XMM_SHUFB_BSWAP %xmm10				// used only when ssse3 is supported
#else	// defined (__i386__)
#define W24     12*16(sp)
#define W28     13*16(sp)
#define XMM_SHUFB_BSWAP 14*16(sp)			// used only when ssse3 is supported 
#endif

#define	xmov	movaps						// aligned 16-byte move
#define	xmovu	movups						// unaligned 16-byte move

// intermediate hash variables
#define A %ecx
#define B %esi
#define C %edi
#define D %ebp
#define E %edx

// temp variables
#define T1 %eax
#define T2 %ebx

#define	WK(t)	(t&15)*4(sp)

	// int F1(int B, int C, int D) { return (D ^ ( B & (C ^ D)); }
	// result in T1
	.macro	F1
	mov	$1, T1
	xor	$2, T1
	and	$0, T1
	xor	$2, T1
	.endm

	// int F2(int B, int C, int D) { return (D ^ B ^ C); }
	// result in T1
	.macro	F2
	mov	$2, T1
	xor	$1, T1
	xor	$0, T1
	.endm

	// int F3(int B, int C, int D) { return (B & C) | (D & (B ^ C)); }
	// result in T1
	.macro	F3
		mov $1, T1
        mov $0, T2
        or  $0, T1
        and $1, T2
        and $2, T1
        or  T2, T1
	.endm

	// for i=60:79, F4 is identical to F2
	#define	F4	F2


	/*
		i=0:15, W[i] = BIG_ENDIAN_LOAD(MESSAGE[i]);

		with ssse3 support, this is achived via
		for (i=0;i<16;i+=4) {
			1. W_TMP = new 16 bytes from MESSAGE[]
			2. W_TMP = pshufb(W_TMP, XMM_SHUFB_BSWAP); save to W circular buffer for updating W 
			3. WTMP += {K,K,K,K};
			4. save quadruple W[i]+K[i] = W_TMP in the stack memory;
		}

		each step is represented in one of the following 4 macro definitions

	*/

	.macro	W_PRECALC_00_15_0				// input argument $0 : 0/4/8/12
#if defined (__x86_64__)					// BUFFER_PTR is already an address register in x86_64
	xmovu	$0*4(BUFFER_PTR), W_TMP			// read 16-bytes into W_TMP, BUFFER_PTR possibly not 16-byte aligned
#else										// BUFFER_PTR is from the argument set up in the caller
	mov     BUFFER_PTR, T1					// T1 = BUFFER_PTR
    xmovu  $0*4(T1), W_TMP					// read 16-bytes into W_TMP, BUFFER_PTR possibly not 16-byte aligned
#endif
	.endm

	.macro	W_PRECALC_00_15_1				// input argument $0 : current 16-bytes in the circular buffer, one of W0,W4,W8,...,W28
	xmov	W_TMP, $0						// save W_TMP in the circular buffer
	.endm

	.macro	W_PRECALC_00_15_2				// K_BASE points to the current K quadruple.
#if defined (__x86_64__)					// K_BASE is already an address register in x86_64
	paddd	(K_BASE), W_TMP					// W_TMP += {K,K,K,K};
#else										// K_BASE is previously set up in the stack memory
	mov     K_BASE, T1						// T1 = K_BASE
    paddd   (T1), W_TMP						// W_TMP += {K,K,K,K};
#endif
	.endm

	.macro	W_PRECALC_00_15_3
	xmov	W_TMP, WK($0&~3)				// save quadruple W[i]+K in the stack memory, which would be used later for updating the hashes A/B/C/D/E
	.endm

	// rounds 16-31 compute W[0] using the vectorization approach by Dean Gaudet
	/*
	W[i  ] = (W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]) rol 1
    W[i+1] = (W[i-2] ^ W[i-7] ^ W[i-13] ^ W[i-15]) rol 1
    W[i+2] = (W[i-1] ^ W[i-6] ^ W[i-12] ^ W[i-14]) rol 1
    W[i+3] = (   0   ^ W[i-5] ^ W[i-11] ^ W[i-13]) rol 1

	W[i+3] ^= W[i] rol 1;	// this W[i] is already rol by 1, if we are taking from the intial W before rol 1, we should rol this by 2

	The operation (updating W and W+K) is scheduled as and divided into 4 steps

	0. W_tmp = W3; W = W14 ^ W8
	1. W = W3 ^ W8 ^ W14 ^ W16; W_TMP = W; W_TMP2 = (W[i] 0 0 0); 
	2. W_TMP = (W3 ^ W8 ^ W14 ^ W16) rol 1; split (W[i] 0 0 0) rol 2 in W_TMP2 and W
	3. W = W_TMP = W_TMP ^ W_TMP2 ^ W = (W3 ^ W8 ^ W14 ^ W16) rol 1 ^ (W[i] 0 0 0) rol 2; WK = W _TMP+K;  

	*/

	.macro	W_PRECALC_16_31_0_ssse3	// input arguments : W16,W12,W8,W4,W
	xmov	$1, $4					// W = W12
	palignr	$$8, $0, $4				// W = W14
	xmov	$3, W_TMP				// W_TMP = W4
	psrldq	$$4, W_TMP				// W_TMP = W3
	pxor	$2, $4					// W = W8 ^ W14	
	.endm

	.macro	W_PRECALC_16_31_1		// input arguments : W16,W
	pxor	$0, W_TMP				// W_TMP = W3 ^ W16
	pxor	W_TMP, $1				// W = W3 ^ W16 ^ W8 ^ W14
	xmov	$1, W_TMP2				// W_TMP2 = W3 ^ W16 ^ W8 ^ W14 
	xmov	$1, W_TMP				// W_TMP = W3 ^ W16 ^ W8 ^ W14
	pslldq	$$12, W_TMP2			// W_TMP2 = (W[i] 0 0 0)
	.endm

	.macro	W_PRECALC_16_31_2		// input argument : W
	psrld	$$31, $0				// (W3 ^ W16 ^ W8 ^ W14)>>31
	pslld	$$1, W_TMP				// (W3 ^ W16 ^ W8 ^ W14)<<1
	por		$0, W_TMP				// W_TMP = (W3 ^ W16 ^ W8 ^ W14) rol 1
	xmov	W_TMP2, $0				// copy W[i] at location of W[i+3]
	psrld	$$30, W_TMP2			// W_TMP2 = W[i] lower 2 bits after rol 2
	pslld	$$2, $0					// W = W[i] higher 30 bits after rol 2
	.endm

	.macro	W_PRECALC_16_31_3		// input arguments: W, i, K_XMM
#if defined (__i386__)
	mov     K_BASE, T1				// K_BASE is store in the stack memory for i386
#endif
	pxor	$0, W_TMP
	pxor	W_TMP2, W_TMP			// W_TMP = (W3 ^ W16 ^ W8 ^ W14) rol 1 ^ (W[i] 0 0 0) rol 2
	xmov	W_TMP, $0				// save W = W_TMP in the W circular buffer
#if defined (__x86_64__)
	paddd	$2(K_BASE), W_TMP		// W+K
#else
    paddd   $2(T1), W_TMP			// W+K
#endif
	xmov	W_TMP, WK($1&~3)		// save WK = W+K for later update of the hashes A/B/C/D/E
	.endm

	// the following is a variant of W_PRECALC_16_31_0_ssse3 to be used for system without ssse3, palignr is replaced with 4 instructions

	.macro	W_PRECALC_16_31_0_nossse3	// input arguments : W16,W12,W8,W4,W
	xmov	$1, $4						// W = W12 = (w9 w10 w11 w12)

	// the following is a wrokaround for palignr
	xmov	$0, W_TMP					// W16 = (w13 w14 w15 w16)
	pslldq	$$8, $4						// shift left to make (w11 w12 0 0)
	psrldq	$$8, W_TMP					// shift right to make (0 0 w13 w14)
	por		W_TMP, $4					// W = W14 = (w11 w12 w13 w14)

	xmov	$3, W_TMP					// W_TMP = W4 = (w1 w2 w3 w4)
	psrldq	$$4, W_TMP					// W_TMP = W3 = (0 w1 w2 w3)
	pxor	$2, $4						// W = W8 ^ W14	
	.endm

	/* rounds 32-79 compute W und W+K iusing the vectorization approach from the Intel article

		W = rotate_left(left_shift(concatenate(W8,W4),64) ^ W16 ^ W28 ^ W32, 2);

		where left_shift(concatenate(W8,W4),64) is equivalent to W6. Note also that W32 and W use the same register.


	0. W_tmp = W6; W = W28 ^ W32;
	1. W = W_tmp = W6 ^ W16 ^ W28 ^ W32;
	2. W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2;
	3. W = W_Tmp; WK = W_tmp + K;

	*/


	.macro	W_PRECALC_32_79_0_ssse3		// inputr arguments : W28,W8,W4,W
	xmov	$2, W_TMP					// (w1 w2 w3 w4)
	pxor	$0, $3						// W = W28 ^ W32;
	palignr	$$8, $1, W_TMP				// W_tmp = (w3 w4 w5 w6) = W6;
	.endm

	// the following is a variant and will be used for system without ssse3 support
	.macro	W_PRECALC_32_79_0_nossse3	// input arguments : W28,W8,W4,W
	xmov	$2, W_TMP					// (w1 w2 w3 w4)
	xmov    $1, W_TMP2					// (w5 w6 w7 w8)
	pxor	$0, $3						// W = W28 ^ W32
	pslldq	$$8, W_TMP					// (w3 w4 0 0)
	psrldq	$$8, W_TMP2					// (0 0 w5 w6)
	por		W_TMP2, W_TMP				// W_tmp = (w3 w4 w5 w6) = W6
	.endm

	// this is a variant of W_PRECALC_32_79_0_ssse3 for i386 (as W24/W28 are stored in memory, not in registers)
	.macro  W_PRECALC_32_79_0_i386_ssse3	// input arguments : W28,W8,W4,W
    xmov    $3, W_TMP						// W32
    pxor    $0, W_TMP						// W28 ^ W32
    xmov    W_TMP, $3						// W = W28 ^ W32;
    xmov    $2, W_TMP						// W4
    palignr $$8, $1, W_TMP					// W_tmp = (w3 w4 w5 w6) = W6;
    .endm

	// this is a variant of W_PRECALC_32_79_0_nossse3 for i386 (as W24/W28 are stored in memory, not in registers)
	.macro  W_PRECALC_32_79_0_i386_nossse3  // input arguments : W28,W8,W4,W
    xmov    $3, W_TMP						// W32
    pxor    $0, W_TMP						// W28 ^ W32
    xmov    W_TMP, $3						// W = W28 ^ W32
    xmov    $2, W_TMP						// W4 = (w1 w2 w3 w4)
	xmov    $1, W_TMP2						// W8 = (w5 w6 w7 w8)
	pslldq	$$8, W_TMP						// (w3 w4 0 0)
	psrldq	$$8, W_TMP2						// (0 0 w5 w6)
	por		W_TMP2, W_TMP					// W_tmp = (w3 w4 w5 w6) = W6
    .endm

	.macro	W_PRECALC_32_79_1			// input arguments : W16,W
	pxor	$0, W_TMP					// W_tmp = W6 ^ W16
	pxor	$1, W_TMP					// W_tmp = W6 ^ W16 ^ W28 ^ W32
	xmov	W_TMP, $1					// W = W_tmp = W6 ^ W16 ^ W28 ^ W32
	.endm

	.macro	W_PRECALC_32_79_2			// input argument : W
	psrld	$$30, $0					// W >> 30
	pslld	$$2, W_TMP					// W << 2
	por		$0, W_TMP					// W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2
	.endm

	// this is a variant of W_PRECALC_32_79_2 for i386 (as W24/W28 are stored in memory, not in registers)
	// this should be used when the input is either W24 or W28 on i386 architecture
    .macro  W_PRECALC_32_79_2_i386  	// input argument : W
    xmov    $0, W_TMP2					// W
    psrld   $$30, W_TMP2				// W >> 30
    xmov    W_TMP2, $0					// save (W >> 30) at W
    pslld   $$2, W_TMP					// W_tmp << 2
    por     $0, W_TMP					// W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2
    .endm

	.macro	W_PRECALC_32_79_3			// input argument W, i, K_XMM
#if defined (__x86_64__)
	xmov	W_TMP, $0					// W = (W6 ^ W16 ^ W28 ^ W32) rol 2
	paddd	$2(K_BASE), W_TMP			// W + K
	xmov	W_TMP, WK($1&~3)			// write W+K
#else
    mov     K_BASE, T1					// T1 = K_BASE (which is in the caller argument)
    xmov    W_TMP, $0					// W = (W6 ^ W16 ^ W28 ^ W32) rol 2
    paddd   $2(T1), W_TMP				// W_tmp = W + K
    xmov    W_TMP, WK($1&~3)			// write WK
#endif
	.endm


	/* The hash update operation is completed by the following statements.

		A[i+1] = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + WK(i);
        B[i+1] = A[i];
        C[i+1] = ROTATE_LEFT( B[i], 30 );
        D[i+1] = C[i];
        E[i+1] = D[i];

		Suppose we start with A0,B0,C0,D0,E0. The 1st iteration can be expressed as follows:

		A1 = FN + E0 + rol(A0,5) + WK;
		B1 = A0;
		C1 = rol(B0, 30);
		D1 = C0;
		E1 = D0;

		to avoid excessive memory movement between registers, 
			1. A1 = FN + E0 + rol(A0,5) + WK; can be temporarily saved in E0, 
			2. C1 = rol(B0,30) can be temporarily saved in B0. 

		Therefore, ignoring the time index, the update operation is equivalent to
			1. E = FN(B,C,D) + E + rol(A,5) + WK(i)
			2. B = rol(B,30)
			3. the hashes are now stored in the order of E,A,B,C,D


		To pack 2 hash update operations in 1 iteration, starting with A,B,C,D,E
		1. E = FN(B,C,D) + E + rol(A,5) + WK(i)
		2. B = rol(B,30)
		// now the hashes are in the order of E,A,B,C,D
		3. D = FN(A,B,C) + D + rol(E,5) + WK(i+1)
		4. A = rol(A,30)
		// now the hashes are in the order of D,E,A,B,C
	
		These operations are distributed into the following 2 macro definitions RR0 and RR1.	

	*/

	.macro	RR0				// input arguments : FN, A, B, C, D, E, i
	$0		$2, $3, $4		// T1 = FN(B,C,D)
	add		WK($6), $5		// E + WK(i)
	rol		$$30, $2		// B = rol(B,30)
	mov		$1, T2			// T2 = A
	add		WK($6+1), $4	// D + WK(i+1)
	rol		$$5, T2			// rol(A,5)
	add		T1, $5			// E = FN(B,C,D) + E + WK(i)
	.endm

	.macro	RR1
	add		$5, T2			// T2 = FN(B,C,D) + E + rol(A,5) + WK(i)
	mov		T2, $5			// E = FN(B,C,D) + E + rol(A,5) + WK(i)
	rol		$$5, T2			// rol(E,5)
	add		T2, $4			// D + WK(i+1) + rol(E,5)
	$0		$1, $2, $3		// FN(A,B,C)
	add		T1, $4			// D = FN(A,B,C) + D + rol(E,5) + WK(i+1)
	rol		$$30, $1		// A = rol(A,30)
	.endm



	/*

		The following macro definitions are used to expand code for the per-block sha1 operation.

			INITIAL_W_PRECALC_ssse3	: BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack memory
			INTERNAL_ssse3 : updating W (16:79) and update the digests A/B/C/D/E (i=0:63, based on W+K stored in the stack memory) 
			ENDING : finishing up update the digests A/B/C/D/E (i=64:79)

		For multiple-block sha1 operation (Multiple_Blocks = 1), INITIAL_W_PRECALC_ssse3 and ENDING are combined
		into 1 macro definition for software pipeling.

			SOFTWARE_PIPELINING_ssse3 : BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack, and finishing up update the digests A/B/C/D/E (i=64:79) 

		assume cnt (the number of blocks)  >= 1, the main code body should look like

		INITIAL_W_PRECALC_ssse3				// W = big_endian_load and pre-compute W+K (i=0:15)
		do {
			INTERNAL_ssse3					// update W(i=16:79), and update hash digests A/B/C/D/E (i=0:63)
			cnt--;
			if (cnt==0) break;
			BUFFER_PTR += 64;
			SOFTWARE_PIPELINING_ssse3;		// update hash digests A/B/C/D/E (i=64:79) + W = big_endian_load and pre-compute W+K (i=0:15)
		}
		ENDING								// update hash digests A/B/C/D/E (i=64:79)

	*/

	#define	W_PRECALC_16_31_0	W_PRECALC_16_31_0_ssse3
	#define	W_PRECALC_32_79_0	W_PRECALC_32_79_0_ssse3
	#define	W_PRECALC_32_79_0_i386	W_PRECALC_32_79_0_i386_ssse3


	.macro	INITIAL_W_PRECALC_ssse3			// BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack memory	

	// i=0 	: W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K

	// i=4	: W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K

	.endm


	.macro	INTERNAL_ssse3					// updating W (16:79) and update the digests A/B/C/D/E (i=0:63, based on W+K stored in the stack memory)

	// i=16 : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_16_31_0	W0,W28,W24,W20,W16
	RR0					F1,A,B,C,D,E,0
	W_PRECALC_16_31_1	W0,W16
	RR1					F1,A,B,C,D,E,0
	W_PRECALC_16_31_2	W16
	RR0					F1,D,E,A,B,C,2
	W_PRECALC_16_31_3	W16, 2, 0
	RR1					F1,D,E,A,B,C,2

	// i=20 : W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_16_31_0	W28,W24,W20,W16,W12
	RR0					F1,B,C,D,E,A,4
	W_PRECALC_16_31_1	W28,W12
	RR1					F1,B,C,D,E,A,4
	W_PRECALC_16_31_2	W12
	RR0					F1,E,A,B,C,D,6
	W_PRECALC_16_31_3	W12, 6, 16
	RR1					F1,E,A,B,C,D,6

	// i=24 : W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_16_31_0	W24,W20,W16,W12,W8
	RR0					F1,C,D,E,A,B,8
	W_PRECALC_16_31_1	W24,W8
	RR1					F1,C,D,E,A,B,8
	W_PRECALC_16_31_2	W8
	RR0					F1,A,B,C,D,E,10
	W_PRECALC_16_31_3	W8,10,16
	RR1					F1,A,B,C,D,E,10

	// i=28 : W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_16_31_0	W20,W16,W12,W8,W4
	RR0					F1,D,E,A,B,C,12
	W_PRECALC_16_31_1	W20,W4
	RR1					F1,D,E,A,B,C,12
	W_PRECALC_16_31_2	W4
	RR0					F1,B,C,D,E,A,14
	W_PRECALC_16_31_3	W4,14,16
	RR1					F1,B,C,D,E,A,14

	// i=32 : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F1,E,A,B,C,D,16
	W_PRECALC_32_79_1	W16,W0
	RR1					F1,E,A,B,C,D,16
	W_PRECALC_32_79_2	W0
	RR0					F1,C,D,E,A,B,18
	W_PRECALC_32_79_3	W0,18,16
	RR1					F1,C,D,E,A,B,18

	// starting using F2	

	// i=36 : W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F2,A,B,C,D,E,20
	W_PRECALC_32_79_1	W12,W28
	RR1					F2,A,B,C,D,E,20
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F2,D,E,A,B,C,22
	W_PRECALC_32_79_3	W28,22,16
	RR1					F2,D,E,A,B,C,22

	// i=40 : W20,W16,W12,W8,W4,W0,W28,W24	
	#undef  K_XMM
    #define K_XMM   32
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F2,B,C,D,E,A,24
	W_PRECALC_32_79_1	W8,W24
	RR1					F2,B,C,D,E,A,24
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F2,E,A,B,C,D,26
	W_PRECALC_32_79_3	W24,26,K_XMM
	RR1					F2,E,A,B,C,D,26

	// i=44 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F2,C,D,E,A,B,28
	W_PRECALC_32_79_1	W4,W20
	RR1					F2,C,D,E,A,B,28
	W_PRECALC_32_79_2	W20
	RR0					F2,A,B,C,D,E,30
	W_PRECALC_32_79_3	W20,30,K_XMM
	RR1					F2,A,B,C,D,E,30

	// i=48 : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_32_79_0	W12,W24,W20,W16
	RR0					F2,D,E,A,B,C,32
	W_PRECALC_32_79_1	W0,W16
	RR1					F2,D,E,A,B,C,32
	W_PRECALC_32_79_2	W16
	RR0					F2,B,C,D,E,A,34
	W_PRECALC_32_79_3	W16,34,K_XMM
	RR1					F2,B,C,D,E,A,34

	// i=52 : W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_32_79_0	W8,W20,W16,W12
	RR0					F2,E,A,B,C,D,36
	W_PRECALC_32_79_1	W28,W12
	RR1					F2,E,A,B,C,D,36
	W_PRECALC_32_79_2	W12
	RR0					F2,C,D,E,A,B,38
	W_PRECALC_32_79_3	W12,38,K_XMM
	RR1					F2,C,D,E,A,B,38

	// starting using F3	

	// i=56 : W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_32_79_0	W4,W16,W12,W8
	RR0					F3,A,B,C,D,E,40
	W_PRECALC_32_79_1	W24,W8
	RR1					F3,A,B,C,D,E,40
	W_PRECALC_32_79_2	W8
	RR0					F3,D,E,A,B,C,42
	W_PRECALC_32_79_3	W8,42,K_XMM
	RR1					F3,D,E,A,B,C,42

	// i=60 : W0,W28,W24,W20,W16,W12,W8,W4
	#undef	K_XMM
	#define	K_XMM	48
	W_PRECALC_32_79_0	W0,W12,W8,W4
	RR0					F3,B,C,D,E,A,44
	W_PRECALC_32_79_1	W20,W4
	RR1					F3,B,C,D,E,A,44
	W_PRECALC_32_79_2	W4
	RR0					F3,E,A,B,C,D,46
	W_PRECALC_32_79_3	W4,46,K_XMM
	RR1					F3,E,A,B,C,D,46

	// i=64 : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F3,C,D,E,A,B,48
	W_PRECALC_32_79_1	W16,W0
	RR1					F3,C,D,E,A,B,48
	W_PRECALC_32_79_2	W0
	RR0					F3,A,B,C,D,E,50
	W_PRECALC_32_79_3	W0,50,K_XMM
	RR1					F3,A,B,C,D,E,50

	// i=68 : W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F3,D,E,A,B,C,52
	W_PRECALC_32_79_1	W12,W28
	RR1					F3,D,E,A,B,C,52
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F3,B,C,D,E,A,54
	W_PRECALC_32_79_3	W28,54,K_XMM
	RR1					F3,B,C,D,E,A,54

	// i=72 : W20,W16,W12,W8,W4,W0,W28,W24
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F3,E,A,B,C,D,56
	W_PRECALC_32_79_1	W8,W24
	RR1					F3,E,A,B,C,D,56
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F3,C,D,E,A,B,58
	W_PRECALC_32_79_3	W24,58,K_XMM
	RR1					F3,C,D,E,A,B,58

	// starting using F4	

	// i=76 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F4,A,B,C,D,E,60
	W_PRECALC_32_79_1	W4,W20
	RR1					F4,A,B,C,D,E,60
	W_PRECALC_32_79_2	W20
	RR0					F4,D,E,A,B,C,62
	W_PRECALC_32_79_3	W20,62,K_XMM
	RR1					F4,D,E,A,B,C,62

	.endm

	.macro	SOFTWARE_PIPELINING_ssse3
	// i=0  : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	RR0					F4,B,C,D,E,A,64
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	RR1					F4,B,C,D,E,A,64
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	RR0					F4,E,A,B,C,D,66
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K
	RR1					F4,E,A,B,C,D,66

	// i=4  : W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	RR0					F4,C,D,E,A,B,68
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	RR1					F4,C,D,E,A,B,68
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	RR0					F4,A,B,C,D,E,70
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K[0]
	RR1					F4,A,B,C,D,E,70

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	RR0					F4,D,E,A,B,C,72
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	RR1					F4,D,E,A,B,C,72
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	RR0					F4,B,C,D,E,A,74
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K
	RR1					F4,B,C,D,E,A,74

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	RR0					F4,E,A,B,C,D,76
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	RR1					F4,E,A,B,C,D,76
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	RR0					F4,C,D,E,A,B,78
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K
	RR1					F4,C,D,E,A,B,78
	.endm


	#undef	W_PRECALC_16_31_0
	#undef	W_PRECALC_32_79_0
	#undef	W_PRECALC_32_79_0_i386



	/* 

		The following are 3 macro definitions that are no-ssse3 variants of the previous 3 macro definitions.

		INITIAL_W_PRECALC_nossse3
		INTERNAL_nossse3
		SOFTWARE_PIPELINING_nossse3
		
		They will be used in a sha1 code main body definition that will be used for system without ssse3 support.	

	*/

	#define	W_PRECALC_16_31_0	W_PRECALC_16_31_0_nossse3
	#define	W_PRECALC_32_79_0	W_PRECALC_32_79_0_nossse3
	#define	W_PRECALC_32_79_0_i386	W_PRECALC_32_79_0_i386_nossse3


	.macro	INITIAL_W_PRECALC_nossse3

	// i=0 	: W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K

	// i=4	: W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K

	.endm


	.macro	INTERNAL_nossse3
	// i=16
	// circular buffer : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_16_31_0	W0,W28,W24,W20,W16
	RR0					F1,A,B,C,D,E,0
	W_PRECALC_16_31_1	W0,W16
	RR1					F1,A,B,C,D,E,0
	W_PRECALC_16_31_2	W16
	RR0					F1,D,E,A,B,C,2
	W_PRECALC_16_31_3	W16, 2, 0
	RR1					F1,D,E,A,B,C,2

	// i=20,
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_16_31_0	W28,W24,W20,W16,W12
	RR0					F1,B,C,D,E,A,4
	W_PRECALC_16_31_1	W28,W12
	RR1					F1,B,C,D,E,A,4

	W_PRECALC_16_31_2	W12
	RR0					F1,E,A,B,C,D,6
	W_PRECALC_16_31_3	W12, 6, 16
	RR1					F1,E,A,B,C,D,6

	// i=24,
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_16_31_0	W24,W20,W16,W12,W8
	RR0					F1,C,D,E,A,B,8
	W_PRECALC_16_31_1	W24,W8
	RR1					F1,C,D,E,A,B,8

	W_PRECALC_16_31_2	W8
	RR0					F1,A,B,C,D,E,10
	W_PRECALC_16_31_3	W8,10,16
	RR1					F1,A,B,C,D,E,10

	// i=28
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_16_31_0	W20,W16,W12,W8,W4
	RR0					F1,D,E,A,B,C,12
	W_PRECALC_16_31_1	W20,W4
	RR1					F1,D,E,A,B,C,12

	W_PRECALC_16_31_2	W4
	RR0					F1,B,C,D,E,A,14
	W_PRECALC_16_31_3	W4,14,16
	RR1					F1,B,C,D,E,A,14

	//i=32
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F1,E,A,B,C,D,16
	W_PRECALC_32_79_1	W16,W0
	RR1					F1,E,A,B,C,D,16
	W_PRECALC_32_79_2	W0
	RR0					F1,C,D,E,A,B,18
	W_PRECALC_32_79_3	W0,18,16
	RR1					F1,C,D,E,A,B,18

	//i=36
	// W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F2,A,B,C,D,E,20
	W_PRECALC_32_79_1	W12,W28
	RR1					F2,A,B,C,D,E,20
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F2,D,E,A,B,C,22
	W_PRECALC_32_79_3	W28,22,16
	RR1					F2,D,E,A,B,C,22

	//i=40
	#undef  K_XMM
    #define K_XMM   32
	// W20,W16,W12,W8,W4,W0,W28,W24	
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F2,B,C,D,E,A,24
	W_PRECALC_32_79_1	W8,W24
	RR1					F2,B,C,D,E,A,24
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F2,E,A,B,C,D,26
	W_PRECALC_32_79_3	W24,26,K_XMM
	RR1					F2,E,A,B,C,D,26

	//i=44
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F2,C,D,E,A,B,28
	W_PRECALC_32_79_1	W4,W20
	RR1					F2,C,D,E,A,B,28
	W_PRECALC_32_79_2	W20
	RR0					F2,A,B,C,D,E,30
	W_PRECALC_32_79_3	W20,30,K_XMM
	RR1					F2,A,B,C,D,E,30

	//i=48
	// W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_32_79_0	W12,W24,W20,W16
	RR0					F2,D,E,A,B,C,32
	W_PRECALC_32_79_1	W0,W16
	RR1					F2,D,E,A,B,C,32
	W_PRECALC_32_79_2	W16
	RR0					F2,B,C,D,E,A,34
	W_PRECALC_32_79_3	W16,34,K_XMM
	RR1					F2,B,C,D,E,A,34

	//i=52
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_32_79_0	W8,W20,W16,W12
	RR0					F2,E,A,B,C,D,36
	W_PRECALC_32_79_1	W28,W12
	RR1					F2,E,A,B,C,D,36
	W_PRECALC_32_79_2	W12
	RR0					F2,C,D,E,A,B,38
	W_PRECALC_32_79_3	W12,38,K_XMM
	RR1					F2,C,D,E,A,B,38

	//i=56
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_32_79_0	W4,W16,W12,W8
	RR0					F3,A,B,C,D,E,40
	W_PRECALC_32_79_1	W24,W8
	RR1					F3,A,B,C,D,E,40
	W_PRECALC_32_79_2	W8
	RR0					F3,D,E,A,B,C,42
	W_PRECALC_32_79_3	W8,42,K_XMM
	RR1					F3,D,E,A,B,C,42

	//i=60
	#undef	K_XMM
	#define	K_XMM	48
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_32_79_0	W0,W12,W8,W4
	RR0					F3,B,C,D,E,A,44
	W_PRECALC_32_79_1	W20,W4
	RR1					F3,B,C,D,E,A,44
	W_PRECALC_32_79_2	W4
	RR0					F3,E,A,B,C,D,46
	W_PRECALC_32_79_3	W4,46,K_XMM
	RR1					F3,E,A,B,C,D,46

	//i=64
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F3,C,D,E,A,B,48
	W_PRECALC_32_79_1	W16,W0
	RR1					F3,C,D,E,A,B,48
	W_PRECALC_32_79_2	W0
	RR0					F3,A,B,C,D,E,50
	W_PRECALC_32_79_3	W0,50,K_XMM
	RR1					F3,A,B,C,D,E,50

	//i=68
	// W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F3,D,E,A,B,C,52
	W_PRECALC_32_79_1	W12,W28
	RR1					F3,D,E,A,B,C,52
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F3,B,C,D,E,A,54
	W_PRECALC_32_79_3	W28,54,K_XMM
	RR1					F3,B,C,D,E,A,54

	//i=72
	// W20,W16,W12,W8,W4,W0,W28,W24
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F3,E,A,B,C,D,56
	W_PRECALC_32_79_1	W8,W24
	RR1					F3,E,A,B,C,D,56
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F3,C,D,E,A,B,58
	W_PRECALC_32_79_3	W24,58,K_XMM
	RR1					F3,C,D,E,A,B,58

	// starting using F4	

	//i=76
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F4,A,B,C,D,E,60
	W_PRECALC_32_79_1	W4,W20
	RR1					F4,A,B,C,D,E,60
	W_PRECALC_32_79_2	W20
	RR0					F4,D,E,A,B,C,62
	W_PRECALC_32_79_3	W20,62,K_XMM
	RR1					F4,D,E,A,B,C,62

	.endm

	.macro	SOFTWARE_PIPELINING_nossse3
	// i=0  : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	RR0					F4,B,C,D,E,A,64
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	RR1					F4,B,C,D,E,A,64
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	RR0					F4,E,A,B,C,D,66
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K
	RR1					F4,E,A,B,C,D,66

	// i=4  : W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	RR0					F4,C,D,E,A,B,68
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	RR1					F4,C,D,E,A,B,68
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	RR0					F4,A,B,C,D,E,70
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K[0]
	RR1					F4,A,B,C,D,E,70

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	RR0					F4,D,E,A,B,C,72
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	RR1					F4,D,E,A,B,C,72
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	RR0					F4,B,C,D,E,A,74
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K
	RR1					F4,B,C,D,E,A,74

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	RR0					F4,E,A,B,C,D,76
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	RR1					F4,E,A,B,C,D,76
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	RR0					F4,C,D,E,A,B,78
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K
	RR1					F4,C,D,E,A,B,78
	.endm

	.macro	ENDING		// finish up updating hash digests (i=64:79)
	//i=80
	RR0					F4,B,C,D,E,A,64
	RR1					F4,B,C,D,E,A,64
	RR0					F4,E,A,B,C,D,66
	RR1					F4,E,A,B,C,D,66

	//i=84
	RR0					F4,C,D,E,A,B,68
	RR1					F4,C,D,E,A,B,68
	RR0					F4,A,B,C,D,E,70
	RR1					F4,A,B,C,D,E,70

	//i=88
	RR0					F4,D,E,A,B,C,72
	RR1					F4,D,E,A,B,C,72
	RR0					F4,B,C,D,E,A,74
	RR1					F4,B,C,D,E,A,74

	//i=92
	RR0					F4,E,A,B,C,D,76
	RR1					F4,E,A,B,C,D,76
	RR0					F4,C,D,E,A,B,78
	RR1					F4,C,D,E,A,B,78
	.endm

	// load hash digests A,B,C,D,E from memory into registers
	.macro	LOAD_HASH
#if defined (__x86_64__)
	mov			(HASH_PTR), A
	mov			4(HASH_PTR), B
	mov			8(HASH_PTR), C
	mov			12(HASH_PTR), D
	mov			16(HASH_PTR), E
#else
    mov         HASH_PTR, T1
    mov         (T1), A
    mov         4(T1), B
    mov         8(T1), C
    mov         12(T1), D
    mov         16(T1), E
#endif
	.endm

	.macro	UPDATE_HASH
	add		$0, $1
	mov		$1, $0
	.endm

	.macro UPDATE_ALL_HASH	
#if defined (__x86_64__)
	UPDATE_HASH		(HASH_PTR), A
	UPDATE_HASH		4(HASH_PTR), B
	UPDATE_HASH		8(HASH_PTR), C
	UPDATE_HASH		12(HASH_PTR), D
	UPDATE_HASH		16(HASH_PTR), E
#else
    mov             HASH_PTR, T1
    UPDATE_HASH     (T1), A
    UPDATE_HASH     4(T1), B
    UPDATE_HASH     8(T1), C
    UPDATE_HASH     12(T1), D
    UPDATE_HASH     16(T1), E
#endif
	.endm


	/*
		 main sha1 code for system without ssse3 support
	*/

	.macro  SHA1_PIPELINED_MAIN_BODY_nossse3
	LOAD_HASH						// load initial hashes into A,B,C,D,E (registers)
	INITIAL_W_PRECALC_nossse3		// big_endian_load(W) and W+K (i=0:15)
	.align	4,0x90
0:
	INTERNAL_nossse3				// update W (i=16:79) and update ABCDE (i=0:63)	
#if Multiple_Blocks
#if defined(__x86_64__)
	add	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	sub	$$1, cnt					// pre-decrement cnt by 1
#else
	addl	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	subl	$$1, cnt					// pre-decrement cnt by 1
#endif
	jbe	1f							// if cnt <= 0, branch to finish off
	SOFTWARE_PIPELINING_nossse3		// update ABCDE (i=64:79) || big_endian_load(W) and W+K (i=0:15)
	UPDATE_ALL_HASH					// update output hashes
	jmp	0b							// repeat for next block
	.align	4,0x90
1:
#endif
	ENDING							// update ABCDE (i=64:79)
	UPDATE_ALL_HASH					// update output hashes
	.endm

	/*
		 main sha1 code for system with ssse3 support
	*/

	.macro  SHA1_PIPELINED_MAIN_BODY_ssse3
	LOAD_HASH						// load initial hashes into A,B,C,D,E
	INITIAL_W_PRECALC_ssse3			// big_endian_load(W) and W+K (i=0:15)
	.align	4,0x90
0:
	INTERNAL_ssse3					// update W (i=16:79) and update ABCDE (i=0:63)
#if Multiple_Blocks
#if defined(__x86_64__)
	add	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	sub	$$1, cnt					// pre-decrement cnt by 1
#else
	addl	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	subl	$$1, cnt					// pre-decrement cnt by 1
#endif
	jbe	1f							// if cnt <= 0, branch to finish off
	SOFTWARE_PIPELINING_ssse3		// update ABCDE (i=64:79) || big_endian_load(W) and W+K (i=0:15)
	UPDATE_ALL_HASH					// update output hashes
	jmp	0b							// repeat for next block
	.align	4,0x90
1:
#endif
	ENDING							// update ABCDE (i=64:79)
	UPDATE_ALL_HASH					// update output hashes
	.endm

#if	KERNEL
#include <i386/cpu_capabilities.h>
#else
#include <System/i386/cpu_capabilities.h>
#endif

	.text

	.globl _sha1_x86_compress_host_order
    .private_extern _sha1_x86_compress_host_order
_sha1_x86_compress_host_order:

	// detect SSSE3 and dispatch appropriate code branch
	#if defined __x86_64__
    	movq    __cpu_capabilities@GOTPCREL(%rip), %rax         // %rax -> __cpu_capabilities
    	mov     (%rax), %eax                                    // %eax = __cpu_capabilities
	#else       // i386
		#if defined KERNEL
    		leal    __cpu_capabilities, %eax                    // %eax -> __cpu_capabilities
    		mov     (%eax), %eax                                // %eax = __cpu_capabilities
		#else
    		mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
		#endif
	#endif
    test    $(kHasSupplementalSSE3), %eax
    je      _SHA1Compress_x86nossse3_host_order                    			// branch to no-ssse3 code


	// start the sha1 code with ssse3 support

	// save callee-save registers
#if defined (__x86_64__)
	push	%rbx
	push	%rbp
#else
    push    %ebx
    push    %ebp
    push    %esi
    push    %edi
#endif

	sub		$stack_size, sp					// allocate stack memory for use

	// save used xmm register if this is for kernel
#if	KERNEL
	xmov	%xmm0, 4*16(sp)
	xmov	%xmm1, 5*16(sp)
	xmov	%xmm2, 6*16(sp)
	xmov	%xmm3, 7*16(sp)
	xmov	%xmm4, 8*16(sp)
	xmov	%xmm5, 9*16(sp)
	xmov	%xmm6, 10*16(sp)
	xmov	%xmm7, 11*16(sp)
#if defined (__x86_64__)
	xmov	%xmm8, 12*16(sp)
	xmov	%xmm9, 13*16(sp)
	xmov	%xmm10, 14*16(sp)
#endif
#endif

#if defined (__x86_64__)

	// set up registers to free %edx/%edi/%esi for other use (ABCDE)
	mov		ctx, HASH_PTR
	mov		buf, BUFFER_PTR
#if Multiple_Blocks
	mov		%rdx, cnt
#endif
	lea		K_XMM_AR(%rip), K_BASE
	xmov	-16(K_BASE), XMM_SHUFB_BSWAP

#else	// __i386__

#if	KERNEL
    lea     K_XMM_AR, %eax
#else
	// Get address of 0 in R.
           call    0f          // Push program counter onto stack.
        0: pop     %eax      // Get program counter.
		lea	K_XMM_AR-0b(%eax), %eax
#endif
    mov     %eax, K_BASE
    xmov    -16(%eax), %xmm0
    xmov    %xmm0, XMM_SHUFB_BSWAP

#endif

	SHA1_PIPELINED_MAIN_BODY_ssse3

	// restore used xmm registers if this is for kernel
#if	KERNEL
	xmov	4*16(sp), %xmm0
	xmov	5*16(sp), %xmm1
	xmov	6*16(sp), %xmm2
	xmov	7*16(sp), %xmm3
	xmov	8*16(sp), %xmm4
	xmov	9*16(sp), %xmm5
	xmov	10*16(sp), %xmm6
	xmov	11*16(sp), %xmm7
#if defined (__x86_64__)
	xmov	12*16(sp), %xmm8
	xmov	13*16(sp), %xmm9
	xmov	14*16(sp), %xmm10
#endif
#endif

	add		$stack_size, sp		// deallocate stack memory

	// restore callee-save registers
#if defined (__x86_64__)
	pop		%rbp
	pop		%rbx
#else
    pop     %edi
    pop     %esi
    pop     %ebp
    pop     %ebx
#endif

	ret							// return

	// this is equivalent to the above function _SHA1Transform, but it does not use ssse3 instructions

	.globl _SHA1Compress_x86nossse3_host_order
	.private_extern	_SHA1Compress_x86nossse3_host_order
_SHA1Compress_x86nossse3_host_order:

	// push callee-save registers
#if defined (__x86_64__)
	push	%rbx
	push	%rbp
#else
    push    %ebx
    push    %ebp
    push    %esi
    push    %edi
#endif

	sub		$stack_size, sp			// allocate stack memory for local use

	// save used xmm registers if this is for kernel
#if	KERNEL
	xmov	%xmm0, 4*16(sp)
	xmov	%xmm1, 5*16(sp)
	xmov	%xmm2, 6*16(sp)
	xmov	%xmm3, 7*16(sp)
	xmov	%xmm4, 8*16(sp)
	xmov	%xmm5, 9*16(sp)
	xmov	%xmm6, 10*16(sp)
	xmov	%xmm7, 11*16(sp)
#if defined (__x86_64__)
	xmov	%xmm8, 12*16(sp)
	xmov	%xmm9, 13*16(sp)
#endif
#endif

#if defined (__x86_64__)

	// set up registers to free %edx/%edi/%esi for other use (ABCDE)
	mov		ctx, HASH_PTR
	mov		buf, BUFFER_PTR
#if Multiple_Blocks
	mov		%rdx, cnt
#endif
	lea		K_XMM_AR(%rip), K_BASE

#else	// __i386__

#if	KERNEL
    lea     K_XMM_AR, %eax
#else
	// Get address of 0 in R.
           call    0f          // Push program counter onto stack.
        0: pop     %eax      // Get program counter.
		lea	K_XMM_AR-0b(%eax), %eax
#endif
    mov     %eax, K_BASE

#endif

	SHA1_PIPELINED_MAIN_BODY_nossse3

	// restore used xmm registers if this is for kernel
#if	KERNEL
	xmov	4*16(sp), %xmm0
	xmov	5*16(sp), %xmm1
	xmov	6*16(sp), %xmm2
	xmov	7*16(sp), %xmm3
	xmov	8*16(sp), %xmm4
	xmov	9*16(sp), %xmm5
	xmov	10*16(sp), %xmm6
	xmov	11*16(sp), %xmm7
#if defined (__x86_64__)
	xmov	12*16(sp), %xmm8
	xmov	13*16(sp), %xmm9
#endif
#endif

	add		$stack_size, sp		// deallocate stack memory

	// restore callee-save registers
#if defined (__x86_64__)
	pop		%rbp
	pop		%rbx
#else
    pop     %edi
    pop     %esi
    pop     %ebp
    pop     %ebx
#endif

	ret							// return

	.const
	.align	4, 0x90	

#define K1 0x5a827999
#define K2 0x6ed9eba1
#define K3 0x8f1bbcdc
#define K4 0xca62c1d6

bswap_shufb_ctl:
    .long	0x00010203
    .long	0x04050607
    .long	0x08090a0b
    .long	0x0c0d0e0f

K_XMM_AR:
    .long	K1
	.long	K1
	.long	K1
	.long	K1
    .long	K2
	.long	K2
	.long	K2
	.long	K2
    .long	K3
	.long	K3
	.long	K3
	.long	K3
    .long	K4
	.long	K4
	.long	K4
	.long	K4


#endif	// architecture x86_64 or i386

Added Source/descriptors/digestDescriptors/vng_x86_sha1_descriptor/vng_x86_sha1LE.s.





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
/* 
 * Copyright (c) 2011 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* 	sha1edp.s : this file provides optimized x86_64 and i386 implementation of the sha1 function
	CoreOS - vector and numerics group
	cclee	6-21-10
	
	The implementation is based on the principle described in an Intel online article
	"Improving the Performance of the Secure Hash Algorithm (SHA-1)"
	http://software.intel.com/en-us/articles/improving-the-performance-of-the-secure-hash-algorithm-1/


	Update HASH[] by processing a one 64-byte block in MESSAGE[] can be represented by the following C function

void SHA1( int HASH[], int MESSAGE[] )
{
    int A[81], B[81], C[81], D[81], E[81];
    int W[80];

    int i, FN;

    A[0] = HASH[0]; 
    B[0] = HASH[1];
    C[0] = HASH[2];
    D[0] = HASH[3];
    E[0] = HASH[4];

    for ( i=0; i<80; ++i )
    {
        if ( i < 16 )
            W[i] = BIG_ENDIAN_LOAD( MESSAGE[i] );
        else
            W[i] = ROTATE_LEFT( W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1 );

        FN = F( i, B[i], C[i], D[i] );

        A[i+1] = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + W[i] + K(i);
        B[i+1] = A[i];
        C[i+1] = ROTATE_LEFT( B[i], 30 );
        D[i+1] = C[i];
        E[i+1] = D[i];
    }

    HASH[0] += A[80];
    HASH[1] += B[80];
    HASH[2] += C[80];
    HASH[3] += D[80];
    HASH[4] += E[80];
} 

	For i=0:15, W[i] is simply big-endian loading of MESSAGE[i]. For i=16:79, W[i] is updated according to W[i] = ROTATE_LEFT( W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1 );

	The approach (by Dean Gaudet) can be used to vectorize the computation of W[i] for i=16:79,

	1. done on 4 consequtive W[i] values in a single XMM register
    W[i  ] = (W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]) rol 1
    W[i+1] = (W[i-2] ^ W[i-7] ^ W[i-13] ^ W[i-15]) rol 1
    W[i+2] = (W[i-1] ^ W[i-6] ^ W[i-12] ^ W[i-14]) rol 1
    W[i+3] = (   0   ^ W[i-5] ^ W[i-11] ^ W[i-13]) rol 1

    2. this additional calculation unfortunately requires many additional operations
    W[i+3] ^= W[i] rol 1

    3. once we have 4 W[i] values in XMM we can also add four K values with one instruction
    W[i:i+3] += {K,K,K,K}

	Let W0 = {W[i] W[i+1] W[i+2] W[i+3]} be the current W-vector to be computed, W4 = {W[i-4] W[i-3] W[i-2] W[i-1]} be the previous vector, and so on
	The Dean Gaudet approach can be expressed as

	1. W0 = rotate_left(left_shift(W4,32) ^ W8 ^ left_shift(concatenate(W16,W12),64) ^ W16,1);
	2. W[i+3] ^= W[i] rol 1
	3. W0 += {K,K,K,K}

	For i>=32, the Intel online article suggests that (using a basic identity (X rol 1) rol 1 = X rol 2) the update equation is equivalent to

	1. W0 = rotate_left(left_shift(concatenate(W8,W4),64) ^ W16 ^ W28 ^ W32, 2); 

	Note:
	1. In total, we need 8 16-byte registers or memory for W0,W4,...,W28. W0 and W32 can be the same register or memory.
	2. The registers are used in a circular buffering mode. For example, we start with W28,W24,...,W0 (with W0 indicating the most recent 16-byte)
		i=0, W28,W24,...,W0
		i=4, W24,W20,...,W28
		i=8, W20,W16,...,W24
		.
		.
		and so forth.
	3. 2 ssse3 instructions are used in the Intel article, pshufb and palignr.
		a. pshufb is used to simplify the BIG_ENDIAN_LOAD operation 
		b. palignr is used to simplify the computation of left_shift(concatenate(W12,W8),64)
	4. we probe __cpu_capabilities to detect ssse3 support and dispatch code with ssse3 support when available.
	   If ssse3 is not supported, a suboptimal code (pshufb and palignr workaround) is dispatched. 

*/

/* the code can be compiled into single block (64 bytes) per call mode by setting Multiple_blocks to 0 */
#define	Multiple_Blocks	1

#if defined (__x86_64__) || defined(__i386__)		// x86_64 or i386 architectures

#if defined(__x86_64__)

	// set up for x86_64
#define	stack_size	(8+16*11+16*4)					// 8 (alignedment) + x0-x10 + 4 128-bits for intermediate WK(t) storage
#define	sp			%rsp							// unifying architectural stack pointer representation
#define	ctx			%rdi							// 1st input argument, will move to HASH_PTR (%r9)
#define	buf			%rsi							// 2nd input argument, will move to BUFFER_PTR (%r10) 
#define	cnt			%r11							// will copy from the 3rd input argument (%rdx)
#define K_BASE		%r8								// an aligned pointer to point to shufb reference numbers of table of K values
#define HASH_PTR	%r9								// pointer to Hash values (A,B,C,D,E)
#define BUFFER_PTR	%r10							// pointer to input blocks 

#else	// !__x86_64__

	// set up for i386 
#define stack_size	(12+16*2+16*11+16*4)			// 12-bytes (alignment) + extra 2 + 3 (W24/W28/XMM_SHUFB_BSWAP) + 8 (xmm0-xmm7) + 4 (WK(t))
#define	sp			%esp							// unifying architectural stack pointer representation
#define HASH_PTR	stack_size+16+4(sp)				// use 1st input argument from caller function, 16 for (esi/edi/ebx/ebp)
#define BUFFER_PTR	stack_size+16+8(sp)				// use 2nd input argument from caller function 
#define cnt			stack_size+16+12(sp)			// use 3rd input argument from caller function
#define K_BASE		stack_size-4(sp)				// use for K_BASE

#endif	// __x86_64__

// symbolizing registers or stack memory with algorithmic variables	W0,W4,...,W28 + W_TMP, W_TMP2, and XMM_SHUFB_BSWAP for code with ssse3 support

#define W_TMP  	%xmm0
#define W_TMP2 	%xmm1
#define W0  	%xmm2
#define W4  	%xmm3
#define W8  	%xmm4
#define W12 	%xmm5
#define W16 	%xmm6
#define W20 	%xmm7
#if defined(__x86_64__)
#define W24 	%xmm8
#define W28 	%xmm9
#define XMM_SHUFB_BSWAP %xmm10				// used only when ssse3 is supported
#else	// defined (__i386__)
#define W24     12*16(sp)
#define W28     13*16(sp)
#define XMM_SHUFB_BSWAP 14*16(sp)			// used only when ssse3 is supported 
#endif

#define	xmov	movaps						// aligned 16-byte move
#define	xmovu	movups						// unaligned 16-byte move

// intermediate hash variables
#define A %ecx
#define B %esi
#define C %edi
#define D %ebp
#define E %edx

// temp variables
#define T1 %eax
#define T2 %ebx

#define	WK(t)	(t&15)*4(sp)

	// int F1(int B, int C, int D) { return (D ^ ( B & (C ^ D)); }
	// result in T1
	.macro	F1
	mov	$1, T1
	xor	$2, T1
	and	$0, T1
	xor	$2, T1
	.endm

	// int F2(int B, int C, int D) { return (D ^ B ^ C); }
	// result in T1
	.macro	F2
	mov	$2, T1
	xor	$1, T1
	xor	$0, T1
	.endm

	// int F3(int B, int C, int D) { return (B & C) | (D & (B ^ C)); }
	// result in T1
	.macro	F3
		mov $1, T1
        mov $0, T2
        or  $0, T1
        and $1, T2
        and $2, T1
        or  T2, T1
	.endm

	// for i=60:79, F4 is identical to F2
	#define	F4	F2


	/*
		i=0:15, W[i] = BIG_ENDIAN_LOAD(MESSAGE[i]);

		with ssse3 support, this is achived via
		for (i=0;i<16;i+=4) {
			1. W_TMP = new 16 bytes from MESSAGE[]
			2. W_TMP = pshufb(W_TMP, XMM_SHUFB_BSWAP); save to W circular buffer for updating W 
			3. WTMP += {K,K,K,K};
			4. save quadruple W[i]+K[i] = W_TMP in the stack memory;
		}

		each step is represented in one of the following 4 macro definitions

	*/

	.macro	W_PRECALC_00_15_0_ssse3			// input argument $0 : 0/4/8/12
#if defined (__x86_64__)					// BUFFER_PTR is already an address register in x86_64
	xmovu	$0*4(BUFFER_PTR), W_TMP			// read 16-bytes into W_TMP, BUFFER_PTR possibly not 16-byte aligned
#else										// BUFFER_PTR is from the argument set up in the caller
	mov     BUFFER_PTR, T1					// T1 = BUFFER_PTR
    xmovu  $0*4(T1), W_TMP					// read 16-bytes into W_TMP, BUFFER_PTR possibly not 16-byte aligned
#endif
	.endm

	.macro	W_PRECALC_00_15_1_ssse3			// input argument $0 : current 16-bytes in the circular buffer, one of W0,W4,W8,...,W28
	pshufb	XMM_SHUFB_BSWAP, W_TMP			// convert W_TMP from little-endian into big-endian
	xmov	W_TMP, $0						// save W_TMP in the circular buffer
	.endm

	.macro	W_PRECALC_00_15_2				// K_BASE points to the current K quadruple.
#if defined (__x86_64__)					// K_BASE is already an address register in x86_64
	paddd	(K_BASE), W_TMP					// W_TMP += {K,K,K,K};
#else										// K_BASE is previously set up in the stack memory
	mov     K_BASE, T1						// T1 = K_BASE
    paddd   (T1), W_TMP						// W_TMP += {K,K,K,K};
#endif
	.endm

	.macro	W_PRECALC_00_15_3
	xmov	W_TMP, WK($0&~3)				// save quadruple W[i]+K in the stack memory, which would be used later for updating the hashes A/B/C/D/E
	.endm

	/*
		without ssse3 support, steps 1 and 2 need to be modified
		1. sequentially load 4 words into T1, bswap T1, and save it to 4-bytes in the stack space
		2. load the 16-bytes from the aligned stack memory into W_TMP
	*/

	.macro	W_PRECALC_00_15_0_nossse3		// input argument $0 : 0/4/8/12

#if	defined (__x86_64__)
	#define	BUFFERP	BUFFER_PTR
#else
	mov		BUFFER_PTR, T2					// copy BUFFER_PTR (from caller 2nd argument) to T2
	#define	BUFFERP	T2
#endif

	// load 1st word, bswap it, save it to stack
	mov		$0*4(BUFFERP), T1
	bswap	T1
	mov		T1, 14*16(sp)

	// load 2nd word, bswap it, save it to stack
	mov		4+$0*4(BUFFERP), T1
	bswap	T1
	mov		T1, 4+14*16(sp)

	// load 3rd word, bswap it, save it to stack
	mov		8+$0*4(BUFFERP), T1
	bswap	T1
	mov		T1, 8+14*16(sp)

	// load 4th word, bswap it, save it to stack
	mov		12+$0*4(BUFFERP), T1
	bswap	T1
	mov		T1, 12+14*16(sp)
	.endm

	.macro	W_PRECALC_00_15_1_nossse3 		// input argument $0 : current 16-bytes in the circular buffer, one of W0,W4,W8,...,W28
	xmov	14*16(sp), W_TMP				// load the bswapped 16-bytes from the aligned stack memory
	xmov	W_TMP, $0						// save W = W_TMP in the circular buffer
	.endm

	// rounds 16-31 compute W[0] using the vectorization approach by Dean Gaudet
	/*
	W[i  ] = (W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]) rol 1
    W[i+1] = (W[i-2] ^ W[i-7] ^ W[i-13] ^ W[i-15]) rol 1
    W[i+2] = (W[i-1] ^ W[i-6] ^ W[i-12] ^ W[i-14]) rol 1
    W[i+3] = (   0   ^ W[i-5] ^ W[i-11] ^ W[i-13]) rol 1

	W[i+3] ^= W[i] rol 1;	// this W[i] is already rol by 1, if we are taking from the intial W before rol 1, we should rol this by 2

	The operation (updating W and W+K) is scheduled as and divided into 4 steps

	0. W_tmp = W3; W = W14 ^ W8
	1. W = W3 ^ W8 ^ W14 ^ W16; W_TMP = W; W_TMP2 = (W[i] 0 0 0); 
	2. W_TMP = (W3 ^ W8 ^ W14 ^ W16) rol 1; split (W[i] 0 0 0) rol 2 in W_TMP2 and W
	3. W = W_TMP = W_TMP ^ W_TMP2 ^ W = (W3 ^ W8 ^ W14 ^ W16) rol 1 ^ (W[i] 0 0 0) rol 2; WK = W _TMP+K;  

	*/

	.macro	W_PRECALC_16_31_0_ssse3	// input arguments : W16,W12,W8,W4,W
	xmov	$1, $4					// W = W12
	palignr	$$8, $0, $4				// W = W14
	xmov	$3, W_TMP				// W_TMP = W4
	psrldq	$$4, W_TMP				// W_TMP = W3
	pxor	$2, $4					// W = W8 ^ W14	
	.endm

	.macro	W_PRECALC_16_31_1		// input arguments : W16,W
	pxor	$0, W_TMP				// W_TMP = W3 ^ W16
	pxor	W_TMP, $1				// W = W3 ^ W16 ^ W8 ^ W14
	xmov	$1, W_TMP2				// W_TMP2 = W3 ^ W16 ^ W8 ^ W14 
	xmov	$1, W_TMP				// W_TMP = W3 ^ W16 ^ W8 ^ W14
	pslldq	$$12, W_TMP2			// W_TMP2 = (W[i] 0 0 0)
	.endm

	.macro	W_PRECALC_16_31_2		// input argument : W
	psrld	$$31, $0				// (W3 ^ W16 ^ W8 ^ W14)>>31
	pslld	$$1, W_TMP				// (W3 ^ W16 ^ W8 ^ W14)<<1
	por		$0, W_TMP				// W_TMP = (W3 ^ W16 ^ W8 ^ W14) rol 1
	xmov	W_TMP2, $0				// copy W[i] at location of W[i+3]
	psrld	$$30, W_TMP2			// W_TMP2 = W[i] lower 2 bits after rol 2
	pslld	$$2, $0					// W = W[i] higher 30 bits after rol 2
	.endm

	.macro	W_PRECALC_16_31_3		// input arguments: W, i, K_XMM
#if defined (__i386__)
	mov     K_BASE, T1				// K_BASE is store in the stack memory for i386
#endif
	pxor	$0, W_TMP
	pxor	W_TMP2, W_TMP			// W_TMP = (W3 ^ W16 ^ W8 ^ W14) rol 1 ^ (W[i] 0 0 0) rol 2
	xmov	W_TMP, $0				// save W = W_TMP in the W circular buffer
#if defined (__x86_64__)
	paddd	$2(K_BASE), W_TMP		// W+K
#else
    paddd   $2(T1), W_TMP			// W+K
#endif
	xmov	W_TMP, WK($1&~3)		// save WK = W+K for later update of the hashes A/B/C/D/E
	.endm

	// the following is a variant of W_PRECALC_16_31_0_ssse3 to be used for system without ssse3, palignr is replaced with 4 instructions

	.macro	W_PRECALC_16_31_0_nossse3	// input arguments : W16,W12,W8,W4,W
	xmov	$1, $4						// W = W12 = (w9 w10 w11 w12)

	// the following is a wrokaround for palignr
	xmov	$0, W_TMP					// W16 = (w13 w14 w15 w16)
	pslldq	$$8, $4						// shift left to make (w11 w12 0 0)
	psrldq	$$8, W_TMP					// shift right to make (0 0 w13 w14)
	por		W_TMP, $4					// W = W14 = (w11 w12 w13 w14)

	xmov	$3, W_TMP					// W_TMP = W4 = (w1 w2 w3 w4)
	psrldq	$$4, W_TMP					// W_TMP = W3 = (0 w1 w2 w3)
	pxor	$2, $4						// W = W8 ^ W14	
	.endm

	/* rounds 32-79 compute W und W+K iusing the vectorization approach from the Intel article

		W = rotate_left(left_shift(concatenate(W8,W4),64) ^ W16 ^ W28 ^ W32, 2);

		where left_shift(concatenate(W8,W4),64) is equivalent to W6. Note also that W32 and W use the same register.


	0. W_tmp = W6; W = W28 ^ W32;
	1. W = W_tmp = W6 ^ W16 ^ W28 ^ W32;
	2. W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2;
	3. W = W_Tmp; WK = W_tmp + K;

	*/


	.macro	W_PRECALC_32_79_0_ssse3		// inputr arguments : W28,W8,W4,W
	xmov	$2, W_TMP					// (w1 w2 w3 w4)
	pxor	$0, $3						// W = W28 ^ W32;
	palignr	$$8, $1, W_TMP				// W_tmp = (w3 w4 w5 w6) = W6;
	.endm

	// the following is a variant and will be used for system without ssse3 support
	.macro	W_PRECALC_32_79_0_nossse3	// input arguments : W28,W8,W4,W
	xmov	$2, W_TMP					// (w1 w2 w3 w4)
	xmov    $1, W_TMP2					// (w5 w6 w7 w8)
	pxor	$0, $3						// W = W28 ^ W32
	pslldq	$$8, W_TMP					// (w3 w4 0 0)
	psrldq	$$8, W_TMP2					// (0 0 w5 w6)
	por		W_TMP2, W_TMP				// W_tmp = (w3 w4 w5 w6) = W6
	.endm

	// this is a variant of W_PRECALC_32_79_0_ssse3 for i386 (as W24/W28 are stored in memory, not in registers)
	.macro  W_PRECALC_32_79_0_i386_ssse3	// input arguments : W28,W8,W4,W
    xmov    $3, W_TMP						// W32
    pxor    $0, W_TMP						// W28 ^ W32
    xmov    W_TMP, $3						// W = W28 ^ W32;
    xmov    $2, W_TMP						// W4
    palignr $$8, $1, W_TMP					// W_tmp = (w3 w4 w5 w6) = W6;
    .endm

	// this is a variant of W_PRECALC_32_79_0_nossse3 for i386 (as W24/W28 are stored in memory, not in registers)
	.macro  W_PRECALC_32_79_0_i386_nossse3  // input arguments : W28,W8,W4,W
    xmov    $3, W_TMP						// W32
    pxor    $0, W_TMP						// W28 ^ W32
    xmov    W_TMP, $3						// W = W28 ^ W32
    xmov    $2, W_TMP						// W4 = (w1 w2 w3 w4)
	xmov    $1, W_TMP2						// W8 = (w5 w6 w7 w8)
	pslldq	$$8, W_TMP						// (w3 w4 0 0)
	psrldq	$$8, W_TMP2						// (0 0 w5 w6)
	por		W_TMP2, W_TMP					// W_tmp = (w3 w4 w5 w6) = W6
    .endm

	.macro	W_PRECALC_32_79_1			// input arguments : W16,W
	pxor	$0, W_TMP					// W_tmp = W6 ^ W16
	pxor	$1, W_TMP					// W_tmp = W6 ^ W16 ^ W28 ^ W32
	xmov	W_TMP, $1					// W = W_tmp = W6 ^ W16 ^ W28 ^ W32
	.endm

	.macro	W_PRECALC_32_79_2			// input argument : W
	psrld	$$30, $0					// W >> 30
	pslld	$$2, W_TMP					// W << 2
	por		$0, W_TMP					// W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2
	.endm

	// this is a variant of W_PRECALC_32_79_2 for i386 (as W24/W28 are stored in memory, not in registers)
	// this should be used when the input is either W24 or W28 on i386 architecture
    .macro  W_PRECALC_32_79_2_i386  	// input argument : W
    xmov    $0, W_TMP2					// W
    psrld   $$30, W_TMP2				// W >> 30
    xmov    W_TMP2, $0					// save (W >> 30) at W
    pslld   $$2, W_TMP					// W_tmp << 2
    por     $0, W_TMP					// W_tmp = (W6 ^ W16 ^ W28 ^ W32) rol 2
    .endm

	.macro	W_PRECALC_32_79_3			// input argument W, i, K_XMM
#if defined (__x86_64__)
	xmov	W_TMP, $0					// W = (W6 ^ W16 ^ W28 ^ W32) rol 2
	paddd	$2(K_BASE), W_TMP			// W + K
	xmov	W_TMP, WK($1&~3)			// write W+K
#else
    mov     K_BASE, T1					// T1 = K_BASE (which is in the caller argument)
    xmov    W_TMP, $0					// W = (W6 ^ W16 ^ W28 ^ W32) rol 2
    paddd   $2(T1), W_TMP				// W_tmp = W + K
    xmov    W_TMP, WK($1&~3)			// write WK
#endif
	.endm


	/* The hash update operation is completed by the following statements.

		A[i+1] = FN + E[i] + ROTATE_LEFT( A[i], 5 ) + WK(i);
        B[i+1] = A[i];
        C[i+1] = ROTATE_LEFT( B[i], 30 );
        D[i+1] = C[i];
        E[i+1] = D[i];

		Suppose we start with A0,B0,C0,D0,E0. The 1st iteration can be expressed as follows:

		A1 = FN + E0 + rol(A0,5) + WK;
		B1 = A0;
		C1 = rol(B0, 30);
		D1 = C0;
		E1 = D0;

		to avoid excessive memory movement between registers, 
			1. A1 = FN + E0 + rol(A0,5) + WK; can be temporarily saved in E0, 
			2. C1 = rol(B0,30) can be temporarily saved in B0. 

		Therefore, ignoring the time index, the update operation is equivalent to
			1. E = FN(B,C,D) + E + rol(A,5) + WK(i)
			2. B = rol(B,30)
			3. the hashes are now stored in the order of E,A,B,C,D


		To pack 2 hash update operations in 1 iteration, starting with A,B,C,D,E
		1. E = FN(B,C,D) + E + rol(A,5) + WK(i)
		2. B = rol(B,30)
		// now the hashes are in the order of E,A,B,C,D
		3. D = FN(A,B,C) + D + rol(E,5) + WK(i+1)
		4. A = rol(A,30)
		// now the hashes are in the order of D,E,A,B,C
	
		These operations are distributed into the following 2 macro definitions RR0 and RR1.	

	*/

	.macro	RR0				// input arguments : FN, A, B, C, D, E, i
	$0		$2, $3, $4		// T1 = FN(B,C,D)
	add		WK($6), $5		// E + WK(i)
	rol		$$30, $2		// B = rol(B,30)
	mov		$1, T2			// T2 = A
	add		WK($6+1), $4	// D + WK(i+1)
	rol		$$5, T2			// rol(A,5)
	add		T1, $5			// E = FN(B,C,D) + E + WK(i)
	.endm

	.macro	RR1
	add		$5, T2			// T2 = FN(B,C,D) + E + rol(A,5) + WK(i)
	mov		T2, $5			// E = FN(B,C,D) + E + rol(A,5) + WK(i)
	rol		$$5, T2			// rol(E,5)
	add		T2, $4			// D + WK(i+1) + rol(E,5)
	$0		$1, $2, $3		// FN(A,B,C)
	add		T1, $4			// D = FN(A,B,C) + D + rol(E,5) + WK(i+1)
	rol		$$30, $1		// A = rol(A,30)
	.endm



	/*

		The following macro definitions are used to expand code for the per-block sha1 operation.

			INITIAL_W_PRECALC_ssse3	: BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack memory
			INTERNAL_ssse3 : updating W (16:79) and update the digests A/B/C/D/E (i=0:63, based on W+K stored in the stack memory) 
			ENDING : finishing up update the digests A/B/C/D/E (i=64:79)

		For multiple-block sha1 operation (Multiple_Blocks = 1), INITIAL_W_PRECALC_ssse3 and ENDING are combined
		into 1 macro definition for software pipeling.

			SOFTWARE_PIPELINING_ssse3 : BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack, and finishing up update the digests A/B/C/D/E (i=64:79) 

		assume cnt (the number of blocks)  >= 1, the main code body should look like

		INITIAL_W_PRECALC_ssse3				// W = big_endian_load and pre-compute W+K (i=0:15)
		do {
			INTERNAL_ssse3					// update W(i=16:79), and update hash digests A/B/C/D/E (i=0:63)
			cnt--;
			if (cnt==0) break;
			BUFFER_PTR += 64;
			SOFTWARE_PIPELINING_ssse3;		// update hash digests A/B/C/D/E (i=64:79) + W = big_endian_load and pre-compute W+K (i=0:15)
		}
		ENDING								// update hash digests A/B/C/D/E (i=64:79)

	*/

	#define	W_PRECALC_00_15_0	W_PRECALC_00_15_0_ssse3
	#define	W_PRECALC_00_15_1	W_PRECALC_00_15_1_ssse3
	#define	W_PRECALC_16_31_0	W_PRECALC_16_31_0_ssse3
	#define	W_PRECALC_32_79_0	W_PRECALC_32_79_0_ssse3
	#define	W_PRECALC_32_79_0_i386	W_PRECALC_32_79_0_i386_ssse3


	.macro	INITIAL_W_PRECALC_ssse3			// BIG_ENDIAN_LOAD(64 bytes block) into W (i=0:15) and store W+K into the stack memory	

	// i=0 	: W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K

	// i=4	: W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K

	.endm


	.macro	INTERNAL_ssse3					// updating W (16:79) and update the digests A/B/C/D/E (i=0:63, based on W+K stored in the stack memory)

	// i=16 : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_16_31_0	W0,W28,W24,W20,W16
	RR0					F1,A,B,C,D,E,0
	W_PRECALC_16_31_1	W0,W16
	RR1					F1,A,B,C,D,E,0
	W_PRECALC_16_31_2	W16
	RR0					F1,D,E,A,B,C,2
	W_PRECALC_16_31_3	W16, 2, 0
	RR1					F1,D,E,A,B,C,2

	// i=20 : W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_16_31_0	W28,W24,W20,W16,W12
	RR0					F1,B,C,D,E,A,4
	W_PRECALC_16_31_1	W28,W12
	RR1					F1,B,C,D,E,A,4
	W_PRECALC_16_31_2	W12
	RR0					F1,E,A,B,C,D,6
	W_PRECALC_16_31_3	W12, 6, 16
	RR1					F1,E,A,B,C,D,6

	// i=24 : W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_16_31_0	W24,W20,W16,W12,W8
	RR0					F1,C,D,E,A,B,8
	W_PRECALC_16_31_1	W24,W8
	RR1					F1,C,D,E,A,B,8
	W_PRECALC_16_31_2	W8
	RR0					F1,A,B,C,D,E,10
	W_PRECALC_16_31_3	W8,10,16
	RR1					F1,A,B,C,D,E,10

	// i=28 : W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_16_31_0	W20,W16,W12,W8,W4
	RR0					F1,D,E,A,B,C,12
	W_PRECALC_16_31_1	W20,W4
	RR1					F1,D,E,A,B,C,12
	W_PRECALC_16_31_2	W4
	RR0					F1,B,C,D,E,A,14
	W_PRECALC_16_31_3	W4,14,16
	RR1					F1,B,C,D,E,A,14

	// i=32 : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F1,E,A,B,C,D,16
	W_PRECALC_32_79_1	W16,W0
	RR1					F1,E,A,B,C,D,16
	W_PRECALC_32_79_2	W0
	RR0					F1,C,D,E,A,B,18
	W_PRECALC_32_79_3	W0,18,16
	RR1					F1,C,D,E,A,B,18

	// starting using F2	

	// i=36 : W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F2,A,B,C,D,E,20
	W_PRECALC_32_79_1	W12,W28
	RR1					F2,A,B,C,D,E,20
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F2,D,E,A,B,C,22
	W_PRECALC_32_79_3	W28,22,16
	RR1					F2,D,E,A,B,C,22

	// i=40 : W20,W16,W12,W8,W4,W0,W28,W24	
	#undef  K_XMM
    #define K_XMM   32
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F2,B,C,D,E,A,24
	W_PRECALC_32_79_1	W8,W24
	RR1					F2,B,C,D,E,A,24
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F2,E,A,B,C,D,26
	W_PRECALC_32_79_3	W24,26,K_XMM
	RR1					F2,E,A,B,C,D,26

	// i=44 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F2,C,D,E,A,B,28
	W_PRECALC_32_79_1	W4,W20
	RR1					F2,C,D,E,A,B,28
	W_PRECALC_32_79_2	W20
	RR0					F2,A,B,C,D,E,30
	W_PRECALC_32_79_3	W20,30,K_XMM
	RR1					F2,A,B,C,D,E,30

	// i=48 : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_32_79_0	W12,W24,W20,W16
	RR0					F2,D,E,A,B,C,32
	W_PRECALC_32_79_1	W0,W16
	RR1					F2,D,E,A,B,C,32
	W_PRECALC_32_79_2	W16
	RR0					F2,B,C,D,E,A,34
	W_PRECALC_32_79_3	W16,34,K_XMM
	RR1					F2,B,C,D,E,A,34

	// i=52 : W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_32_79_0	W8,W20,W16,W12
	RR0					F2,E,A,B,C,D,36
	W_PRECALC_32_79_1	W28,W12
	RR1					F2,E,A,B,C,D,36
	W_PRECALC_32_79_2	W12
	RR0					F2,C,D,E,A,B,38
	W_PRECALC_32_79_3	W12,38,K_XMM
	RR1					F2,C,D,E,A,B,38

	// starting using F3	

	// i=56 : W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_32_79_0	W4,W16,W12,W8
	RR0					F3,A,B,C,D,E,40
	W_PRECALC_32_79_1	W24,W8
	RR1					F3,A,B,C,D,E,40
	W_PRECALC_32_79_2	W8
	RR0					F3,D,E,A,B,C,42
	W_PRECALC_32_79_3	W8,42,K_XMM
	RR1					F3,D,E,A,B,C,42

	// i=60 : W0,W28,W24,W20,W16,W12,W8,W4
	#undef	K_XMM
	#define	K_XMM	48
	W_PRECALC_32_79_0	W0,W12,W8,W4
	RR0					F3,B,C,D,E,A,44
	W_PRECALC_32_79_1	W20,W4
	RR1					F3,B,C,D,E,A,44
	W_PRECALC_32_79_2	W4
	RR0					F3,E,A,B,C,D,46
	W_PRECALC_32_79_3	W4,46,K_XMM
	RR1					F3,E,A,B,C,D,46

	// i=64 : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F3,C,D,E,A,B,48
	W_PRECALC_32_79_1	W16,W0
	RR1					F3,C,D,E,A,B,48
	W_PRECALC_32_79_2	W0
	RR0					F3,A,B,C,D,E,50
	W_PRECALC_32_79_3	W0,50,K_XMM
	RR1					F3,A,B,C,D,E,50

	// i=68 : W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F3,D,E,A,B,C,52
	W_PRECALC_32_79_1	W12,W28
	RR1					F3,D,E,A,B,C,52
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F3,B,C,D,E,A,54
	W_PRECALC_32_79_3	W28,54,K_XMM
	RR1					F3,B,C,D,E,A,54

	// i=72 : W20,W16,W12,W8,W4,W0,W28,W24
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F3,E,A,B,C,D,56
	W_PRECALC_32_79_1	W8,W24
	RR1					F3,E,A,B,C,D,56
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F3,C,D,E,A,B,58
	W_PRECALC_32_79_3	W24,58,K_XMM
	RR1					F3,C,D,E,A,B,58

	// starting using F4	

	// i=76 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F4,A,B,C,D,E,60
	W_PRECALC_32_79_1	W4,W20
	RR1					F4,A,B,C,D,E,60
	W_PRECALC_32_79_2	W20
	RR0					F4,D,E,A,B,C,62
	W_PRECALC_32_79_3	W20,62,K_XMM
	RR1					F4,D,E,A,B,C,62

	.endm

	.macro	SOFTWARE_PIPELINING_ssse3
	// i=0  : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	RR0					F4,B,C,D,E,A,64
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	RR1					F4,B,C,D,E,A,64
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	RR0					F4,E,A,B,C,D,66
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K
	RR1					F4,E,A,B,C,D,66

	// i=4  : W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	RR0					F4,C,D,E,A,B,68
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	RR1					F4,C,D,E,A,B,68
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	RR0					F4,A,B,C,D,E,70
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K[0]
	RR1					F4,A,B,C,D,E,70

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	RR0					F4,D,E,A,B,C,72
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	RR1					F4,D,E,A,B,C,72
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	RR0					F4,B,C,D,E,A,74
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K
	RR1					F4,B,C,D,E,A,74

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	RR0					F4,E,A,B,C,D,76
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	RR1					F4,E,A,B,C,D,76
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	RR0					F4,C,D,E,A,B,78
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K
	RR1					F4,C,D,E,A,B,78
	.endm


	#undef	W_PRECALC_00_15_0
	#undef	W_PRECALC_00_15_1
	#undef	W_PRECALC_16_31_0
	#undef	W_PRECALC_32_79_0
	#undef	W_PRECALC_32_79_0_i386



	/* 

		The following are 3 macro definitions that are no-ssse3 variants of the previous 3 macro definitions.

		INITIAL_W_PRECALC_nossse3
		INTERNAL_nossse3
		SOFTWARE_PIPELINING_nossse3
		
		They will be used in a sha1 code main body definition that will be used for system without ssse3 support.	

	*/

	#define	W_PRECALC_00_15_0	W_PRECALC_00_15_0_nossse3
	#define	W_PRECALC_00_15_1	W_PRECALC_00_15_1_nossse3
	#define	W_PRECALC_16_31_0	W_PRECALC_16_31_0_nossse3
	#define	W_PRECALC_32_79_0	W_PRECALC_32_79_0_nossse3
	#define	W_PRECALC_32_79_0_i386	W_PRECALC_32_79_0_i386_nossse3


	.macro	INITIAL_W_PRECALC_nossse3

	// i=0 	: W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K

	// i=4	: W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K

	.endm


	.macro	INTERNAL_nossse3
	// i=16
	// circular buffer : W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_16_31_0	W0,W28,W24,W20,W16
	RR0					F1,A,B,C,D,E,0
	W_PRECALC_16_31_1	W0,W16
	RR1					F1,A,B,C,D,E,0
	W_PRECALC_16_31_2	W16
	RR0					F1,D,E,A,B,C,2
	W_PRECALC_16_31_3	W16, 2, 0
	RR1					F1,D,E,A,B,C,2

	// i=20,
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_16_31_0	W28,W24,W20,W16,W12
	RR0					F1,B,C,D,E,A,4
	W_PRECALC_16_31_1	W28,W12
	RR1					F1,B,C,D,E,A,4

	W_PRECALC_16_31_2	W12
	RR0					F1,E,A,B,C,D,6
	W_PRECALC_16_31_3	W12, 6, 16
	RR1					F1,E,A,B,C,D,6

	// i=24,
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_16_31_0	W24,W20,W16,W12,W8
	RR0					F1,C,D,E,A,B,8
	W_PRECALC_16_31_1	W24,W8
	RR1					F1,C,D,E,A,B,8

	W_PRECALC_16_31_2	W8
	RR0					F1,A,B,C,D,E,10
	W_PRECALC_16_31_3	W8,10,16
	RR1					F1,A,B,C,D,E,10

	// i=28
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_16_31_0	W20,W16,W12,W8,W4
	RR0					F1,D,E,A,B,C,12
	W_PRECALC_16_31_1	W20,W4
	RR1					F1,D,E,A,B,C,12

	W_PRECALC_16_31_2	W4
	RR0					F1,B,C,D,E,A,14
	W_PRECALC_16_31_3	W4,14,16
	RR1					F1,B,C,D,E,A,14

	//i=32
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F1,E,A,B,C,D,16
	W_PRECALC_32_79_1	W16,W0
	RR1					F1,E,A,B,C,D,16
	W_PRECALC_32_79_2	W0
	RR0					F1,C,D,E,A,B,18
	W_PRECALC_32_79_3	W0,18,16
	RR1					F1,C,D,E,A,B,18

	//i=36
	// W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F2,A,B,C,D,E,20
	W_PRECALC_32_79_1	W12,W28
	RR1					F2,A,B,C,D,E,20
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F2,D,E,A,B,C,22
	W_PRECALC_32_79_3	W28,22,16
	RR1					F2,D,E,A,B,C,22

	//i=40
	#undef  K_XMM
    #define K_XMM   32
	// W20,W16,W12,W8,W4,W0,W28,W24	
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F2,B,C,D,E,A,24
	W_PRECALC_32_79_1	W8,W24
	RR1					F2,B,C,D,E,A,24
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F2,E,A,B,C,D,26
	W_PRECALC_32_79_3	W24,26,K_XMM
	RR1					F2,E,A,B,C,D,26

	//i=44
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F2,C,D,E,A,B,28
	W_PRECALC_32_79_1	W4,W20
	RR1					F2,C,D,E,A,B,28
	W_PRECALC_32_79_2	W20
	RR0					F2,A,B,C,D,E,30
	W_PRECALC_32_79_3	W20,30,K_XMM
	RR1					F2,A,B,C,D,E,30

	//i=48
	// W12,W8,W4,W0,W28,W24,W20,W16
	W_PRECALC_32_79_0	W12,W24,W20,W16
	RR0					F2,D,E,A,B,C,32
	W_PRECALC_32_79_1	W0,W16
	RR1					F2,D,E,A,B,C,32
	W_PRECALC_32_79_2	W16
	RR0					F2,B,C,D,E,A,34
	W_PRECALC_32_79_3	W16,34,K_XMM
	RR1					F2,B,C,D,E,A,34

	//i=52
	// W8,W4,W0,W28,W24,W20,W16,W12
	W_PRECALC_32_79_0	W8,W20,W16,W12
	RR0					F2,E,A,B,C,D,36
	W_PRECALC_32_79_1	W28,W12
	RR1					F2,E,A,B,C,D,36
	W_PRECALC_32_79_2	W12
	RR0					F2,C,D,E,A,B,38
	W_PRECALC_32_79_3	W12,38,K_XMM
	RR1					F2,C,D,E,A,B,38

	//i=56
	// W4,W0,W28,W24,W20,W16,W12,W8
	W_PRECALC_32_79_0	W4,W16,W12,W8
	RR0					F3,A,B,C,D,E,40
	W_PRECALC_32_79_1	W24,W8
	RR1					F3,A,B,C,D,E,40
	W_PRECALC_32_79_2	W8
	RR0					F3,D,E,A,B,C,42
	W_PRECALC_32_79_3	W8,42,K_XMM
	RR1					F3,D,E,A,B,C,42

	//i=60
	#undef	K_XMM
	#define	K_XMM	48
	// W0,W28,W24,W20,W16,W12,W8,W4
	W_PRECALC_32_79_0	W0,W12,W8,W4
	RR0					F3,B,C,D,E,A,44
	W_PRECALC_32_79_1	W20,W4
	RR1					F3,B,C,D,E,A,44
	W_PRECALC_32_79_2	W4
	RR0					F3,E,A,B,C,D,46
	W_PRECALC_32_79_3	W4,46,K_XMM
	RR1					F3,E,A,B,C,D,46

	//i=64
	// W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_32_79_0	W28,W8,W4,W0
	RR0					F3,C,D,E,A,B,48
	W_PRECALC_32_79_1	W16,W0
	RR1					F3,C,D,E,A,B,48
	W_PRECALC_32_79_2	W0
	RR0					F3,A,B,C,D,E,50
	W_PRECALC_32_79_3	W0,50,K_XMM
	RR1					F3,A,B,C,D,E,50

	//i=68
	// W24,W20,W16,W12,W8,W4,W0,W28
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W24,W4,W0,W28
#else
	W_PRECALC_32_79_0_i386	W24,W4,W0,W28
#endif
	RR0					F3,D,E,A,B,C,52
	W_PRECALC_32_79_1	W12,W28
	RR1					F3,D,E,A,B,C,52
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W28
#else
	W_PRECALC_32_79_2_i386	W28
#endif
	RR0					F3,B,C,D,E,A,54
	W_PRECALC_32_79_3	W28,54,K_XMM
	RR1					F3,B,C,D,E,A,54

	//i=72
	// W20,W16,W12,W8,W4,W0,W28,W24
#if defined (__x86_64__)
	W_PRECALC_32_79_0	W20,W0,W28,W24
#else
	W_PRECALC_32_79_0_i386	W20,W0,W28,W24
#endif
	RR0					F3,E,A,B,C,D,56
	W_PRECALC_32_79_1	W8,W24
	RR1					F3,E,A,B,C,D,56
#if defined (__x86_64__)
	W_PRECALC_32_79_2	W24
#else
	W_PRECALC_32_79_2_i386	W24
#endif
	RR0					F3,C,D,E,A,B,58
	W_PRECALC_32_79_3	W24,58,K_XMM
	RR1					F3,C,D,E,A,B,58

	// starting using F4	

	//i=76
	// W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_32_79_0	W16,W28,W24,W20
	RR0					F4,A,B,C,D,E,60
	W_PRECALC_32_79_1	W4,W20
	RR1					F4,A,B,C,D,E,60
	W_PRECALC_32_79_2	W20
	RR0					F4,D,E,A,B,C,62
	W_PRECALC_32_79_3	W20,62,K_XMM
	RR1					F4,D,E,A,B,C,62

	.endm

	.macro	SOFTWARE_PIPELINING_nossse3
	// i=0  : W28,W24,W20,W16,W12,W8,W4,W0
	W_PRECALC_00_15_0	0					// W_TMP = (BUFFER_PTR)
	RR0					F4,B,C,D,E,A,64
	W_PRECALC_00_15_1	W0					// convert W_TMP to big-endian, and save W0 = W_TMP	
	RR1					F4,B,C,D,E,A,64
	W_PRECALC_00_15_2						// W_TMP = W0 + K
	RR0					F4,E,A,B,C,D,66
	W_PRECALC_00_15_3	3					// (sp) = W_TMP = W0 + K
	RR1					F4,E,A,B,C,D,66

	// i=4  : W24,W20,W16,W12,W8,W4,W0,W28
	W_PRECALC_00_15_0	4					// W_TMP = 16(BUFFER_PTR)
	RR0					F4,C,D,E,A,B,68
	W_PRECALC_00_15_1	W28					// convert W_TMP to big-endian, and save W28 = W_TMP	
	RR1					F4,C,D,E,A,B,68
	W_PRECALC_00_15_2						// W_TMP = W28 + K
	RR0					F4,A,B,C,D,E,70
	W_PRECALC_00_15_3	7					// 16(sp) = W_TMP = W28 + K[0]
	RR1					F4,A,B,C,D,E,70

	// i=8  : W20,W16,W12,W8,W4,W0,W28,W24
	W_PRECALC_00_15_0	8					// W_TMP = 32(BUFFER_PTR)
	RR0					F4,D,E,A,B,C,72
	W_PRECALC_00_15_1	W24					// convert W_TMP to big-endian, and save W24 = W_TMP
	RR1					F4,D,E,A,B,C,72
	W_PRECALC_00_15_2						// W_TMP = W24 + K
	RR0					F4,B,C,D,E,A,74
	W_PRECALC_00_15_3	11					// 32(sp) = W_TMP = W24 + K
	RR1					F4,B,C,D,E,A,74

	// i=12 : W16,W12,W8,W4,W0,W28,W24,W20
	W_PRECALC_00_15_0	12					// W_TMP = 48(BUFFER_PTR)
	RR0					F4,E,A,B,C,D,76
	W_PRECALC_00_15_1	W20					// convert W_TMP to big-endian, and save W20 = W_TMP	
	RR1					F4,E,A,B,C,D,76
	W_PRECALC_00_15_2						// W_TMP = W20 + K
	RR0					F4,C,D,E,A,B,78
	W_PRECALC_00_15_3	15					// 48(sp) = W_TMP = W20 + K
	RR1					F4,C,D,E,A,B,78
	.endm

	.macro	ENDING		// finish up updating hash digests (i=64:79)
	//i=80
	RR0					F4,B,C,D,E,A,64
	RR1					F4,B,C,D,E,A,64
	RR0					F4,E,A,B,C,D,66
	RR1					F4,E,A,B,C,D,66

	//i=84
	RR0					F4,C,D,E,A,B,68
	RR1					F4,C,D,E,A,B,68
	RR0					F4,A,B,C,D,E,70
	RR1					F4,A,B,C,D,E,70

	//i=88
	RR0					F4,D,E,A,B,C,72
	RR1					F4,D,E,A,B,C,72
	RR0					F4,B,C,D,E,A,74
	RR1					F4,B,C,D,E,A,74

	//i=92
	RR0					F4,E,A,B,C,D,76
	RR1					F4,E,A,B,C,D,76
	RR0					F4,C,D,E,A,B,78
	RR1					F4,C,D,E,A,B,78
	.endm

	// load hash digests A,B,C,D,E from memory into registers
	.macro	LOAD_HASH
#if defined (__x86_64__)
	mov			(HASH_PTR), A
	mov			4(HASH_PTR), B
	mov			8(HASH_PTR), C
	mov			12(HASH_PTR), D
	mov			16(HASH_PTR), E
#else
    mov         HASH_PTR, T1
    mov         (T1), A
    mov         4(T1), B
    mov         8(T1), C
    mov         12(T1), D
    mov         16(T1), E
#endif
	.endm

	.macro	UPDATE_HASH
	add		$0, $1
	mov		$1, $0
	.endm

	.macro UPDATE_ALL_HASH	
#if defined (__x86_64__)
	UPDATE_HASH		(HASH_PTR), A
	UPDATE_HASH		4(HASH_PTR), B
	UPDATE_HASH		8(HASH_PTR), C
	UPDATE_HASH		12(HASH_PTR), D
	UPDATE_HASH		16(HASH_PTR), E
#else
    mov             HASH_PTR, T1
    UPDATE_HASH     (T1), A
    UPDATE_HASH     4(T1), B
    UPDATE_HASH     8(T1), C
    UPDATE_HASH     12(T1), D
    UPDATE_HASH     16(T1), E
#endif
	.endm


	/*
		 main sha1 code for system without ssse3 support
	*/

	.macro  SHA1_PIPELINED_MAIN_BODY_nossse3
	LOAD_HASH						// load initial hashes into A,B,C,D,E (registers)
	INITIAL_W_PRECALC_nossse3		// big_endian_load(W) and W+K (i=0:15)
	.align	4,0x90
0:
	INTERNAL_nossse3				// update W (i=16:79) and update ABCDE (i=0:63)	
#if Multiple_Blocks
#if defined(__x86_64__)
	add	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	sub	$$1, cnt					// pre-decrement cnt by 1
#else
	addl	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	subl	$$1, cnt					// pre-decrement cnt by 1
#endif
	jbe	1f							// if cnt <= 0, branch to finish off
	SOFTWARE_PIPELINING_nossse3		// update ABCDE (i=64:79) || big_endian_load(W) and W+K (i=0:15)
	UPDATE_ALL_HASH					// update output hashes
	jmp	0b							// repeat for next block
	.align	4,0x90
1:
#endif
	ENDING							// update ABCDE (i=64:79)
	UPDATE_ALL_HASH					// update output hashes
	.endm

	/*
		 main sha1 code for system with ssse3 support
	*/

	.macro  SHA1_PIPELINED_MAIN_BODY_ssse3
	LOAD_HASH						// load initial hashes into A,B,C,D,E
	INITIAL_W_PRECALC_ssse3			// big_endian_load(W) and W+K (i=0:15)
	.align	4,0x90
0:
	INTERNAL_ssse3					// update W (i=16:79) and update ABCDE (i=0:63)
#if Multiple_Blocks
#if defined(__x86_64__)
	add	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	sub	$$1, cnt					// pre-decrement cnt by 1
#else
	addl	$$64, BUFFER_PTR			// BUFFER_PTR+=64;
	subl	$$1, cnt					// pre-decrement cnt by 1
#endif
	jbe	1f							// if cnt <= 0, branch to finish off
	SOFTWARE_PIPELINING_ssse3		// update ABCDE (i=64:79) || big_endian_load(W) and W+K (i=0:15)
	UPDATE_ALL_HASH					// update output hashes
	jmp	0b							// repeat for next block
	.align	4,0x90
1:
#endif
	ENDING							// update ABCDE (i=64:79)
	UPDATE_ALL_HASH					// update output hashes
	.endm

#if	KERNEL
#include <i386/cpu_capabilities.h>
#else
#include <System/i386/cpu_capabilities.h>
#endif

	.text

    .globl _sha1_x86_compress_data_order
    .private_extern _sha1_x86_compress_data_order
_sha1_x86_compress_data_order:

	// detect SSSE3 and dispatch appropriate code branch
	#if defined __x86_64__
    	movq    __cpu_capabilities@GOTPCREL(%rip), %rax         // %rax -> __cpu_capabilities
    	mov     (%rax), %eax                                    // %eax = __cpu_capabilities
	#else       // i386
		#if KERNEL
    		leal    __cpu_capabilities, %eax                    // %eax -> __cpu_capabilities
    		mov     (%eax), %eax                                // %eax = __cpu_capabilities
		#else
    		mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
		#endif
	#endif
    test    $(kHasSupplementalSSE3), %eax
    je      _SHA1Compress_x86nossse3                    			// branch to no-ssse3 code

	// start the sha1 code with ssse3 support

	// save callee-save registers
#if defined (__x86_64__)
	push	%rbx
	push	%rbp
#else
    push    %ebx
    push    %ebp
    push    %esi
    push    %edi
#endif

	sub		$stack_size, sp					// allocate stack memory for use

	// save used xmm register if this is for kernel
#if	KERNEL
	xmov	%xmm0, 4*16(sp)
	xmov	%xmm1, 5*16(sp)
	xmov	%xmm2, 6*16(sp)
	xmov	%xmm3, 7*16(sp)
	xmov	%xmm4, 8*16(sp)
	xmov	%xmm5, 9*16(sp)
	xmov	%xmm6, 10*16(sp)
	xmov	%xmm7, 11*16(sp)
#if defined (__x86_64__)
	xmov	%xmm8, 12*16(sp)
	xmov	%xmm9, 13*16(sp)
	xmov	%xmm10, 14*16(sp)
#endif
#endif

#if defined (__x86_64__)

	// set up registers to free %edx/%edi/%esi for other use (ABCDE)
	mov		ctx, HASH_PTR
	mov		buf, BUFFER_PTR
#if Multiple_Blocks
	mov		%rdx, cnt
#endif
	lea		K_XMM_AR(%rip), K_BASE
	xmov	0x40(K_BASE), XMM_SHUFB_BSWAP

#else	// __i386__

#if	KERNEL
    lea     K_XMM_AR, %eax
#else
	// Get address of 0 in R.
           call    0f          // Push program counter onto stack.
        0: pop     %eax      // Get program counter.
		lea	K_XMM_AR-0b(%eax), %eax
#endif
    mov     %eax, K_BASE
    xmov    0x40(%eax), %xmm0
    xmov    %xmm0, XMM_SHUFB_BSWAP

#endif

	SHA1_PIPELINED_MAIN_BODY_ssse3

	// restore used xmm registers if this is for kernel
#if	KERNEL
	xmov	4*16(sp), %xmm0
	xmov	5*16(sp), %xmm1
	xmov	6*16(sp), %xmm2
	xmov	7*16(sp), %xmm3
	xmov	8*16(sp), %xmm4
	xmov	9*16(sp), %xmm5
	xmov	10*16(sp), %xmm6
	xmov	11*16(sp), %xmm7
#if defined (__x86_64__)
	xmov	12*16(sp), %xmm8
	xmov	13*16(sp), %xmm9
	xmov	14*16(sp), %xmm10
#endif
#endif

	add		$stack_size, sp		// deallocate stack memory

	// restore callee-save registers
#if defined (__x86_64__)
	pop		%rbp
	pop		%rbx
#else
    pop     %edi
    pop     %esi
    pop     %ebp
    pop     %ebx
#endif

	ret							// return

	// this is equivalent to the above function _SHA1Transform, but it does not use ssse3 instructions

	.globl _SHA1Compress_x86nossse3
	.private_extern	_SHA1Compress_x86nossse3
_SHA1Compress_x86nossse3:

	// push callee-save registers
#if defined (__x86_64__)
	push	%rbx
	push	%rbp
#else
    push    %ebx
    push    %ebp
    push    %esi
    push    %edi
#endif

	sub		$stack_size, sp			// allocate stack memory for local use

	// save used xmm registers if this is for kernel
#if	KERNEL
	xmov	%xmm0, 4*16(sp)
	xmov	%xmm1, 5*16(sp)
	xmov	%xmm2, 6*16(sp)
	xmov	%xmm3, 7*16(sp)
	xmov	%xmm4, 8*16(sp)
	xmov	%xmm5, 9*16(sp)
	xmov	%xmm6, 10*16(sp)
	xmov	%xmm7, 11*16(sp)
#if defined (__x86_64__)
	xmov	%xmm8, 12*16(sp)
	xmov	%xmm9, 13*16(sp)
#endif
#endif

#if defined (__x86_64__)

	// set up registers to free %edx/%edi/%esi for other use (ABCDE)
	mov		ctx, HASH_PTR
	mov		buf, BUFFER_PTR
#if Multiple_Blocks
	mov		%rdx, cnt
#endif
	lea		K_XMM_AR(%rip), K_BASE

#else	// __i386__

#if	KERNEL
    lea     K_XMM_AR, %eax
#else
	// Get address of 0 in R.
           call    0f          // Push program counter onto stack.
        0: pop     %eax      // Get program counter.
		lea	K_XMM_AR-0b(%eax), %eax
#endif
    mov     %eax, K_BASE

#endif

	SHA1_PIPELINED_MAIN_BODY_nossse3

	// restore used xmm registers if this is for kernel
#if	KERNEL
	xmov	4*16(sp), %xmm0
	xmov	5*16(sp), %xmm1
	xmov	6*16(sp), %xmm2
	xmov	7*16(sp), %xmm3
	xmov	8*16(sp), %xmm4
	xmov	9*16(sp), %xmm5
	xmov	10*16(sp), %xmm6
	xmov	11*16(sp), %xmm7
#if defined (__x86_64__)
	xmov	12*16(sp), %xmm8
	xmov	13*16(sp), %xmm9
#endif
#endif

	add		$stack_size, sp		// deallocate stack memory

	// restore callee-save registers
#if defined (__x86_64__)
	pop		%rbp
	pop		%rbx
#else
    pop     %edi
    pop     %esi
    pop     %ebp
    pop     %ebx
#endif

	ret							// return

	.const
	.align	4, 0x90	

#define K1 0x5a827999
#define K2 0x6ed9eba1
#define K3 0x8f1bbcdc
#define K4 0xca62c1d6

K_XMM_AR:
    .long	K1
	.long	K1
	.long	K1
	.long	K1
    .long	K2
	.long	K2
	.long	K2
	.long	K2
    .long	K3
	.long	K3
	.long	K3
	.long	K3
    .long	K4
	.long	K4
	.long	K4
	.long	K4
// bswap_shufb_ctl: accessed thru 0x40(K_XMM_AR)
    .long	0x00010203
    .long	0x04050607
    .long	0x08090a0b
    .long	0x0c0d0e0f



#endif	// architecture x86_64 or i386

Added Source/descriptors/digestDescriptors/vng_x86_sha2_descriptor/sha256.s.



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
/* 
 * Copyright (c) 2011 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
	This file provides x86_64/i386 hand implementation of the following function

	void SHA256_Transform(SHA256_ctx *ctx, char *data, unsigned int num_blocks);

	which is a C function in sha2.c (from xnu).

	The code 1st probes cpu_capabilities to detect whether ssse3 is supported. If not, it branches to
	SHA256_Transform_nossse3 (in a separate source file sha256nossse3.s) that was cloned from this file
	with all ssse3 instructions replaced with sse3 or below instructions.

	sha256 algorithm per block description:

		1. W(0:15) = big-endian (per 4 bytes) loading of input data (64 byte) 
		2. load 8 digests a-h from ctx->state
		3. for r = 0:15
				T1 = h + Sigma1(e) + Ch(e,f,g) + K[r] + W[r];
				d += T1;
				h = T1 + Sigma0(a) + Maj(a,b,c)
				permute a,b,c,d,e,f,g,h into h,a,b,c,d,e,f,g
		4. for r = 16:63
				W[r] = W[r-16] + sigma1(W[r-2]) + W[r-7] + sigma0(W[r-15]);
				T1 = h + Sigma1(e) + Ch(e,f,g) + K[r] + W[r];
				d += T1;
				h = T1 + Sigma0(a) + Maj(a,b,c)
				permute a,b,c,d,e,f,g,h into h,a,b,c,d,e,f,g
				
	In the assembly implementation:	
		- a circular window of message schedule W(r:r+15) is updated and stored in xmm0-xmm3
		- its corresponding W+K(r:r+15) is updated and stored in a stack space circular buffer
		- the 8 digests (a-h) will be stored in GPR or m32 (all in GPR for x86_64, and some in m32 for i386)

	the implementation per block looks like

	----------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into xmm0:xmm3 
	pre_calculate and store W+K(0:15) in stack

	load digests a-h from ctx->state;

	for (r=0;r<48;r+=4) {
		digests a-h update and permute round r:r+3
		update W([r:r+3]%16) and WK([r:r+3]%16) for the next 4th iteration 
	}

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
	}

	ctx->states += digests a-h;

	----------------------------------------------------------------------------

	our implementation (allows multiple blocks per call) pipelines the loading of W/WK of a future block 
	into the last 16 rounds of its previous block:

	----------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into xmm0:xmm3 
	pre_calculate and store W+K(0:15) in stack

L_loop:

	load digests a-h from ctx->state;

	for (r=0;r<48;r+=4) {
		digests a-h update and permute round r:r+3
		update W([r:r+3]%16) and WK([r:r+3]%16) for the next 4th iteration 
	}

	num_block--;
	if (num_block==0)	jmp L_last_block;

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
		load W([r:r+3]%16) (big-endian per 4 bytes) into xmm0:xmm3 
		pre_calculate and store W+K([r:r+3]%16) in stack
	}

	ctx->states += digests a-h;

	jmp	L_loop;

L_last_block:

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
	}

	ctx->states += digests a-h;

	------------------------------------------------------------------------

	Apple CoreOS vector & numerics
	cclee 8-3-10
*/
#if defined __i386__ || defined __x86_64__
#if defined	KERNEL
#include <i386/cpu_capabilities.h>
#else
#include <System/i386/cpu_capabilities.h>
#endif

#if defined (__i386__)
.section    __IMPORT,__pointers,non_lazy_symbol_pointers
L_K256$non_lazy_ptr:
.indirect_symbol _K256
.long   0
#endif


	// associate variables with registers or memory

#if defined	(__x86_64__)
	#define	sp			%rsp
	#define	ctx			%rdi
	#define data		%rsi
	#define	num_blocks	%rdx

	#define	a			%r8d
	#define	b			%r9d
	#define	c			%r10d
	#define	d			%r11d
	#define	e			%r12d
	#define	f			%r13d
	#define	g			%r14d
	#define	h			%r15d

	#define	K			%rbx
	#define stack_size	(8+16*8+16+64)	// 8 (align) + xmm0:xmm7 + L_aligned_bswap + WK(0:15)

	#define	L_aligned_bswap	64(sp)		// bswap : big-endian loading of 4-byte words
	#define	xmm_save	80(sp)			// starting address for xmm save/restore
#else
	#define	sp 	%esp
	#define stack_size	(12+16*8+16+16+64)	// 12 (align) + xmm0:xmm7 + 16 (c,f,h,K) + L_aligned_bswap + WK(0:15)
	#define	ctx_addr	20+stack_size(sp)	// ret_addr + 4 registers = 20, 1st caller argument
	#define	data_addr	24+stack_size(sp)	// 2nd caller argument
	#define	num_blocks	28+stack_size(sp)	// 3rd caller argument

	#define	a	%ebx
	#define	b	%edx
	#define	c	64(sp)
	#define	d	%ebp
	#define	e	%esi
	#define	f	68(sp)
	#define	g	%edi
	#define	h	72(sp)

	#define	K	76(sp)					// pointer to K256[] table
	#define	L_aligned_bswap	80(sp)		// bswap : big-endian loading of 4-byte words
	#define	xmm_save	96(sp)			// starting address for xmm save/restore
#endif

	// 2 local variables
	#define	t	%eax
	#define	s	%ecx

	// a window (16 words) of message scheule
	#define	W0	%xmm0
	#define	W1	%xmm1
	#define	W2	%xmm2
	#define	W3	%xmm3

	// circular buffer for WK[(r:r+15)%16]
	#define WK(x)   (x&15)*4(sp)



// #define Ch(x,y,z)   (((x) & (y)) ^ ((~(x)) & (z)))

	.macro Ch
	mov		$0, t		// x
	mov		$0, s		// x
	not		t			// ~x
	and		$1, s		// x & y
	and		$2, t		// ~x & z
	xor		s, t		// t = ((x) & (y)) ^ ((~(x)) & (z));
	.endm

// #define Maj(x,y,z)  (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

	.macro	Maj
	mov		$0, t		// x
	mov		$1, s		// y
	and		s, t		// x&y
	and		$2, s		// y&z
	xor		s, t		// (x&y) ^ (y&z)
	mov		$2, s		// z
	and		$0, s		// (x&z)
	xor		s, t		// t = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) 
	.endm

/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
// #define R(b,x)      ((x) >> (b))
/* 32-bit Rotate-right (used in SHA-256): */
// #define S32(b,x)    (((x) >> (b)) | ((x) << (32 - (b))))

// #define sigma0_256(x)   (S32(7,  (x)) ^ S32(18, (x)) ^ R(3 ,   (x)))

	// performs sigma0_256 on 4 words on an xmm registers
	// use xmm6/xmm7 as intermediate registers
	.macro	sigma0
	movdqa	$0, %xmm6
	movdqa	$0, %xmm7
	psrld	$$3, $0			// SHR3(x)
	psrld	$$7, %xmm6		// part of ROTR7
	pslld	$$14, %xmm7		// part of ROTR18
	pxor	%xmm6, $0
	pxor	%xmm7, $0
	psrld	$$11, %xmm6		// part of ROTR18
	pslld	$$11, %xmm7		// part of ROTR7
	pxor	%xmm6, $0
	pxor	%xmm7, $0
	.endm

// #define sigma1_256(x)   (S32(17, (x)) ^ S32(19, (x)) ^ R(10,   (x)))

	// performs sigma1_256 on 4 words on an xmm registers
	// use xmm6/xmm7 as intermediate registers
	.macro	sigma1
	movdqa	$0, %xmm6
	movdqa	$0, %xmm7
	psrld	$$10, $0		// SHR10(x)
	psrld	$$17, %xmm6		// part of ROTR17
	pxor	%xmm6, $0
	pslld	$$13, %xmm7		// part of ROTR19
	pxor	%xmm7, $0
	psrld	$$2, %xmm6		// part of ROTR19
	pxor	%xmm6, $0
	pslld	$$2, %xmm7		// part of ROTR17
	pxor	%xmm7, $0
	.endm

// #define Sigma0_256(x)   (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))

	.macro	Sigma0
	mov		$0, t			// x
	mov		$0, s			// x
	ror		$$2, t			// S32(2,  (x))
	ror		$$13, s			// S32(13,  (x))
	xor		s, t			// S32(2,  (x)) ^ S32(13, (x))
	ror		$$9, s			// S32(22,  (x))
	xor		s, t			// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))
	.endm

// #define Sigma1_256(x)   (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))

	.macro	Sigma1
	mov		$0, s			// x
	ror		$$6, s			// S32(6,  (x))
	mov		s, t			// S32(6,  (x))
	ror		$$5, s			// S32(11, (x))
	xor		s, t			// S32(6,  (x)) ^ S32(11, (x))
	ror		$$14, s			// S32(25, (x))
	xor		s, t			// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	.endm

	// per round digests update
	.macro	round
	Sigma1	$4				// t = T1
	add		t, $7			// use h to store h+Sigma1(e)
	Ch		$4, $5, $6		// t = Ch (e, f, g);
	add		$7, t			// t = h+Sigma1(e)+Ch(e,f,g);
	add		WK($8), t		// h = T1
	add		t, $3			// d += T1;
	mov		t, $7			// h = T1
	Sigma0	$0				// t = Sigma0(a);
	add		t, $7			// h = T1 + Sigma0(a);
	Maj		$0, $1, $2		// t = Maj(a,b,c)
	add		t, $7			// h = T1 + Sigma0(a) + Maj(a,b,c);			
	.endm

	// per 4 rounds digests update and permutation
	// permutation is absorbed by rotating the roles of digests a-h
	.macro	rounds
	round	$0, $1, $2, $3, $4, $5, $6, $7, 0+$8
	round	$7, $0, $1, $2, $3, $4, $5, $6, 1+$8
	round	$6, $7, $0, $1, $2, $3, $4, $5, 2+$8
	round	$5, $6, $7, $0, $1, $2, $3, $4, 3+$8
	.endm

	// update the message schedule W and W+K (4 rounds) 16 rounds ahead in the future 
	.macro	message_schedule

	// 4 32-bit K256 words in xmm5
#if defined	(__x86_64__)
	movdqu	(K), %xmm5
	add		$$16, K				// K points to next K256 word for next iteration
#else
	mov		K, t
	movdqu	(t), %xmm5 
	addl	$$16, K				// K points to next K256 word for next iteration
#endif	
	movdqa	$1, %xmm4 			// W7:W4
	palignr	$$4, $0, %xmm4		// W4:W1
	sigma0	%xmm4				// sigma0(W4:W1)
	movdqa	$3, %xmm6 			// W15:W12
	paddd	%xmm4, $0			// $0 = W3:W0 + sigma0(W4:W1) 
	palignr	$$4, $2, %xmm6		// W12:W9
	paddd	%xmm6, $0			// $0 = W12:W9 + sigma0(W4:W1) + W3:W0	
	movdqa	$3, %xmm4			// W15:W12
	psrldq	$$8, %xmm4			// 0,0,W15,W14	
	sigma1	%xmm4				// sigma1(0,0,W15,W14)
	paddd	%xmm4, $0			// sigma1(0,0,W15,W14) + W12:W9 + sigma0(W4:W1) + W3:W0
	movdqa	$0, %xmm4			// W19-sigma1(W17), W18-sigma1(W16), W17, W16
	pslldq	$$8, %xmm4			// W17, W16, 0, 0
	sigma1	%xmm4				// sigma1(W17,W16,0,0)
	paddd	%xmm4, $0			// W19:W16
	paddd	$0, %xmm5			// WK
	movdqa	%xmm5, WK($4)
	.endm

	// this macro is used in the last 16 rounds of a current block
	// it reads the next message (16 4-byte words), load it into 4 words W[r:r+3], computes WK[r:r+3]
	// and save into stack to prepare for next block

	.macro	update_W_WK
#if defined (__x86_64__)
	movdqu	$0*16(data), $1		// read 4 4-byte words
	pshufb	L_aligned_bswap, $1	// big-endian of each 4-byte word, W[r:r+3]
	movdqu	$0*16(K), %xmm4		// K[r:r+3]
#else
	mov		data_addr, t
	movdqu	$0*16(t), $1		// read 4 4-byte words
	pshufb	L_aligned_bswap, $1	// big-endian of each 4-byte word, W[r:r+3]
	mov		K, t
	movdqu	$0*16(t), %xmm4		// K[r:r+3]
#endif
	paddd	$1, %xmm4			// WK[r:r+3]
	movdqa	%xmm4, WK($0*4)		// save WK[r:r+3] into stack circular buffer
	.endm

	.text

#if defined (__x86_64__) || defined (__i386__)

	.globl	_vng_x86_sha256_compress

_vng_x86_sha256_compress:


	// detect SSSE3 and dispatch appropriate code branch
	#if defined __x86_64__
        movq    __cpu_capabilities@GOTPCREL(%rip), %rax         // %rax -> __cpu_capabilities
        mov     (%rax), %eax                                    // %eax = __cpu_capabilities
    #else       // i386
        #if defined KERNEL
            leal    __cpu_capabilities, %eax                    // %eax -> __cpu_capabilities
            mov     (%eax), %eax                                // %eax = __cpu_capabilities
        #else
            mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
        #endif
    #endif
    test    $(kHasSupplementalSSE3), %eax
    je      _SHA256_Transform_nossse3                              // branch to no-ssse3 code

	// push callee-saved registers
#if defined	(__x86_64__)
	push	%rbp
	push	%rbx
	push	%r12
	push	%r13
	push	%r14
	push	%r15
#else
    push    %ebp
	push    %ebx
    push    %esi
    push    %edi
#endif

	// allocate stack space
	sub		$stack_size, sp

	// if kernel code, save used xmm registers
#if	KERNEL
	movdqa	%xmm0, 0*16+xmm_save
	movdqa	%xmm1, 1*16+xmm_save
	movdqa	%xmm2, 2*16+xmm_save
	movdqa	%xmm3, 3*16+xmm_save
	movdqa	%xmm4, 4*16+xmm_save
	movdqa	%xmm5, 5*16+xmm_save
	movdqa	%xmm6, 6*16+xmm_save
	movdqa	%xmm7, 7*16+xmm_save
#endif

	// set up bswap parameters in the aligned stack space and pointer to table K256[]
#if defined (__x86_64__)
	lea		_K256(%rip), K
	lea		L_bswap(%rip), %rax
	movdqa	(%rax), %xmm0
#else
#if defined (KERNEL)
    lea     _K256, t
#else
    call    0f          // Push program counter onto stack.
0:  pop     t           // Get program counter.
    movl L_K256$non_lazy_ptr-0b(t), t

#endif
	mov		t, K
    call    0f           // Push program counter onto stack.
0:
    pop     t            // Get program counter.
    lea     L_bswap-0b(t), t
	movdqa	(%eax), %xmm0
#endif
	movdqa	%xmm0, L_aligned_bswap	

	// load W[0:15] into xmm0-xmm3
#if defined (__x86_64__)
	movdqu	0*16(data), W0
	movdqu	1*16(data), W1
	movdqu	2*16(data), W2
	movdqu	3*16(data), W3
	add		$64, data
#else
	mov		data_addr, t
	movdqu	0*16(t), W0
	movdqu	1*16(t), W1
	movdqu	2*16(t), W2
	movdqu	3*16(t), W3
	addl	$64, data_addr
#endif
	pshufb	L_aligned_bswap, W0
	pshufb	L_aligned_bswap, W1
	pshufb	L_aligned_bswap, W2
	pshufb	L_aligned_bswap, W3

	// compute WK[0:15] and save in stack
#if defined (__x86_64__)
	movdqu	0*16(K), %xmm4	
	movdqu	1*16(K), %xmm5
	movdqu	2*16(K), %xmm6	
	movdqu	3*16(K), %xmm7
	add		$64, K
#else
	mov		K, t
	movdqu	0*16(t), %xmm4	
	movdqu	1*16(t), %xmm5
	movdqu	2*16(t), %xmm6	
	movdqu	3*16(t), %xmm7
	addl	$64, K
#endif
	paddd	%xmm0, %xmm4
	paddd	%xmm1, %xmm5
	paddd	%xmm2, %xmm6
	paddd	%xmm3, %xmm7
	movdqa	%xmm4, WK(0)
	movdqa	%xmm5, WK(4)
	movdqa	%xmm6, WK(8)
	movdqa	%xmm7, WK(12)

L_loop:

	// digests a-h = ctx->states;
#if defined (__x86_64__)
	mov		0*4(ctx), a
	mov		1*4(ctx), b
	mov		2*4(ctx), c
	mov		3*4(ctx), d
	mov		4*4(ctx), e
	mov		5*4(ctx), f
	mov		6*4(ctx), g
	mov		7*4(ctx), h
#else
	mov		ctx_addr, t
	mov 	0*4(t), a
	mov 	1*4(t), b
	mov 	2*4(t), s
	mov		s, c
	mov 	3*4(t), d
	mov 	4*4(t), e
	mov 	5*4(t), s
	mov		s, f
	mov 	6*4(t), g
	mov 	7*4(t), s
	mov		s, h
#endif

	// rounds 0:47 interleaved with W/WK update for rounds 16:63
	rounds	a, b, c, d, e, f, g, h, 0
	message_schedule W0,W1,W2,W3,16
	rounds	e, f, g, h, a, b, c, d, 4 
	message_schedule W1,W2,W3,W0,20
	rounds	a, b, c, d, e, f, g, h, 8
	message_schedule W2,W3,W0,W1,24
	rounds	e, f, g, h, a, b, c, d, 12 
	message_schedule W3,W0,W1,W2,28
	rounds	a, b, c, d, e, f, g, h, 16
	message_schedule W0,W1,W2,W3,32
	rounds	e, f, g, h, a, b, c, d, 20 
	message_schedule W1,W2,W3,W0,36
	rounds	a, b, c, d, e, f, g, h, 24
	message_schedule W2,W3,W0,W1,40
	rounds	e, f, g, h, a, b, c, d, 28 
	message_schedule W3,W0,W1,W2,44
	rounds	a, b, c, d, e, f, g, h, 32
	message_schedule W0,W1,W2,W3,48
	rounds	e, f, g, h, a, b, c, d, 36 
	message_schedule W1,W2,W3,W0,52
	rounds	a, b, c, d, e, f, g, h, 40
	message_schedule W2,W3,W0,W1,56
	rounds	e, f, g, h, a, b, c, d, 44 
	message_schedule W3,W0,W1,W2,60

	// revert K to the beginning of K256[]
#if defined __x86_64__
	sub		$256, K
	sub		$1, num_blocks				// num_blocks--
#else
	subl	$256, K
	subl	$1, num_blocks				// num_blocks--
#endif

	je		L_final_block				// if final block, wrap up final rounds

	// rounds 48:63 interleaved with W/WK initialization for next block rounds 0:15 
	rounds	a, b, c, d, e, f, g, h, 48
	update_W_WK	0, W0
	rounds	e, f, g, h, a, b, c, d, 52 
	update_W_WK	1, W1
	rounds	a, b, c, d, e, f, g, h, 56
	update_W_WK	2, W2
	rounds	e, f, g, h, a, b, c, d, 60 
	update_W_WK	3, W3

#if defined (__x86_64__)
	add		$64, K
	add		$64, data
#else
	addl	$64, K
	addl	$64, data_addr
#endif

	// ctx->states += digests a-h
#if	defined (__x86_64__)
	add		a, 0*4(ctx)
	add		b, 1*4(ctx)
	add		c, 2*4(ctx)
	add		d, 3*4(ctx)
	add		e, 4*4(ctx)
	add		f, 5*4(ctx)
	add		g, 6*4(ctx)
	add		h, 7*4(ctx)
#else
	mov		ctx_addr, t
	add		a, 0*4(t)
	add		b, 1*4(t)
	mov		c, s
	add		s, 2*4(t)
	add		d, 3*4(t)
	add		e, 4*4(t)
	mov		f, s
	add		s, 5*4(t)
	add		g, 6*4(t)
	mov		h, s
	add		s, 7*4(t)
#endif

	jmp		L_loop				// branch for next block

	// wrap up digest update round 48:63 for final block
L_final_block:
	rounds	a, b, c, d, e, f, g, h, 48
	rounds	e, f, g, h, a, b, c, d, 52 
	rounds	a, b, c, d, e, f, g, h, 56
	rounds	e, f, g, h, a, b, c, d, 60 

	// ctx->states += digests a-h
#if	defined (__x86_64__)
	add		a, 0*4(ctx)
	add		b, 1*4(ctx)
	add		c, 2*4(ctx)
	add		d, 3*4(ctx)
	add		e, 4*4(ctx)
	add		f, 5*4(ctx)
	add		g, 6*4(ctx)
	add		h, 7*4(ctx)
#else
	mov		ctx_addr, t
	add		a, 0*4(t)
	add		b, 1*4(t)
	mov		c, s
	add		s, 2*4(t)
	add		d, 3*4(t)
	add		e, 4*4(t)
	mov		f, s
	add		s, 5*4(t)
	add		g, 6*4(t)
	mov		h, s
	add		s, 7*4(t)
#endif

	// if kernel, restore xmm0-xmm7
#if	KERNEL
	movdqa	0*16+xmm_save, %xmm0
	movdqa	1*16+xmm_save, %xmm1
	movdqa	2*16+xmm_save, %xmm2
	movdqa	3*16+xmm_save, %xmm3
	movdqa	4*16+xmm_save, %xmm4
	movdqa	5*16+xmm_save, %xmm5
	movdqa	6*16+xmm_save, %xmm6
	movdqa	7*16+xmm_save, %xmm7
#endif

	// free allocated stack memory
	add		$stack_size, sp

	// restore callee-saved registers
#if defined (__x86_64__)
	pop		%r15
	pop		%r14
	pop		%r13
	pop		%r12
	pop		%rbx
	pop		%rbp
#else
    pop		%edi
    pop		%esi
	pop		%ebx
    pop		%ebp
#endif

	// return
	ret


	.const
	.align	4, 0x90

L_bswap:
    .long   0x00010203
    .long   0x04050607
    .long   0x08090a0b
    .long   0x0c0d0e0f

#endif		// x86_64/i386
#endif		// x86_64/i386

Added Source/descriptors/digestDescriptors/vng_x86_sha2_descriptor/sha256_nossse3.s.









































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/* 
 * Copyright (c) 2011 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
	This file provides x86_64/i386 hand implementation of the following function

	void SHA256_Transform(SHA256_ctx *ctx, char *data, unsigned int num_blocks);

	which is a C function in sha2.c (from xnu).

	The code SHA256_Transform_nossse3 is a clone of SHA256_Transform
	with all ssse3 instructions replaced with sse3 or below instructions.

	For performance reason, this function should not be called directly. This file should be working
	together with the one that implements SHA256_Transform. There, cpu_capabilities is probed to detect
	ssse3. If ssse3 is not supported, the execution will be branched to this no-ssse3-specific function.

	sha256 algorithm per block description:

		1. W(0:15) = big-endian (per 4 bytes) loading of input data (64 byte) 
		2. load 8 digests a-h from ctx->state
		3. for r = 0:15
				T1 = h + Sigma1(e) + Ch(e,f,g) + K[r] + W[r];
				d += T1;
				h = T1 + Sigma0(a) + Maj(a,b,c)
				permute a,b,c,d,e,f,g,h into h,a,b,c,d,e,f,g
		4. for r = 16:63
				W[r] = W[r-16] + sigma1(W[r-2]) + W[r-7] + sigma0(W[r-15]);
				T1 = h + Sigma1(e) + Ch(e,f,g) + K[r] + W[r];
				d += T1;
				h = T1 + Sigma0(a) + Maj(a,b,c)
				permute a,b,c,d,e,f,g,h into h,a,b,c,d,e,f,g
				
	In the assembly implementation:	
		- a circular window of message schedule W(r:r+15) is updated and stored in xmm0-xmm3
		- its corresponding W+K(r:r+15) is updated and stored in a stack space circular buffer
		- the 8 digests (a-h) will be stored in GPR or m32 (all in GPR for x86_64, and some in m32 for i386)

	the implementation per block looks like

	----------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into xmm0:xmm3 
	pre_calculate and store W+K(0:15) in stack

	load digests a-h from ctx->state;

	for (r=0;r<48;r+=4) {
		digests a-h update and permute round r:r+3
		update W([r:r+3]%16) and WK([r:r+3]%16) for the next 4th iteration 
	}

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
	}

	ctx->states += digests a-h;

	----------------------------------------------------------------------------

	our implementation (allows multiple blocks per call) pipelines the loading of W/WK of a future block 
	into the last 16 rounds of its previous block:

	----------------------------------------------------------------------------

	load W(0:15) (big-endian per 4 bytes) into xmm0:xmm3 
	pre_calculate and store W+K(0:15) in stack

L_loop:

	load digests a-h from ctx->state;

	for (r=0;r<48;r+=4) {
		digests a-h update and permute round r:r+3
		update W([r:r+3]%16) and WK([r:r+3]%16) for the next 4th iteration 
	}

	num_block--;
	if (num_block==0)	jmp L_last_block;

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
		load W([r:r+3]%16) (big-endian per 4 bytes) into xmm0:xmm3 
		pre_calculate and store W+K([r:r+3]%16) in stack
	}

	ctx->states += digests a-h;

	jmp	L_loop;

L_last_block:

	for (r=48;r<64;r+=4) {
		digests a-h update and permute round r:r+3
	}

	ctx->states += digests a-h;

	------------------------------------------------------------------------

	Apple CoreOS vector & numerics
	cclee 8-3-10
*/

#if defined (__x86_64__) || defined (__i386__)

#if defined	KERNEL
#include <i386/cpu_capabilities.h>
#else
#include <System/i386/cpu_capabilities.h>
#endif

#if defined (__i386__)
    .section    __IMPORT,__pointers,non_lazy_symbol_pointers
L_K256$non_lazy_ptr:
.indirect_symbol _K256
    .long   0
#endif

	// associate variables with registers or memory

#if defined	(__x86_64__)
	#define	sp			%rsp
	#define	ctx			%rdi
	#define data		%rsi
	#define	num_blocks	%rdx

	#define	a			%r8d
	#define	b			%r9d
	#define	c			%r10d
	#define	d			%r11d
	#define	e			%r12d
	#define	f			%r13d
	#define	g			%r14d
	#define	h			%r15d

	#define	K			%rbx
	#define stack_size	(8+16*8+16+64)	// 8 (align) + xmm0:xmm7 + L_aligned_bswap + WK(0:15)

	#define	xmm_save	80(sp)			// starting address for xmm save/restore
#else
	#define	sp 	%esp
	#define stack_size	(12+16*8+16+16+64)	// 12 (align) + xmm0:xmm7 + 16 (c,f,h,K) + L_aligned_bswap + WK(0:15)
	#define	ctx_addr	20+stack_size(sp)	// ret_addr + 4 registers = 20, 1st caller argument
	#define	data_addr	24+stack_size(sp)	// 2nd caller argument
	#define	num_blocks	28+stack_size(sp)	// 3rd caller argument

	#define	a	%ebx
	#define	b	%edx
	#define	c	64(sp)
	#define	d	%ebp
	#define	e	%esi
	#define	f	68(sp)
	#define	g	%edi
	#define	h	72(sp)

	#define	K	76(sp)					// pointer to K256[] table
	#define	xmm_save	96(sp)			// starting address for xmm save/restore
#endif

	// 2 local variables
	#define	t	%eax
	#define	s	%ecx

	// a window (16 words) of message scheule
	#define	W0	%xmm0
	#define	W1	%xmm1
	#define	W2	%xmm2
	#define	W3	%xmm3

	// circular buffer for WK[(r:r+15)%16]
	#define WK(x)   (x&15)*4(sp)

// #define Ch(x,y,z)   (((x) & (y)) ^ ((~(x)) & (z)))

	.macro Ch
	mov		$0, t		// x
	mov		$0, s		// x
	not		t			// ~x
	and		$1, s		// x & y
	and		$2, t		// ~x & z
	xor		s, t		// t = ((x) & (y)) ^ ((~(x)) & (z));
	.endm

// #define Maj(x,y,z)  (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))

	.macro	Maj
	mov		$0, t		// x
	mov		$1, s		// y
	and		s, t		// x&y
	and		$2, s		// y&z
	xor		s, t		// (x&y) ^ (y&z)
	mov		$2, s		// z
	and		$0, s		// (x&z)
	xor		s, t		// t = (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) 
	.endm

/* Shift-right (used in SHA-256, SHA-384, and SHA-512): */
// #define R(b,x)      ((x) >> (b))
/* 32-bit Rotate-right (used in SHA-256): */
// #define S32(b,x)    (((x) >> (b)) | ((x) << (32 - (b))))

// #define sigma0_256(x)   (S32(7,  (x)) ^ S32(18, (x)) ^ R(3 ,   (x)))

	// performs sigma0_256 on 4 words on an xmm registers
	// use xmm6/xmm7 as intermediate registers
	.macro	sigma0
	movdqa	$0, %xmm6
	movdqa	$0, %xmm7
	psrld	$$3, $0			// SHR3(x)
	psrld	$$7, %xmm6		// part of ROTR7
	pslld	$$14, %xmm7		// part of ROTR18
	pxor	%xmm6, $0
	pxor	%xmm7, $0
	psrld	$$11, %xmm6		// part of ROTR18
	pslld	$$11, %xmm7		// part of ROTR7
	pxor	%xmm6, $0
	pxor	%xmm7, $0
	.endm

// #define sigma1_256(x)   (S32(17, (x)) ^ S32(19, (x)) ^ R(10,   (x)))

	// performs sigma1_256 on 4 words on an xmm registers
	// use xmm6/xmm7 as intermediate registers
	.macro	sigma1
	movdqa	$0, %xmm6
	movdqa	$0, %xmm7
	psrld	$$10, $0		// SHR10(x)
	psrld	$$17, %xmm6		// part of ROTR17
	pxor	%xmm6, $0
	pslld	$$13, %xmm7		// part of ROTR19
	pxor	%xmm7, $0
	psrld	$$2, %xmm6		// part of ROTR19
	pxor	%xmm6, $0
	pslld	$$2, %xmm7		// part of ROTR17
	pxor	%xmm7, $0
	.endm

// #define Sigma0_256(x)   (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))

	.macro	Sigma0
	mov		$0, t			// x
	mov		$0, s			// x
	ror		$$2, t			// S32(2,  (x))
	ror		$$13, s			// S32(13,  (x))
	xor		s, t			// S32(2,  (x)) ^ S32(13, (x))
	ror		$$9, s			// S32(22,  (x))
	xor		s, t			// t = (S32(2,  (x)) ^ S32(13, (x)) ^ S32(22, (x)))
	.endm

// #define Sigma1_256(x)   (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))

	.macro	Sigma1
	mov		$0, s			// x
	ror		$$6, s			// S32(6,  (x))
	mov		s, t			// S32(6,  (x))
	ror		$$5, s			// S32(11, (x))
	xor		s, t			// S32(6,  (x)) ^ S32(11, (x))
	ror		$$14, s			// S32(25, (x))
	xor		s, t			// t = (S32(6,  (x)) ^ S32(11, (x)) ^ S32(25, (x)))
	.endm

	// per round digests update
	.macro	round
	Sigma1	$4				// t = T1
	add		t, $7			// use h to store h+Sigma1(e)
	Ch		$4, $5, $6		// t = Ch (e, f, g);
	add		$7, t			// t = h+Sigma1(e)+Ch(e,f,g);
	add		WK($8), t		// h = T1
	add		t, $3			// d += T1;
	mov		t, $7			// h = T1
	Sigma0	$0				// t = Sigma0(a);
	add		t, $7			// h = T1 + Sigma0(a);
	Maj		$0, $1, $2		// t = Maj(a,b,c)
	add		t, $7			// h = T1 + Sigma0(a) + Maj(a,b,c);			
	.endm

	// per 4 rounds digests update and permutation
	// permutation is absorbed by rotating the roles of digests a-h
	.macro	rounds
	round	$0, $1, $2, $3, $4, $5, $6, $7, 0+$8
	round	$7, $0, $1, $2, $3, $4, $5, $6, 1+$8
	round	$6, $7, $0, $1, $2, $3, $4, $5, 2+$8
	round	$5, $6, $7, $0, $1, $2, $3, $4, 3+$8
	.endm

	// update the message schedule W and W+K (4 rounds) 16 rounds ahead in the future 
	.macro	message_schedule

	// 4 32-bit K256 words in xmm5
#if defined	(__x86_64__)
	movdqu	(K), %xmm5
	add		$$16, K				// K points to next K256 word for next iteration
#else
	mov		K, t
	movdqu	(t), %xmm5 
	addl	$$16, K				// K points to next K256 word for next iteration
#endif	
	movdqa	$1, %xmm4 			// W7:W4
#if 0
	palignr	$$4, $0, %xmm4		// W4:W1
#else	// no-ssse3 implementation of palignr
	movdqa  $0, %xmm7
    pslldq  $$12, %xmm4
    psrldq  $$4, %xmm7
    por     %xmm7, %xmm4
#endif
	sigma0	%xmm4				// sigma0(W4:W1)
	movdqa	$3, %xmm6 			// W15:W12
	paddd	%xmm4, $0			// $0 = W3:W0 + sigma0(W4:W1) 
#if 0
	palignr	$$4, $2, %xmm6		// W12:W9
#else	// no-ssse3 implementation of palignr
	movdqa  $2, %xmm7
    pslldq  $$12, %xmm6
    psrldq  $$4, %xmm7
    por     %xmm7, %xmm6
#endif
	paddd	%xmm6, $0			// $0 = W12:W9 + sigma0(W4:W1) + W3:W0	
	movdqa	$3, %xmm4			// W15:W12
	psrldq	$$8, %xmm4			// 0,0,W15,W14	
	sigma1	%xmm4				// sigma1(0,0,W15,W14)
	paddd	%xmm4, $0			// sigma1(0,0,W15,W14) + W12:W9 + sigma0(W4:W1) + W3:W0
	movdqa	$0, %xmm4			// W19-sigma1(W17), W18-sigma1(W16), W17, W16
	pslldq	$$8, %xmm4			// W17, W16, 0, 0
	sigma1	%xmm4				// sigma1(W17,W16,0,0)
	paddd	%xmm4, $0			// W19:W16
	paddd	$0, %xmm5			// WK
	movdqa	%xmm5, WK($4)
	.endm

	// this macro is used in the last 16 rounds of a current block
	// it reads the next message (16 4-byte words), load it into 4 words W[r:r+3], computes WK[r:r+3]
	// and save into stack to prepare for next block

	.macro	update_W_WK
#if defined (__x86_64__)
#if 0
	movdqu	$0*16(data), $1		// read 4 4-byte words
	pshufb	L_aligned_bswap, $1	// big-endian of each 4-byte word, W[r:r+3]
#else	// no-ssse3 implementation
	mov     0+$0*16(data), s
    bswap   s
    mov     s, 0+WK($0*4)
    mov     4+$0*16(data), s
    bswap   s
    mov     s, 4+WK($0*4)
    mov     8+$0*16(data), s
    bswap   s
    mov     s, 8+WK($0*4)
    mov     12+$0*16(data), s
    bswap   s
    mov     s, 12+WK($0*4)
    movdqa  WK($0*4), $1
#endif
	movdqu	$0*16(K), %xmm4		// K[r:r+3]
#else
	mov		data_addr, t
#if 0
	movdqu	$0*16(t), $1		// read 4 4-byte words
	pshufb	L_aligned_bswap, $1	// big-endian of each 4-byte word, W[r:r+3]
#else	// no-ssse3 implementation
	mov     0+$0*16(t), s
    bswap   s
    mov     s, 0+WK($0*4)
    mov     4+$0*16(t), s
    bswap   s
    mov     s, 4+WK($0*4)
    mov     8+$0*16(t), s
    bswap   s
    mov     s, 8+WK($0*4)
    mov     12+$0*16(t), s
    bswap   s
    mov     s, 12+WK($0*4)
    movdqa  WK($0*4), $1
#endif
	mov		K, t
	movdqu	$0*16(t), %xmm4		// K[r:r+3]
#endif
	paddd	$1, %xmm4			// WK[r:r+3]
	movdqa	%xmm4, WK($0*4)		// save WK[r:r+3] into stack circular buffer
	.endm

	.text

#if defined (__x86_64__) || defined (__i386__)

	.globl	_SHA256_Transform_nossse3

_SHA256_Transform_nossse3:

	// push callee-saved registers
#if defined	(__x86_64__)
	push	%rbp
	push	%rbx
	push	%r12
	push	%r13
	push	%r14
	push	%r15
#else
    push    %ebp
	push    %ebx
    push    %esi
    push    %edi
#endif

	// allocate stack space
	sub		$stack_size, sp

	// if kernel code, save used xmm registers
#if	KERNEL
	movdqa	%xmm0, 0*16+xmm_save
	movdqa	%xmm1, 1*16+xmm_save
	movdqa	%xmm2, 2*16+xmm_save
	movdqa	%xmm3, 3*16+xmm_save
	movdqa	%xmm4, 4*16+xmm_save
	movdqa	%xmm5, 5*16+xmm_save
	movdqa	%xmm6, 6*16+xmm_save
	movdqa	%xmm7, 7*16+xmm_save
#endif

	// set up pointer to table K256[]
#if defined (__x86_64__)
	lea		_K256(%rip), K
#else
#if defined (KERNEL)
	lea		_K256, t
#else
    call    0f          // Push program counter onto stack.
0:  pop     t           // Get program counter.
    movl L_K256$non_lazy_ptr-0b(t), t

#endif
	mov		t, K
#endif

	// load W[0:15] into xmm0-xmm3
    .macro  mybswap
    movl    0+$0*16($1), a
    movl    4+$0*16($1), b
    movl    8+$0*16($1), e
    movl    12+$0*16($1), d
    bswap   a
    bswap   b
    bswap   e
    bswap   d
    movl    a, $0*16(sp)
    movl    b, 4+$0*16(sp)
    movl    e, 8+$0*16(sp)
    movl    d, 12+$0*16(sp)
    .endm

#if defined (__x86_64__)
    mybswap 0, data
    mybswap 1, data
    mybswap 2, data
    mybswap 3, data
	add		$64, data
#else
	mov		data_addr, t
    mybswap 0, t
    mybswap 1, t
    mybswap 2, t
    mybswap 3, t
    addl    $64, data_addr
#endif
    movdqa  0*16(sp), W0
    movdqa  1*16(sp), W1
    movdqa  2*16(sp), W2
    movdqa  3*16(sp), W3

	// compute WK[0:15] and save in stack
#if defined (__x86_64__)
	movdqu	0*16(K), %xmm4	
	movdqu	1*16(K), %xmm5
	movdqu	2*16(K), %xmm6	
	movdqu	3*16(K), %xmm7
	add		$64, K
#else
	mov		K, t
	movdqu	0*16(t), %xmm4	
	movdqu	1*16(t), %xmm5
	movdqu	2*16(t), %xmm6	
	movdqu	3*16(t), %xmm7
	addl	$64, K
#endif
	paddd	%xmm0, %xmm4
	paddd	%xmm1, %xmm5
	paddd	%xmm2, %xmm6
	paddd	%xmm3, %xmm7
	movdqa	%xmm4, WK(0)
	movdqa	%xmm5, WK(4)
	movdqa	%xmm6, WK(8)
	movdqa	%xmm7, WK(12)

L_loop:

	// digests a-h = ctx->states;
#if defined (__x86_64__)
	mov		0*4(ctx), a
	mov		1*4(ctx), b
	mov		2*4(ctx), c
	mov		3*4(ctx), d
	mov		4*4(ctx), e
	mov		5*4(ctx), f
	mov		6*4(ctx), g
	mov		7*4(ctx), h
#else
	mov		ctx_addr, t
	mov 	0*4(t), a
	mov 	1*4(t), b
	mov 	2*4(t), s
	mov		s, c
	mov 	3*4(t), d
	mov 	4*4(t), e
	mov 	5*4(t), s
	mov		s, f
	mov 	6*4(t), g
	mov 	7*4(t), s
	mov		s, h
#endif

	// rounds 0:47 interleaved with W/WK update for rounds 16:63
	rounds	a, b, c, d, e, f, g, h, 0
	message_schedule W0,W1,W2,W3,16
	rounds	e, f, g, h, a, b, c, d, 4 
	message_schedule W1,W2,W3,W0,20
	rounds	a, b, c, d, e, f, g, h, 8
	message_schedule W2,W3,W0,W1,24
	rounds	e, f, g, h, a, b, c, d, 12 
	message_schedule W3,W0,W1,W2,28
	rounds	a, b, c, d, e, f, g, h, 16
	message_schedule W0,W1,W2,W3,32
	rounds	e, f, g, h, a, b, c, d, 20 
	message_schedule W1,W2,W3,W0,36
	rounds	a, b, c, d, e, f, g, h, 24
	message_schedule W2,W3,W0,W1,40
	rounds	e, f, g, h, a, b, c, d, 28 
	message_schedule W3,W0,W1,W2,44
	rounds	a, b, c, d, e, f, g, h, 32
	message_schedule W0,W1,W2,W3,48
	rounds	e, f, g, h, a, b, c, d, 36 
	message_schedule W1,W2,W3,W0,52
	rounds	a, b, c, d, e, f, g, h, 40
	message_schedule W2,W3,W0,W1,56
	rounds	e, f, g, h, a, b, c, d, 44 
	message_schedule W3,W0,W1,W2,60

	// revert K to the beginning of K256[]
#if defined __x86_64__
	sub		$256, K
	sub		$1, num_blocks				// num_blocks--
#else
	subl	$256, K
	subl	$1, num_blocks				// num_blocks--
#endif

	je		L_final_block				// if final block, wrap up final rounds

	// rounds 48:63 interleaved with W/WK initialization for next block rounds 0:15 
	rounds	a, b, c, d, e, f, g, h, 48
	update_W_WK	0, W0
	rounds	e, f, g, h, a, b, c, d, 52 
	update_W_WK	1, W1
	rounds	a, b, c, d, e, f, g, h, 56
	update_W_WK	2, W2
	rounds	e, f, g, h, a, b, c, d, 60 
	update_W_WK	3, W3

#if defined (__x86_64__)
	add		$64, K
	add		$64, data
#else
	addl	$64, K
	addl	$64, data_addr
#endif

	// ctx->states += digests a-h
#if	defined (__x86_64__)
	add		a, 0*4(ctx)
	add		b, 1*4(ctx)
	add		c, 2*4(ctx)
	add		d, 3*4(ctx)
	add		e, 4*4(ctx)
	add		f, 5*4(ctx)
	add		g, 6*4(ctx)
	add		h, 7*4(ctx)
#else
	mov		ctx_addr, t
	add		a, 0*4(t)
	add		b, 1*4(t)
	mov		c, s
	add		s, 2*4(t)
	add		d, 3*4(t)
	add		e, 4*4(t)
	mov		f, s
	add		s, 5*4(t)
	add		g, 6*4(t)
	mov		h, s
	add		s, 7*4(t)
#endif

	jmp		L_loop				// branch for next block

	// wrap up digest update round 48:63 for final block
L_final_block:
	rounds	a, b, c, d, e, f, g, h, 48
	rounds	e, f, g, h, a, b, c, d, 52 
	rounds	a, b, c, d, e, f, g, h, 56
	rounds	e, f, g, h, a, b, c, d, 60 

	// ctx->states += digests a-h
#if	defined (__x86_64__)
	add		a, 0*4(ctx)
	add		b, 1*4(ctx)
	add		c, 2*4(ctx)
	add		d, 3*4(ctx)
	add		e, 4*4(ctx)
	add		f, 5*4(ctx)
	add		g, 6*4(ctx)
	add		h, 7*4(ctx)
#else
	mov		ctx_addr, t
	add		a, 0*4(t)
	add		b, 1*4(t)
	mov		c, s
	add		s, 2*4(t)
	add		d, 3*4(t)
	add		e, 4*4(t)
	mov		f, s
	add		s, 5*4(t)
	add		g, 6*4(t)
	mov		h, s
	add		s, 7*4(t)
#endif

	// if kernel, restore xmm0-xmm7
#if	KERNEL
	movdqa	0*16+xmm_save, %xmm0
	movdqa	1*16+xmm_save, %xmm1
	movdqa	2*16+xmm_save, %xmm2
	movdqa	3*16+xmm_save, %xmm3
	movdqa	4*16+xmm_save, %xmm4
	movdqa	5*16+xmm_save, %xmm5
	movdqa	6*16+xmm_save, %xmm6
	movdqa	7*16+xmm_save, %xmm7
#endif

	// free allocated stack memory
	add		$stack_size, sp

	// restore callee-saved registers
#if defined (__x86_64__)
	pop		%r15
	pop		%r14
	pop		%r13
	pop		%r12
	pop		%rbx
	pop		%rbp
#else
    pop		%edi
    pop		%esi
	pop		%ebx
    pop		%ebp
#endif

	// return
	ret


#endif		// x86_64/i386
#endif		// x86_64/i386

Added Source/descriptors/digestDescriptors/vng_x86_sha2_descriptor/vng_x86_sha224.c.































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* Adapted from LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
/**
   @param sha224.c
   vng_x86_SHA-224 new NIST standard based off of vng_x86_SHA-256 truncated to 224 bits (Tom St Denis)
*/
#if defined (__x86_64__) || defined(__i386__)		// x86_64 or i386 architectures

const ccDescriptor vng_x86_sha224_desc =
{
    .implementation_info = &cc_sha224_impinfo,
	.dtype.digest.hashsize = CC_SHA224_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA224_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &vng_x86_sha224_init,
	.dtype.digest.process = &vng_x86_sha256_process,
	.dtype.digest.done = &vng_x86_sha224_done,
};


/* init the sha256 er... sha224 state ;-) */
/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int vng_x86_sha224_init(vng_x86_sha256_ctx *ctx)
{
    LTC_ARGCHK(ctx != NULL);

    // ctx->curlen = 0;
    ctx->length = 0;
    ctx->state[0] = 0xc1059ed8UL;
    ctx->state[1] = 0x367cd507UL;
    ctx->state[2] = 0x3070dd17UL;
    ctx->state[3] = 0xf70e5939UL;
    ctx->state[4] = 0xffc00b31UL;
    ctx->state[5] = 0x68581511UL;
    ctx->state[6] = 0x64f98fa7UL;
    ctx->state[7] = 0xbefa4fa4UL;

    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (28 bytes)
   @return CRYPT_OK if successful
*/
int vng_x86_sha224_done(vng_x86_sha256_ctx *ctx, unsigned char *out)
{
    unsigned char buf[32];
    int err;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    err = vng_x86_sha256_done(ctx, buf);
    CC_XMEMCPY(out, buf, 28);
    return err;
}

#endif

Added Source/descriptors/digestDescriptors/vng_x86_sha2_descriptor/vng_x86_sha224.h.







































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  vng_x86_sha224.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */


#if defined (__x86_64__) || defined(__i386__)		// x86_64 or i386 architectures

#ifndef _VNG_X86_SHA224_H_
#define _VNG_X86_SHA224_H_

/*
 * Note that vng_x86_sha256 is required for vng_x86_sha224.
 */

#define	VNG_X86_SHA224_HASHSIZE	28
#define	VNG_X86_SHA224_BLOCKSIZE	64

int vng_x86_sha224_init(vng_x86_sha256_ctx *ctx);
#define vng_x86_sha224_process vng_x86_sha256_process
int vng_x86_sha224_done(vng_x86_sha256_ctx *ctx, unsigned char *hash);

#endif /* _VNG_X86_SHA224_H_ */
#endif /* x86 */

Added Source/descriptors/digestDescriptors/vng_x86_sha2_descriptor/vng_x86_sha256.c.







































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */

#if defined (__x86_64__) || defined(__i386__)		// x86_64 or i386 architectures

#include <stdio.h>
#include "vng_x86_sha256.h"
#include "vng_x86_sha224.h"
#include "ltc_hashcommon.h"
#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_argchk.h"
#include "ccDescriptors.h"
#include "ccErrors.h"
#include "ccMemory.h"
#include "CommonDigest.h"

/**
  @file vng_x86_sha256.c
  vng_x86_SHA256 by Tom St Denis 
*/

const ccDescriptor vng_x86_sha256_desc =
{
    .implementation_info = &cc_sha256_impinfo,
	.dtype.digest.hashsize = CC_SHA256_DIGEST_LENGTH,
	.dtype.digest.blocksize = CC_SHA256_BLOCK_BYTES,
    .dtype.digest.digest_info = NULL,
	.dtype.digest.init = &vng_x86_sha256_init,
	.dtype.digest.process = &vng_x86_sha256_process,
	.dtype.digest.done = &vng_x86_sha256_done,
};

extern const uint32_t K256[64] =
{   0x428a2f98ul, 0x71374491ul, 0xb5c0fbcful, 0xe9b5dba5ul,
    0x3956c25bul, 0x59f111f1ul, 0x923f82a4ul, 0xab1c5ed5ul,
    0xd807aa98ul, 0x12835b01ul, 0x243185beul, 0x550c7dc3ul,
    0x72be5d74ul, 0x80deb1feul, 0x9bdc06a7ul, 0xc19bf174ul,
    0xe49b69c1ul, 0xefbe4786ul, 0x0fc19dc6ul, 0x240ca1ccul,
    0x2de92c6ful, 0x4a7484aaul, 0x5cb0a9dcul, 0x76f988daul,
    0x983e5152ul, 0xa831c66dul, 0xb00327c8ul, 0xbf597fc7ul,
    0xc6e00bf3ul, 0xd5a79147ul, 0x06ca6351ul, 0x14292967ul,
    0x27b70a85ul, 0x2e1b2138ul, 0x4d2c6dfcul, 0x53380d13ul,
    0x650a7354ul, 0x766a0abbul, 0x81c2c92eul, 0x92722c85ul,
    0xa2bfe8a1ul, 0xa81a664bul, 0xc24b8b70ul, 0xc76c51a3ul,
    0xd192e819ul, 0xd6990624ul, 0xf40e3585ul, 0x106aa070ul,
    0x19a4c116ul, 0x1e376c08ul, 0x2748774cul, 0x34b0bcb5ul,
    0x391c0cb3ul, 0x4ed8aa4aul, 0x5b9cca4ful, 0x682e6ff3ul,
    0x748f82eeul, 0x78a5636ful, 0x84c87814ul, 0x8cc70208ul,
    0x90befffaul, 0xa4506cebul, 0xbef9a3f7ul, 0xc67178f2ul,
};


/* Various logical functions */
#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
#define Maj(x,y,z)      (((x | y) & z) | (x & y)) 
#define S(x, n)         LTC_RORc((x),(n))
#define R(x, n)         (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x)       (S(x, 2) ^ S(x, 13) ^ S(x, 22))
#define Sigma1(x)       (S(x, 6) ^ S(x, 11) ^ S(x, 25))
#define Gamma0(x)       (S(x, 7) ^ S(x, 18) ^ R(x, 3))
#define Gamma1(x)       (S(x, 17) ^ S(x, 19) ^ R(x, 10))


#define FULLLENGTH_MASK 0xffffffffffffffc0
#define BUFFLENGTH_MASK 0x3f
/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int vng_x86_sha256_init(vng_x86_sha256_ctx *ctx)
{
    LTC_ARGCHK(ctx != NULL);

    ctx->length = 0;
    ctx->state[0] = 0x6A09E667UL;
    ctx->state[1] = 0xBB67AE85UL;
    ctx->state[2] = 0x3C6EF372UL;
    ctx->state[3] = 0xA54FF53AUL;
    ctx->state[4] = 0x510E527FUL;
    ctx->state[5] = 0x9B05688CUL;
    ctx->state[6] = 0x1F83D9ABUL;
    ctx->state[7] = 0x5BE0CD19UL;

    return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
int vng_x86_sha256_process(vng_x86_sha256_ctx *ctx, const unsigned char *in, unsigned long inlen)
{
    unsigned long n; 
    int err;
    int fullblocks, remainder, processed;
    uint64_t curlen;
    
    LTC_ARGCHK(ctx != NULL); 
    LTC_ARGCHK(in != NULL);
            
    curlen = ctx->length & BUFFLENGTH_MASK;
    
    if ((ctx->length + inlen) < ctx->length) { 
        return CRYPT_HASH_OVERFLOW; 
    }
    
    while (inlen > 0) { 
        if (curlen == 0 && inlen >= VNG_X86_SHA256_BLOCKSIZE && CC_XALIGNED(in, 4)) {
            fullblocks = inlen / VNG_X86_SHA256_BLOCKSIZE;
            remainder = inlen % VNG_X86_SHA256_BLOCKSIZE;
            processed = fullblocks * VNG_X86_SHA256_BLOCKSIZE;
            vng_x86_sha256_compress (ctx->state, in, fullblocks);
            ctx->length += VNG_X86_SHA256_BLOCKSIZE * 8 * fullblocks; 
            in += processed;
            inlen -= processed; 
        } else {
            n = MIN(inlen, (VNG_X86_SHA256_BLOCKSIZE - curlen)); 
            memcpy(ctx->buf + curlen, in, (size_t)n); 
            curlen += n; in += n; inlen -= n; 
            if (curlen == VNG_X86_SHA256_BLOCKSIZE) {
                vng_x86_sha256_compress (ctx->state, ctx->buf, 1);
                ctx->length += 8*VNG_X86_SHA256_BLOCKSIZE;
                curlen = 0; 
            } 
        } 
    }
    
    ctx->length = (ctx->length & FULLLENGTH_MASK) + curlen;
    
    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (32 bytes)
   @return CRYPT_OK if successful
*/
int vng_x86_sha256_done(vng_x86_sha256_ctx *ctx, unsigned char *out)
{
    int i;
    uint64_t curlen;

    LTC_ARGCHK(ctx  != NULL);
    LTC_ARGCHK(out != NULL);

    curlen = ctx->length & BUFFLENGTH_MASK;
    ctx->length &= FULLLENGTH_MASK;

    /* increase the length of the message */
    ctx->length += curlen * 8;

    /* append the '1' bit */
    ctx->buf[curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (curlen > 56) {
        while (curlen < 64) {
            ctx->buf[curlen++] = (unsigned char)0;
        }
        vng_x86_sha256_compress (ctx->state, ctx->buf, 1);

        curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (curlen < 56) {
        ctx->buf[curlen++] = (unsigned char)0;
    }

    /* store length */
    LTC_STORE64H(ctx->length, ctx->buf+56);
    vng_x86_sha256_compress (ctx->state, ctx->buf, 1);

    /* copy output */
    for (i = 0; i < 8; i++) {
        LTC_STORE32H(ctx->state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    ltc_zeromem(ctx, sizeof(hash_state));
#endif
    return CRYPT_OK;
}


#include "vng_x86_sha224.c"

#endif /* x86 */

Added Source/descriptors/digestDescriptors/vng_x86_sha2_descriptor/vng_x86_sha256.h.

















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  vng_x86_sha256.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */


#if defined (__x86_64__) || defined(__i386__)		// x86_64 or i386 architectures
#include <stdint.h>

#ifndef _VNG_X86_SHA256_H_
#define _VNG_X86_SHA256_H_

#define	VNG_X86_SHA256_HASHSIZE	32
#define	VNG_X86_SHA256_BLOCKSIZE	64

typedef struct vng_x86_sha256_state {
    uint64_t length;
    uint32_t state[8];
    unsigned char buf[VNG_X86_SHA256_BLOCKSIZE];
} vng_x86_sha256_ctx;

int vng_x86_sha256_init(vng_x86_sha256_ctx *ctx);
int vng_x86_sha256_process(vng_x86_sha256_ctx *ctx, const unsigned char *in,
    unsigned long inlen);
int vng_x86_sha256_done(vng_x86_sha256_ctx *ctx, unsigned char *hash);
void vng_x86_sha256_compress(void *c, const void *p, unsigned long num);

#endif /* _VNG_X86_SHA256_H_ */
#endif /* x86 */

Added Source/libDER/README.txt.





































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
                             libDER Library Notes
			    Last update to this file Jan. 26 2006 by dmitch

This module is a very lightweight implementation of a DER encoder and 
decoder. Unlike most other DER packages, this one does no malloc or 
copies when it encodes or decodes; decoding an item yields a pointer 
and a byte count which refer to memory inside of the "thing" being 
decoded. Likewise, when encoding, the caller mustsupply a target buffer
to which the encoded item is written. 

Support for encoding sequences and for decoding sequences and sets of 
known items is also included; when you decode a sequence, you get a
sequence of pointers and byte counts - again, no mallocs or copies occur. 

The directory libDER contains the DER decoding library proper. The main
API is in DER_Decode.h. Support for RSA keys, X509 certs, X509 CRLs, and
miscellaneous OIDs can also be found in libDER. 

Command line programs to parse and display the contents of X509 certificates
and CRLs, using libDER, can be found in the Tests directory. 

Revision History
----------------

  Date        svk tag		Changes
--------    -----------		----------------------------------------
01/26/06	 libDER-5		Avoid varargs macros for portability. 
01/03/06	 libDER-4		Initial distribution in RSACertLib.
12/23/05	 libDER-3		Fix DER_DECODE_ENABLE ifdef for DER_Decode.c.
							Add MD2, MD5 OID and DigestInfo capabilities.
12/13/05	 libDER-2		Added Apple Custom RSA public key formats. 
							Added PKCS1 RSA private keys. 
11/28/05	 libDER-1		Initial tag.

Added Source/libDER/Tests/AppleMobilePersonalizedTicket.h.





































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
 *  AppleMobilePersonalizedTicket.h
 *  ticketlib
 *
 *  Created by Jason Gosnell on 9/24/09.
 *  Copyright 2009 Apple, Inc. All rights reserved.
 *
 */

#ifndef APPLEMOBILEPERSONALIZEDTICKET_H
#define APPLEMOBILEPERSONALIZEDTICKET_H

const unsigned kApECIDTag                                 = 1;
const unsigned kApChipIDTag                               = 2;
const unsigned kApBoardIDTag                              = 3;
const unsigned kApProductionModeTag                       = 4;
const unsigned kApSecurityDomainTag                       = 5;
const unsigned kLLBBuildStringTag                         = 6;
const unsigned kiBootDigestTag                            = 7;
const unsigned kAppleLogoDigestTag                        = 8;
const unsigned kDeviceTreeDigestTag                       = 9;
const unsigned kKernelCacheDigestTag                      = 10;
const unsigned kDiagsDigestTag                            = 11;
const unsigned kBatteryChargingDigestTag                  = 12;
const unsigned kBatteryPluginDigestTag                    = 13;
const unsigned kBatteryLow0DigestTag                      = 14;
const unsigned kBatteryLow1DigestTag                      = 15;
const unsigned kRecoveryModeDigestTag                     = 16;
const unsigned kNeedServiceDigestTag                      = 17;
const unsigned kApNonceTag                                = 18;
const unsigned kApPriorTicketIDTag                        = 19;
const unsigned kiBSSBuildStringTag                        = 20;
const unsigned kHostiBootTag                              = 21;
const unsigned kiBECBuildStringTag                        = 22;
const unsigned kRestoreLogoDigestTag                      = 23;
const unsigned kRestoreDeviceTreeDigestTag                = 24;
const unsigned kRestoreKernelCacheDigestTag               = 25;
const unsigned kRestoreRamDiskDigestTag                   = 26;
const unsigned kOSDigestTag                               = 27;
const unsigned kApBindingDigestTag                        = 28;
const unsigned kApServerNonceTag                          = 29;
const unsigned kLLBPartialDigestTag                       = 30;
const unsigned kiBootPartialDigestTag                     = 31;
const unsigned kAppleLogoPartialDigestTag                 = 32;
const unsigned kDeviceTreePartialDigestTag                = 33;
const unsigned kKernelCachePartialDigestTag               = 34;
const unsigned kDiagsPartialDigestTag                     = 35;
const unsigned kBatteryChargingPartialDigestTag           = 36;
const unsigned kBatteryPluginPartialDigestTag             = 37;
const unsigned kBatteryLow0PartialDigestTag               = 38;
const unsigned kBatteryLow1PartialDigestTag               = 39;
const unsigned kRecoveryModePartialDigestTag              = 40;
const unsigned kNeedServicePartialDigestTag               = 41;
const unsigned kiBSSPartialDigestTag                      = 42;
const unsigned kiBECPartialDigestTag                      = 43;
const unsigned kRestoreLogoPartialDigestTag               = 44;
const unsigned kRestoreDeviceTreePartialDigestTag         = 45;
const unsigned kRestoreKernelCachePartialDigestTag        = 46;
const unsigned kRestoreRamDiskPartialDigestTag            = 47;
const unsigned kiBootTrustedTag                           = 48;
const unsigned kAppleLogoTrustedTag                       = 49;
const unsigned kDeviceTreeTrustedTag                      = 50;
const unsigned kKernelCacheTrustedTag                     = 51;
const unsigned kDiagsTrustedTag                           = 52;
const unsigned kBatteryChargingTrustedTag                 = 53;
const unsigned kBatteryPluginTrustedTag                   = 54;
const unsigned kBatteryLow0TrustedTag                     = 55;
const unsigned kBatteryLow1TrustedTag                     = 56;
const unsigned kRecoveryModeTrustedTag                    = 57;
const unsigned kNeedServiceTrustedTag                     = 58;
const unsigned kRestoreLogoTrustedTag                     = 59;
const unsigned kRestoreDeviceTreeTrustedTag               = 60;
const unsigned kRestoreKernelCacheTrustedTag              = 61;
const unsigned kRestoreRamDiskTrustedTag                  = 62;
const unsigned kBbSNUMTag                                 = 63;
const unsigned kBbChipIDTag                               = 64;
const unsigned kBbProductionModeTag                       = 65;
const unsigned kFlashPSIBuildStringTag                    = 66;
const unsigned kModemStackDigestTag                       = 67;
const unsigned kBbNonceTag                                = 68;
const unsigned kBbPriorTicketIdTag                        = 69;
const unsigned kRamPSIBuildStringTag                      = 70;
const unsigned kHostFlashPSITag                           = 71;
const unsigned kEBLDigestTag                              = 72;
const unsigned kStaticEEPDigestTag                        = 73;
const unsigned kBbApBindingDigestTag                      = 74;
const unsigned kBbServerNonceTag                          = 75;
const unsigned kRamPSIPartialDigestTag                    = 76;
const unsigned kFlashPSIPartialDigestTag                  = 77;
const unsigned kBatteryCharging0DigestTag                 = 78;
const unsigned kBatteryCharging1DigestTag                 = 79;
const unsigned kBatteryFullDigestTag                      = 80;
const unsigned kBatteryCharging0PartialDigestTag          = 81;
const unsigned kBatteryCharging1PartialDigestTag          = 82;
const unsigned kBatteryFullPartialDigestTag               = 83;
const unsigned kBatteryCharging0TrustedTag                = 84;
const unsigned kBatteryCharging1TrustedTag                = 85;
const unsigned kBatteryFullTrustedTag                     = 86;
const unsigned kUniqueBuildIDTag                          = 87;
const unsigned kBbGoldCertIdTag                           = 88;
const unsigned kBbSkeyIdTag                               = 89;
const unsigned kBasebandFirmwareFlashPSIVersionTag        = 90;
const unsigned kBasebandFirmwareModemStackDigestTag       = 91;
const unsigned kBasebandFirmwareRamPSIVersionTag          = 92;
const unsigned kBasebandFirmwareEBLDigestTag              = 93;
const unsigned kBasebandFirmwareFlashPSISecPackDigestTag  = 94;
const unsigned kBasebandFirmwareModemStackSecPackDigestTag= 95;
const unsigned kBasebandFirmwareFlashPSIDigestTag         = 96;
const unsigned kBasebandFirmwareRamPSIPartialDigestTag    = 97;
const unsigned kBasebandFirmwareFlashPSIPartialDigestTag  = 98;
const unsigned kBbJtagEnableTag                           = 99;


#endif /* APPLEMOBILEPERSONALIZEDTICKET_H */

Added Source/libDER/Tests/DER_Ticket.c.

























































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/*
 *  DER_Ticket.c
 *  libDER
 *
 *  Created by Michael Brouwer on 10/13/09.
 *  Copyright 2009 Apple Inc. All rights reserved.
 *
 */

#include "DER_Ticket.h"

#include <libDER/asn1Types.h>
#include <libDER/DER_Decode.h>
#include <libDER/DER_Encode.h>
#include <libDER/DER_Keys.h>

/* Application Processor Ticket */
const DERItemSpec DERApTicketItemSpecs[] =
{
	{ DER_OFFSET(DERApTicket, signatureAlgorithm),
			ASN1_CONSTR_SEQUENCE,
			DER_DEC_NO_OPTS | DER_ENC_WRITE_DER },
	{ DER_OFFSET(DERApTicket, body),
			ASN1_CONSTR_SET,
			DER_DEC_NO_OPTS | DER_DEC_SAVE_DER | DER_ENC_WRITE_DER },
	{ DER_OFFSET(DERApTicket, signature),
			ASN1_OCTET_STRING,
			DER_DEC_NO_OPTS },
	{ DER_OFFSET(DERApTicket, certificates),
			ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 1,
			DER_DEC_NO_OPTS | DER_ENC_WRITE_DER }
};
const DERSize DERNumApTicketItemSpecs =
	sizeof(DERApTicketItemSpecs) / sizeof(DERItemSpec);

/* Baseband Ticket */
const DERItemSpec DERBbTicketItemSpecs[] =
{
	{ DER_OFFSET(DERBbTicket, signatureAlgorithm),
			ASN1_CONSTR_SEQUENCE,
			DER_DEC_NO_OPTS | DER_ENC_WRITE_DER },
	{ DER_OFFSET(DERBbTicket, body),
			ASN1_CONSTR_SET,
			DER_DEC_NO_OPTS | DER_DEC_SAVE_DER | DER_ENC_WRITE_DER },
	{ DER_OFFSET(DERBbTicket, signature),
			ASN1_OCTET_STRING,
			DER_DEC_NO_OPTS },
	{ DER_OFFSET(DERBbTicket, gpuk),
			ASN1_CONTEXT_SPECIFIC | 2,
			DER_DEC_NO_OPTS }
};
const DERSize DERNumBbTicketItemSpecs =
	sizeof(DERBbTicketItemSpecs) / sizeof(DERItemSpec);

#if 0
/* We need to verify this value and use it here. */
const DERByte rsaWithSha1Algorithm[] = {
    0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x05
};
#endif

#ifdef FAST_SET_LOOKUP
/* Iterates over all the tags in the set to build an index returned in
   derSet. */
DERReturn DERDecodeSetContentInit(
	const DERItem   *content,			/* data to decode */
	DERSet          *derSet)            /* IN/OUT, to use in DERDecodeSetTag */
{
    DERReturn drtn;
    DERSequence derSeq;
    memset(derSet->byTag, 0, derSet->capacity);
    drtn = DERDecodeSeqContentInit(content, &derSeq);
    if (drtn == DR_Success) {
        DERDecodedInfo element;
        while ((drtn = DERDecodeSeqNext(&derSeq, &element)) == DR_Success) {
            if (element.tag >= derSet->capacity) return DR_UnexpectedTag;
            derSet->byTag[element.tag] = element.content.data;
        }
        if (drtn == DR_EndOfSequence) drtn = DR_Success;
    }
    derSet->end = content->data + content->length;

    return drtn;
}

DERReturn DERDecodeSetTag(
	DERSet          *derSet,		/* data to decode */
	DERTag			tag,			/* tag in sequence/set we are looking for. */
	DERItem         *content)		/* RETURNED */
{
    DERReturn drtn;
    DERTag tagNumber = tag & ASN1_TAGNUM_MASK;
    if (tagNumber > derSet->capacity)
        return DR_UnexpectedTag;
    DERByte *start = derSet->byTag[tagNumber];
    if (!start) return DR_UnexpectedTag;
    DERItem derItem = { .data = start, .length = derSet->end - start };
    DERDecodedInfo element;
    drtn = DERDecodeItem(&derItem, &element);
    if (drtn) return drtn;
    if (tag != element.tag) return DR_UnexpectedTag;
    *content = element.content;

    return drtn;
}
#endif /* FAST_SET_LOOKUP */

/* Returns the item with tag from the sequence or set pointed to by der.
   result DR_EndOfSequence if the tag was not found. */
DERReturn DERSetDecodeItemWithTag(
	const DERItem	*der,			/* data to decode */
	DERTag			tag,			/* tag in sequence/set we are looking for. */
	DERItem         *content)		/* RETURNED */
{
    DERReturn drtn;
    DERSequence derSeq;
    DERTag topTag;
    drtn = DERDecodeSeqInit(der, &topTag, &derSeq);
    if (drtn == DR_Success) {
        DERDecodedInfo info;
        while ((drtn = DERDecodeSeqNext(&derSeq, &info)) == DR_Success) {
            if (info.tag == tag) {
                *content = info.content;
                return DR_Success;
            }
        }
    }

    return drtn;
}

DERReturn DERDecodeApTicket(
	const DERItem	*contents,
	DERApTicket		*ticket,            /* RETURNED */
	DERSize			*numUsedBytes)      /* RETURNED */
{
    DERReturn drtn;
    DERDecodedInfo decodedTicket;
    drtn = DERDecodeItem(contents, &decodedTicket);
    if (drtn != DR_Success) goto badTicket;
    drtn = DERParseSequenceContent(&decodedTicket.content,
        DERNumApTicketItemSpecs, DERApTicketItemSpecs, ticket, 0);
    if (drtn != DR_Success) goto badTicket;

    /* Decode the algorithm sequence. */
    DERAlgorithmId algorithm = {};
    drtn = DERParseSequenceContent(&ticket->signatureAlgorithm,
        DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs, &algorithm, 0);
    if (drtn != DR_Success) goto badTicket;
    /* TODO Check algorithm oid and ensure there are no params.
       Alternatively replace the code above with a simple memcmp with
       an already ASN.1 encoded algorithm parms block. */

badTicket:
    *numUsedBytes = decodedTicket.content.length +
        decodedTicket.content.data - contents->data;

    return drtn;
}

DERReturn DERDecodeBbTicket(
	const DERItem	*contents,
	DERBbTicket		*ticket,            /* RETURNED */
	DERSize			*numUsedBytes)      /* RETURNED */
{
    DERReturn drtn;
    DERDecodedInfo decodedTicket;
    drtn = DERDecodeItem(contents, &decodedTicket);
    if (drtn != DR_Success) goto badTicket;
    drtn = DERParseSequenceContent(&decodedTicket.content,
        DERNumBbTicketItemSpecs, DERBbTicketItemSpecs, ticket, 0);
    if (drtn != DR_Success) goto badTicket;

    /* Decode the algorithm sequence. */
    DERAlgorithmId algorithm = {};
    drtn = DERParseSequenceContent(&ticket->signatureAlgorithm,
        DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs, &algorithm, 0);
    if (drtn != DR_Success) goto badTicket;
    /* TODO Check algorithm oid and ensure there are no params.
       Alternatively replace the code above with a simple memcmp with
       an already ASN.1 encoded algorithm parms block. */

badTicket:
    *numUsedBytes = decodedTicket.content.length +
        decodedTicket.content.data - contents->data;

    return drtn;
}

Added Source/libDER/Tests/DER_Ticket.h.



































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
 *  DER_Ticket.h
 *  libDER
 *
 *  Created by Michael Brouwer on 10/13/09.
 *  Copyright 2009 Apple Inc. All rights reserved.
 *
 */

#include <libDER/libDER.h>


#define FAST_SET_LOOKUP     1

#ifdef FAST_SET_LOOKUP
/* state representing a fast by tag set accessor, the caller needs to provide
   a set large enough to hold all */
typedef struct {
	DERTag	capacity;   /* should be large enough to hold all encountered tags.
                           otherwise DR_UnexpectedTag will be returned, note
                           that only one tag per tag number can exist. */
	DERByte	*end;
	DERByte	*byTag[];   /* maxTag element array of pointers to tag + length
                           of items in set indexed by tagNumber. */
} DERSet;

/* Iterates over all the tags in the set to build an index returned in
   derSet. */
DERReturn DERDecodeSetContentInit(
	const DERItem   *der,			/* data to decode */
	DERSet          *derSet);		/* IN/OUT, to use in DERDecodeSetTag */

/* Returns DR_UnexpectedTag if the requested tag is not in derSet, returns
   the content of the decoded item in content otherwise. */
DERReturn DERDecodeSetTag(
	DERSet          *derSeq,		/* data to decode */
	DERTag			tag,			/* tag in sequence/set we are looking for. */
	DERItem         *content);		/* RETURNED */
#endif /* FAST_SET_LOOKUP */


DERReturn DERSetDecodeItemWithTag(
	const DERItem	*der,			/* data to decode */
	DERTag			tag,			/* tag in sequence/set we are looking for. */
	DERItem         *content);		/* RETURNED */


/* Application Processor Ticket */
typedef struct {
	DERItem		signatureAlgorithm;     /* AlgorithmId */
	DERItem		body;                   /* SET OF OCTECT STRING, DER_DEC_SAVE_DER */
	DERItem		signature;              /* OCTET STRING */
	DERItem		certificates;            /* SEQUENCE of CERTIFICATE */
} DERApTicket;

/* DERItemSpecs to decode into a DERApTicket */
extern const DERItemSpec DERApTicketItemSpecs[];
extern const DERSize DERNumApTicketItemSpecs;

DERReturn DERDecodeApTicket(
	const DERItem	*contents,
	DERApTicket		*ticket,            /* RETURNED */
	DERSize			*numUsedBytes);     /* RETURNED */


/* Baseband Ticket */
typedef struct {
	DERItem		signatureAlgorithm;     /* AlgorithmId */
	DERItem		body;                   /* SET OF OCTECT STRING, DER_DEC_SAVE_DER */
	DERItem		signature;              /* OCTET STRING */
	DERItem		gpuk;                   /* OCTET STRING */
} DERBbTicket;

/* DERItemSpecs to decode into a DERBbTicket */
extern const DERItemSpec DERBbTicketItemSpecs[];
extern const DERSize DERNumBbTicketItemSpecs;

DERReturn DERDecodeBbTicket(
	const DERItem	*contents,
	DERBbTicket		*ticket,            /* RETURNED */
	DERSize			*numUsedBytes);     /* RETURNED */

Added Source/libDER/Tests/G1_GPrK.pem.































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCv34jZMZdANoIYptLYgU121ucX5UAKaKQUlihPwS6W2R5phNog
w5PH0cBv+znVYhqmZLW8ctV0nQqk8Zo33I0qeJeBE2zptK6Yv79mhmbY14VhKeMc
Smjb2+o3kVYlLMKoB3Xl76yjB0InYOnddK8JoLXkK7PYbTiBfejxT8ZuMQIBAwKB
gHU/sJDLuirPAWXEjJBWM6SPRLqY1VxFwrhkGt/WHw87aZut5sCCYoU2gEqne+OW
vG7tzn2h46MTXG32Zs/oXhs1dKaKdHJyKZcrC+SMKjpL+tSVflujUDkF3qFnCneX
x1n16nWMOuwAoVlrXuqG3TLUiYBBbJAZy2rJuDYid/WjAkEA1tzwbnj4coGtW++2
ExAbIt6szd96y2MOGWbm3a+rm0D2FHrUfq8yamGsrRRtF9HM+kbTgSM3ulGExA6w
0L0p4wJBANGLltVFRZbuiKM92aEXZkKudXvGGAoNeDm1XpkWxi3WqwIbYR6lDpvu
dJLHEJKRcGeg0EhtyIw13ItF70tVU9sCQQCPPfWe+1BMVnOSn863YBIXPx3elPyH
l167me8+dR0SK064UeL/H3bxlnMeDZ4P4TNRhI0AwiUm4QMtXyCLKMaXAkEAi7Jk
ji4uZJ8Fwik7wLpELHROUoQQBrOle84/ELnZc+RyAWeWFG4JvUmjDIS1twugRRXg
MEkwXXk9si6fh4435wJAOYJia32scDKS4C20zVc12mQutnaK6g9Bdt2vzH3u82Ef
nchdtuR4ipWl3v8xX6jX3XdD31xa2Dh840iP1wjPrg==
-----END RSA PRIVATE KEY-----

Added Source/libDER/Tests/S5L8920_TATSU_FAC_DARWIN_DEV_CHAIN.der.

cannot compute difference between binary files

Added Source/libDER/Tests/bb_ticket.bin.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/EndCertificateCP.01.01.crt.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/Test_CRL_CA1.crl.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/Test_CRL_CA1.crl.pem.



























>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
-----BEGIN X509 CRL-----
MIIB3zCByDANBgkqhkiG9w0BAQQFADBvMQswCQYDVQQGEwJkZTEgMB4GA1UEChMX
SW5zZWN1cmVUZXN0Q2VydGlmaWNhdGUxFzAVBgNVBAMTDkZvciBUZXN0cyBPbmx5
MSUwIwYJKoZIhvcNAQkBFhZpbnNlY3VyZUB0ZXN0Lmluc2VjdXJlFw0wMTA4MTcx
MTEyMDNaFw0wNjA4MTYxMTEyMDNaMCgwEgIBAxcNMDEwODE3MTExMDM5WjASAgEF
Fw0wMTA4MTcxMTExNTlaMA0GCSqGSIb3DQEBBAUAA4IBAQB47lMVCKlPoBAgLway
76eNRq1749jt/7g/Ouh06isNM66/CgzVL2xKSC3s2FX4xKg320niWI6Dvm4H3M6I
7RvuoCvZBVpu1MA8z2No89g2UPWlSxUAvuvo2GOGRgo+8nc/84g8biLUxTSF8Vs4
T1Hngo1qrfePM4ou1uu7LhRnR8tuIVoQT6W3RSlEsQRBRM3y+VkOPAf0GBGyl6WG
WiymXHqsqis80WbX50tr859Cltqbu2yaFAX++IEBBDB7JoVi1blumgarqfXYkoUW
n9d3F8qySNjsfhOV613fXpmfXFZ33uTFsLSoihP8f6+Cusx2rfuGap7jOPv7j7sj
l2Y1
-----END X509 CRL-----

Added Source/libDER/Tests/certsCrls/TrustAnchorCP.01.01.crt.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/TrustAnchorCRLCP.01.01.crl.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/apple_v3.000.cer.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/apple_v3.001.cer.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/entrust_v3.100.cer.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/entrust_v3.101.cer.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/keybank_v3.100.cer.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/keybank_v3.101.cer.

cannot compute difference between binary files

Added Source/libDER/Tests/certsCrls/keybank_v3.102.cer.

cannot compute difference between binary files

Added Source/libDER/Tests/parseCert.c.











































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/*
 * Copyright (c) 2005-2007,2010 Apple Inc. All Rights Reserved.
 *
 * parseCert.c - parse a DER-encoded X509 certificate using libDER. 
 */
 
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
#include <unistd.h>
#include <libDER/libDER.h>
#include <libDER/asn1Types.h>
#include <libDER/DER_CertCrl.h>
#include <libDER/DER_Keys.h>
#include <libDERUtils/fileIo.h>
#include <libDERUtils/libDERUtils.h>
#include <libDERUtils/printFields.h>

static void usage(char **argv)
{
	printf("usage: %s certFile [options]\n", argv[0]);
	printf("Options:\n");
	printf("  -v     -- verbose \n");
	/* etc. */
	exit(1);
}

static void	printValidity(
	DERItem *validity, 
	int verbose)
{
	DERReturn drtn;
	DERValidity derv;
	
	drtn = DERParseSequenceContent(validity,
		DERNumValidityItemSpecs, DERValidityItemSpecs,
		&derv, sizeof(derv));
	if(drtn) {
		DERPerror("DERParseSequenceContent(validity)", drtn);
		return;
	}
	decodePrintItem("notBefore", IT_Leaf, verbose, &derv.notBefore);
	decodePrintItem("notAfter",  IT_Leaf, verbose, &derv.notAfter);
	
}

int main(int argc, char **argv)
{
	unsigned char *certData = NULL;
	unsigned certDataLen = 0;
	DERSignedCertCrl signedCert;
	DERTBSCert tbs;
	DERReturn drtn;
	DERItem item;
	int verbose = 0;
	extern char *optarg;
	int arg;
	extern int optind;
	
	if(argc < 2) {
		usage(argv);
	}
	if(readFile(argv[1], &certData, &certDataLen)) {
		printf("***Error reading cert from %s. Aborting.\n", argv[1]);
		exit(1);
	}

	optind = 2;
	while ((arg = getopt(argc, argv, "vh")) != -1) {
		switch (arg) {
			case 'v':
				verbose = 1;
				break;
			case 'h':
				usage(argv);
		}
	}
	if(optind != argc) {
		usage(argv);
	}

	/* Top level decode of signed cert into 3 components */
	item.data = certData;
	item.length = certDataLen;
	drtn = DERParseSequence(&item, DERNumSignedCertCrlItemSpecs, DERSignedCertCrlItemSpecs,
		&signedCert, sizeof(signedCert));
	if(drtn) {
		DERPerror("DERParseSequence(SignedCert)", drtn);
		exit(1);
	}
	printItem("TBSCert", IT_Branch, verbose, ASN1_CONSTR_SEQUENCE, &signedCert.tbs);
	
	incrIndent();
	
	/* decode the TBSCert - it was saved in full DER form */
	drtn = DERParseSequence(&signedCert.tbs, 
		DERNumTBSCertItemSpecs, DERTBSCertItemSpecs,
		&tbs, sizeof(tbs));
	if(drtn) {
		DERPerror("DERParseSequenceContent(TBSCert)", drtn);
		exit(1);
	}
	if(tbs.version.data) {
		/* unwrap the explicitly tagged integer.... */
		decodePrintItem("version", IT_Leaf, verbose, &tbs.version);
	}
	printItem("serialNum", IT_Leaf, verbose, ASN1_INTEGER, &tbs.serialNum);
	
	printItem("tbsSigAlg", IT_Branch, verbose, ASN1_CONSTR_SEQUENCE, &tbs.tbsSigAlg);
	incrIndent();
	printAlgId(&tbs.tbsSigAlg, verbose);
	decrIndent();
	
	printItem("issuer", IT_Leaf, verbose, ASN1_CONSTR_SEQUENCE, &tbs.issuer);
	printItem("subject", IT_Leaf, verbose, ASN1_CONSTR_SEQUENCE, &tbs.subject);
	
	printItem("validity", IT_Branch, verbose, ASN1_CONSTR_SEQUENCE, &tbs.validity);
	incrIndent();
	printValidity(&tbs.validity, verbose);
	decrIndent();
	
	printItem("subjectPubKey", IT_Branch, verbose, ASN1_CONSTR_SEQUENCE, 
		&tbs.subjectPubKey);
	incrIndent();
	printSubjPubKeyInfo(&tbs.subjectPubKey, verbose);
	decrIndent();
	
	if(tbs.issuerID.data) {
		/* found tag is implicit context specific: tell printItem what it really is */
		printItem("issuerID", IT_Leaf, verbose, ASN1_BIT_STRING, &tbs.issuerID);
	}
	if(tbs.subjectID.data) {
		printItem("subjectID", IT_Leaf, verbose, ASN1_BIT_STRING, &tbs.subjectID);
	}
	if(tbs.extensions.data) {
		printItem("extensions", IT_Leaf, verbose, ASN1_CONSTRUCTED | ASN1_CONTEXT_SPECIFIC | 3, 
			&tbs.extensions);
	}
	decrIndent();
	
	printItem("sigAlg", IT_Branch, verbose, ASN1_CONSTR_SEQUENCE, &signedCert.sigAlg);
	incrIndent();
	printAlgId(&signedCert.sigAlg, verbose);
	decrIndent();

	printItem("sig", IT_Leaf, verbose, ASN1_BIT_STRING, &signedCert.sig);
	
	return 0;
}

Added Source/libDER/Tests/parseCrl.c.















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/*
 * Copyright (c) 2005-2007,2010 Apple Inc. All Rights Reserved.
 *
 * parseCrl.c - parse a DER-encoded X509 CRL using libDER. 
 */
 
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
#include <unistd.h>
#include <libDER/libDER.h>
#include <libDER/asn1Types.h>
#include <libDER/DER_CertCrl.h>
#include <libDER/DER_Keys.h>
#include <libDERUtils/fileIo.h>
#include <libDERUtils/libDERUtils.h>
#include <libDERUtils/printFields.h>

static void usage(char **argv)
{
	printf("usage: %s crlFile [options]\n", argv[0]);
	printf("Options:\n");
	printf("  -v     -- verbose \n");
	/* etc. */
	exit(1);
}

/* 
 * This is a SEQUENCE OF so we use the low-level DERDecodeSeq* routines to snag one entry 
 * at a time.
 */
static void	printRevokedCerts(
	DERItem *revokedCerts, 
	int verbose)
{
	DERReturn drtn;
	DERDecodedInfo currItem;
	DERSequence seq;
	unsigned certNum;
	DERRevokedCert revoked;
	
	drtn = DERDecodeSeqContentInit(revokedCerts, &seq);
	if(drtn) {
		DERPerror("DERDecodeSeqContentInit(revokedCerts)", drtn);
		return;
	}
	
	for(certNum=0; ; certNum++) {
		drtn = DERDecodeSeqNext(&seq, &currItem);
		switch(drtn) {
			case DR_EndOfSequence:
				/* normal termination */
				return;
			default:
				DERPerror("DERDecodeSeqNext", drtn);
				return;
			case DR_Success:
				doIndent();
				printf("revoked cert %u\n", certNum);
				incrIndent();
				drtn = DERParseSequenceContent(&currItem.content, 
					DERNumRevokedCertItemSpecs, DERRevokedCertItemSpecs,
					&revoked, sizeof(revoked));
				if(drtn) {
					DERPerror("DERParseSequenceContent(RevokedCert)", drtn);
					decrIndent();
					return;
				}
				printItem("serialNum", IT_Leaf, verbose, ASN1_INTEGER, &revoked.serialNum);
				decodePrintItem("revocationDate",  IT_Leaf, verbose, &revoked.revocationDate);
				printItem("extensions", IT_Branch, verbose, ASN1_CONSTR_SEQUENCE, &revoked.extensions);
				decrIndent();
		}
	}
}

int main(int argc, char **argv)
{
	unsigned char *crlData = NULL;
	unsigned crlDataLen = 0;
	DERSignedCertCrl signedCrl;
	DERTBSCrl tbs;
	DERReturn drtn;
	DERItem item;
	int verbose = 0;
	extern char *optarg;
	int arg;
	extern int optind;
	
	if(argc < 2) {
		usage(argv);
	}
	if(readFile(argv[1], &crlData, &crlDataLen)) {
		printf("***Error reading CRL from %s. Aborting.\n", argv[1]);
		exit(1);
	}

	optind = 2;
	while ((arg = getopt(argc, argv, "vh")) != -1) {
		switch (arg) {
			case 'v':
				verbose = 1;
				break;
			case 'h':
				usage(argv);
		}
	}
	if(optind != argc) {
		usage(argv);
	}

	/* Top level decode of signed CRL into 3 components */
	item.data = crlData;
	item.length = crlDataLen;
	drtn = DERParseSequence(&item, DERNumSignedCertCrlItemSpecs, DERSignedCertCrlItemSpecs,
		&signedCrl, sizeof(signedCrl));
	if(drtn) {
		DERPerror("DERParseSequence(SignedCrl)", drtn);
		exit(1);
	}
	printItem("TBSCrl", IT_Branch, verbose, ASN1_CONSTR_SEQUENCE, &signedCrl.tbs);
	
	incrIndent();
	
	/* decode the TBSCrl - it was saved in full DER form */
	drtn = DERParseSequence(&signedCrl.tbs, 
		DERNumTBSCrlItemSpecs, DERTBSCrlItemSpecs,
		&tbs, sizeof(tbs));
	if(drtn) {
		DERPerror("DERParseSequenceContent(TBSCrl)", drtn);
		exit(1);
	}
	if(tbs.version.data) {
		printItem("version", IT_Leaf, verbose, ASN1_INTEGER, &tbs.version);
	}
	
	printItem("tbsSigAlg", IT_Branch, verbose, ASN1_CONSTR_SEQUENCE, &tbs.tbsSigAlg);
	incrIndent();
	printAlgId(&tbs.tbsSigAlg, verbose);
	decrIndent();
	
	printItem("issuer", IT_Leaf, verbose, ASN1_CONSTR_SEQUENCE, &tbs.issuer);
	
	decodePrintItem("thisUpdate",  IT_Leaf, verbose, &tbs.thisUpdate);
	decodePrintItem("nextUpdate",  IT_Leaf, verbose, &tbs.nextUpdate);
	
	if(tbs.revokedCerts.data) {
		printItem("version", IT_Leaf, verbose, ASN1_CONSTR_SEQUENCE, &tbs.revokedCerts);
		incrIndent();
		printRevokedCerts(&tbs.revokedCerts, verbose);
		decrIndent();
	}
	
	if(tbs.extensions.data) {
		printItem("extensions", IT_Leaf, verbose, ASN1_CONSTRUCTED | ASN1_CONTEXT_SPECIFIC | 3, 
			&tbs.extensions);
	}
	
	printItem("sigAlg", IT_Branch, verbose, ASN1_CONSTR_SEQUENCE, &signedCrl.sigAlg);
	incrIndent();
	printAlgId(&signedCrl.sigAlg, verbose);
	decrIndent();

	printItem("sig", IT_Leaf, verbose, ASN1_BIT_STRING, &signedCrl.sig);
	
	return 0;
}

Added Source/libDER/Tests/parseTicket.c.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>
#include <openssl/bio.h>
#include <openssl/x509.h>
#include <openssl/sha.h>
#include "AppleMobilePersonalizedTicket.h"
#include <libDER/libDER.h>
#include <libDER/asn1Types.h>
#include <libDER/DER_Decode.h>
#include <libDER/DER_Encode.h>
#include <libDER/DER_Keys.h>
#include <libDER/oids.h>
#include "DER_Ticket.h"

const unsigned char GoldKeyCert[] = {
0x01, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00,
0x00, 0x08, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x31, 0x6e, 0xc6, 0x4f,
0xf1, 0xe8, 0x7d, 0x81, 0x38, 0x6d, 0xd8, 0xb3,
0x2b, 0xe4, 0xb5, 0xa0, 0x09, 0xaf, 0x74, 0xdd,
0xe9, 0x60, 0x27, 0x42, 0x07, 0xa3, 0xac, 0xef,
0xe5, 0x75, 0x07, 0xa8, 0xc2, 0x2c, 0x25, 0x56,
0x91, 0x37, 0xea, 0xdb, 0xdb, 0x68, 0x4a, 0x1c,
0xe3, 0x29, 0x61, 0x85, 0xd7, 0xd8, 0x66, 0x86,
0x66, 0xbf, 0xbf, 0x98, 0xae, 0xb4, 0xe9, 0x6c,
0x13, 0x81, 0x97, 0x78, 0x2a, 0x8d, 0xdc, 0x37,
0x9a, 0xf1, 0xa4, 0x0a, 0x9d, 0x74, 0xd5, 0x72,
0xbc, 0xb5, 0x64, 0xa6, 0x1a, 0x62, 0xd5, 0x39,
0xfb, 0x6f, 0xc0, 0xd1, 0xc7, 0x93, 0xc3, 0x20,
0xda, 0x84, 0x69, 0x1e, 0xd9, 0x96, 0x2e, 0xc1,
0x4f, 0x28, 0x96, 0x14, 0xa4, 0x68, 0x0a, 0x40,
0xe5, 0x17, 0xe7, 0xd6, 0x76, 0x4d, 0x81, 0xd8,
0xd2, 0xa6, 0x18, 0x82, 0x36, 0x40, 0x97, 0x31,
0xd9, 0x88, 0xdf, 0xaf, 0x05, 0x3a, 0x4b, 0x4e,
0x1b, 0x4a, 0x76, 0x6f, 0xb9, 0x6c, 0x18, 0x5d,
0xd5, 0x98, 0xf0, 0xf1, 0xbe, 0x0a, 0xd9, 0x57,
0x85, 0xc6, 0xc9, 0x63, 0xb3, 0xf5, 0x21, 0x26,
0x07, 0xba, 0x6a, 0x05, 0xfb, 0x5a, 0x06, 0x87,
0x2a, 0x30, 0x3f, 0xa9, 0xea, 0xab, 0x0e, 0x50,
0x70, 0x3b, 0x7e, 0xd4, 0xd2, 0x8c, 0xf3, 0xa1,
0xcf, 0x9a, 0x6c, 0x6b, 0xcf, 0x9b, 0x1b, 0x2a,
0x97, 0x6a, 0x3c, 0x38, 0x40, 0x43, 0xb1, 0x97,
0x19, 0x07, 0x64, 0x11, 0x94, 0x73, 0x14, 0xc9,
0xa3, 0xfe, 0x7f, 0xf6, 0x64, 0x23, 0x73, 0xe3,
0x76, 0xce, 0xf7, 0xf4, 0x2f, 0x6c, 0x9d, 0x0a,
0xf6, 0x39, 0xe6, 0x1d, 0xb2, 0x17, 0x29, 0x39,
0x98, 0x52, 0xda, 0xe0, 0x31, 0xa1, 0xfa, 0x85,
0x52, 0xc2, 0x60, 0xb5, 0x11, 0x42, 0xc6, 0x9b,
0x55, 0xd8, 0x40, 0x37, 0xf7, 0xdb, 0x01, 0x6a,
0xd5, 0x26, 0x3b, 0x27, 0x07, 0x20, 0xf7, 0x58,
0xd5, 0xa4, 0x1c, 0xe6, 0x2f, 0x74, 0x14, 0x6e,
0xa4, 0xe8, 0xc8, 0xe8, 0x9a, 0x39, 0x6d, 0xde,
0x7f, 0x67, 0x65, 0x40, 0x68, 0x26, 0x65, 0x62,
0x95, 0x87, 0x45, 0x62, 0x0d, 0x8d, 0x42, 0xad,
0x3b, 0x4f, 0xd3, 0x8f, 0x58, 0xcb, 0x61, 0x46,
0xc9, 0x3d, 0x7d, 0x75, 0x3c, 0x6d, 0xac, 0xdf,
0x53, 0xf4, 0x66, 0x9e, 0x14, 0x82, 0xc7, 0xd1,
0xd0, 0xec, 0x92, 0x24, 0x97, 0x1e, 0xc9, 0x7a,
0xfd, 0x8f, 0x75, 0xe2, 0xfd, 0x7e, 0x07, 0x44,
0x46, 0x56, 0x64, 0x9b, 0x1b, 0x17, 0xfa, 0xd6,
0xf5, 0xdb, 0xc9, 0x27, 0x3b, 0x60, 0x27, 0x2f,
0x84, 0xd7, 0xac, 0x7f, 0xf3, 0xa7, 0x16, 0x31,
0xfa, 0x19, 0x54, 0x57, 0x98, 0xb5, 0xdb, 0x9c,
0xc3, 0xb5, 0x55, 0x72, 0x98, 0x2f, 0x56, 0x33,
0x7c, 0x38, 0x1f, 0xb4, 0x8c, 0x94, 0x1a, 0x6a,
0x26, 0x8a, 0x84, 0xfc, 0x8d, 0xb1, 0x49, 0xbb,
0x6d, 0x11, 0x36, 0xc9, 0x05, 0x57, 0x87, 0xd2,
0xdb, 0xd3, 0xe3, 0xea, 0x08, 0xb2, 0x9f, 0x44,
0x85, 0xd7, 0xd4, 0x96, 0x25, 0xeb, 0x2b, 0xca,
0x86, 0x0f, 0x33, 0x69, 0xc4, 0xda, 0x98, 0x68,
0x21, 0xad, 0xd8, 0xc4, 0x4e, 0x46, 0x33, 0x43,
0xad, 0xe7, 0xfe, 0x58, 0x10, 0x00, 0x76, 0x3c,
0xd4, 0x14, 0x5a, 0x74, 0x43, 0x04, 0xc3, 0xdd,
0x46, 0xc3, 0xe0, 0x4b, 0x46, 0xb5, 0x84, 0xcb,
0xe6, 0x40, 0x71, 0xdf, 0x50, 0x16, 0x5f, 0xf0,
0x0f, 0xc5, 0x9c, 0x50, 0x64, 0xe0, 0x64, 0x1c,
0x58, 0x87, 0xae, 0x91, 0x9c, 0xb6, 0x57, 0x77,
0xf0, 0xc4, 0x3e, 0xcf, 0xb6, 0xc5, 0x10, 0x0c,
0xea, 0x5b, 0xcc, 0xaf, 0xee, 0x7b, 0x15, 0x4e,
0x4e, 0x3c, 0x29, 0x9c, 0xf8, 0xe6, 0x59, 0xca,
0xaf, 0x48, 0x12, 0x99, 0x76, 0xde, 0x54, 0xe2,
0x75, 0x62, 0x31, 0x17,
};

#define SIG_LEN     128
#define HASH_LEN    20

const unsigned char fakeAlgOID[] = {
0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x05
};

const unsigned char fakeG3Cert[] = {
0x01,0x00,0x00,0x00,
0x1c,0x00,0x00,0x00,
0x01,0x08,0x00,0x00,
0x10,0x0a,0x00,0x00,
0x00,0x00,0x00,0x00,
0x00,0x04,0x00,0x00,
0x01,0x00,0x01,0x00,
0x19,0xfc,0xb6,0x7b,0x4e,0xa8,0xd7,0xb1,0xeb,0xf9,0x19,0x28,0x07,0x7f,0x47,0x4c,
0xe1,0x9f,0xbe,0x01,0x15,0x5c,0xea,0xda,0xc3,0xd1,0x59,0x3c,0x75,0xed,0x00,0x7b,
0x22,0x67,0x22,0xd6,0xd3,0xee,0xc2,0x04,0xdf,0x47,0xc4,0x85,0xc0,0x56,0xa4,0x8d,
0xf3,0xf0,0xcf,0x00,0x9d,0xd2,0x03,0xc1,0x23,0x3f,0xc8,0x9f,0xef,0xfe,0xea,0x50,
0x33,0x6b,0xbe,0x74,0x1a,0xa3,0x3c,0x13,0xa2,0xc5,0xf6,0x75,0x88,0x1d,0x3f,0xba,
0xff,0x0d,0x47,0xab,0xbe,0xfe,0x42,0xd3,0xea,0xe2,0xe2,0xb0,0x06,0xd7,0x88,0xf8,
0x1d,0x93,0xdf,0x86,0xbd,0xd8,0xa8,0x5f,0x2b,0xe3,0x97,0x41,0xa1,0xc6,0x1d,0x69,
0xe9,0x88,0xdf,0x87,0xbb,0x1b,0xff,0x31,0x82,0xae,0x8a,0x69,0x31,0xca,0xc3,0x90,
0x0f,0x0d,0x22,0xa3,0xcf,0x8d,0xcc,0x23,0x03,0x10,0xed,0x74,0x8e,0x13,0x74,0x49,
0x9d,0x9a,0x1c,0xf2,0x57,0x2d,0x18,0x89,0x6d,0xb8,0xcc,0xab,0xcf,0xd9,0xd8,0x0e,
0x46,0x68,0x98,0xa3,0x81,0x5d,0x18,0xe8,0x4d,0x03,0x96,0x14,0xc5,0xaf,0x21,0x91,
0xb7,0x8c,0x97,0xa1,0x85,0xde,0x85,0x78,0xa8,0xd7,0x25,0x20,0x9b,0x2b,0x98,0x36,
0xd5,0xfe,0x14,0x9b,0x5d,0xe3,0x78,0xf4,0xd6,0xb2,0x15,0xc9,0xfd,0x13,0x77,0x7b,
0x8a,0x5e,0x9e,0x85,0xff,0x53,0x6d,0x24,0x5d,0xc9,0x52,0x16,0x98,0x18,0xb1,0xaf,
0xe1,0x6a,0xd6,0xe8,0xa9,0x7c,0x78,0x8e,0x9f,0x79,0x21,0xa1,0xde,0xf4,0xaf,0x9c,
0xd4,0x61,0x52,0xf9,0xe7,0xfc,0xd7,0x10,0x1b,0x91,0x66,0x14,0x26,0xfd,0xda,0xee,
0xe5,0xd9,0x4c,0xb7,0x9d,0x6d,0x17,0xf8,0xc2,0x21,0xb4,0x34,0x08,0x0c,0x44,0x79,
0x53,0x9c,0x81,0xbf,0x1f,0x22,0x0a,0xa6,0xe7,0x22,0x5f,0x5c,0xcb,0x31,0x2e,0xf5,
0x0c,0x1a,0xf1,0x67,0x13,0x7f,0xe6,0xb3,0xb2,0xfe,0x6b,0x09,0xac,0xa6,0xd4,0x14,
0xe7,0xe9,0x11,0x0e,0x49,0x99,0x06,0x04,0xa4,0x43,0x22,0xec,0x9f,0x59,0x83,0xfb,
0xef,0xa3,0x8f,0x6b,0xde,0x70,0x0c,0xbb,0x89,0xe9,0x88,0xbc,0xeb,0x36,0x42,0x42,
0x50,0x84,0xf5,0x93,0x98,0x93,0xed,0xa2,0x1f,0x13,0x60,0x36,0xc8,0x2f,0x9f,0xd1,
0xc4,0x23,0xf6,0xd0,0x49,0x40,0xab,0xbe,0xf7,0x43,0x02,0x96,0xf0,0x74,0xa5,0x7d,
0x68,0x89,0xfa,0x58, 0xad, 0x7b, 0x2f, 0x7d, 0xe8, 0x21, 0x34, 0x5e, 0x6c, 0x20,
0x97, 0x9e
};

const unsigned char fakeSig[] = {
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10
};

static void
dumpBytes( const char *title, const unsigned char *data, int len, int nonewline );

static int
rsa_sign(
    const char *keyFile,
    unsigned char *plain,
    unsigned plainLength,
    unsigned char signature[SIG_LEN] )
{
    int rc = -1;
    FILE *fp = NULL;
    RSA *rsa = NULL;
    unsigned signatureLength = 0;

    fp = fopen ( (char*) keyFile, "r" );
    if ( !fp ) {
        fprintf( stderr, "failed to open file=%s\n", keyFile );
        goto cleanup;
    }
    rsa = RSA_new();
    if ( !rsa ) {
        fprintf( stderr, "RSA_new() failed\n" );
        goto cleanup;
    }
    rsa = (RSA*)PEM_read_RSAPrivateKey( fp, &rsa, NULL, NULL );
    if ( !rsa ) {
        fprintf( stderr, "PEM_read_RSAPrivateKey() failed\n" );
        goto cleanup;
    }
    signatureLength = SIG_LEN;
    char sha1[20] = {};
    (void) SHA1( plain, plainLength, (unsigned char*)sha1 );
    rc = RSA_sign( NID_sha1, (unsigned char*)sha1, sizeof( sha1),
        signature, &signatureLength, rsa );
    if ( rc != 1 ) {
        fprintf(stderr, "RSA_sign failed=%d\n", rc );
        rc = -1;
        goto cleanup;
    } else {
        rc = 0;
    }

cleanup:
    if ( fp ) fclose( fp );
    RSA_free( rsa );
    return rc;
}

static int
rsa_verify(
    const char *keyFile,
    unsigned char *plain,
    unsigned plainLength,
    unsigned char signature[SIG_LEN] )
{
    int rc = -1;
    FILE *fp = NULL;
    RSA *rsa = NULL;
    unsigned signatureLength = 0;

    fp = fopen ( (char*) keyFile, "r" );
    if ( !fp ) {
        fprintf( stderr, "failed to open file=%s\n", keyFile );
        goto cleanup;
    }
    rsa = RSA_new();
    if ( !rsa ) {
        fprintf( stderr, "RSA_new() failed\n" );
        goto cleanup;
    }
    rsa = (RSA*)PEM_read_RSAPrivateKey( fp, &rsa, NULL, NULL );
    if ( !rsa ) {
        fprintf( stderr, "PEM_read_RSAPrivateKey() failed\n" );
        goto cleanup;
    }
    signatureLength = SIG_LEN;
    char sha1[20] = {};
    (void) SHA1( plain, plainLength, (unsigned char*)sha1 );
    rc = RSA_verify( NID_sha1, (unsigned char*)sha1, sizeof( sha1 ),
        signature, signatureLength, rsa );
    if ( rc != 1 ) {
        fprintf(stderr, "RSA_verify failed=%d\n", rc );
        rc = -1;
        goto cleanup;
    } else {
        rc = 0;
    }

cleanup:
    if ( fp ) fclose( fp );
    RSA_free( rsa );
    return rc;
    return rc;
}

static void
dumpBytes( const char *title, const unsigned char *data, int len, int nonewline )
{
    int width = 16;
    int line = 0;
    int multiple = 0;

    multiple = ( len % width == 0 );

    printf( "[%s: %d bytes]\n", title, len );
    while ( len-- > 0 ) {
        line++;
        printf( "%02X ", *data++ );
        if ( line % width == 0 && len > 0 && !nonewline ) {
            printf( "\n" );
        }
    }

    printf("\n");
}

static void
readFile(char *filename, unsigned char **data, unsigned *len)
{
    int size = 0;
    FILE *file = NULL;
    if ((file = fopen(filename, "r")) == NULL) {
        fprintf(stderr, "could not open file=%s", filename);
        return;
    }
    fseek(file, 0, SEEK_END);
    size = ftell(file);
    *len = size;
    *data = (unsigned char*)malloc(*len);
    if (!*data) {
        fprintf(stderr, "Out of memory");
        fclose(file);
        return;
    }
    rewind(file);
    (void)fread(*data, size, 1, file);
    fclose(file);
}

static void
writeFile( char* filename, unsigned char* buf, int len )
{
    FILE *file = NULL;
    file = fopen( filename, "w" );
    if ( file ) {
        fwrite( buf, len, 1, file );
        fclose( file );
    }
}


static void
verify_bb_ticket(
    unsigned char *ticketData,
    unsigned ticketLength,
    const char *keyFile,
    bool doPrint )
{
    if ( doPrint ) {
        dumpBytes( "Ticket (whole)", ticketData, ticketLength, 0 );
        printf( "\nBreakdown:\n" );
    }

    DERItem derTicket = { .data = ticketData, .length = ticketLength };
    DERReturn drtn;
    DERBbTicket ticket = {};
    DERSize ticketSize;
    drtn = DERDecodeBbTicket(&derTicket, &ticket, &ticketSize);
    if (drtn != DR_Success) goto badTicket;
    fprintf( stderr, "ticketSize=%u\n", ticketSize );

    // Verify signature if key file exists (we should really use the certificate or GPUK in the ticket here. */
    if ( keyFile ) {
        int status =  rsa_verify(
            keyFile,
            (unsigned char *)ticket.body.data,
            ticket.body.length,
            (unsigned char *)ticket.signature.data );
        if ( status ) {
            fprintf( stderr, "rsa_verify failed=%d\n", status );
        } else {
            fprintf( stdout, "Signature verified successfully\n");
        }
    }

    /* Example of how to retrive fields from ticket. */
    DERItem snum;
    drtn = DERSetDecodeItemWithTag(&ticket.body,
        ASN1_CONTEXT_SPECIFIC | kBbSNUMTag, &snum);
    if (drtn != DR_Success) goto badTicket;
    DERItem chipId;
    drtn = DERSetDecodeItemWithTag(&ticket.body,
        ASN1_CONTEXT_SPECIFIC | kBbChipIDTag, &chipId);
    if (drtn != DR_Success) goto badTicket;

    return;
badTicket:
    fprintf( stdout, "Bad ticket\n");
    return;
}

static void
verify_ticket_file(
    const char *ticketFile,
    const char *keyFile )
{
    unsigned char *ticket = NULL;
    unsigned ticketLength = 0;
    readFile( (char*)ticketFile, &ticket, &ticketLength );
    verify_bb_ticket( ticket, ticketLength, keyFile, false );
}

static void
make_sample_ap_ticket( void )
{
    unsigned char chipId[] = { 0x01, 0x02, 0x03, 0x04 };
    unsigned char ecid[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

    DERApTicket ticket = { };

    /* Encode the signatureAlgorithm field of the ticket. */
    DERAlgorithmId algorithmId = { .oid = oidSha1Rsa, .params = {} };
    ticket.signatureAlgorithm.length = DERLengthOfEncodedSequence(
        ASN1_CONSTR_SEQUENCE, &algorithmId, DERNumAlgorithmIdItemSpecs,
        DERAlgorithmIdItemSpecs);
    ticket.signatureAlgorithm.data = malloc(ticket.signatureAlgorithm.length);
    DEREncodeSequence(ASN1_CONSTR_SEQUENCE, &algorithmId, DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs, ticket.signatureAlgorithm.data, &ticket.signatureAlgorithm.length);

    /* Construct ticket body. */
    DERSize numBodyItemSpecs = 0;
    DERItemSpec bodyItemSpecs[50] = {};
    DERItem bodyItems[50] = {};

    /* Add tags in sorted order. */
    bodyItemSpecs[numBodyItemSpecs].offset = numBodyItemSpecs * sizeof(DERItem);
    bodyItemSpecs[numBodyItemSpecs].tag = ASN1_CONTEXT_SPECIFIC | kApECIDTag;
    bodyItemSpecs[numBodyItemSpecs].options = DER_ENC_NO_OPTS;
    bodyItems[numBodyItemSpecs].data = ecid;
    bodyItems[numBodyItemSpecs].length = sizeof(ecid);
    numBodyItemSpecs++;

    bodyItemSpecs[numBodyItemSpecs].offset = numBodyItemSpecs * sizeof(DERItem);
    bodyItemSpecs[numBodyItemSpecs].tag = ASN1_CONTEXT_SPECIFIC | kApChipIDTag;
    bodyItemSpecs[numBodyItemSpecs].options = DER_ENC_NO_OPTS;
    bodyItems[numBodyItemSpecs].data = chipId;
    bodyItems[numBodyItemSpecs].length = sizeof(chipId);
    numBodyItemSpecs++;

    /* Encode ticket body. */
    ticket.body.length = DERLengthOfEncodedSequence(ASN1_CONSTR_SET,
        &bodyItems, numBodyItemSpecs, bodyItemSpecs);
    ticket.body.data = malloc(ticket.body.length);
    DEREncodeSequence(ASN1_CONSTR_SET, &bodyItems, numBodyItemSpecs,
        bodyItemSpecs, ticket.body.data, &ticket.body.length);

    // Signature
    ticket.signature.data = (DERByte *)fakeSig;
    ticket.signature.length = sizeof(fakeSig);

    // Certificates
    DERItemSpec certItemSpecs[1];
    DERItem certItems[1];
    certItemSpecs[0].offset = 0;
    certItemSpecs[0].tag = ASN1_CONSTR_SEQUENCE;
    certItemSpecs[0].options = DER_ENC_WRITE_DER;

    // NOTE: The Certificate should be added to the ticket by the host. I'm just simulating that here
    // to generate the final ticket blob.
    readFile("S5L8920_TATSU_FAC_DARWIN_DEV_CHAIN.der", &certItems[0].data, &certItems[0].length);

    ticket.certificates.length = DERLengthOfEncodedSequence(
        ASN1_CONSTRUCTED | ASN1_CONTEXT_SPECIFIC | 1, &certItems,
        1, certItemSpecs);
    ticket.certificates.data = malloc(ticket.certificates.length);
    DEREncodeSequence(ASN1_CONSTRUCTED | ASN1_CONTEXT_SPECIFIC | 1, &certItems,
        1, certItemSpecs, ticket.certificates.data, &ticket.certificates.length);

    /* Encode the entire ticket. */
    DERSize ticketLength = DERLengthOfEncodedSequence(ASN1_CONSTR_SEQUENCE,
        &ticket, DERNumApTicketItemSpecs, DERApTicketItemSpecs);
    DERByte *ticketBytes = malloc(ticketLength);
    DEREncodeSequence(ASN1_CONSTR_SEQUENCE, &ticket, DERNumApTicketItemSpecs, DERApTicketItemSpecs,
        ticketBytes, &ticketLength);

    // save ticket to file
    writeFile("ApTicket.bin", ticketBytes, ticketLength);

//cleanup:
    free(ticket.body.data);
    free(ticket.signatureAlgorithm.data);
    free(ticket.certificates.data);
    free(ticketBytes);
}

static void
make_sample_bb_ticket( void )
{
    int status = 0;
    unsigned char chipId[] = { 0x01, 0x02, 0x03, 0x04 };
    unsigned char snum[] = { 0x01, 0x02, 0x03, 0x04 };
    unsigned char signature[SIG_LEN] = {};
    DERByte *ticketBytes = NULL;

    DERBbTicket ticket = {};

    /* Encode the signatureAlgorithm field of the ticket. */
    DERAlgorithmId algorithmId = { .oid = oidSha1Rsa };
    ticket.signatureAlgorithm.length = DERLengthOfEncodedSequence(
        ASN1_CONSTR_SEQUENCE, &algorithmId, DERNumAlgorithmIdItemSpecs,
        DERAlgorithmIdItemSpecs);
    ticket.signatureAlgorithm.data = malloc(ticket.signatureAlgorithm.length);
    DEREncodeSequence(ASN1_CONSTR_SEQUENCE, &algorithmId,
        DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs,
        ticket.signatureAlgorithm.data, &ticket.signatureAlgorithm.length);

    /* Construct ticket body. */
    DERSize numBodyItemSpecs = 0;
    DERItemSpec bodyItemSpecs[50] = {};
    DERItem bodyItems[50] = {};

    /* Add tags in sorted order. */
    bodyItemSpecs[numBodyItemSpecs].offset = numBodyItemSpecs * sizeof(DERItem);
    bodyItemSpecs[numBodyItemSpecs].tag = ASN1_CONTEXT_SPECIFIC | kBbSNUMTag;
    bodyItemSpecs[numBodyItemSpecs].options = DER_ENC_NO_OPTS;
    bodyItems[numBodyItemSpecs].data = snum;
    bodyItems[numBodyItemSpecs].length = sizeof(snum);
    numBodyItemSpecs++;

    bodyItemSpecs[numBodyItemSpecs].offset = numBodyItemSpecs * sizeof(DERItem);
    bodyItemSpecs[numBodyItemSpecs].tag = ASN1_CONTEXT_SPECIFIC | kBbChipIDTag;
    bodyItemSpecs[numBodyItemSpecs].options = DER_ENC_NO_OPTS;
    bodyItems[numBodyItemSpecs].data = chipId;
    bodyItems[numBodyItemSpecs].length = sizeof(chipId);
    numBodyItemSpecs++;

    /* Encode ticket body. */
    ticket.body.length = DERLengthOfEncodedSequence(ASN1_CONSTR_SET,
        &bodyItems, numBodyItemSpecs, bodyItemSpecs);
    ticket.body.data = malloc(ticket.body.length);
    DEREncodeSequence(ASN1_CONSTR_SET, &bodyItems, numBodyItemSpecs, bodyItemSpecs,
        ticket.body.data, &ticket.body.length);

    // NOTE: In the SEE machine, the Body above will then be hashed/signed to generate signature
    status =  rsa_sign(
        "G1_GPrK.pem",
        ticket.body.data,
        ticket.body.length,
        (unsigned char *)signature );
    if ( status ) {
        fprintf( stderr, "rsa_sign failed=%d\n", status );
        goto cleanup;
    } else {
        fprintf( stdout, "Signed successfully\n");
    }

    status =  rsa_verify(
        "G1_GPrK.pem",
        ticket.body.data,
        ticket.body.length,
        (unsigned char *)signature );
    if ( status ) {
        fprintf( stderr, "rsa_verify failed=%d\n", status );
        goto cleanup;
    } else {
        fprintf( stdout, "Signature verified successfully\n");
    }

    // Signature
    ticket.signature.data = signature;
    ticket.signature.length = SIG_LEN;

    // Certificates
    ticket.gpuk.length = sizeof(GoldKeyCert);
    ticket.gpuk.data = (DERByte *)GoldKeyCert;

    /* Encode the entire ticket. */
    DERSize ticketLength = DERLengthOfEncodedSequence(ASN1_CONSTR_SEQUENCE,
        &ticket, DERNumBbTicketItemSpecs, DERBbTicketItemSpecs);
    ticketBytes = malloc(ticketLength);
    DEREncodeSequence(ASN1_CONSTR_SEQUENCE, &ticket, DERNumBbTicketItemSpecs,
        DERBbTicketItemSpecs, ticketBytes, &ticketLength);

    // save ticket to file
    writeFile("BbTicket.bin", ticketBytes, ticketLength);

cleanup:
    free(ticket.body.data);
    free(ticket.signatureAlgorithm.data);
    free(ticketBytes);
}

static void
long_tag_test(void)
{
    printf("ASN1_TAG_MASK           0x%.016qx\n", (uint64_t)ASN1_TAG_MASK);
    printf("ASN1_TAGNUM_MASK        0x%.016qx\n", (uint64_t)ASN1_TAGNUM_MASK);
    printf("ASN1_METHOD_MASK        0x%.016qx\n", (uint64_t)ASN1_METHOD_MASK);
    printf("ASN1_PRIMITIVE          0x%.016qx\n", (uint64_t)ASN1_PRIMITIVE);
    printf("ASN1_CONSTRUCTED        0x%.016qx\n", (uint64_t)ASN1_CONSTRUCTED);
    printf("ASN1_CLASS_MASK         0x%.016qx\n", (uint64_t)ASN1_CLASS_MASK);
    printf("ASN1_UNIVERSAL          0x%.016qx\n", (uint64_t)ASN1_UNIVERSAL);
    printf("ASN1_APPLICATION        0x%.016qx\n", (uint64_t)ASN1_APPLICATION);
    printf("ASN1_CONTEXT_SPECIFIC   0x%.016qx\n", (uint64_t)ASN1_CONTEXT_SPECIFIC);
    printf("ASN1_PRIVATE            0x%.016qx\n", (uint64_t)ASN1_PRIVATE);

    DERByte buf[10];
    DERSize len = sizeof(buf);
    DERReturn drtn;
    DERTag tag = ASN1_CONTEXT_SPECIFIC | ASN1_TAGNUM_MASK;
    drtn = DEREncodeItem(tag, 0, 0, buf, &len);
    if (drtn)
    {
        printf("DEREncodeItem: %u\n", drtn);
    }
    DERItem der = { .data = buf, .length = len };

    dumpBytes("tlv", buf, len, 0);

    DERDecodedInfo decoded;
    drtn = DERDecodeItem(&der, &decoded);
    if (drtn)
    {
        printf("DERDecodeItem: %u\n", drtn);
    }
    if (decoded.tag != tag)
    {
        printf("DERDecodeItem tag: 0x%qx != 0x%qx\n", (uint64_t)decoded.tag, (uint64_t)tag);
    }
    printf("DERDecodeItem tag: 0x%qx encoded in %u bytes, decoded length: %u\n",
        (uint64_t)tag, len, decoded.content.length);
}

int main(int argc, char **argv)
{
    long_tag_test();
    printf( "=> Making sample BB ticket...\n");
    make_sample_bb_ticket();
    printf( "=> Making sample AP ticket...\n");
    make_sample_ap_ticket();
    printf( "=> Verifying signature in bb_ticket.bin ...\n");
    verify_ticket_file( "bb_ticket.bin", "G1_GPrK.pem" );
    return 0;
}

Added Source/libDER/libDER.xcodeproj/project.pbxproj.

























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
// !$*UTF8*$!
{
	archiveVersion = 1;
	classes = {
	};
	objectVersion = 46;
	objects = {

/* Begin PBXAggregateTarget section */
		053BA30F091C00B100A7007A /* World */ = {
			isa = PBXAggregateTarget;
			buildConfigurationList = 4CD81A6D09BE1FD2000A9641 /* Build configuration list for PBXAggregateTarget "World" */;
			buildPhases = (
			);
			dependencies = (
				053BA317091C017E00A7007A /* PBXTargetDependency */,
				053BA463091FE60E00A7007A /* PBXTargetDependency */,
				058ECC54091FF0000050AA30 /* PBXTargetDependency */,
				058F16680925224F009FA1C5 /* PBXTargetDependency */,
				4C96C8DC113F4174005483E8 /* PBXTargetDependency */,
			);
			name = World;
			productName = World;
		};
/* End PBXAggregateTarget section */

/* Begin PBXBuildFile section */
		053BA324091C02B700A7007A /* DER_Decode.h in Headers */ = {isa = PBXBuildFile; fileRef = 053BA321091C02B700A7007A /* DER_Decode.h */; };
		053BA325091C02B700A7007A /* libDER_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 053BA322091C02B700A7007A /* libDER_config.h */; };
		053BA326091C02B700A7007A /* libDER.h in Headers */ = {isa = PBXBuildFile; fileRef = 053BA323091C02B700A7007A /* libDER.h */; };
		053BA344091C089B00A7007A /* asn1Types.h in Headers */ = {isa = PBXBuildFile; fileRef = 053BA342091C089B00A7007A /* asn1Types.h */; };
		053BA345091C089B00A7007A /* DER_Decode.c in Sources */ = {isa = PBXBuildFile; fileRef = 053BA343091C089B00A7007A /* DER_Decode.c */; };
		053BA399091C258100A7007A /* DER_CertCrl.c in Sources */ = {isa = PBXBuildFile; fileRef = 053BA397091C258100A7007A /* DER_CertCrl.c */; };
		053BA39A091C258100A7007A /* DER_CertCrl.h in Headers */ = {isa = PBXBuildFile; fileRef = 053BA398091C258100A7007A /* DER_CertCrl.h */; };
		053BA45D091FE5E700A7007A /* libDER.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 053BA314091C00BF00A7007A /* libDER.a */; };
		053BA461091FE60700A7007A /* parseCert.c in Sources */ = {isa = PBXBuildFile; fileRef = 053BA460091FE60700A7007A /* parseCert.c */; };
		053BA470091FE6C100A7007A /* fileIo.c in Sources */ = {isa = PBXBuildFile; fileRef = 053BA46E091FE6C100A7007A /* fileIo.c */; };
		053BA471091FE6C100A7007A /* fileIo.h in Headers */ = {isa = PBXBuildFile; fileRef = 053BA46F091FE6C100A7007A /* fileIo.h */; };
		053BA47D091FE7CC00A7007A /* libDERUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 053BA47B091FE7CC00A7007A /* libDERUtils.h */; };
		053BA47E091FE7CC00A7007A /* libDERUtils.c in Sources */ = {isa = PBXBuildFile; fileRef = 053BA47C091FE7CC00A7007A /* libDERUtils.c */; };
		0544AEA10940939C00DD6C0B /* DER_Encode.h in Headers */ = {isa = PBXBuildFile; fileRef = 0544AE9F0940939C00DD6C0B /* DER_Encode.h */; };
		0544AEA20940939C00DD6C0B /* DER_Encode.c in Sources */ = {isa = PBXBuildFile; fileRef = 0544AEA00940939C00DD6C0B /* DER_Encode.c */; };
		058ECC52091FEFF70050AA30 /* libDERUtils.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 053BA46B091FE63E00A7007A /* libDERUtils.a */; };
		058ECD350920F5E30050AA30 /* DER_Keys.c in Sources */ = {isa = PBXBuildFile; fileRef = 058ECD330920F5E30050AA30 /* DER_Keys.c */; };
		058ECD360920F5E30050AA30 /* DER_Keys.h in Headers */ = {isa = PBXBuildFile; fileRef = 058ECD340920F5E30050AA30 /* DER_Keys.h */; };
		058F15C20922B73F009FA1C5 /* printFields.h in Headers */ = {isa = PBXBuildFile; fileRef = 058F15C00922B73F009FA1C5 /* printFields.h */; };
		058F15C30922B73F009FA1C5 /* printFields.c in Sources */ = {isa = PBXBuildFile; fileRef = 058F15C10922B73F009FA1C5 /* printFields.c */; };
		058F163109250D16009FA1C5 /* oids.c in Sources */ = {isa = PBXBuildFile; fileRef = 058F162D09250D0D009FA1C5 /* oids.c */; };
		058F163209250D17009FA1C5 /* oids.h in Headers */ = {isa = PBXBuildFile; fileRef = 058F162E09250D0D009FA1C5 /* oids.h */; };
		058F1659092513A7009FA1C5 /* parseCrl.c in Sources */ = {isa = PBXBuildFile; fileRef = 058F1658092513A7009FA1C5 /* parseCrl.c */; };
		058F16710925230E009FA1C5 /* libDER.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 053BA314091C00BF00A7007A /* libDER.a */; };
		058F16720925230F009FA1C5 /* libDERUtils.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 053BA46B091FE63E00A7007A /* libDERUtils.a */; };
		05E0E40709228A5E005F4693 /* DER_Digest.h in Headers */ = {isa = PBXBuildFile; fileRef = 05E0E40509228A5E005F4693 /* DER_Digest.h */; };
		05E0E40809228A5E005F4693 /* DER_Digest.c in Sources */ = {isa = PBXBuildFile; fileRef = 05E0E40609228A5E005F4693 /* DER_Digest.c */; };
		4C96C8D6113F4165005483E8 /* DER_Ticket.c in Sources */ = {isa = PBXBuildFile; fileRef = 4C96C8D3113F4165005483E8 /* DER_Ticket.c */; };
		4C96C8D7113F4165005483E8 /* parseTicket.c in Sources */ = {isa = PBXBuildFile; fileRef = 4C96C8D5113F4165005483E8 /* parseTicket.c */; };
		4C96C8E2113F4232005483E8 /* libDER.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 053BA314091C00BF00A7007A /* libDER.a */; };
		4C96C8ED113F42D1005483E8 /* libcrypto.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 4C96C8EC113F42C4005483E8 /* libcrypto.dylib */; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
		053BA316091C017E00A7007A /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 053BA30A091C00A400A7007A /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 053BA313091C00BF00A7007A;
			remoteInfo = libDER;
		};
		053BA458091FE59900A7007A /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 053BA30A091C00A400A7007A /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 053BA313091C00BF00A7007A;
			remoteInfo = libDER;
		};
		053BA462091FE60E00A7007A /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 053BA30A091C00A400A7007A /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 053BA444091FE58C00A7007A;
			remoteInfo = parseCert;
		};
		058ECC53091FF0000050AA30 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 053BA30A091C00A400A7007A /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 053BA46A091FE63E00A7007A;
			remoteInfo = libDERUtils;
		};
		058ECC55091FF0090050AA30 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 053BA30A091C00A400A7007A /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 053BA46A091FE63E00A7007A;
			remoteInfo = libDERUtils;
		};
		058F16670925224F009FA1C5 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 053BA30A091C00A400A7007A /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 058F16530925135E009FA1C5;
			remoteInfo = parseCrl;
		};
		058F1675092523D8009FA1C5 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 053BA30A091C00A400A7007A /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 053BA313091C00BF00A7007A;
			remoteInfo = libDER;
		};
		058F1677092523DD009FA1C5 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 053BA30A091C00A400A7007A /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 053BA46A091FE63E00A7007A;
			remoteInfo = libDERUtils;
		};
		4C96C8DB113F4174005483E8 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 053BA30A091C00A400A7007A /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 4C96C8CD113F4132005483E8;
			remoteInfo = parseTicket;
		};
		4C96C8E0113F4223005483E8 /* PBXContainerItemProxy */ = {
			isa = PBXContainerItemProxy;
			containerPortal = 053BA30A091C00A400A7007A /* Project object */;
			proxyType = 1;
			remoteGlobalIDString = 053BA313091C00BF00A7007A;
			remoteInfo = libDER;
		};
/* End PBXContainerItemProxy section */

/* Begin PBXFileReference section */
		053BA314091C00BF00A7007A /* libDER.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libDER.a; sourceTree = BUILT_PRODUCTS_DIR; };
		053BA321091C02B700A7007A /* DER_Decode.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DER_Decode.h; sourceTree = "<group>"; };
		053BA322091C02B700A7007A /* libDER_config.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = libDER_config.h; sourceTree = "<group>"; };
		053BA323091C02B700A7007A /* libDER.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = libDER.h; sourceTree = "<group>"; };
		053BA342091C089B00A7007A /* asn1Types.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = asn1Types.h; sourceTree = "<group>"; };
		053BA343091C089B00A7007A /* DER_Decode.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = DER_Decode.c; sourceTree = "<group>"; };
		053BA397091C258100A7007A /* DER_CertCrl.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = DER_CertCrl.c; sourceTree = "<group>"; };
		053BA398091C258100A7007A /* DER_CertCrl.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DER_CertCrl.h; sourceTree = "<group>"; };
		053BA445091FE58C00A7007A /* parseCert */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = parseCert; sourceTree = BUILT_PRODUCTS_DIR; };
		053BA460091FE60700A7007A /* parseCert.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = parseCert.c; sourceTree = "<group>"; };
		053BA46B091FE63E00A7007A /* libDERUtils.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libDERUtils.a; sourceTree = BUILT_PRODUCTS_DIR; };
		053BA46E091FE6C100A7007A /* fileIo.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = fileIo.c; sourceTree = "<group>"; };
		053BA46F091FE6C100A7007A /* fileIo.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = fileIo.h; sourceTree = "<group>"; };
		053BA47B091FE7CC00A7007A /* libDERUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = libDERUtils.h; sourceTree = "<group>"; };
		053BA47C091FE7CC00A7007A /* libDERUtils.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = libDERUtils.c; sourceTree = "<group>"; };
		0544AE9F0940939C00DD6C0B /* DER_Encode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DER_Encode.h; sourceTree = "<group>"; };
		0544AEA00940939C00DD6C0B /* DER_Encode.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = DER_Encode.c; sourceTree = "<group>"; };
		058ECD330920F5E30050AA30 /* DER_Keys.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = DER_Keys.c; sourceTree = "<group>"; };
		058ECD340920F5E30050AA30 /* DER_Keys.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = DER_Keys.h; sourceTree = "<group>"; };
		058ECE5C09211AE40050AA30 /* libGiants.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libGiants.a; sourceTree = BUILT_PRODUCTS_DIR; };
		058ECE5E09211AFB0050AA30 /* libgRSA.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libgRSA.a; sourceTree = BUILT_PRODUCTS_DIR; };
		058F15C00922B73F009FA1C5 /* printFields.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = printFields.h; sourceTree = "<group>"; };
		058F15C10922B73F009FA1C5 /* printFields.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = printFields.c; sourceTree = "<group>"; };
		058F162D09250D0D009FA1C5 /* oids.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = oids.c; sourceTree = "<group>"; };
		058F162E09250D0D009FA1C5 /* oids.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = oids.h; sourceTree = "<group>"; };
		058F16540925135E009FA1C5 /* parseCrl */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = parseCrl; sourceTree = BUILT_PRODUCTS_DIR; };
		058F1658092513A7009FA1C5 /* parseCrl.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = parseCrl.c; sourceTree = "<group>"; };
		05E0E40509228A5E005F4693 /* DER_Digest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DER_Digest.h; sourceTree = "<group>"; };
		05E0E40609228A5E005F4693 /* DER_Digest.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = DER_Digest.c; sourceTree = "<group>"; };
		4C86289E1137D5BE009EAB5A /* iPhoneFamily.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = iPhoneFamily.xcconfig; path = AppleInternal/XcodeConfig/iPhoneFamily.xcconfig; sourceTree = DEVELOPER_DIR; };
		4C96C8CE113F4132005483E8 /* parseTicket */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = parseTicket; sourceTree = BUILT_PRODUCTS_DIR; };
		4C96C8D2113F4165005483E8 /* AppleMobilePersonalizedTicket.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppleMobilePersonalizedTicket.h; sourceTree = "<group>"; };
		4C96C8D3113F4165005483E8 /* DER_Ticket.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = DER_Ticket.c; sourceTree = "<group>"; };
		4C96C8D4113F4165005483E8 /* DER_Ticket.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DER_Ticket.h; sourceTree = "<group>"; };
		4C96C8D5113F4165005483E8 /* parseTicket.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = parseTicket.c; sourceTree = "<group>"; };
		4C96C8EC113F42C4005483E8 /* libcrypto.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libcrypto.dylib; path = /usr/lib/libcrypto.dylib; sourceTree = "<absolute>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
		053BA312091C00BF00A7007A /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		053BA443091FE58C00A7007A /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
				058ECC52091FEFF70050AA30 /* libDERUtils.a in Frameworks */,
				053BA45D091FE5E700A7007A /* libDER.a in Frameworks */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		053BA469091FE63E00A7007A /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		058F16520925135E009FA1C5 /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
				058F16720925230F009FA1C5 /* libDERUtils.a in Frameworks */,
				058F16710925230E009FA1C5 /* libDER.a in Frameworks */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		4C96C8CC113F4132005483E8 /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
				4C96C8E2113F4232005483E8 /* libDER.a in Frameworks */,
				4C96C8ED113F42D1005483E8 /* libcrypto.dylib in Frameworks */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXFrameworksBuildPhase section */

/* Begin PBXGroup section */
		053BA306091C00A400A7007A = {
			isa = PBXGroup;
			children = (
				053BA31E091C029900A7007A /* libDER */,
				053BA466091FE62100A7007A /* libDERUtils */,
				053BA45C091FE5CE00A7007A /* Tests */,
				4C86289E1137D5BE009EAB5A /* iPhoneFamily.xcconfig */,
				058ECE5B09211AB20050AA30 /* External Libs */,
				053BA315091C00BF00A7007A /* Products */,
			);
			sourceTree = "<group>";
		};
		053BA315091C00BF00A7007A /* Products */ = {
			isa = PBXGroup;
			children = (
				053BA314091C00BF00A7007A /* libDER.a */,
				053BA445091FE58C00A7007A /* parseCert */,
				053BA46B091FE63E00A7007A /* libDERUtils.a */,
				058F16540925135E009FA1C5 /* parseCrl */,
				4C96C8CE113F4132005483E8 /* parseTicket */,
			);
			name = Products;
			sourceTree = "<group>";
		};
		053BA31E091C029900A7007A /* libDER */ = {
			isa = PBXGroup;
			children = (
				058ECD330920F5E30050AA30 /* DER_Keys.c */,
				058ECD340920F5E30050AA30 /* DER_Keys.h */,
				053BA342091C089B00A7007A /* asn1Types.h */,
				053BA397091C258100A7007A /* DER_CertCrl.c */,
				053BA398091C258100A7007A /* DER_CertCrl.h */,
				053BA343091C089B00A7007A /* DER_Decode.c */,
				053BA321091C02B700A7007A /* DER_Decode.h */,
				0544AEA00940939C00DD6C0B /* DER_Encode.c */,
				0544AE9F0940939C00DD6C0B /* DER_Encode.h */,
				053BA322091C02B700A7007A /* libDER_config.h */,
				053BA323091C02B700A7007A /* libDER.h */,
				05E0E40509228A5E005F4693 /* DER_Digest.h */,
				05E0E40609228A5E005F4693 /* DER_Digest.c */,
				058F162D09250D0D009FA1C5 /* oids.c */,
				058F162E09250D0D009FA1C5 /* oids.h */,
			);
			path = libDER;
			sourceTree = "<group>";
		};
		053BA45C091FE5CE00A7007A /* Tests */ = {
			isa = PBXGroup;
			children = (
				4C96C8D2113F4165005483E8 /* AppleMobilePersonalizedTicket.h */,
				4C96C8D3113F4165005483E8 /* DER_Ticket.c */,
				4C96C8D4113F4165005483E8 /* DER_Ticket.h */,
				4C96C8D5113F4165005483E8 /* parseTicket.c */,
				053BA460091FE60700A7007A /* parseCert.c */,
				058F1658092513A7009FA1C5 /* parseCrl.c */,
			);
			path = Tests;
			sourceTree = "<group>";
		};
		053BA466091FE62100A7007A /* libDERUtils */ = {
			isa = PBXGroup;
			children = (
				053BA47B091FE7CC00A7007A /* libDERUtils.h */,
				053BA47C091FE7CC00A7007A /* libDERUtils.c */,
				053BA46E091FE6C100A7007A /* fileIo.c */,
				053BA46F091FE6C100A7007A /* fileIo.h */,
				058F15C00922B73F009FA1C5 /* printFields.h */,
				058F15C10922B73F009FA1C5 /* printFields.c */,
			);
			path = libDERUtils;
			sourceTree = "<group>";
		};
		058ECE5B09211AB20050AA30 /* External Libs */ = {
			isa = PBXGroup;
			children = (
				058ECE5E09211AFB0050AA30 /* libgRSA.a */,
				058ECE5C09211AE40050AA30 /* libGiants.a */,
				4C96C8EC113F42C4005483E8 /* libcrypto.dylib */,
			);
			name = "External Libs";
			sourceTree = "<group>";
		};
/* End PBXGroup section */

/* Begin PBXHeadersBuildPhase section */
		053BA310091C00BF00A7007A /* Headers */ = {
			isa = PBXHeadersBuildPhase;
			buildActionMask = 2147483647;
			files = (
				053BA324091C02B700A7007A /* DER_Decode.h in Headers */,
				053BA325091C02B700A7007A /* libDER_config.h in Headers */,
				053BA326091C02B700A7007A /* libDER.h in Headers */,
				053BA344091C089B00A7007A /* asn1Types.h in Headers */,
				053BA39A091C258100A7007A /* DER_CertCrl.h in Headers */,
				058ECD360920F5E30050AA30 /* DER_Keys.h in Headers */,
				05E0E40709228A5E005F4693 /* DER_Digest.h in Headers */,
				058F163209250D17009FA1C5 /* oids.h in Headers */,
				0544AEA10940939C00DD6C0B /* DER_Encode.h in Headers */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		053BA467091FE63E00A7007A /* Headers */ = {
			isa = PBXHeadersBuildPhase;
			buildActionMask = 2147483647;
			files = (
				053BA471091FE6C100A7007A /* fileIo.h in Headers */,
				053BA47D091FE7CC00A7007A /* libDERUtils.h in Headers */,
				058F15C20922B73F009FA1C5 /* printFields.h in Headers */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXHeadersBuildPhase section */

/* Begin PBXNativeTarget section */
		053BA313091C00BF00A7007A /* libDER */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 4CD81A5D09BE1FD2000A9641 /* Build configuration list for PBXNativeTarget "libDER" */;
			buildPhases = (
				053BA310091C00BF00A7007A /* Headers */,
				053BA311091C00BF00A7007A /* Sources */,
				053BA312091C00BF00A7007A /* Frameworks */,
			);
			buildRules = (
			);
			dependencies = (
			);
			name = libDER;
			productName = libDER;
			productReference = 053BA314091C00BF00A7007A /* libDER.a */;
			productType = "com.apple.product-type.library.static";
		};
		053BA444091FE58C00A7007A /* parseCert */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 4CD81A6509BE1FD2000A9641 /* Build configuration list for PBXNativeTarget "parseCert" */;
			buildPhases = (
				053BA442091FE58C00A7007A /* Sources */,
				053BA443091FE58C00A7007A /* Frameworks */,
			);
			buildRules = (
			);
			dependencies = (
				053BA459091FE59900A7007A /* PBXTargetDependency */,
				058ECC56091FF0090050AA30 /* PBXTargetDependency */,
			);
			name = parseCert;
			productName = parseCert;
			productReference = 053BA445091FE58C00A7007A /* parseCert */;
			productType = "com.apple.product-type.tool";
		};
		053BA46A091FE63E00A7007A /* libDERUtils */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 4CD81A6109BE1FD2000A9641 /* Build configuration list for PBXNativeTarget "libDERUtils" */;
			buildPhases = (
				053BA467091FE63E00A7007A /* Headers */,
				053BA468091FE63E00A7007A /* Sources */,
				053BA469091FE63E00A7007A /* Frameworks */,
			);
			buildRules = (
			);
			dependencies = (
			);
			name = libDERUtils;
			productName = libDERUtils;
			productReference = 053BA46B091FE63E00A7007A /* libDERUtils.a */;
			productType = "com.apple.product-type.library.static";
		};
		058F16530925135E009FA1C5 /* parseCrl */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 4CD81A6909BE1FD2000A9641 /* Build configuration list for PBXNativeTarget "parseCrl" */;
			buildPhases = (
				058F16510925135E009FA1C5 /* Sources */,
				058F16520925135E009FA1C5 /* Frameworks */,
			);
			buildRules = (
			);
			dependencies = (
				058F1676092523D8009FA1C5 /* PBXTargetDependency */,
				058F1678092523DD009FA1C5 /* PBXTargetDependency */,
			);
			name = parseCrl;
			productName = parseCrl;
			productReference = 058F16540925135E009FA1C5 /* parseCrl */;
			productType = "com.apple.product-type.tool";
		};
		4C96C8CD113F4132005483E8 /* parseTicket */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 4C96C8D8113F4165005483E8 /* Build configuration list for PBXNativeTarget "parseTicket" */;
			buildPhases = (
				4C96C8CB113F4132005483E8 /* Sources */,
				4C96C8CC113F4132005483E8 /* Frameworks */,
			);
			buildRules = (
			);
			dependencies = (
				4C96C8E1113F4223005483E8 /* PBXTargetDependency */,
			);
			name = parseTicket;
			productName = parseTicket;
			productReference = 4C96C8CE113F4132005483E8 /* parseTicket */;
			productType = "com.apple.product-type.tool";
		};
/* End PBXNativeTarget section */

/* Begin PBXProject section */
		053BA30A091C00A400A7007A /* Project object */ = {
			isa = PBXProject;
			attributes = {
				LastUpgradeCheck = 0420;
			};
			buildConfigurationList = 4CD81A7109BE1FD2000A9641 /* Build configuration list for PBXProject "libDER" */;
			compatibilityVersion = "Xcode 3.2";
			developmentRegion = English;
			hasScannedForEncodings = 0;
			knownRegions = (
				English,
				Japanese,
				French,
				German,
			);
			mainGroup = 053BA306091C00A400A7007A;
			productRefGroup = 053BA315091C00BF00A7007A /* Products */;
			projectDirPath = "";
			projectRoot = "";
			targets = (
				053BA30F091C00B100A7007A /* World */,
				053BA313091C00BF00A7007A /* libDER */,
				053BA444091FE58C00A7007A /* parseCert */,
				053BA46A091FE63E00A7007A /* libDERUtils */,
				058F16530925135E009FA1C5 /* parseCrl */,
				4C96C8CD113F4132005483E8 /* parseTicket */,
			);
		};
/* End PBXProject section */

/* Begin PBXSourcesBuildPhase section */
		053BA311091C00BF00A7007A /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				053BA345091C089B00A7007A /* DER_Decode.c in Sources */,
				053BA399091C258100A7007A /* DER_CertCrl.c in Sources */,
				058ECD350920F5E30050AA30 /* DER_Keys.c in Sources */,
				05E0E40809228A5E005F4693 /* DER_Digest.c in Sources */,
				058F163109250D16009FA1C5 /* oids.c in Sources */,
				0544AEA20940939C00DD6C0B /* DER_Encode.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		053BA442091FE58C00A7007A /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				053BA461091FE60700A7007A /* parseCert.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		053BA468091FE63E00A7007A /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				053BA470091FE6C100A7007A /* fileIo.c in Sources */,
				053BA47E091FE7CC00A7007A /* libDERUtils.c in Sources */,
				058F15C30922B73F009FA1C5 /* printFields.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		058F16510925135E009FA1C5 /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				058F1659092513A7009FA1C5 /* parseCrl.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
		4C96C8CB113F4132005483E8 /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				4C96C8D6113F4165005483E8 /* DER_Ticket.c in Sources */,
				4C96C8D7113F4165005483E8 /* parseTicket.c in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXSourcesBuildPhase section */

/* Begin PBXTargetDependency section */
		053BA317091C017E00A7007A /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 053BA313091C00BF00A7007A /* libDER */;
			targetProxy = 053BA316091C017E00A7007A /* PBXContainerItemProxy */;
		};
		053BA459091FE59900A7007A /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 053BA313091C00BF00A7007A /* libDER */;
			targetProxy = 053BA458091FE59900A7007A /* PBXContainerItemProxy */;
		};
		053BA463091FE60E00A7007A /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 053BA444091FE58C00A7007A /* parseCert */;
			targetProxy = 053BA462091FE60E00A7007A /* PBXContainerItemProxy */;
		};
		058ECC54091FF0000050AA30 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 053BA46A091FE63E00A7007A /* libDERUtils */;
			targetProxy = 058ECC53091FF0000050AA30 /* PBXContainerItemProxy */;
		};
		058ECC56091FF0090050AA30 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 053BA46A091FE63E00A7007A /* libDERUtils */;
			targetProxy = 058ECC55091FF0090050AA30 /* PBXContainerItemProxy */;
		};
		058F16680925224F009FA1C5 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 058F16530925135E009FA1C5 /* parseCrl */;
			targetProxy = 058F16670925224F009FA1C5 /* PBXContainerItemProxy */;
		};
		058F1676092523D8009FA1C5 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 053BA313091C00BF00A7007A /* libDER */;
			targetProxy = 058F1675092523D8009FA1C5 /* PBXContainerItemProxy */;
		};
		058F1678092523DD009FA1C5 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 053BA46A091FE63E00A7007A /* libDERUtils */;
			targetProxy = 058F1677092523DD009FA1C5 /* PBXContainerItemProxy */;
		};
		4C96C8DC113F4174005483E8 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 4C96C8CD113F4132005483E8 /* parseTicket */;
			targetProxy = 4C96C8DB113F4174005483E8 /* PBXContainerItemProxy */;
		};
		4C96C8E1113F4223005483E8 /* PBXTargetDependency */ = {
			isa = PBXTargetDependency;
			target = 053BA313091C00BF00A7007A /* libDER */;
			targetProxy = 4C96C8E0113F4223005483E8 /* PBXContainerItemProxy */;
		};
/* End PBXTargetDependency section */

/* Begin XCBuildConfiguration section */
		4C96C8D0113F4132005483E8 /* Debug */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				PRODUCT_NAME = parseTicket;
			};
			name = Debug;
		};
		4C96C8D1113F4132005483E8 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				PRODUCT_NAME = parseTicket;
			};
			name = Release;
		};
		792E01120CBC0CE3007C00A0 /* Debug */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				INSTALL_PATH = "$(INDIGO_INSTALL_PATH_PREFIX)/usr/local/lib";
				LIBRARY_STYLE = STATIC;
				PRODUCT_NAME = DER;
				SKIP_INSTALL = YES;
			};
			name = Debug;
		};
		792E01130CBC0CE3007C00A0 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				INSTALL_PATH = "$(INDIGO_INSTALL_PATH_PREFIX)/usr/local/lib";
				LIBRARY_STYLE = STATIC;
				PRODUCT_NAME = DER;
				SKIP_INSTALL = YES;
			};
			name = Release;
		};
		792E01140CBC0CE3007C00A0 /* Debug */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				LIBRARY_STYLE = STATIC;
				PRODUCT_NAME = DERUtils;
				SKIP_INSTALL = YES;
			};
			name = Debug;
		};
		792E01150CBC0CE3007C00A0 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				LIBRARY_STYLE = STATIC;
				PRODUCT_NAME = DERUtils;
				SKIP_INSTALL = YES;
			};
			name = Release;
		};
		792E01160CBC0CE3007C00A0 /* Debug */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				PRODUCT_NAME = parseCert;
			};
			name = Debug;
		};
		792E01170CBC0CE3007C00A0 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				PRODUCT_NAME = parseCert;
			};
			name = Release;
		};
		792E01180CBC0CE3007C00A0 /* Debug */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				PRODUCT_NAME = parseCrl;
			};
			name = Debug;
		};
		792E01190CBC0CE3007C00A0 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				PRODUCT_NAME = parseCrl;
			};
			name = Release;
		};
		792E011A0CBC0CE3007C00A0 /* Debug */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				COPY_PHASE_STRIP = YES;
				OTHER_CFLAGS = "-DNDEBUG";
				OTHER_LDFLAGS = "";
				OTHER_REZFLAGS = "";
				PRODUCT_NAME = World;
				SECTORDER_FLAGS = "";
				WARNING_CFLAGS = (
					"-Wmost",
					"-Wno-four-char-constants",
					"-Wno-unknown-pragmas",
				);
			};
			name = Debug;
		};
		792E011B0CBC0CE3007C00A0 /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				OTHER_CFLAGS = "";
				OTHER_LDFLAGS = "";
				OTHER_REZFLAGS = "";
				PRODUCT_NAME = World;
				SECTORDER_FLAGS = "";
				WARNING_CFLAGS = (
					"-Wmost",
					"-Wno-four-char-constants",
					"-Wno-unknown-pragmas",
				);
			};
			name = Release;
		};
		792E011C0CBC0CE3007C00A0 /* Debug */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 4C86289E1137D5BE009EAB5A /* iPhoneFamily.xcconfig */;
			buildSettings = {
				COPY_PHASE_STRIP = NO;
				GCC_OPTIMIZATION_LEVEL = 1;
				GCC_PREPROCESSOR_DEFINITIONS = "DEBUG=1";
				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
				GCC_WARN_ABOUT_MISSING_NEWLINE = YES;
				GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
				GCC_WARN_ABOUT_RETURN_TYPE = YES;
				GCC_WARN_CHECK_SWITCH_STATEMENTS = YES;
				GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES;
				GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
				GCC_WARN_MISSING_PARENTHESES = YES;
				GCC_WARN_SHADOW = YES;
				GCC_WARN_SIGN_COMPARE = YES;
				GCC_WARN_UNINITIALIZED_AUTOS = YES;
				GCC_WARN_UNKNOWN_PRAGMAS = YES;
				GCC_WARN_UNUSED_FUNCTION = YES;
				GCC_WARN_UNUSED_LABEL = YES;
				GCC_WARN_UNUSED_VALUE = YES;
				GCC_WARN_UNUSED_VARIABLE = YES;
				HEADER_SEARCH_PATHS = (
					"$(SRCROOT)",
					"$(SRCROOT)/libDER",
				);
				"HEADER_SEARCH_PATHS[sdk=macosx*][arch=*]" = (
					"$(SYSTEM_LIBRARY_DIR)/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Headers",
					"$(HEADER_SEARCH_PATHS)",
				);
				OTHER_CFLAGS = (
					"-fconstant-cfstrings",
					"-fno-inline",
				);
				SDKROOT = iphoneos.internal;
				SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
				WARNING_CFLAGS = (
					"-Wall",
					"-Wextra",
					"-Wno-unused-parameter",
					"-Wno-missing-field-initializers",
				);
			};
			name = Debug;
		};
		792E011D0CBC0CE3007C00A0 /* Release */ = {
			isa = XCBuildConfiguration;
			baseConfigurationReference = 4C86289E1137D5BE009EAB5A /* iPhoneFamily.xcconfig */;
			buildSettings = {
				COPY_PHASE_STRIP = YES;
				GCC_OPTIMIZATION_LEVEL = s;
				GCC_PREPROCESSOR_DEFINITIONS = "NDEBUG=1";
				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
				GCC_WARN_ABOUT_MISSING_NEWLINE = YES;
				GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES;
				GCC_WARN_ABOUT_RETURN_TYPE = YES;
				GCC_WARN_CHECK_SWITCH_STATEMENTS = YES;
				GCC_WARN_FOUR_CHARACTER_CONSTANTS = YES;
				GCC_WARN_INITIALIZER_NOT_FULLY_BRACKETED = YES;
				GCC_WARN_MISSING_PARENTHESES = YES;
				GCC_WARN_SHADOW = YES;
				GCC_WARN_SIGN_COMPARE = YES;
				GCC_WARN_UNINITIALIZED_AUTOS = YES;
				GCC_WARN_UNKNOWN_PRAGMAS = YES;
				GCC_WARN_UNUSED_FUNCTION = YES;
				GCC_WARN_UNUSED_LABEL = YES;
				GCC_WARN_UNUSED_VALUE = YES;
				GCC_WARN_UNUSED_VARIABLE = YES;
				HEADER_SEARCH_PATHS = (
					"$(SRCROOT)",
					"$(SRCROOT)/libDER",
				);
				"HEADER_SEARCH_PATHS[sdk=macosx*][arch=*]" = (
					"$(SYSTEM_LIBRARY_DIR)/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Headers",
					"$(HEADER_SEARCH_PATHS)",
				);
				OTHER_CFLAGS = "-fconstant-cfstrings";
				SDKROOT = iphoneos.internal;
				SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
				WARNING_CFLAGS = (
					"-Wall",
					"-Wextra",
					"-Wno-unused-parameter",
					"-Wno-missing-field-initializers",
				);
			};
			name = Release;
		};
/* End XCBuildConfiguration section */

/* Begin XCConfigurationList section */
		4C96C8D8113F4165005483E8 /* Build configuration list for PBXNativeTarget "parseTicket" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				4C96C8D0113F4132005483E8 /* Debug */,
				4C96C8D1113F4132005483E8 /* Release */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		4CD81A5D09BE1FD2000A9641 /* Build configuration list for PBXNativeTarget "libDER" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				792E01120CBC0CE3007C00A0 /* Debug */,
				792E01130CBC0CE3007C00A0 /* Release */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		4CD81A6109BE1FD2000A9641 /* Build configuration list for PBXNativeTarget "libDERUtils" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				792E01140CBC0CE3007C00A0 /* Debug */,
				792E01150CBC0CE3007C00A0 /* Release */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		4CD81A6509BE1FD2000A9641 /* Build configuration list for PBXNativeTarget "parseCert" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				792E01160CBC0CE3007C00A0 /* Debug */,
				792E01170CBC0CE3007C00A0 /* Release */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		4CD81A6909BE1FD2000A9641 /* Build configuration list for PBXNativeTarget "parseCrl" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				792E01180CBC0CE3007C00A0 /* Debug */,
				792E01190CBC0CE3007C00A0 /* Release */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		4CD81A6D09BE1FD2000A9641 /* Build configuration list for PBXAggregateTarget "World" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				792E011A0CBC0CE3007C00A0 /* Debug */,
				792E011B0CBC0CE3007C00A0 /* Release */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		4CD81A7109BE1FD2000A9641 /* Build configuration list for PBXProject "libDER" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				792E011C0CBC0CE3007C00A0 /* Debug */,
				792E011D0CBC0CE3007C00A0 /* Release */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
/* End XCConfigurationList section */
	};
	rootObject = 053BA30A091C00A400A7007A /* Project object */;
}

Added Source/libDER/libDER/DER_CertCrl.c.































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/* Copyright (c) 2005-2009 Apple Inc.  All Rights Reserved. */

/*
 * DER_Cert.c - support for decoding X509 certificates
 *
 * Created Nov. 4 2005 by Doug Mitchell.
 */
 
#include "DER_Decode.h"
#include "DER_CertCrl.h"
#include "asn1Types.h"

/* 
 * DERItemSpecs for X509 certificates. 
 */
 
/* top level cert with three components */
const DERItemSpec DERSignedCertCrlItemSpecs[] = 
{
	{ DER_OFFSET(DERSignedCertCrl, tbs),
			ASN1_CONSTR_SEQUENCE,	
			DER_DEC_NO_OPTS | DER_DEC_SAVE_DER},		
	{ DER_OFFSET(DERSignedCertCrl, sigAlg),
			ASN1_CONSTR_SEQUENCE,	
			DER_DEC_NO_OPTS },		
	{ DER_OFFSET(DERSignedCertCrl, sig),
			ASN1_BIT_STRING,		
			DER_DEC_NO_OPTS }	
};

const DERSize DERNumSignedCertCrlItemSpecs = 
	sizeof(DERSignedCertCrlItemSpecs) / sizeof(DERItemSpec);

/* TBS cert */
const DERItemSpec DERTBSCertItemSpecs[] = 
{
	{ DER_OFFSET(DERTBSCert, version),
			ASN1_CONSTRUCTED | ASN1_CONTEXT_SPECIFIC | 0,		
			DER_DEC_OPTIONAL },						/* version - EXPLICIT */
	{ DER_OFFSET(DERTBSCert, serialNum),
			ASN1_INTEGER,			
			DER_DEC_NO_OPTS },		
	{ DER_OFFSET(DERTBSCert, tbsSigAlg),
			ASN1_CONSTR_SEQUENCE, 
			DER_DEC_NO_OPTS },
	{ DER_OFFSET(DERTBSCert, issuer),
			ASN1_CONSTR_SEQUENCE, 
			DER_DEC_NO_OPTS },	
	{ DER_OFFSET(DERTBSCert, validity),
			ASN1_CONSTR_SEQUENCE, 
			DER_DEC_NO_OPTS },	
	{ DER_OFFSET(DERTBSCert, subject),
			ASN1_CONSTR_SEQUENCE, 
			DER_DEC_NO_OPTS },	
	{ DER_OFFSET(DERTBSCert, subjectPubKey),
			ASN1_CONSTR_SEQUENCE, 
			DER_DEC_NO_OPTS },	
	/* libsecurity_asn1 has these two as CONSTRUCTED, but the ASN.1 spec
	 * doesn't look that way to me. I don't have any certs that have these
	 * fields.... */
	{ DER_OFFSET(DERTBSCert, issuerID),
			ASN1_CONTEXT_SPECIFIC | 1, 
			DER_DEC_OPTIONAL },
	{ DER_OFFSET(DERTBSCert, subjectID),
			ASN1_CONTEXT_SPECIFIC | 2, 
			DER_DEC_OPTIONAL },
	{ DER_OFFSET(DERTBSCert, extensions),
			ASN1_CONSTRUCTED | ASN1_CONTEXT_SPECIFIC | 3,
			DER_DEC_OPTIONAL }
};
const DERSize DERNumTBSCertItemSpecs = sizeof(DERTBSCertItemSpecs) / sizeof(DERItemSpec);

/* DERValidity */
const DERItemSpec DERValidityItemSpecs[] = 
{
	{ DER_OFFSET(DERValidity, notBefore),
			0,					/* no tag - ANY */
			DER_DEC_ASN_ANY | DER_DEC_SAVE_DER },	
	{ DER_OFFSET(DERValidity, notAfter),
			0,					/* no tag - ANY */
			DER_DEC_ASN_ANY | DER_DEC_SAVE_DER }
};
const DERSize DERNumValidityItemSpecs = 
	sizeof(DERValidityItemSpecs) / sizeof(DERItemSpec);

/* DERAttributeTypeAndValue */
const DERItemSpec DERAttributeTypeAndValueItemSpecs[] = {
	{ DER_OFFSET(DERAttributeTypeAndValue, type),
			ASN1_OBJECT_ID,
			DER_DEC_NO_OPTS },	
	{ DER_OFFSET(DERAttributeTypeAndValue, value),
			0,					/* no tag - ANY */
			DER_DEC_ASN_ANY | DER_DEC_SAVE_DER }
};

const DERSize DERNumAttributeTypeAndValueItemSpecs =
	sizeof(DERAttributeTypeAndValueItemSpecs) / sizeof(DERItemSpec);

/* DERExtension */
const DERItemSpec DERExtensionItemSpecs[] = 
{
	{ DER_OFFSET(DERExtension, extnID),
			ASN1_OBJECT_ID,
			DER_DEC_NO_OPTS },
	{ DER_OFFSET(DERExtension, critical),
			ASN1_BOOLEAN,
			DER_DEC_OPTIONAL },
	{ DER_OFFSET(DERExtension, extnValue),
			ASN1_OCTET_STRING,
            DER_DEC_NO_OPTS }
};
const DERSize DERNumExtensionItemSpecs = 
	sizeof(DERExtensionItemSpecs) / sizeof(DERItemSpec);

/* DERBasicConstraints */
const DERItemSpec DERBasicConstraintsItemSpecs[] = 
{
	{ DER_OFFSET(DERBasicConstraints, cA),
			ASN1_BOOLEAN,
			DER_DEC_OPTIONAL },
	{ DER_OFFSET(DERBasicConstraints, pathLenConstraint),
			ASN1_INTEGER,
			DER_DEC_OPTIONAL }
};
const DERSize DERNumBasicConstraintsItemSpecs = 
	sizeof(DERBasicConstraintsItemSpecs) / sizeof(DERItemSpec);

/* DERPrivateKeyUsagePeriod. */
const DERItemSpec DERPrivateKeyUsagePeriodItemSpecs[] = 
{
	{ DER_OFFSET(DERPrivateKeyUsagePeriod, notBefore),
			ASN1_CONTEXT_SPECIFIC | 0,
			DER_DEC_OPTIONAL },	
	{ DER_OFFSET(DERPrivateKeyUsagePeriod, notAfter),
			ASN1_CONTEXT_SPECIFIC | 1,
			DER_DEC_OPTIONAL }
};
const DERSize DERNumPrivateKeyUsagePeriodItemSpecs = 
	sizeof(DERPrivateKeyUsagePeriodItemSpecs) / sizeof(DERItemSpec);

/* DERDistributionPoint. */
const DERItemSpec DERDistributionPointItemSpecs[] = 
{
	{ DER_OFFSET(DERDistributionPoint, distributionPoint),
			ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 0,
			DER_DEC_OPTIONAL },	
	{ DER_OFFSET(DERDistributionPoint, reasons),
			ASN1_CONTEXT_SPECIFIC | 1,
			DER_DEC_OPTIONAL },	
	{ DER_OFFSET(DERDistributionPoint, cRLIssuer),
			ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 2,
			DER_DEC_OPTIONAL }
};
const DERSize DERNumDistributionPointItemSpecs = 
	sizeof(DERDistributionPointItemSpecs) / sizeof(DERItemSpec);

/* DERPolicyInformation. */
const DERItemSpec DERPolicyInformationItemSpecs[] = 
{
	{ DER_OFFSET(DERPolicyInformation, policyIdentifier),
			ASN1_OBJECT_ID,
			DER_DEC_NO_OPTS },	
	{ DER_OFFSET(DERPolicyInformation, policyQualifiers),
			ASN1_CONSTR_SEQUENCE,
			DER_DEC_OPTIONAL }
};
const DERSize DERNumPolicyInformationItemSpecs = 
	sizeof(DERPolicyInformationItemSpecs) / sizeof(DERItemSpec);

/* DERPolicyQualifierInfo. */
const DERItemSpec DERPolicyQualifierInfoItemSpecs[] = 
{
	{ DER_OFFSET(DERPolicyQualifierInfo, policyQualifierID),
			ASN1_OBJECT_ID,
			DER_DEC_NO_OPTS },	
	{ DER_OFFSET(DERPolicyQualifierInfo, qualifier),
			0,					/* no tag - ANY */
			DER_DEC_ASN_ANY | DER_DEC_SAVE_DER }
};
const DERSize DERNumPolicyQualifierInfoItemSpecs = 
	sizeof(DERPolicyQualifierInfoItemSpecs) / sizeof(DERItemSpec);

/* DERUserNotice. */
const DERItemSpec DERUserNoticeItemSpecs[] = 
{
	{ DER_OFFSET(DERUserNotice, noticeRef),
			ASN1_CONSTR_SEQUENCE,
			DER_DEC_OPTIONAL },	
	{ DER_OFFSET(DERUserNotice, explicitText),
			0,					/* no tag - ANY */
			DER_DEC_ASN_ANY | DER_DEC_OPTIONAL | DER_DEC_SAVE_DER }
};
const DERSize DERNumUserNoticeItemSpecs = 
	sizeof(DERUserNoticeItemSpecs) / sizeof(DERItemSpec);

/* DERNoticeReference. */
const DERItemSpec DERNoticeReferenceItemSpecs[] = 
{
	{ DER_OFFSET(DERNoticeReference, organization),
			0,					/* no tag - ANY */
			DER_DEC_ASN_ANY | DER_DEC_SAVE_DER },
	{ DER_OFFSET(DERNoticeReference, noticeNumbers),
			ASN1_CONSTR_SEQUENCE,
			DER_DEC_NO_OPTS }	
};
const DERSize DERNumNoticeReferenceItemSpecs = 
	sizeof(DERNoticeReferenceItemSpecs) / sizeof(DERItemSpec);

/* DERPolicyMapping. */
const DERItemSpec DERPolicyMappingItemSpecs[] = 
{
	{ DER_OFFSET(DERPolicyMapping, issuerDomainPolicy),
			ASN1_OBJECT_ID,
			DER_DEC_NO_OPTS },
	{ DER_OFFSET(DERPolicyMapping, subjectDomainPolicy),
			ASN1_OBJECT_ID,
			DER_DEC_NO_OPTS }
};
const DERSize DERNumPolicyMappingItemSpecs = 
	sizeof(DERPolicyMappingItemSpecs) / sizeof(DERItemSpec);

/* DERAccessDescription. */
const DERItemSpec DERAccessDescriptionItemSpecs[] = 
{
	{ DER_OFFSET(DERAccessDescription, accessMethod),
			ASN1_OBJECT_ID,
			DER_DEC_NO_OPTS },	
	{ DER_OFFSET(DERAccessDescription, accessLocation),
			0,					/* no tag - ANY */
			DER_DEC_ASN_ANY | DER_DEC_SAVE_DER }
};
const DERSize DERNumAccessDescriptionItemSpecs = 
	sizeof(DERAccessDescriptionItemSpecs) / sizeof(DERItemSpec);

/* DERAuthorityKeyIdentifier. */
const DERItemSpec DERAuthorityKeyIdentifierItemSpecs[] = 
{
	{ DER_OFFSET(DERAuthorityKeyIdentifier, keyIdentifier),
			ASN1_CONTEXT_SPECIFIC | 0,
			DER_DEC_OPTIONAL },
	{ DER_OFFSET(DERAuthorityKeyIdentifier, authorityCertIssuer),
			ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 1,
			DER_DEC_OPTIONAL },
	{ DER_OFFSET(DERAuthorityKeyIdentifier, authorityCertSerialNumber),
			ASN1_CONTEXT_SPECIFIC | 2,
			DER_DEC_OPTIONAL }
};
const DERSize DERNumAuthorityKeyIdentifierItemSpecs = 
	sizeof(DERAuthorityKeyIdentifierItemSpecs) / sizeof(DERItemSpec);

/* DEROtherName. */
const DERItemSpec DEROtherNameItemSpecs[] = 
{
	{ DER_OFFSET(DEROtherName, typeIdentifier),
			ASN1_OBJECT_ID,
			DER_DEC_NO_OPTS },	
	{ DER_OFFSET(DEROtherName, value),
			ASN1_CONTEXT_SPECIFIC | ASN1_CONSTRUCTED | 0,
			DER_DEC_NO_OPTS },
};
const DERSize DERNumOtherNameItemSpecs = 
	sizeof(DEROtherNameItemSpecs) / sizeof(DERItemSpec);

/* DERPolicyConstraints. */
const DERItemSpec DERPolicyConstraintsItemSpecs[] = 
{
	{ DER_OFFSET(DERPolicyConstraints, requireExplicitPolicy),
			ASN1_CONTEXT_SPECIFIC | 0,
			DER_DEC_OPTIONAL },
	{ DER_OFFSET(DERPolicyConstraints, inhibitPolicyMapping),
			ASN1_CONTEXT_SPECIFIC | 1,
			DER_DEC_OPTIONAL }
};
const DERSize DERNumPolicyConstraintsItemSpecs = 
	sizeof(DERPolicyConstraintsItemSpecs) / sizeof(DERItemSpec);

/* DERTBSCrl */
const DERItemSpec DERTBSCrlItemSpecs[] = 
{
	{ DER_OFFSET(DERTBSCrl, version),
			ASN1_INTEGER,		
			DER_DEC_OPTIONAL },	
	{ DER_OFFSET(DERTBSCrl, tbsSigAlg),
			ASN1_CONSTR_SEQUENCE, 
			DER_DEC_NO_OPTS },
	{ DER_OFFSET(DERTBSCrl, issuer),
			ASN1_CONSTR_SEQUENCE, 
			DER_DEC_NO_OPTS },	
	{ DER_OFFSET(DERTBSCrl, thisUpdate),
			0,					/* no tag - ANY */
			DER_DEC_ASN_ANY | DER_DEC_SAVE_DER },	
	{ DER_OFFSET(DERTBSCrl, nextUpdate),
			0,					/* no tag - ANY */
			DER_DEC_ASN_ANY | DER_DEC_SAVE_DER },	
	{ DER_OFFSET(DERTBSCrl, revokedCerts),
			ASN1_CONSTR_SEQUENCE, 
			DER_DEC_OPTIONAL },
	{ DER_OFFSET(DERTBSCrl, extensions),
			ASN1_CONSTRUCTED | ASN1_CONTEXT_SPECIFIC | 0,
			DER_DEC_OPTIONAL }
};
const DERSize DERNumTBSCrlItemSpecs = sizeof(DERTBSCrlItemSpecs) / sizeof(DERItemSpec);

/* DERRevokedCert */
const DERItemSpec DERRevokedCertItemSpecs[] = 
{
	{ DER_OFFSET(DERRevokedCert, serialNum),
			ASN1_INTEGER,		
			DER_DEC_NO_OPTS },	
	{ DER_OFFSET(DERRevokedCert, revocationDate),
			0,					/* no tag - ANY */
			DER_DEC_ASN_ANY | DER_DEC_SAVE_DER },	
	{ DER_OFFSET(DERRevokedCert, extensions),
			ASN1_CONSTR_SEQUENCE, 
			DER_DEC_OPTIONAL }
};

const DERSize DERNumRevokedCertItemSpecs = 
	sizeof(DERRevokedCertItemSpecs) / sizeof(DERItemSpec);

Added Source/libDER/libDER/DER_CertCrl.h.



























































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/* Copyright (c) 2005-2009 Apple Inc. All Rights Reserved. */

/*
 * DER_CertCrl.h - support for decoding X509 certificates and CRLs
 *
 * Created Nov. 4 2005 by dmitch
 */
 
#ifndef	_DER_CERT_CRL_H_
#define _DER_CERT_CRL_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "libDER.h"
#include "DER_Decode.h"

/* 
 * Top level cert or CRL - the two are identical at this level - three 
 * components. The tbs field is saved in full DER form for sig verify. 
 */
typedef struct {
	DERItem		tbs;			/* sequence, DERTBSCert, DER_DEC_SAVE_DER */
	DERItem		sigAlg;			/* sequence, DERAlgorithmId */
	DERItem		sig;			/* bit string */
} DERSignedCertCrl;

/* DERItemSpecs to decode into a DERSignedCertCrl */
extern const DERItemSpec DERSignedCertCrlItemSpecs[];
extern const DERSize DERNumSignedCertCrlItemSpecs;

/* TBS cert components */
typedef struct {
	DERItem		version;		/* integer, optional, EXPLICIT */
	DERItem		serialNum;		/* integer */
	DERItem		tbsSigAlg;		/* sequence, DERAlgorithmId */
	DERItem		issuer;			/* sequence, TBD */
	DERItem		validity;		/* sequence,  DERValidity */
	DERItem		subject;		/* sequence, TBD */
	DERItem		subjectPubKey;	/* sequence, DERSubjPubKeyInfo */
	DERItem		issuerID;		/* bit string, optional */
	DERItem		subjectID;		/* bit string, optional */
	DERItem		extensions;		/* sequence, optional, EXPLICIT */
} DERTBSCert;

/* DERItemSpecs to decode into a DERTBSCert */
extern const DERItemSpec DERTBSCertItemSpecs[];
extern const DERSize DERNumTBSCertItemSpecs;

/* 
 * validity - components can be either UTC or generalized time.
 * Both are ASN_ANY with DER_DEC_SAVE_DER.
 */
typedef struct {
	DERItem		notBefore;
	DERItem		notAfter;
} DERValidity;

/* DERItemSpecs to decode into a DERValidity */
extern const DERItemSpec DERValidityItemSpecs[];
extern const DERSize DERNumValidityItemSpecs;

/* AttributeTypeAndValue components. */
typedef struct {
	DERItem		type;
	DERItem		value;
} DERAttributeTypeAndValue;

/* DERItemSpecs to decode into DERAttributeTypeAndValue */
extern const DERItemSpec DERAttributeTypeAndValueItemSpecs[];
extern const DERSize DERNumAttributeTypeAndValueItemSpecs;

/* Extension components */
typedef struct {
	DERItem		extnID;
	DERItem		critical;
	DERItem		extnValue;
} DERExtension;

/* DERItemSpecs to decode into DERExtension */
extern const DERItemSpec DERExtensionItemSpecs[];
extern const DERSize DERNumExtensionItemSpecs;

/* BasicConstraints components. */
typedef struct {
	DERItem		cA;
	DERItem		pathLenConstraint;
} DERBasicConstraints;

/* DERItemSpecs to decode into DERBasicConstraints */
extern const DERItemSpec DERBasicConstraintsItemSpecs[];
extern const DERSize DERNumBasicConstraintsItemSpecs;

/* PrivateKeyUsagePeriod components. */
typedef struct {
	DERItem		notBefore;
	DERItem		notAfter;
} DERPrivateKeyUsagePeriod;

/* DERItemSpecs to decode into a DERPrivateKeyUsagePeriod */
extern const DERItemSpec DERPrivateKeyUsagePeriodItemSpecs[];
extern const DERSize DERNumPrivateKeyUsagePeriodItemSpecs;

/* DistributionPoint components. */
typedef struct {
	DERItem		distributionPoint;
	DERItem		reasons;
    DERItem     cRLIssuer;
} DERDistributionPoint;

/* DERItemSpecs to decode into a DERDistributionPoint */
extern const DERItemSpec DERDistributionPointItemSpecs[];
extern const DERSize DERNumDistributionPointItemSpecs;

/* PolicyInformation components. */
typedef struct {
    DERItem policyIdentifier;
    DERItem policyQualifiers;
} DERPolicyInformation;

/* DERItemSpecs to decode into a DERPolicyInformation */
extern const DERItemSpec DERPolicyInformationItemSpecs[];
extern const DERSize DERNumPolicyInformationItemSpecs;

/* PolicyQualifierInfo components. */
typedef struct {
    DERItem policyQualifierID;
    DERItem qualifier;
} DERPolicyQualifierInfo;

/* DERItemSpecs to decode into a DERPolicyQualifierInfo */
extern const DERItemSpec DERPolicyQualifierInfoItemSpecs[];
extern const DERSize DERNumPolicyQualifierInfoItemSpecs;

/* UserNotice components. */
typedef struct {
    DERItem noticeRef;
    DERItem explicitText;
} DERUserNotice;

/* DERItemSpecs to decode into a DERUserNotice */
extern const DERItemSpec DERUserNoticeItemSpecs[];
extern const DERSize DERNumUserNoticeItemSpecs;

/* NoticeReference components. */
typedef struct {
    DERItem organization;
    DERItem noticeNumbers;
} DERNoticeReference;

/* DERItemSpecs to decode into a DERNoticeReference */
extern const DERItemSpec DERNoticeReferenceItemSpecs[];
extern const DERSize DERNumNoticeReferenceItemSpecs;

/* PolicyMapping components. */
typedef struct {
    DERItem issuerDomainPolicy;
    DERItem subjectDomainPolicy;
} DERPolicyMapping;

/* DERItemSpecs to decode into a DERPolicyMapping */
extern const DERItemSpec DERPolicyMappingItemSpecs[];
extern const DERSize DERNumPolicyMappingItemSpecs;

/* AccessDescription components. */
typedef struct {
    DERItem accessMethod;
    DERItem accessLocation;
} DERAccessDescription;

/* DERItemSpecs to decode into a DERAccessDescription */
extern const DERItemSpec DERAccessDescriptionItemSpecs[];
extern const DERSize DERNumAccessDescriptionItemSpecs;

/* AuthorityKeyIdentifier components. */
typedef struct {
    DERItem keyIdentifier;
    DERItem authorityCertIssuer;
    DERItem authorityCertSerialNumber;
} DERAuthorityKeyIdentifier;

/* DERItemSpecs to decode into a DERAuthorityKeyIdentifier */
extern const DERItemSpec DERAuthorityKeyIdentifierItemSpecs[];
extern const DERSize DERNumAuthorityKeyIdentifierItemSpecs;

/* OtherName components. */
typedef struct {
    DERItem typeIdentifier;
    DERItem value;
} DEROtherName;

/* DERItemSpecs to decode into a DEROtherName */
extern const DERItemSpec DEROtherNameItemSpecs[];
extern const DERSize DERNumOtherNameItemSpecs;

/* PolicyConstraints components. */
typedef struct {
    DERItem requireExplicitPolicy;
    DERItem inhibitPolicyMapping;
} DERPolicyConstraints;

/* DERItemSpecs to decode into a DERPolicyConstraints */
extern const DERItemSpec DERPolicyConstraintsItemSpecs[];
extern const DERSize DERNumPolicyConstraintsItemSpecs;

/* TBS CRL */
typedef struct {
	DERItem		version;		/* integer, optional */
	DERItem		tbsSigAlg;		/* sequence, DERAlgorithmId */
	DERItem		issuer;			/* sequence, TBD */
	DERItem		thisUpdate;		/* ASN_ANY, SAVE_DER */
	DERItem		nextUpdate;		/* ASN_ANY, SAVE_DER */
	DERItem		revokedCerts;	/* sequence of DERRevokedCert, optional */
	DERItem		extensions;		/* sequence, optional, EXPLICIT */
} DERTBSCrl;

/* DERItemSpecs to decode into a DERTBSCrl */
extern const DERItemSpec DERTBSCrlItemSpecs[];
extern const DERSize DERNumTBSCrlItemSpecs;

typedef struct {
	DERItem		serialNum;		/* integer */
	DERItem		revocationDate;	/* time - ASN_ANY, SAVE_DER */
	DERItem		extensions;		/* sequence, optional, EXPLICIT */
} DERRevokedCert;

/* DERItemSpecs to decode into a DERRevokedCert */
extern const DERItemSpec DERRevokedCertItemSpecs[];
extern const DERSize DERNumRevokedCertItemSpecs;

#ifdef __cplusplus
}
#endif

#endif	/* _DER_CERT_CRL_H_ */

Added Source/libDER/libDER/DER_Decode.c.

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
/*
 * Copyright (c) 2005-2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* 
 * DER_Decode.c - DER decoding routines
 */
 
#include "DER_Decode.h"
#include "asn1Types.h"

#include "libDER_config.h"

#ifndef	DER_DECODE_ENABLE
#error Please define DER_DECODE_ENABLE.
#endif

#if		DER_DECODE_ENABLE

#define DER_DECODE_DEBUG	0
#if		DER_DECODE_DEBUG
#include <stdio.h>
#define derDecDbg(a)			printf(a)
#define derDecDbg1(a, b)		printf(a, b)
#define derDecDbg2(a, b, c)		printf(a, b, c)
#define derDecDbg3(a, b, c, d)	printf(a, b, c, d)
#else	
#define derDecDbg(a)	
#define derDecDbg1(a, b)	
#define derDecDbg2(a, b, c)	
#define derDecDbg3(a, b, c, d)
#endif	/* DER_DECODE_DEBUG */

/*
 *  Basic decoding primitive. Only works with:
 *
 *  -- definite length encoding 
 *  -- one-byte tags 
 *  -- max content length fits in a DERSize
 *
 * No malloc or copy of the contents is performed; the returned 
 * content->content.data is a pointer into the incoming der data.
 */
DERReturn DERDecodeItem(
	const DERItem	*der,			/* data to decode */
	DERDecodedInfo	*decoded)		/* RETURNED */
{
	DERByte tag1;			/* first tag byte */
	DERByte len1;			/* first length byte */
	DERTag tagNumber;       /* tag number without class and method bits */
	DERByte *derPtr = der->data;
	DERSize derLen = der->length;

    /* The tag decoding below is fully BER complient.  We support a max tag
       value of 2 ^ ((sizeof(DERTag) * 8) - 3) - 1 so for tag size 1 byte we
       support tag values from 0 - 0x1F.  For tag size 2 tag values
       from 0 - 0x1FFF and for tag size 4 values from 0 - 0x1FFFFFFF. */
	if(derLen < 2) {
		return DR_DecodeError;
	}
    /* Grab the first byte of the tag. */
	tag1 = *derPtr++;
	derLen--;
	tagNumber = tag1 & 0x1F;
	if(tagNumber == 0x1F) {
#ifdef DER_MULTIBYTE_TAGS
        /* Long tag form: bit 8 of each octet shall be set to one unless it is
           the last octet of the tag */
        const DERTag overflowMask = ((DERTag)0x7F << (sizeof(DERTag) * 8 - 7));
        DERByte tagByte;
        tagNumber = 0;
        do {
            if(derLen < 2 || (tagNumber & overflowMask) != 0) {
                return DR_DecodeError;
            }
            tagByte = *derPtr++;
            derLen--;
            tagNumber = (tagNumber << 7) | (tagByte & 0x7F);
        } while((tagByte & 0x80) != 0);

        /* Check for any of the top 3 reserved bits being set. */
        if ((tagNumber & (overflowMask << 4)) != 0)
#endif
            return DR_DecodeError;
	}
    /* Returned tag, top 3 bits are class/method remaining bits are number. */
    decoded->tag = ((DERTag)(tag1 & 0xE0) << ((sizeof(DERTag) - 1) * 8)) | tagNumber;

    /* Tag decoding above ensured we have at least one more input byte left. */
	len1 = *derPtr++;
	derLen--;
	if(len1 & 0x80) {
		/* long length form - first byte is length of length */
		DERSize longLen = 0;	/* long form length */
		unsigned dex;

		len1 &= 0x7f;
		if((len1 > sizeof(DERSize)) || (len1 > derLen)) {
			/* no can do */
			return DR_DecodeError;
		}
		for(dex=0; dex<len1; dex++) {
			longLen <<= 8;
			longLen |= *derPtr++;
			derLen--;
		}
		if(longLen > derLen) {
			/* not enough data left for this encoding */
			return DR_DecodeError;
		}
		decoded->content.data = derPtr;
		decoded->content.length = longLen;
	}
	else {
		/* short length form, len1 is the length */
		if(len1 > derLen) {
			/* not enough data left for this encoding */
			return DR_DecodeError;
		}
		decoded->content.data = derPtr;
		decoded->content.length = len1;
	}

    return DR_Success;
}

/* 
 * Given a BIT_STRING, in the form of its raw content bytes, 
 * obtain the number of unused bits and the raw bit string bytes.
 */
DERReturn DERParseBitString(
	const DERItem	*contents,
	DERItem			*bitStringBytes,	/* RETURNED */
	DERByte			*numUnusedBits)		/* RETURNED */
{
	if(contents->length < 2) {
		/* not enough room for actual bits after the unused bits field */
		*numUnusedBits = 0;
		bitStringBytes->data = NULL;
		bitStringBytes->length = 0;
		return DR_Success;
	}
	*numUnusedBits = contents->data[0];
	bitStringBytes->data = contents->data + 1;
	bitStringBytes->length = contents->length - 1;
	return DR_Success;
}

/* 
 * Given a BOOLEAN, in the form of its raw content bytes, 
 * obtain it's value.
 */
DERReturn DERParseBoolean(
	const DERItem	*contents,
	bool			defaultValue,
	bool			*value) {	/* RETURNED */
    if (contents->length == 0) {
        *value = defaultValue;
        return DR_Success;
    }
    if (contents->length != 1 ||
        (contents->data[0] != 0 && contents->data[0] != 0xFF))
        return DR_DecodeError;

    *value = contents->data[0] != 0;
    return DR_Success;
}

DERReturn DERParseInteger(
	const DERItem	*contents,
	uint32_t        *result) {	/* RETURNED */
    DERSize ix, length = contents->length;
    if (length > 4)
        return DR_BufOverflow;
    uint32_t value = 0;
    for (ix = 0; ix < length; ++ix) {
        value <<= 8;
        value += contents->data[ix];
    }
    *result = value;
    return DR_Success;
}

/* Sequence/set support */

/* 
 * To decode a set or sequence, call DERDecodeSeqInit once, then
 * call DERDecodeSeqNext to get each enclosed item.
 * DERDecodeSeqNext returns DR_EndOfSequence when no more
 * items are available. 
 */
DERReturn DERDecodeSeqInit(
	const DERItem	*der,			/* data to decode */
	DERTag			*tag,			/* RETURNED tag of sequence/set. This will be
									 * either ASN1_CONSTR_SEQUENCE or ASN1_CONSTR_SET. */
	DERSequence		*derSeq)		/* RETURNED, to use in DERDecodeSeqNext */
{
	DERDecodedInfo decoded;
	DERReturn drtn;
	
	drtn = DERDecodeItem(der, &decoded);
	if(drtn) {
		return drtn;
	}
    *tag = decoded.tag;
	switch(decoded.tag) {
		case ASN1_CONSTR_SEQUENCE:
		case ASN1_CONSTR_SET:
			break;
		default:
			return DR_UnexpectedTag;
	}
	derSeq->nextItem = decoded.content.data;
	derSeq->end = decoded.content.data + decoded.content.length;
	return DR_Success;
}

/* 
 * Use this to start in on decoding a sequence's content, when 
 * the top-level tag and content have already been decoded. 
 */
DERReturn DERDecodeSeqContentInit(
	const DERItem	*content,
	DERSequence		*derSeq)		/* RETURNED, to use in DERDecodeSeqNext */
{
	/* just prepare for decoding items in content */
	derSeq->nextItem = content->data;
	derSeq->end = content->data + content->length;
	return DR_Success;
}

DERReturn DERDecodeSeqNext(
	DERSequence		*derSeq,
	DERDecodedInfo	*decoded)		/* RETURNED */
{
	DERReturn drtn;
	DERItem item;
	
	if(derSeq->nextItem >= derSeq->end) {
		/* normal termination, contents all used up */
		return DR_EndOfSequence;
	}
	
	/* decode next item */
	item.data = derSeq->nextItem;
	item.length = derSeq->end - derSeq->nextItem;
	drtn = DERDecodeItem(&item, decoded);
	if(drtn) {
		return drtn;
	}	
	
	/* skip over the item we just decoded */
	derSeq->nextItem = decoded->content.data + decoded->content.length;
	return DR_Success;
}

/* 
 * High level sequence parse, starting with top-level tag and content.
 * Top level tag must be ASN1_CONSTR_SEQUENCE - if it's not, and that's 
 * OK, use DERParseSequenceContent().
 */
DERReturn DERParseSequence(
	const DERItem			*der,
	DERShort				numItems,	/* size of itemSpecs[] */
	const DERItemSpec		*itemSpecs,
	void					*dest,		/* DERDecodedInfo(s) here RETURNED */
	DERSize					sizeToZero)	/* optional */
{
	DERReturn drtn;
	DERDecodedInfo topDecode;
	
	drtn = DERDecodeItem(der, &topDecode);
	if(drtn) {
		return drtn;
	}
	if(topDecode.tag != ASN1_CONSTR_SEQUENCE) {
		return DR_UnexpectedTag;
	}
	return DERParseSequenceContent(&topDecode.content,
		numItems, itemSpecs, dest, sizeToZero);
}

/* high level sequence parse, starting with sequence's content */
DERReturn DERParseSequenceContent(
	const DERItem			*content,
	DERShort				numItems,	/* size of itemSpecs[] */
	const DERItemSpec		*itemSpecs,
	void					*dest,		/* DERDecodedInfo(s) here RETURNED */
	DERSize					sizeToZero)	/* optional */
{
	DERSequence			derSeq;
	DERReturn			drtn;
	DERShort			itemDex;
	DERByte				*currDER;	/* full DER encoding of current item */
	
	if(sizeToZero) {
		DERMemset(dest, 0, sizeToZero);
	}
	
	drtn = DERDecodeSeqContentInit(content, &derSeq);
	if(drtn) {
		return drtn;
	}
	
	/* main loop */
	for(itemDex=0 ; itemDex<numItems; ) {
		DERDecodedInfo currDecoded;
		DERShort i;
		DERTag foundTag;
		char foundMatch = 0;
		
		/* save this in case of DER_DEC_SAVE_DER */
		currDER = derSeq.nextItem;
		
		drtn = DERDecodeSeqNext(&derSeq, &currDecoded);
		if(drtn) {
			/* 
			 * One legal error here is DR_EndOfSequence when 
			 * all remaining DERSequenceItems are optional. 
			 */
			if(drtn == DR_EndOfSequence) {
				for(i=itemDex; i<numItems; i++) {
					if(!(itemSpecs[i].options & DER_DEC_OPTIONAL)) {
						/* unexpected end of sequence */
						return DR_IncompleteSeq;
					}
				}
				/* the rest are optional; success */
				return DR_Success;
			}
			else {
				/* any other error is fatal */
				return drtn;
			}
		}	/* decode error */
		
		/* 
		 * Seek matching tag or ASN_ANY in itemSpecs, skipping 
		 * over optional items.
		 */
		foundTag = currDecoded.tag;
		derDecDbg1("--- foundTag 0x%x\n", foundTag);
		
		for(i=itemDex; i<numItems; i++) {
			const DERItemSpec *currItemSpec = &itemSpecs[i];
			DERShort currOptions = currItemSpec->options;
			derDecDbg3("--- currItem %u expectTag 0x%x currOptions 0x%x\n", 
				i, currItemSpec->tag, currOptions);
			
			if((currOptions & DER_DEC_ASN_ANY) ||
			   (foundTag == currItemSpec->tag)) {
				/* 
				 * We're good with this one. Cook up destination address
				 * as appropriate. 
				 */
				if(!(currOptions & DER_DEC_SKIP)) {
					derDecDbg1("--- MATCH at currItem %u\n", i);
					DERByte *byteDst = (DERByte *)dest + currItemSpec->offset;
					DERItem *dst = (DERItem *)byteDst;
					*dst = currDecoded.content;
					if(currOptions & DER_DEC_SAVE_DER) {
						/* recreate full DER encoding of this item */
						derDecDbg1("--- SAVE_DER at currItem %u\n", i);
						dst->data = currDER;
						dst->length += (currDecoded.content.data - currDER);
					}
				}

				/* on to next item */
				itemDex = i + 1;
				
				/* is this the end? */
				if(itemDex == numItems) {
					/* normal termination */
					return DR_Success;
				}
				else {
					/* on to next item */ 
					foundMatch = 1;
					break;
				}
			} /* ASN_ANY, or match */
			
			/* 
			 * If current itemSpec isn't optional, abort - else on to 
			 * next item
			 */
			if(!(currOptions & DER_DEC_OPTIONAL)) {
				derDecDbg1("--- MISMATCH at currItem %u, !OPTIONAL, abort\n", i);
				return DR_UnexpectedTag;
			}
			
			/* else this was optional, on to next item */
		} /* searching for tag match */
		
		if(foundMatch == 0) {
			/* 
			 * Found an item we couldn't match to any tag spec and we're at
			 * the end. 
			 */
			derDecDbg("--- TAG NOT FOUND, abort\n");
			return DR_UnexpectedTag;
		}
		
		/* else on to next item */
	}	/* main loop */
	
	/*
	 * If we get here, there appears to be more to process, but we've
	 * given the caller everything they want. 
	 */
	return DR_Success;
}

#if 0
/* 
 * High level sequence parse, starting with top-level tag and content.
 * Top level tag must be ASN1_CONSTR_SEQUENCE - if it's not, and that's 
 * OK, use DERParseSequenceContent().
 */
DERReturn DERParseSequenceOf(
	const DERItem			*der,
	DERShort				numItems,	/* size of itemSpecs[] */
	const DERItemSpec		*itemSpecs,
	void					*dest,		/* DERDecodedInfo(s) here RETURNED */
	DERSize					*numDestItems)	/* output */
{
	DERReturn drtn;
	DERDecodedInfo topDecode;
	
	drtn = DERDecodeItem(der, &topDecode);
	if(drtn) {
		return drtn;
	}
	if(topDecode.tag != ASN1_CONSTR_SEQUENCE) {
		return DR_UnexpectedTag;
	}
	return DERParseSequenceContent(&topDecode.content,
		numItems, itemSpecs, dest, sizeToZero);
}

/* 
 * High level set of parse, starting with top-level tag and content.
 * Top level tag must be ASN1_CONSTR_SET - if it's not, and that's 
 * OK, use DERParseSetOrSequenceOfContent().
 */
DERReturn DERParseSetOf(
	const DERItem			*der,
	DERShort				numItems,	/* size of itemSpecs[] */
	const DERItemSpec		*itemSpecs,
	void					*dest,		/* DERDecodedInfo(s) here RETURNED */
	DERSize					*numDestItems)	/* output */
{
	DERReturn drtn;
	DERDecodedInfo topDecode;
	
	drtn = DERDecodeItem(der, &topDecode);
	if(drtn) {
		return drtn;
	}
	if(topDecode.tag != ASN1_CONSTR_SET) {
		return DR_UnexpectedTag;
	}
	return DERParseSetOrSequenceOfContent(&topDecode.content,
		numItems, itemSpecs, dest, numDestItems);
}

/* High level set of or sequence of parse, starting with set or
   sequence's content */
DERReturn DERParseSetOrSequenceOfContent(
    const DERItem			*content,
    void(*itemHandeler)(void *, const DERDecodedInfo *)
	void					*itemHandelerContext);
{
    DERSequence			derSeq;
    DERShort			itemDex;

    drtn = DERDecodeSeqContentInit(content, &derSeq);
    require_noerr_quiet(drtn, badCert);

    /* main loop */
    for (;;) {
        DERDecodedInfo currDecoded;
        DERShort i;
        DERByte foundTag;
        char foundMatch = 0;

        drtn = DERDecodeSeqNext(&derSeq, &currDecoded);
        if(drtn) {
            /* The only legal error here is DR_EndOfSequence. */
            if(drtn == DR_EndOfSequence) {
                /* no more items left in the sequence; success */
                return DR_Success;
            }
            else {
                /* any other error is fatal */
                require_noerr_quiet(drtn, badCert);
            }
        }	/* decode error */
        
        /* Each element can be anything. */
        foundTag = currDecoded.tag;

        /* 
         * We're good with this one. Cook up destination address
         * as appropriate. 
         */
        DERByte *byteDst = (DERByte *)dest + currItemSpec->offset;
        DERItem *dst = (DERItem *)byteDst;
        *dst = currDecoded.content;
        if(currOptions & DER_DEC_SAVE_DER) {
            /* recreate full DER encoding of this item */
            derDecDbg1("--- SAVE_DER at currItem %u\n", i);
            dst->data = currDER;
            dst->length += (currDecoded.content.data - currDER);
        }

        /* on to next item */
        itemDex = i + 1;
        
        /* is this the end? */
        if(itemDex == numItems) {
            /* normal termination */
            return DR_Success;
        }
        else {
            /* on to next item */ 
            foundMatch = 1;
            break;
        }
            
            /* 
             * If current itemSpec isn't optional, abort - else on to 
             * next item
             */
            if(!(currOptions & DER_DEC_OPTIONAL)) {
                derDecDbg1("--- MISMATCH at currItem %u, !OPTIONAL, abort\n", i);
                return DR_UnexpectedTag;
            }
            
            /* else this was optional, on to next item */
        } /* searching for tag match */
        
        if(foundMatch == 0) {
            /* 
             * Found an item we couldn't match to any tag spec and we're at
             * the end. 
             */
            derDecDbg("--- TAG NOT FOUND, abort\n");
            return DR_UnexpectedTag;
        }
        
        /* else on to next item */
    }	/* main loop */

    /*
     * If we get here, there appears to be more to process, but we've
     * given the caller everything they want. 
     */
    return DR_Success;
    }
}
#endif

#endif	/* DER_DECODE_ENABLE */

Added Source/libDER/libDER/DER_Decode.h.







































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
/*
 * Copyright (c) 2005-2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* 
 * DER_Decode.h - DER decoding routines
 */
 
#ifndef	_DER_DECODE_H_
#define _DER_DECODE_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "libDER.h"
#include <stdbool.h>

/*
 * Decoding one item consists of extracting its tag, a pointer
 * to the actual content, and the length of the content. Those
 * three are represented by a DERDecodedInfo.
 */
typedef struct {
	DERTag		tag;
	DERItem		content;
} DERDecodedInfo;

/*
 * Basic decoding primitive. Only works with:
 *
 *  -- definite length encoding 
 *  -- one-byte tags 
 *  -- max content length fits in a DERSize
 *
 * No malloc or copy of the contents is performed; the returned 
 * content->content.data is a pointer into the incoming der data.
 */
DERReturn DERDecodeItem(
	const DERItem	*der,			/* data to decode */
	DERDecodedInfo	*decoded);		/* RETURNED */

/* 
 * Given a BIT_STRING, in the form of its raw content bytes, 
 * obtain the number of unused bits and the raw bit string bytes.
 */
DERReturn DERParseBitString(
	const DERItem	*contents,
	DERItem			*bitStringBytes,	/* RETURNED */
	DERByte			*numUnusedBits);	/* RETURNED */

/* 
 * Given a BOOLEAN, in the form of its raw content bytes, 
 * obtain it's value.
 */
DERReturn DERParseBoolean(
	const DERItem	*contents,
	bool			defaultValue,
	bool			*value);	/* RETURNED */

DERReturn DERParseInteger(
	const DERItem	*contents,
	uint32_t        *value);	/* RETURNED */

/* 
 * Sequence/set decode support.
 */
 
/* state representing a sequence or set being decoded */
typedef struct {
	DERByte	*nextItem;
	DERByte	*end;
} DERSequence;

/* 
 * To decode a set or sequence, call DERDecodeSeqInit or
 * DERDecodeSeqContentInit once, then call DERDecodeSeqNext to 
 * get each enclosed item. 
 *
 * DERDecodeSeqNext returns DR_EndOfSequence when no more
 * items are available. 
 */
 
/* 
 * Use this to parse the top level sequence's tag and content length.
 */
DERReturn DERDecodeSeqInit(
	const DERItem	*der,			/* data to decode */
	DERTag			*tag,			/* RETURNED tag of sequence/set. This will be
									 *    either ASN1_CONSTR_SEQUENCE or 
									 *    ASN1_CONSTR_SET. */
	DERSequence		*derSeq);		/* RETURNED, to use in DERDecodeSeqNext */
	
/* 
 * Use this to start in on decoding a sequence's content, when 
 * the top-level tag and content have already been decoded. 
 */
DERReturn DERDecodeSeqContentInit(
	const DERItem	*content,
	DERSequence		*derSeq);		/* RETURNED, to use in DERDecodeSeqNext */

/* obtain the next decoded item in a sequence or set */
DERReturn DERDecodeSeqNext(
	DERSequence		*derSeq,
	DERDecodedInfo	*decoded);		/* RETURNED */
	
/*
 * High level sequence decode.
 */

/* 
 * Per-item decode options.
 */
 
/* Explicit default, no options */
#define DER_DEC_NO_OPTS		0x0000

/* This item optional, can be skipped during decode */
#define DER_DEC_OPTIONAL	0x0001	

/* Skip the tag check; accept anything. */
#define DER_DEC_ASN_ANY		0x0002	

/* Skip item, no write to DERDecodedInfo (but tag check still performed) */
#define DER_DEC_SKIP		0x0004		

/* Save full DER encoding in DERDecodedInfo, including tag and length. Normally
 * only the content is saved. */
#define DER_DEC_SAVE_DER	0x0008

/* 
 * High level sequence parse, starting with top-level tag and content.
 * Top level tag must be ASN1_CONSTR_SEQUENCE - if it's not, and that's 
 * OK, use DERParseSequenceContent().
 *
 * These never return DR_EndOfSequence - if an *unexpected* end of sequence
 * occurs, return DR_IncompleteSeq.
 *
 * Results of the decoding of one item are placed in a DERItem whose address 
 * is the dest arg plus the offset value in the associated DERItemSpec. 
 *
 * Items which are optional (DER_DEC_OPTIONAL) and which are not found, 
 * leave their associated DERDecodedInfos unmodified.
 *
 * Processing of a sequence ends on detection of any error or after the
 * last DERItemSpec is processed. 
 *
 * The sizeToZero argument, if nonzero, indicates the number of bytes
 * starting at dest to zero before processing the sequence. This is 
 * generally desirable, particularly if there are any DER_DEC_OPTIONAL
 * items in the sequence; skipped optional items are detected by the 
 * caller via a NULL DERDecodedInfo.content.data; if this hasn't been
 * explicitly zeroed (generally, by passing a nonzero value of sizeToZero),
 * skipped items can't be detected. 
 */
DERReturn DERParseSequence(
	const DERItem			*der,
	DERShort				numItems,		/* size of itemSpecs[] */
	const DERItemSpec		*itemSpecs,
	void					*dest,			/* DERDecodedInfo(s) here RETURNED */
	DERSize					sizeToZero);	/* optional */
	
/* high level sequence parse, starting with sequence's content */
DERReturn DERParseSequenceContent(
	const DERItem			*content,
	DERShort				numItems,		/* size of itemSpecs[] */
	const DERItemSpec		*itemSpecs,
	void					*dest,			/* DERDecodedInfo(s) here RETURNED */
	DERSize					sizeToZero);	/* optional */

#ifdef __cplusplus
}
#endif

#endif	/* _DER_DECODE_H_ */

Added Source/libDER/libDER/DER_Digest.c.





































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/* Copyright (c) 2005-2008,2010 Apple Inc. All Rights Reserved. */

/*
 * DER_Digest.h - DER encode a DigestInfo
 *
 * Created Nov. 9 2005 by dmitch
 */

#include "DER_Digest.h"

/* 
 * Create an encoded DigestInfo based on the specified SHA1 digest. 
 * The digest must be 20 bytes long. 
 *
 * Result is placed in caller's buffer, which must be at least of
 * length DER_DIGEST_INFO_LEN bytes. 
 *
 * The *resultLen parameter is the available size in the result
 * buffer on input, and the actual length of the encoded DigestInfo 
 * on output. 
 *
 * In the interest of saving code space, this just drops the caller's 
 * digest into an otherwise hard-coded, fixed, encoded SHA1 DigestInfo.
 * Nothing is variable so we know the whole thing. It looks like this:
 *
 * SEQUENCE OF <33> {
 *		SEQUENCE OF <9> {
 *			OID <5>: OID : < 06 05 2B 0E 03 02 1A >
 *			NULL
 *		}
 *		OCTET STRING <20>:
 *			55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 
 *			55 55 55 55 
 *		}
 *		
 *
 * tower.local:digestInfo> hexdump -x /tmp/encodedDigest 
 * 0000000    3021    3009    0605    2b0e    0302    1a05    0004    1455
 * 0000010    5555    5555    5555    5555    5555    5555    5555    5555
 * *
 * 0000020
 */
 
static const unsigned char encodedSha1Digest[] = 
{
	0x30, 0x21,				/* top level sequence length 33 */
		  0x30, 0x09,		/* algorithm ID, sequence length 9 */
			    0x06, 0x05,	/* alg OID, length 5, SHA1 */
					  0x2b, 0x0e, 0x03, 0x02, 0x1a,
				0x05, 0x00,	/* NULL parameters */
		  0x04, 0x14		/* integer length 20 */
							/* digest follows */
};

DERReturn DEREncodeSHA1DigestInfo(
	const DERByte	*sha1Digest,
	DERSize			sha1DigestLen,
	DERByte			*result,		/* encoded result RETURNED here */
	DERSize			*resultLen)		/* IN/OUT */
{
	DERSize totalLen = sizeof(encodedSha1Digest) + DER_SHA1_DIGEST_LEN;
	
	if((sha1Digest == NULL) || (sha1DigestLen != DER_SHA1_DIGEST_LEN) ||
		(result == NULL) || (resultLen == NULL)) {
		return DR_ParamErr;
	}
	if(*resultLen < DER_SHA1_DIGEST_INFO_LEN) {
		return DR_BufOverflow;
	}
	DERMemmove(result, encodedSha1Digest, sizeof(encodedSha1Digest));
	DERMemmove(result + sizeof(encodedSha1Digest), sha1Digest, DER_SHA1_DIGEST_LEN);
	*resultLen = totalLen;
	return DR_Success;
}

/* 
        joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) 
        csor(3) nistalgorithm(4) hashAlgs(2) sha256(1)
        
        future ones to add: sha384(2)  sha512(3)  sha224(4)
*/
static const unsigned char encodedSha256Digest[] = 
{
	0x30, 0x31,				/* top level sequence length 49 */
		  0x30, 0x0d,		/* algorithm ID, sequence length 13 */
                0x06, 0x09,
                      0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
                0x05, 0x00, /* NULL parameters */
		  0x04, 0x20		/* integer length 32 */
							/* digest follows */
};

DERReturn DEREncodeSHA256DigestInfo(
	const DERByte	*sha256Digest,
	DERSize			sha256DigestLen,
	DERByte			*result,		/* encoded result RETURNED here */
	DERSize			*resultLen)		/* IN/OUT */
{
	DERSize totalLen = sizeof(encodedSha256Digest) + DER_SHA256_DIGEST_LEN;
	
	if((sha256Digest == NULL) || (sha256DigestLen != DER_SHA256_DIGEST_LEN) ||
		(result == NULL) || (resultLen == NULL)) {
		return DR_ParamErr;
	}
	if(*resultLen < DER_SHA256_DIGEST_INFO_LEN) {
		return DR_BufOverflow;
	}
	DERMemmove(result, encodedSha256Digest, sizeof(encodedSha256Digest));
	DERMemmove(result + sizeof(encodedSha256Digest), sha256Digest, DER_SHA256_DIGEST_LEN);
	*resultLen = totalLen;
	return DR_Success;
}


/* Same thing, MD5/MD2 */
static const unsigned char encodedMdDigest[] = 
{
	0x30, 0x20,				/* top level sequence length 32 */
		  0x30, 0x0c,		/* algorithm ID, sequence length 12 */
			    0x06, 0x08,	/* alg OID, length 8, MD2/MD5 */
					  0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 
							0x05,	/* 5 = MD5, 2 = MD2 */
				0x05, 0x00,	/* NULL parameters */
		  0x04, 0x10		/* integer length 16 */
							/* digest follows */
};

#define WHICH_DIGEST_INDEX	13
#define WHICH_DIGEST_MD2	2
#define WHICH_DIGEST_MD5	5

DERReturn DEREncodeMDDigestInfo(
	WhichDigest		whichDigest,	
	const DERByte	*mdDigest,
	DERSize			mdDigestLen,
	DERByte			*result,		/* encoded result RETURNED here */
	DERSize			*resultLen)		/* IN/OUT */
{
	DERSize totalLen = sizeof(encodedMdDigest) + DER_MD_DIGEST_LEN;
	
	if((mdDigest == NULL) || (mdDigestLen != DER_MD_DIGEST_LEN) ||
		(result == NULL) || (resultLen == NULL)) {
		return DR_ParamErr;
	}
	if(*resultLen < totalLen) {
		return DR_BufOverflow;
	}
	DERMemmove(result, encodedMdDigest, sizeof(encodedMdDigest));
	DERMemmove(result + sizeof(encodedMdDigest), mdDigest, DER_MD_DIGEST_LEN);
	switch(whichDigest) {
		case WD_MD2:
			result[WHICH_DIGEST_INDEX] = WHICH_DIGEST_MD2;
			break;
		case WD_MD5:
			result[WHICH_DIGEST_INDEX] = WHICH_DIGEST_MD5;
			break;
		default:
			return DR_ParamErr;
	}
	*resultLen = totalLen;
	return DR_Success;
}

Added Source/libDER/libDER/DER_Digest.h.





















































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/* Copyright (c) 2005-2008,2010 Apple Inc. All Rights Reserved. */

/*
 * DER_Digest.h - DER encode a DigestInfo
 *
 * Created Nov. 9 2005 by dmitch
 */

#ifndef	_DER_DIGEST_H_
#define _DER_DIGEST_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "libDER.h"

/* 
 * Create an encoded DigestInfo based on the specified SHA1 digest. 
 * The incoming digest must be 20 bytes long. 
 *
 * Result is placed in caller's buffer, which must be at least of
 * length DER_SHA1_DIGEST_INFO_LEN bytes. 
 *
 * The *resultLen parameter is the available size in the result
 * buffer on input, and the actual length of the encoded DigestInfo 
 * on output. 
 */
#define DER_SHA1_DIGEST_LEN			20
#define DER_SHA1_DIGEST_INFO_LEN	35 

DERReturn DEREncodeSHA1DigestInfo(
	const DERByte	*sha1Digest,
	DERSize			sha1DigestLen,
	DERByte			*result,		/* encoded result RETURNED here */
	DERSize			*resultLen);	/* IN/OUT */

#define DER_SHA256_DIGEST_LEN		32
#define DER_SHA256_DIGEST_INFO_LEN	51 

DERReturn DEREncodeSHA256DigestInfo(
	const DERByte	*sha256Digest,
	DERSize			sha256DigestLen,
	DERByte			*result,		/* encoded result RETURNED here */
	DERSize			*resultLen);	/* IN/OUT */

/*
 * Likewise, create an encoded DIgestInfo for specified MD5 or MD2 digest. 
 */
#define DER_MD_DIGEST_LEN			16
#define DER_MD_DIGEST_INFO_LEN		34 

typedef enum {
	WD_MD2 = 1,
	WD_MD5 = 2
} WhichDigest;

DERReturn DEREncodeMDDigestInfo(
	WhichDigest		whichDigest,
	const DERByte	*mdDigest,
	DERSize			mdDigestLen,
	DERByte			*result,		/* encoded result RETURNED here */
	DERSize			*resultLen);	/* IN/OUT */

/* max sizes you'll need in the general cases */
#define DER_MAX_DIGEST_LEN			DER_SHA256_DIGEST_LEN
#define DER_MAX_ENCODED_INFO_LEN	DER_SHA256_DIGEST_INFO_LEN

#ifdef __cplusplus
}
#endif

#endif	/* _DER_DIGEST_H_ */

Added Source/libDER/libDER/DER_Encode.c.













































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/* Copyright (c) 2005-2007 Apple Inc. All Rights Reserved. */

/*
 * DER_Encode.h - DER encoding routines
 *
 * Created Dec. 2 2005 by dmitch
 */

#include "DER_Encode.h"
#include "asn1Types.h"
#include "libDER_config.h"
#include "DER_Decode.h"

#ifndef	DER_ENCODE_ENABLE
#error Please define DER_ENCODE_ENABLE.
#endif

#if		DER_ENCODE_ENABLE

/* calculate size of encoded tag */
static DERSize DERLengthOfTag(
	DERTag tag)
{
	DERSize rtn = 1;

    tag &= ASN1_TAGNUM_MASK;
    if (tag >= 0x1F) {
        /* Shift 7-bit digits out of the tag integer until it's zero. */
        while(tag != 0) {
            rtn++;
            tag >>= 7;
        }
    }

    return rtn;
}

/* encode tag */
static DERReturn DEREncodeTag(
	DERTag tag,
	DERByte *buf,		/* encoded length goes here */
	DERSize *inOutLen)	/* IN/OUT */
{
    DERSize outLen = DERLengthOfTag(tag);
    DERTag tagNumber = tag & ASN1_TAGNUM_MASK;
    DERByte tag1 = (tag >> (sizeof(DERTag) * 8 - 8)) & 0xE0;

	if(outLen > *inOutLen) {
		return DR_BufOverflow;
	}

    if(outLen == 1) {
		/* short form */
		*buf = tag1 | tagNumber;
	}
	else {
        /* long form */
        DERByte *tagBytes = buf + outLen;	// l.s. digit of tag
        *buf = tag1 | 0x1F;                 // tag class / method indicator
        *--tagBytes = tagNumber & 0x7F;
        tagNumber >>= 7;
        while(tagNumber != 0) {
            *--tagBytes = (tagNumber & 0x7F) | 0x80;
            tagNumber >>= 7;
        }
    }
	*inOutLen = outLen;
	return DR_Success;
}

/* calculate size of encoded length */
DERSize DERLengthOfLength(
	DERSize length)
{
	DERSize rtn;
	
	if(length < 0x80) {
		/* short form length */
		return 1;
	}
	
	/* long form - one length-of-length byte plus length bytes */
	rtn = 1;
	while(length != 0) {
		rtn++;
		length >>= 8;
	}
	return rtn;
}

/* encode length */
DERReturn DEREncodeLength(
	DERSize length,
	DERByte *buf,		/* encoded length goes here */
	DERSize *inOutLen)	/* IN/OUT */
{
	DERByte *lenBytes;
	DERSize outLen = DERLengthOfLength(length);
	
	if(outLen > *inOutLen) {
		return DR_BufOverflow;
	}
	
	if(length < 0x80) {
		/* short form */
		*buf = (DERByte)length;
		*inOutLen = 1;
		return DR_Success;
	}
	
	/* long form */
	*buf = (outLen - 1) | 0x80;		// length of length, long form indicator
	lenBytes = buf + outLen - 1;	// l.s. digit of length 
	while(length != 0) {
		*lenBytes-- = (DERByte)length;
		length >>= 8;
	}
	*inOutLen = outLen;
	return DR_Success;
}

DERSize DERLengthOfItem(
	DERTag tag,
	DERSize length)
{
    return DERLengthOfTag(tag) + DERLengthOfLength(length) + length;
}

DERReturn DEREncodeItem(
	DERTag tag,
	DERSize length,
    const DERByte *src,
	DERByte *derOut,	/* encoded item goes here */
	DERSize *inOutLen)	/* IN/OUT */
{
	DERReturn		drtn;
	DERSize			itemLen;
	DERByte			*currPtr = derOut;
	DERSize         bytesLeft = DERLengthOfItem(tag, length);
	if(bytesLeft > *inOutLen) {
		return DR_BufOverflow;
	}
	*inOutLen = bytesLeft;

	/* top level tag */
	itemLen = bytesLeft;
	drtn = DEREncodeTag(tag, currPtr, &itemLen);
	if(drtn) {
		return drtn;
	}
	currPtr += itemLen;
	bytesLeft -= itemLen;
	itemLen = bytesLeft;
	drtn = DEREncodeLength(length, currPtr, &itemLen);
	if(drtn) {
		return drtn;
	}
	currPtr += itemLen;
	bytesLeft -= itemLen;
	DERMemmove(currPtr, src, length);

	return DR_Success;
}

static /* calculate the content length of an encoded sequence */
DERSize DERContentLengthOfEncodedSequence(
	const void			*src,		/* generally a ptr to a struct full of 
									 *    DERItems */
	DERShort			numItems,	/* size of itemSpecs[] */
	const DERItemSpec	*itemSpecs)
{
	DERSize contentLen = 0;
	unsigned dex;
	DERSize thisContentLen;
	
	/* find length of each item */
	for(dex=0; dex<numItems; dex++) {
		const DERItemSpec *currItemSpec = &itemSpecs[dex];
		DERShort currOptions = currItemSpec->options;
		const DERByte *byteSrc = (const DERByte *)src + currItemSpec->offset;
		const DERItem *itemSrc = (const DERItem *)byteSrc;

		if(currOptions & DER_ENC_WRITE_DER) {
			/* easy case - no encode */
			contentLen += itemSrc->length;
			continue;
		}
		
        if ((currOptions & DER_DEC_OPTIONAL) && itemSrc->length == 0) {
            /* If an optional item isn't present we don't encode a
               tag and len. */
            continue;
        }

		/* 
		 * length of this item = 
		 *   tag (one byte) +
		 *   length of length +
		 *   content length +
		 *   optional zero byte for signed integer
		 */
		contentLen += DERLengthOfTag(currItemSpec->tag);

		/* check need for pad byte before calculating lengthOfLength... */
		thisContentLen = itemSrc->length;
		if((currOptions & DER_ENC_SIGNED_INT) &&
		   (itemSrc->length != 0)) {
			if(itemSrc->data[0] & 0x80) {
				/* insert zero keep it positive */
				thisContentLen++;
			}
		}
		contentLen += DERLengthOfLength(thisContentLen);
		contentLen += thisContentLen;
	}
	return contentLen;
}

DERReturn DEREncodeSequence(
	DERTag				topTag,		/* ASN1_CONSTR_SEQUENCE, ASN1_CONSTR_SET */
	const void			*src,		/* generally a ptr to a struct full of 
									 *    DERItems */
	DERShort			numItems,	/* size of itemSpecs[] */
	const DERItemSpec	*itemSpecs,
	DERByte				*derOut,	/* encoded data written here */
	DERSize				*inOutLen)	/* IN/OUT */
{
	const DERByte	*endPtr = derOut + *inOutLen;
	DERByte			*currPtr = derOut;
	DERSize			bytesLeft = *inOutLen;
	DERSize			contentLen;
	DERReturn		drtn;
	DERSize			itemLen;
	unsigned		dex;
	
	/* top level tag */
	itemLen = bytesLeft;
    drtn = DEREncodeTag(topTag, currPtr, &itemLen);
	if(drtn) {
		return drtn;
	}
	currPtr += itemLen;
	bytesLeft -= itemLen;
	if(currPtr >= endPtr) {	
		return DR_BufOverflow;
	}
	
	/* content length */
	contentLen = DERContentLengthOfEncodedSequence(src, numItems, itemSpecs);	
	itemLen = bytesLeft;
	drtn = DEREncodeLength(contentLen, currPtr, &itemLen);
	if(drtn) {
		return drtn;
	}
	currPtr += itemLen;
	bytesLeft -= itemLen;
	if(currPtr + contentLen > endPtr) {
		return DR_BufOverflow;
	}
	/* we don't have to check for overflow any more */
	
	/* grind thru the items */
	for(dex=0; dex<numItems; dex++) {
		const DERItemSpec *currItemSpec = &itemSpecs[dex];
		DERShort currOptions = currItemSpec->options;
		const DERByte *byteSrc = (const DERByte *)src + currItemSpec->offset;
		const DERItem *itemSrc = (const DERItem *)byteSrc;
		int prependZero = 0;
		
		if(currOptions & DER_ENC_WRITE_DER) {
			/* easy case */
			DERMemmove(currPtr, itemSrc->data, itemSrc->length);
			currPtr += itemSrc->length;
			bytesLeft -= itemSrc->length;
			continue;
		}

        if ((currOptions & DER_DEC_OPTIONAL) && itemSrc->length == 0) {
            /* If an optional item isn't present we skip it. */
            continue;
        }

        /* encode one item: first the tag */
        itemLen = bytesLeft;
        drtn = DEREncodeTag(currItemSpec->tag, currPtr, &itemLen);
        if(drtn) {
            return drtn;
        }
        currPtr += itemLen;
        bytesLeft -= itemLen;

		/* do we need to prepend a zero to content? */
		contentLen = itemSrc->length;
		if((currOptions & DER_ENC_SIGNED_INT) &&
		   (itemSrc->length != 0)) {
			if(itemSrc->data[0] & 0x80) {
				/* insert zero keep it positive */
				contentLen++;
				prependZero = 1;
			}
		}

		/* encode content length */
		itemLen = bytesLeft;
		drtn = DEREncodeLength(contentLen, currPtr, &itemLen);
		if(drtn) {
			return drtn;
		}
		currPtr += itemLen;
		bytesLeft -= itemLen;
		
		/* now the content, with possible leading zero added */
		if(prependZero) {
			*currPtr++ = 0;
			bytesLeft--;
		}
		DERMemmove(currPtr, itemSrc->data, itemSrc->length);
		currPtr += itemSrc->length;
		bytesLeft -= itemSrc->length;
	}
	*inOutLen = (currPtr - derOut);
	return DR_Success;
}

/* calculate the length of an encoded sequence. */
DERSize DERLengthOfEncodedSequence(
    DERTag				topTag,
	const void			*src,		/* generally a ptr to a struct full of 
									 *    DERItems */
	DERShort			numItems,	/* size of itemSpecs[] */
	const DERItemSpec	*itemSpecs)
{
	DERSize contentLen = DERContentLengthOfEncodedSequence(
		src, numItems, itemSpecs);

	return DERLengthOfTag(topTag) +
        DERLengthOfLength(contentLen) +
		contentLen;
}

#endif	/* DER_ENCODE_ENABLE */

Added Source/libDER/libDER/DER_Encode.h.















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/* Copyright (c) 2005-2007 Apple Inc. All Rights Reserved. */

/*
 * DER_Encode.h - DER encoding routines
 *
 * Created Dec. 2 2005 by dmitch
 */
 
#ifndef	_DER_ENCCODE_H_
#define _DER_ENCODE_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "libDER.h"

/* 
 * Max size of an encoded item given its length. 
 * This includes a possible leading zero prepended to a signed integer
 * (see DER_ENC_SIGNED_INT below).
 */
#define DER_MAX_ENCODED_SIZE(len)					\
	( 1 +			/* tag */						\
	  5 +			/* max length */				\
	  1 +			/* possible prepended zero */	\
	  len)
	
/* calculate size of encoded length */
DERSize DERLengthOfLength(
	DERSize length);

/* encode length */
DERReturn DEREncodeLength(
	DERSize length,
	DERByte *buf,		/* encoded length goes here */
	DERSize *inOutLen);	/* IN/OUT */

/* calculate size of encoded length */
DERSize DERLengthOfItem(
	DERTag tag,
	DERSize length);

/* encode item */
DERReturn DEREncodeItem(
	DERTag tag,
	DERSize length,
    const DERByte *src,
	DERByte *derOut,	/* encoded item goes here */
	DERSize *inOutLen);	/* IN/OUT */

/* 
 * Per-item encode options.
 */
 
/* explicit default, no options */
#define DER_ENC_NO_OPTS			0x0000

/* signed integer check: if incoming m.s. bit is 1, prepend a zero */
#define DER_ENC_SIGNED_INT		0x0100

/* DERItem contains fully encoded item - copy, don't encode */
#define DER_ENC_WRITE_DER		0x0200


/*
 * High-level sequence or set encode support.
 *
 * The outgoing sequence is expressed as an array of DERItemSpecs, each
 * of which corresponds to one item in the encoded sequence. 
 *
 * Normally the tag of the encoded item comes from the associated 
 * DERItemSpec, and the content comes from the DERItem whose address is 
 * the src arg plus the offset value in the associated DERItemSpec.
 *
 * If the DER_ENC_WRITE_DER option is true for a given DERItemSpec then 
 * no per-item encoding is done; the DER - with tag, length, and content -
 * is taken en masse from the associated DERItem. 
 */
DERReturn DEREncodeSequence(
	DERTag				topTag,		/* ASN1_CONSTR_SEQUENCE, ASN1_CONSTR_SET */
	const void			*src,		/* generally a ptr to a struct full of 
									 *    DERItems */
	DERShort			numItems,	/* size of itemSpecs[] */
	const DERItemSpec	*itemSpecs,
	DERByte				*derOut,	/* encoded data written here */
	DERSize				*inOutLen);	/* IN/OUT */

/* precalculate the length of an encoded sequence. */
DERSize DERLengthOfEncodedSequence(
	DERTag				topTag,		/* ASN1_CONSTR_SEQUENCE, ASN1_CONSTR_SET */
	const void			*src,		/* generally a ptr to a struct full of 
									 *    DERItems */
	DERShort			numItems,	/* size of itemSpecs[] */
	const DERItemSpec	*itemSpecs);


#ifdef __cplusplus
}
#endif

#endif	/* _DER_DECODE_H_ */

Added Source/libDER/libDER/DER_Keys.c.















































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/* Copyright (c) 2005-2007 Apple Inc.  All Rights Reserved. */

/*
 * DER_Cert.c - support for decoding RSA keys
 *
 * Created Nov. 8 2005 by Doug Mitchell.
 */
 
#include "DER_Decode.h"
#include "DER_Encode.h"
#include "DER_Keys.h"
#include "asn1Types.h"
#include "libDER_config.h"

#ifndef	DER_DECODE_ENABLE
#error Please define DER_DECODE_ENABLE.
#endif
#if		DER_DECODE_ENABLE

/* 
 * DERItemSpecs for decoding RSA keys. 
 */
 
/* Algorithm Identifier */
const DERItemSpec DERAlgorithmIdItemSpecs[] = 
{
	{ DER_OFFSET(DERAlgorithmId, oid),
			ASN1_OBJECT_ID,
			DER_DEC_NO_OPTS },
	{ DER_OFFSET(DERAlgorithmId, params),
			0,				/* no tag - any */
			DER_DEC_ASN_ANY | DER_DEC_OPTIONAL | DER_DEC_SAVE_DER }
};
const DERSize DERNumAlgorithmIdItemSpecs = 
	sizeof(DERAlgorithmIdItemSpecs) / sizeof(DERItemSpec);

/* X509 SubjectPublicKeyInfo */
const DERItemSpec DERSubjPubKeyInfoItemSpecs[] = 
{
	{ DER_OFFSET(DERSubjPubKeyInfo, algId),
			ASN1_CONSTR_SEQUENCE,	
			DER_DEC_NO_OPTS },		
	{ DER_OFFSET(DERSubjPubKeyInfo, pubKey),
			ASN1_BIT_STRING,	
			DER_DEC_NO_OPTS },		

};
const DERSize DERNumSubjPubKeyInfoItemSpecs = 
	sizeof(DERSubjPubKeyInfoItemSpecs) / sizeof(DERItemSpec);

/* 
 * RSA private key in CRT format
 */
const DERItemSpec DERRSAPrivKeyCRTItemSpecs[] = 
{
	/* version, n, e, d - skip */
	{ 0,
			ASN1_INTEGER,
			DER_DEC_SKIP },
	{ 0,
			ASN1_INTEGER,
			DER_DEC_SKIP },
	{ 0,
			ASN1_INTEGER,
			DER_DEC_SKIP },
	{ 0,
			ASN1_INTEGER,
			DER_DEC_SKIP },
	{ DER_OFFSET(DERRSAPrivKeyCRT, p),
			ASN1_INTEGER,	
			DER_DEC_NO_OPTS },		
	{ DER_OFFSET(DERRSAPrivKeyCRT, q),
			ASN1_INTEGER,	
			DER_DEC_NO_OPTS },		
	{ DER_OFFSET(DERRSAPrivKeyCRT, dp),
			ASN1_INTEGER,	
			DER_DEC_NO_OPTS },		
	{ DER_OFFSET(DERRSAPrivKeyCRT, dq),
			ASN1_INTEGER,	
			DER_DEC_NO_OPTS },		
	{ DER_OFFSET(DERRSAPrivKeyCRT, qInv),
			ASN1_INTEGER,	
			DER_DEC_NO_OPTS },		
	/* ignore the (optional) rest */
};
const DERSize DERNumRSAPrivKeyCRTItemSpecs = 
	sizeof(DERRSAPrivKeyCRTItemSpecs) / sizeof(DERItemSpec);

#endif	/* DER_DECODE_ENABLE */

#if		DER_DECODE_ENABLE || DER_ENCODE_ENABLE

/* RSA public key in PKCS1 format - encode and decode */
const DERItemSpec DERRSAPubKeyPKCS1ItemSpecs[] = 
{
	{ DER_OFFSET(DERRSAPubKeyPKCS1, modulus),
			ASN1_INTEGER,	
			DER_DEC_NO_OPTS | DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAPubKeyPKCS1, pubExponent),
			ASN1_INTEGER,	
			DER_DEC_NO_OPTS | DER_ENC_SIGNED_INT },		
};
const DERSize DERNumRSAPubKeyPKCS1ItemSpecs = 
	sizeof(DERRSAPubKeyPKCS1ItemSpecs) / sizeof(DERItemSpec);

/* RSA public key in Apple custome format with reciprocal - encode and decode */
const DERItemSpec DERRSAPubKeyAppleItemSpecs[] = 
{
	{ DER_OFFSET(DERRSAPubKeyApple, modulus),
			ASN1_INTEGER,	
			DER_DEC_NO_OPTS | DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAPubKeyApple, reciprocal),
			ASN1_INTEGER,	
			DER_DEC_NO_OPTS | DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAPubKeyApple, pubExponent),
			ASN1_INTEGER,	
			DER_DEC_NO_OPTS | DER_ENC_SIGNED_INT },		
};
const DERSize DERNumRSAPubKeyAppleItemSpecs = 
	sizeof(DERRSAPubKeyAppleItemSpecs) / sizeof(DERItemSpec);


#endif		/* DER_DECODE_ENABLE || DER_ENCODE_ENABLE */

#ifndef	DER_ENCODE_ENABLE
#error Please define DER_ENCODE_ENABLE.
#endif

#if		DER_ENCODE_ENABLE

/* RSA Key Pair, encode only */
const DERItemSpec DERRSAKeyPairItemSpecs[] = 
{
	{ DER_OFFSET(DERRSAKeyPair, version),
			ASN1_INTEGER,	
			DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAKeyPair, n),
			ASN1_INTEGER,	
			DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAKeyPair, e),
			ASN1_INTEGER,	
			DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAKeyPair, d),
			ASN1_INTEGER,	
			DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAKeyPair, p),
			ASN1_INTEGER,	
			DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAKeyPair, q),
			ASN1_INTEGER,	
			DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAKeyPair, dp),
			ASN1_INTEGER,	
			DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAKeyPair, dq),
			ASN1_INTEGER,	
			DER_ENC_SIGNED_INT },		
	{ DER_OFFSET(DERRSAKeyPair, qInv),
			ASN1_INTEGER,	
			DER_ENC_SIGNED_INT },		
};

const DERSize DERNumRSAKeyPairItemSpecs = 
	sizeof(DERRSAKeyPairItemSpecs) / sizeof(DERItemSpec);

#endif	/* DER_ENCODE_ENABLE */

Added Source/libDER/libDER/DER_Keys.h.

















































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* Copyright (c) 2005-2007 Apple Inc. All Rights Reserved. */

/*
 * DER_Keys.h - support for decoding RSA keys
 *
 * Created Nov. 8 2005 by dmitch
 */
 
#ifndef	_DER_KEYS_H_
#define _DER_KEYS_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "libDER.h"
#include "DER_Decode.h"

/* Algorithm Identifier components */
typedef struct {
	DERItem		oid;			/* OID */
	DERItem		params;			/* ASN_ANY, optional, DER_DEC_SAVE_DER */
} DERAlgorithmId;

/* DERItemSpecs to decode into a DERAlgorithmId */
extern const DERItemSpec DERAlgorithmIdItemSpecs[];
extern const DERSize DERNumAlgorithmIdItemSpecs;

/* X509 SubjectPublicKeyInfo */
typedef struct {
	DERItem		algId;			/* sequence, DERAlgorithmId */
	DERItem		pubKey;			/* BIT STRING */
} DERSubjPubKeyInfo;

/* DERItemSpecs to decode into a DERSubjPubKeyInfo */
extern const DERItemSpec DERSubjPubKeyInfoItemSpecs[];
extern const DERSize DERNumSubjPubKeyInfoItemSpecs;

/* 
 * RSA public key in PKCS1 format; this is inside the BIT_STRING in 
 * DERSubjPubKeyInfo.pubKey.
 */
typedef struct {
	DERItem		modulus;		/* n - INTEGER */
	DERItem		pubExponent;	/* e - INTEGER */
} DERRSAPubKeyPKCS1;

/* DERItemSpecs to decode/encode into/from a DERRSAPubKeyPKCS1 */
extern const DERItemSpec DERRSAPubKeyPKCS1ItemSpecs[];
extern const DERSize DERNumRSAPubKeyPKCS1ItemSpecs;

/* 
 * RSA public key in custom (to this library) format, including
 * the reciprocal. All fields are integers. 
 */
typedef struct {
	DERItem		modulus;		/* n */
	DERItem		reciprocal;		/* reciprocal of modulus */
	DERItem		pubExponent;	/* e */
} DERRSAPubKeyApple;

/* DERItemSpecs to decode/encode into/from a DERRSAPubKeyApple */
extern const DERItemSpec DERRSAPubKeyAppleItemSpecs[];
extern const DERSize DERNumRSAPubKeyAppleItemSpecs;

/* 
 * RSA Private key, PKCS1 format, CRT option.
 * All fields are integers. 
 */
typedef struct {
	DERItem		p;				/* p * q = n */
	DERItem		q;
	DERItem		dp;				/* d mod (p-1) */
	DERItem		dq;				/* d mod (q-1) */
	DERItem		qInv;		
} DERRSAPrivKeyCRT;

/* DERItemSpecs to decode into a DERRSAPrivKeyCRT */
extern const DERItemSpec DERRSAPrivKeyCRTItemSpecs[];
extern const DERSize DERNumRSAPrivKeyCRTItemSpecs;

/* Fully formed RSA key pair, for generating a PKCS1 private key */
typedef struct {
	DERItem		version;	
	DERItem		n;		/* modulus */
	DERItem		e;		/* public exponent */
	DERItem		d;		/* private exponent */
	DERItem		p;		/* n = p*q */
	DERItem		q;
	DERItem		dp;		/* d mod (p-1) */
	DERItem		dq;		/* d mod (q-1) */
	DERItem		qInv;	/* q^(-1) mod p */
} DERRSAKeyPair;

/* DERItemSpecs to encode a DERRSAKeyPair */
extern const DERItemSpec DERRSAKeyPairItemSpecs[];
extern const DERSize DERNumRSAKeyPairItemSpecs;

#ifdef __cplusplus
}
#endif

#endif	/* _DER_KEYS_H_ */

Added Source/libDER/libDER/asn1Types.h.























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/* Copyright (c) 2005-2007 Apple Inc. All Rights Reserved. */

/*
 * asn1Types.h - ASN.1/DER #defines - strictly hard coded per the real world
 *
 * Created Nov. 4 2005 by dmitch
 */
 
#ifndef	_ASN1_TYPES_H_
#define _ASN1_TYPES_H_

#ifdef __cplusplus
extern "C" {
#endif

/* copied from libsecurity_asn1 project */

#define ASN1_BOOLEAN			0x01
#define ASN1_INTEGER			0x02
#define ASN1_BIT_STRING			0x03
#define ASN1_OCTET_STRING		0x04
#define ASN1_NULL				0x05
#define ASN1_OBJECT_ID			0x06
#define ASN1_OBJECT_DESCRIPTOR  0x07
/* External type and instance-of type   0x08 */
#define ASN1_REAL               0x09
#define ASN1_ENUMERATED			0x0a
#define ASN1_EMBEDDED_PDV       0x0b
#define ASN1_UTF8_STRING		0x0c
/*                                  0x0d */
/*                                  0x0e */
/*                                  0x0f */
#define ASN1_SEQUENCE			0x10
#define ASN1_SET				0x11
#define ASN1_NUMERIC_STRING		0x12
#define ASN1_PRINTABLE_STRING	0x13
#define ASN1_T61_STRING			0x14
#define ASN1_VIDEOTEX_STRING	0x15
#define ASN1_IA5_STRING			0x16
#define ASN1_UTC_TIME			0x17
#define ASN1_GENERALIZED_TIME	0x18
#define ASN1_GRAPHIC_STRING		0x19
#define ASN1_VISIBLE_STRING		0x1a
#define ASN1_GENERAL_STRING		0x1b
#define ASN1_UNIVERSAL_STRING	0x1c
/*                                  0x1d */
#define ASN1_BMP_STRING			0x1e
#define ASN1_HIGH_TAG_NUMBER	0x1f
#define ASN1_TELETEX_STRING ASN1_T61_STRING

#ifdef DER_MULTIBYTE_TAGS

#define ASN1_TAG_MASK			((DERTag)~0)
#define ASN1_TAGNUM_MASK        ((DERTag)~((DERTag)7 << (sizeof(DERTag) * 8 - 3)))

#define ASN1_METHOD_MASK		((DERTag)1 << (sizeof(DERTag) * 8 - 3))
#define ASN1_PRIMITIVE			((DERTag)0 << (sizeof(DERTag) * 8 - 3))
#define ASN1_CONSTRUCTED		((DERTag)1 << (sizeof(DERTag) * 8 - 3))

#define ASN1_CLASS_MASK			((DERTag)3 << (sizeof(DERTag) * 8 - 2))
#define ASN1_UNIVERSAL			((DERTag)0 << (sizeof(DERTag) * 8 - 2))
#define ASN1_APPLICATION		((DERTag)1 << (sizeof(DERTag) * 8 - 2))
#define ASN1_CONTEXT_SPECIFIC	((DERTag)2 << (sizeof(DERTag) * 8 - 2))
#define ASN1_PRIVATE			((DERTag)3 << (sizeof(DERTag) * 8 - 2))

#else /* DER_MULTIBYTE_TAGS */

#define ASN1_TAG_MASK			0xff
#define ASN1_TAGNUM_MASK		0x1f
#define ASN1_METHOD_MASK		0x20
#define ASN1_PRIMITIVE			0x00
#define ASN1_CONSTRUCTED		0x20

#define ASN1_CLASS_MASK			0xc0
#define ASN1_UNIVERSAL			0x00
#define ASN1_APPLICATION		0x40
#define ASN1_CONTEXT_SPECIFIC	0x80
#define ASN1_PRIVATE			0xc0

#endif /* !DER_MULTIBYTE_TAGS */

/* sequence and set appear as the following */
#define ASN1_CONSTR_SEQUENCE	(ASN1_CONSTRUCTED | ASN1_SEQUENCE)
#define ASN1_CONSTR_SET			(ASN1_CONSTRUCTED | ASN1_SET)

#ifdef __cplusplus
}
#endif

#endif	/* _ASN1_TYPES_H_ */

Added Source/libDER/libDER/libDER.h.



































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* Copyright (c) 2005-2007 Apple Inc. All Rights Reserved. */

/*
 * libDER.h - main header for libDER, a ROM-capable DER decoding library. 
 *
 * Created Nov. 4 2005 by dmitch
 */
 
#ifndef	_LIB_DER_H_
#define _LIB_DER_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "libDER_config.h"
/*
 * Error returns generated by this library.
 */
typedef enum {
	DR_Success,
	DR_EndOfSequence,	/* end of sequence or set */
	DR_UnexpectedTag,	/* unexpected tag found while decoding */
	DR_DecodeError,		/* misc. decoding error (badly formatted DER) */
	DR_Unimplemented,	/* function not implemented in this configuration */
	DR_IncompleteSeq,	/* incomplete sequence */
	DR_ParamErr,		/* incoming parameter error */
	DR_BufOverflow		/* buffer overflow */
	/* etc. */
} DERReturn;

/* 
 * Primary representation of a block of memory.
 */
typedef struct {
	DERByte		*data;
	DERSize		length;
} DERItem;

/*
 * The structure of a sequence during decode or encode is expressed as 
 * an array of DERItemSpecs. While decoding or encoding a sequence, 
 * each item in the sequence corresponds to one DERItemSpec.
 */
typedef struct {
	DERSize			offset;			/* offset of destination DERItem */
	DERTag			tag;			/* DER tag */
	DERShort		options;		/* DER_DEC_xxx or DER_ENC_xxx */
} DERItemSpec;

/*
 * Macro to obtain offset of a DERDecodedInfo within a struct.
 * FIXME this is going to need reworking to avoid compiler warnings
 * on 64-bit compiles. It'll work OK as long as an offset can't be larger
 * than a DERSize, but the cast from a pointer to a DERSize may 
 * provoke compiler warnings. 
 */
#define DER_OFFSET(type, field) ((DERSize)(&((type *)0)->field))

#ifdef __cplusplus
}
#endif

#endif	/* _LIB_DER_H_ */

Added Source/libDER/libDER/libDER_config.h.

























































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* Copyright (c) 2005-2007 Apple Inc. All Rights Reserved. */

/*
 * libDER_config.h - platform dependent #defines and typedefs for libDER
 *
 * Created Nov. 4 2005 by dmitch
 */
 
#ifndef	_LIB_DER_CONFIG_H_
#define _LIB_DER_CONFIG_H_

#include <stdint.h>
#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Basic data types: unsigned 8-bit integer, unsigned 32-bit integer
 */
typedef uint8_t DERByte;
typedef uint16_t DERShort;
typedef size_t DERSize;

/* 
 * Use these #defines of you have memset, memmove, and memcmp; else
 * write your own equivalents.
 */

#define DERMemset(ptr, c, len)		memset(ptr, c, len)
#define DERMemmove(dst, src, len)	memmove(dst, src, len)
#define DERMemcmp(b1, b2, len)		memcmp(b1, b2, len)


/***
 *** Compile time options to trim size of the library. 
 ***/
 
/* enable general DER encode */
#define DER_ENCODE_ENABLE		1

/* enable general DER decode */
#define DER_DECODE_ENABLE		1

#ifndef DER_MULTIBYTE_TAGS
/* enable multibyte tag support. */
#define DER_MULTIBYTE_TAGS		1
#endif

#ifndef DER_TAG_SIZE
/* Iff DER_MULTIBYTE_TAGS is 1 this is the sizeof(DERTag) in bytes. Note that
   tags are still encoded and decoded from a minimally encoded DER
   represantation.  This value determines how big each DERItemSpecs is, we
   choose 2 since that makes DERItemSpecs 8 bytes wide.  */
#define DER_TAG_SIZE            2
#endif


/* ---------------------- Do not edit below this line ---------------------- */

/*
 * Logical representation of a tag (the encoded representation is always in
 * the minimal number of bytes). The top 3 bits encode class and method
 * The remaining bits encode the tag value.  To obtain smaller DERItemSpecs
 * sizes, choose the smallest type that fits your needs.  Most standard ASN.1
 * usage only needs single byte tags, but ocasionally custom applications
 * require a larger tag namespace.
 */
#if DER_MULTIBYTE_TAGS

#if DER_TAG_SIZE == 1
typedef uint8_t DERTag;
#elif DER_TAG_SIZE == 2
typedef uint16_t DERTag;
#elif DER_TAG_SIZE == 4
typedef uint32_t DERTag;
#elif DER_TAG_SIZE == 8
typedef uint64_t DERTag;
#else
#error DER_TAG_SIZE invalid
#endif

#else /* DER_MULTIBYTE_TAGS */
typedef DERByte DERTag;
#endif /* !DER_MULTIBYTE_TAGS */

#ifdef __cplusplus
}
#endif

#endif	/* _LIB_DER_CONFIG_H_ */

Added Source/libDER/libDER/oids.c.





































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/* Copyright (c) 2005-2009 Apple Inc. All Rights Reserved. */

/*
 * oids.c - OID consts 
 *
 * Created Nov. 11 2005 by dmitch
 */

#include "libDER.h"
#include "oids.h"

#define OID_ISO_CCITT_DIR_SERVICE 			85
#define OID_DS              				OID_ISO_CCITT_DIR_SERVICE 
#define OID_ATTR_TYPE        				OID_DS, 4                
#define OID_EXTENSION        				OID_DS, 29          
#define OID_ISO_STANDARD      	 			40
#define OID_ISO_MEMBER         				42                     
#define OID_US                 				OID_ISO_MEMBER, 134, 72

#define OID_ISO_IDENTIFIED_ORG 				43
#define OID_OSINET             				OID_ISO_IDENTIFIED_ORG, 4
#define OID_GOSIP              				OID_ISO_IDENTIFIED_ORG, 5
#define OID_DOD                				OID_ISO_IDENTIFIED_ORG, 6
#define OID_OIW                				OID_ISO_IDENTIFIED_ORG, 14 

/* From the PKCS Standards */
#define OID_RSA               				OID_US, 134, 247, 13
#define OID_RSA_HASH          				OID_RSA, 2
#define OID_RSA_ENCRYPT       				OID_RSA, 3
#define OID_PKCS             				OID_RSA, 1
#define OID_PKCS_1          				OID_PKCS, 1
#define OID_PKCS_2          				OID_PKCS, 2
#define OID_PKCS_3          				OID_PKCS, 3
#define OID_PKCS_4          				OID_PKCS, 4
#define OID_PKCS_5          				OID_PKCS, 5
#define OID_PKCS_6          				OID_PKCS, 6
#define OID_PKCS_7          				OID_PKCS, 7
#define OID_PKCS_8          				OID_PKCS, 8
#define OID_PKCS_9          				OID_PKCS, 9
#define OID_PKCS_10         				OID_PKCS, 10
#define OID_PKCS_11          				OID_PKCS, 11
#define OID_PKCS_12          				OID_PKCS, 12

/* ANSI X9.62 */
#define OID_ANSI_X9_62						OID_US, 206, 61
#define OID_PUBLIC_KEY_TYPE					OID_ANSI_X9_62, 2
#define OID_EC_SIG_TYPE                     OID_ANSI_X9_62, 4
#define OID_ECDSA_WITH_SHA2                 OID_EC_SIG_TYPE, 3

/* ANSI X9.42 */
#define OID_ANSI_X9_42						OID_US, 206, 62, 2
#define OID_ANSI_X9_42_SCHEME				OID_ANSI_X9_42, 3
#define OID_ANSI_X9_42_NAMED_SCHEME			OID_ANSI_X9_42, 4

/* DOD IANA Security releated objects. */
#define OID_IANA                            OID_DOD, 1, 5

/* Kerberos PKINIT */
#define OID_KERBv5							OID_IANA, 2
#define OID_KERBv5_PKINIT					OID_KERBv5, 3

/* DOD IANA Mechanisms. */
#define OID_MECHANISMS						OID_IANA, 5

/* PKIX */
#define OID_PKIX							OID_MECHANISMS, 7
#define OID_PE								OID_PKIX, 1
#define OID_QT								OID_PKIX, 2
#define OID_KP								OID_PKIX, 3
#define OID_OTHER_NAME						OID_PKIX, 8
#define OID_PDA								OID_PKIX, 9
#define OID_QCS								OID_PKIX, 11
#define OID_AD								OID_PKIX, 48
#define OID_AD_OCSP							OID_AD, 1
#define OID_AD_CAISSUERS                    OID_AD, 2

/* ISAKMP */
#define OID_ISAKMP							OID_MECHANISMS, 8

/* ETSI */
#define OID_ETSI							0x04, 0x00
#define OID_ETSI_QCS						0x04, 0x00, 0x8E, 0x46, 0x01
	
#define OID_OIW_SECSIG        				OID_OIW, 3

#define OID_OIW_ALGORITHM    				OID_OIW_SECSIG, 2

/* NIST defined digest algorithm arc (2, 16, 840, 1, 101, 3, 4, 2) */
#define OID_NIST_HASHALG					0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02

/*
 * Apple-specific OID bases
 */
 
/* 
 * apple OBJECT IDENTIFIER ::=
 * 	{ iso(1) member-body(2) US(840) 113635 }
 * 
 * BER = 06 06 2A 86 48 86 F7 63
 */
#define APPLE_OID				OID_US, 0x86, 0xf7, 0x63

/* appleDataSecurity OBJECT IDENTIFIER ::=
 *		{ apple 100 }
 *      { 1 2 840 113635 100 }
 *
 * BER = 06 07 2A 86 48 86 F7 63 64
 */
#define APPLE_ADS_OID			APPLE_OID, 0x64

/*
 * appleTrustPolicy OBJECT IDENTIFIER ::=
 *		{ appleDataSecurity 1 }
 *      { 1 2 840 113635 100 1 }
 *
 * BER = 06 08 2A 86 48 86 F7 63 64 01 
 */ 
#define APPLE_TP_OID			APPLE_ADS_OID, 1

/*
 *	appleSecurityAlgorithm OBJECT IDENTIFIER ::=
 *		{ appleDataSecurity 2 }
 *      { 1 2 840 113635 100 2 }
 *
 * BER = 06 08 2A 86 48 86 F7 63 64 02
 */
#define APPLE_ALG_OID			APPLE_ADS_OID, 2

/*
 * appleDotMacCertificate OBJECT IDENTIFIER ::= 
 *		{ appleDataSecurity 3 }
 *      { 1 2 840 113635 100 3 }
 */
#define APPLE_DOTMAC_CERT_OID			APPLE_ADS_OID, 3

/*
 * Basis of Policy OIDs for .mac TP requests
 *
 * dotMacCertificateRequest OBJECT IDENTIFIER ::= 
 *		{ appleDotMacCertificate 1 }
 *      { 1 2 840 113635 100 3 1 }
 */
#define APPLE_DOTMAC_CERT_REQ_OID			APPLE_DOTMAC_CERT_OID, 1

/*
 * Basis of .mac Certificate Extensions
 *
 * dotMacCertificateExtension OBJECT IDENTIFIER ::= 
 *		{ appleDotMacCertificate 2 }
 *      { 1 2 840 113635 100 3 2 }
 */
#define APPLE_DOTMAC_CERT_EXTEN_OID			APPLE_DOTMAC_CERT_OID, 2

/*
 * Basis of .mac Certificate request OID/value identitifiers
 *
 * dotMacCertificateRequestValues OBJECT IDENTIFIER ::= 
 *		{ appleDotMacCertificate 3 }
 *      { 1 2 840 113635 100 3 3 }
 */
#define APPLE_DOTMAC_CERT_REQ_VALUE_OID			APPLE_DOTMAC_CERT_OID, 3

/*
 * Basis of Apple-specific extended key usages
 *
 * appleExtendedKeyUsage OBJECT IDENTIFIER ::= 
 *		{ appleDataSecurity 4 }
 *      { 1 2 840 113635 100 4 }
 */
#define APPLE_EKU_OID					APPLE_ADS_OID, 4

/* 
 * Basis of Apple Code Signing extended key usages
 * appleCodeSigning  OBJECT IDENTIFIER ::= 
 *		{ appleExtendedKeyUsage 1 }
 *      { 1 2 840 113635 100 4 1}
 */
#define APPLE_EKU_CODE_SIGNING			APPLE_EKU_OID, 1
#define APPLE_EKU_APPLE_ID              APPLE_EKU_OID, 7

/*
 * Basis of Apple-specific Certific Policy IDs.
 * appleCertificatePolicies OBJECT IDENTIFIER ::= 
 *		{ appleDataSecurity 5 }
 *		{ 1 2 840 113635 100 5 }
 */
#define APPLE_CERT_POLICIES				APPLE_ADS_OID, 5

/*
 * Basis of Apple-specific Signing extensions
 *		{ appleDataSecurity 6 }
 */
#define APPLE_CERT_EXT    APPLE_ADS_OID, 6
/* Apple Intermediate Marker OIDs */
#define APPLE_CERT_EXT_INTERMEDIATE_MARKER APPLE_CERT_EXT, 2
/* Apple Apple ID Intermediate Marker */
#define APPLE_CERT_EXT_INTERMEDIATE_MARKER_APPLEID APPLE_CERT_EXT_INTERMEDIATE_MARKER, 3

/* Secure Boot Embedded Image3 value,
   co-opted by desktop for "Apple Released Code Signature", without value */
#define APPLE_SBOOT_CERT_EXTEN_SBOOT_SPEC_OID	APPLE_ADS_OID, 6, 1, 1
/* iPhone Provisioning Profile Signing leaf */
#define APPLE_PROVISIONING_PROFILE_OID	APPLE_ADS_OID, 6, 2, 2, 1
/* iPhone Application Signing leaf */
#define APPLE_APP_SIGINING_OID	APPLE_ADS_OID, 6, 1, 3

/*
 * Netscape OIDs.
 */
#define NETSCAPE_BASE_OID           0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42

/*
 * Netscape cert extension.
 *
 *  netscape-cert-extension OBJECT IDENTIFIER ::=
 * 		{ 2 16 840 1 113730 1 }
 *
 *	BER = 06 08 60 86 48 01 86 F8 42 01
 */
#define NETSCAPE_CERT_EXTEN			NETSCAPE_BASE_OID, 0x01

#define NETSCAPE_CERT_POLICY		NETSCAPE_BASE_OID, 0x04

/* Entrust OIDs. */
#define ENTRUST_BASE_OID            OID_US, 0x86, 0xf6, 0x7d

/*
 * Entrust cert extension.
 *
 *  entrust-cert-extension OBJECT IDENTIFIER ::=
 * 		{  1 2 840 113533 7 65 }
 *
 *	BER = 06 08 2A 86 48 86 F6 7D 07 41
 */
#define ENTRUST_CERT_EXTEN			ENTRUST_BASE_OID, 0x07, 0x41

/* Microsfot OIDs. */
#define MICROSOFT_BASE_OID          OID_DOD, 0x01, 0x04, 0x01, 0x82, 0x37
#define MICROSOFT_ENROLLMENT_OID    MICROSOFT_BASE_OID, 0x14

/* Algorithm OIDs. */
static const DERByte
    _oidRsa[]                       = { OID_PKCS_1, 1 },
    _oidMd2Rsa[]                    = { OID_PKCS_1, 2 },
    _oidMd5Rsa[]                    = { OID_PKCS_1, 4 },
    _oidSha1Rsa[]                   = { OID_PKCS_1, 5 },
    _oidSha256Rsa[]                 = { OID_PKCS_1, 11 },
    _oidEcPubKey[]                  = { OID_PUBLIC_KEY_TYPE, 1 },
    _oidSha1Ecdsa[]                 = { OID_EC_SIG_TYPE, 1 },     /* rfc3279 */
    _oidSha224Ecdsa[]               = { OID_ECDSA_WITH_SHA2, 1 }, /* rfc5758 */
    _oidSha256Ecdsa[]               = { OID_ECDSA_WITH_SHA2, 2 }, /* rfc5758 */
    _oidSha384Ecdsa[]               = { OID_ECDSA_WITH_SHA2, 3 }, /* rfc5758 */
    _oidSha512Ecdsa[]               = { OID_ECDSA_WITH_SHA2, 4 }, /* rfc5758 */
    _oidMd2[]                       = { OID_RSA_HASH, 2 },
    _oidMd4[]                       = { OID_RSA_HASH, 4 },
    _oidMd5[]                       = { OID_RSA_HASH, 5 },
    _oidSha1[]                      = { OID_OIW_ALGORITHM, 26 },
    _oidSha256[]                    = { OID_NIST_HASHALG, 1 },
    _oidSha384[]                    = { OID_NIST_HASHALG, 2 },
    _oidSha512[]                    = { OID_NIST_HASHALG, 3 },
    _oidSha224[]                    = { OID_NIST_HASHALG, 4 };

const DERItem
    oidRsa                          = { (DERByte *)_oidRsa,
                                        sizeof(_oidRsa) },
    oidMd2Rsa                       = { (DERByte *)_oidMd2Rsa,
                                        sizeof(_oidMd2Rsa) },
    oidMd5Rsa                       = { (DERByte *)_oidMd5Rsa,
                                        sizeof(_oidMd5Rsa) },
    oidSha1Rsa                      = { (DERByte *)_oidSha1Rsa,
                                        sizeof(_oidSha1Rsa) },
    oidSha256Rsa                    = { (DERByte *)_oidSha256Rsa,
                                        sizeof(_oidSha256Rsa) },
    oidEcPubKey                     = { (DERByte *)_oidEcPubKey,
                                        sizeof(_oidEcPubKey) },
    oidSha1Ecdsa                    = { (DERByte *)_oidSha1Ecdsa,
                                        sizeof(_oidSha1Ecdsa) },
    oidSha224Ecdsa                    = { (DERByte *)_oidSha224Ecdsa,
                                        sizeof(_oidSha224Ecdsa) },
    oidSha256Ecdsa                    = { (DERByte *)_oidSha256Ecdsa,
                                        sizeof(_oidSha256Ecdsa) },
    oidSha384Ecdsa                    = { (DERByte *)_oidSha384Ecdsa,
                                        sizeof(_oidSha384Ecdsa) },
    oidSha512Ecdsa                    = { (DERByte *)_oidSha512Ecdsa,
                                        sizeof(_oidSha512Ecdsa) },
    oidMd2                          = { (DERByte *)_oidMd2,
                                        sizeof(_oidMd2) },
    oidMd4                          = { (DERByte *)_oidMd4,
                                        sizeof(_oidMd4) },
    oidMd5                          = { (DERByte *)_oidMd5,
                                        sizeof(_oidMd5) },
    oidSha1                         = { (DERByte *)_oidSha1,
                                        sizeof(_oidSha1) },
    oidSha256                       = { (DERByte *)_oidSha256,
                                        sizeof(_oidSha256) },
    oidSha384                       = { (DERByte *)_oidSha384,
                                        sizeof(_oidSha384) },
    oidSha512                       = { (DERByte *)_oidSha512,
                                        sizeof(_oidSha512) },
    oidSha224                       = { (DERByte *)_oidSha224,
                                        sizeof(_oidSha224) };

/* Extension OIDs. */
static const DERByte
    _oidSubjectKeyIdentifier[]      = { OID_EXTENSION, 14 },
    _oidKeyUsage[]                  = { OID_EXTENSION, 15 },
    _oidPrivateKeyUsagePeriod[]     = { OID_EXTENSION, 16 },
    _oidSubjectAltName[]            = { OID_EXTENSION, 17 },
    _oidIssuerAltName[]             = { OID_EXTENSION, 18 },
    _oidBasicConstraints[]          = { OID_EXTENSION, 19 },
    _oidCrlDistributionPoints[]     = { OID_EXTENSION, 31 },
    _oidCertificatePolicies[]       = { OID_EXTENSION, 32 },
    _oidAnyPolicy[]                 = { OID_EXTENSION, 32, 0 },
    _oidPolicyMappings[]            = { OID_EXTENSION, 33 },
    _oidAuthorityKeyIdentifier[]    = { OID_EXTENSION, 35 },
    _oidPolicyConstraints[]         = { OID_EXTENSION, 36 },
    _oidExtendedKeyUsage[]          = { OID_EXTENSION, 37 },
    _oidAnyExtendedKeyUsage[]          = { OID_EXTENSION, 37, 0 },
    _oidInhibitAnyPolicy[]          = { OID_EXTENSION, 54 },
    _oidAuthorityInfoAccess[]       = { OID_PE, 1 },
    _oidSubjectInfoAccess[]			= { OID_PE, 11 },
    _oidAdOCSP[]                    = { OID_AD_OCSP },
    _oidAdCAIssuer[]                = { OID_AD_CAISSUERS },
    _oidNetscapeCertType[]          = { NETSCAPE_CERT_EXTEN, 1 },
    _oidEntrustVersInfo[]           = { ENTRUST_CERT_EXTEN, 0 },
    _oidMSNTPrincipalName[]         = { MICROSOFT_ENROLLMENT_OID, 2, 3 },
    /* Policy Qualifier IDs for Internet policy qualifiers. */
    _oidQtCps[]                     = { OID_QT, 1 },
    _oidQtUNotice[]                 = { OID_QT, 2 },
    /* X.501 Name IDs. */
    _oidCommonName[]                = { OID_ATTR_TYPE, 3 },
    _oidCountryName[]               = { OID_ATTR_TYPE, 6 },
    _oidLocalityName[]              = { OID_ATTR_TYPE, 7 },
    _oidStateOrProvinceName[]       = { OID_ATTR_TYPE, 8 },
    _oidOrganizationName[]          = { OID_ATTR_TYPE, 10 },
    _oidOrganizationalUnitName[]    = { OID_ATTR_TYPE, 11 },
    _oidDescription[]               = { OID_ATTR_TYPE, 13 },
    _oidEmailAddress[]              = { OID_PKCS_9, 1 },
    _oidFriendlyName[]              = { OID_PKCS_9, 20 },
    _oidLocalKeyId[]                = { OID_PKCS_9, 21 },
    _oidExtendedKeyUsageServerAuth[] = { OID_KP, 1 },
    _oidExtendedKeyUsageClientAuth[] = { OID_KP, 2 },
    _oidExtendedKeyUsageCodeSigning[] = { OID_KP, 3 },
    _oidExtendedKeyUsageEmailProtection[] = { OID_KP, 4 },
    _oidExtendedKeyUsageOCSPSigning[] = { OID_KP, 9 },
    _oidExtendedKeyUsageIPSec[]     = { OID_ISAKMP, 2, 2 },
    _oidExtendedKeyUsageMicrosoftSGC[] = { MICROSOFT_BASE_OID, 10, 3, 3 },
    _oidExtendedKeyUsageNetscapeSGC[] = { NETSCAPE_CERT_POLICY, 1 },
    _oidAppleSecureBootCertSpec[]   = { APPLE_SBOOT_CERT_EXTEN_SBOOT_SPEC_OID },
    _oidAppleProvisioningProfile[]  = {APPLE_PROVISIONING_PROFILE_OID },
    _oidAppleApplicationSigning[]   = { APPLE_APP_SIGINING_OID },
    _oidAppleExtendedKeyUsageAppleID[] = { APPLE_EKU_APPLE_ID },
    _oidAppleIntmMarkerAppleID[] = { APPLE_CERT_EXT_INTERMEDIATE_MARKER_APPLEID };

const DERItem
    oidSubjectKeyIdentifier         = { (DERByte *)_oidSubjectKeyIdentifier,
                                        sizeof(_oidSubjectKeyIdentifier) },
    oidKeyUsage                     = { (DERByte *)_oidKeyUsage,
                                        sizeof(_oidKeyUsage) },
    oidPrivateKeyUsagePeriod        = { (DERByte *)_oidPrivateKeyUsagePeriod,
                                        sizeof(_oidPrivateKeyUsagePeriod) },
    oidSubjectAltName               = { (DERByte *)_oidSubjectAltName,
                                        sizeof(_oidSubjectAltName) },
    oidIssuerAltName                = { (DERByte *)_oidIssuerAltName,
                                        sizeof(_oidIssuerAltName) },
    oidBasicConstraints             = { (DERByte *)_oidBasicConstraints,
                                        sizeof(_oidBasicConstraints) },
    oidCrlDistributionPoints        = { (DERByte *)_oidCrlDistributionPoints,
                                        sizeof(_oidCrlDistributionPoints) },
    oidCertificatePolicies          = { (DERByte *)_oidCertificatePolicies,
                                        sizeof(_oidCertificatePolicies) },
    oidAnyPolicy                    = { (DERByte *)_oidAnyPolicy,
                                        sizeof(_oidAnyPolicy) },
    oidPolicyMappings               = { (DERByte *)_oidPolicyMappings,
                                        sizeof(_oidPolicyMappings) },
    oidAuthorityKeyIdentifier       = { (DERByte *)_oidAuthorityKeyIdentifier,
                                        sizeof(_oidAuthorityKeyIdentifier) },
    oidPolicyConstraints            = { (DERByte *)_oidPolicyConstraints,
                                        sizeof(_oidPolicyConstraints) },
    oidExtendedKeyUsage             = { (DERByte *)_oidExtendedKeyUsage,
                                        sizeof(_oidExtendedKeyUsage) },
    oidAnyExtendedKeyUsage          = { (DERByte *)_oidAnyExtendedKeyUsage,
                                        sizeof(_oidAnyExtendedKeyUsage) },
    oidInhibitAnyPolicy             = { (DERByte *)_oidInhibitAnyPolicy,
                                        sizeof(_oidInhibitAnyPolicy) },
    oidAuthorityInfoAccess          = { (DERByte *)_oidAuthorityInfoAccess,
                                        sizeof(_oidAuthorityInfoAccess) },
    oidSubjectInfoAccess			= { (DERByte *)_oidSubjectInfoAccess,
                                        sizeof(_oidSubjectInfoAccess) },
    oidAdOCSP                       = { (DERByte *)_oidAdOCSP,
                                        sizeof(_oidAdOCSP) },
    oidAdCAIssuer                   = { (DERByte *)_oidAdCAIssuer,
                                        sizeof(_oidAdCAIssuer) },
    oidNetscapeCertType             = { (DERByte *)_oidNetscapeCertType,
                                        sizeof(_oidNetscapeCertType) },
    oidEntrustVersInfo              = { (DERByte *)_oidEntrustVersInfo,
                                        sizeof(_oidEntrustVersInfo) },
    oidMSNTPrincipalName              = { (DERByte *)_oidMSNTPrincipalName,
                                        sizeof(_oidMSNTPrincipalName) },
    /* Policy Qualifier IDs for Internet policy qualifiers. */
    oidQtCps                        = { (DERByte *)_oidQtCps,
                                        sizeof(_oidQtCps) },
    oidQtUNotice                    = { (DERByte *)_oidQtUNotice,
                                        sizeof(_oidQtUNotice) },
    /* X.501 Name IDs. */
    oidCommonName                   = { (DERByte *)_oidCommonName,
                                        sizeof(_oidCommonName) },
    oidCountryName                  = { (DERByte *)_oidCountryName,
                                        sizeof(_oidCountryName) },
    oidLocalityName                 = { (DERByte *)_oidLocalityName,
                                        sizeof(_oidLocalityName) },
    oidStateOrProvinceName          = { (DERByte *)_oidStateOrProvinceName,
                                        sizeof(_oidStateOrProvinceName) },
    oidOrganizationName             = { (DERByte *)_oidOrganizationName,
                                        sizeof(_oidOrganizationName) },
    oidOrganizationalUnitName       = { (DERByte *)_oidOrganizationalUnitName,
                                        sizeof(_oidOrganizationalUnitName) },
    oidDescription                  = { (DERByte *)_oidDescription,
                                        sizeof(_oidDescription) },
    oidEmailAddress                 = { (DERByte *)_oidEmailAddress,
                                        sizeof(_oidEmailAddress) },
    oidFriendlyName                 = { (DERByte *)_oidFriendlyName, 
                                        sizeof(_oidFriendlyName) },
    oidLocalKeyId                   = { (DERByte *)_oidLocalKeyId,
                                        sizeof(_oidLocalKeyId) },
    oidExtendedKeyUsageServerAuth   = { (DERByte *)_oidExtendedKeyUsageServerAuth,
                                        sizeof(_oidExtendedKeyUsageServerAuth) },
    oidExtendedKeyUsageClientAuth   = { (DERByte *)_oidExtendedKeyUsageClientAuth,
                                        sizeof(_oidExtendedKeyUsageClientAuth) },
    oidExtendedKeyUsageCodeSigning  = { (DERByte *)_oidExtendedKeyUsageCodeSigning,
                                        sizeof(_oidExtendedKeyUsageCodeSigning) },
    oidExtendedKeyUsageEmailProtection  = { (DERByte *)_oidExtendedKeyUsageEmailProtection,
                                        sizeof(_oidExtendedKeyUsageEmailProtection) },
    oidExtendedKeyUsageOCSPSigning  = { (DERByte *)_oidExtendedKeyUsageOCSPSigning,
                                        sizeof(_oidExtendedKeyUsageOCSPSigning) },
    oidExtendedKeyUsageIPSec        = { (DERByte *)_oidExtendedKeyUsageIPSec,
                                        sizeof(_oidExtendedKeyUsageIPSec) },
    oidExtendedKeyUsageMicrosoftSGC = { (DERByte *)_oidExtendedKeyUsageMicrosoftSGC,
                                        sizeof(_oidExtendedKeyUsageMicrosoftSGC) },
    oidExtendedKeyUsageNetscapeSGC  = { (DERByte *)_oidExtendedKeyUsageNetscapeSGC,
                                        sizeof(_oidExtendedKeyUsageNetscapeSGC) },
    oidAppleSecureBootCertSpec      = { (DERByte *)_oidAppleSecureBootCertSpec,
                                        sizeof(_oidAppleSecureBootCertSpec) },
    oidAppleProvisioningProfile     = { (DERByte *)_oidAppleProvisioningProfile,
                                        sizeof(_oidAppleProvisioningProfile) },
    oidAppleApplicationSigning      = { (DERByte *)_oidAppleApplicationSigning,
                                        sizeof(_oidAppleApplicationSigning) },
    oidAppleExtendedKeyUsageAppleID = { (DERByte *)_oidAppleExtendedKeyUsageAppleID,
                                        sizeof(_oidAppleExtendedKeyUsageAppleID) },
    oidAppleIntmMarkerAppleID       = { (DERByte *)_oidAppleIntmMarkerAppleID,
                                        sizeof(_oidAppleIntmMarkerAppleID) };


bool DEROidCompare(const DERItem *oid1, const DERItem *oid2) {
	if ((oid1 == NULL) || (oid2 == NULL)) {
		return false;
	}
	if (oid1->length != oid2->length) {
		return false;
	}
	if (!DERMemcmp(oid1->data, oid2->data, oid1->length)) {
		return true;
	} else {
		return false;
	}
}

Added Source/libDER/libDER/oids.h.











































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* Copyright (c) 2005-2009 Apple Inc. All Rights Reserved. */

/*
 * oids.h - declaration of OID consts 
 *
 * Created Nov. 11 2005 by dmitch
 */

#ifndef	_LIB_DER_OIDS_H_
#define _LIB_DER_OIDS_H_

#include "libDER.h"
#include <stdbool.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Algorithm oids. */
extern const DERItem
    oidRsa,         /* PKCS1 RSA encryption, used to identify RSA keys */
    oidMd2Rsa,      /* PKCS1 md2withRSAEncryption signature alg */
    oidMd5Rsa,      /* PKCS1 md5withRSAEncryption signature alg */
    oidSha1Rsa,     /* PKCS1 sha1withRSAEncryption signature alg */
    oidSha256Rsa,   /* PKCS1 sha256WithRSAEncryption signature alg */
    oidEcPubKey,    /* ECDH or ECDSA public key in a certificate */
    oidSha1Ecdsa,   /* ECDSA with SHA1 signature alg */
    oidSha224Ecdsa, /* ECDSA with SHA224 signature alg */
    oidSha256Ecdsa, /* ECDSA with SHA256 signature alg */
    oidSha384Ecdsa, /* ECDSA with SHA384 signature alg */
    oidSha512Ecdsa, /* ECDSA with SHA512 signature alg */
    oidMd2,         /* OID_RSA_HASH 2 */
    oidMd4,         /* OID_RSA_HASH 4 */
    oidMd5,         /* OID_RSA_HASH 5 */
    oidSha1,        /* OID_OIW_ALGORITHM 26 */
    oidSha256,      /* OID_NIST_HASHALG 1 */
    oidSha384,      /* OID_NIST_HASHALG 2 */
    oidSha512,      /* OID_NIST_HASHALG 3 */
    oidSha224;      /* OID_NIST_HASHALG 4 */

/* Standard X.509 Cert and CRL extensions. */
extern const DERItem
    oidSubjectKeyIdentifier,
    oidKeyUsage,
    oidPrivateKeyUsagePeriod,
    oidSubjectAltName,
    oidIssuerAltName,
    oidBasicConstraints,
    oidCrlDistributionPoints,
    oidCertificatePolicies,
    oidAnyPolicy,
    oidPolicyMappings,
    oidAuthorityKeyIdentifier,
    oidPolicyConstraints,
    oidExtendedKeyUsage,
    oidAnyExtendedKeyUsage,
    oidInhibitAnyPolicy,
    oidAuthorityInfoAccess,
    oidSubjectInfoAccess,
    oidAdOCSP,
    oidAdCAIssuer,
    oidNetscapeCertType,
    oidEntrustVersInfo,
    oidMSNTPrincipalName,
    /* Policy Qualifier IDs for Internet policy qualifiers. */
    oidQtCps,
    oidQtUNotice,
    /* X.501 Name IDs. */
	oidCommonName,
    oidCountryName,
    oidLocalityName,
    oidStateOrProvinceName,
	oidOrganizationName,
	oidOrganizationalUnitName,
	oidDescription,
	oidEmailAddress,
    oidFriendlyName,
    oidLocalKeyId,
    oidExtendedKeyUsageServerAuth,
    oidExtendedKeyUsageClientAuth,
    oidExtendedKeyUsageCodeSigning,
    oidExtendedKeyUsageEmailProtection,
    oidExtendedKeyUsageOCSPSigning,
    oidExtendedKeyUsageIPSec,
    oidExtendedKeyUsageMicrosoftSGC,
    oidExtendedKeyUsageNetscapeSGC,
	/* Secure Boot Spec oid */
	oidAppleSecureBootCertSpec,
    oidAppleProvisioningProfile,
    oidAppleApplicationSigning,
    oidAppleExtendedKeyUsageAppleID,
    oidAppleIntmMarkerAppleID;

/* Compare two decoded OIDs.  Returns true iff they are equivalent. */
bool DEROidCompare(const DERItem *oid1, const DERItem *oid2);

#ifdef __cplusplus
}
#endif

#endif	/* _LIB_DER_UTILS_H_ */

Added Source/libDER/libDERUtils/fileIo.c.











































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
 * Copyright (c) 2005-2007,2010 Apple Inc. All Rights Reserved.
 */

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "fileIo.h"

int writeFile(
	const char			*fileName,
	const unsigned char	*bytes,
	unsigned			numBytes)
{
	int		rtn;
	int 	fd;
	
	fd = open(fileName, O_RDWR | O_CREAT | O_TRUNC, 0600);
	if(fd <= 0) {
		return errno;
	}
	rtn = write(fd, bytes, (size_t)numBytes);
	if(rtn != (int)numBytes) {
		if(rtn >= 0) {
			fprintf(stderr, "writeFile: short write\n");
		}
		rtn = EIO;
	}
	else {
		rtn = 0;
	}
	close(fd);
	return rtn;
}
	
/*
 * Read entire file. 
 */
int readFile(
	const char		*fileName,
	unsigned char	**bytes,		// mallocd and returned
	unsigned		*numBytes)		// returned
{
	int rtn;
	int fd;
	char *buf;
	struct stat	sb;
	size_t size;
	
	*numBytes = 0;
	*bytes = NULL;
	fd = open(fileName, O_RDONLY, 0);
	if(fd <= 0) {
		return errno;
	}
	rtn = fstat(fd, &sb);
	if(rtn) {
		goto errOut;
	}
	size = (size_t) sb.st_size;
	buf = (char *)malloc(size);
	if(buf == NULL) {
		rtn = ENOMEM;
		goto errOut;
	}
	rtn = read(fd, buf, (size_t)size);
	if(rtn != (int)size) {
		if(rtn >= 0) {
			fprintf(stderr, "readFile: short read\n");
		}
		rtn = EIO;
	}
	else {
		rtn = 0;
		*bytes = (unsigned char *)buf;
		*numBytes = size;
	}
errOut:
	close(fd);
	return rtn;
}

Added Source/libDER/libDERUtils/fileIo.h.



























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
 * Copyright (c) 2005-2007,2010 Apple Inc. All Rights Reserved.
 */

#ifndef	_DER_FILE_IO_H_
#define _DER_FILE_IO_H_

/*
 * Read entire file. 
 */
#ifdef __cplusplus
extern "C" {
#endif

int readFile(
	const char			*fileName,
	unsigned char		**bytes,		// mallocd and returned
	unsigned			*numBytes);		// returned

int writeFile(
	const char			*fileName,
	const unsigned char	*bytes,
	unsigned			numBytes);

#ifdef __cplusplus
}
#endif

#endif	/* _DER_FILE_IO_H_ */

Added Source/libDER/libDERUtils/libDERUtils.c.









































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* Copyright (c) 2005-2007 Apple Inc. All Rights Reserved. */

/*
 * libDERUtils.c - support routines for libDER tests & examples 
 *
 * Created Nov. 7 2005 by dmitch
 */

#include <libDERUtils/libDERUtils.h>
#include <stdio.h>

const char *DERReturnString(
	DERReturn		drtn)
{
	static char unknown[128];
	
	switch(drtn) {
		case DR_Success: return "DR_Success";
		case DR_EndOfSequence: return "DR_EndOfSequence";
		case DR_UnexpectedTag: return "DR_UnexpectedTag";
		case DR_DecodeError: return "DR_DecodeError";
		case DR_Unimplemented: return "DR_Unimplemented";
		case DR_IncompleteSeq: return "DR_IncompleteSeq";
		default:
			sprintf(unknown, "Unknown error (%d)", (int)drtn);
			return unknown;
	}
}
	
void DERPerror(
	const char *op,
	DERReturn drtn)
{
	fprintf(stderr, "*** %s: %s\n", op, DERReturnString(drtn));
}

Added Source/libDER/libDERUtils/libDERUtils.h.



























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* Copyright (c) 2005-2007 Apple Inc. All Rights Reserved. */

/*
 * libDERUtils.h - support routines for libDER tests & examples 
 *
 * Created Nov. 7 2005 by dmitch
 */

#ifndef	_LIB_DER_UTILS_H_
#define _LIB_DER_UTILS_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <libDER/libDER.h>

const char *DERReturnString(
	DERReturn		drtn);
	
void DERPerror(
	const char *op,
	DERReturn rtn);
	
#ifdef __cplusplus
}
#endif

#endif	/* _LIB_DER_UTILS_H_ */

Added Source/libDER/libDERUtils/printFields.c.















































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/* Copyright (c) 2005-2007 Apple Inc. All Rights Reserved. */

/*
 * printFeilds.h - print various DER objects
 *
 * Created Nov. 9 2005 by dmitch
 */

#include <libDERUtils/printFields.h>
#include <libDER/DER_Decode.h>
#include <libDER/asn1Types.h>
#include <libDER/DER_Keys.h>
#include <libDERUtils/libDERUtils.h>
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>

static int indentLevel = 0;

void doIndent()
{
	int i;
	for (i = 0; i<indentLevel; i++) {
		putchar(' ');
	}
} /* indent */

void incrIndent()
{
	indentLevel += 3;
}

void decrIndent()
{
	indentLevel -= 3;
}

#define TO_PRINT_MAX	12

void printHex(
	DERItem *item)
{
	unsigned dex;
	unsigned toPrint = item->length;
	
	printf("<%u> ", item->length);
	if(toPrint > TO_PRINT_MAX) {
		toPrint = TO_PRINT_MAX;
	}
	for(dex=0; dex<toPrint; dex++) {
		printf("%02x ", item->data[dex]);
	}
	if(item->length > TO_PRINT_MAX) {
		printf("...");
	}
	printf("\n");
}

void printBitString(
	DERItem *item)
{
	unsigned dex;
	unsigned toPrint = item->length;
	DERItem bitStringBytes;
	DERByte numUnused;
	DERReturn drtn;
			
	drtn = DERParseBitString(item, &bitStringBytes, &numUnused);
	if(drtn) {
		DERPerror("DERParseBitString", drtn);
		return;
	}

	printf("<%u, %u> ", bitStringBytes.length, numUnused);
	toPrint = bitStringBytes.length;
	if(toPrint > TO_PRINT_MAX) {
		toPrint = TO_PRINT_MAX;
	}
	for(dex=0; dex<toPrint; dex++) {
		printf("%02x ", bitStringBytes.data[dex]);
	}
	if(item->length > TO_PRINT_MAX) {
		printf("...");
	}
	printf("\n");
}

void printString(
	DERItem *item)
{
	unsigned dex;
	char *cp = (char *)item->data;
	printf("'");
	for(dex=0; dex<item->length; dex++) {
		putchar(*cp++);
	}
	printf("'\n");

}

#define COLON_COLUMN	20

/*
 * Print line header, with current indent, followed by specified label, followed
 * by a ':' in column COLON_COLUMN, followed by one space. 
 */
void printHeader(
	const char *label)
{
	unsigned numPrinted;
	
	doIndent();
	printf("%s", label);
	numPrinted = indentLevel + strlen(label);
	if(numPrinted < COLON_COLUMN) {
		unsigned numSpaces = COLON_COLUMN - numPrinted;
		unsigned dex;
		for(dex=0; dex<numSpaces; dex++) {
			putchar(' ');
		}
	}
	printf(": ");
}

void printItem(
	const char *label,
	ItemType itemType,
	int verbose,
	DERTag tag,         // maybe from decoding, maybe the real tag underlying
						// an implicitly tagged item
	DERItem *item)		// content 
{
	DERTag tagClass = tag & ASN1_CLASS_MASK;
	DERTag tagNum = tag & ASN1_TAGNUM_MASK;
	char printable = 0;
	char *asnType = NULL;

	printHeader(label);
	
	if((itemType == IT_Branch) && !verbose) {
		printf("\n");
		return;
	}
	switch(tagClass) {
		case ASN1_UNIVERSAL:
			break;		// proceed with normal tags */
		case ASN1_APPLICATION:
			printf("APPLICATION (tag %u) ", tagNum);
			printHex(item);
			return;
		case ASN1_CONTEXT_SPECIFIC:
			printf("CONTEXT SPECIFIC (tag %u) ", tagNum);
			printHex(item);
			return;
		case ASN1_PRIVATE:
			printf("PRIVATE (tag %u) ", tagNum);
			printHex(item);
			return;
	}
	switch(tagNum) {
		case ASN1_BOOLEAN:
			asnType = "BOOLEAN";
			break;
		case ASN1_INTEGER:
			asnType = "INTEGER";
			break;
		case ASN1_BIT_STRING:
			/* special case here... */
			printf("BIT STRING ");
			printBitString(item);
			return;
		case ASN1_OCTET_STRING:
			asnType = "OCTET STRING";
			break;
		case ASN1_NULL:
			asnType = "NULL";
			break;
		case ASN1_OBJECT_ID:
			asnType = "OID";
			break;
		case ASN1_OBJECT_DESCRIPTOR:
			asnType = "OBJECT_DESCRIPTOR";
			break;
		case ASN1_REAL:
			asnType = "REAL";
			break;
		case ASN1_ENUMERATED:
			asnType = "ENUM";
			break;
		case ASN1_EMBEDDED_PDV:
			asnType = "EMBEDDED_PDV";
			break;
		case ASN1_UTF8_STRING:
			asnType = "UTF8 STRING";
			/* FIXME print these too */
			break;
		case ASN1_SEQUENCE:
			asnType = "SEQ";
			break;
		case ASN1_SET:
			asnType = "SET";
			break;
		case ASN1_NUMERIC_STRING:
			asnType = "NUMERIC_STRING";
			break;
		case ASN1_PRINTABLE_STRING:
			asnType = "PRINTABLE_STRING";
			printable = 1;
			break;
		case ASN1_T61_STRING:
			asnType = "T61_STRING";
			printable = 1;
			break;
		case ASN1_VIDEOTEX_STRING:
			asnType = "VIDEOTEX_STRING";
			printable = 1;
			break;
		case ASN1_IA5_STRING:
			asnType = "IA5_STRING";
			printable = 1;
			break;
		case ASN1_UTC_TIME:
			asnType = "UTC_TIME";
			printable = 1;
			break;
		case ASN1_GENERALIZED_TIME:
			asnType = "GENERALIZED_TIME";
			printable = 1;
			break;
		case ASN1_GRAPHIC_STRING:
			asnType = "GRAPHIC_STRING";
			break;
		case ASN1_VISIBLE_STRING:
			asnType = "VISIBLE_STRING";
			break;
		case ASN1_GENERAL_STRING:
			asnType = "GENERAL_STRING";
			break;
		case ASN1_UNIVERSAL_STRING:
			asnType = "UNIVERSAL_STRING";
			break;
		case ASN1_BMP_STRING:
			asnType = "BMP_STRING";
			break;
		default:
			asnType = "[unknown]";
			break;
	}
	printf("%s ", asnType);
	if(printable) {
		printString(item);
	}
	else {
		printHex(item);
	}
}

void printAlgId(
	const DERItem *content,
	int verbose)
{
	DERReturn drtn;
	DERAlgorithmId algId;
	
	drtn = DERParseSequenceContent(content,
		DERNumAlgorithmIdItemSpecs, DERAlgorithmIdItemSpecs,
		&algId, sizeof(algId));
	if(drtn) {
		DERPerror("DERParseSequenceContent(algId)", drtn);
		return;
	}
	printItem("alg", IT_Leaf, verbose, ASN1_OBJECT_ID, &algId.oid);
	if(algId.params.data) {
		printItem("params", IT_Leaf, verbose, algId.params.data[0], &algId.params);
	}
}

void printSubjPubKeyInfo(
	const DERItem *content,
	int verbose)
{
	DERReturn drtn;
	DERSubjPubKeyInfo pubKeyInfo;
	DERRSAPubKeyPKCS1 pkcs1Key;
	DERItem bitStringContents;
	DERByte numUnused;
	
	drtn = DERParseSequenceContent(content,
		DERNumSubjPubKeyInfoItemSpecs, DERSubjPubKeyInfoItemSpecs,
		&pubKeyInfo, sizeof(pubKeyInfo));
	if(drtn) {
		DERPerror("DERParseSequenceContent(pubKeyInfo)", drtn);
		return;
	}
	printItem("algId", IT_Branch, verbose, ASN1_CONSTR_SEQUENCE, &pubKeyInfo.algId);
	incrIndent();
	printAlgId(&pubKeyInfo.algId, verbose);
	decrIndent();

	printItem("pubKey", IT_Branch, verbose, ASN1_BIT_STRING, &pubKeyInfo.pubKey);
	
	/* 
	 * The contents of that bit string are a PKCS1 format RSA key. 
	 */
	drtn = DERParseBitString(&pubKeyInfo.pubKey, &bitStringContents, &numUnused);
	if(drtn) {
		DERPerror("DERParseBitString(pubKeyInfo.pubKey)", drtn);
		decrIndent();
		return;
	}
	drtn = DERParseSequence(&bitStringContents,
		DERNumRSAPubKeyPKCS1ItemSpecs, DERRSAPubKeyPKCS1ItemSpecs,
		&pkcs1Key, sizeof(pkcs1Key));
	if(drtn) {
		DERPerror("DERParseSequenceContent(pubKeyBits)", drtn);
		decrIndent();
		return;
	}
	incrIndent();
	printItem("modulus", IT_Leaf, verbose, ASN1_INTEGER, &pkcs1Key.modulus);
	printItem("pubExponent", IT_Leaf, verbose, ASN1_INTEGER, &pkcs1Key.pubExponent);
	
	decrIndent();
}

/* decode one item and print it */
void decodePrintItem(
	const char *label,
	ItemType itemType,
	int verbose,
	DERItem *derItem)
{
	DERDecodedInfo decoded;
	DERReturn drtn;
	
	drtn = DERDecodeItem(derItem, &decoded);
	if(drtn) {
		DERPerror("DERDecodeItem()", drtn);
		return;
	}
	printItem(label, IT_Leaf, 0, decoded.tag, &decoded.content);
}

Added Source/libDER/libDERUtils/printFields.h.



















































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* Copyright (c) 2005-2007 Apple Inc. All Rights Reserved. */

/*
 * printFeilds.h - print various DER objects
 *
 * Created Nov. 9 2005 by dmitch
 */

#ifndef	_PRINT_FIELDS_H_
#define _PRINT_FIELDS_H_

#include <libDER/libDER.h>

#ifdef __cplusplus
extern "C" {
#endif

void doIndent();
void incrIndent();
void decrIndent();
void printHex(DERItem *item);
void printBitString(DERItem *item);
void printString(DERItem *item);
void printHeader(const char *label);

typedef enum {
	IT_Leaf,		// leaf; always print contents
	IT_Branch		// branch; print contents iff verbose
} ItemType;

void printItem(
	const char *label,
	ItemType itemType,
	int verbose,
	DERTag tag,         // maybe from decoding, maybe the real tag underlying
						// an implicitly tagged item
	DERItem *item);		// content 

void printAlgId(
	const DERItem *content,
	int verbose);
void printSubjPubKeyInfo(
	const DERItem *content,
	int verbose);
	
/* decode one item and print it */
void decodePrintItem(
	const char *label,
	ItemType itemType,
	int verbose,
	DERItem *derItem);

#ifdef __cplusplus
}
#endif

#endif	/* _PRINT_FIELDS_H_ */

Deleted Source/libtomcrypt/doc/footer.html.

1
2
3
4
5
6
7
8
9
10
<hr width="80%">
Code by <a href="http://www.libtomcrypt.com/">Tom</a><br>
Docs using <img src="doxygen.png" alt="doxygen" align="middle" border=0>
<a href="http://jlcooke.ca/tom/hidden_image.png">

<!--
/* $Source: /cvs/libtom/libtomcrypt/doc/footer.html,v $ */
/* $Revision: 1.4 $ */
/* $Date: 2006/03/31 14:15:34 $ */
-->
<
<
<
<
<
<
<
<
<
<




















Deleted Source/libtomcrypt/doc/header.html.

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
<title>LibTomCrypt: Main Page</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.3.8 -->

<!--
/* $Source: /cvs/libtom/libtomcrypt/doc/header.html,v $ */
/* $Revision: 1.3 $ */
/* $Date: 2005/05/07 10:09:20 $ */
-->
<
<
<
<
<
<
<
<
<
<
<
<
























Deleted Source/libtomcrypt/src/ciphers/RC4/rc4.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/*
 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
 * 
 * The contents of this file constitute Original Code as defined in and are
 * subject to the Apple Public Source License Version 1.2 (the 'License').
 * You may not use this file except in compliance with the License. Please obtain
 * a copy of the License at http://www.apple.com/publicsource and read it before
 * using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
 * specific language governing rights and limitations under the License.
 */


/* crypto/rc4/rc4.h */
/* Copyright (C) 1995-1997 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#ifndef HEADER_RC4_H
#define HEADER_RC4_H

#include <Availability.h>
#include <AvailabilityMacros.h>
//#include <CommonCrypto/CommonCryptoPriv.h>
#include <stdint.h>

#ifdef  __cplusplus
extern "C" {
#endif

#ifdef NO_RC4
#error RC4 is disabled.
#endif


typedef uint32_t RC4_INT;

/* and we'll map to unique function names to avoid collisions with libcrypto */
// #define RC4_set_key	CC_RC4_set_key
// #define RC4			CC_RC4


#define RC4_MIN_KEY_SIZE_BYTES	1
#define RC4_MAX_KEY_SIZE_BYTES	512

typedef struct rc4_key_st
	{
	RC4_INT x,y;
	RC4_INT data[256];
	} RC4_KEY;

__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void CC_RC4_set_key(RC4_KEY *key, int len, const unsigned char *data);
 
__OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_4, __MAC_10_7, __IPHONE_NA, __IPHONE_NA)
void CC_RC4(RC4_KEY *key, unsigned long len, const unsigned char *indata,
		unsigned char *outdata);

#ifdef  __cplusplus
}
#endif

#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































































































Deleted Source/libtomcrypt/src/ciphers/RC4/rc4_enc.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*
 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
 * 
 * The contents of this file constitute Original Code as defined in and are
 * subject to the Apple Public Source License Version 1.2 (the 'License').
 * You may not use this file except in compliance with the License. Please obtain
 * a copy of the License at http://www.apple.com/publicsource and read it before
 * using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
 * specific language governing rights and limitations under the License.
 */


/* crypto/rc4/rc4_enc.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include "rc4.h"

/* RC4 as implemented from a posting from
 * Newsgroups: sci.crypt
 * From: sterndark@netcom.com (David Sterndark)
 * Subject: RC4 Algorithm revealed.
 * Message-ID: <sternCvKL4B.Hyy@netcom.com>
 * Date: Wed, 14 Sep 1994 06:35:31 GMT
 */

void CC_RC4(RC4_KEY *key, unsigned long len, const unsigned char *indata,
	     unsigned char *outdata)
	{
        register RC4_INT *d;
        register RC4_INT x,y,tx,ty;
	int i;
        
        x=key->x;     
        y=key->y;     
        d=key->data; 

#if defined(RC4_CHUNK)
	/*
	 * The original reason for implementing this(*) was the fact that
	 * pre-21164a Alpha CPUs don't have byte load/store instructions
	 * and e.g. a byte store has to be done with 64-bit load, shift,
	 * and, or and finally 64-bit store. Peaking data and operating
	 * at natural word size made it possible to reduce amount of
	 * instructions as well as to perform early read-ahead without
	 * suffering from RAW (read-after-write) hazard. This resulted
	 * in ~40%(**) performance improvement on 21064 box with gcc.
	 * But it's not only Alpha users who win here:-) Thanks to the
	 * early-n-wide read-ahead this implementation also exhibits
	 * >40% speed-up on SPARC and 20-30% on 64-bit MIPS (depending
	 * on sizeof(RC4_INT)).
	 *
	 * (*)	"this" means code which recognizes the case when input
	 *	and output pointers appear to be aligned at natural CPU
	 *	word boundary
	 * (**)	i.e. according to 'apps/openssl speed rc4' benchmark,
	 *	crypto/rc4/rc4speed.c exhibits almost 70% speed-up...
	 *
	 * Cavets.
	 *
	 * - RC4_CHUNK="unsigned long long" should be a #1 choice for
	 *   UltraSPARC. Unfortunately gcc generates very slow code
	 *   (2.5-3 times slower than one generated by Sun's WorkShop
	 *   C) and therefore gcc (at least 2.95 and earlier) should
	 *   always be told that RC4_CHUNK="unsigned long".
	 *
	 *					<appro@fy.chalmers.se>
	 */

# define RC4_STEP	( \
			x=(x+1) &0xff,	\
			tx=d[x],	\
			y=(tx+y)&0xff,	\
			ty=d[y],	\
			d[y]=tx,	\
			d[x]=ty,	\
			(RC4_CHUNK)d[(tx+ty)&0xff]\
			)

	if ( ( ((unsigned long)indata  & (sizeof(RC4_CHUNK)-1)) | 
	       ((unsigned long)outdata & (sizeof(RC4_CHUNK)-1)) ) == 0 )
		{
		RC4_CHUNK ichunk,otp;
		const union { long one; char little; } is_endian = {1};

		/*
		 * I reckon we can afford to implement both endian
		 * cases and to decide which way to take at run-time
		 * because the machine code appears to be very compact
		 * and redundant 1-2KB is perfectly tolerable (i.e.
		 * in case the compiler fails to eliminate it:-). By
		 * suggestion from Terrel Larson <terr@terralogic.net>
		 * who also stands for the is_endian union:-)
		 *
		 * Special notes.
		 *
		 * - is_endian is declared automatic as doing otherwise
		 *   (declaring static) prevents gcc from eliminating
		 *   the redundant code;
		 * - compilers (those I've tried) don't seem to have
		 *   problems eliminating either the operators guarded
		 *   by "if (sizeof(RC4_CHUNK)==8)" or the condition
		 *   expressions themselves so I've got 'em to replace
		 *   corresponding #ifdefs from the previous version;
		 * - I chose to let the redundant switch cases when
		 *   sizeof(RC4_CHUNK)!=8 be (were also #ifdefed
		 *   before);
		 * - in case you wonder "&(sizeof(RC4_CHUNK)*8-1)" in
		 *   [LB]ESHFT guards against "shift is out of range"
		 *   warnings when sizeof(RC4_CHUNK)!=8 
		 *
		 *			<appro@fy.chalmers.se>
		 */
		if (!is_endian.little)
			{	/* BIG-ENDIAN CASE */
# define BESHFT(c)	(((sizeof(RC4_CHUNK)-(c)-1)*8)&(sizeof(RC4_CHUNK)*8-1))
			for (;len&-sizeof(RC4_CHUNK);len-=sizeof(RC4_CHUNK))
				{
				ichunk  = *(RC4_CHUNK *)indata;
				otp  = RC4_STEP<<BESHFT(0);
				otp |= RC4_STEP<<BESHFT(1);
				otp |= RC4_STEP<<BESHFT(2);
				otp |= RC4_STEP<<BESHFT(3);
				if (sizeof(RC4_CHUNK)==8)
					{
					otp |= RC4_STEP<<BESHFT(4);
					otp |= RC4_STEP<<BESHFT(5);
					otp |= RC4_STEP<<BESHFT(6);
					otp |= RC4_STEP<<BESHFT(7);
					}
				*(RC4_CHUNK *)outdata = otp^ichunk;
				indata  += sizeof(RC4_CHUNK);
				outdata += sizeof(RC4_CHUNK);
				}
			if (len)
				{
				RC4_CHUNK mask=(RC4_CHUNK)-1, ochunk;

				ichunk = *(RC4_CHUNK *)indata;
				ochunk = *(RC4_CHUNK *)outdata;
				otp = 0;
				i = BESHFT(0);
				mask <<= (sizeof(RC4_CHUNK)-len)<<3;
				switch (len&(sizeof(RC4_CHUNK)-1))
					{
					case 7:	otp  = RC4_STEP<<i, i-=8;
					case 6:	otp |= RC4_STEP<<i, i-=8;
					case 5:	otp |= RC4_STEP<<i, i-=8;
					case 4:	otp |= RC4_STEP<<i, i-=8;
					case 3:	otp |= RC4_STEP<<i, i-=8;
					case 2:	otp |= RC4_STEP<<i, i-=8;
					case 1:	otp |= RC4_STEP<<i, i-=8;
					case 0: ; /*
						   * it's never the case,
						   * but it has to be here
						   * for ultrix?
						   */
					}
				ochunk &= ~mask;
				ochunk |= (otp^ichunk) & mask;
				*(RC4_CHUNK *)outdata = ochunk;
				}
			key->x=x;     
			key->y=y;
			return;
			}	/* big-endian */
		else
			{	/* LITTLE-ENDIAN CASE */
# define LESHFT(c)	(((c)*8)&(sizeof(RC4_CHUNK)*8-1))
			for (;len&-sizeof(RC4_CHUNK);len-=sizeof(RC4_CHUNK))
				{
				ichunk  = *(RC4_CHUNK *)indata;
				otp  = RC4_STEP;
				otp |= RC4_STEP<<8;
				otp |= RC4_STEP<<16;
				otp |= RC4_STEP<<24;
				if (sizeof(RC4_CHUNK)==8)
					{
					otp |= RC4_STEP<<LESHFT(4);
					otp |= RC4_STEP<<LESHFT(5);
					otp |= RC4_STEP<<LESHFT(6);
					otp |= RC4_STEP<<LESHFT(7);
					}
				*(RC4_CHUNK *)outdata = otp^ichunk;
				indata  += sizeof(RC4_CHUNK);
				outdata += sizeof(RC4_CHUNK);
				}
			if (len)
				{
				RC4_CHUNK mask=(RC4_CHUNK)-1, ochunk;

				ichunk = *(RC4_CHUNK *)indata;
				ochunk = *(RC4_CHUNK *)outdata;
				otp = 0;
				i   = 0;
				mask >>= (sizeof(RC4_CHUNK)-len)<<3;
				switch (len&(sizeof(RC4_CHUNK)-1))
					{
					case 7:	otp  = RC4_STEP,    i+=8;
					case 6:	otp |= RC4_STEP<<i, i+=8;
					case 5:	otp |= RC4_STEP<<i, i+=8;
					case 4:	otp |= RC4_STEP<<i, i+=8;
					case 3:	otp |= RC4_STEP<<i, i+=8;
					case 2:	otp |= RC4_STEP<<i, i+=8;
					case 1:	otp |= RC4_STEP<<i, i+=8;
					case 0: ; /*
						   * it's never the case,
						   * but it has to be here
						   * for ultrix?
						   */
					}
				ochunk &= ~mask;
				ochunk |= (otp^ichunk) & mask;
				*(RC4_CHUNK *)outdata = ochunk;
				}
			key->x=x;     
			key->y=y;
			return;
			} /* little-endian */
		}
#endif
#define LOOP(in,out) \
		x=((x+1)&0xff); \
		tx=d[x]; \
		y=(tx+y)&0xff; \
		d[x]=ty=d[y]; \
		d[y]=tx; \
		(out) = d[(tx+ty)&0xff]^ (in);

#ifndef RC4_INDEX
#define RC4_LOOP(a,b,i)	LOOP(*((a)++),*((b)++))
#else
#define RC4_LOOP(a,b,i)	LOOP(a[i],b[i])
#endif

	i=(int)(len>>3L);
	if (i)
		{
		for (;;)
			{
			RC4_LOOP(indata,outdata,0);
			RC4_LOOP(indata,outdata,1);
			RC4_LOOP(indata,outdata,2);
			RC4_LOOP(indata,outdata,3);
			RC4_LOOP(indata,outdata,4);
			RC4_LOOP(indata,outdata,5);
			RC4_LOOP(indata,outdata,6);
			RC4_LOOP(indata,outdata,7);
#ifdef RC4_INDEX
			indata+=8;
			outdata+=8;
#endif
			if (--i == 0) break;
			}
		}
	i=(int)len&0x07;
	if (i)
		{
		for (;;)
			{
			RC4_LOOP(indata,outdata,0); if (--i == 0) break;
			RC4_LOOP(indata,outdata,1); if (--i == 0) break;
			RC4_LOOP(indata,outdata,2); if (--i == 0) break;
			RC4_LOOP(indata,outdata,3); if (--i == 0) break;
			RC4_LOOP(indata,outdata,4); if (--i == 0) break;
			RC4_LOOP(indata,outdata,5); if (--i == 0) break;
			RC4_LOOP(indata,outdata,6); if (--i == 0) break;
			}
		}               
	key->x=x;     
	key->y=y;
	}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/RC4/rc4_skey.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
 * 
 * The contents of this file constitute Original Code as defined in and are
 * subject to the Apple Public Source License Version 1.2 (the 'License').
 * You may not use this file except in compliance with the License. Please obtain
 * a copy of the License at http://www.apple.com/publicsource and read it before
 * using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
 * specific language governing rights and limitations under the License.
 */


/* crypto/rc4/rc4_skey.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 * 
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 * 
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from 
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 * 
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * 
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.]
 */

#include "rc4.h"


/* RC4 as implemented from a posting from
 * Newsgroups: sci.crypt
 * From: sterndark@netcom.com (David Sterndark)
 * Subject: RC4 Algorithm revealed.
 * Message-ID: <sternCvKL4B.Hyy@netcom.com>
 * Date: Wed, 14 Sep 1994 06:35:31 GMT
 */

void CC_RC4_set_key(RC4_KEY *key, int len, const unsigned char *data)
	{
        register RC4_INT tmp;
        register int id1,id2;
        register RC4_INT *d;
        unsigned int i;
        
        d= &(key->data[0]);
	for (i=0; i<256; i++)
		d[i]=i;
        key->x = 0;     
        key->y = 0;     
        id1=id2=0;     

#define SK_LOOP(n) { \
		tmp=d[(n)]; \
		id2 = (data[id1] + tmp + id2) & 0xff; \
		if (++id1 == len) id1=0; \
		d[(n)]=d[id2]; \
		d[id2]=tmp; }

	for (i=0; i < 256; i+=4)
		{
		SK_LOOP(i+0);
		SK_LOOP(i+1);
		SK_LOOP(i+2);
		SK_LOOP(i+3);
		}
	}
    
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/AES.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/*	AES.s -- Core AES routines for Intel processors.

	Written by Eric Postpischil, January 30, 2008.
*/
#if defined __i386__ || defined __x86_64__


/*	We build these AES routines as a single module because the routines refer
	to labels in Data.s and it is easier and faster to refer to them as local
	labels.  In my implementations of AES for CommonCrypto, both i386 and
	x86_64 use position-independent code.  For this in-kernel implementation,
	i386 has been converted to absolute addressing, but x86_64 still uses PIC.

	A local label can be referred to with position-independent assembler
	expressions such as "label-base(register)", where <base> is a local label
	whose address has been loaded into <register>.  (On i386, this is typically
	done with the idiom of a call to the next instruction and a pop of that
	return address into a register.)  Without local labels, the references must
	be done using spaces for addresses of "lazy symbols" that are filled in by
	the dynamic loader and loaded by the code that wants the address.

	So the various routines in other files are assembled here via #include
	directives.
*/
#include "Data.s"


#define	TableSize	(256*4)
	/*	Each of the arrays defined in Data.s except for the round constants
		in _AESRcon is composed of four tables of 256 entries of four bytes
		each.  TableSize is the number of bytes in one of those four tables.
	*/


// Include constants describing the AES context structures.
#include "Context.h"


/*	Define a macro to select a value based on architecture.  This reduces
	some of the architecture conditionalization later in the source.
*/
#if defined __i386__
	#define	Arch(i386, x86_64)	i386
#elif defined __x86_64__
	#define	Arch(i386, x86_64)	x86_64
#endif


// Define an instruction for moving pointers.
#define	movp	Arch(movd, movd)
	// Latter argument should be "movq", but the assembler uses "movd".


/*	Rename the general registers.  This makes it easier to keep track of them
	and provides names for the "whole register" that are uniform between i386
	and x86_64.
*/
#if defined __i386__
	#define	r0	%eax	// Available for any use.
	#define	r1	%ecx	// Available for any use, some special purposes (loop).
	#define	r2	%edx	// Available for any use.
	#define	r3	%ebx	// Must be preserved by called routine.
	#define	r4	%esp	// Stack pointer.
	#define	r5	%ebp	// Frame pointer, must preserve, no bare indirect.
	#define	r6	%esi	// Must be preserved by called routine.
	#define	r7	%edi	// Must be preserved by called routine.
#elif defined __x86_64__
	#define	r0	%rax	// Available for any use.
	#define	r1	%rcx	// Available for any use.
	#define	r2	%rdx	// Available for any use.
	#define	r3	%rbx	// Must be preserved by called routine.
	#define	r4	%rsp	// Stack pointer.
	#define	r5	%rbp	// Frame pointer.  Must be preserved by called routine.
	#define	r6	%rsi	// Available for any use.
	#define	r7	%rdi	// Available for any use.
	#define	r8	%r8		// Available for any use.
	#define	r9	%r9		// Available for any use.
	#define	r10	%r10	// Available for any use.
	#define	r11	%r11	// Available for any use.
	#define	r12	%r12	// Must be preserved by called routine.
	#define	r13	%r13	// Must be preserved by called routine.
	#define	r14	%r14	// Must be preserved by called routine.
	#define	r15	%r15	// Must be preserved by called routine.
#else
	#error "Unknown architecture."
#endif

// Define names for parts of registers.

#define	r0d		%eax	// Low 32 bits of r0.
#define	r1d		%ecx	// Low 32 bits of r1.
#define	r2d		%edx	// Low 32 bits of r2.
#define	r3d		%ebx	// Low 32 bits of r3.
#define	r5d		%ebp	// Low 32 bits of r5.
#define	r6d		%esi	// Low 32 bits of r6.
#define	r7d		%edi	// Low 32 bits of r7.
#define	r8d		%r8d	// Low 32 bits of r8.
#define	r9d		%r9d	// Low 32 bits of r9.
#define	r11d	%r11d	// Low 32 bits of r11.

#define	r0l		%al		// Low byte of r0.
#define	r1l		%cl		// Low byte of r1.
#define	r2l		%dl		// Low byte of r2.
#define	r3l		%bl		// Low byte of r3.
#define	r5l		%bpl	// Low byte of r5.

#define	r0h		%ah		// Second lowest byte of r0.
#define	r1h		%ch		// Second lowest byte of r1.
#define	r2h		%dh		// Second lowest byte of r2.
#define	r3h		%bh		// Second lowest byte of r3.


	.text


// Define encryption routine, _AESEncryptWithExpandedKey
#define	Select	0
#include "EncryptDecrypt.s"
#undef	Select


// Define decryption routine, _AESDecryptWithExpandedKey
#define	Select	1
#include "EncryptDecrypt.s"
#undef	Select

// Define encryption routine, _AESEncryptWithExpandedKey
#define	Select	2
#include "EncryptDecrypt.s"
#undef	Select


// Define decryption routine, _AESDecryptWithExpandedKey
#define	Select	3
#include "EncryptDecrypt.s"
#undef	Select


// Define key expansion routine for encryption, _AESExpandKeyForEncryption.
#include "ExpandKeyForEncryption.s"


// Define key expansion for decryption routine, _AESExpandKeyForDecryption.
#include "ExpandKeyForDecryption.s"
#endif /* x86 based build */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/Context.h.

1
2
3
4
5
6
7
8
9
// Define byte offset of key within context structure.
#define	ContextKey			0

/*	Define byte offset of key length within context structure.  The number
	stored there is the number of bytes from the start of the first round key
	to the start of the last round key.  That is 16 less than the number of
	bytes in the entire key.
*/
#define	ContextKeyLength	240
<
<
<
<
<
<
<
<
<


















Deleted Source/libtomcrypt/src/ciphers/aesedpport/Data.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
// This file was generated by MakeData.c.


	.const


// Round constants.
	.globl	_AESRcon
	.private_extern	_AESRcon
_AESRcon:
	.byte	0	// Not used, included for indexing simplicity.
	.byte	0x01
	.byte	0x02
	.byte	0x04
	.byte	0x08
	.byte	0x10
	.byte	0x20
	.byte	0x40
	.byte	0x80
	.byte	0x1b
	.byte	0x36


// Tables for InvMixColumn.
	.globl	_AESInvMixColumnTable
	.private_extern	_AESInvMixColumnTable
	.align	2
_AESInvMixColumnTable:
	// Table 0.
	.long	0x00000000
	.long	0x0b0d090e
	.long	0x161a121c
	.long	0x1d171b12
	.long	0x2c342438
	.long	0x27392d36
	.long	0x3a2e3624
	.long	0x31233f2a
	.long	0x58684870
	.long	0x5365417e
	.long	0x4e725a6c
	.long	0x457f5362
	.long	0x745c6c48
	.long	0x7f516546
	.long	0x62467e54
	.long	0x694b775a
	.long	0xb0d090e0
	.long	0xbbdd99ee
	.long	0xa6ca82fc
	.long	0xadc78bf2
	.long	0x9ce4b4d8
	.long	0x97e9bdd6
	.long	0x8afea6c4
	.long	0x81f3afca
	.long	0xe8b8d890
	.long	0xe3b5d19e
	.long	0xfea2ca8c
	.long	0xf5afc382
	.long	0xc48cfca8
	.long	0xcf81f5a6
	.long	0xd296eeb4
	.long	0xd99be7ba
	.long	0x7bbb3bdb
	.long	0x70b632d5
	.long	0x6da129c7
	.long	0x66ac20c9
	.long	0x578f1fe3
	.long	0x5c8216ed
	.long	0x41950dff
	.long	0x4a9804f1
	.long	0x23d373ab
	.long	0x28de7aa5
	.long	0x35c961b7
	.long	0x3ec468b9
	.long	0x0fe75793
	.long	0x04ea5e9d
	.long	0x19fd458f
	.long	0x12f04c81
	.long	0xcb6bab3b
	.long	0xc066a235
	.long	0xdd71b927
	.long	0xd67cb029
	.long	0xe75f8f03
	.long	0xec52860d
	.long	0xf1459d1f
	.long	0xfa489411
	.long	0x9303e34b
	.long	0x980eea45
	.long	0x8519f157
	.long	0x8e14f859
	.long	0xbf37c773
	.long	0xb43ace7d
	.long	0xa92dd56f
	.long	0xa220dc61
	.long	0xf66d76ad
	.long	0xfd607fa3
	.long	0xe07764b1
	.long	0xeb7a6dbf
	.long	0xda595295
	.long	0xd1545b9b
	.long	0xcc434089
	.long	0xc74e4987
	.long	0xae053edd
	.long	0xa50837d3
	.long	0xb81f2cc1
	.long	0xb31225cf
	.long	0x82311ae5
	.long	0x893c13eb
	.long	0x942b08f9
	.long	0x9f2601f7
	.long	0x46bde64d
	.long	0x4db0ef43
	.long	0x50a7f451
	.long	0x5baafd5f
	.long	0x6a89c275
	.long	0x6184cb7b
	.long	0x7c93d069
	.long	0x779ed967
	.long	0x1ed5ae3d
	.long	0x15d8a733
	.long	0x08cfbc21
	.long	0x03c2b52f
	.long	0x32e18a05
	.long	0x39ec830b
	.long	0x24fb9819
	.long	0x2ff69117
	.long	0x8dd64d76
	.long	0x86db4478
	.long	0x9bcc5f6a
	.long	0x90c15664
	.long	0xa1e2694e
	.long	0xaaef6040
	.long	0xb7f87b52
	.long	0xbcf5725c
	.long	0xd5be0506
	.long	0xdeb30c08
	.long	0xc3a4171a
	.long	0xc8a91e14
	.long	0xf98a213e
	.long	0xf2872830
	.long	0xef903322
	.long	0xe49d3a2c
	.long	0x3d06dd96
	.long	0x360bd498
	.long	0x2b1ccf8a
	.long	0x2011c684
	.long	0x1132f9ae
	.long	0x1a3ff0a0
	.long	0x0728ebb2
	.long	0x0c25e2bc
	.long	0x656e95e6
	.long	0x6e639ce8
	.long	0x737487fa
	.long	0x78798ef4
	.long	0x495ab1de
	.long	0x4257b8d0
	.long	0x5f40a3c2
	.long	0x544daacc
	.long	0xf7daec41
	.long	0xfcd7e54f
	.long	0xe1c0fe5d
	.long	0xeacdf753
	.long	0xdbeec879
	.long	0xd0e3c177
	.long	0xcdf4da65
	.long	0xc6f9d36b
	.long	0xafb2a431
	.long	0xa4bfad3f
	.long	0xb9a8b62d
	.long	0xb2a5bf23
	.long	0x83868009
	.long	0x888b8907
	.long	0x959c9215
	.long	0x9e919b1b
	.long	0x470a7ca1
	.long	0x4c0775af
	.long	0x51106ebd
	.long	0x5a1d67b3
	.long	0x6b3e5899
	.long	0x60335197
	.long	0x7d244a85
	.long	0x7629438b
	.long	0x1f6234d1
	.long	0x146f3ddf
	.long	0x097826cd
	.long	0x02752fc3
	.long	0x335610e9
	.long	0x385b19e7
	.long	0x254c02f5
	.long	0x2e410bfb
	.long	0x8c61d79a
	.long	0x876cde94
	.long	0x9a7bc586
	.long	0x9176cc88
	.long	0xa055f3a2
	.long	0xab58faac
	.long	0xb64fe1be
	.long	0xbd42e8b0
	.long	0xd4099fea
	.long	0xdf0496e4
	.long	0xc2138df6
	.long	0xc91e84f8
	.long	0xf83dbbd2
	.long	0xf330b2dc
	.long	0xee27a9ce
	.long	0xe52aa0c0
	.long	0x3cb1477a
	.long	0x37bc4e74
	.long	0x2aab5566
	.long	0x21a65c68
	.long	0x10856342
	.long	0x1b886a4c
	.long	0x069f715e
	.long	0x0d927850
	.long	0x64d90f0a
	.long	0x6fd40604
	.long	0x72c31d16
	.long	0x79ce1418
	.long	0x48ed2b32
	.long	0x43e0223c
	.long	0x5ef7392e
	.long	0x55fa3020
	.long	0x01b79aec
	.long	0x0aba93e2
	.long	0x17ad88f0
	.long	0x1ca081fe
	.long	0x2d83bed4
	.long	0x268eb7da
	.long	0x3b99acc8
	.long	0x3094a5c6
	.long	0x59dfd29c
	.long	0x52d2db92
	.long	0x4fc5c080
	.long	0x44c8c98e
	.long	0x75ebf6a4
	.long	0x7ee6ffaa
	.long	0x63f1e4b8
	.long	0x68fcedb6
	.long	0xb1670a0c
	.long	0xba6a0302
	.long	0xa77d1810
	.long	0xac70111e
	.long	0x9d532e34
	.long	0x965e273a
	.long	0x8b493c28
	.long	0x80443526
	.long	0xe90f427c
	.long	0xe2024b72
	.long	0xff155060
	.long	0xf418596e
	.long	0xc53b6644
	.long	0xce366f4a
	.long	0xd3217458
	.long	0xd82c7d56
	.long	0x7a0ca137
	.long	0x7101a839
	.long	0x6c16b32b
	.long	0x671bba25
	.long	0x5638850f
	.long	0x5d358c01
	.long	0x40229713
	.long	0x4b2f9e1d
	.long	0x2264e947
	.long	0x2969e049
	.long	0x347efb5b
	.long	0x3f73f255
	.long	0x0e50cd7f
	.long	0x055dc471
	.long	0x184adf63
	.long	0x1347d66d
	.long	0xcadc31d7
	.long	0xc1d138d9
	.long	0xdcc623cb
	.long	0xd7cb2ac5
	.long	0xe6e815ef
	.long	0xede51ce1
	.long	0xf0f207f3
	.long	0xfbff0efd
	.long	0x92b479a7
	.long	0x99b970a9
	.long	0x84ae6bbb
	.long	0x8fa362b5
	.long	0xbe805d9f
	.long	0xb58d5491
	.long	0xa89a4f83
	.long	0xa397468d
	// Table 1.
	.long	0x00000000
	.long	0x0d090e0b
	.long	0x1a121c16
	.long	0x171b121d
	.long	0x3424382c
	.long	0x392d3627
	.long	0x2e36243a
	.long	0x233f2a31
	.long	0x68487058
	.long	0x65417e53
	.long	0x725a6c4e
	.long	0x7f536245
	.long	0x5c6c4874
	.long	0x5165467f
	.long	0x467e5462
	.long	0x4b775a69
	.long	0xd090e0b0
	.long	0xdd99eebb
	.long	0xca82fca6
	.long	0xc78bf2ad
	.long	0xe4b4d89c
	.long	0xe9bdd697
	.long	0xfea6c48a
	.long	0xf3afca81
	.long	0xb8d890e8
	.long	0xb5d19ee3
	.long	0xa2ca8cfe
	.long	0xafc382f5
	.long	0x8cfca8c4
	.long	0x81f5a6cf
	.long	0x96eeb4d2
	.long	0x9be7bad9
	.long	0xbb3bdb7b
	.long	0xb632d570
	.long	0xa129c76d
	.long	0xac20c966
	.long	0x8f1fe357
	.long	0x8216ed5c
	.long	0x950dff41
	.long	0x9804f14a
	.long	0xd373ab23
	.long	0xde7aa528
	.long	0xc961b735
	.long	0xc468b93e
	.long	0xe757930f
	.long	0xea5e9d04
	.long	0xfd458f19
	.long	0xf04c8112
	.long	0x6bab3bcb
	.long	0x66a235c0
	.long	0x71b927dd
	.long	0x7cb029d6
	.long	0x5f8f03e7
	.long	0x52860dec
	.long	0x459d1ff1
	.long	0x489411fa
	.long	0x03e34b93
	.long	0x0eea4598
	.long	0x19f15785
	.long	0x14f8598e
	.long	0x37c773bf
	.long	0x3ace7db4
	.long	0x2dd56fa9
	.long	0x20dc61a2
	.long	0x6d76adf6
	.long	0x607fa3fd
	.long	0x7764b1e0
	.long	0x7a6dbfeb
	.long	0x595295da
	.long	0x545b9bd1
	.long	0x434089cc
	.long	0x4e4987c7
	.long	0x053eddae
	.long	0x0837d3a5
	.long	0x1f2cc1b8
	.long	0x1225cfb3
	.long	0x311ae582
	.long	0x3c13eb89
	.long	0x2b08f994
	.long	0x2601f79f
	.long	0xbde64d46
	.long	0xb0ef434d
	.long	0xa7f45150
	.long	0xaafd5f5b
	.long	0x89c2756a
	.long	0x84cb7b61
	.long	0x93d0697c
	.long	0x9ed96777
	.long	0xd5ae3d1e
	.long	0xd8a73315
	.long	0xcfbc2108
	.long	0xc2b52f03
	.long	0xe18a0532
	.long	0xec830b39
	.long	0xfb981924
	.long	0xf691172f
	.long	0xd64d768d
	.long	0xdb447886
	.long	0xcc5f6a9b
	.long	0xc1566490
	.long	0xe2694ea1
	.long	0xef6040aa
	.long	0xf87b52b7
	.long	0xf5725cbc
	.long	0xbe0506d5
	.long	0xb30c08de
	.long	0xa4171ac3
	.long	0xa91e14c8
	.long	0x8a213ef9
	.long	0x872830f2
	.long	0x903322ef
	.long	0x9d3a2ce4
	.long	0x06dd963d
	.long	0x0bd49836
	.long	0x1ccf8a2b
	.long	0x11c68420
	.long	0x32f9ae11
	.long	0x3ff0a01a
	.long	0x28ebb207
	.long	0x25e2bc0c
	.long	0x6e95e665
	.long	0x639ce86e
	.long	0x7487fa73
	.long	0x798ef478
	.long	0x5ab1de49
	.long	0x57b8d042
	.long	0x40a3c25f
	.long	0x4daacc54
	.long	0xdaec41f7
	.long	0xd7e54ffc
	.long	0xc0fe5de1
	.long	0xcdf753ea
	.long	0xeec879db
	.long	0xe3c177d0
	.long	0xf4da65cd
	.long	0xf9d36bc6
	.long	0xb2a431af
	.long	0xbfad3fa4
	.long	0xa8b62db9
	.long	0xa5bf23b2
	.long	0x86800983
	.long	0x8b890788
	.long	0x9c921595
	.long	0x919b1b9e
	.long	0x0a7ca147
	.long	0x0775af4c
	.long	0x106ebd51
	.long	0x1d67b35a
	.long	0x3e58996b
	.long	0x33519760
	.long	0x244a857d
	.long	0x29438b76
	.long	0x6234d11f
	.long	0x6f3ddf14
	.long	0x7826cd09
	.long	0x752fc302
	.long	0x5610e933
	.long	0x5b19e738
	.long	0x4c02f525
	.long	0x410bfb2e
	.long	0x61d79a8c
	.long	0x6cde9487
	.long	0x7bc5869a
	.long	0x76cc8891
	.long	0x55f3a2a0
	.long	0x58faacab
	.long	0x4fe1beb6
	.long	0x42e8b0bd
	.long	0x099fead4
	.long	0x0496e4df
	.long	0x138df6c2
	.long	0x1e84f8c9
	.long	0x3dbbd2f8
	.long	0x30b2dcf3
	.long	0x27a9ceee
	.long	0x2aa0c0e5
	.long	0xb1477a3c
	.long	0xbc4e7437
	.long	0xab55662a
	.long	0xa65c6821
	.long	0x85634210
	.long	0x886a4c1b
	.long	0x9f715e06
	.long	0x9278500d
	.long	0xd90f0a64
	.long	0xd406046f
	.long	0xc31d1672
	.long	0xce141879
	.long	0xed2b3248
	.long	0xe0223c43
	.long	0xf7392e5e
	.long	0xfa302055
	.long	0xb79aec01
	.long	0xba93e20a
	.long	0xad88f017
	.long	0xa081fe1c
	.long	0x83bed42d
	.long	0x8eb7da26
	.long	0x99acc83b
	.long	0x94a5c630
	.long	0xdfd29c59
	.long	0xd2db9252
	.long	0xc5c0804f
	.long	0xc8c98e44
	.long	0xebf6a475
	.long	0xe6ffaa7e
	.long	0xf1e4b863
	.long	0xfcedb668
	.long	0x670a0cb1
	.long	0x6a0302ba
	.long	0x7d1810a7
	.long	0x70111eac
	.long	0x532e349d
	.long	0x5e273a96
	.long	0x493c288b
	.long	0x44352680
	.long	0x0f427ce9
	.long	0x024b72e2
	.long	0x155060ff
	.long	0x18596ef4
	.long	0x3b6644c5
	.long	0x366f4ace
	.long	0x217458d3
	.long	0x2c7d56d8
	.long	0x0ca1377a
	.long	0x01a83971
	.long	0x16b32b6c
	.long	0x1bba2567
	.long	0x38850f56
	.long	0x358c015d
	.long	0x22971340
	.long	0x2f9e1d4b
	.long	0x64e94722
	.long	0x69e04929
	.long	0x7efb5b34
	.long	0x73f2553f
	.long	0x50cd7f0e
	.long	0x5dc47105
	.long	0x4adf6318
	.long	0x47d66d13
	.long	0xdc31d7ca
	.long	0xd138d9c1
	.long	0xc623cbdc
	.long	0xcb2ac5d7
	.long	0xe815efe6
	.long	0xe51ce1ed
	.long	0xf207f3f0
	.long	0xff0efdfb
	.long	0xb479a792
	.long	0xb970a999
	.long	0xae6bbb84
	.long	0xa362b58f
	.long	0x805d9fbe
	.long	0x8d5491b5
	.long	0x9a4f83a8
	.long	0x97468da3
	// Table 2.
	.long	0x00000000
	.long	0x090e0b0d
	.long	0x121c161a
	.long	0x1b121d17
	.long	0x24382c34
	.long	0x2d362739
	.long	0x36243a2e
	.long	0x3f2a3123
	.long	0x48705868
	.long	0x417e5365
	.long	0x5a6c4e72
	.long	0x5362457f
	.long	0x6c48745c
	.long	0x65467f51
	.long	0x7e546246
	.long	0x775a694b
	.long	0x90e0b0d0
	.long	0x99eebbdd
	.long	0x82fca6ca
	.long	0x8bf2adc7
	.long	0xb4d89ce4
	.long	0xbdd697e9
	.long	0xa6c48afe
	.long	0xafca81f3
	.long	0xd890e8b8
	.long	0xd19ee3b5
	.long	0xca8cfea2
	.long	0xc382f5af
	.long	0xfca8c48c
	.long	0xf5a6cf81
	.long	0xeeb4d296
	.long	0xe7bad99b
	.long	0x3bdb7bbb
	.long	0x32d570b6
	.long	0x29c76da1
	.long	0x20c966ac
	.long	0x1fe3578f
	.long	0x16ed5c82
	.long	0x0dff4195
	.long	0x04f14a98
	.long	0x73ab23d3
	.long	0x7aa528de
	.long	0x61b735c9
	.long	0x68b93ec4
	.long	0x57930fe7
	.long	0x5e9d04ea
	.long	0x458f19fd
	.long	0x4c8112f0
	.long	0xab3bcb6b
	.long	0xa235c066
	.long	0xb927dd71
	.long	0xb029d67c
	.long	0x8f03e75f
	.long	0x860dec52
	.long	0x9d1ff145
	.long	0x9411fa48
	.long	0xe34b9303
	.long	0xea45980e
	.long	0xf1578519
	.long	0xf8598e14
	.long	0xc773bf37
	.long	0xce7db43a
	.long	0xd56fa92d
	.long	0xdc61a220
	.long	0x76adf66d
	.long	0x7fa3fd60
	.long	0x64b1e077
	.long	0x6dbfeb7a
	.long	0x5295da59
	.long	0x5b9bd154
	.long	0x4089cc43
	.long	0x4987c74e
	.long	0x3eddae05
	.long	0x37d3a508
	.long	0x2cc1b81f
	.long	0x25cfb312
	.long	0x1ae58231
	.long	0x13eb893c
	.long	0x08f9942b
	.long	0x01f79f26
	.long	0xe64d46bd
	.long	0xef434db0
	.long	0xf45150a7
	.long	0xfd5f5baa
	.long	0xc2756a89
	.long	0xcb7b6184
	.long	0xd0697c93
	.long	0xd967779e
	.long	0xae3d1ed5
	.long	0xa73315d8
	.long	0xbc2108cf
	.long	0xb52f03c2
	.long	0x8a0532e1
	.long	0x830b39ec
	.long	0x981924fb
	.long	0x91172ff6
	.long	0x4d768dd6
	.long	0x447886db
	.long	0x5f6a9bcc
	.long	0x566490c1
	.long	0x694ea1e2
	.long	0x6040aaef
	.long	0x7b52b7f8
	.long	0x725cbcf5
	.long	0x0506d5be
	.long	0x0c08deb3
	.long	0x171ac3a4
	.long	0x1e14c8a9
	.long	0x213ef98a
	.long	0x2830f287
	.long	0x3322ef90
	.long	0x3a2ce49d
	.long	0xdd963d06
	.long	0xd498360b
	.long	0xcf8a2b1c
	.long	0xc6842011
	.long	0xf9ae1132
	.long	0xf0a01a3f
	.long	0xebb20728
	.long	0xe2bc0c25
	.long	0x95e6656e
	.long	0x9ce86e63
	.long	0x87fa7374
	.long	0x8ef47879
	.long	0xb1de495a
	.long	0xb8d04257
	.long	0xa3c25f40
	.long	0xaacc544d
	.long	0xec41f7da
	.long	0xe54ffcd7
	.long	0xfe5de1c0
	.long	0xf753eacd
	.long	0xc879dbee
	.long	0xc177d0e3
	.long	0xda65cdf4
	.long	0xd36bc6f9
	.long	0xa431afb2
	.long	0xad3fa4bf
	.long	0xb62db9a8
	.long	0xbf23b2a5
	.long	0x80098386
	.long	0x8907888b
	.long	0x9215959c
	.long	0x9b1b9e91
	.long	0x7ca1470a
	.long	0x75af4c07
	.long	0x6ebd5110
	.long	0x67b35a1d
	.long	0x58996b3e
	.long	0x51976033
	.long	0x4a857d24
	.long	0x438b7629
	.long	0x34d11f62
	.long	0x3ddf146f
	.long	0x26cd0978
	.long	0x2fc30275
	.long	0x10e93356
	.long	0x19e7385b
	.long	0x02f5254c
	.long	0x0bfb2e41
	.long	0xd79a8c61
	.long	0xde94876c
	.long	0xc5869a7b
	.long	0xcc889176
	.long	0xf3a2a055
	.long	0xfaacab58
	.long	0xe1beb64f
	.long	0xe8b0bd42
	.long	0x9fead409
	.long	0x96e4df04
	.long	0x8df6c213
	.long	0x84f8c91e
	.long	0xbbd2f83d
	.long	0xb2dcf330
	.long	0xa9ceee27
	.long	0xa0c0e52a
	.long	0x477a3cb1
	.long	0x4e7437bc
	.long	0x55662aab
	.long	0x5c6821a6
	.long	0x63421085
	.long	0x6a4c1b88
	.long	0x715e069f
	.long	0x78500d92
	.long	0x0f0a64d9
	.long	0x06046fd4
	.long	0x1d1672c3
	.long	0x141879ce
	.long	0x2b3248ed
	.long	0x223c43e0
	.long	0x392e5ef7
	.long	0x302055fa
	.long	0x9aec01b7
	.long	0x93e20aba
	.long	0x88f017ad
	.long	0x81fe1ca0
	.long	0xbed42d83
	.long	0xb7da268e
	.long	0xacc83b99
	.long	0xa5c63094
	.long	0xd29c59df
	.long	0xdb9252d2
	.long	0xc0804fc5
	.long	0xc98e44c8
	.long	0xf6a475eb
	.long	0xffaa7ee6
	.long	0xe4b863f1
	.long	0xedb668fc
	.long	0x0a0cb167
	.long	0x0302ba6a
	.long	0x1810a77d
	.long	0x111eac70
	.long	0x2e349d53
	.long	0x273a965e
	.long	0x3c288b49
	.long	0x35268044
	.long	0x427ce90f
	.long	0x4b72e202
	.long	0x5060ff15
	.long	0x596ef418
	.long	0x6644c53b
	.long	0x6f4ace36
	.long	0x7458d321
	.long	0x7d56d82c
	.long	0xa1377a0c
	.long	0xa8397101
	.long	0xb32b6c16
	.long	0xba25671b
	.long	0x850f5638
	.long	0x8c015d35
	.long	0x97134022
	.long	0x9e1d4b2f
	.long	0xe9472264
	.long	0xe0492969
	.long	0xfb5b347e
	.long	0xf2553f73
	.long	0xcd7f0e50
	.long	0xc471055d
	.long	0xdf63184a
	.long	0xd66d1347
	.long	0x31d7cadc
	.long	0x38d9c1d1
	.long	0x23cbdcc6
	.long	0x2ac5d7cb
	.long	0x15efe6e8
	.long	0x1ce1ede5
	.long	0x07f3f0f2
	.long	0x0efdfbff
	.long	0x79a792b4
	.long	0x70a999b9
	.long	0x6bbb84ae
	.long	0x62b58fa3
	.long	0x5d9fbe80
	.long	0x5491b58d
	.long	0x4f83a89a
	.long	0x468da397
	// Table 3.
	.long	0x00000000
	.long	0x0e0b0d09
	.long	0x1c161a12
	.long	0x121d171b
	.long	0x382c3424
	.long	0x3627392d
	.long	0x243a2e36
	.long	0x2a31233f
	.long	0x70586848
	.long	0x7e536541
	.long	0x6c4e725a
	.long	0x62457f53
	.long	0x48745c6c
	.long	0x467f5165
	.long	0x5462467e
	.long	0x5a694b77
	.long	0xe0b0d090
	.long	0xeebbdd99
	.long	0xfca6ca82
	.long	0xf2adc78b
	.long	0xd89ce4b4
	.long	0xd697e9bd
	.long	0xc48afea6
	.long	0xca81f3af
	.long	0x90e8b8d8
	.long	0x9ee3b5d1
	.long	0x8cfea2ca
	.long	0x82f5afc3
	.long	0xa8c48cfc
	.long	0xa6cf81f5
	.long	0xb4d296ee
	.long	0xbad99be7
	.long	0xdb7bbb3b
	.long	0xd570b632
	.long	0xc76da129
	.long	0xc966ac20
	.long	0xe3578f1f
	.long	0xed5c8216
	.long	0xff41950d
	.long	0xf14a9804
	.long	0xab23d373
	.long	0xa528de7a
	.long	0xb735c961
	.long	0xb93ec468
	.long	0x930fe757
	.long	0x9d04ea5e
	.long	0x8f19fd45
	.long	0x8112f04c
	.long	0x3bcb6bab
	.long	0x35c066a2
	.long	0x27dd71b9
	.long	0x29d67cb0
	.long	0x03e75f8f
	.long	0x0dec5286
	.long	0x1ff1459d
	.long	0x11fa4894
	.long	0x4b9303e3
	.long	0x45980eea
	.long	0x578519f1
	.long	0x598e14f8
	.long	0x73bf37c7
	.long	0x7db43ace
	.long	0x6fa92dd5
	.long	0x61a220dc
	.long	0xadf66d76
	.long	0xa3fd607f
	.long	0xb1e07764
	.long	0xbfeb7a6d
	.long	0x95da5952
	.long	0x9bd1545b
	.long	0x89cc4340
	.long	0x87c74e49
	.long	0xddae053e
	.long	0xd3a50837
	.long	0xc1b81f2c
	.long	0xcfb31225
	.long	0xe582311a
	.long	0xeb893c13
	.long	0xf9942b08
	.long	0xf79f2601
	.long	0x4d46bde6
	.long	0x434db0ef
	.long	0x5150a7f4
	.long	0x5f5baafd
	.long	0x756a89c2
	.long	0x7b6184cb
	.long	0x697c93d0
	.long	0x67779ed9
	.long	0x3d1ed5ae
	.long	0x3315d8a7
	.long	0x2108cfbc
	.long	0x2f03c2b5
	.long	0x0532e18a
	.long	0x0b39ec83
	.long	0x1924fb98
	.long	0x172ff691
	.long	0x768dd64d
	.long	0x7886db44
	.long	0x6a9bcc5f
	.long	0x6490c156
	.long	0x4ea1e269
	.long	0x40aaef60
	.long	0x52b7f87b
	.long	0x5cbcf572
	.long	0x06d5be05
	.long	0x08deb30c
	.long	0x1ac3a417
	.long	0x14c8a91e
	.long	0x3ef98a21
	.long	0x30f28728
	.long	0x22ef9033
	.long	0x2ce49d3a
	.long	0x963d06dd
	.long	0x98360bd4
	.long	0x8a2b1ccf
	.long	0x842011c6
	.long	0xae1132f9
	.long	0xa01a3ff0
	.long	0xb20728eb
	.long	0xbc0c25e2
	.long	0xe6656e95
	.long	0xe86e639c
	.long	0xfa737487
	.long	0xf478798e
	.long	0xde495ab1
	.long	0xd04257b8
	.long	0xc25f40a3
	.long	0xcc544daa
	.long	0x41f7daec
	.long	0x4ffcd7e5
	.long	0x5de1c0fe
	.long	0x53eacdf7
	.long	0x79dbeec8
	.long	0x77d0e3c1
	.long	0x65cdf4da
	.long	0x6bc6f9d3
	.long	0x31afb2a4
	.long	0x3fa4bfad
	.long	0x2db9a8b6
	.long	0x23b2a5bf
	.long	0x09838680
	.long	0x07888b89
	.long	0x15959c92
	.long	0x1b9e919b
	.long	0xa1470a7c
	.long	0xaf4c0775
	.long	0xbd51106e
	.long	0xb35a1d67
	.long	0x996b3e58
	.long	0x97603351
	.long	0x857d244a
	.long	0x8b762943
	.long	0xd11f6234
	.long	0xdf146f3d
	.long	0xcd097826
	.long	0xc302752f
	.long	0xe9335610
	.long	0xe7385b19
	.long	0xf5254c02
	.long	0xfb2e410b
	.long	0x9a8c61d7
	.long	0x94876cde
	.long	0x869a7bc5
	.long	0x889176cc
	.long	0xa2a055f3
	.long	0xacab58fa
	.long	0xbeb64fe1
	.long	0xb0bd42e8
	.long	0xead4099f
	.long	0xe4df0496
	.long	0xf6c2138d
	.long	0xf8c91e84
	.long	0xd2f83dbb
	.long	0xdcf330b2
	.long	0xceee27a9
	.long	0xc0e52aa0
	.long	0x7a3cb147
	.long	0x7437bc4e
	.long	0x662aab55
	.long	0x6821a65c
	.long	0x42108563
	.long	0x4c1b886a
	.long	0x5e069f71
	.long	0x500d9278
	.long	0x0a64d90f
	.long	0x046fd406
	.long	0x1672c31d
	.long	0x1879ce14
	.long	0x3248ed2b
	.long	0x3c43e022
	.long	0x2e5ef739
	.long	0x2055fa30
	.long	0xec01b79a
	.long	0xe20aba93
	.long	0xf017ad88
	.long	0xfe1ca081
	.long	0xd42d83be
	.long	0xda268eb7
	.long	0xc83b99ac
	.long	0xc63094a5
	.long	0x9c59dfd2
	.long	0x9252d2db
	.long	0x804fc5c0
	.long	0x8e44c8c9
	.long	0xa475ebf6
	.long	0xaa7ee6ff
	.long	0xb863f1e4
	.long	0xb668fced
	.long	0x0cb1670a
	.long	0x02ba6a03
	.long	0x10a77d18
	.long	0x1eac7011
	.long	0x349d532e
	.long	0x3a965e27
	.long	0x288b493c
	.long	0x26804435
	.long	0x7ce90f42
	.long	0x72e2024b
	.long	0x60ff1550
	.long	0x6ef41859
	.long	0x44c53b66
	.long	0x4ace366f
	.long	0x58d32174
	.long	0x56d82c7d
	.long	0x377a0ca1
	.long	0x397101a8
	.long	0x2b6c16b3
	.long	0x25671bba
	.long	0x0f563885
	.long	0x015d358c
	.long	0x13402297
	.long	0x1d4b2f9e
	.long	0x472264e9
	.long	0x492969e0
	.long	0x5b347efb
	.long	0x553f73f2
	.long	0x7f0e50cd
	.long	0x71055dc4
	.long	0x63184adf
	.long	0x6d1347d6
	.long	0xd7cadc31
	.long	0xd9c1d138
	.long	0xcbdcc623
	.long	0xc5d7cb2a
	.long	0xefe6e815
	.long	0xe1ede51c
	.long	0xf3f0f207
	.long	0xfdfbff0e
	.long	0xa792b479
	.long	0xa999b970
	.long	0xbb84ae6b
	.long	0xb58fa362
	.long	0x9fbe805d
	.long	0x91b58d54
	.long	0x83a89a4f
	.long	0x8da39746


// Tables for main encryption iterations.
	.globl	_AESEncryptTable
	.private_extern	_AESEncryptTable
	.align	2
_AESEncryptTable:
	// Table 0.
	.long	0xa56363c6
	.long	0x847c7cf8
	.long	0x997777ee
	.long	0x8d7b7bf6
	.long	0x0df2f2ff
	.long	0xbd6b6bd6
	.long	0xb16f6fde
	.long	0x54c5c591
	.long	0x50303060
	.long	0x03010102
	.long	0xa96767ce
	.long	0x7d2b2b56
	.long	0x19fefee7
	.long	0x62d7d7b5
	.long	0xe6abab4d
	.long	0x9a7676ec
	.long	0x45caca8f
	.long	0x9d82821f
	.long	0x40c9c989
	.long	0x877d7dfa
	.long	0x15fafaef
	.long	0xeb5959b2
	.long	0xc947478e
	.long	0x0bf0f0fb
	.long	0xecadad41
	.long	0x67d4d4b3
	.long	0xfda2a25f
	.long	0xeaafaf45
	.long	0xbf9c9c23
	.long	0xf7a4a453
	.long	0x967272e4
	.long	0x5bc0c09b
	.long	0xc2b7b775
	.long	0x1cfdfde1
	.long	0xae93933d
	.long	0x6a26264c
	.long	0x5a36366c
	.long	0x413f3f7e
	.long	0x02f7f7f5
	.long	0x4fcccc83
	.long	0x5c343468
	.long	0xf4a5a551
	.long	0x34e5e5d1
	.long	0x08f1f1f9
	.long	0x937171e2
	.long	0x73d8d8ab
	.long	0x53313162
	.long	0x3f15152a
	.long	0x0c040408
	.long	0x52c7c795
	.long	0x65232346
	.long	0x5ec3c39d
	.long	0x28181830
	.long	0xa1969637
	.long	0x0f05050a
	.long	0xb59a9a2f
	.long	0x0907070e
	.long	0x36121224
	.long	0x9b80801b
	.long	0x3de2e2df
	.long	0x26ebebcd
	.long	0x6927274e
	.long	0xcdb2b27f
	.long	0x9f7575ea
	.long	0x1b090912
	.long	0x9e83831d
	.long	0x742c2c58
	.long	0x2e1a1a34
	.long	0x2d1b1b36
	.long	0xb26e6edc
	.long	0xee5a5ab4
	.long	0xfba0a05b
	.long	0xf65252a4
	.long	0x4d3b3b76
	.long	0x61d6d6b7
	.long	0xceb3b37d
	.long	0x7b292952
	.long	0x3ee3e3dd
	.long	0x712f2f5e
	.long	0x97848413
	.long	0xf55353a6
	.long	0x68d1d1b9
	.long	0x00000000
	.long	0x2cededc1
	.long	0x60202040
	.long	0x1ffcfce3
	.long	0xc8b1b179
	.long	0xed5b5bb6
	.long	0xbe6a6ad4
	.long	0x46cbcb8d
	.long	0xd9bebe67
	.long	0x4b393972
	.long	0xde4a4a94
	.long	0xd44c4c98
	.long	0xe85858b0
	.long	0x4acfcf85
	.long	0x6bd0d0bb
	.long	0x2aefefc5
	.long	0xe5aaaa4f
	.long	0x16fbfbed
	.long	0xc5434386
	.long	0xd74d4d9a
	.long	0x55333366
	.long	0x94858511
	.long	0xcf45458a
	.long	0x10f9f9e9
	.long	0x06020204
	.long	0x817f7ffe
	.long	0xf05050a0
	.long	0x443c3c78
	.long	0xba9f9f25
	.long	0xe3a8a84b
	.long	0xf35151a2
	.long	0xfea3a35d
	.long	0xc0404080
	.long	0x8a8f8f05
	.long	0xad92923f
	.long	0xbc9d9d21
	.long	0x48383870
	.long	0x04f5f5f1
	.long	0xdfbcbc63
	.long	0xc1b6b677
	.long	0x75dadaaf
	.long	0x63212142
	.long	0x30101020
	.long	0x1affffe5
	.long	0x0ef3f3fd
	.long	0x6dd2d2bf
	.long	0x4ccdcd81
	.long	0x140c0c18
	.long	0x35131326
	.long	0x2fececc3
	.long	0xe15f5fbe
	.long	0xa2979735
	.long	0xcc444488
	.long	0x3917172e
	.long	0x57c4c493
	.long	0xf2a7a755
	.long	0x827e7efc
	.long	0x473d3d7a
	.long	0xac6464c8
	.long	0xe75d5dba
	.long	0x2b191932
	.long	0x957373e6
	.long	0xa06060c0
	.long	0x98818119
	.long	0xd14f4f9e
	.long	0x7fdcdca3
	.long	0x66222244
	.long	0x7e2a2a54
	.long	0xab90903b
	.long	0x8388880b
	.long	0xca46468c
	.long	0x29eeeec7
	.long	0xd3b8b86b
	.long	0x3c141428
	.long	0x79dedea7
	.long	0xe25e5ebc
	.long	0x1d0b0b16
	.long	0x76dbdbad
	.long	0x3be0e0db
	.long	0x56323264
	.long	0x4e3a3a74
	.long	0x1e0a0a14
	.long	0xdb494992
	.long	0x0a06060c
	.long	0x6c242448
	.long	0xe45c5cb8
	.long	0x5dc2c29f
	.long	0x6ed3d3bd
	.long	0xefacac43
	.long	0xa66262c4
	.long	0xa8919139
	.long	0xa4959531
	.long	0x37e4e4d3
	.long	0x8b7979f2
	.long	0x32e7e7d5
	.long	0x43c8c88b
	.long	0x5937376e
	.long	0xb76d6dda
	.long	0x8c8d8d01
	.long	0x64d5d5b1
	.long	0xd24e4e9c
	.long	0xe0a9a949
	.long	0xb46c6cd8
	.long	0xfa5656ac
	.long	0x07f4f4f3
	.long	0x25eaeacf
	.long	0xaf6565ca
	.long	0x8e7a7af4
	.long	0xe9aeae47
	.long	0x18080810
	.long	0xd5baba6f
	.long	0x887878f0
	.long	0x6f25254a
	.long	0x722e2e5c
	.long	0x241c1c38
	.long	0xf1a6a657
	.long	0xc7b4b473
	.long	0x51c6c697
	.long	0x23e8e8cb
	.long	0x7cdddda1
	.long	0x9c7474e8
	.long	0x211f1f3e
	.long	0xdd4b4b96
	.long	0xdcbdbd61
	.long	0x868b8b0d
	.long	0x858a8a0f
	.long	0x907070e0
	.long	0x423e3e7c
	.long	0xc4b5b571
	.long	0xaa6666cc
	.long	0xd8484890
	.long	0x05030306
	.long	0x01f6f6f7
	.long	0x120e0e1c
	.long	0xa36161c2
	.long	0x5f35356a
	.long	0xf95757ae
	.long	0xd0b9b969
	.long	0x91868617
	.long	0x58c1c199
	.long	0x271d1d3a
	.long	0xb99e9e27
	.long	0x38e1e1d9
	.long	0x13f8f8eb
	.long	0xb398982b
	.long	0x33111122
	.long	0xbb6969d2
	.long	0x70d9d9a9
	.long	0x898e8e07
	.long	0xa7949433
	.long	0xb69b9b2d
	.long	0x221e1e3c
	.long	0x92878715
	.long	0x20e9e9c9
	.long	0x49cece87
	.long	0xff5555aa
	.long	0x78282850
	.long	0x7adfdfa5
	.long	0x8f8c8c03
	.long	0xf8a1a159
	.long	0x80898909
	.long	0x170d0d1a
	.long	0xdabfbf65
	.long	0x31e6e6d7
	.long	0xc6424284
	.long	0xb86868d0
	.long	0xc3414182
	.long	0xb0999929
	.long	0x772d2d5a
	.long	0x110f0f1e
	.long	0xcbb0b07b
	.long	0xfc5454a8
	.long	0xd6bbbb6d
	.long	0x3a16162c
	// Table 1.
	.long	0x6363c6a5
	.long	0x7c7cf884
	.long	0x7777ee99
	.long	0x7b7bf68d
	.long	0xf2f2ff0d
	.long	0x6b6bd6bd
	.long	0x6f6fdeb1
	.long	0xc5c59154
	.long	0x30306050
	.long	0x01010203
	.long	0x6767cea9
	.long	0x2b2b567d
	.long	0xfefee719
	.long	0xd7d7b562
	.long	0xabab4de6
	.long	0x7676ec9a
	.long	0xcaca8f45
	.long	0x82821f9d
	.long	0xc9c98940
	.long	0x7d7dfa87
	.long	0xfafaef15
	.long	0x5959b2eb
	.long	0x47478ec9
	.long	0xf0f0fb0b
	.long	0xadad41ec
	.long	0xd4d4b367
	.long	0xa2a25ffd
	.long	0xafaf45ea
	.long	0x9c9c23bf
	.long	0xa4a453f7
	.long	0x7272e496
	.long	0xc0c09b5b
	.long	0xb7b775c2
	.long	0xfdfde11c
	.long	0x93933dae
	.long	0x26264c6a
	.long	0x36366c5a
	.long	0x3f3f7e41
	.long	0xf7f7f502
	.long	0xcccc834f
	.long	0x3434685c
	.long	0xa5a551f4
	.long	0xe5e5d134
	.long	0xf1f1f908
	.long	0x7171e293
	.long	0xd8d8ab73
	.long	0x31316253
	.long	0x15152a3f
	.long	0x0404080c
	.long	0xc7c79552
	.long	0x23234665
	.long	0xc3c39d5e
	.long	0x18183028
	.long	0x969637a1
	.long	0x05050a0f
	.long	0x9a9a2fb5
	.long	0x07070e09
	.long	0x12122436
	.long	0x80801b9b
	.long	0xe2e2df3d
	.long	0xebebcd26
	.long	0x27274e69
	.long	0xb2b27fcd
	.long	0x7575ea9f
	.long	0x0909121b
	.long	0x83831d9e
	.long	0x2c2c5874
	.long	0x1a1a342e
	.long	0x1b1b362d
	.long	0x6e6edcb2
	.long	0x5a5ab4ee
	.long	0xa0a05bfb
	.long	0x5252a4f6
	.long	0x3b3b764d
	.long	0xd6d6b761
	.long	0xb3b37dce
	.long	0x2929527b
	.long	0xe3e3dd3e
	.long	0x2f2f5e71
	.long	0x84841397
	.long	0x5353a6f5
	.long	0xd1d1b968
	.long	0x00000000
	.long	0xededc12c
	.long	0x20204060
	.long	0xfcfce31f
	.long	0xb1b179c8
	.long	0x5b5bb6ed
	.long	0x6a6ad4be
	.long	0xcbcb8d46
	.long	0xbebe67d9
	.long	0x3939724b
	.long	0x4a4a94de
	.long	0x4c4c98d4
	.long	0x5858b0e8
	.long	0xcfcf854a
	.long	0xd0d0bb6b
	.long	0xefefc52a
	.long	0xaaaa4fe5
	.long	0xfbfbed16
	.long	0x434386c5
	.long	0x4d4d9ad7
	.long	0x33336655
	.long	0x85851194
	.long	0x45458acf
	.long	0xf9f9e910
	.long	0x02020406
	.long	0x7f7ffe81
	.long	0x5050a0f0
	.long	0x3c3c7844
	.long	0x9f9f25ba
	.long	0xa8a84be3
	.long	0x5151a2f3
	.long	0xa3a35dfe
	.long	0x404080c0
	.long	0x8f8f058a
	.long	0x92923fad
	.long	0x9d9d21bc
	.long	0x38387048
	.long	0xf5f5f104
	.long	0xbcbc63df
	.long	0xb6b677c1
	.long	0xdadaaf75
	.long	0x21214263
	.long	0x10102030
	.long	0xffffe51a
	.long	0xf3f3fd0e
	.long	0xd2d2bf6d
	.long	0xcdcd814c
	.long	0x0c0c1814
	.long	0x13132635
	.long	0xececc32f
	.long	0x5f5fbee1
	.long	0x979735a2
	.long	0x444488cc
	.long	0x17172e39
	.long	0xc4c49357
	.long	0xa7a755f2
	.long	0x7e7efc82
	.long	0x3d3d7a47
	.long	0x6464c8ac
	.long	0x5d5dbae7
	.long	0x1919322b
	.long	0x7373e695
	.long	0x6060c0a0
	.long	0x81811998
	.long	0x4f4f9ed1
	.long	0xdcdca37f
	.long	0x22224466
	.long	0x2a2a547e
	.long	0x90903bab
	.long	0x88880b83
	.long	0x46468cca
	.long	0xeeeec729
	.long	0xb8b86bd3
	.long	0x1414283c
	.long	0xdedea779
	.long	0x5e5ebce2
	.long	0x0b0b161d
	.long	0xdbdbad76
	.long	0xe0e0db3b
	.long	0x32326456
	.long	0x3a3a744e
	.long	0x0a0a141e
	.long	0x494992db
	.long	0x06060c0a
	.long	0x2424486c
	.long	0x5c5cb8e4
	.long	0xc2c29f5d
	.long	0xd3d3bd6e
	.long	0xacac43ef
	.long	0x6262c4a6
	.long	0x919139a8
	.long	0x959531a4
	.long	0xe4e4d337
	.long	0x7979f28b
	.long	0xe7e7d532
	.long	0xc8c88b43
	.long	0x37376e59
	.long	0x6d6ddab7
	.long	0x8d8d018c
	.long	0xd5d5b164
	.long	0x4e4e9cd2
	.long	0xa9a949e0
	.long	0x6c6cd8b4
	.long	0x5656acfa
	.long	0xf4f4f307
	.long	0xeaeacf25
	.long	0x6565caaf
	.long	0x7a7af48e
	.long	0xaeae47e9
	.long	0x08081018
	.long	0xbaba6fd5
	.long	0x7878f088
	.long	0x25254a6f
	.long	0x2e2e5c72
	.long	0x1c1c3824
	.long	0xa6a657f1
	.long	0xb4b473c7
	.long	0xc6c69751
	.long	0xe8e8cb23
	.long	0xdddda17c
	.long	0x7474e89c
	.long	0x1f1f3e21
	.long	0x4b4b96dd
	.long	0xbdbd61dc
	.long	0x8b8b0d86
	.long	0x8a8a0f85
	.long	0x7070e090
	.long	0x3e3e7c42
	.long	0xb5b571c4
	.long	0x6666ccaa
	.long	0x484890d8
	.long	0x03030605
	.long	0xf6f6f701
	.long	0x0e0e1c12
	.long	0x6161c2a3
	.long	0x35356a5f
	.long	0x5757aef9
	.long	0xb9b969d0
	.long	0x86861791
	.long	0xc1c19958
	.long	0x1d1d3a27
	.long	0x9e9e27b9
	.long	0xe1e1d938
	.long	0xf8f8eb13
	.long	0x98982bb3
	.long	0x11112233
	.long	0x6969d2bb
	.long	0xd9d9a970
	.long	0x8e8e0789
	.long	0x949433a7
	.long	0x9b9b2db6
	.long	0x1e1e3c22
	.long	0x87871592
	.long	0xe9e9c920
	.long	0xcece8749
	.long	0x5555aaff
	.long	0x28285078
	.long	0xdfdfa57a
	.long	0x8c8c038f
	.long	0xa1a159f8
	.long	0x89890980
	.long	0x0d0d1a17
	.long	0xbfbf65da
	.long	0xe6e6d731
	.long	0x424284c6
	.long	0x6868d0b8
	.long	0x414182c3
	.long	0x999929b0
	.long	0x2d2d5a77
	.long	0x0f0f1e11
	.long	0xb0b07bcb
	.long	0x5454a8fc
	.long	0xbbbb6dd6
	.long	0x16162c3a
	// Table 2.
	.long	0x63c6a563
	.long	0x7cf8847c
	.long	0x77ee9977
	.long	0x7bf68d7b
	.long	0xf2ff0df2
	.long	0x6bd6bd6b
	.long	0x6fdeb16f
	.long	0xc59154c5
	.long	0x30605030
	.long	0x01020301
	.long	0x67cea967
	.long	0x2b567d2b
	.long	0xfee719fe
	.long	0xd7b562d7
	.long	0xab4de6ab
	.long	0x76ec9a76
	.long	0xca8f45ca
	.long	0x821f9d82
	.long	0xc98940c9
	.long	0x7dfa877d
	.long	0xfaef15fa
	.long	0x59b2eb59
	.long	0x478ec947
	.long	0xf0fb0bf0
	.long	0xad41ecad
	.long	0xd4b367d4
	.long	0xa25ffda2
	.long	0xaf45eaaf
	.long	0x9c23bf9c
	.long	0xa453f7a4
	.long	0x72e49672
	.long	0xc09b5bc0
	.long	0xb775c2b7
	.long	0xfde11cfd
	.long	0x933dae93
	.long	0x264c6a26
	.long	0x366c5a36
	.long	0x3f7e413f
	.long	0xf7f502f7
	.long	0xcc834fcc
	.long	0x34685c34
	.long	0xa551f4a5
	.long	0xe5d134e5
	.long	0xf1f908f1
	.long	0x71e29371
	.long	0xd8ab73d8
	.long	0x31625331
	.long	0x152a3f15
	.long	0x04080c04
	.long	0xc79552c7
	.long	0x23466523
	.long	0xc39d5ec3
	.long	0x18302818
	.long	0x9637a196
	.long	0x050a0f05
	.long	0x9a2fb59a
	.long	0x070e0907
	.long	0x12243612
	.long	0x801b9b80
	.long	0xe2df3de2
	.long	0xebcd26eb
	.long	0x274e6927
	.long	0xb27fcdb2
	.long	0x75ea9f75
	.long	0x09121b09
	.long	0x831d9e83
	.long	0x2c58742c
	.long	0x1a342e1a
	.long	0x1b362d1b
	.long	0x6edcb26e
	.long	0x5ab4ee5a
	.long	0xa05bfba0
	.long	0x52a4f652
	.long	0x3b764d3b
	.long	0xd6b761d6
	.long	0xb37dceb3
	.long	0x29527b29
	.long	0xe3dd3ee3
	.long	0x2f5e712f
	.long	0x84139784
	.long	0x53a6f553
	.long	0xd1b968d1
	.long	0x00000000
	.long	0xedc12ced
	.long	0x20406020
	.long	0xfce31ffc
	.long	0xb179c8b1
	.long	0x5bb6ed5b
	.long	0x6ad4be6a
	.long	0xcb8d46cb
	.long	0xbe67d9be
	.long	0x39724b39
	.long	0x4a94de4a
	.long	0x4c98d44c
	.long	0x58b0e858
	.long	0xcf854acf
	.long	0xd0bb6bd0
	.long	0xefc52aef
	.long	0xaa4fe5aa
	.long	0xfbed16fb
	.long	0x4386c543
	.long	0x4d9ad74d
	.long	0x33665533
	.long	0x85119485
	.long	0x458acf45
	.long	0xf9e910f9
	.long	0x02040602
	.long	0x7ffe817f
	.long	0x50a0f050
	.long	0x3c78443c
	.long	0x9f25ba9f
	.long	0xa84be3a8
	.long	0x51a2f351
	.long	0xa35dfea3
	.long	0x4080c040
	.long	0x8f058a8f
	.long	0x923fad92
	.long	0x9d21bc9d
	.long	0x38704838
	.long	0xf5f104f5
	.long	0xbc63dfbc
	.long	0xb677c1b6
	.long	0xdaaf75da
	.long	0x21426321
	.long	0x10203010
	.long	0xffe51aff
	.long	0xf3fd0ef3
	.long	0xd2bf6dd2
	.long	0xcd814ccd
	.long	0x0c18140c
	.long	0x13263513
	.long	0xecc32fec
	.long	0x5fbee15f
	.long	0x9735a297
	.long	0x4488cc44
	.long	0x172e3917
	.long	0xc49357c4
	.long	0xa755f2a7
	.long	0x7efc827e
	.long	0x3d7a473d
	.long	0x64c8ac64
	.long	0x5dbae75d
	.long	0x19322b19
	.long	0x73e69573
	.long	0x60c0a060
	.long	0x81199881
	.long	0x4f9ed14f
	.long	0xdca37fdc
	.long	0x22446622
	.long	0x2a547e2a
	.long	0x903bab90
	.long	0x880b8388
	.long	0x468cca46
	.long	0xeec729ee
	.long	0xb86bd3b8
	.long	0x14283c14
	.long	0xdea779de
	.long	0x5ebce25e
	.long	0x0b161d0b
	.long	0xdbad76db
	.long	0xe0db3be0
	.long	0x32645632
	.long	0x3a744e3a
	.long	0x0a141e0a
	.long	0x4992db49
	.long	0x060c0a06
	.long	0x24486c24
	.long	0x5cb8e45c
	.long	0xc29f5dc2
	.long	0xd3bd6ed3
	.long	0xac43efac
	.long	0x62c4a662
	.long	0x9139a891
	.long	0x9531a495
	.long	0xe4d337e4
	.long	0x79f28b79
	.long	0xe7d532e7
	.long	0xc88b43c8
	.long	0x376e5937
	.long	0x6ddab76d
	.long	0x8d018c8d
	.long	0xd5b164d5
	.long	0x4e9cd24e
	.long	0xa949e0a9
	.long	0x6cd8b46c
	.long	0x56acfa56
	.long	0xf4f307f4
	.long	0xeacf25ea
	.long	0x65caaf65
	.long	0x7af48e7a
	.long	0xae47e9ae
	.long	0x08101808
	.long	0xba6fd5ba
	.long	0x78f08878
	.long	0x254a6f25
	.long	0x2e5c722e
	.long	0x1c38241c
	.long	0xa657f1a6
	.long	0xb473c7b4
	.long	0xc69751c6
	.long	0xe8cb23e8
	.long	0xdda17cdd
	.long	0x74e89c74
	.long	0x1f3e211f
	.long	0x4b96dd4b
	.long	0xbd61dcbd
	.long	0x8b0d868b
	.long	0x8a0f858a
	.long	0x70e09070
	.long	0x3e7c423e
	.long	0xb571c4b5
	.long	0x66ccaa66
	.long	0x4890d848
	.long	0x03060503
	.long	0xf6f701f6
	.long	0x0e1c120e
	.long	0x61c2a361
	.long	0x356a5f35
	.long	0x57aef957
	.long	0xb969d0b9
	.long	0x86179186
	.long	0xc19958c1
	.long	0x1d3a271d
	.long	0x9e27b99e
	.long	0xe1d938e1
	.long	0xf8eb13f8
	.long	0x982bb398
	.long	0x11223311
	.long	0x69d2bb69
	.long	0xd9a970d9
	.long	0x8e07898e
	.long	0x9433a794
	.long	0x9b2db69b
	.long	0x1e3c221e
	.long	0x87159287
	.long	0xe9c920e9
	.long	0xce8749ce
	.long	0x55aaff55
	.long	0x28507828
	.long	0xdfa57adf
	.long	0x8c038f8c
	.long	0xa159f8a1
	.long	0x89098089
	.long	0x0d1a170d
	.long	0xbf65dabf
	.long	0xe6d731e6
	.long	0x4284c642
	.long	0x68d0b868
	.long	0x4182c341
	.long	0x9929b099
	.long	0x2d5a772d
	.long	0x0f1e110f
	.long	0xb07bcbb0
	.long	0x54a8fc54
	.long	0xbb6dd6bb
	.long	0x162c3a16
	// Table 3.
	.long	0xc6a56363
	.long	0xf8847c7c
	.long	0xee997777
	.long	0xf68d7b7b
	.long	0xff0df2f2
	.long	0xd6bd6b6b
	.long	0xdeb16f6f
	.long	0x9154c5c5
	.long	0x60503030
	.long	0x02030101
	.long	0xcea96767
	.long	0x567d2b2b
	.long	0xe719fefe
	.long	0xb562d7d7
	.long	0x4de6abab
	.long	0xec9a7676
	.long	0x8f45caca
	.long	0x1f9d8282
	.long	0x8940c9c9
	.long	0xfa877d7d
	.long	0xef15fafa
	.long	0xb2eb5959
	.long	0x8ec94747
	.long	0xfb0bf0f0
	.long	0x41ecadad
	.long	0xb367d4d4
	.long	0x5ffda2a2
	.long	0x45eaafaf
	.long	0x23bf9c9c
	.long	0x53f7a4a4
	.long	0xe4967272
	.long	0x9b5bc0c0
	.long	0x75c2b7b7
	.long	0xe11cfdfd
	.long	0x3dae9393
	.long	0x4c6a2626
	.long	0x6c5a3636
	.long	0x7e413f3f
	.long	0xf502f7f7
	.long	0x834fcccc
	.long	0x685c3434
	.long	0x51f4a5a5
	.long	0xd134e5e5
	.long	0xf908f1f1
	.long	0xe2937171
	.long	0xab73d8d8
	.long	0x62533131
	.long	0x2a3f1515
	.long	0x080c0404
	.long	0x9552c7c7
	.long	0x46652323
	.long	0x9d5ec3c3
	.long	0x30281818
	.long	0x37a19696
	.long	0x0a0f0505
	.long	0x2fb59a9a
	.long	0x0e090707
	.long	0x24361212
	.long	0x1b9b8080
	.long	0xdf3de2e2
	.long	0xcd26ebeb
	.long	0x4e692727
	.long	0x7fcdb2b2
	.long	0xea9f7575
	.long	0x121b0909
	.long	0x1d9e8383
	.long	0x58742c2c
	.long	0x342e1a1a
	.long	0x362d1b1b
	.long	0xdcb26e6e
	.long	0xb4ee5a5a
	.long	0x5bfba0a0
	.long	0xa4f65252
	.long	0x764d3b3b
	.long	0xb761d6d6
	.long	0x7dceb3b3
	.long	0x527b2929
	.long	0xdd3ee3e3
	.long	0x5e712f2f
	.long	0x13978484
	.long	0xa6f55353
	.long	0xb968d1d1
	.long	0x00000000
	.long	0xc12ceded
	.long	0x40602020
	.long	0xe31ffcfc
	.long	0x79c8b1b1
	.long	0xb6ed5b5b
	.long	0xd4be6a6a
	.long	0x8d46cbcb
	.long	0x67d9bebe
	.long	0x724b3939
	.long	0x94de4a4a
	.long	0x98d44c4c
	.long	0xb0e85858
	.long	0x854acfcf
	.long	0xbb6bd0d0
	.long	0xc52aefef
	.long	0x4fe5aaaa
	.long	0xed16fbfb
	.long	0x86c54343
	.long	0x9ad74d4d
	.long	0x66553333
	.long	0x11948585
	.long	0x8acf4545
	.long	0xe910f9f9
	.long	0x04060202
	.long	0xfe817f7f
	.long	0xa0f05050
	.long	0x78443c3c
	.long	0x25ba9f9f
	.long	0x4be3a8a8
	.long	0xa2f35151
	.long	0x5dfea3a3
	.long	0x80c04040
	.long	0x058a8f8f
	.long	0x3fad9292
	.long	0x21bc9d9d
	.long	0x70483838
	.long	0xf104f5f5
	.long	0x63dfbcbc
	.long	0x77c1b6b6
	.long	0xaf75dada
	.long	0x42632121
	.long	0x20301010
	.long	0xe51affff
	.long	0xfd0ef3f3
	.long	0xbf6dd2d2
	.long	0x814ccdcd
	.long	0x18140c0c
	.long	0x26351313
	.long	0xc32fecec
	.long	0xbee15f5f
	.long	0x35a29797
	.long	0x88cc4444
	.long	0x2e391717
	.long	0x9357c4c4
	.long	0x55f2a7a7
	.long	0xfc827e7e
	.long	0x7a473d3d
	.long	0xc8ac6464
	.long	0xbae75d5d
	.long	0x322b1919
	.long	0xe6957373
	.long	0xc0a06060
	.long	0x19988181
	.long	0x9ed14f4f
	.long	0xa37fdcdc
	.long	0x44662222
	.long	0x547e2a2a
	.long	0x3bab9090
	.long	0x0b838888
	.long	0x8cca4646
	.long	0xc729eeee
	.long	0x6bd3b8b8
	.long	0x283c1414
	.long	0xa779dede
	.long	0xbce25e5e
	.long	0x161d0b0b
	.long	0xad76dbdb
	.long	0xdb3be0e0
	.long	0x64563232
	.long	0x744e3a3a
	.long	0x141e0a0a
	.long	0x92db4949
	.long	0x0c0a0606
	.long	0x486c2424
	.long	0xb8e45c5c
	.long	0x9f5dc2c2
	.long	0xbd6ed3d3
	.long	0x43efacac
	.long	0xc4a66262
	.long	0x39a89191
	.long	0x31a49595
	.long	0xd337e4e4
	.long	0xf28b7979
	.long	0xd532e7e7
	.long	0x8b43c8c8
	.long	0x6e593737
	.long	0xdab76d6d
	.long	0x018c8d8d
	.long	0xb164d5d5
	.long	0x9cd24e4e
	.long	0x49e0a9a9
	.long	0xd8b46c6c
	.long	0xacfa5656
	.long	0xf307f4f4
	.long	0xcf25eaea
	.long	0xcaaf6565
	.long	0xf48e7a7a
	.long	0x47e9aeae
	.long	0x10180808
	.long	0x6fd5baba
	.long	0xf0887878
	.long	0x4a6f2525
	.long	0x5c722e2e
	.long	0x38241c1c
	.long	0x57f1a6a6
	.long	0x73c7b4b4
	.long	0x9751c6c6
	.long	0xcb23e8e8
	.long	0xa17cdddd
	.long	0xe89c7474
	.long	0x3e211f1f
	.long	0x96dd4b4b
	.long	0x61dcbdbd
	.long	0x0d868b8b
	.long	0x0f858a8a
	.long	0xe0907070
	.long	0x7c423e3e
	.long	0x71c4b5b5
	.long	0xccaa6666
	.long	0x90d84848
	.long	0x06050303
	.long	0xf701f6f6
	.long	0x1c120e0e
	.long	0xc2a36161
	.long	0x6a5f3535
	.long	0xaef95757
	.long	0x69d0b9b9
	.long	0x17918686
	.long	0x9958c1c1
	.long	0x3a271d1d
	.long	0x27b99e9e
	.long	0xd938e1e1
	.long	0xeb13f8f8
	.long	0x2bb39898
	.long	0x22331111
	.long	0xd2bb6969
	.long	0xa970d9d9
	.long	0x07898e8e
	.long	0x33a79494
	.long	0x2db69b9b
	.long	0x3c221e1e
	.long	0x15928787
	.long	0xc920e9e9
	.long	0x8749cece
	.long	0xaaff5555
	.long	0x50782828
	.long	0xa57adfdf
	.long	0x038f8c8c
	.long	0x59f8a1a1
	.long	0x09808989
	.long	0x1a170d0d
	.long	0x65dabfbf
	.long	0xd731e6e6
	.long	0x84c64242
	.long	0xd0b86868
	.long	0x82c34141
	.long	0x29b09999
	.long	0x5a772d2d
	.long	0x1e110f0f
	.long	0x7bcbb0b0
	.long	0xa8fc5454
	.long	0x6dd6bbbb
	.long	0x2c3a1616


// Tables for main decryption iterations.
	.globl	_AESDecryptTable
	.private_extern	_AESDecryptTable
	.align	2
_AESDecryptTable:
	// Table 0.
	.long	0x50a7f451
	.long	0x5365417e
	.long	0xc3a4171a
	.long	0x965e273a
	.long	0xcb6bab3b
	.long	0xf1459d1f
	.long	0xab58faac
	.long	0x9303e34b
	.long	0x55fa3020
	.long	0xf66d76ad
	.long	0x9176cc88
	.long	0x254c02f5
	.long	0xfcd7e54f
	.long	0xd7cb2ac5
	.long	0x80443526
	.long	0x8fa362b5
	.long	0x495ab1de
	.long	0x671bba25
	.long	0x980eea45
	.long	0xe1c0fe5d
	.long	0x02752fc3
	.long	0x12f04c81
	.long	0xa397468d
	.long	0xc6f9d36b
	.long	0xe75f8f03
	.long	0x959c9215
	.long	0xeb7a6dbf
	.long	0xda595295
	.long	0x2d83bed4
	.long	0xd3217458
	.long	0x2969e049
	.long	0x44c8c98e
	.long	0x6a89c275
	.long	0x78798ef4
	.long	0x6b3e5899
	.long	0xdd71b927
	.long	0xb64fe1be
	.long	0x17ad88f0
	.long	0x66ac20c9
	.long	0xb43ace7d
	.long	0x184adf63
	.long	0x82311ae5
	.long	0x60335197
	.long	0x457f5362
	.long	0xe07764b1
	.long	0x84ae6bbb
	.long	0x1ca081fe
	.long	0x942b08f9
	.long	0x58684870
	.long	0x19fd458f
	.long	0x876cde94
	.long	0xb7f87b52
	.long	0x23d373ab
	.long	0xe2024b72
	.long	0x578f1fe3
	.long	0x2aab5566
	.long	0x0728ebb2
	.long	0x03c2b52f
	.long	0x9a7bc586
	.long	0xa50837d3
	.long	0xf2872830
	.long	0xb2a5bf23
	.long	0xba6a0302
	.long	0x5c8216ed
	.long	0x2b1ccf8a
	.long	0x92b479a7
	.long	0xf0f207f3
	.long	0xa1e2694e
	.long	0xcdf4da65
	.long	0xd5be0506
	.long	0x1f6234d1
	.long	0x8afea6c4
	.long	0x9d532e34
	.long	0xa055f3a2
	.long	0x32e18a05
	.long	0x75ebf6a4
	.long	0x39ec830b
	.long	0xaaef6040
	.long	0x069f715e
	.long	0x51106ebd
	.long	0xf98a213e
	.long	0x3d06dd96
	.long	0xae053edd
	.long	0x46bde64d
	.long	0xb58d5491
	.long	0x055dc471
	.long	0x6fd40604
	.long	0xff155060
	.long	0x24fb9819
	.long	0x97e9bdd6
	.long	0xcc434089
	.long	0x779ed967
	.long	0xbd42e8b0
	.long	0x888b8907
	.long	0x385b19e7
	.long	0xdbeec879
	.long	0x470a7ca1
	.long	0xe90f427c
	.long	0xc91e84f8
	.long	0x00000000
	.long	0x83868009
	.long	0x48ed2b32
	.long	0xac70111e
	.long	0x4e725a6c
	.long	0xfbff0efd
	.long	0x5638850f
	.long	0x1ed5ae3d
	.long	0x27392d36
	.long	0x64d90f0a
	.long	0x21a65c68
	.long	0xd1545b9b
	.long	0x3a2e3624
	.long	0xb1670a0c
	.long	0x0fe75793
	.long	0xd296eeb4
	.long	0x9e919b1b
	.long	0x4fc5c080
	.long	0xa220dc61
	.long	0x694b775a
	.long	0x161a121c
	.long	0x0aba93e2
	.long	0xe52aa0c0
	.long	0x43e0223c
	.long	0x1d171b12
	.long	0x0b0d090e
	.long	0xadc78bf2
	.long	0xb9a8b62d
	.long	0xc8a91e14
	.long	0x8519f157
	.long	0x4c0775af
	.long	0xbbdd99ee
	.long	0xfd607fa3
	.long	0x9f2601f7
	.long	0xbcf5725c
	.long	0xc53b6644
	.long	0x347efb5b
	.long	0x7629438b
	.long	0xdcc623cb
	.long	0x68fcedb6
	.long	0x63f1e4b8
	.long	0xcadc31d7
	.long	0x10856342
	.long	0x40229713
	.long	0x2011c684
	.long	0x7d244a85
	.long	0xf83dbbd2
	.long	0x1132f9ae
	.long	0x6da129c7
	.long	0x4b2f9e1d
	.long	0xf330b2dc
	.long	0xec52860d
	.long	0xd0e3c177
	.long	0x6c16b32b
	.long	0x99b970a9
	.long	0xfa489411
	.long	0x2264e947
	.long	0xc48cfca8
	.long	0x1a3ff0a0
	.long	0xd82c7d56
	.long	0xef903322
	.long	0xc74e4987
	.long	0xc1d138d9
	.long	0xfea2ca8c
	.long	0x360bd498
	.long	0xcf81f5a6
	.long	0x28de7aa5
	.long	0x268eb7da
	.long	0xa4bfad3f
	.long	0xe49d3a2c
	.long	0x0d927850
	.long	0x9bcc5f6a
	.long	0x62467e54
	.long	0xc2138df6
	.long	0xe8b8d890
	.long	0x5ef7392e
	.long	0xf5afc382
	.long	0xbe805d9f
	.long	0x7c93d069
	.long	0xa92dd56f
	.long	0xb31225cf
	.long	0x3b99acc8
	.long	0xa77d1810
	.long	0x6e639ce8
	.long	0x7bbb3bdb
	.long	0x097826cd
	.long	0xf418596e
	.long	0x01b79aec
	.long	0xa89a4f83
	.long	0x656e95e6
	.long	0x7ee6ffaa
	.long	0x08cfbc21
	.long	0xe6e815ef
	.long	0xd99be7ba
	.long	0xce366f4a
	.long	0xd4099fea
	.long	0xd67cb029
	.long	0xafb2a431
	.long	0x31233f2a
	.long	0x3094a5c6
	.long	0xc066a235
	.long	0x37bc4e74
	.long	0xa6ca82fc
	.long	0xb0d090e0
	.long	0x15d8a733
	.long	0x4a9804f1
	.long	0xf7daec41
	.long	0x0e50cd7f
	.long	0x2ff69117
	.long	0x8dd64d76
	.long	0x4db0ef43
	.long	0x544daacc
	.long	0xdf0496e4
	.long	0xe3b5d19e
	.long	0x1b886a4c
	.long	0xb81f2cc1
	.long	0x7f516546
	.long	0x04ea5e9d
	.long	0x5d358c01
	.long	0x737487fa
	.long	0x2e410bfb
	.long	0x5a1d67b3
	.long	0x52d2db92
	.long	0x335610e9
	.long	0x1347d66d
	.long	0x8c61d79a
	.long	0x7a0ca137
	.long	0x8e14f859
	.long	0x893c13eb
	.long	0xee27a9ce
	.long	0x35c961b7
	.long	0xede51ce1
	.long	0x3cb1477a
	.long	0x59dfd29c
	.long	0x3f73f255
	.long	0x79ce1418
	.long	0xbf37c773
	.long	0xeacdf753
	.long	0x5baafd5f
	.long	0x146f3ddf
	.long	0x86db4478
	.long	0x81f3afca
	.long	0x3ec468b9
	.long	0x2c342438
	.long	0x5f40a3c2
	.long	0x72c31d16
	.long	0x0c25e2bc
	.long	0x8b493c28
	.long	0x41950dff
	.long	0x7101a839
	.long	0xdeb30c08
	.long	0x9ce4b4d8
	.long	0x90c15664
	.long	0x6184cb7b
	.long	0x70b632d5
	.long	0x745c6c48
	.long	0x4257b8d0
	// Table 1.
	.long	0xa7f45150
	.long	0x65417e53
	.long	0xa4171ac3
	.long	0x5e273a96
	.long	0x6bab3bcb
	.long	0x459d1ff1
	.long	0x58faacab
	.long	0x03e34b93
	.long	0xfa302055
	.long	0x6d76adf6
	.long	0x76cc8891
	.long	0x4c02f525
	.long	0xd7e54ffc
	.long	0xcb2ac5d7
	.long	0x44352680
	.long	0xa362b58f
	.long	0x5ab1de49
	.long	0x1bba2567
	.long	0x0eea4598
	.long	0xc0fe5de1
	.long	0x752fc302
	.long	0xf04c8112
	.long	0x97468da3
	.long	0xf9d36bc6
	.long	0x5f8f03e7
	.long	0x9c921595
	.long	0x7a6dbfeb
	.long	0x595295da
	.long	0x83bed42d
	.long	0x217458d3
	.long	0x69e04929
	.long	0xc8c98e44
	.long	0x89c2756a
	.long	0x798ef478
	.long	0x3e58996b
	.long	0x71b927dd
	.long	0x4fe1beb6
	.long	0xad88f017
	.long	0xac20c966
	.long	0x3ace7db4
	.long	0x4adf6318
	.long	0x311ae582
	.long	0x33519760
	.long	0x7f536245
	.long	0x7764b1e0
	.long	0xae6bbb84
	.long	0xa081fe1c
	.long	0x2b08f994
	.long	0x68487058
	.long	0xfd458f19
	.long	0x6cde9487
	.long	0xf87b52b7
	.long	0xd373ab23
	.long	0x024b72e2
	.long	0x8f1fe357
	.long	0xab55662a
	.long	0x28ebb207
	.long	0xc2b52f03
	.long	0x7bc5869a
	.long	0x0837d3a5
	.long	0x872830f2
	.long	0xa5bf23b2
	.long	0x6a0302ba
	.long	0x8216ed5c
	.long	0x1ccf8a2b
	.long	0xb479a792
	.long	0xf207f3f0
	.long	0xe2694ea1
	.long	0xf4da65cd
	.long	0xbe0506d5
	.long	0x6234d11f
	.long	0xfea6c48a
	.long	0x532e349d
	.long	0x55f3a2a0
	.long	0xe18a0532
	.long	0xebf6a475
	.long	0xec830b39
	.long	0xef6040aa
	.long	0x9f715e06
	.long	0x106ebd51
	.long	0x8a213ef9
	.long	0x06dd963d
	.long	0x053eddae
	.long	0xbde64d46
	.long	0x8d5491b5
	.long	0x5dc47105
	.long	0xd406046f
	.long	0x155060ff
	.long	0xfb981924
	.long	0xe9bdd697
	.long	0x434089cc
	.long	0x9ed96777
	.long	0x42e8b0bd
	.long	0x8b890788
	.long	0x5b19e738
	.long	0xeec879db
	.long	0x0a7ca147
	.long	0x0f427ce9
	.long	0x1e84f8c9
	.long	0x00000000
	.long	0x86800983
	.long	0xed2b3248
	.long	0x70111eac
	.long	0x725a6c4e
	.long	0xff0efdfb
	.long	0x38850f56
	.long	0xd5ae3d1e
	.long	0x392d3627
	.long	0xd90f0a64
	.long	0xa65c6821
	.long	0x545b9bd1
	.long	0x2e36243a
	.long	0x670a0cb1
	.long	0xe757930f
	.long	0x96eeb4d2
	.long	0x919b1b9e
	.long	0xc5c0804f
	.long	0x20dc61a2
	.long	0x4b775a69
	.long	0x1a121c16
	.long	0xba93e20a
	.long	0x2aa0c0e5
	.long	0xe0223c43
	.long	0x171b121d
	.long	0x0d090e0b
	.long	0xc78bf2ad
	.long	0xa8b62db9
	.long	0xa91e14c8
	.long	0x19f15785
	.long	0x0775af4c
	.long	0xdd99eebb
	.long	0x607fa3fd
	.long	0x2601f79f
	.long	0xf5725cbc
	.long	0x3b6644c5
	.long	0x7efb5b34
	.long	0x29438b76
	.long	0xc623cbdc
	.long	0xfcedb668
	.long	0xf1e4b863
	.long	0xdc31d7ca
	.long	0x85634210
	.long	0x22971340
	.long	0x11c68420
	.long	0x244a857d
	.long	0x3dbbd2f8
	.long	0x32f9ae11
	.long	0xa129c76d
	.long	0x2f9e1d4b
	.long	0x30b2dcf3
	.long	0x52860dec
	.long	0xe3c177d0
	.long	0x16b32b6c
	.long	0xb970a999
	.long	0x489411fa
	.long	0x64e94722
	.long	0x8cfca8c4
	.long	0x3ff0a01a
	.long	0x2c7d56d8
	.long	0x903322ef
	.long	0x4e4987c7
	.long	0xd138d9c1
	.long	0xa2ca8cfe
	.long	0x0bd49836
	.long	0x81f5a6cf
	.long	0xde7aa528
	.long	0x8eb7da26
	.long	0xbfad3fa4
	.long	0x9d3a2ce4
	.long	0x9278500d
	.long	0xcc5f6a9b
	.long	0x467e5462
	.long	0x138df6c2
	.long	0xb8d890e8
	.long	0xf7392e5e
	.long	0xafc382f5
	.long	0x805d9fbe
	.long	0x93d0697c
	.long	0x2dd56fa9
	.long	0x1225cfb3
	.long	0x99acc83b
	.long	0x7d1810a7
	.long	0x639ce86e
	.long	0xbb3bdb7b
	.long	0x7826cd09
	.long	0x18596ef4
	.long	0xb79aec01
	.long	0x9a4f83a8
	.long	0x6e95e665
	.long	0xe6ffaa7e
	.long	0xcfbc2108
	.long	0xe815efe6
	.long	0x9be7bad9
	.long	0x366f4ace
	.long	0x099fead4
	.long	0x7cb029d6
	.long	0xb2a431af
	.long	0x233f2a31
	.long	0x94a5c630
	.long	0x66a235c0
	.long	0xbc4e7437
	.long	0xca82fca6
	.long	0xd090e0b0
	.long	0xd8a73315
	.long	0x9804f14a
	.long	0xdaec41f7
	.long	0x50cd7f0e
	.long	0xf691172f
	.long	0xd64d768d
	.long	0xb0ef434d
	.long	0x4daacc54
	.long	0x0496e4df
	.long	0xb5d19ee3
	.long	0x886a4c1b
	.long	0x1f2cc1b8
	.long	0x5165467f
	.long	0xea5e9d04
	.long	0x358c015d
	.long	0x7487fa73
	.long	0x410bfb2e
	.long	0x1d67b35a
	.long	0xd2db9252
	.long	0x5610e933
	.long	0x47d66d13
	.long	0x61d79a8c
	.long	0x0ca1377a
	.long	0x14f8598e
	.long	0x3c13eb89
	.long	0x27a9ceee
	.long	0xc961b735
	.long	0xe51ce1ed
	.long	0xb1477a3c
	.long	0xdfd29c59
	.long	0x73f2553f
	.long	0xce141879
	.long	0x37c773bf
	.long	0xcdf753ea
	.long	0xaafd5f5b
	.long	0x6f3ddf14
	.long	0xdb447886
	.long	0xf3afca81
	.long	0xc468b93e
	.long	0x3424382c
	.long	0x40a3c25f
	.long	0xc31d1672
	.long	0x25e2bc0c
	.long	0x493c288b
	.long	0x950dff41
	.long	0x01a83971
	.long	0xb30c08de
	.long	0xe4b4d89c
	.long	0xc1566490
	.long	0x84cb7b61
	.long	0xb632d570
	.long	0x5c6c4874
	.long	0x57b8d042
	// Table 2.
	.long	0xf45150a7
	.long	0x417e5365
	.long	0x171ac3a4
	.long	0x273a965e
	.long	0xab3bcb6b
	.long	0x9d1ff145
	.long	0xfaacab58
	.long	0xe34b9303
	.long	0x302055fa
	.long	0x76adf66d
	.long	0xcc889176
	.long	0x02f5254c
	.long	0xe54ffcd7
	.long	0x2ac5d7cb
	.long	0x35268044
	.long	0x62b58fa3
	.long	0xb1de495a
	.long	0xba25671b
	.long	0xea45980e
	.long	0xfe5de1c0
	.long	0x2fc30275
	.long	0x4c8112f0
	.long	0x468da397
	.long	0xd36bc6f9
	.long	0x8f03e75f
	.long	0x9215959c
	.long	0x6dbfeb7a
	.long	0x5295da59
	.long	0xbed42d83
	.long	0x7458d321
	.long	0xe0492969
	.long	0xc98e44c8
	.long	0xc2756a89
	.long	0x8ef47879
	.long	0x58996b3e
	.long	0xb927dd71
	.long	0xe1beb64f
	.long	0x88f017ad
	.long	0x20c966ac
	.long	0xce7db43a
	.long	0xdf63184a
	.long	0x1ae58231
	.long	0x51976033
	.long	0x5362457f
	.long	0x64b1e077
	.long	0x6bbb84ae
	.long	0x81fe1ca0
	.long	0x08f9942b
	.long	0x48705868
	.long	0x458f19fd
	.long	0xde94876c
	.long	0x7b52b7f8
	.long	0x73ab23d3
	.long	0x4b72e202
	.long	0x1fe3578f
	.long	0x55662aab
	.long	0xebb20728
	.long	0xb52f03c2
	.long	0xc5869a7b
	.long	0x37d3a508
	.long	0x2830f287
	.long	0xbf23b2a5
	.long	0x0302ba6a
	.long	0x16ed5c82
	.long	0xcf8a2b1c
	.long	0x79a792b4
	.long	0x07f3f0f2
	.long	0x694ea1e2
	.long	0xda65cdf4
	.long	0x0506d5be
	.long	0x34d11f62
	.long	0xa6c48afe
	.long	0x2e349d53
	.long	0xf3a2a055
	.long	0x8a0532e1
	.long	0xf6a475eb
	.long	0x830b39ec
	.long	0x6040aaef
	.long	0x715e069f
	.long	0x6ebd5110
	.long	0x213ef98a
	.long	0xdd963d06
	.long	0x3eddae05
	.long	0xe64d46bd
	.long	0x5491b58d
	.long	0xc471055d
	.long	0x06046fd4
	.long	0x5060ff15
	.long	0x981924fb
	.long	0xbdd697e9
	.long	0x4089cc43
	.long	0xd967779e
	.long	0xe8b0bd42
	.long	0x8907888b
	.long	0x19e7385b
	.long	0xc879dbee
	.long	0x7ca1470a
	.long	0x427ce90f
	.long	0x84f8c91e
	.long	0x00000000
	.long	0x80098386
	.long	0x2b3248ed
	.long	0x111eac70
	.long	0x5a6c4e72
	.long	0x0efdfbff
	.long	0x850f5638
	.long	0xae3d1ed5
	.long	0x2d362739
	.long	0x0f0a64d9
	.long	0x5c6821a6
	.long	0x5b9bd154
	.long	0x36243a2e
	.long	0x0a0cb167
	.long	0x57930fe7
	.long	0xeeb4d296
	.long	0x9b1b9e91
	.long	0xc0804fc5
	.long	0xdc61a220
	.long	0x775a694b
	.long	0x121c161a
	.long	0x93e20aba
	.long	0xa0c0e52a
	.long	0x223c43e0
	.long	0x1b121d17
	.long	0x090e0b0d
	.long	0x8bf2adc7
	.long	0xb62db9a8
	.long	0x1e14c8a9
	.long	0xf1578519
	.long	0x75af4c07
	.long	0x99eebbdd
	.long	0x7fa3fd60
	.long	0x01f79f26
	.long	0x725cbcf5
	.long	0x6644c53b
	.long	0xfb5b347e
	.long	0x438b7629
	.long	0x23cbdcc6
	.long	0xedb668fc
	.long	0xe4b863f1
	.long	0x31d7cadc
	.long	0x63421085
	.long	0x97134022
	.long	0xc6842011
	.long	0x4a857d24
	.long	0xbbd2f83d
	.long	0xf9ae1132
	.long	0x29c76da1
	.long	0x9e1d4b2f
	.long	0xb2dcf330
	.long	0x860dec52
	.long	0xc177d0e3
	.long	0xb32b6c16
	.long	0x70a999b9
	.long	0x9411fa48
	.long	0xe9472264
	.long	0xfca8c48c
	.long	0xf0a01a3f
	.long	0x7d56d82c
	.long	0x3322ef90
	.long	0x4987c74e
	.long	0x38d9c1d1
	.long	0xca8cfea2
	.long	0xd498360b
	.long	0xf5a6cf81
	.long	0x7aa528de
	.long	0xb7da268e
	.long	0xad3fa4bf
	.long	0x3a2ce49d
	.long	0x78500d92
	.long	0x5f6a9bcc
	.long	0x7e546246
	.long	0x8df6c213
	.long	0xd890e8b8
	.long	0x392e5ef7
	.long	0xc382f5af
	.long	0x5d9fbe80
	.long	0xd0697c93
	.long	0xd56fa92d
	.long	0x25cfb312
	.long	0xacc83b99
	.long	0x1810a77d
	.long	0x9ce86e63
	.long	0x3bdb7bbb
	.long	0x26cd0978
	.long	0x596ef418
	.long	0x9aec01b7
	.long	0x4f83a89a
	.long	0x95e6656e
	.long	0xffaa7ee6
	.long	0xbc2108cf
	.long	0x15efe6e8
	.long	0xe7bad99b
	.long	0x6f4ace36
	.long	0x9fead409
	.long	0xb029d67c
	.long	0xa431afb2
	.long	0x3f2a3123
	.long	0xa5c63094
	.long	0xa235c066
	.long	0x4e7437bc
	.long	0x82fca6ca
	.long	0x90e0b0d0
	.long	0xa73315d8
	.long	0x04f14a98
	.long	0xec41f7da
	.long	0xcd7f0e50
	.long	0x91172ff6
	.long	0x4d768dd6
	.long	0xef434db0
	.long	0xaacc544d
	.long	0x96e4df04
	.long	0xd19ee3b5
	.long	0x6a4c1b88
	.long	0x2cc1b81f
	.long	0x65467f51
	.long	0x5e9d04ea
	.long	0x8c015d35
	.long	0x87fa7374
	.long	0x0bfb2e41
	.long	0x67b35a1d
	.long	0xdb9252d2
	.long	0x10e93356
	.long	0xd66d1347
	.long	0xd79a8c61
	.long	0xa1377a0c
	.long	0xf8598e14
	.long	0x13eb893c
	.long	0xa9ceee27
	.long	0x61b735c9
	.long	0x1ce1ede5
	.long	0x477a3cb1
	.long	0xd29c59df
	.long	0xf2553f73
	.long	0x141879ce
	.long	0xc773bf37
	.long	0xf753eacd
	.long	0xfd5f5baa
	.long	0x3ddf146f
	.long	0x447886db
	.long	0xafca81f3
	.long	0x68b93ec4
	.long	0x24382c34
	.long	0xa3c25f40
	.long	0x1d1672c3
	.long	0xe2bc0c25
	.long	0x3c288b49
	.long	0x0dff4195
	.long	0xa8397101
	.long	0x0c08deb3
	.long	0xb4d89ce4
	.long	0x566490c1
	.long	0xcb7b6184
	.long	0x32d570b6
	.long	0x6c48745c
	.long	0xb8d04257
	// Table 3.
	.long	0x5150a7f4
	.long	0x7e536541
	.long	0x1ac3a417
	.long	0x3a965e27
	.long	0x3bcb6bab
	.long	0x1ff1459d
	.long	0xacab58fa
	.long	0x4b9303e3
	.long	0x2055fa30
	.long	0xadf66d76
	.long	0x889176cc
	.long	0xf5254c02
	.long	0x4ffcd7e5
	.long	0xc5d7cb2a
	.long	0x26804435
	.long	0xb58fa362
	.long	0xde495ab1
	.long	0x25671bba
	.long	0x45980eea
	.long	0x5de1c0fe
	.long	0xc302752f
	.long	0x8112f04c
	.long	0x8da39746
	.long	0x6bc6f9d3
	.long	0x03e75f8f
	.long	0x15959c92
	.long	0xbfeb7a6d
	.long	0x95da5952
	.long	0xd42d83be
	.long	0x58d32174
	.long	0x492969e0
	.long	0x8e44c8c9
	.long	0x756a89c2
	.long	0xf478798e
	.long	0x996b3e58
	.long	0x27dd71b9
	.long	0xbeb64fe1
	.long	0xf017ad88
	.long	0xc966ac20
	.long	0x7db43ace
	.long	0x63184adf
	.long	0xe582311a
	.long	0x97603351
	.long	0x62457f53
	.long	0xb1e07764
	.long	0xbb84ae6b
	.long	0xfe1ca081
	.long	0xf9942b08
	.long	0x70586848
	.long	0x8f19fd45
	.long	0x94876cde
	.long	0x52b7f87b
	.long	0xab23d373
	.long	0x72e2024b
	.long	0xe3578f1f
	.long	0x662aab55
	.long	0xb20728eb
	.long	0x2f03c2b5
	.long	0x869a7bc5
	.long	0xd3a50837
	.long	0x30f28728
	.long	0x23b2a5bf
	.long	0x02ba6a03
	.long	0xed5c8216
	.long	0x8a2b1ccf
	.long	0xa792b479
	.long	0xf3f0f207
	.long	0x4ea1e269
	.long	0x65cdf4da
	.long	0x06d5be05
	.long	0xd11f6234
	.long	0xc48afea6
	.long	0x349d532e
	.long	0xa2a055f3
	.long	0x0532e18a
	.long	0xa475ebf6
	.long	0x0b39ec83
	.long	0x40aaef60
	.long	0x5e069f71
	.long	0xbd51106e
	.long	0x3ef98a21
	.long	0x963d06dd
	.long	0xddae053e
	.long	0x4d46bde6
	.long	0x91b58d54
	.long	0x71055dc4
	.long	0x046fd406
	.long	0x60ff1550
	.long	0x1924fb98
	.long	0xd697e9bd
	.long	0x89cc4340
	.long	0x67779ed9
	.long	0xb0bd42e8
	.long	0x07888b89
	.long	0xe7385b19
	.long	0x79dbeec8
	.long	0xa1470a7c
	.long	0x7ce90f42
	.long	0xf8c91e84
	.long	0x00000000
	.long	0x09838680
	.long	0x3248ed2b
	.long	0x1eac7011
	.long	0x6c4e725a
	.long	0xfdfbff0e
	.long	0x0f563885
	.long	0x3d1ed5ae
	.long	0x3627392d
	.long	0x0a64d90f
	.long	0x6821a65c
	.long	0x9bd1545b
	.long	0x243a2e36
	.long	0x0cb1670a
	.long	0x930fe757
	.long	0xb4d296ee
	.long	0x1b9e919b
	.long	0x804fc5c0
	.long	0x61a220dc
	.long	0x5a694b77
	.long	0x1c161a12
	.long	0xe20aba93
	.long	0xc0e52aa0
	.long	0x3c43e022
	.long	0x121d171b
	.long	0x0e0b0d09
	.long	0xf2adc78b
	.long	0x2db9a8b6
	.long	0x14c8a91e
	.long	0x578519f1
	.long	0xaf4c0775
	.long	0xeebbdd99
	.long	0xa3fd607f
	.long	0xf79f2601
	.long	0x5cbcf572
	.long	0x44c53b66
	.long	0x5b347efb
	.long	0x8b762943
	.long	0xcbdcc623
	.long	0xb668fced
	.long	0xb863f1e4
	.long	0xd7cadc31
	.long	0x42108563
	.long	0x13402297
	.long	0x842011c6
	.long	0x857d244a
	.long	0xd2f83dbb
	.long	0xae1132f9
	.long	0xc76da129
	.long	0x1d4b2f9e
	.long	0xdcf330b2
	.long	0x0dec5286
	.long	0x77d0e3c1
	.long	0x2b6c16b3
	.long	0xa999b970
	.long	0x11fa4894
	.long	0x472264e9
	.long	0xa8c48cfc
	.long	0xa01a3ff0
	.long	0x56d82c7d
	.long	0x22ef9033
	.long	0x87c74e49
	.long	0xd9c1d138
	.long	0x8cfea2ca
	.long	0x98360bd4
	.long	0xa6cf81f5
	.long	0xa528de7a
	.long	0xda268eb7
	.long	0x3fa4bfad
	.long	0x2ce49d3a
	.long	0x500d9278
	.long	0x6a9bcc5f
	.long	0x5462467e
	.long	0xf6c2138d
	.long	0x90e8b8d8
	.long	0x2e5ef739
	.long	0x82f5afc3
	.long	0x9fbe805d
	.long	0x697c93d0
	.long	0x6fa92dd5
	.long	0xcfb31225
	.long	0xc83b99ac
	.long	0x10a77d18
	.long	0xe86e639c
	.long	0xdb7bbb3b
	.long	0xcd097826
	.long	0x6ef41859
	.long	0xec01b79a
	.long	0x83a89a4f
	.long	0xe6656e95
	.long	0xaa7ee6ff
	.long	0x2108cfbc
	.long	0xefe6e815
	.long	0xbad99be7
	.long	0x4ace366f
	.long	0xead4099f
	.long	0x29d67cb0
	.long	0x31afb2a4
	.long	0x2a31233f
	.long	0xc63094a5
	.long	0x35c066a2
	.long	0x7437bc4e
	.long	0xfca6ca82
	.long	0xe0b0d090
	.long	0x3315d8a7
	.long	0xf14a9804
	.long	0x41f7daec
	.long	0x7f0e50cd
	.long	0x172ff691
	.long	0x768dd64d
	.long	0x434db0ef
	.long	0xcc544daa
	.long	0xe4df0496
	.long	0x9ee3b5d1
	.long	0x4c1b886a
	.long	0xc1b81f2c
	.long	0x467f5165
	.long	0x9d04ea5e
	.long	0x015d358c
	.long	0xfa737487
	.long	0xfb2e410b
	.long	0xb35a1d67
	.long	0x9252d2db
	.long	0xe9335610
	.long	0x6d1347d6
	.long	0x9a8c61d7
	.long	0x377a0ca1
	.long	0x598e14f8
	.long	0xeb893c13
	.long	0xceee27a9
	.long	0xb735c961
	.long	0xe1ede51c
	.long	0x7a3cb147
	.long	0x9c59dfd2
	.long	0x553f73f2
	.long	0x1879ce14
	.long	0x73bf37c7
	.long	0x53eacdf7
	.long	0x5f5baafd
	.long	0xdf146f3d
	.long	0x7886db44
	.long	0xca81f3af
	.long	0xb93ec468
	.long	0x382c3424
	.long	0xc25f40a3
	.long	0x1672c31d
	.long	0xbc0c25e2
	.long	0x288b493c
	.long	0xff41950d
	.long	0x397101a8
	.long	0x08deb30c
	.long	0xd89ce4b4
	.long	0x6490c156
	.long	0x7b6184cb
	.long	0xd570b632
	.long	0x48745c6c
	.long	0xd04257b8


// SubBytes embedded in words tables.
	.globl	_AESSubBytesWordTable
	.private_extern	_AESSubBytesWordTable
	.align	2
_AESSubBytesWordTable:
	// Table 0.
	.long	0x00000063
	.long	0x0000007c
	.long	0x00000077
	.long	0x0000007b
	.long	0x000000f2
	.long	0x0000006b
	.long	0x0000006f
	.long	0x000000c5
	.long	0x00000030
	.long	0x00000001
	.long	0x00000067
	.long	0x0000002b
	.long	0x000000fe
	.long	0x000000d7
	.long	0x000000ab
	.long	0x00000076
	.long	0x000000ca
	.long	0x00000082
	.long	0x000000c9
	.long	0x0000007d
	.long	0x000000fa
	.long	0x00000059
	.long	0x00000047
	.long	0x000000f0
	.long	0x000000ad
	.long	0x000000d4
	.long	0x000000a2
	.long	0x000000af
	.long	0x0000009c
	.long	0x000000a4
	.long	0x00000072
	.long	0x000000c0
	.long	0x000000b7
	.long	0x000000fd
	.long	0x00000093
	.long	0x00000026
	.long	0x00000036
	.long	0x0000003f
	.long	0x000000f7
	.long	0x000000cc
	.long	0x00000034
	.long	0x000000a5
	.long	0x000000e5
	.long	0x000000f1
	.long	0x00000071
	.long	0x000000d8
	.long	0x00000031
	.long	0x00000015
	.long	0x00000004
	.long	0x000000c7
	.long	0x00000023
	.long	0x000000c3
	.long	0x00000018
	.long	0x00000096
	.long	0x00000005
	.long	0x0000009a
	.long	0x00000007
	.long	0x00000012
	.long	0x00000080
	.long	0x000000e2
	.long	0x000000eb
	.long	0x00000027
	.long	0x000000b2
	.long	0x00000075
	.long	0x00000009
	.long	0x00000083
	.long	0x0000002c
	.long	0x0000001a
	.long	0x0000001b
	.long	0x0000006e
	.long	0x0000005a
	.long	0x000000a0
	.long	0x00000052
	.long	0x0000003b
	.long	0x000000d6
	.long	0x000000b3
	.long	0x00000029
	.long	0x000000e3
	.long	0x0000002f
	.long	0x00000084
	.long	0x00000053
	.long	0x000000d1
	.long	0x00000000
	.long	0x000000ed
	.long	0x00000020
	.long	0x000000fc
	.long	0x000000b1
	.long	0x0000005b
	.long	0x0000006a
	.long	0x000000cb
	.long	0x000000be
	.long	0x00000039
	.long	0x0000004a
	.long	0x0000004c
	.long	0x00000058
	.long	0x000000cf
	.long	0x000000d0
	.long	0x000000ef
	.long	0x000000aa
	.long	0x000000fb
	.long	0x00000043
	.long	0x0000004d
	.long	0x00000033
	.long	0x00000085
	.long	0x00000045
	.long	0x000000f9
	.long	0x00000002
	.long	0x0000007f
	.long	0x00000050
	.long	0x0000003c
	.long	0x0000009f
	.long	0x000000a8
	.long	0x00000051
	.long	0x000000a3
	.long	0x00000040
	.long	0x0000008f
	.long	0x00000092
	.long	0x0000009d
	.long	0x00000038
	.long	0x000000f5
	.long	0x000000bc
	.long	0x000000b6
	.long	0x000000da
	.long	0x00000021
	.long	0x00000010
	.long	0x000000ff
	.long	0x000000f3
	.long	0x000000d2
	.long	0x000000cd
	.long	0x0000000c
	.long	0x00000013
	.long	0x000000ec
	.long	0x0000005f
	.long	0x00000097
	.long	0x00000044
	.long	0x00000017
	.long	0x000000c4
	.long	0x000000a7
	.long	0x0000007e
	.long	0x0000003d
	.long	0x00000064
	.long	0x0000005d
	.long	0x00000019
	.long	0x00000073
	.long	0x00000060
	.long	0x00000081
	.long	0x0000004f
	.long	0x000000dc
	.long	0x00000022
	.long	0x0000002a
	.long	0x00000090
	.long	0x00000088
	.long	0x00000046
	.long	0x000000ee
	.long	0x000000b8
	.long	0x00000014
	.long	0x000000de
	.long	0x0000005e
	.long	0x0000000b
	.long	0x000000db
	.long	0x000000e0
	.long	0x00000032
	.long	0x0000003a
	.long	0x0000000a
	.long	0x00000049
	.long	0x00000006
	.long	0x00000024
	.long	0x0000005c
	.long	0x000000c2
	.long	0x000000d3
	.long	0x000000ac
	.long	0x00000062
	.long	0x00000091
	.long	0x00000095
	.long	0x000000e4
	.long	0x00000079
	.long	0x000000e7
	.long	0x000000c8
	.long	0x00000037
	.long	0x0000006d
	.long	0x0000008d
	.long	0x000000d5
	.long	0x0000004e
	.long	0x000000a9
	.long	0x0000006c
	.long	0x00000056
	.long	0x000000f4
	.long	0x000000ea
	.long	0x00000065
	.long	0x0000007a
	.long	0x000000ae
	.long	0x00000008
	.long	0x000000ba
	.long	0x00000078
	.long	0x00000025
	.long	0x0000002e
	.long	0x0000001c
	.long	0x000000a6
	.long	0x000000b4
	.long	0x000000c6
	.long	0x000000e8
	.long	0x000000dd
	.long	0x00000074
	.long	0x0000001f
	.long	0x0000004b
	.long	0x000000bd
	.long	0x0000008b
	.long	0x0000008a
	.long	0x00000070
	.long	0x0000003e
	.long	0x000000b5
	.long	0x00000066
	.long	0x00000048
	.long	0x00000003
	.long	0x000000f6
	.long	0x0000000e
	.long	0x00000061
	.long	0x00000035
	.long	0x00000057
	.long	0x000000b9
	.long	0x00000086
	.long	0x000000c1
	.long	0x0000001d
	.long	0x0000009e
	.long	0x000000e1
	.long	0x000000f8
	.long	0x00000098
	.long	0x00000011
	.long	0x00000069
	.long	0x000000d9
	.long	0x0000008e
	.long	0x00000094
	.long	0x0000009b
	.long	0x0000001e
	.long	0x00000087
	.long	0x000000e9
	.long	0x000000ce
	.long	0x00000055
	.long	0x00000028
	.long	0x000000df
	.long	0x0000008c
	.long	0x000000a1
	.long	0x00000089
	.long	0x0000000d
	.long	0x000000bf
	.long	0x000000e6
	.long	0x00000042
	.long	0x00000068
	.long	0x00000041
	.long	0x00000099
	.long	0x0000002d
	.long	0x0000000f
	.long	0x000000b0
	.long	0x00000054
	.long	0x000000bb
	.long	0x00000016
	// Table 1.
	.long	0x00006300
	.long	0x00007c00
	.long	0x00007700
	.long	0x00007b00
	.long	0x0000f200
	.long	0x00006b00
	.long	0x00006f00
	.long	0x0000c500
	.long	0x00003000
	.long	0x00000100
	.long	0x00006700
	.long	0x00002b00
	.long	0x0000fe00
	.long	0x0000d700
	.long	0x0000ab00
	.long	0x00007600
	.long	0x0000ca00
	.long	0x00008200
	.long	0x0000c900
	.long	0x00007d00
	.long	0x0000fa00
	.long	0x00005900
	.long	0x00004700
	.long	0x0000f000
	.long	0x0000ad00
	.long	0x0000d400
	.long	0x0000a200
	.long	0x0000af00
	.long	0x00009c00
	.long	0x0000a400
	.long	0x00007200
	.long	0x0000c000
	.long	0x0000b700
	.long	0x0000fd00
	.long	0x00009300
	.long	0x00002600
	.long	0x00003600
	.long	0x00003f00
	.long	0x0000f700
	.long	0x0000cc00
	.long	0x00003400
	.long	0x0000a500
	.long	0x0000e500
	.long	0x0000f100
	.long	0x00007100
	.long	0x0000d800
	.long	0x00003100
	.long	0x00001500
	.long	0x00000400
	.long	0x0000c700
	.long	0x00002300
	.long	0x0000c300
	.long	0x00001800
	.long	0x00009600
	.long	0x00000500
	.long	0x00009a00
	.long	0x00000700
	.long	0x00001200
	.long	0x00008000
	.long	0x0000e200
	.long	0x0000eb00
	.long	0x00002700
	.long	0x0000b200
	.long	0x00007500
	.long	0x00000900
	.long	0x00008300
	.long	0x00002c00
	.long	0x00001a00
	.long	0x00001b00
	.long	0x00006e00
	.long	0x00005a00
	.long	0x0000a000
	.long	0x00005200
	.long	0x00003b00
	.long	0x0000d600
	.long	0x0000b300
	.long	0x00002900
	.long	0x0000e300
	.long	0x00002f00
	.long	0x00008400
	.long	0x00005300
	.long	0x0000d100
	.long	0x00000000
	.long	0x0000ed00
	.long	0x00002000
	.long	0x0000fc00
	.long	0x0000b100
	.long	0x00005b00
	.long	0x00006a00
	.long	0x0000cb00
	.long	0x0000be00
	.long	0x00003900
	.long	0x00004a00
	.long	0x00004c00
	.long	0x00005800
	.long	0x0000cf00
	.long	0x0000d000
	.long	0x0000ef00
	.long	0x0000aa00
	.long	0x0000fb00
	.long	0x00004300
	.long	0x00004d00
	.long	0x00003300
	.long	0x00008500
	.long	0x00004500
	.long	0x0000f900
	.long	0x00000200
	.long	0x00007f00
	.long	0x00005000
	.long	0x00003c00
	.long	0x00009f00
	.long	0x0000a800
	.long	0x00005100
	.long	0x0000a300
	.long	0x00004000
	.long	0x00008f00
	.long	0x00009200
	.long	0x00009d00
	.long	0x00003800
	.long	0x0000f500
	.long	0x0000bc00
	.long	0x0000b600
	.long	0x0000da00
	.long	0x00002100
	.long	0x00001000
	.long	0x0000ff00
	.long	0x0000f300
	.long	0x0000d200
	.long	0x0000cd00
	.long	0x00000c00
	.long	0x00001300
	.long	0x0000ec00
	.long	0x00005f00
	.long	0x00009700
	.long	0x00004400
	.long	0x00001700
	.long	0x0000c400
	.long	0x0000a700
	.long	0x00007e00
	.long	0x00003d00
	.long	0x00006400
	.long	0x00005d00
	.long	0x00001900
	.long	0x00007300
	.long	0x00006000
	.long	0x00008100
	.long	0x00004f00
	.long	0x0000dc00
	.long	0x00002200
	.long	0x00002a00
	.long	0x00009000
	.long	0x00008800
	.long	0x00004600
	.long	0x0000ee00
	.long	0x0000b800
	.long	0x00001400
	.long	0x0000de00
	.long	0x00005e00
	.long	0x00000b00
	.long	0x0000db00
	.long	0x0000e000
	.long	0x00003200
	.long	0x00003a00
	.long	0x00000a00
	.long	0x00004900
	.long	0x00000600
	.long	0x00002400
	.long	0x00005c00
	.long	0x0000c200
	.long	0x0000d300
	.long	0x0000ac00
	.long	0x00006200
	.long	0x00009100
	.long	0x00009500
	.long	0x0000e400
	.long	0x00007900
	.long	0x0000e700
	.long	0x0000c800
	.long	0x00003700
	.long	0x00006d00
	.long	0x00008d00
	.long	0x0000d500
	.long	0x00004e00
	.long	0x0000a900
	.long	0x00006c00
	.long	0x00005600
	.long	0x0000f400
	.long	0x0000ea00
	.long	0x00006500
	.long	0x00007a00
	.long	0x0000ae00
	.long	0x00000800
	.long	0x0000ba00
	.long	0x00007800
	.long	0x00002500
	.long	0x00002e00
	.long	0x00001c00
	.long	0x0000a600
	.long	0x0000b400
	.long	0x0000c600
	.long	0x0000e800
	.long	0x0000dd00
	.long	0x00007400
	.long	0x00001f00
	.long	0x00004b00
	.long	0x0000bd00
	.long	0x00008b00
	.long	0x00008a00
	.long	0x00007000
	.long	0x00003e00
	.long	0x0000b500
	.long	0x00006600
	.long	0x00004800
	.long	0x00000300
	.long	0x0000f600
	.long	0x00000e00
	.long	0x00006100
	.long	0x00003500
	.long	0x00005700
	.long	0x0000b900
	.long	0x00008600
	.long	0x0000c100
	.long	0x00001d00
	.long	0x00009e00
	.long	0x0000e100
	.long	0x0000f800
	.long	0x00009800
	.long	0x00001100
	.long	0x00006900
	.long	0x0000d900
	.long	0x00008e00
	.long	0x00009400
	.long	0x00009b00
	.long	0x00001e00
	.long	0x00008700
	.long	0x0000e900
	.long	0x0000ce00
	.long	0x00005500
	.long	0x00002800
	.long	0x0000df00
	.long	0x00008c00
	.long	0x0000a100
	.long	0x00008900
	.long	0x00000d00
	.long	0x0000bf00
	.long	0x0000e600
	.long	0x00004200
	.long	0x00006800
	.long	0x00004100
	.long	0x00009900
	.long	0x00002d00
	.long	0x00000f00
	.long	0x0000b000
	.long	0x00005400
	.long	0x0000bb00
	.long	0x00001600
	// Table 2.
	.long	0x00630000
	.long	0x007c0000
	.long	0x00770000
	.long	0x007b0000
	.long	0x00f20000
	.long	0x006b0000
	.long	0x006f0000
	.long	0x00c50000
	.long	0x00300000
	.long	0x00010000
	.long	0x00670000
	.long	0x002b0000
	.long	0x00fe0000
	.long	0x00d70000
	.long	0x00ab0000
	.long	0x00760000
	.long	0x00ca0000
	.long	0x00820000
	.long	0x00c90000
	.long	0x007d0000
	.long	0x00fa0000
	.long	0x00590000
	.long	0x00470000
	.long	0x00f00000
	.long	0x00ad0000
	.long	0x00d40000
	.long	0x00a20000
	.long	0x00af0000
	.long	0x009c0000
	.long	0x00a40000
	.long	0x00720000
	.long	0x00c00000
	.long	0x00b70000
	.long	0x00fd0000
	.long	0x00930000
	.long	0x00260000
	.long	0x00360000
	.long	0x003f0000
	.long	0x00f70000
	.long	0x00cc0000
	.long	0x00340000
	.long	0x00a50000
	.long	0x00e50000
	.long	0x00f10000
	.long	0x00710000
	.long	0x00d80000
	.long	0x00310000
	.long	0x00150000
	.long	0x00040000
	.long	0x00c70000
	.long	0x00230000
	.long	0x00c30000
	.long	0x00180000
	.long	0x00960000
	.long	0x00050000
	.long	0x009a0000
	.long	0x00070000
	.long	0x00120000
	.long	0x00800000
	.long	0x00e20000
	.long	0x00eb0000
	.long	0x00270000
	.long	0x00b20000
	.long	0x00750000
	.long	0x00090000
	.long	0x00830000
	.long	0x002c0000
	.long	0x001a0000
	.long	0x001b0000
	.long	0x006e0000
	.long	0x005a0000
	.long	0x00a00000
	.long	0x00520000
	.long	0x003b0000
	.long	0x00d60000
	.long	0x00b30000
	.long	0x00290000
	.long	0x00e30000
	.long	0x002f0000
	.long	0x00840000
	.long	0x00530000
	.long	0x00d10000
	.long	0x00000000
	.long	0x00ed0000
	.long	0x00200000
	.long	0x00fc0000
	.long	0x00b10000
	.long	0x005b0000
	.long	0x006a0000
	.long	0x00cb0000
	.long	0x00be0000
	.long	0x00390000
	.long	0x004a0000
	.long	0x004c0000
	.long	0x00580000
	.long	0x00cf0000
	.long	0x00d00000
	.long	0x00ef0000
	.long	0x00aa0000
	.long	0x00fb0000
	.long	0x00430000
	.long	0x004d0000
	.long	0x00330000
	.long	0x00850000
	.long	0x00450000
	.long	0x00f90000
	.long	0x00020000
	.long	0x007f0000
	.long	0x00500000
	.long	0x003c0000
	.long	0x009f0000
	.long	0x00a80000
	.long	0x00510000
	.long	0x00a30000
	.long	0x00400000
	.long	0x008f0000
	.long	0x00920000
	.long	0x009d0000
	.long	0x00380000
	.long	0x00f50000
	.long	0x00bc0000
	.long	0x00b60000
	.long	0x00da0000
	.long	0x00210000
	.long	0x00100000
	.long	0x00ff0000
	.long	0x00f30000
	.long	0x00d20000
	.long	0x00cd0000
	.long	0x000c0000
	.long	0x00130000
	.long	0x00ec0000
	.long	0x005f0000
	.long	0x00970000
	.long	0x00440000
	.long	0x00170000
	.long	0x00c40000
	.long	0x00a70000
	.long	0x007e0000
	.long	0x003d0000
	.long	0x00640000
	.long	0x005d0000
	.long	0x00190000
	.long	0x00730000
	.long	0x00600000
	.long	0x00810000
	.long	0x004f0000
	.long	0x00dc0000
	.long	0x00220000
	.long	0x002a0000
	.long	0x00900000
	.long	0x00880000
	.long	0x00460000
	.long	0x00ee0000
	.long	0x00b80000
	.long	0x00140000
	.long	0x00de0000
	.long	0x005e0000
	.long	0x000b0000
	.long	0x00db0000
	.long	0x00e00000
	.long	0x00320000
	.long	0x003a0000
	.long	0x000a0000
	.long	0x00490000
	.long	0x00060000
	.long	0x00240000
	.long	0x005c0000
	.long	0x00c20000
	.long	0x00d30000
	.long	0x00ac0000
	.long	0x00620000
	.long	0x00910000
	.long	0x00950000
	.long	0x00e40000
	.long	0x00790000
	.long	0x00e70000
	.long	0x00c80000
	.long	0x00370000
	.long	0x006d0000
	.long	0x008d0000
	.long	0x00d50000
	.long	0x004e0000
	.long	0x00a90000
	.long	0x006c0000
	.long	0x00560000
	.long	0x00f40000
	.long	0x00ea0000
	.long	0x00650000
	.long	0x007a0000
	.long	0x00ae0000
	.long	0x00080000
	.long	0x00ba0000
	.long	0x00780000
	.long	0x00250000
	.long	0x002e0000
	.long	0x001c0000
	.long	0x00a60000
	.long	0x00b40000
	.long	0x00c60000
	.long	0x00e80000
	.long	0x00dd0000
	.long	0x00740000
	.long	0x001f0000
	.long	0x004b0000
	.long	0x00bd0000
	.long	0x008b0000
	.long	0x008a0000
	.long	0x00700000
	.long	0x003e0000
	.long	0x00b50000
	.long	0x00660000
	.long	0x00480000
	.long	0x00030000
	.long	0x00f60000
	.long	0x000e0000
	.long	0x00610000
	.long	0x00350000
	.long	0x00570000
	.long	0x00b90000
	.long	0x00860000
	.long	0x00c10000
	.long	0x001d0000
	.long	0x009e0000
	.long	0x00e10000
	.long	0x00f80000
	.long	0x00980000
	.long	0x00110000
	.long	0x00690000
	.long	0x00d90000
	.long	0x008e0000
	.long	0x00940000
	.long	0x009b0000
	.long	0x001e0000
	.long	0x00870000
	.long	0x00e90000
	.long	0x00ce0000
	.long	0x00550000
	.long	0x00280000
	.long	0x00df0000
	.long	0x008c0000
	.long	0x00a10000
	.long	0x00890000
	.long	0x000d0000
	.long	0x00bf0000
	.long	0x00e60000
	.long	0x00420000
	.long	0x00680000
	.long	0x00410000
	.long	0x00990000
	.long	0x002d0000
	.long	0x000f0000
	.long	0x00b00000
	.long	0x00540000
	.long	0x00bb0000
	.long	0x00160000
	// Table 3.
	.long	0x63000000
	.long	0x7c000000
	.long	0x77000000
	.long	0x7b000000
	.long	0xf2000000
	.long	0x6b000000
	.long	0x6f000000
	.long	0xc5000000
	.long	0x30000000
	.long	0x01000000
	.long	0x67000000
	.long	0x2b000000
	.long	0xfe000000
	.long	0xd7000000
	.long	0xab000000
	.long	0x76000000
	.long	0xca000000
	.long	0x82000000
	.long	0xc9000000
	.long	0x7d000000
	.long	0xfa000000
	.long	0x59000000
	.long	0x47000000
	.long	0xf0000000
	.long	0xad000000
	.long	0xd4000000
	.long	0xa2000000
	.long	0xaf000000
	.long	0x9c000000
	.long	0xa4000000
	.long	0x72000000
	.long	0xc0000000
	.long	0xb7000000
	.long	0xfd000000
	.long	0x93000000
	.long	0x26000000
	.long	0x36000000
	.long	0x3f000000
	.long	0xf7000000
	.long	0xcc000000
	.long	0x34000000
	.long	0xa5000000
	.long	0xe5000000
	.long	0xf1000000
	.long	0x71000000
	.long	0xd8000000
	.long	0x31000000
	.long	0x15000000
	.long	0x04000000
	.long	0xc7000000
	.long	0x23000000
	.long	0xc3000000
	.long	0x18000000
	.long	0x96000000
	.long	0x05000000
	.long	0x9a000000
	.long	0x07000000
	.long	0x12000000
	.long	0x80000000
	.long	0xe2000000
	.long	0xeb000000
	.long	0x27000000
	.long	0xb2000000
	.long	0x75000000
	.long	0x09000000
	.long	0x83000000
	.long	0x2c000000
	.long	0x1a000000
	.long	0x1b000000
	.long	0x6e000000
	.long	0x5a000000
	.long	0xa0000000
	.long	0x52000000
	.long	0x3b000000
	.long	0xd6000000
	.long	0xb3000000
	.long	0x29000000
	.long	0xe3000000
	.long	0x2f000000
	.long	0x84000000
	.long	0x53000000
	.long	0xd1000000
	.long	0x00000000
	.long	0xed000000
	.long	0x20000000
	.long	0xfc000000
	.long	0xb1000000
	.long	0x5b000000
	.long	0x6a000000
	.long	0xcb000000
	.long	0xbe000000
	.long	0x39000000
	.long	0x4a000000
	.long	0x4c000000
	.long	0x58000000
	.long	0xcf000000
	.long	0xd0000000
	.long	0xef000000
	.long	0xaa000000
	.long	0xfb000000
	.long	0x43000000
	.long	0x4d000000
	.long	0x33000000
	.long	0x85000000
	.long	0x45000000
	.long	0xf9000000
	.long	0x02000000
	.long	0x7f000000
	.long	0x50000000
	.long	0x3c000000
	.long	0x9f000000
	.long	0xa8000000
	.long	0x51000000
	.long	0xa3000000
	.long	0x40000000
	.long	0x8f000000
	.long	0x92000000
	.long	0x9d000000
	.long	0x38000000
	.long	0xf5000000
	.long	0xbc000000
	.long	0xb6000000
	.long	0xda000000
	.long	0x21000000
	.long	0x10000000
	.long	0xff000000
	.long	0xf3000000
	.long	0xd2000000
	.long	0xcd000000
	.long	0x0c000000
	.long	0x13000000
	.long	0xec000000
	.long	0x5f000000
	.long	0x97000000
	.long	0x44000000
	.long	0x17000000
	.long	0xc4000000
	.long	0xa7000000
	.long	0x7e000000
	.long	0x3d000000
	.long	0x64000000
	.long	0x5d000000
	.long	0x19000000
	.long	0x73000000
	.long	0x60000000
	.long	0x81000000
	.long	0x4f000000
	.long	0xdc000000
	.long	0x22000000
	.long	0x2a000000
	.long	0x90000000
	.long	0x88000000
	.long	0x46000000
	.long	0xee000000
	.long	0xb8000000
	.long	0x14000000
	.long	0xde000000
	.long	0x5e000000
	.long	0x0b000000
	.long	0xdb000000
	.long	0xe0000000
	.long	0x32000000
	.long	0x3a000000
	.long	0x0a000000
	.long	0x49000000
	.long	0x06000000
	.long	0x24000000
	.long	0x5c000000
	.long	0xc2000000
	.long	0xd3000000
	.long	0xac000000
	.long	0x62000000
	.long	0x91000000
	.long	0x95000000
	.long	0xe4000000
	.long	0x79000000
	.long	0xe7000000
	.long	0xc8000000
	.long	0x37000000
	.long	0x6d000000
	.long	0x8d000000
	.long	0xd5000000
	.long	0x4e000000
	.long	0xa9000000
	.long	0x6c000000
	.long	0x56000000
	.long	0xf4000000
	.long	0xea000000
	.long	0x65000000
	.long	0x7a000000
	.long	0xae000000
	.long	0x08000000
	.long	0xba000000
	.long	0x78000000
	.long	0x25000000
	.long	0x2e000000
	.long	0x1c000000
	.long	0xa6000000
	.long	0xb4000000
	.long	0xc6000000
	.long	0xe8000000
	.long	0xdd000000
	.long	0x74000000
	.long	0x1f000000
	.long	0x4b000000
	.long	0xbd000000
	.long	0x8b000000
	.long	0x8a000000
	.long	0x70000000
	.long	0x3e000000
	.long	0xb5000000
	.long	0x66000000
	.long	0x48000000
	.long	0x03000000
	.long	0xf6000000
	.long	0x0e000000
	.long	0x61000000
	.long	0x35000000
	.long	0x57000000
	.long	0xb9000000
	.long	0x86000000
	.long	0xc1000000
	.long	0x1d000000
	.long	0x9e000000
	.long	0xe1000000
	.long	0xf8000000
	.long	0x98000000
	.long	0x11000000
	.long	0x69000000
	.long	0xd9000000
	.long	0x8e000000
	.long	0x94000000
	.long	0x9b000000
	.long	0x1e000000
	.long	0x87000000
	.long	0xe9000000
	.long	0xce000000
	.long	0x55000000
	.long	0x28000000
	.long	0xdf000000
	.long	0x8c000000
	.long	0xa1000000
	.long	0x89000000
	.long	0x0d000000
	.long	0xbf000000
	.long	0xe6000000
	.long	0x42000000
	.long	0x68000000
	.long	0x41000000
	.long	0x99000000
	.long	0x2d000000
	.long	0x0f000000
	.long	0xb0000000
	.long	0x54000000
	.long	0xbb000000
	.long	0x16000000


// InvSubBytes embedded in words tables.
	.globl	_AESInvSubBytesWordTable
	.private_extern	_AESInvSubBytesWordTable
	.align	2
_AESInvSubBytesWordTable:
	// Table 0.
	.long	0x00000052
	.long	0x00000009
	.long	0x0000006a
	.long	0x000000d5
	.long	0x00000030
	.long	0x00000036
	.long	0x000000a5
	.long	0x00000038
	.long	0x000000bf
	.long	0x00000040
	.long	0x000000a3
	.long	0x0000009e
	.long	0x00000081
	.long	0x000000f3
	.long	0x000000d7
	.long	0x000000fb
	.long	0x0000007c
	.long	0x000000e3
	.long	0x00000039
	.long	0x00000082
	.long	0x0000009b
	.long	0x0000002f
	.long	0x000000ff
	.long	0x00000087
	.long	0x00000034
	.long	0x0000008e
	.long	0x00000043
	.long	0x00000044
	.long	0x000000c4
	.long	0x000000de
	.long	0x000000e9
	.long	0x000000cb
	.long	0x00000054
	.long	0x0000007b
	.long	0x00000094
	.long	0x00000032
	.long	0x000000a6
	.long	0x000000c2
	.long	0x00000023
	.long	0x0000003d
	.long	0x000000ee
	.long	0x0000004c
	.long	0x00000095
	.long	0x0000000b
	.long	0x00000042
	.long	0x000000fa
	.long	0x000000c3
	.long	0x0000004e
	.long	0x00000008
	.long	0x0000002e
	.long	0x000000a1
	.long	0x00000066
	.long	0x00000028
	.long	0x000000d9
	.long	0x00000024
	.long	0x000000b2
	.long	0x00000076
	.long	0x0000005b
	.long	0x000000a2
	.long	0x00000049
	.long	0x0000006d
	.long	0x0000008b
	.long	0x000000d1
	.long	0x00000025
	.long	0x00000072
	.long	0x000000f8
	.long	0x000000f6
	.long	0x00000064
	.long	0x00000086
	.long	0x00000068
	.long	0x00000098
	.long	0x00000016
	.long	0x000000d4
	.long	0x000000a4
	.long	0x0000005c
	.long	0x000000cc
	.long	0x0000005d
	.long	0x00000065
	.long	0x000000b6
	.long	0x00000092
	.long	0x0000006c
	.long	0x00000070
	.long	0x00000048
	.long	0x00000050
	.long	0x000000fd
	.long	0x000000ed
	.long	0x000000b9
	.long	0x000000da
	.long	0x0000005e
	.long	0x00000015
	.long	0x00000046
	.long	0x00000057
	.long	0x000000a7
	.long	0x0000008d
	.long	0x0000009d
	.long	0x00000084
	.long	0x00000090
	.long	0x000000d8
	.long	0x000000ab
	.long	0x00000000
	.long	0x0000008c
	.long	0x000000bc
	.long	0x000000d3
	.long	0x0000000a
	.long	0x000000f7
	.long	0x000000e4
	.long	0x00000058
	.long	0x00000005
	.long	0x000000b8
	.long	0x000000b3
	.long	0x00000045
	.long	0x00000006
	.long	0x000000d0
	.long	0x0000002c
	.long	0x0000001e
	.long	0x0000008f
	.long	0x000000ca
	.long	0x0000003f
	.long	0x0000000f
	.long	0x00000002
	.long	0x000000c1
	.long	0x000000af
	.long	0x000000bd
	.long	0x00000003
	.long	0x00000001
	.long	0x00000013
	.long	0x0000008a
	.long	0x0000006b
	.long	0x0000003a
	.long	0x00000091
	.long	0x00000011
	.long	0x00000041
	.long	0x0000004f
	.long	0x00000067
	.long	0x000000dc
	.long	0x000000ea
	.long	0x00000097
	.long	0x000000f2
	.long	0x000000cf
	.long	0x000000ce
	.long	0x000000f0
	.long	0x000000b4
	.long	0x000000e6
	.long	0x00000073
	.long	0x00000096
	.long	0x000000ac
	.long	0x00000074
	.long	0x00000022
	.long	0x000000e7
	.long	0x000000ad
	.long	0x00000035
	.long	0x00000085
	.long	0x000000e2
	.long	0x000000f9
	.long	0x00000037
	.long	0x000000e8
	.long	0x0000001c
	.long	0x00000075
	.long	0x000000df
	.long	0x0000006e
	.long	0x00000047
	.long	0x000000f1
	.long	0x0000001a
	.long	0x00000071
	.long	0x0000001d
	.long	0x00000029
	.long	0x000000c5
	.long	0x00000089
	.long	0x0000006f
	.long	0x000000b7
	.long	0x00000062
	.long	0x0000000e
	.long	0x000000aa
	.long	0x00000018
	.long	0x000000be
	.long	0x0000001b
	.long	0x000000fc
	.long	0x00000056
	.long	0x0000003e
	.long	0x0000004b
	.long	0x000000c6
	.long	0x000000d2
	.long	0x00000079
	.long	0x00000020
	.long	0x0000009a
	.long	0x000000db
	.long	0x000000c0
	.long	0x000000fe
	.long	0x00000078
	.long	0x000000cd
	.long	0x0000005a
	.long	0x000000f4
	.long	0x0000001f
	.long	0x000000dd
	.long	0x000000a8
	.long	0x00000033
	.long	0x00000088
	.long	0x00000007
	.long	0x000000c7
	.long	0x00000031
	.long	0x000000b1
	.long	0x00000012
	.long	0x00000010
	.long	0x00000059
	.long	0x00000027
	.long	0x00000080
	.long	0x000000ec
	.long	0x0000005f
	.long	0x00000060
	.long	0x00000051
	.long	0x0000007f
	.long	0x000000a9
	.long	0x00000019
	.long	0x000000b5
	.long	0x0000004a
	.long	0x0000000d
	.long	0x0000002d
	.long	0x000000e5
	.long	0x0000007a
	.long	0x0000009f
	.long	0x00000093
	.long	0x000000c9
	.long	0x0000009c
	.long	0x000000ef
	.long	0x000000a0
	.long	0x000000e0
	.long	0x0000003b
	.long	0x0000004d
	.long	0x000000ae
	.long	0x0000002a
	.long	0x000000f5
	.long	0x000000b0
	.long	0x000000c8
	.long	0x000000eb
	.long	0x000000bb
	.long	0x0000003c
	.long	0x00000083
	.long	0x00000053
	.long	0x00000099
	.long	0x00000061
	.long	0x00000017
	.long	0x0000002b
	.long	0x00000004
	.long	0x0000007e
	.long	0x000000ba
	.long	0x00000077
	.long	0x000000d6
	.long	0x00000026
	.long	0x000000e1
	.long	0x00000069
	.long	0x00000014
	.long	0x00000063
	.long	0x00000055
	.long	0x00000021
	.long	0x0000000c
	.long	0x0000007d
	// Table 1.
	.long	0x00005200
	.long	0x00000900
	.long	0x00006a00
	.long	0x0000d500
	.long	0x00003000
	.long	0x00003600
	.long	0x0000a500
	.long	0x00003800
	.long	0x0000bf00
	.long	0x00004000
	.long	0x0000a300
	.long	0x00009e00
	.long	0x00008100
	.long	0x0000f300
	.long	0x0000d700
	.long	0x0000fb00
	.long	0x00007c00
	.long	0x0000e300
	.long	0x00003900
	.long	0x00008200
	.long	0x00009b00
	.long	0x00002f00
	.long	0x0000ff00
	.long	0x00008700
	.long	0x00003400
	.long	0x00008e00
	.long	0x00004300
	.long	0x00004400
	.long	0x0000c400
	.long	0x0000de00
	.long	0x0000e900
	.long	0x0000cb00
	.long	0x00005400
	.long	0x00007b00
	.long	0x00009400
	.long	0x00003200
	.long	0x0000a600
	.long	0x0000c200
	.long	0x00002300
	.long	0x00003d00
	.long	0x0000ee00
	.long	0x00004c00
	.long	0x00009500
	.long	0x00000b00
	.long	0x00004200
	.long	0x0000fa00
	.long	0x0000c300
	.long	0x00004e00
	.long	0x00000800
	.long	0x00002e00
	.long	0x0000a100
	.long	0x00006600
	.long	0x00002800
	.long	0x0000d900
	.long	0x00002400
	.long	0x0000b200
	.long	0x00007600
	.long	0x00005b00
	.long	0x0000a200
	.long	0x00004900
	.long	0x00006d00
	.long	0x00008b00
	.long	0x0000d100
	.long	0x00002500
	.long	0x00007200
	.long	0x0000f800
	.long	0x0000f600
	.long	0x00006400
	.long	0x00008600
	.long	0x00006800
	.long	0x00009800
	.long	0x00001600
	.long	0x0000d400
	.long	0x0000a400
	.long	0x00005c00
	.long	0x0000cc00
	.long	0x00005d00
	.long	0x00006500
	.long	0x0000b600
	.long	0x00009200
	.long	0x00006c00
	.long	0x00007000
	.long	0x00004800
	.long	0x00005000
	.long	0x0000fd00
	.long	0x0000ed00
	.long	0x0000b900
	.long	0x0000da00
	.long	0x00005e00
	.long	0x00001500
	.long	0x00004600
	.long	0x00005700
	.long	0x0000a700
	.long	0x00008d00
	.long	0x00009d00
	.long	0x00008400
	.long	0x00009000
	.long	0x0000d800
	.long	0x0000ab00
	.long	0x00000000
	.long	0x00008c00
	.long	0x0000bc00
	.long	0x0000d300
	.long	0x00000a00
	.long	0x0000f700
	.long	0x0000e400
	.long	0x00005800
	.long	0x00000500
	.long	0x0000b800
	.long	0x0000b300
	.long	0x00004500
	.long	0x00000600
	.long	0x0000d000
	.long	0x00002c00
	.long	0x00001e00
	.long	0x00008f00
	.long	0x0000ca00
	.long	0x00003f00
	.long	0x00000f00
	.long	0x00000200
	.long	0x0000c100
	.long	0x0000af00
	.long	0x0000bd00
	.long	0x00000300
	.long	0x00000100
	.long	0x00001300
	.long	0x00008a00
	.long	0x00006b00
	.long	0x00003a00
	.long	0x00009100
	.long	0x00001100
	.long	0x00004100
	.long	0x00004f00
	.long	0x00006700
	.long	0x0000dc00
	.long	0x0000ea00
	.long	0x00009700
	.long	0x0000f200
	.long	0x0000cf00
	.long	0x0000ce00
	.long	0x0000f000
	.long	0x0000b400
	.long	0x0000e600
	.long	0x00007300
	.long	0x00009600
	.long	0x0000ac00
	.long	0x00007400
	.long	0x00002200
	.long	0x0000e700
	.long	0x0000ad00
	.long	0x00003500
	.long	0x00008500
	.long	0x0000e200
	.long	0x0000f900
	.long	0x00003700
	.long	0x0000e800
	.long	0x00001c00
	.long	0x00007500
	.long	0x0000df00
	.long	0x00006e00
	.long	0x00004700
	.long	0x0000f100
	.long	0x00001a00
	.long	0x00007100
	.long	0x00001d00
	.long	0x00002900
	.long	0x0000c500
	.long	0x00008900
	.long	0x00006f00
	.long	0x0000b700
	.long	0x00006200
	.long	0x00000e00
	.long	0x0000aa00
	.long	0x00001800
	.long	0x0000be00
	.long	0x00001b00
	.long	0x0000fc00
	.long	0x00005600
	.long	0x00003e00
	.long	0x00004b00
	.long	0x0000c600
	.long	0x0000d200
	.long	0x00007900
	.long	0x00002000
	.long	0x00009a00
	.long	0x0000db00
	.long	0x0000c000
	.long	0x0000fe00
	.long	0x00007800
	.long	0x0000cd00
	.long	0x00005a00
	.long	0x0000f400
	.long	0x00001f00
	.long	0x0000dd00
	.long	0x0000a800
	.long	0x00003300
	.long	0x00008800
	.long	0x00000700
	.long	0x0000c700
	.long	0x00003100
	.long	0x0000b100
	.long	0x00001200
	.long	0x00001000
	.long	0x00005900
	.long	0x00002700
	.long	0x00008000
	.long	0x0000ec00
	.long	0x00005f00
	.long	0x00006000
	.long	0x00005100
	.long	0x00007f00
	.long	0x0000a900
	.long	0x00001900
	.long	0x0000b500
	.long	0x00004a00
	.long	0x00000d00
	.long	0x00002d00
	.long	0x0000e500
	.long	0x00007a00
	.long	0x00009f00
	.long	0x00009300
	.long	0x0000c900
	.long	0x00009c00
	.long	0x0000ef00
	.long	0x0000a000
	.long	0x0000e000
	.long	0x00003b00
	.long	0x00004d00
	.long	0x0000ae00
	.long	0x00002a00
	.long	0x0000f500
	.long	0x0000b000
	.long	0x0000c800
	.long	0x0000eb00
	.long	0x0000bb00
	.long	0x00003c00
	.long	0x00008300
	.long	0x00005300
	.long	0x00009900
	.long	0x00006100
	.long	0x00001700
	.long	0x00002b00
	.long	0x00000400
	.long	0x00007e00
	.long	0x0000ba00
	.long	0x00007700
	.long	0x0000d600
	.long	0x00002600
	.long	0x0000e100
	.long	0x00006900
	.long	0x00001400
	.long	0x00006300
	.long	0x00005500
	.long	0x00002100
	.long	0x00000c00
	.long	0x00007d00
	// Table 2.
	.long	0x00520000
	.long	0x00090000
	.long	0x006a0000
	.long	0x00d50000
	.long	0x00300000
	.long	0x00360000
	.long	0x00a50000
	.long	0x00380000
	.long	0x00bf0000
	.long	0x00400000
	.long	0x00a30000
	.long	0x009e0000
	.long	0x00810000
	.long	0x00f30000
	.long	0x00d70000
	.long	0x00fb0000
	.long	0x007c0000
	.long	0x00e30000
	.long	0x00390000
	.long	0x00820000
	.long	0x009b0000
	.long	0x002f0000
	.long	0x00ff0000
	.long	0x00870000
	.long	0x00340000
	.long	0x008e0000
	.long	0x00430000
	.long	0x00440000
	.long	0x00c40000
	.long	0x00de0000
	.long	0x00e90000
	.long	0x00cb0000
	.long	0x00540000
	.long	0x007b0000
	.long	0x00940000
	.long	0x00320000
	.long	0x00a60000
	.long	0x00c20000
	.long	0x00230000
	.long	0x003d0000
	.long	0x00ee0000
	.long	0x004c0000
	.long	0x00950000
	.long	0x000b0000
	.long	0x00420000
	.long	0x00fa0000
	.long	0x00c30000
	.long	0x004e0000
	.long	0x00080000
	.long	0x002e0000
	.long	0x00a10000
	.long	0x00660000
	.long	0x00280000
	.long	0x00d90000
	.long	0x00240000
	.long	0x00b20000
	.long	0x00760000
	.long	0x005b0000
	.long	0x00a20000
	.long	0x00490000
	.long	0x006d0000
	.long	0x008b0000
	.long	0x00d10000
	.long	0x00250000
	.long	0x00720000
	.long	0x00f80000
	.long	0x00f60000
	.long	0x00640000
	.long	0x00860000
	.long	0x00680000
	.long	0x00980000
	.long	0x00160000
	.long	0x00d40000
	.long	0x00a40000
	.long	0x005c0000
	.long	0x00cc0000
	.long	0x005d0000
	.long	0x00650000
	.long	0x00b60000
	.long	0x00920000
	.long	0x006c0000
	.long	0x00700000
	.long	0x00480000
	.long	0x00500000
	.long	0x00fd0000
	.long	0x00ed0000
	.long	0x00b90000
	.long	0x00da0000
	.long	0x005e0000
	.long	0x00150000
	.long	0x00460000
	.long	0x00570000
	.long	0x00a70000
	.long	0x008d0000
	.long	0x009d0000
	.long	0x00840000
	.long	0x00900000
	.long	0x00d80000
	.long	0x00ab0000
	.long	0x00000000
	.long	0x008c0000
	.long	0x00bc0000
	.long	0x00d30000
	.long	0x000a0000
	.long	0x00f70000
	.long	0x00e40000
	.long	0x00580000
	.long	0x00050000
	.long	0x00b80000
	.long	0x00b30000
	.long	0x00450000
	.long	0x00060000
	.long	0x00d00000
	.long	0x002c0000
	.long	0x001e0000
	.long	0x008f0000
	.long	0x00ca0000
	.long	0x003f0000
	.long	0x000f0000
	.long	0x00020000
	.long	0x00c10000
	.long	0x00af0000
	.long	0x00bd0000
	.long	0x00030000
	.long	0x00010000
	.long	0x00130000
	.long	0x008a0000
	.long	0x006b0000
	.long	0x003a0000
	.long	0x00910000
	.long	0x00110000
	.long	0x00410000
	.long	0x004f0000
	.long	0x00670000
	.long	0x00dc0000
	.long	0x00ea0000
	.long	0x00970000
	.long	0x00f20000
	.long	0x00cf0000
	.long	0x00ce0000
	.long	0x00f00000
	.long	0x00b40000
	.long	0x00e60000
	.long	0x00730000
	.long	0x00960000
	.long	0x00ac0000
	.long	0x00740000
	.long	0x00220000
	.long	0x00e70000
	.long	0x00ad0000
	.long	0x00350000
	.long	0x00850000
	.long	0x00e20000
	.long	0x00f90000
	.long	0x00370000
	.long	0x00e80000
	.long	0x001c0000
	.long	0x00750000
	.long	0x00df0000
	.long	0x006e0000
	.long	0x00470000
	.long	0x00f10000
	.long	0x001a0000
	.long	0x00710000
	.long	0x001d0000
	.long	0x00290000
	.long	0x00c50000
	.long	0x00890000
	.long	0x006f0000
	.long	0x00b70000
	.long	0x00620000
	.long	0x000e0000
	.long	0x00aa0000
	.long	0x00180000
	.long	0x00be0000
	.long	0x001b0000
	.long	0x00fc0000
	.long	0x00560000
	.long	0x003e0000
	.long	0x004b0000
	.long	0x00c60000
	.long	0x00d20000
	.long	0x00790000
	.long	0x00200000
	.long	0x009a0000
	.long	0x00db0000
	.long	0x00c00000
	.long	0x00fe0000
	.long	0x00780000
	.long	0x00cd0000
	.long	0x005a0000
	.long	0x00f40000
	.long	0x001f0000
	.long	0x00dd0000
	.long	0x00a80000
	.long	0x00330000
	.long	0x00880000
	.long	0x00070000
	.long	0x00c70000
	.long	0x00310000
	.long	0x00b10000
	.long	0x00120000
	.long	0x00100000
	.long	0x00590000
	.long	0x00270000
	.long	0x00800000
	.long	0x00ec0000
	.long	0x005f0000
	.long	0x00600000
	.long	0x00510000
	.long	0x007f0000
	.long	0x00a90000
	.long	0x00190000
	.long	0x00b50000
	.long	0x004a0000
	.long	0x000d0000
	.long	0x002d0000
	.long	0x00e50000
	.long	0x007a0000
	.long	0x009f0000
	.long	0x00930000
	.long	0x00c90000
	.long	0x009c0000
	.long	0x00ef0000
	.long	0x00a00000
	.long	0x00e00000
	.long	0x003b0000
	.long	0x004d0000
	.long	0x00ae0000
	.long	0x002a0000
	.long	0x00f50000
	.long	0x00b00000
	.long	0x00c80000
	.long	0x00eb0000
	.long	0x00bb0000
	.long	0x003c0000
	.long	0x00830000
	.long	0x00530000
	.long	0x00990000
	.long	0x00610000
	.long	0x00170000
	.long	0x002b0000
	.long	0x00040000
	.long	0x007e0000
	.long	0x00ba0000
	.long	0x00770000
	.long	0x00d60000
	.long	0x00260000
	.long	0x00e10000
	.long	0x00690000
	.long	0x00140000
	.long	0x00630000
	.long	0x00550000
	.long	0x00210000
	.long	0x000c0000
	.long	0x007d0000
	// Table 3.
	.long	0x52000000
	.long	0x09000000
	.long	0x6a000000
	.long	0xd5000000
	.long	0x30000000
	.long	0x36000000
	.long	0xa5000000
	.long	0x38000000
	.long	0xbf000000
	.long	0x40000000
	.long	0xa3000000
	.long	0x9e000000
	.long	0x81000000
	.long	0xf3000000
	.long	0xd7000000
	.long	0xfb000000
	.long	0x7c000000
	.long	0xe3000000
	.long	0x39000000
	.long	0x82000000
	.long	0x9b000000
	.long	0x2f000000
	.long	0xff000000
	.long	0x87000000
	.long	0x34000000
	.long	0x8e000000
	.long	0x43000000
	.long	0x44000000
	.long	0xc4000000
	.long	0xde000000
	.long	0xe9000000
	.long	0xcb000000
	.long	0x54000000
	.long	0x7b000000
	.long	0x94000000
	.long	0x32000000
	.long	0xa6000000
	.long	0xc2000000
	.long	0x23000000
	.long	0x3d000000
	.long	0xee000000
	.long	0x4c000000
	.long	0x95000000
	.long	0x0b000000
	.long	0x42000000
	.long	0xfa000000
	.long	0xc3000000
	.long	0x4e000000
	.long	0x08000000
	.long	0x2e000000
	.long	0xa1000000
	.long	0x66000000
	.long	0x28000000
	.long	0xd9000000
	.long	0x24000000
	.long	0xb2000000
	.long	0x76000000
	.long	0x5b000000
	.long	0xa2000000
	.long	0x49000000
	.long	0x6d000000
	.long	0x8b000000
	.long	0xd1000000
	.long	0x25000000
	.long	0x72000000
	.long	0xf8000000
	.long	0xf6000000
	.long	0x64000000
	.long	0x86000000
	.long	0x68000000
	.long	0x98000000
	.long	0x16000000
	.long	0xd4000000
	.long	0xa4000000
	.long	0x5c000000
	.long	0xcc000000
	.long	0x5d000000
	.long	0x65000000
	.long	0xb6000000
	.long	0x92000000
	.long	0x6c000000
	.long	0x70000000
	.long	0x48000000
	.long	0x50000000
	.long	0xfd000000
	.long	0xed000000
	.long	0xb9000000
	.long	0xda000000
	.long	0x5e000000
	.long	0x15000000
	.long	0x46000000
	.long	0x57000000
	.long	0xa7000000
	.long	0x8d000000
	.long	0x9d000000
	.long	0x84000000
	.long	0x90000000
	.long	0xd8000000
	.long	0xab000000
	.long	0x00000000
	.long	0x8c000000
	.long	0xbc000000
	.long	0xd3000000
	.long	0x0a000000
	.long	0xf7000000
	.long	0xe4000000
	.long	0x58000000
	.long	0x05000000
	.long	0xb8000000
	.long	0xb3000000
	.long	0x45000000
	.long	0x06000000
	.long	0xd0000000
	.long	0x2c000000
	.long	0x1e000000
	.long	0x8f000000
	.long	0xca000000
	.long	0x3f000000
	.long	0x0f000000
	.long	0x02000000
	.long	0xc1000000
	.long	0xaf000000
	.long	0xbd000000
	.long	0x03000000
	.long	0x01000000
	.long	0x13000000
	.long	0x8a000000
	.long	0x6b000000
	.long	0x3a000000
	.long	0x91000000
	.long	0x11000000
	.long	0x41000000
	.long	0x4f000000
	.long	0x67000000
	.long	0xdc000000
	.long	0xea000000
	.long	0x97000000
	.long	0xf2000000
	.long	0xcf000000
	.long	0xce000000
	.long	0xf0000000
	.long	0xb4000000
	.long	0xe6000000
	.long	0x73000000
	.long	0x96000000
	.long	0xac000000
	.long	0x74000000
	.long	0x22000000
	.long	0xe7000000
	.long	0xad000000
	.long	0x35000000
	.long	0x85000000
	.long	0xe2000000
	.long	0xf9000000
	.long	0x37000000
	.long	0xe8000000
	.long	0x1c000000
	.long	0x75000000
	.long	0xdf000000
	.long	0x6e000000
	.long	0x47000000
	.long	0xf1000000
	.long	0x1a000000
	.long	0x71000000
	.long	0x1d000000
	.long	0x29000000
	.long	0xc5000000
	.long	0x89000000
	.long	0x6f000000
	.long	0xb7000000
	.long	0x62000000
	.long	0x0e000000
	.long	0xaa000000
	.long	0x18000000
	.long	0xbe000000
	.long	0x1b000000
	.long	0xfc000000
	.long	0x56000000
	.long	0x3e000000
	.long	0x4b000000
	.long	0xc6000000
	.long	0xd2000000
	.long	0x79000000
	.long	0x20000000
	.long	0x9a000000
	.long	0xdb000000
	.long	0xc0000000
	.long	0xfe000000
	.long	0x78000000
	.long	0xcd000000
	.long	0x5a000000
	.long	0xf4000000
	.long	0x1f000000
	.long	0xdd000000
	.long	0xa8000000
	.long	0x33000000
	.long	0x88000000
	.long	0x07000000
	.long	0xc7000000
	.long	0x31000000
	.long	0xb1000000
	.long	0x12000000
	.long	0x10000000
	.long	0x59000000
	.long	0x27000000
	.long	0x80000000
	.long	0xec000000
	.long	0x5f000000
	.long	0x60000000
	.long	0x51000000
	.long	0x7f000000
	.long	0xa9000000
	.long	0x19000000
	.long	0xb5000000
	.long	0x4a000000
	.long	0x0d000000
	.long	0x2d000000
	.long	0xe5000000
	.long	0x7a000000
	.long	0x9f000000
	.long	0x93000000
	.long	0xc9000000
	.long	0x9c000000
	.long	0xef000000
	.long	0xa0000000
	.long	0xe0000000
	.long	0x3b000000
	.long	0x4d000000
	.long	0xae000000
	.long	0x2a000000
	.long	0xf5000000
	.long	0xb0000000
	.long	0xc8000000
	.long	0xeb000000
	.long	0xbb000000
	.long	0x3c000000
	.long	0x83000000
	.long	0x53000000
	.long	0x99000000
	.long	0x61000000
	.long	0x17000000
	.long	0x2b000000
	.long	0x04000000
	.long	0x7e000000
	.long	0xba000000
	.long	0x77000000
	.long	0xd6000000
	.long	0x26000000
	.long	0xe1000000
	.long	0x69000000
	.long	0x14000000
	.long	0x63000000
	.long	0x55000000
	.long	0x21000000
	.long	0x0c000000
	.long	0x7d000000
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/EncryptDecrypt.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/*	This file defines _aes_encrypt or _aes_decrypt, according to the value of
	the Select preprocessor symbol.  This file is designed to be included in
	another assembly file using the preprocessor #include directive, to benefit
	from some assembly-time calculations.

	These two routines are nearly identical.  They differ only in the tables
	they use, the direction they iterate through the key, and the permutation
	performed on part of the state.

	Written by Eric Postpischil, January 2008.
*/

/* add AES HW detection and HW-specific program branch cclee 3-12-10 */

#include <System/i386/cpu_capabilities.h>

#if Select == 0
	#define	Name		_aes_encrypt				// Routine name.
	#define	MTable		_AESEncryptTable			// Main table.
	#define	FTable		_AESSubBytesWordTable		// Final table.
	#define	P0			S0							// State permutation.
	#define	P1			S1
	#define	P2			S2
	#define	P3			S3
	#define	Increment	+16							// ExpandedKey increment.
#elif Select == 1
	#define	Name		_aes_decrypt				// Routine name.
	#define	MTable		_AESDecryptTable			// Main table.
	#define	FTable		_AESInvSubBytesWordTable	// Final table.
	#define	P0			S2							// State permutation.
	#define	P1			S3
	#define	P2			S0
	#define	P3			S1
	#define	Increment	-16							// ExpandedKey increment.
#elif Select == 2
	#define	Name		_aes_encrypt_xmm_no_save	// Routine name.
	#define	MTable		_AESEncryptTable			// Main table.
	#define	FTable		_AESSubBytesWordTable		// Final table.
	#define	P0			S0							// State permutation.
	#define	P1			S1
	#define	P2			S2
	#define	P3			S3
	#define	Increment	+16							// ExpandedKey increment.
#elif Select == 3
	#define	Name		_aes_decrypt_xmm_no_save	// Routine name.
	#define	MTable		_AESDecryptTable			// Main table.
	#define	FTable		_AESInvSubBytesWordTable	// Final table.
	#define	P0			S2							// State permutation.
	#define	P1			S3
	#define	P2			S0
	#define	P3			S1
	#define	Increment	-16							// ExpandedKey increment.
#endif	// Select


/*	Routine:

		_AESEncryptWithExpandedKey (if Select is 0) or
		_AESDecryptWithExpandedKey (if Select is 1).

	Function:

		Perform the AES cipher or its inverse as defined in Federal Information
		Processing Standards Publication 197 (FIPS-197), November 26, 2001.

		The inverse cipher here is the "Equivalent Inverse Cipher" in FIPS-197.

	Input:

		Constant data:

			The following names must be locally defined so the assembler
			can calculate certain offsets.
				
			For encryption:

				static const Word _AESEncryptTable[4][256].

					_AESEncryptTable[i] contains the tables T[i] defined in AES
					Proposal: Rijndael, version 2, 03/09/99, by Joan Daemen and
					Vincent Rijmen, section 5.2.1, page 18.  These tables
					combine the SubBytes and MixColumns operations.

				static const Word _AESSubBytesWordTable[256].

					_AESSubBytesWordTable[i][j] = SubBytes(j) << 8*i, where
					SubBytes is defined in FIPS-197.  _AESSubBytesWordTable
					differs from _AESEncryptTable in that it does not include
					the MixColumn operation.  It is used in performing the last
					round, which differs fromm the previous rounds in that it
					does not include the MixColumn operation.

			For decryption:

				static const Word _AESDecryptTable[4][256].

					The analog of _AESEncryptTable for decryption.

				static const Word _AESSubBytesWordTable[256].

					_AESInvSubBytesWordTable[i][j] = InvSubBytes(j) << 8*i,
					where InvSubBytes is defined in FIPS-197.
					_AESInvSubBytesWordTable differs from _AESDecryptTable in
					that it does not include the InvMixColumn operation.  It is
					used in performing the last round, which differs from the
					previous rounds in that it does not include the
					InvMixColumn operation.

		Arguments:

			const Byte *InputText.

				Address of input, 16 bytes.  Best if four-byte aligned.

			Byte *OutputText.

				Address of output, 16 bytes.  Best if four-byte aligned.

			aes_encrypt_ctx *Context or aes_decrypt_ctx *Context

				aes_encrypt_ctx and aes_decrypt_ctx are identical except the
				former is used for encryption and the latter for decryption.

				Each is a structure containing the expanded key beginning at
				offset ContextKey and a four-byte "key length" beginning at
				offset ContextKeyLength.  The "key length" is the number of
				bytes from the start of the first round key to the start of the
				last round key.  That is 16 less than the number of bytes in
				the entire key.

	Output:

		Encrypted or decrypted data is written to *OutputText.

	Return:

		aes_rval	// -1 if "key length" is invalid.  0 otherwise.
*/

	.text
	.globl Name
Name:

    // detect AES HW, cclee 3-13-10
#if Select < 2												// only for aes_encrypt/aes_decrypt
#if defined __x86_64__
    movq    __cpu_capabilities@GOTPCREL(%rip), %rax			// %rax -> __cpu_capabilities
    mov     (%rax), %eax									// %eax = __cpu_capabilities
#else
#ifdef	KERNEL
    leal    __cpu_capabilities, %eax						// %eax -> __cpu_capabilities
    mov     (%eax), %eax									// %eax = __cpu_capabilities
#else
	mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
#endif
#endif
    test    $(kHasAES), %eax								// __cpu_capabilities & kHasAES
#if Select == 0
    jne     _aes_encrypt_hw									// if AES HW detected, branch to HW specific code
#else
    jne     _aes_decrypt_hw									// if AES HW detected, branch to HW specific code
#endif
#endif		// Select

	// Push new stack frame.
	push	r5

	/*	Save registers and set SaveSize to the number of bytes pushed onto the
		stack so far, including the caller's return address.
	*/
	push	r3
	#if defined __i386__
		push	r6
		push	r7
		#define	SaveSize	(5*4)
	#else
		#define	SaveSize	(3*8)
	#endif

	/*	Number of bytes used for local variables:

			4 (i386) or 0 (x86_64) bytes for ExpandedKeyEnd.

			5 (i386) or 3 (x86_64) 16-byte spaces to save XMM registers.
	*/
	#define	LocalsSize	(Arch(4, 0) + Arch(5, 3)*16)

	#if 0 < LocalsSize
		// Padding to position stack pointer at a multiple of 16 bytes.
		#define	Padding	(15 & -(SaveSize + LocalsSize))
		sub		$Padding + LocalsSize, r4	// Allocate space on stack.
	#else
		#define	Padding	0
	#endif

#ifdef KERNEL
#if	Select < 2
	// Save XMM registers.
	movaps	%xmm0, 0*16(r4)
	movaps	%xmm1, 1*16(r4)
	movaps	%xmm2, 2*16(r4)
#if defined __i386__
	movaps	%xmm3, 3*16(r4)
	movaps	%xmm4, 4*16(r4)
#endif
#endif	// Select
#endif	// KERNEL

#if defined __i386__

	// Number of bytes from caller's stack pointer to ours.
	#define	StackFrame	(SaveSize + Padding + LocalsSize)

	// Define location of argument i (presuming 4-byte arguments).
	#define	Argument(i)	StackFrame+4*(i)(%esp)

	#define	ArgInputText	Argument(0)
	#define	ArgOutputText	Argument(1)
	#define	ArgContext		Argument(2)

#elif defined __x86_64__

	// Arguments.
	#define	InputText		r7	// Used early then overwritten for other use.
	#define	OutputText		r6	// Needed near end of routine.
	#define	ArgContext		r2
		/*	The argument passed in r2 overlaps registers we need for other
		 	work, so it must be moved early in the routine.
		*/

#endif

#define	BaseP		Arch(r6, r9)	// Base pointer for addressing global data.
#define	ExpandedKey	Arch(t0, r10)	// Address of expanded key.

/*	The Work registers defined below are used to hold parts of the AES state
	while we dissect or assemble it.  They must be assigned to the A, B, C, and
	D registers so that we can access the bytes in %al, %ah, and so on.
*/
#define	Work0d	r0d
#define	Work0l	r0l
#define	Work0h	r0h
#define	Work1d	r3d
#define	Work1l	r3l
#define	Work1h	r3h
#define	Work2d	r1d
#define	Work2l	r1l
#define	Work2h	r1h
#define	Work3d	r2d
#define	Work3l	r2l
#define	Work3h	r2h

#define	t0		r5
#define	t0d		r5d		// Low 32 bits of t0.
#define	t0l		r5l		// Low byte of t0.

#define	t1		r7

/*	S0, S1, S2, and S3 are where we assemble the new AES state when computing
	a regular round.  S1, S2, and S3 are assigned to the Work registers, but
	S0 needs to go somewhere else because Work0 holds part of the old state.
*/
#define	S0		Arch(t1, r8d)
#define	S1		Work1d
#define	S2		Work2d
#define	S3		Work3d

/*	These XMM registers are used as holding space, because it is faster to
	spill to these registers than to the stack.  (On x86_64, we do not need
	to spill, because there are additional general registers available.
	However, using more general registers requires saving them to the stack
	and restoring them.  I timed it, and no time was saved.)
*/
#define	vS1		%xmm0
#define	vS2		%xmm1
#define	vS3		%xmm2
#if defined __i386__
	#define	vExpandedKey	%xmm3
	#define	vIncrement		%xmm4
#endif

	// Get address of expanded key.
	mov	ArgContext, ExpandedKey
	#if 0 != ContextKey
		add		$ContextKey, ExpandedKey
	#endif

/*	Store sentinel value of ExpandedKey on the stack on i386, a register on
 	x86_64.
*/
#define	ExpandedKeyEnd	Arch(5*16(r4), r11)

	// Get and check "key length".
	movzx	ContextKeyLength(ExpandedKey), r0
	cmp		$160, r0
	je		2f
	cmp		$192, r0
	je		2f
	cmp		$224, r0
	je		2f
	mov		$-1, r0		// Return error.
	jmp		9f
2:

	#if (Select == 0 || Select == 2)
		// For encryption, prepare to iterate forward through expanded key.
		add		ExpandedKey, r0
		mov		r0, ExpandedKeyEnd
	#else
		// For decryption, prepare to iterate backward through expanded key.
		mov		ExpandedKey, ExpandedKeyEnd
		add		r0, ExpandedKey
	#endif

	// Initialize State from input text.
	#if defined __i386__
		mov		ArgInputText, BaseP
		#define	InputText	BaseP
	#endif
	mov		0*4(InputText), Work0d
	mov		1*4(InputText), S1
	mov		2*4(InputText), S2
	mov		3*4(InputText), S3
#undef	InputText	// Register is reused after this for other purposes.

	// Add round key and save results.
	xor		0*4(ExpandedKey), Work0d	// S0 is in dissection register.
	xor		1*4(ExpandedKey), S1
	movd	S1, vS1						// Save S1 to S3 in vector registers.
	xor		2*4(ExpandedKey), S2
	movd	S2, vS2
	xor		3*4(ExpandedKey), S3
	movd	S3, vS3

	add		$Increment, ExpandedKey		 // Advance to next round key.

	#if defined __i386__
		// Save expanded key address and increment in vector registers.
		mov		$Increment, t1
		movp	ExpandedKey, vExpandedKey
		movp	t1, vIncrement
	#endif

	// Set up relative addressing.
	#if defined __i386__

		// Get address of 0 in BaseP.
			call	0f				// Push program counter onto stack.
		0:
			pop		BaseP			// Get program counter.

		// Define macros to help address data.
#define	LookupM(table, index)	MTable-0b+(table)*TableSize(BaseP, index, 4)
#define LookupF(table, index)	FTable-0b+(table)*TableSize(BaseP, index, 4)

	#elif defined __x86_64__

		lea	MTable(%rip), BaseP

		// Define macros to help address data.
		#define	LookupM(table, index)	(table)*TableSize(BaseP, index, 4)
		#define	LookupF(table, index)	(table)*TableSize(BaseP, index, 4)

/*	With these definitions of LookupM and LookupF, BaseP must be loaded with
	the address of the table at the point where it is used.  So we need an
	instruction to change BaseP after we are done with MTable and before we
	start using FTable.  I would prefer to use something like:

		.set	FMinusM, FTable - MTable
		#define LookupF(table, index)	\
			FMinusM+(table)*TableSize(BaseP, index, 4)

	Then BaseP would not need to change.  However, this fails due to an
	assembler/linker bug, <rdar://problem/5683882>.
*/

	#endif

	// Get round key.
	mov		0*4(ExpandedKey), S0
	mov		1*4(ExpandedKey), S1
	mov		2*4(ExpandedKey), S2
	mov		3*4(ExpandedKey), S3

1:
	/*	Word 0 of the current state must be in Work0 now, and the next round
		key must be in S0 to S3.
	*/

	// Process previous S0.
	movzx	Work0l, t0
	xor		LookupM(0, t0), S0
	movzx	Work0h, t0d
	xor		LookupM(1, t0), P3
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupM(2, t0), S2
	movzx	Work0h, t0d
	xor		LookupM(3, t0), P1

	// Process previous S1.
	movd	vS1, Work0d
	movzx	Work0l, t0d
	xor		LookupM(0, t0), S1
	movzx	Work0h, t0d
	xor		LookupM(1, t0), P0
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupM(2, t0), S3
	movzx	Work0h, t0d
	xor		LookupM(3, t0), P2

	// Process previous S2.
	movd	vS2, Work0d
	movzx	Work0l, t0d
	xor		LookupM(0, t0), S2
	movzx	Work0h, t0d
	xor		LookupM(1, t0), P1
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupM(2, t0), S0
	movzx	Work0h, t0d
	xor		LookupM(3, t0), P3

	// Process previous S3.
	movd	vS3, Work0d
	movzx	Work0l, t0d
	xor		LookupM(0, t0), S3
	movzx	Work0h, t0d
	xor		LookupM(1, t0), P2
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupM(2, t0), S1
	movzx	Work0h, t0d
	xor		LookupM(3, t0), P0

	#if defined __i386__
		paddd	vIncrement, vExpandedKey
		movp	vExpandedKey, ExpandedKey
	#else
		add		$Increment, ExpandedKey
	#endif

	// Save state for next iteration and load next round key.
	mov		S0, Work0d
	mov		0*4(ExpandedKey), S0
	movd	S1, vS1
	mov		1*4(ExpandedKey), S1
	movd	S2, vS2
	mov		2*4(ExpandedKey), S2
	movd	S3, vS3
	mov		3*4(ExpandedKey), S3

	cmp		ExpandedKeyEnd, ExpandedKey
	jne		1b

	/*	Word 0 of the current state must be in Work0 now, and the next round
		key must be in S0 to S3.
	*/

	// Work around assembler bug.  See comments above about Radar 5683882.
	#if defined __x86_64__
		lea	FTable(%rip), BaseP
	#endif

	// Process previous S0.
	movzx	Work0l, t0
	xor		LookupF(0, t0), S0
	movzx	Work0h, t0d
	xor		LookupF(1, t0), P3
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupF(2, t0), S2
	movzx	Work0h, t0d
	xor		LookupF(3, t0), P1

	// Process previous S1.
	movd	vS1, Work0d
	movzx	Work0l, t0d
	xor		LookupF(0, t0), S1
	movzx	Work0h, t0d
	xor		LookupF(1, t0), P0
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupF(2, t0), S3
	movzx	Work0h, t0d
	xor		LookupF(3, t0), P2

	// Process previous S2.
	movd	vS2, Work0d
	movzx	Work0l, t0d
	xor		LookupF(0, t0), S2
	movzx	Work0h, t0d
	xor		LookupF(1, t0), P1
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupF(2, t0), S0
	movzx	Work0h, t0d
	xor		LookupF(3, t0), P3

	// Process previous S3.
	movd	vS3, Work0d
	movzx	Work0l, t0d
	xor		LookupF(0, t0), S3
	movzx	Work0h, t0d
	xor		LookupF(1, t0), P2
	shr		$16, Work0d
	movzx	Work0l, t0d
	xor		LookupF(2, t0), S1
	movzx	Work0h, t0d
	xor		LookupF(3, t0), P0

	#if defined __i386__	// Architecture.
		// Get OutputText address.
		#define	OutputText	BaseP
		mov		ArgOutputText, OutputText
	#endif	// Architecture.

	// Write output.
	mov		S0, 0*4(OutputText)
	mov		S1, 1*4(OutputText)
	mov		S2, 2*4(OutputText)
	mov		S3, 3*4(OutputText)

	xor		r0, r0		// Return success.

9:
	// Pop stack and restore registers.
#ifdef	KERNEL
#if	Select < 2
#if defined __i386__
	movaps	4*16(r4), %xmm4
	movaps	3*16(r4), %xmm3
#endif
	movaps	2*16(r4), %xmm2
	movaps	1*16(r4), %xmm1
	movaps	0*16(r4), %xmm0
#endif	// Select
#endif	// KERNEL
	#if 0 < LocalsSize
		add		$Padding + LocalsSize, r4
	#endif
	#if defined __i386__
		pop		r7
		pop		r6
	#elif defined __x86_64__
	#endif
	pop		r3
	pop		r5

	ret


#undef	ArgExpandedKey
#undef	ArgInputText
#undef	ArgNr
#undef	ArgOutputText
#undef	Argument
#undef	BaseP
#undef	ExpandedKey
#undef	ExpandedKeyEnd
#undef	FTable
#undef	InputText
#undef	LocalsSize
#undef	LookupM
#undef	LookupF
#undef	MTable
#undef	OutputText
#undef	Padding
#undef	SaveSize
#undef	S0
#undef	S1
#undef	S2
#undef	S3
#undef	StackFrame
#undef	Work0d
#undef	Work0h
#undef	Work0l
#undef	Work1d
#undef	Work1h
#undef	Work1l
#undef	Work2d
#undef	Work2h
#undef	Work2l
#undef	Work3d
#undef	Work3h
#undef	Work3l
#undef	t0
#undef	t0d
#undef	t0l
#undef	t1
#undef	vExpandedKey
#undef	vS1
#undef	vS2
#undef	vS3

#undef	Name
#undef	MTable
#undef	FTable
#undef	P0
#undef	P1
#undef	P2
#undef	P3
#undef	Increment
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/ExpandKeyForDecryption.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
/*	This file defines _aes_decrypt_key, _aes_decrypt_key128,
	_aes_decrypt_key192, and _aes_decrypt_key256.  It is designed to be
	included in another assembly file with the preprocessor #include directive,
	to benefit from some assembly-time calculations.

	Written by Eric Postpischil, January 2008.

	The comments here do not say much about the algorithm; the code just
	follows the FIPS-197 specification.  I recommend reading the specification
	before working with this code or examining the C code in the parent
	directory that illustrates key expansion.

	One complication is that this routine both expands the key and applies
	InvMixColumn to most of the words in the expanded key.  This modifies the
	key for use with the Equivalent Inverse Cipher.

	During key expansion, there are sequences of four or six words that are
	produced like this:

		E[i+0] = E[i+0-Nk] ^ f(E[i-1]), where f is some function.
		E[i+1] = E[i+1-Nk] ^ E[i+0].
		E[i+2] = E[i+2-Nk] ^ E[i+1].
		E[i+3] = E[i+3-Nk] ^ E[i+2].

	When Nk is four or eight, the sequence stops there.  When it is six, it
	goes on for two more words.  Let I be the InvMixColumn function.  for the
	Equivalent Inverse Cipher, we want to store I(E[i+0]), I(E[i+1]),
	I(E[i+2]), I(E[i+3]) (and two more when Nk is six).  However, we do not
	need to calculate I four times.  In AES' finite field, I is a linear
	combination of the four bytes of its input.  The ^ operation on the bits
	that represent field elements is an addition in the Galois field.  So
	I(a ^ b) = I(a) ^ I(b).  Then we have:

		I(E[i+0]) = I(E[i+0-Nk] ^ f(E[i-1])) = I(E[i+0-Nk]) ^ I(f(E[i-1])).
		I(E[i+1]) = I(E[i+1-Nk]) ^ I(E[i+0]).
		I(E[i+2]) = I(E[i+2-Nk]) ^ I(E[i+1]).
		I(E[i+3]) = I(E[i+3-Nk]) ^ I(E[i+2]).

	To compute this, we compute I(f(E[i-1])) and XOR it with the previously
	stored E[i+0-Nk])) to get I(E[i+0])).  Then we XOR that with the previously
	stored E[i+1-Nk])) to get I(E[i+1])), and so on.

	Note that to compute I(f(E[i-1])), we need to have E[i-1].  So we have to
	compute the pre-InvMixColumn words of the expanded key; it is not
	sufficient to have the post-InvMixColumn words.
*/


/*	Routine:

		_aes_decrypt_key.

		_aes_decrypt_key128, _aes_decrypt_key192, and _aes_decrypt_key256.

	Function:

		Expand the user's cipher key into the key schedule, as defined in
		Federal Information Processing Standards Publication 197 (FIPS-197),
		November 26, 2001.

		For decryption, the key is modified as shown in Figure 15 in FIPS-197,
		to support the Equivalent Inverse Cipher.

	Input:

		Constant data:

			The following names must be locally defined so the assembler
			can calculate certain offsets.

			static const Word _AESSubBytesWordTable[4][256].

				_AESSubBytesWordTable[i][j] = SubBytes(j) << 8*i, where
				SubBytes is defined in FIPS-197.  _AESSubBytesWordTable
				differs from _AESEncryptTable in that it does not include
				the MixColumn operation.  It is used in performing the last
				round, which differs fromm the previous rounds in that it
				does not include the MixColumn operation.

			static const Word _AESSInvMixColumnTable[4][256].

				_AESInvMixColumnTable[i][j] contains the contribution of byte
				j to element i of the InvMixColumn operation.

				The four bytes of the word _AESInvMixColumnTable[0][j] are:

					{0xe}*{j}, {0x9}*{j}, {0xd}*{j}, {0xb}*{j},

				listed in increasing address order, where multiplication is
				performed in the Galois field.  {j} designates the element of
				the Galois field represented by j.  _AESInvMixColumn[i][j] has
				the same bytes, rotated right in the order shown above.

			static const Byte _AESRcon[].

				Round constants, beginning with AESRcon[1] for the first round
				(AESRcon[0] is padding.)
	
		Arguments:

			const unsigned char *Key

				Address of user's cipher key.

			int Length

				Number of bytes (16, 24, or 32) or bits (128, 192, or 256) in
				user's cipher key.

				This argument is used with _aes_decrypt_key.  It is not
				present for the other routines.  In those routines, Context
				is the second argument.

			aes_decrypt_ctx *Context

				Structure to contain the expanded key beginning at offset
				ContextKey and a four-byte "key length" beginning at offset
				ContextKeyLength.  The "key length" is the number of bytes from
				the start of the first round key to the startof the last rond
				key.  That is 16 less than the number of bytes in the entire
				key.

	Output:

		The expanded key and the "key length" are written to *Context.

	Return:

		aes_rval	// -1 if "key length" is invalid.  0 otherwise.
*/
/* add AES HW detection and program branch if AES HW is detected cclee 3-12-10 */

#include <System/i386/cpu_capabilities.h>

#define	dr		r0d				// Dissection register.
#define	drl		r0l				// Low 8 bits of dissection register.
#define	drh		r0h				// Second-lowest 8 bits of dissection register.

#define	t0		r1
#define	t0d		r1d				// Low 32 bits of t0.

#define	STable	r2				// Address of SubBytes table.  Overlaps Nk.
#define	ITable	r3				// Address of InvMixColumn table.
#define	offset	Arch(r5, r11)	// Address offset and loop sentinel.

#define	R		r7				// Address of round constant.
#define	K		r7				// User key pointer.
	// R and K overlap.

#define	E		r6				// Expanded key pointer.

#define	ve0		%xmm0
#define	ve1		%xmm1
#define	ve2		%xmm2
#define	ve3		%xmm3
#define	ve4		%xmm4
#define	ve5		%xmm5
#define	vt1		%xmm6
#define	vt0		%xmm7

#define	LookupS(table, index)	(table)*TableSize(STable, index, 4)
#define	LookupI(table, index)	(table)*TableSize(ITable, index, 4)


/*	InvMixColumn puts InvMixColumn(dr) into vt0.  This is a non-standard
	subroutine.  It does not conform to the ABI.  It is an integral part of
	_ExpandKeyForDecryption and shares register use with it.
*/
InvMixColumn:
	movzx	drl, t0
	movd	LookupI(0, t0), vt0		// Look up byte 0 in table 0.
	movzx	drh, t0d
	movd	LookupI(1, t0), vt1		// Look up byte 1 in table 1.
	pxor	vt1, vt0
	shr		$16, dr
	movzx	drl, t0d
	movd	LookupI(2, t0), vt1		// Look up byte 2 in table 2.
	pxor	vt1, vt0
	movzx	drh, t0d
	movd	LookupI(3, t0), vt1		// Look up byte 3 in table 3.
	pxor	vt1, vt0
	ret


	// SubWordRotWord adds (XORs) SubWord(RotWord(dr)) to vt0.
	.macro	SubWordRotWord
		movzx	drl, t0
		movd	LookupS(3, t0), vt1		// Look up byte 0 in table 3.
		pxor	vt1, vt0
		movzx	drh, t0d
		movd	LookupS(0, t0), vt1		// Look up byte 1 in table 0.
		pxor	vt1, vt0
		shr		$$16, dr
		movzx	drl, t0d
		movd	LookupS(1, t0), vt1		// Look up byte 2 in table 1.
		pxor	vt1, vt0
		movzx	drh, t0d
		movd	LookupS(2, t0), vt1		// Look up byte 3 in table 2.
		pxor	vt1, vt0
	.endmacro


	// SubWord puts SubWord(dr) into vt0.
	.macro	SubWord
		movzx	drl, t0
		movd	LookupS(0, t0), vt0		// Look up byte 0 in table 0.
		movzx	drh, t0d
		movd	LookupS(1, t0), vt1		// Look up byte 1 in table 1.
		pxor	vt1,vt0
		shr		$$16, dr
		movzx	drl, t0d
		movd	LookupS(2, t0), vt1		// Look up byte 2 in table 2.
		pxor	vt1,vt0
		movzx	drh, t0d
		movd	LookupS(3, t0), vt1		// Look up byte 3 in table 3.
		pxor	vt1,vt0
	.endmacro

	.text
	.globl _aes_decrypt_key
//	.private_extern	_aes_decrypt_key
_aes_decrypt_key:

	// detect AES HW, cclee 3-13-10
#if defined __x86_64__
    movq    __cpu_capabilities@GOTPCREL(%rip), %rax				// %rax -> __cpu_capabilities
    mov     (%rax), %eax										// %eax  = __cpu_capabilities
#else
#ifdef	KERNEL
    leal    __cpu_capabilities, %eax							// %eax -> __cpu_capabilities
    mov     (%eax), %eax										// %eax  = __cpu_capabilities
#else
	mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
#endif
#endif
    test    $(kHasAES), %eax									// __cpu_capabilities & kHasAES
    jne     _aes_decrypt_key_hw									// if AES HW detected, branch to _aes_decrypt_key_hw

	/*	Save registers and set SaveSize to the number of bytes pushed onto the
		stack so far, including the caller's return address.
	*/
	push	r3
	#if defined __i386__
		push	r5
		push	r6
		push	r7
		#define	SaveSize	(5*4)
	#else
		#define	SaveSize	(2*8)
	#endif

	/*	Number of bytes used for local variables:

			8 16-byte spaces to save XMM registers.

			8 four-byte spaces for work.
	*/
	#define	LocalsSize	(8*16 + 8*4)

	// Define stack offset to storage space for local data.
	#define	Local	(8*16)

	#if 0 < LocalsSize
		// Padding to position stack pointer at a multiple of 16 bytes.
		#define	Padding	(15 & -(SaveSize + LocalsSize))
		sub		$Padding + LocalsSize, r4	// Allocate space on stack.
	#else
		#define	Padding	0
	#endif

	/*	StackFrame is the number of bytes in our stack frame, from caller's
		stack pointer to ours (so it includes the return address).
	*/
	#define	StackFrame	(SaveSize + Padding + LocalsSize)

	// Save xmm registers.
	movaps	%xmm0, 0*16(r4)
	movaps	%xmm1, 1*16(r4)
	movaps	%xmm2, 2*16(r4)
	movaps	%xmm3, 3*16(r4)
	movaps	%xmm4, 4*16(r4)
	movaps	%xmm5, 5*16(r4)
	movaps	%xmm6, 6*16(r4)
	movaps	%xmm7, 7*16(r4)

#if defined __i386__

	// Define location of argument i.
	#define	Argument(i)	StackFrame+4*(i)(r4)

	#define	Nk		t0d

	// Load arguments.
	mov		Argument(2), E
	mov		Argument(1), Nk
	mov		Argument(0), K

#elif defined __x86_64__

	#define	Nk		r9d			// Number of words in key.
	mov		r6d, Nk				// Move Nk argument out of way.
	mov		r2, E				// Move E argument to common register.

#endif

	// Dispatch on key length.
	cmp		$128, Nk
	jge		2f
	shl		$3, Nk				// Convert from bytes to bits.
	cmp		$128, Nk
2:
	je		DKeyHas4Words
	cmp		$192, Nk
	je		DKeyHas6Words
	cmp		$256, Nk
	je		DKeyHas8Words
	mov		$-1, r0				// Return error.
	jmp		9f


	.globl _aes_decrypt_key128
//	.private_extern	_aes_decrypt_key128
_aes_decrypt_key128:

	/*	Save registers and set SaveSize to the number of bytes pushed onto the
		stack so far, including the caller's return address.
	*/
	push	r3
	#if defined __i386__
		push	r5
		push	r6
		push	r7
		#define	SaveSize	(5*4)
	#else
		#define	SaveSize	(2*8)
	#endif

	/*	Number of bytes used for local variables:

			8 16-byte spaces to save XMM registers.

			8 four-byte spaces for work.
	*/
	#define	LocalsSize	(8*16 + 8*4)

	// Define stack offset to storage space for local data.
	#define	Local	(8*16)

	#if 0 < LocalsSize
		// Padding to position stack pointer at a multiple of 16 bytes.
		#define	Padding	(15 & -(SaveSize + LocalsSize))
		sub		$Padding + LocalsSize, r4	// Allocate space on stack.
	#else
		#define	Padding	0
	#endif

	/*	StackFrame is the number of bytes in our stack frame, from caller's
		stack pointer to ours (so it includes the return address).
	*/
	#define	StackFrame	(SaveSize + Padding + LocalsSize)

	// Save xmm registers.
	movaps	%xmm0, 0*16(r4)
	movaps	%xmm1, 1*16(r4)
	movaps	%xmm2, 2*16(r4)
	movaps	%xmm3, 3*16(r4)
	movaps	%xmm4, 4*16(r4)
	movaps	%xmm5, 5*16(r4)
	movaps	%xmm6, 6*16(r4)
	movaps	%xmm7, 7*16(r4)

#if defined __i386__

	// Load arguments.
	#define	Argument(i)	StackFrame+4*(i)(r4)
	mov		Argument(1), E
	mov		Argument(0), K

#endif

// Merge point for _aes_decrypt_key and _aes_decrypt_key128.
DKeyHas4Words:

	// First words of expanded key are copied from user key.
	movd	0*4(K), ve0
	movd	1*4(K), ve1
	movd	2*4(K), ve2
	movd	3*4(K), ve3

	movl	$10*16, ContextKeyLength(E)	// Set "key length."

	#if 0 != ContextKey
		add		$ContextKey, E
	#endif

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__

			call    0f          // Push program counter onto stack.
		0:	pop     STable      // Get program counter.
			lea     _AESRcon-0b(STable), R
			lea     _AESInvMixColumnTable-0b(STable), ITable
			lea     _AESSubBytesWordTable-0b(STable), STable

	#elif defined __x86_64__

		lea		_AESRcon(%rip), R
		lea		_AESInvMixColumnTable(%rip), ITable
		lea		_AESSubBytesWordTable(%rip), STable

	#endif

	/*	With a four-word key, there are ten rounds (eleven 16-byte key blocks),
		nine of which have InvMixColumn applied.
	*/
	mov		$-9*4*4, offset
	sub		offset, E

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E, offset)
	movd	ve1, 1*4(E, offset)
	movd	ve2, 2*4(E, offset)
	movd	ve3, 3*4(E, offset)

/*	Here is the first iteration of the key expansion.  It is separate from the
	main loop below because we need to apply InvMixColumn to each of the
	outputs, in ve0 through ve3.  In the main loop, the technique described at
	the top of this file is used to compute the proper outputs while using
	InvMixColumn only once.
*/
	add		$1, R					// Advance pointer.
	movd	ve3, dr					// Put previous word into work register.
	movzx	(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	pxor	ve0, ve1
	pxor	ve1, ve2
	pxor	ve2, ve3

	add		$4*4, offset

	/*	Apply InvMixColumn to each word.  The transformed values are stored in
		the expanded key.  The original values are retained in registers for
		further computation.
	*/
	movd	ve0, dr
	call	InvMixColumn
	movd	vt0, 0*4(E, offset)

	movd	ve1, dr
	call	InvMixColumn
	movd	vt0, 1*4(E, offset)

	movd	ve2, dr
	call	InvMixColumn
	movd	vt0, 2*4(E, offset)

	movd	ve3, dr
	call	InvMixColumn
	movd	vt0, 3*4(E, offset)

//	Here is the main loop.
1:
	add		$1, R					// Advance pointer.
	movd	ve3, dr					// Put previous word into work register.
	movzx	(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	pxor	ve0, ve1
	pxor	ve1, ve2
	pxor	ve2, ve3
		/*	Dr. Brian Gladman uses a technique with a single XOR here instead
			of the previous four.  There is some periodic behavior in the key
			expansion, and Gladman maintains E[4*i+3] for the latest four
			values of i.  XORing the value in vt0 with one of these yields its
			replacement.  However, using this technique requires additional
			instructions before the loop (to initialize the values) and after
			it (to extract the final values to be stored) and either some way
			to rotate or index four values in the loop or a four-fold unrolling
			of the loop to provide the indexing.  Experiment suggests the
			former is not worthwhile.  Unrolling the loop might give a small
			gain, at the cost of increased use of instruction cache, increased
			instructions loads the first time the routine is executed, and
			increased code complexity, so I decided against it.
		*/

	// Apply InvMixColumn to the difference.
	movd	vt0, dr
	call	InvMixColumn

	add		$4*4, offset

	// Chain the transformed difference to previously transformed outputs.
	movd	(0-4)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 0*4(E, offset)

	movd	(1-4)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 1*4(E, offset)

	movd	(2-4)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 2*4(E, offset)

	movd	(3-4)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 3*4(E, offset)

	jl		1b

// Here is the final iteration, which does not perform InvMixColumn.

	movd	ve3, dr					// Put previous word into work register.
	movzx	1(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	movd	ve0, 4*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 5*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 6*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 7*4(E, offset)

	xor		r0, r0				// Return success.

9:
	// Pop stack and restore registers.
	movaps	7*16(r4), %xmm7
	movaps	6*16(r4), %xmm6
	movaps	5*16(r4), %xmm5
	movaps	4*16(r4), %xmm4
	movaps	3*16(r4), %xmm3
	movaps	2*16(r4), %xmm2
	movaps	1*16(r4), %xmm1
	movaps	0*16(r4), %xmm0
	#if 0 < LocalsSize
		add		$Padding + LocalsSize, r4
	#endif
	#if defined __i386__
		pop		r7
		pop		r6
		pop		r5
	#endif
	pop		r3

	ret


	.globl _aes_decrypt_key192
//	.private_extern	_aes_decrypt_key192
_aes_decrypt_key192:

	/*	Save registers and set SaveSize to the number of bytes pushed onto the
		stack so far, including the caller's return address.
	*/
	push	r3
	#if defined __i386__
		push	r5
		push	r6
		push	r7
		#define	SaveSize	(5*4)
	#else
		#define	SaveSize	(2*8)
	#endif

	/*	Number of bytes used for local variables:

			8 16-byte spaces to save XMM registers.

			8 four-byte spaces for work.
	*/
	#define	LocalsSize	(8*16 + 8*4)

	// Define stack offset to storage space for local data.
	#define	Local	(8*16)

	#if 0 < LocalsSize
		// Padding to position stack pointer at a multiple of 16 bytes.
		#define	Padding	(15 & -(SaveSize + LocalsSize))
		sub		$Padding + LocalsSize, r4	// Allocate space on stack.
	#else
		#define	Padding	0
	#endif

	/*	StackFrame is the number of bytes in our stack frame, from caller's
		stack pointer to ours (so it includes the return address).
	*/
	#define	StackFrame	(SaveSize + Padding + LocalsSize)

	// Save xmm registers.
	movaps	%xmm0, 0*16(r4)
	movaps	%xmm1, 1*16(r4)
	movaps	%xmm2, 2*16(r4)
	movaps	%xmm3, 3*16(r4)
	movaps	%xmm4, 4*16(r4)
	movaps	%xmm5, 5*16(r4)
	movaps	%xmm6, 6*16(r4)
	movaps	%xmm7, 7*16(r4)

#if defined __i386__

	// Load arguments.
	#define	Argument(i)	StackFrame+4*(i)(r4)
	mov		Argument(1), E
	mov		Argument(0), K

#endif

// Merge point for _aes_decrypt_key and _aes_decrypt_key192.
DKeyHas6Words:

	// First words of expanded key are copied from user key.
	movd	0*4(K), ve0
	movd	1*4(K), ve1
	movd	2*4(K), ve2
	movd	3*4(K), ve3

	movl	$12*16, ContextKeyLength(E)	// Set "key length."

	#if 0 != ContextKey
		add		$ContextKey, E
	#endif

	movd	4*4(K), ve4
	movd	5*4(K), ve5

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__

			call    0f          // Push program counter onto stack.
		0:	pop     STable      // Get program counter.
			lea     _AESRcon-0b(STable), R
			lea     _AESInvMixColumnTable-0b(STable), ITable
			lea     _AESSubBytesWordTable-0b(STable), STable

	#elif defined __x86_64__

		lea		_AESRcon(%rip), R
		lea		_AESInvMixColumnTable(%rip), ITable
		lea		_AESSubBytesWordTable(%rip), STable

	#endif

	/*	With a six-word key, there are twelve rounds (thirteen 16-byte key
		blocks), eleven of which have InvMixColumn applied.  The key expansion
		proceeds in iterations of six four-byte words, so the termination
		condition is a bit complicated.  We set offset to the negative of 10
		four four-byte words, and the loop branch does another iteration if
		offset is less than or equal to zero, meaning the number of iterations
		performed so far is less than or equal to 10.  Thus, after ten
		iterations, it branches again.  After the eleventh iteration, it
		stops.  Code after the end of the loop computes the twelfth key block,
		which does not have InvMixColumn applied.
	*/
	mov		$-10*4*4, offset
	sub		offset, E

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E, offset)
	movd	ve1, 1*4(E, offset)
	movd	ve2, 2*4(E, offset)
	movd	ve3, 3*4(E, offset)

	/*	The first four words are stored untransformed.  After that, words in
		the expanded key are transformed by InvMixColumn.
	*/
	movd	ve4, dr
	call	InvMixColumn
	movd	vt0, 4*4(E, offset)

	movd	ve5, dr
	call	InvMixColumn
	movd	vt0, 5*4(E, offset)

/*	Here is the first iteration of the key expansion.  It is separate from the
	main loop below because we need to apply InvMixColumn to each of the
	outputs, in ve0 through ve5.  In the main loop, the technique described at
	the top of this file is used to compute the proper outputs while using
	InvMixColumn only once.
*/
	add		$1, R					// Advance pointer.
	movd	ve5, dr					// Put previous word into work register.
	movzx	(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	pxor	ve0, ve1
	pxor	ve1, ve2
	pxor	ve2, ve3
	pxor	ve3, ve4
	pxor	ve4, ve5

	add		$6*4, offset

	/*	Apply InvMixColumn to each word.  The transformed values are stored in
		the expanded key.  The original values are retained in registers for
		further computation.
	*/
	movd	ve0, dr
	call	InvMixColumn
	movd	vt0, 0*4(E, offset)

	movd	ve1, dr
	call	InvMixColumn
	movd	vt0, 1*4(E, offset)

	movd	ve2, dr
	call	InvMixColumn
	movd	vt0, 2*4(E, offset)

	movd	ve3, dr
	call	InvMixColumn
	movd	vt0, 3*4(E, offset)

	movd	(4-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 4*4(E, offset)

	movd	(5-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 5*4(E, offset)

//	Here is the main loop.
1:
	add		$1, R					// Advance pointer.
	movd	ve5, dr					// Put previous word into work register.
	movzx	(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	pxor	ve0, ve1
	pxor	ve1, ve2
	pxor	ve2, ve3
	pxor	ve3, ve4
	pxor	ve4, ve5

	// Apply InvMixColumn to the difference.
	movd	vt0, dr
	call	InvMixColumn

	add		$6*4, offset

	// Chain the transformed difference to previously transformed outputs.
	movd	(0-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 0*4(E, offset)

	movd	(1-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 1*4(E, offset)

	movd	(2-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 2*4(E, offset)

	movd	(3-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 3*4(E, offset)

	movd	(4-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 4*4(E, offset)

	movd	(5-6)*4(E, offset), vt1
	pxor	vt1, vt0
	movd	vt0, 5*4(E, offset)

	jle		1b

// Here is the final iteration, which does not perform InvMixColumn.

	movd	ve5, dr					// Put previous word into work register.
	movzx	1(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord
	pxor	vt0, ve0

	// Chain to successive words.
	movd	ve0, 6*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 7*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 8*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 9*4(E, offset)

	xor		r0, r0				// Return success.

	// Pop stack and restore registers.
	movaps	7*16(r4), %xmm7
	movaps	6*16(r4), %xmm6
	movaps	5*16(r4), %xmm5
	movaps	4*16(r4), %xmm4
	movaps	3*16(r4), %xmm3
	movaps	2*16(r4), %xmm2
	movaps	1*16(r4), %xmm1
	movaps	0*16(r4), %xmm0
	#if 0 < LocalsSize
		add		$Padding + LocalsSize, r4
	#endif
	#if defined __i386__
		pop		r7
		pop		r6
		pop		r5
	#endif
	pop		r3

	ret


	.globl _aes_decrypt_key256
//	.private_extern	_aes_decrypt_key256
_aes_decrypt_key256:

	/*	Save registers and set SaveSize to the number of bytes pushed onto the
		stack so far, including the caller's return address.
	*/
	push	r3
	#if defined __i386__
		push	r5
		push	r6
		push	r7
		#define	SaveSize	(5*4)
	#else
		#define	SaveSize	(2*8)
	#endif

	/*	Number of bytes used for local variables:

			8 16-byte spaces to save XMM registers.

			8 four-byte spaces for work.
	*/
	#define	LocalsSize	(8*16 + 8*4)

	// Define stack offset to storage space for local data.
	#define	Local	(8*16)

	#if 0 < LocalsSize
		// Padding to position stack pointer at a multiple of 16 bytes.
		#define	Padding	(15 & -(SaveSize + LocalsSize))
		sub		$Padding + LocalsSize, r4	// Allocate space on stack.
	#else
		#define	Padding	0
	#endif

	/*	StackFrame is the number of bytes in our stack frame, from caller's
		stack pointer to ours (so it includes the return address).
	*/
	#define	StackFrame	(SaveSize + Padding + LocalsSize)

	// Save xmm registers.
	movaps	%xmm0, 0*16(r4)
	movaps	%xmm1, 1*16(r4)
	movaps	%xmm2, 2*16(r4)
	movaps	%xmm3, 3*16(r4)
	movaps	%xmm4, 4*16(r4)
	movaps	%xmm5, 5*16(r4)
	movaps	%xmm6, 6*16(r4)
	movaps	%xmm7, 7*16(r4)

#if defined __i386__

	// Load arguments.
	#define	Argument(i)	StackFrame+4*(i)(r4)
	mov		Argument(1), E
	mov		Argument(0), K

#endif

// Merge point for _aes_decrypt_key and _aes_decrypt_key256.
DKeyHas8Words:

	// First words of expanded key are copied from user key.
	movd	0*4(K), ve0
	movd	1*4(K), ve1
	movd	2*4(K), ve2
	movd	3*4(K), ve3

	movl	$14*16, ContextKeyLength(E)	// Set "key length."

	#if 0 != ContextKey
		add		$ContextKey, E
	#endif

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E)
	movd	ve1, 1*4(E)
	movd	ve2, 2*4(E)
	movd	ve3, 3*4(E)
	movd	4*4(K), ve0
	movd	5*4(K), ve1
	movd	6*4(K), ve2
	movd	7*4(K), ve3

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__

			call    0f          // Push program counter onto stack.
		0:	pop     STable      // Get program counter.
			lea     _AESRcon-0b(STable), R
			lea     _AESInvMixColumnTable-0b(STable), ITable
			lea     _AESSubBytesWordTable-0b(STable), STable

	#elif defined __x86_64__

		lea		_AESRcon(%rip), R
		lea		_AESInvMixColumnTable(%rip), ITable
		lea		_AESSubBytesWordTable(%rip), STable

	#endif

	/*	With an eight-word key, there are fourteen rounds (fifteen 16-byte key
		blocks), thirteen of which have InvMixColumn applied.
	*/
	mov		$-12*4*4, offset
	sub		offset, E

	// Save untransformed values in stack area.
	movd	ve0, 4*4+Local(r4)
	movd	ve1, 5*4+Local(r4)
	movd	ve2, 6*4+Local(r4)
	movd	ve3, 7*4+Local(r4)

	/*	Apply InvMixColumn to words 4 through 7.  The transformed values are
		stored in the expanded key.  The original values are saved in the stack
		area for further computation.
	*/
	movd	ve0, dr
	call	InvMixColumn
	movd	vt0, 4*4(E, offset)

	movd	ve1, dr
	call	InvMixColumn
	movd	vt0, 5*4(E, offset)

	movd	ve2, dr
	call	InvMixColumn
	movd	vt0, 6*4(E, offset)

	movd	ve3, dr
	call	InvMixColumn
	movd	vt0, 7*4(E, offset)

/*	Here is the first iteration of the key expansion.  It is separate from the
	main loop below because we need to apply InvMixColumn to each of the
	outputs, in ve0 through ve3.  In the main loop, the technique described at
	the top of this file is used to compute the proper outputs while using
	InvMixColumn only once.
*/
	add		$1, R					// Advance pointer.
	movd	ve3, dr					// Put previous word into work register.
	movzx	(R), t0d				// Get round constant.
	movd	t0d, vt0

	SubWordRotWord

	add		$8*4, offset

	movd	(0-8)*4(E, offset), ve0		// Get old word.
	pxor	vt0, ve0
	movd	ve0, 0*4+Local(r4)			// Save on stack.
	movd	ve0, dr
	call	InvMixColumn
	movd	vt0, 0*4(E, offset)			// Write to expanded key.

	/*	 Chain to successive words and apply InvMixColumn to each word.  The
		 transformed values are stored in the expanded key.  The original
		 values are retained in local data for further computation.
	*/
	movd	(1-8)*4(E, offset), ve1		// Get old word.
	pxor	ve0, ve1					// Chain.
	movd	ve1, 1*4+Local(r4)			// Save on stack.
	movd	ve1, dr
	call	InvMixColumn
	movd	vt0, 1*4(E, offset)			// Write to expanded key.

	movd	(2-8)*4(E, offset), ve2		// Get old word.
	pxor	ve1, ve2					// Chain.
	movd	ve2, 2*4+Local(r4)			// Save on stack.
	movd	ve2, dr
	call	InvMixColumn
	movd	vt0, 2*4(E, offset)			// Write to expanded key.

	movd	(3-8)*4(E, offset), ve3		// Get old word.
	pxor	ve2, ve3					// Chain.
	movd	ve3, 3*4+Local(r4)			// Save on stack.
	movd	ve3, dr
	call	InvMixColumn
	movd	vt0, 3*4(E, offset)			// Write to expanded key.

	movd	ve3, dr						// Put previous word into work register.
	SubWord

	movd	4*4+Local(r4), ve0			// Get old word.
	pxor	vt0, ve0					// Chain.
	movd	ve0, 4*4+Local(r4)			// Save on stack.

	movd	5*4+Local(r4), ve1			// Get old word.
	pxor	ve0, ve1					// Chain.
	movd	ve1, 5*4+Local(r4)			// Save on stack.

	movd	6*4+Local(r4), ve2			// Get old word.
	pxor	ve1, ve2					// Chain.
	movd	ve2, 6*4+Local(r4)			// Save on stack.

	movd	7*4+Local(r4), ve3			// Get old word.
	pxor	ve2, ve3					// Chain.
	movd	ve3, 7*4+Local(r4)			// Save on stack.

	movd	vt0, dr						// Move change to work register.
	call	InvMixColumn

	movd	(4-8)*4(E, offset), vt1		// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, 4*4(E, offset)			// Write new word to expanded key.

	movd	(5-8)*4(E, offset), vt1		// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, 5*4(E, offset)			// Write new word to expanded key.

	movd	(6-8)*4(E, offset), vt1		// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, 6*4(E, offset)			// Write new word to expanded key.

	movd	(7-8)*4(E, offset), vt1		// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, 7*4(E, offset)			// Write new word to expanded key.

//	Here is the main loop.
1:
	add		$1, R						// Advance pointer.
	movd	ve3, dr						// Put previous word into work register.
	movzx	(R), t0d					// Get round constant.
	movd	t0d, vt0

	SubWordRotWord

	movd	0*4+Local(r4), ve0			// Get old word.
	pxor	vt0, ve0
	movd	ve0, 0*4+Local(r4)			// Save on stack.

	// Chain to successive words.
	movd	1*4+Local(r4), ve1			// Get old word.
	pxor	ve0, ve1					// Chain.
	movd	ve1, 1*4+Local(r4)			// Save on stack.

	movd	2*4+Local(r4), ve2			// Get old word.
	pxor	ve1, ve2					// Chain.
	movd	ve2, 2*4+Local(r4)			// Save on stack.

	movd	3*4+Local(r4), ve3			// Get old word.
	pxor	ve2, ve3					// Chain.
	movd	ve3, 3*4+Local(r4)			// Save on stack.

	movd	vt0, dr						// Move change to work register.
	call	InvMixColumn

	movd	0*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (0+8)*4(E, offset)		// Write new word to expanded key.

	movd	1*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (1+8)*4(E, offset)		// Write new word to expanded key.

	movd	2*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (2+8)*4(E, offset)		// Write new word to expanded key.

	movd	3*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (3+8)*4(E, offset)		// Write new word to expanded key.

	movd	ve3, dr						// Put previous word into work register.
	SubWord

	movd	4*4+Local(r4), ve0			// Get old word.
	pxor	vt0, ve0					// Chain.
	movd	ve0, 4*4+Local(r4)			// Save on stack.

	movd	5*4+Local(r4), ve1			// Get old word.
	pxor	ve0, ve1					// Chain.
	movd	ve1, 5*4+Local(r4)			// Save on stack.

	movd	6*4+Local(r4), ve2			// Get old word.
	pxor	ve1, ve2					// Chain.
	movd	ve2, 6*4+Local(r4)			// Save on stack.

	movd	7*4+Local(r4), ve3			// Get old word.
	pxor	ve2, ve3					// Chain.
	movd	ve3, 7*4+Local(r4)			// Save on stack.

	movd	vt0, dr						// Move change to work register.
	call	InvMixColumn

	movd	4*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (4+8)*4(E, offset)		// Write new word to expanded key.

	movd	5*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (5+8)*4(E, offset)		// Write new word to expanded key.

	movd	6*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (6+8)*4(E, offset)		// Write new word to expanded key.

	movd	7*4(E, offset), vt1			// Get old word.
	pxor	vt1, vt0					// Chain.
	movd	vt0, (7+8)*4(E, offset)		// Write new word to expanded key.

	add		$8*4, offset

	jl		1b

	movd	ve3, dr						// Put previous word into work register.
	movzx	1(R), t0d					// Get round constant.
	movd	t0d, vt0

	SubWordRotWord

	movd	0*4+Local(r4), ve0			// Get old word.
	pxor	vt0, ve0					// Chain.
	movd	ve0, (0+8)*4(E, offset)

	// Chain to successive words.
	movd	1*4+Local(r4), ve1			// Get old word.
	pxor	ve0, ve1					// Chain.
	movd	ve1, (1+8)*4(E, offset)

	movd	2*4+Local(r4), ve2			// Get old word.
	pxor	ve1, ve2					// Chain.
	movd	ve2, (2+8)*4(E, offset)

	movd	3*4+Local(r4), ve3			// Get old word.
	pxor	ve2, ve3					// Chain.
	movd	ve3, (3+8)*4(E, offset)

	xor		r0, r0				// Return success.

	// Pop stack and restore registers.
	movaps	7*16(r4), %xmm7
	movaps	6*16(r4), %xmm6
	movaps	5*16(r4), %xmm5
	movaps	4*16(r4), %xmm4
	movaps	3*16(r4), %xmm3
	movaps	2*16(r4), %xmm2
	movaps	1*16(r4), %xmm1
	movaps	0*16(r4), %xmm0
	#if 0 < LocalsSize
		add		$Padding + LocalsSize, r4
	#endif
	#if defined __i386__
		pop		r7
		pop		r6
		pop		r5
	#endif
	pop		r3

	ret


#undef	Address
#undef	Argument
#undef	E
#undef	ITable
#undef	K
#undef	Local
#undef	LocalsSize
#undef	LookupI
#undef	LookupS
#undef	Nk
#undef	Padding
#undef	R
#undef	SaveSize
#undef	STable
#undef	StackFrame
#undef	dr
#undef	drh
#undef	drl
#undef	offset
#undef	t0
#undef	t0d
#undef	ve0
#undef	ve1
#undef	ve2
#undef	ve3
#undef	ve4
#undef	ve5
#undef	vt0
#undef	vt1
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/ExpandKeyForEncryption.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
/*	This file defines _aes_encrypt_key, _aes_encrypt_key128,
	_aes_encrypt_key192, and _aes_encrypt_key256.  It is designed to be
	included in another assembly file with the preprocessor #include directive,
	to benefit from some assembly-time calculations.

	Written by Eric Postpischil, January 2008.

	The comments here do not say much about the algorithm; the code just
	follows the FIPS-197 specification.  I recommend reading the specification
	before working with this code or examining the C code in the parent
	directory that illustrates key expansion.
*/


/*	Routines:

		_aes_encrypt_key.

		_aes_encrypt_key128, _aes_encrypt_key192, and _aes_encrypt_key256.

	Function:

		Expand the user's cipher key into the key schedule, as defined in
		Federal Information Processing Standards Publication 197 (FIPS-197),
		November 26, 2001.

	Input:

		Constant data:

			The following names must be locally defined so the assembler
			can calculate certain offsets.

			static const Word _AESSubBytesWordTable[4][256].

				_AESSubBytesWordTable[i][j] = SubBytes(j) << 8*i, where
				SubBytes is defined in FIPS-197.  _AESSubBytesWordTable
				differs from _AESEncryptTable in that it does not include
				the MixColumn operation.  It is used in performing the last
				round, which differs fromm the previous rounds in that it
				does not include the MixColumn operation.

			static const Byte _AESRcon[].

				Round constants, beginning with AESRcon[1] for the first round
				(AESRcon[0] is padding.)
	
		Arguments:

			const unsigned char *Key

				Address of user's cipher key.

			int Length

				Number of bytes (16, 24, or 32) or bits (128, 192, or 256) in
				user's cipher key.

				This argument is used with _aes_encrypt_key.  It is not
				present for the other routines.  In those routines, Context
				is the second argument.

			aes_encrypt_ctx *Context

				Structure to contain the expanded key beginning at offset
				ContextKey and a four-byte "key length" beginning at offset
				ContextKeyLength.  The "key length" is the number of bytes from
				the start of the first round key to the start of the last round
				key.  That is 16 less than the number of bytes in the entire
				key.

	Output:

		The expanded key and the "key length" are written to *Context.

	Return:

		aes_rval	// -1 if "key length" is invalid.  0 otherwise.
*/

/* add AES HW detection and program branch if AES HW is detected cclee 3-12-10 */

#include <System/i386/cpu_capabilities.h>

	.text
	.globl _aes_encrypt_key
//	.private_extern	_aes_encrypt_key
_aes_encrypt_key:

    // detect AES HW, cclee-3-13-10
#if defined __x86_64__
    movq    __cpu_capabilities@GOTPCREL(%rip), %rax				// %rax -> __cpu_capabilities
    mov     (%rax), %eax										// %eax  = __cpu_capabilities
#else
#ifdef	KERNEL
    leal    __cpu_capabilities, %eax							// %eax -> __cpu_capabilities
    mov     (%eax), %eax										// %eax  = __cpu_capabilities
#else
	mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
#endif
#endif
    test    $(kHasAES), %eax									// __cpu_capabilities & kHasAES
    jne     _aes_encrypt_key_hw									// if AES HW detected, branch to _aes_encrypt_key_hw

#define	dr		r0d				// Dissection register.
#define	drl		r0l				// Low 8 bits of dissection register.
#define	drh		r0h				// Second-lowest 8 bits of dissection register.

#define	t0		r1
#define	t0d		r1d				// Low 32 bits of t0.

#define	offset	Arch(r5, r11)	// Address offset and loop sentinel.

#define	R		r7				// Address of round constant.
#define	K		r7				// User key pointer.
	// R and K overlap.

#define	E		r6				// Expanded key pointer.

#define	ve0		%xmm0
#define	ve1		%xmm1
#define	ve2		%xmm2
#define	ve3		%xmm3
#define	vt3		%xmm4
#define	vt2		%xmm5
#define	vt1		%xmm6
#define	vt0		%xmm7

#define	LookupS(table, index)	(table)*TableSize(STable, index, 4)

	/*	Save registers and set SaveSize to the number of bytes pushed onto the
		stack so far, including the caller's return address.
	*/
	push	r3
	#if defined __i386__
		push	r5
		push	r6
		push	r7
		#define	SaveSize	(5*4)
	#else
		#define	SaveSize	(2*8)
	#endif

	/*	Number of bytes used for local variables:

			8 16-byte spaces to save XMM registers.
	*/
	#define	LocalsSize	(8*16)

	#if 0 < LocalsSize
		// Padding to position stack pointer at a multiple of 16 bytes.
		#define	Padding	(15 & -(SaveSize + LocalsSize))
		sub		$Padding + LocalsSize, r4	// Allocate space on stack.
	#else
		#define	Padding	0
	#endif

	/*	StackFrame is the number of bytes in our stack frame, from caller's
		stack pointer to ours (so it includes the return address).
	*/
	#define	StackFrame	(SaveSize + Padding + LocalsSize)

	// Save xmm registers.
	movaps	%xmm0, 0*16(r4)
	movaps	%xmm1, 1*16(r4)
	movaps	%xmm2, 2*16(r4)
	movaps	%xmm3, 3*16(r4)
	movaps	%xmm4, 4*16(r4)
	movaps	%xmm5, 5*16(r4)
	movaps	%xmm6, 6*16(r4)
	movaps	%xmm7, 7*16(r4)

#if defined __i386__

	// Define location of argument i.
	#define	Argument(i)	StackFrame+4*(i)(r4)

	#define	Nk		t0d

	// Load arguments.
	mov		Argument(2), E
	mov		Argument(1), Nk
	mov		Argument(0), K

#elif defined __x86_64__

	#define	Nk		r9d			// Number of words in key.
	mov		r6d, Nk				// Move Nk argument out of way.
	mov		r2, E				// Move E argument to common register.

#endif

	// Dispatch on key length.
	cmp		$128, Nk
	jge		2f
	shl		$3, Nk				// Convert from bytes to bits.
	cmp		$128, Nk
2:
	je		EKeyHas4Words
	cmp		$192, Nk
	je		EKeyHas6Words
	cmp		$256, Nk
	je		EKeyHas8Words
	mov		$-1, r0				// Return error.
	jmp		9f

// Stop using Nk.
#undef	Nk

	.globl _aes_encrypt_key128
//	.private_extern	_aes_encrypt_key128
_aes_encrypt_key128:

	/*	Save registers and set SaveSize to the number of bytes pushed onto the
		stack so far, including the caller's return address.
	*/
	push	r3
	#if defined __i386__
		push	r5
		push	r6
		push	r7
		#define	SaveSize	(5*4)
	#else
		#define	SaveSize	(2*8)
	#endif

	/*	Number of bytes used for local variables:

			8 16-byte spaces to save XMM registers.
	*/
	#define	LocalsSize	(8*16)

	#if 0 < LocalsSize
		// Padding to position stack pointer at a multiple of 16 bytes.
		#define	Padding	(15 & -(SaveSize + LocalsSize))
		sub		$Padding + LocalsSize, r4	// Allocate space on stack.
	#else
		#define	Padding	0
	#endif

	/*	StackFrame is the number of bytes in our stack frame, from caller's
		stack pointer to ours (so it includes the return address).
	*/
	#define	StackFrame	(SaveSize + Padding + LocalsSize)

	// Save xmm registers.
	movaps	%xmm0, 0*16(r4)
	movaps	%xmm1, 1*16(r4)
	movaps	%xmm2, 2*16(r4)
	movaps	%xmm3, 3*16(r4)
	movaps	%xmm4, 4*16(r4)
	movaps	%xmm5, 5*16(r4)
	movaps	%xmm6, 6*16(r4)
	movaps	%xmm7, 7*16(r4)

	#if defined __i386__

		// Load arguments.
		#define	Argument(i)	StackFrame+4*(i)(r4)
		mov		Argument(1), E
		mov		Argument(0), K

	#endif

// Merge point for _aes_encrypt_key and _aes_encrypt_key128.
EKeyHas4Words:

#define	e0	r2d
#define	e1	r3d
#define	e2	Arch(r5d, r11d)
#define	e3	r7d

	// First words of expanded key are copied from user key.
	mov		0*4(K), e0
	mov		1*4(K), e1
	mov		2*4(K), e2
	mov		3*4(K), e3

	movl	$10*16, ContextKeyLength(E)	// Set "key length."

	#if 0 != ContextKey
		add		$ContextKey, E
	#endif

	// K cannot be used after we write to R, since they use the same register.

	// Cache round constants in output buffer.  The last is a sentinel.
	movb	$0x01,  1*16(E)
	movb	$0x02,  2*16(E)
	movb	$0x04,  3*16(E)
	movb	$0x08,  4*16(E)
	movb	$0x10,  5*16(E)
	movb	$0x20,  6*16(E)
	movb	$0x40,  7*16(E)
	movb	$0x80,  8*16(E)
	movb	$0x1b,  9*16(E)
	movb	$0x36, 10*16(E)

	// Store initial words of expanded key, which are copies of user's key.
	mov		e0, 0*4(E)
	mov		e1, 1*4(E)
	mov		e2, 2*4(E)
	mov		e3, 3*4(E)

	#if defined __x86_64__

		#define	STable	r8
		lea		_AESSubBytesWordTable(%rip), STable

	#else

		#define	STable	r6
		sub		$16, r4			// allocate stack memory for storing E and STable
		mov		E, (r4)			// save E

            call    0f          // Push program counter onto stack.
        0:
            pop     %eax      	// Get program counter.

        lea     _AESSubBytesWordTable-0b(%eax), STable
		mov		STable, 4(r4)	// Save STable

	#endif

1:
	mov		e3, dr				// Put previous word into dissection register.

	// Perform SubWord(RotWord(dr)).
	movzx	drl, t0
	xor		LookupS(3, t0), e0		// Look up byte 0 in table 3.
	movzx	drh, t0d
	xor		LookupS(0, t0), e0		// Look up byte 1 in table 0.
	shr		$16, dr
	movzx	drl, t0d
	xor		LookupS(1, t0), e0		// Look up byte 2 in table 1.
	movzx	drh, t0d
	xor		LookupS(2, t0), e0		// Look up byte 3 in table 2.

#if defined	__i386__
	mov		(r4), E
#endif

	add		$4*4, E

	movzx	(E), t0d				// Get cached round constant.
	xor		t0d, e0					// XOR with word from four words back.

	// Chain to successive words.
	mov		e0, 0*4(E)
	xor		e0, e1
	mov		e1, 1*4(E)
	xor		e1, e2
	mov		e2, 2*4(E)
	xor		e2, e3
	mov		e3, 3*4(E)

#if defined	__i386__
	mov		E, (r4)
	mov		4(r4), STable 
#endif

	cmp		$0x36, t0d				// Was this the last round constant?

	jne		1b

#if defined	__i386__
	add		$16, r4
#endif

	xor		r0, r0		// Return success.

9:
	// Pop stack and restore registers.
	movaps	7*16(r4), %xmm7
	movaps	6*16(r4), %xmm6
	movaps	5*16(r4), %xmm5
	movaps	4*16(r4), %xmm4
	movaps	3*16(r4), %xmm3
	movaps	2*16(r4), %xmm2
	movaps	1*16(r4), %xmm1
	movaps	0*16(r4), %xmm0
	#if 0 < LocalsSize
		add		$Padding + LocalsSize, r4
	#endif
	#if defined __i386__
		pop		r7
		pop		r6
		pop		r5
	#endif
	pop		r3

	ret


// Reset definitions for next case.
#undef	e0
#undef	e1
#undef	e2
#undef	e3
#undef	STable

#undef	vt3
#undef	vt2
#define	ve4	%xmm4
#define	ve5	%xmm5


	.globl _aes_encrypt_key192
//	.private_extern	_aes_encrypt_key192
_aes_encrypt_key192:

	/*	Save registers and set SaveSize to the number of bytes pushed onto the
		stack so far, including the caller's return address.
	*/
	push	r3
	#if defined __i386__
		push	r5
		push	r6
		push	r7
		#define	SaveSize	(5*4)
	#else
		#define	SaveSize	(2*8)
	#endif

	/*	Number of bytes used for local variables:

			8 16-byte spaces to save XMM registers.
	*/
	#define	LocalsSize	(8*16)

	#if 0 < LocalsSize
		// Padding to position stack pointer at a multiple of 16 bytes.
		#define	Padding	(15 & -(SaveSize + LocalsSize))
		sub		$Padding + LocalsSize, r4	// Allocate space on stack.
	#else
		#define	Padding	0
	#endif

	/*	StackFrame is the number of bytes in our stack frame, from caller's
		stack pointer to ours (so it includes the return address).
	*/
	#define	StackFrame	(SaveSize + Padding + LocalsSize)

	// Save xmm registers.
	movaps	%xmm0, 0*16(r4)
	movaps	%xmm1, 1*16(r4)
	movaps	%xmm2, 2*16(r4)
	movaps	%xmm3, 3*16(r4)
	movaps	%xmm4, 4*16(r4)
	movaps	%xmm5, 5*16(r4)
	movaps	%xmm6, 6*16(r4)
	movaps	%xmm7, 7*16(r4)

	#if defined __i386__

		// Load arguments.
		#define	Argument(i)	StackFrame+4*(i)(r4)
		mov		Argument(1), E
		mov		Argument(0), K

	#endif

// Merge point for _aes_encrypt_key and _aes_encrypt_key192.
EKeyHas6Words:

	// First words of expanded key are copied from user key.
	movd	0*4(K), ve0
	movd	1*4(K), ve1
	movd	2*4(K), ve2
	movd	3*4(K), ve3

	movl	$12*16, ContextKeyLength(E)	// Set "key length."

	#if 0 != ContextKey
		add		$ContextKey, E
	#endif

	movd	4*4(K), ve4
	movd	5*4(K), ve5

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__

	// Get address of 0 in R.
            call    0f          // Push program counter onto stack.
        0:
            pop     %eax      // Get program counter.
 
		#define	STable	r3
        lea     _AESRcon-0b(%eax), R
        lea     _AESSubBytesWordTable-0b(%eax), STable

	#elif defined __x86_64__

		#define	STable	r8
		lea		_AESRcon(%rip), R
		lea		_AESSubBytesWordTable(%rip), STable

	#endif

	/*	With a six-word key, there are twelve rounds (thirteen 16-byte key
		blocks).
	*/
	mov		$-12*4*4, offset
	sub		offset, E

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E, offset)
	movd	ve1, 1*4(E, offset)
	movd	ve2, 2*4(E, offset)
	movd	ve3, 3*4(E, offset)
	movd	ve4, 4*4(E, offset)
	movd	ve5, 5*4(E, offset)

/*	Jump into loop body.  The key expansion processes six four-byte words per
	iteration.  52 are needed in the key.  So only four are needed in the last
	iteration.
*/
	jmp		2f		
1:
	// Continue chaining to successive words.
	pxor	ve3, ve4
	movd	ve4, 4*4(E, offset)
	pxor	ve4, ve5
	movd	ve5, 5*4(E, offset)
2:
	add		$1, R				// Advance pointer.
	movd	ve5, dr				// Put previous word into dissection register.
	movzx	(R), t0				// Get round constant.
	movd	t0d, vt1
	pxor	vt1, ve0			// XOR with word from six words back.

	// Perform SubWord(RotWord(dr)).
	movzx	drl, t0d
	movd	LookupS(3, t0), vt0		// Look up byte 0 in table 3.
	movzx	drh, t0d
	movd	LookupS(0, t0), vt1		// Look up byte 1 in table 0.
	shr		$16, dr
	movzx	drl, t0d
	pxor	vt1, vt0
	pxor	vt0, ve0
	movd	LookupS(1, t0), vt0		// Look up byte 2 in table 1.
	movzx	drh, t0d
	movd	LookupS(2, t0), vt1		// Look up byte 3 in table 2.
	pxor	vt1, vt0
	pxor	vt0, ve0

	add		$6*4, offset

	// Chain to successive words.
	movd	ve0, 0*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 1*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 2*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 3*4(E, offset)

	jne		1b

	xor		r0, r0		// Return success.

	// Pop stack and restore registers.
	movaps	7*16(r4), %xmm7
	movaps	6*16(r4), %xmm6
	movaps	5*16(r4), %xmm5
	movaps	4*16(r4), %xmm4
	movaps	3*16(r4), %xmm3
	movaps	2*16(r4), %xmm2
	movaps	1*16(r4), %xmm1
	movaps	0*16(r4), %xmm0
	#if 0 < LocalsSize
		add		$Padding + LocalsSize, r4
	#endif
	#if defined __i386__
		pop		r7
		pop		r6
		pop		r5
	#endif
	pop		r3

	ret


// Reset definitions for next case.
#undef	ve4
#undef	ve5
#define	vt3	%xmm4
#define	vt2	%xmm5

#undef	STable

	.globl _aes_encrypt_key256
//	.private_extern	_aes_encrypt_key256
_aes_encrypt_key256:

	/*	Save registers and set SaveSize to the number of bytes pushed onto the
		stack so far, including the caller's return address.
	*/
	push	r3
	#if defined __i386__
		push	r5
		push	r6
		push	r7
		#define	SaveSize	(5*4)
	#else
		#define	SaveSize	(2*8)
	#endif

	/*	Number of bytes used for local variables:

			8 16-byte spaces to save XMM registers.
	*/
	#define	LocalsSize	(8*16)

	#if 0 < LocalsSize
		// Padding to position stack pointer at a multiple of 16 bytes.
		#define	Padding	(15 & -(SaveSize + LocalsSize))
		sub		$Padding + LocalsSize, r4	// Allocate space on stack.
	#else
		#define	Padding	0
	#endif

	/*	StackFrame is the number of bytes in our stack frame, from caller's
		stack pointer to ours (so it includes the return address).
	*/
	#define	StackFrame	(SaveSize + Padding + LocalsSize)

	// Save xmm registers.
	movaps	%xmm0, 0*16(r4)
	movaps	%xmm1, 1*16(r4)
	movaps	%xmm2, 2*16(r4)
	movaps	%xmm3, 3*16(r4)
	movaps	%xmm4, 4*16(r4)
	movaps	%xmm5, 5*16(r4)
	movaps	%xmm6, 6*16(r4)
	movaps	%xmm7, 7*16(r4)

	#if defined __i386__

		// Load arguments.
		#define	Argument(i)	StackFrame+4*(i)(r4)
		mov		Argument(1), E
		mov		Argument(0), K

	#endif

// Merge point for _aes_encrypt_key and _aes_encrypt_key256.
EKeyHas8Words:

	// First words of expanded key are copied from user key.
	movd	0*4(K), ve0
	movd	1*4(K), ve1
	movd	2*4(K), ve2
	movd	3*4(K), ve3

	movl	$14*16, ContextKeyLength(E)	// Set "key length."

	#if 0 != ContextKey
		add		$ContextKey, E
	#endif

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 0*4(E)
	movd	ve1, 1*4(E)
	movd	ve2, 2*4(E)
	movd	ve3, 3*4(E)
	movd	4*4(K), ve0
	movd	5*4(K), ve1
	movd	6*4(K), ve2
	movd	7*4(K), ve3

	// K cannot be used after we write to R, since they use the same register.

	#if defined __i386__

		// Get address of 0 in R.
            call    0f          // Push program counter onto stack.
        0:
            pop     %eax      // Get program counter.
 
		#define	STable	r3
        lea     _AESRcon-0b(%eax), R
        lea     _AESSubBytesWordTable-0b(%eax), STable

	#elif defined __x86_64__

		#define	STable	r8
		lea		_AESRcon(%rip), R
		lea		_AESSubBytesWordTable(%rip), STable

	#endif

	/*	With an eight-word key, there are fourteen rounds (fifteen 16-byte key
	 	blocks).
	*/
	mov		$-14*4*4, offset
	sub		offset, E

	// Store initial words of expanded key, which are copies of user's key.
	movd	ve0, 4*4(E, offset)
	movd	ve1, 5*4(E, offset)
	movd	ve2, 6*4(E, offset)
	movd	ve3, 7*4(E, offset)

/*	Jump into loop body.  The key expansion processes eight four-byte words per
	iteration.  60 are needed in the key.  So only four are needed in the last
	iteration.
*/
	jmp		2f		
1:
	movd	ve3, dr				// Put previous word into dissection register.

	/*	Get word from eight words back (it is four words back from where E
	 	currently points, and we use it to prepare the value to be stored
		four words beyond where E currently points).
	*/
	movd	-4*4(E, offset), ve0

	// Perform SubWord(dr).
	movzx	drl, t0
	movd	LookupS(0, t0), vt0		// Look up byte 0 in table 0.
	movzx	drh, t0d
	movd	LookupS(1, t0), vt1		// Look up byte 1 in table 1.
	shr		$16, dr
	movzx	drl, t0d
	movd	LookupS(2, t0), vt2		// Look up byte 2 in table 2.
	movzx	drh, t0d
	movd	LookupS(3, t0), vt3		// Look up byte 3 in table 3.
	pxor	vt1, vt0
	pxor	vt3, vt2
	pxor	vt0, ve0
	pxor	vt2, ve0

	movd	-3*4(E, offset), ve1	// Get words from eight words back.
	movd	-2*4(E, offset), ve2
	movd	-1*4(E, offset), ve3

	// Chain to successive words.
	movd	ve0, 4*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 5*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 6*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 7*4(E, offset)

2:
	add		$1, R				// Advance pointer.
	movd	ve3, dr				// Put previous word into dissection register.
	movzx	(R), t0d			// Get round constant.
	movd	t0d, vt1
	movd	0*4(E, offset), ve0	// Get word from eight words back.
	pxor	vt1, ve0

	// Perform SubWord(RotWord(dr)).
	movzx	drl, t0
	movd	LookupS(3, t0), vt0		// Look up byte 0 in table 3.
	movzx	drh, t0d
	movd	LookupS(0, t0), vt1		// Look up byte 1 in table 0.
	shr		$16, dr
	movzx	drl, t0d
	movd	LookupS(1, t0), vt2		// Look up byte 2 in table 1.
	movzx	drh, t0d
	movd	LookupS(2, t0), vt3		// Look up byte 3 in table 2.
	pxor	vt1, vt0
	pxor	vt3, vt2
	pxor	vt0, ve0
	pxor	vt2, ve0

	movd	1*4(E, offset), ve1
	movd	2*4(E, offset), ve2
	movd	3*4(E, offset), ve3

	add		$8*4, offset

	// Chain to successive words.
	movd	ve0, 0*4(E, offset)
	pxor	ve0, ve1
	movd	ve1, 1*4(E, offset)
	pxor	ve1, ve2
	movd	ve2, 2*4(E, offset)
	pxor	ve2, ve3
	movd	ve3, 3*4(E, offset)

	jne		1b

	xor		r0, r0		// Return success.

	// Pop stack and restore registers.
	movaps	7*16(r4), %xmm7
	movaps	6*16(r4), %xmm6
	movaps	5*16(r4), %xmm5
	movaps	4*16(r4), %xmm4
	movaps	3*16(r4), %xmm3
	movaps	2*16(r4), %xmm2
	movaps	1*16(r4), %xmm1
	movaps	0*16(r4), %xmm0
	#if 0 < LocalsSize
		add		$Padding + LocalsSize, r4
	#endif
	#if defined __i386__
		pop		r7
		pop		r6
		pop		r5
	#endif
	pop		r3

	ret


#undef	Address
#undef	Argument
#undef	E
#undef	K
#undef	LocalsSize
#undef	LookupS
#undef	Padding
#undef	R
#undef	SaveSize
#undef	STable
#undef	StackFrame
#undef	dr
#undef	drh
#undef	drl
#undef	offset
#undef	t0
#undef	t0d
#undef	ve0
#undef	ve1
#undef	ve2
#undef	ve3
#undef	vt0
#undef	vt1
#undef	vt2
#undef	vt3
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/Setup/Data.mk.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
default:
	@echo "This makefile builds Data.s, which contains constant data for the"
	@echo "AES implementation.  This file does not normally need to be rebuilt,"
	@echo "so it is checked into the source code repository.  It should be"
	@echo "changed only when the implementation changes and needs data in a"
	@echo "different format.  (This file can also build a C version, Data.c,"
	@echo "but that is not currently in use.)"
	@echo ""
	@echo "To rebuild the file(s), execute \"make -f Data.mk all\"."

.PHONY:	all clean
Targets = Data.s
all:	$(Targets)

CFLAGS += -O3 -std=c99 -Wmost -Werror

.INTERMEDIATE:	MakeData
MakeData:	MakeData.c

# Do not leave bad output files if the build fails.
.DELETE_ON_ERROR:	$(Targets)

Data.c:	MakeData
	./$< >$@ C

Data.s:	MakeData
	./$< >$@ Intel

clean:
	-rm $(Targets)
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































Deleted Source/libtomcrypt/src/ciphers/aesedpport/Setup/MakeData.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define	MaxRcon	11

typedef uint8_t Byte;
typedef uint32_t Word;


/*	In comments below, {n} designates the Galois field element represented by
	the byte n.  See notes about Galois field multiplication in ReadMe.txt.

	So 3+5 is addition of ordinary integers, and 3+5 == 8, while {3}+{5} is
	addition in the field, and {3} + {5} = {3 XOR 5} = {6}.)
*/


// Define constants for languages.
typedef enum { C, IntelAssembly } Language;


/*	LogBase3[i] will contain the base-three logarithm of i in the 256-element
	Galois field defined by AES.  That is, {3}**LogBase3[i] == {3}**i.
*/
static Byte LogBase3[256];

/*	AntilogBase3[i] will contain {3}**i in the 256-element Galois field defined
	by AES.  It contains extra elements so that the antilog of a+b can be found
	by looking up a+b directly, without having to reduce modulo the period, for
	0 <= a, b < 255.

	(254 is the greatest value we encounter.  Each a or b we use is the
	base-three logarithm of some element.  As a primitive root, the powers of
	three cycle through all non-zero elements of the field, of which there are
	255, so the exponents cover 0 to 254 before the powers repeat.)
*/
static Byte AntilogBase3[254+254+1];


static void InitializeLogTables(void)
{
	// log({1}) is zero, so start {p} (power) at {1} and l (logarithm) at 0.
	Byte p = 1;
	int l = 0;
	do
	{
		// Record table entries.
		LogBase3[p] = l;
		AntilogBase3[l] = p;

		/*	Observe that {2}*{p} is {p << 1 ^ (a & 0x80 ? 0x1b : 0)}, per notes
			in ReadMe.txt.  We produce {3}*{p}:

				{3}*{p}
					= {1}*{p} + {2}*{p}
					= {1}*{p} + {p << 1 ^ (a & 0x80 ? 0x1b : 0)}
					= {p ^ p << 1 ^ (p & 0x80 ? 0x1b : 0)}.
		*/
		p ^= p << 1 ^ (p & 0x80 ? 0x1b : 0);
		++l;

	} while (p != 1);	// Stop when we have gone around completely.

	/*	The antilogarithms are periodic with a period of 255, and we want to
		look up elements as high as 254+254 (the largest that a sum of two
		logarithms could be), so we replicate the table beyond the first
		period.
	*/
	for (l = 255; l < 254+254; ++l)
		AntilogBase3[l] = AntilogBase3[l-255];
}


/*	MultiplyByte(Byte b, Byte c) returns {b}*{c}.  It requires tables that must
	be initialized before this routine is used.
*/
static Byte MultiplyByte(Byte b, Byte c)
{
	// Calculate product by adding logarithms, but avoid logarithms of zero.
	return b == 0 || c == 0 ? 0 : AntilogBase3[LogBase3[b] + LogBase3[c]];
}


// Return {0} if {b} is {0} and the multiplicative inverse of {b} otherwise.
static Byte InverseByte(Byte b)
{
	return b == 0 ? 0 : AntilogBase3[255 - LogBase3[b]];
}


// Perform AES' SubBytes operation on a single byte.
static Byte SubByte(Byte b)
{
	unsigned int r = InverseByte(b);

	// Duplicate r as a proxy for a rotate operation.
	r = r | r<<8;

	// Apply the standard's affine transformation.
	return r ^ r>>4 ^ r>>5 ^ r>>6 ^ r>>7 ^ 0x63;
}


// Define and populate tables for the SubBytes and InvSubBytes operations.
static Byte SubBytesTable[256];
static Byte InvSubBytesTable[256];


static void InitializeSubBytesTable(void)
{
	for (int i = 0; i < 256; ++i)
		SubBytesTable[i] = SubByte((Byte) i);
}


static void InitializeInvSubBytesTable(void)
{
	for (int i = 0; i < 256; ++i)
		InvSubBytesTable[SubByte((Byte) i)] = i;
}


/*	Print tables for SubBytes function providing the output byte embedded in
	various places in a word, so that the table entries can be used with
	fewer byte manipulations.
*/
static void PrintSubBytesWordTable(Language language)
{
	switch (language)
	{
		case C:
			printf("\n\n"
				"// SubBytes embedded in words tables.\n"
				"const Word AESSubBytesWordTable[4][256] =\n"
				"{\n");
			for (int j = 0; j < 4; ++j)
			{
				printf("\t{\n");
				for (int i = 0; i < 256; ++i)
					printf("\t\t0x%08x,\n", SubBytesTable[i] << j*8);
				printf("\t},\n");
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// SubBytes embedded in words tables.\n"
				"\t.globl\t_AESSubBytesWordTable\n"
				"\t.private_extern\t_AESSubBytesWordTable\n"
				"\t.align\t2\n"
				"_AESSubBytesWordTable:\n");
			for (int j = 0; j < 4; ++j)
			{
				printf("\t// Table %d.\n", j);
				for (int i = 0; i < 256; ++i)
					printf("\t.long\t0x%08x\n", SubBytesTable[i] << j*8);
			}
			break;
	}
}


/*	Print tables for InvSubBytes function providing the output byte embedded in
	various places in a word, so that the table entries can be used with
	fewer byte manipulations.
*/
static void PrintInvSubBytesWordTable(Language language)
{
	switch (language)
	{
		case C:
			printf("\n\n"
				"// InvSubBytes embedded in words tables.\n"
				"const Word AESInvSubBytesWordTable[4][256] =\n"
				"{\n");
			for (int j = 0; j < 4; ++j)
			{
				printf("\t{\n");
				for (int i = 0; i < 256; ++i)
					printf("\t\t0x%08x,\n", InvSubBytesTable[i] << j*8);
				printf("\t},\n");
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// InvSubBytes embedded in words tables.\n"
				"\t.globl\t_AESInvSubBytesWordTable\n"
				"\t.private_extern\t_AESInvSubBytesWordTable\n"
				"\t.align\t2\n"
				"_AESInvSubBytesWordTable:\n");
			for (int j = 0; j < 4; ++j)
			{
				printf("\t// Table %d.\n", j);
				for (int i = 0; i < 256; ++i)
					printf("\t.long\t0x%08x\n", InvSubBytesTable[i] << j*8);
			}
			break;
	}
}


// Print the round constants.
static void PrintRcon(Language language)
{
	union { Byte c[4]; Word w; } t = { { 1, 0, 0, 0 } };

	switch (language)
	{
		case C:
			printf("\n\n"
				"// Round constants.\n"
				"const Byte AESRcon[] =\n"
				"{\n"
				"\t0,\t// Not used, included for indexing simplicity.\n");
			for (int i = 1; i < MaxRcon; ++i)
			{
				printf("\t0x%02x,\n", t.w);
				t.c[0] = MultiplyByte(0x2, t.c[0]);
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// Round constants.\n"
				"\t.globl\t_AESRcon\n"
				"\t.private_extern\t_AESRcon\n"
				"_AESRcon:\n"
				"\t.byte\t0\t// Not used, included for indexing simplicity.\n");
			for (int i = 1; i < MaxRcon; ++i)
			{
				printf("\t.byte\t0x%02x\n", t.w);
				t.c[0] = MultiplyByte(0x2, t.c[0]);
			}
			break;
	}
}


// Print tables for the InvMixColumn operation.
static void PrintInvMixColumnTable(Language language)
{
	Word T[4][256];

	for (int i = 0; i < 256; ++i)
	{
		union { Byte b[4]; Word w; } c;

		Byte s9 = MultiplyByte(0x9, i);
		Byte sb = MultiplyByte(0xb, i);
		Byte sd = MultiplyByte(0xd, i);
		Byte se = MultiplyByte(0xe, i);

		c.b[0] = se;
		c.b[1] = s9;
		c.b[2] = sd;
		c.b[3] = sb;
		T[0][i] = c.w;

		c.b[0] = sb;
		c.b[1] = se;
		c.b[2] = s9;
		c.b[3] = sd;
		T[1][i] = c.w;

		c.b[0] = sd;
		c.b[1] = sb;
		c.b[2] = se;
		c.b[3] = s9;
		T[2][i] = c.w;

		c.b[0] = s9;
		c.b[1] = sd;
		c.b[2] = sb;
		c.b[3] = se;
		T[3][i] = c.w;
	}

	switch (language)
	{
		case C:
			printf("\n\n"
				"// Tables for InvMixColumn.\n"
				"const Word AESInvMixColumnTable[4][256] =\n"
				"{\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t{\n");
				for (int j = 0; j < 256; ++j)
					printf("\t\t0x%08x,\n", T[i][j]);
				printf("\t},\n");
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// Tables for InvMixColumn.\n"
				"\t.globl\t_AESInvMixColumnTable\n"
				"\t.private_extern\t_AESInvMixColumnTable\n"
				"\t.align\t2\n"
				"_AESInvMixColumnTable:\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t// Table %d.\n", i);
				for (int j = 0; j < 256; ++j)
					printf("\t.long\t0x%08x\n", T[i][j]);
			}
			break;
	}
}


/*	Print the tables defined AES Proposal: Rijndael, amended, 9/04/2003,
	section 5.2.1.  These combine the MixColumn and SubBytes operations.
*/
static void PrintEncryptTable(Language language)
{
	Word T[4][256];

	for (int i = 0; i < 256; ++i)
	{
		union { Byte b[4]; Word w; } c;

		Byte s1 = SubBytesTable[i];
		Byte s2 = MultiplyByte(0x2, s1);
		Byte s3 = s1 ^ s2;

		c.b[0] = s2;
		c.b[1] = s1;
		c.b[2] = s1;
		c.b[3] = s3;
		T[0][i] = c.w;

		c.b[0] = s3;
		c.b[1] = s2;
		//c.b[2] = s1;
		c.b[3] = s1;
		T[1][i] = c.w;

		c.b[0] = s1;
		c.b[1] = s3;
		c.b[2] = s2;
		//c.b[3] = s1;
		T[2][i] = c.w;

		//c.b[0] = s1;
		c.b[1] = s1;
		c.b[2] = s3;
		c.b[3] = s2;
		T[3][i] = c.w;
	}

	switch (language)
	{
		case C:
			printf("\n\n"
				"// Tables for main encryption iterations.\n"
				"const Word AESEncryptTable[4][256] =\n"
				"{\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t{\n");
				for (int j = 0; j < 256; ++j)
					printf("\t\t0x%08x,\n", T[i][j]);
				printf("\t},\n");
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// Tables for main encryption iterations.\n"
				"\t.globl\t_AESEncryptTable\n"
				"\t.private_extern\t_AESEncryptTable\n"
				"\t.align\t2\n"
				"_AESEncryptTable:\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t// Table %d.\n", i);
				for (int j = 0; j < 256; ++j)
					printf("\t.long\t0x%08x\n", T[i][j]);
			}
			break;
	}
}


/*	Print the inverse tables.  These correspond to the tables above, but for
	decyrption.  These combine the InvSubBytes and InvMixColumn operations.
*/
static void PrintDecryptTable(Language language)
{
	Word T[4][256];

	for (int i = 0; i < 256; ++i)
	{
		union { Byte b[4]; Word w; } c;

		Byte si = InvSubBytesTable[i];

		Byte s9 = MultiplyByte(0x9, si);
		Byte sb = MultiplyByte(0xb, si);
		Byte sd = MultiplyByte(0xd, si);
		Byte se = MultiplyByte(0xe, si);

		c.b[0] = se;
		c.b[1] = s9;
		c.b[2] = sd;
		c.b[3] = sb;
		T[0][i] = c.w;

		c.b[0] = sb;
		c.b[1] = se;
		c.b[2] = s9;
		c.b[3] = sd;
		T[1][i] = c.w;

		c.b[0] = sd;
		c.b[1] = sb;
		c.b[2] = se;
		c.b[3] = s9;
		T[2][i] = c.w;

		c.b[0] = s9;
		c.b[1] = sd;
		c.b[2] = sb;
		c.b[3] = se;
		T[3][i] = c.w;
	}

	switch (language)
	{
		case C:
			printf("\n\n"
				"// Tables for main decryption iterations.\n"
				"const Word AESDecryptTable[4][256] =\n"
				"{\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t{\n");
				for (int j = 0; j < 256; ++j)
					printf("\t\t0x%08x,\n", T[i][j]);
				printf("\t},\n");
			}
			printf("};\n");
			break;

		case IntelAssembly:
			printf("\n\n"
				"// Tables for main decryption iterations.\n"
				"\t.globl\t_AESDecryptTable\n"
				"\t.private_extern\t_AESDecryptTable\n"
				"\t.align\t2\n"
				"_AESDecryptTable:\n");
			for (int i = 0; i < 4; ++i)
			{
				printf("\t// Table %d.\n", i);
				for (int j = 0; j < 256; ++j)
					printf("\t.long\t0x%08x\n", T[i][j]);
			}
			break;
	}
}


static void Usage(const char *ProgramName)
{
	fprintf(stderr,
		"%s:  This program must have exactly one argument, \"C\" to generate\n"
		"C or \"Intel\" to generate GCC i386/x86_64 assembly.\n", ProgramName);
	exit(EXIT_FAILURE);
}


int main(int argc, char *argv[])
{
	if (argc != 2)
		Usage(argv[0]);

	Language language;

	// Figure out which language to generate, C or Intel assembly.
	if (0 == strcmp(argv[1], "C"))
		language = C;
	else if (0 == strcmp(argv[1], "Intel"))
		language = IntelAssembly;
	else
		Usage(argv[0]);

	printf("// This file was generated by " __FILE__ ".\n");

	if (language == C)
		printf("\n\n#include \"AES.h\"\n");

	if (language == IntelAssembly)
		printf("\n\n\t.const\n");

	InitializeLogTables();
	InitializeSubBytesTable();
	InitializeInvSubBytesTable();

	PrintRcon(language);
	PrintInvMixColumnTable(language);
	PrintEncryptTable(language);
	PrintDecryptTable(language);
	PrintSubBytesWordTable(language);
	PrintInvSubBytesWordTable(language);

	return 0;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/Setup/ReadMe.txt.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
This directory contains a hybrid AES implementation.  The core AES routines
(the actual encryption, decryption, and key expansion) are in:

	AES.s
	Data.mk
	Data.s
	EncryptDecrypt.s
	ExpandKeyForDecryption.s
	ExpandKeyForEncryption.s
	MakeData.c

Although the above files do not explicitly include aes.h, they confirm to
certain things defined in it, notably the aes_rval type and the layout of the
aes_encrypt_ctx and aes_decrypt_ctx structures.  These must be kept
compatibility; the definitions of ContextKey and ContextKeyLength in AES.s must
match the offsets of the key ("ks") and key_length ("inf") members of
aes_encrypt_ctx and aes_decrypt_ctx.  (For some reason, aes_inf is a union that
is written as a 32-bit integer and read as an 8-bit integer.  I do not know
why but have reproduced that behavior in the new implementation.)

aes_modes.c extends the API, most notably by implementing CBC mode using the
basic AES block encryption.  It uses aesopt.h and edefs.h.
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































Deleted Source/libtomcrypt/src/ciphers/aesedpport/aes_crypt_hw.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/* 	This files defines _aes_encrypt_hw and _aes_decrypt_hw --- Intel Westmere HW AES-based implementation
	of _aes_encrypt and _aes_decrypt. 

	These 2 functions SHOULD BE entried ONLY after the AES HW is verified to be available. 
	They SHOULD NOT be called without AES HW detection. It might cause xnu to crash.

	The AES HW is detected 1st thing in 
		_aes_encrypt (EncryptDecrypt.s) 
		_aes_decrypt (EncryptDecrypt.s)
	and, if AES HW is detected, branch without link (ie, jump) to the functions here.

	The implementation here follows the examples in an Intel White Paper
	"Intel Advanced Encryption Standard (AES) Instruction Set" Rev.2 01

	Note: Rev. 03 Final 2010 01 26 is available. Looks like some code change from Rev.2 01

	cclee 3-13-10
*/
#if defined __i386__ || defined __x86_64__

    .text
    .align 4,0x90
.globl	_aes_encrypt_hw
_aes_encrypt_hw:

#if	defined	__i386__	
	movl	4(%esp), %eax	// in
	movl	12(%esp), %edx	// ctx
	movl	8(%esp), %ecx	// out

	#define	LOCAL_SIZE	(12+16+16)		// 16-byte align (-4 for return address) + 16 (xmm0) + 16 (xmm1)
	#define	in		%eax
	#define	ctx		%edx
	#define	out		%ecx
	#define	r13		%esp

#else		// x86_64

	#define	LOCAL_SIZE	(8+16+16)		// 16-byte align (-8 for return address) + 16 (xmm0) + 16 (xmm1)
	#define	in			%rdi
	#define	ctx			%rdx
	#define	out			%rsi
	#define	r13			%rsp

#endif		// i386 or x86_64

#ifdef KERNEL
	sub		$LOCAL_SIZE, r13
	movaps	%xmm0, (r13)
#endif
	movups	(in), %xmm0

	// key length identification
	movl	240(ctx), %eax			// key length
	cmp		$160, %eax
	je		L_AES_128
	cmp		$192, %eax
	je		L_AES_192
	cmp		$224, %eax
	je		L_AES_256
	mov		$-1, %eax					// return ERROR
#ifdef KERNEL
	movaps	(r13), %xmm0	
	add		$LOCAL_SIZE, r13
#endif
	ret

L_AES_128:
	testb	$15, %dl					// check whether expanded key is 16-byte aligned
	jne		0f							// if not 16-byte aligned, aesenc xmm, m128 won't work	
	pxor	(ctx), %xmm0
	aesenc	16(ctx), %xmm0
	aesenc	32(ctx), %xmm0
	aesenc	48(ctx), %xmm0
	aesenc	64(ctx), %xmm0
	aesenc	80(ctx), %xmm0
	aesenc	96(ctx), %xmm0
	aesenc	112(ctx), %xmm0
	aesenc	128(ctx), %xmm0
	aesenc	144(ctx), %xmm0
	aesenclast	160(ctx), %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	add		$LOCAL_SIZE, r13
#endif
	ret
0:										// special case expanded key is not 16-byte aligned	
#ifdef	KERNEL
	movaps	%xmm1, 16(r13)				// save xmm1 into stack
#endif
	movups	(ctx), %xmm1
	pxor	%xmm1, %xmm0
	movups	16(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	32(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	48(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	64(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	80(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	96(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	112(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	128(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	144(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	160(ctx), %xmm1
	aesenclast	%xmm1, %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	movaps	16(r13), %xmm1
	add		$LOCAL_SIZE, r13
#endif
	ret

L_AES_192:
	testb	$15, %dl					// check whether expanded key is 16-byte aligned
	jne		0f							// if not 16-byte aligned, aesenc xmm, m128 won't work	
	pxor	(ctx), %xmm0
	aesenc	16(ctx), %xmm0
	aesenc	32(ctx), %xmm0
	aesenc	48(ctx), %xmm0
	aesenc	64(ctx), %xmm0
	aesenc	80(ctx), %xmm0
	aesenc	96(ctx), %xmm0
	aesenc	112(ctx), %xmm0
	aesenc	128(ctx), %xmm0
	aesenc	144(ctx), %xmm0
	aesenc	160(ctx), %xmm0
	aesenc	176(ctx), %xmm0
	aesenclast	192(ctx), %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	add		$LOCAL_SIZE, r13
#endif
	ret
0:										// special case expanded key is not 16-byte aligned	
#ifdef	KERNEL
	movaps	%xmm1, 16(r13)				// save xmm1 into stack
#endif
	movups	(ctx), %xmm1
	pxor	%xmm1, %xmm0
	movups	16(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	32(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	48(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	64(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	80(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	96(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	112(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	128(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	144(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	160(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	176(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	192(ctx), %xmm1
	aesenclast	%xmm1, %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	movaps	16(r13), %xmm1
	add		$LOCAL_SIZE, r13
#endif
	ret

L_AES_256:
	testb	$15, %dl					// check whether expanded key is 16-byte aligned
	jne		0f							// if not 16-byte aligned, aesenc xmm, m128 won't work	
	pxor	(ctx), %xmm0
	aesenc	16(ctx), %xmm0
	aesenc	32(ctx), %xmm0
	aesenc	48(ctx), %xmm0
	aesenc	64(ctx), %xmm0
	aesenc	80(ctx), %xmm0
	aesenc	96(ctx), %xmm0
	aesenc	112(ctx), %xmm0
	aesenc	128(ctx), %xmm0
	aesenc	144(ctx), %xmm0
	aesenc	160(ctx), %xmm0
	aesenc	176(ctx), %xmm0
	aesenc	192(ctx), %xmm0
	aesenc	208(ctx), %xmm0
	aesenclast	224(ctx), %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	add		$LOCAL_SIZE, r13
#endif
	ret
0:										// special case expanded key is not 16-byte aligned	
#ifdef	KERNEL
	movaps	%xmm1, 16(r13)				// save xmm1 into stack
#endif
	movups	(ctx), %xmm1
	pxor	%xmm1, %xmm0
	movups	16(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	32(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	48(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	64(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	80(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	96(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	112(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	128(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	144(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	160(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	176(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	192(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	208(ctx), %xmm1
	aesenc	%xmm1, %xmm0
	movups	224(ctx), %xmm1
	aesenclast	%xmm1, %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	movaps	16(r13), %xmm1
	add		$LOCAL_SIZE, r13
#endif
	ret


    .text
    .align 4,0x90
.globl	_aes_decrypt_hw
_aes_decrypt_hw:

#if	defined	__i386__	
	movl	4(%esp), %eax	// in
	movl	12(%esp), %edx	// ctx
	movl	8(%esp), %ecx	// out

#endif

#ifdef KERNEL
	sub		$LOCAL_SIZE, r13
	movaps	%xmm0, (r13)
#endif
	movups	(in), %xmm0

	// key length identification
	movl	240(ctx), %eax			// key length
	cmp		$160, %eax
	je		0f						// AES-128
	cmp		$192, %eax
	je		1f						// AES-192
	cmp		$224, %eax
	je		2f						// AES-256
	mov		$-1, %eax				// return ERROR
#ifdef KERNEL
	movaps	(r13), %xmm0	
	add		$LOCAL_SIZE, r13
#endif
	ret

0:									// AES-128
	testb	$15, %dl					// check whether expanded key is 16-byte aligned
	jne		9f							// if not 16-byte aligned, aesenc xmm, m128 won't work	
	pxor	160(ctx), %xmm0
	aesdec	144(ctx), %xmm0
	aesdec	128(ctx), %xmm0
	aesdec	112(ctx), %xmm0
	aesdec	96(ctx), %xmm0
	aesdec	80(ctx), %xmm0
	aesdec	64(ctx), %xmm0
	aesdec	48(ctx), %xmm0
	aesdec	32(ctx), %xmm0
	aesdec	16(ctx), %xmm0
	aesdeclast	(ctx), %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	add		$LOCAL_SIZE, r13
#endif
	ret
9:										// AES-128 Decrypt : special case expanded key is not 16-byte aligned 
#ifdef	KERNEL
	movaps	%xmm1, 16(r13)				// save xmm1 into stack
#endif
	movups	160(ctx), %xmm1
	pxor	%xmm1, %xmm0
	movups	144(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	128(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	112(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	96(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	80(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	64(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	48(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	32(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	16(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	(ctx), %xmm1
	aesdeclast	%xmm1, %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	movaps	16(r13), %xmm1	
	add		$LOCAL_SIZE, r13
#endif
	ret

1:								// AES-192
	testb	$15, %dl					// check whether expanded key is 16-byte aligned
	jne		9f							// if not 16-byte aligned, aesenc xmm, m128 won't work	
	pxor	192(ctx), %xmm0
	aesdec	176(ctx), %xmm0
	aesdec	160(ctx), %xmm0
	aesdec	144(ctx), %xmm0
	aesdec	128(ctx), %xmm0
	aesdec	112(ctx), %xmm0
	aesdec	96(ctx), %xmm0
	aesdec	80(ctx), %xmm0
	aesdec	64(ctx), %xmm0
	aesdec	48(ctx), %xmm0
	aesdec	32(ctx), %xmm0
	aesdec	16(ctx), %xmm0
	aesdeclast	(ctx), %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	add		$LOCAL_SIZE, r13
#endif
	ret
9:										// AES-192 Decrypt : special case expanded key is not 16-byte aligned 
#ifdef	KERNEL
	movaps	%xmm1, 16(r13)				// save xmm1 into stack
#endif
	movups	192(ctx), %xmm1
	pxor	%xmm1, %xmm0
	movups	176(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	160(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	144(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	128(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	112(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	96(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	80(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	64(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	48(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	32(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	16(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	(ctx), %xmm1
	aesdeclast	%xmm1, %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	movaps	16(r13), %xmm1	
	add		$LOCAL_SIZE, r13
#endif
	ret

2:							// AES-256
	testb	$15, %dl					// check whether expanded key is 16-byte aligned
	jne		9f							// if not 16-byte aligned, aesenc xmm, m128 won't work	
	pxor	224(ctx), %xmm0
	aesdec	208(ctx), %xmm0
	aesdec	192(ctx), %xmm0
	aesdec	176(ctx), %xmm0
	aesdec	160(ctx), %xmm0
	aesdec	144(ctx), %xmm0
	aesdec	128(ctx), %xmm0
	aesdec	112(ctx), %xmm0
	aesdec	96(ctx), %xmm0
	aesdec	80(ctx), %xmm0
	aesdec	64(ctx), %xmm0
	aesdec	48(ctx), %xmm0
	aesdec	32(ctx), %xmm0
	aesdec	16(ctx), %xmm0
	aesdeclast	(ctx), %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	add		$LOCAL_SIZE, r13
#endif
	ret
9:										// AES-256 Decrypt : special case expanded key is not 16-byte aligned 
#ifdef	KERNEL
	movaps	%xmm1, 16(r13)				// save xmm1 into stack
#endif
	movups	224(ctx), %xmm1
	pxor	%xmm1, %xmm0
	movups	208(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	192(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	176(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	160(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	144(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	128(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	112(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	96(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	80(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	64(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	48(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	32(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	16(ctx), %xmm1
	aesdec	%xmm1, %xmm0
	movups	(ctx), %xmm1
	aesdeclast	%xmm1, %xmm0
	xorl	%eax, %eax
	movups	%xmm0, (out)
#ifdef KERNEL
	movaps	(r13), %xmm0	
	movaps	16(r13), %xmm1	
	add		$LOCAL_SIZE, r13
#endif
	ret

#endif /* x86 based build */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/aes_key_hw.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/* 	This files defines _aes_encrypt_key_hw and _aes_decrypt_key_hw --- Intel Westmere HW AES-based implementation
	of _aes_encrypt_key and _aes_decrypt_key. 

	These 2 functions SHOULD BE entried ONLY after the AES HW is verified to be available. 
	They SHOULD NOT be called without AES HW detection. It might cause xnu to crash.

	The AES HW is detected 1st thing in 
		_aes_encrypt_key (ExpandKeyForEncryption.s) 
		_aes_decrypt_key (ExpandKeyForDecryption.s)
	and, if AES HW is detected, branch without link (ie, jump) to the functions here.

	The implementation here follows the examples in an Intel White Paper
	"Intel Advanced Encryption Standard (AES) Instruction Set" Rev.2 01

	Note: Rev. 03 Final 2010 01 26 is available. Looks like some code change from Rev.2 01

	cclee 3-13-10
*/
#if defined __i386__ || defined __x86_64__

	.text	
	.align	4,0x90

	// hw_aes_encrypt_key(key, klen, hwectx);
	// klen = 16, 24, or 32, or (128/192/256)

	.globl	_aes_encrypt_key_hw
_aes_encrypt_key_hw:

#ifdef	__i386__
	push	%ebp
	mov		%esp, %ebp
	push	%ebx
	push	%edi	
	mov		8(%ebp), %eax		// pointer to key
	mov		12(%ebp), %ebx		// klen
	mov		16(%ebp), %edi		// ctx
	#define	pkey	%eax
	#define	klen	%ebx
	#define	ctx		%edi
	#define	sp		%esp
	#define	cx		%ecx
#else
	#define	pkey	%rdi
	#define	klen	%rsi
	#define	ctx		%rdx
	#define	sp		%rsp
	#define	cx		%rcx
	push	%rbp
	mov		%rsp, %rbp
#endif

#ifdef	KERNEL
	// for xmm registers save and restore
	sub		$(16*4), sp
#endif

	cmp		$32, klen
	jg		0f					// klen>32
	shl		$3, klen			// convert 16/24/32 to 128/192/256
0:

	cmp		$128, klen			// AES-128 ?
	je		L_AES_128_Encrypt_Key
	cmp		$192, klen			// AES-192 ?
	je		L_AES_192_Encrypt_Key
	cmp		$256, klen			// AES-256 ?
	je		L_AES_256_Encrypt_Key
	mov		$1, %eax			// return error for wrong klen 
L_Encrypt_Key_2_return:
#ifdef	KERNEL
	add		$(16*4), sp
#endif
#ifdef	__i386__
	pop		%edi
	pop		%ebx
#endif
	leave
	ret

L_AES_128_Encrypt_Key:
#ifdef	KERNEL
	// save xmm registers
	movaps	%xmm1, (sp)
	movaps	%xmm2, 16(sp)
	movaps	%xmm3, 32(sp)
#endif	// KERNEL

	movl	$160, 240(ctx)		// write expanded key length to ctx
	xor		cx, cx

	movups	(pkey), %xmm1
	movups	%xmm1, (ctx)
	aeskeygenassist	$1, %xmm1, %xmm2
	call	L_key_expansion_128
	aeskeygenassist	$2, %xmm1, %xmm2
	call	L_key_expansion_128
	aeskeygenassist	$4, %xmm1, %xmm2
	call	L_key_expansion_128
	aeskeygenassist	$8, %xmm1, %xmm2
	call	L_key_expansion_128
	aeskeygenassist	$0x10, %xmm1, %xmm2
	call	L_key_expansion_128
	aeskeygenassist	$0x20, %xmm1, %xmm2
	call	L_key_expansion_128
	aeskeygenassist	$0x40, %xmm1, %xmm2
	call	L_key_expansion_128
	aeskeygenassist	$0x80, %xmm1, %xmm2
	call	L_key_expansion_128
	aeskeygenassist	$0x1b, %xmm1, %xmm2
	call	L_key_expansion_128
	aeskeygenassist	$0x36, %xmm1, %xmm2
	call	L_key_expansion_128

#ifdef	KERNEL
	// restore xmm registers
	movaps	(sp), %xmm1
	movaps	16(sp), %xmm2
	movaps	32(sp), %xmm3
#endif	// KERNEL
	xor		%eax, %eax			// return 0 for success
	jmp		L_Encrypt_Key_2_return

	.align	4, 0x90
L_key_expansion_128:
	pshufd	$0xff, %xmm2, %xmm2
	movaps	%xmm1, %xmm3
	pslldq	$4, %xmm3
	pxor	%xmm3, %xmm1
	movaps	%xmm1, %xmm3
	pslldq	$4, %xmm3
	pxor	%xmm3, %xmm1
	movaps	%xmm1, %xmm3
	pslldq	$4, %xmm3
	pxor	%xmm3, %xmm1
	pxor	%xmm2, %xmm1
	add		$16, cx
	movups	%xmm1, (ctx, cx)
	ret

L_AES_192_Encrypt_Key:
#ifdef	KERNEL
	// save xmm registers
	movaps	%xmm1, (sp)
	movaps	%xmm2, 16(sp)
	movaps	%xmm3, 32(sp)
	movaps	%xmm4, 48(sp)
#endif	// KERNEL
	movl	$192, 240(ctx)		// write expanded key length to ctx

	movups	(pkey), %xmm1
	movq	16(pkey), %xmm3

	movups	%xmm1, (ctx)
	movq	%xmm3, 16(ctx)

	lea		24(ctx), cx

	aeskeygenassist	$1, %xmm3, %xmm2
	call	L_key_expansion_192
	aeskeygenassist	$2, %xmm3, %xmm2
	call	L_key_expansion_192
	aeskeygenassist	$4, %xmm3, %xmm2
	call	L_key_expansion_192
	aeskeygenassist	$8, %xmm3, %xmm2
	call	L_key_expansion_192
	aeskeygenassist	$0x10, %xmm3, %xmm2
	call	L_key_expansion_192
	aeskeygenassist	$0x20, %xmm3, %xmm2
	call	L_key_expansion_192
	aeskeygenassist	$0x40, %xmm3, %xmm2
	call	L_key_expansion_192
	aeskeygenassist	$0x80, %xmm3, %xmm2
	call	L_key_expansion_192

#ifdef	KERNEL
	// restore xmm registers
	movaps	(sp), %xmm1
	movaps	16(sp), %xmm2
	movaps	32(sp), %xmm3
	movaps	48(sp), %xmm4
#endif	// KERNEL
	xor		%eax, %eax			// return 0 for success
	jmp		L_Encrypt_Key_2_return

	.align	4, 0x90
L_key_expansion_192:
	pshufd	$0x55, %xmm2, %xmm2

	movaps	%xmm1, %xmm4
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm1
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm1
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm1
	pxor	%xmm2, %xmm1

	pshufd	$0xff, %xmm1, %xmm2

	movaps	%xmm3, %xmm4
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm3
	pxor	%xmm2, %xmm3

	movups	%xmm1, (cx)
	movq	%xmm3, 16(cx)

	add		$24, cx
	ret

L_AES_256_Encrypt_Key:
#ifdef	KERNEL
	// save xmm registers
	movaps	%xmm1, (sp)
	movaps	%xmm2, 16(sp)
	movaps	%xmm3, 32(sp)
	movaps	%xmm4, 48(sp)
#endif	// KERNEL
	movl	$224, 240(ctx)		// write expanded key length to ctx

	movups	(pkey), %xmm1
	movups	16(pkey), %xmm3
	movups	%xmm1, (ctx)
	movups	%xmm3, 16(ctx)

	lea		32(ctx), cx

	aeskeygenassist	$1, %xmm3, %xmm2
	call	L_key_expansion_256
	aeskeygenassist	$2, %xmm3, %xmm2
	call	L_key_expansion_256
	aeskeygenassist	$4, %xmm3, %xmm2
	call	L_key_expansion_256
	aeskeygenassist	$8, %xmm3, %xmm2
	call	L_key_expansion_256
	aeskeygenassist	$0x10, %xmm3, %xmm2
	call	L_key_expansion_256
	aeskeygenassist	$0x20, %xmm3, %xmm2
	call	L_key_expansion_256
	aeskeygenassist	$0x40, %xmm3, %xmm2
	call	L_key_expansion_256_final

#ifdef	KERNEL
	// restore xmm registers
	movaps	(sp), %xmm1
	movaps	16(sp), %xmm2
	movaps	32(sp), %xmm3
	movaps	48(sp), %xmm4
#endif	// KERNEL
	xor		%eax, %eax			// return 0 for success
	jmp		L_Encrypt_Key_2_return

	.align	4, 0x90
L_key_expansion_256:

	pshufd	$0xff, %xmm2, %xmm2

	movaps	%xmm1, %xmm4
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm1
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm1
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm1
	pxor	%xmm2, %xmm1

	movups	%xmm1, (cx)

	aeskeygenassist	$0, %xmm1, %xmm4

	pshufd	$0xaa, %xmm4, %xmm2

	movaps	%xmm3, %xmm4
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm3
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm3
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm3
	pxor	%xmm2, %xmm3

	movups	%xmm3, 16(cx)

	add		$32, cx
	ret

	.align	4, 0x90
L_key_expansion_256_final:

	pshufd	$0xff, %xmm2, %xmm2

	movaps	%xmm1, %xmm4
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm1
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm1
	pslldq	$4, %xmm4

	pxor	%xmm4, %xmm1
	pxor	%xmm2, %xmm1

	movups	%xmm1, (cx)
	ret 

// _aes_decrypt_key_hw is implemented as
// 	1. call _aes_encrypt_key_hw
// 	2. use aesimc to convert the expanded round keys (except the 1st and last round keys)

	.text	
	.align	4, 0x90
	.globl	_aes_decrypt_key_hw
_aes_decrypt_key_hw:

#ifdef	__i386__

	push	%ebp
	mov		%esp, %ebp
	sub		$(8+16), %esp

	// copy input arguments for calling aes_decrypt_key_hw

	mov		8(%ebp), %eax
	mov		%eax, (%esp)
	mov		12(%ebp), %eax
	mov		%eax, 4(%esp)
	mov		16(%ebp), %eax
	mov		%eax, 8(%esp)

#else

	push	%rbp
	mov		%rsp, %rbp
	sub		$16, %rsp

	// calling arguments %rdi/%rsi/%rdx will be used for encrypt_key 
	// %rdx (ctx) will return unchanged
	// %rsi (klen) will (<<3) if <= 32

#endif
	call	_aes_encrypt_key_hw
	cmp		$0, %eax
	je		L_decrypt_inv
L_decrypt_almost_done:
#ifdef	__i386__
	add		$(8+16), %esp
#else
	add		$16, %rsp
#endif
	leave
	ret

L_decrypt_inv:
#ifdef	KERNEL
	movaps	%xmm0, (sp)
#endif

#ifdef	__i386__	
	#undef	klen
	#undef	ctx	
	mov     12(%ebp), %eax      // klen
    mov     16(%ebp), %edx      // ctx
	#define	klen	%eax
	#define	ctx		%edx
	cmp		$32, klen
	jg		0f					// klen>32
	shl		$3, klen			// convert 16/24/32 to 128/192/256
0:
#endif

	mov		$9, cx				// default is AES-128
	cmp		$128, klen
	je		L_Decrypt_Key
	add		$2, cx
	cmp		$192, klen
	je		L_Decrypt_Key
	add		$2, cx 

L_Decrypt_Key:
	add		$16, ctx
	movups	(ctx), %xmm0
	aesimc	%xmm0, %xmm0
	movups	%xmm0, (ctx)
	sub		$1, cx
	jg		L_Decrypt_Key

#ifdef	KERNEL
	movaps	(sp), %xmm0
#endif
#ifdef	__i386__
	xor		%eax, %eax
#endif
	jmp		L_decrypt_almost_done

#endif /* x86 based build */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/aes_modes_asm.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
 ---------------------------------------------------------------------------
 Copyright (c) 2003, Dr Brian Gladman, Worcester, UK.   All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue 31/01/2006

 These subroutines implement multiple block AES modes for ECB, CBC, CFB,
 OFB and CTR encryption,  The code provides support for the VIA Advanced 
 Cryptography Engine (ACE).

 NOTE: In the following subroutines, the AES contexts (ctx) must be
 16 byte aligned if VIA ACE is being used
*/
#if defined __i386__ || defined __x86_64__

/* modified 3/5/10 cclee */
/* Clean up those related to VIA ACE and hand optimize aes_cbc_encrypt and aes_cbc_decrypt */
/* move the xmm registers save/restore originally inside the callee functions into these 2 caller functions */

/* add code comments/description and HW AES detection and execution branch cclee 3-13-10 */

/* cclee 7-30-10
	per murf's request, I changed the type of the 2nd argument iv in aes_encrypt_cbc/aes_decrypt_cbc
	from "const unsigned char *" to "unsigned char *". That is, the updated *iv (16-bytes) is written back
	to the memory in the caller function pointed by the input argument.
	In the implementation, *iv is locally saved in %xmm7.
	Before return, we now write %xmm7 back to *iv.

	Note: we only do this in CommonCrypto. In the kernel, there are some other functions (IOKit/vm_pageout, e.g.)
	that might assume *iv is read only, and therefore should not be changed. This is being tracked in

	<rdar://problem/8256020> xnu : add cbc feature in bsd/crypto/aes/i386/
	
*/

#include <System/i386/cpu_capabilities.h> 	// to use __cpu_capabilities&kHasAES to detect Intel Westmere AES HW

#if 0

// TODO:
// aes_ecb_encrypt and aes_ecb_decrypt are not present in gen/aescrypt.c
// would add the implementation if needed
// they are now compiled from aes_modes.c

aes_rval aes_ecb_encrypt(const unsigned char *ibuf, unsigned char *obuf,
                    int len, const aes_encrypt_ctx ctx[1])
{   int nb = len >> 4;

    if(len & (AES_BLOCK_SIZE - 1)) return 1;
    while(nb--) {
        aes_encrypt(ibuf, obuf, ctx);
        ibuf += AES_BLOCK_SIZE;
        obuf += AES_BLOCK_SIZE;
    }
    return 0;
}

aes_rval aes_ecb_decrypt(const unsigned char *ibuf, unsigned char *obuf,
                    int len, const aes_decrypt_ctx ctx[1])
{   int nb = len >> 4;

    if(len & (AES_BLOCK_SIZE - 1)) return 1;
    while(nb--) {
        aes_decrypt(ibuf, obuf, ctx);
        ibuf += AES_BLOCK_SIZE;
        obuf += AES_BLOCK_SIZE;
    }
    return 0;
}
#endif

#if 0
aes_rval aesedp_encrypt_cbc(const unsigned char *ibuf, unsigned char *iv, unsigned int num_blk,
					 unsigned char *obuf, const aes_encrypt_ctx ctx[1])
{
		int i;
		
		while (num_blk--) {
			*iv ^= ibuf;			// 128-bit	
            aes_encrypt(*iv, *iv, ctx);
            memcpy(obuf, iv, AES_BLOCK_SIZE);
            ibuf += AES_BLOCK_SIZE;
            obuf += AES_BLOCK_SIZE;
			
		}		

		return 0;
}
#endif

	.text
	.align	4,0x90
	.globl	_aesedp_encrypt_cbc
_aesedp_encrypt_cbc:

	// detect AES HW
	// if AES HW detected, branch to AES-HW-specific function _aesedp_encrypt_cbc_hw (aes_modes_hw.s)
	// o.w., fall through to the original AES-SW function

#if defined	__x86_64__
	movq	__cpu_capabilities@GOTPCREL(%rip), %rax			// %rax -> __cpu_capability
	mov		(%rax), %eax									// %eax = __cpu_capabilities
#else
#ifdef	KERNEL
	leal	__cpu_capabilities, %eax						// %eax -> __cpu_capabilities
	mov		(%eax), %eax									// %eax = __cpu_capabilities
#else
	mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
#endif
#endif
	test	$(kHasAES), %eax								// kHasAES & __cpu_capabilities
	jne		_aesedp_encrypt_cbc_hw								// if AES HW detected, branch to HW-specific code

	// save registers and allocate stack memory for xmm registers and calling arguments (i386 only)
#if	defined	__i386__
	push	%ebp
	mov		%esp, %ebp
	push	%ebx					// to be used as ibuf
	push	%edi					// to be used as obuf
	sub		$(16+16+7*16), %esp		// 12 (calling arguments) + 4 (%esi) + 16 (iv) + 7*16 (xmm)
	mov		%esi, 12(%esp)			// save %esp in the unused 4-bytes, to be used as num_blk

	#define	sp	%esp
#else	// __x86_64__
	push	%rbp
	mov		%rsp, %rbp
	push	%rbx
	push	%r12
	push	%r13
	push	%r14
	push	%r15
	sub		$(8+16+5*16+16), %rsp	// 8 (align) + 16 (dummy iv) + 5*16 (xmm) + 16 (for i386-x86_64 consistency)	

	#define	sp	%rsp
#endif

	// save xmm registers for kernel use
	// xmm6-xmm7 will be used locally
	// xmm0-xmm2 (x86_64) or xmm0-/xmm4 (i386) will be used inside _aes_encrypt_xmm_no_save (non-restored)

	// the following code is changed per to a request from commoncrypto, it use directly *iv, not a local copy

#ifdef	KERNEL
	movaps	%xmm7, 16(sp)
	movaps	%xmm6, 32(sp)
	movaps	%xmm0, 64(sp)
	movaps	%xmm1, 80(sp)
	movaps	%xmm2, 96(sp)
#if defined	__i386__
	movaps	%xmm3, 112(sp)
	movaps	%xmm4, 128(sp)
#endif
#endif

	// set up registers from calling arguments

#if defined	__i386__

	mov		12(%ebp), %eax			// iv
	mov		24(%ebp), %edx			// ctx
	movups	(%eax), %xmm7			// in_iv	
	mov		%eax, (%esp)			// 1st iv for aes_encrypt
	mov		%eax, 4(%esp)			// 2nd iv for aes_encrypt
	mov		%edx, 8(%esp)			// ctx for aes_encrypt
	mov		8(%ebp), %ebx			// ibuf
	mov		16(%ebp), %esi			// num_blk
	mov		20(%ebp), %edi			// obuf

	#define	ibuf	%ebx
	#define	obuf	%edi
	#define num_blk	%esi	

#else	//	__x86_64__, calling arguments order : rdi/rsi/rdx/rcx/r8

	mov		%rdi, %rbx				// ibuf
	mov		%rsi, %r12				// &iv
	movups	(%rsi), %xmm7			// in_iv
	mov		%rdx, %r13				// num_blk
	mov		%rcx, %r14				// obuf
	mov		%r8, %r15				// ctx	

	#define	ibuf	%rbx
	#define	iv		%r12
	#define	num_blk	%r13d
	#define	obuf	%r14	
	#define	ctx		%r15

#endif

	cmp		$1, num_blk				// num_blk vs 1
	jl		9f						// if num_blk < 1, branch to bypass the main loop
0:
	movups	(ibuf), %xmm6			// ibuf
#if defined	__i386__
	mov		12(%ebp), %eax			// &iv[0]
	pxor	%xmm6, %xmm7			// iv ^= ibuf
	movups	%xmm7, (%eax)			// save iv
#else
	pxor	%xmm6, %xmm7			// iv ^= ibuf
	movups	%xmm7, (iv)				// save iv
	mov		iv, %rdi				// 1st calling argument for aes_encrypt
	mov		iv, %rsi				// 2nd calling argument for aes_encrypt
	mov		ctx, %rdx				// 3rd calling argument for aes_encrypt
#endif
	call	_aes_encrypt_xmm_no_save	// aes_encrypt(iv, iv, ctx)
#if defined __i386__
	mov		12(%ebp), %eax			// &iv[0]
	movups	(%eax), %xmm7			// read iv
#else
	movups	(iv), %xmm7				// read iv
#endif
	movups	%xmm7, (obuf)			// memcpy(obuf, iv, AES_BLOCK_SIZE);
	add		$16, ibuf				// ibuf += AES_BLOCK_SIZE; 
	add		$16, obuf				// obuf += AES_BLOCK_SIZE;	
	sub		$1, num_blk				// num_blk --
	jg		0b						// if num_blk > 0, repeat the loop
9:	

L_crypt_cbc_done:

	// save the updated *iv
#if defined __i386__
	mov		12(%ebp), %eax
	movups	%xmm7, (%eax)
#else
	movups	%xmm7, (iv)
#endif

	// restore xmm registers due to kernel use
#ifdef	KERNEL
	movaps	16(sp), %xmm7
	movaps	32(sp), %xmm6
	movaps	64(sp), %xmm0
	movaps	80(sp), %xmm1
	movaps	96(sp), %xmm2
#if defined	__i386__
	movaps	112(sp), %xmm3
	movaps	128(sp), %xmm4
#endif
#endif

	xor		%eax, %eax				// to return 0 for SUCCESS

#if	defined	__i386__
	mov		12(%esp), %esi			// restore %esi
	add		$(16+16+7*16), %esp		// 12 (calling arguments) + 4 (%esi) + 16 (iv) + 7*16 (xmm)
	pop		%edi
	pop		%ebx
#else
	add		$(8+16+5*16+16), %rsp	// 8 (align) + 16 (dummy iv) + 5*16 (xmm) + 16 (for i386-x86_64 consistency)	
	pop		%r15
	pop		%r14
	pop		%r13
	pop		%r12
	pop		%rbx
#endif
	leave
	ret

#if 0
aes_rval aesedp_decrypt_cbc(const unsigned char *ibuf, unsigned char *iv, unsigned int num_blk,
					 unsigned char *obuf, const aes_decrypt_ctx cx[1])
{
		unsigned char tmp[16];
		int i;
		
		while (num_blk--) {

            memcpy(tmp, ibuf, AES_BLOCK_SIZE);
            aes_decrypt(ibuf, obuf, ctx);
			obuf ^= *iv;
            memcpy(iv, tmp, AES_BLOCK_SIZE);
            ibuf += AES_BLOCK_SIZE;
            obuf += AES_BLOCK_SIZE;
		}

		return 0;
}
#endif

	.text
	.align	4,0x90
	.globl	_aesedp_decrypt_cbc
_aesedp_decrypt_cbc:

	// detect AES HW
	// if AES HW detected, branch to AES-HW-specific function _aesedp_decrypt_cbc_hw (aes_modes_hw.s)
	// o.w., fall through to the original AES-SW function

#if defined	__x86_64__
	movq	__cpu_capabilities@GOTPCREL(%rip), %rax			// %rax -> __cpu_capability
	mov		(%rax), %eax									// %eax = __cpu_capabilities
#else
#ifdef	KERNEL
	leal	__cpu_capabilities, %eax						// %eax -> __cpu_capabilities
	mov		(%eax), %eax									// %eax = __cpu_capabilities
#else
	mov    _COMM_PAGE_CPU_CAPABILITIES, %eax
#endif
#endif
	test	$(kHasAES), %eax								// kHasAES & __cpu_capabilities
	jne		_aesedp_decrypt_cbc_hw

	// save registers and allocate stack memory for xmm registers and calling arguments (i386 only)
#if	defined	__i386__
	push	%ebp
	mov		%esp, %ebp
	push	%ebx					// to be used as ibuf
	push	%edi					// to be used as obuf
	sub		$(16+16+7*16), %esp		// 12 (calling arguments) + 4 (%esi) + 16 (iv) + 7*16 (xmm)
	mov		%esi, 12(%esp)			// save %esp in the unused 4-bytes, to be used as num_blk

	#define	sp	%esp
#else	// __x86_64__
	push	%rbp
	mov		%rsp, %rbp
	push	%rbx
	push	%r12
	push	%r13
	push	%r14
	push	%r15
	sub		$(8+16+5*16+16), %rsp	// 8 (align) + 16 (dummy iv) + 5*16 (xmm) + 16 (for i386-x86_64 consistency)	

	#define	sp	%rsp
#endif

	// save xmm registers for kernel use
	// xmm6-xmm7 will be used locally
	// xmm0-xmm2 (x86_64) or xmm0-/xmm4 (i386) will be used inside _aes_encrypt_xmm_no_save (non-restored)

#ifdef	KERNEL
	movaps	%xmm7, 16(sp)
	movaps	%xmm6, 32(sp)
	movaps	%xmm0, 64(sp)
	movaps	%xmm1, 80(sp)
	movaps	%xmm2, 96(sp)
#if defined	__i386__
	movaps	%xmm3, 112(sp)
	movaps	%xmm4, 128(sp)
#endif
#endif

	// set up registers from calling arguments

#if defined	__i386__
	mov		12(%ebp), %eax			// &iv[0]
	mov		24(%ebp), %edx			// ctx
	movups	(%eax), %xmm7			// in_iv	
	mov		%edx, 8(%esp)			// ctx for aes_encrypt
	mov		8(%ebp), %ebx			// ibuf
	mov		16(%ebp), %esi			// num_blk
	mov		20(%ebp), %edi			// obuf

	#define	ibuf	%ebx
	#define	obuf	%edi
	#define num_blk	%esi	
#else	//	__x86_64__, rdi/rsi/rdx/rcx/r8
	mov		%rdi, %rbx				// ibuf
	mov		%rsi, %r12				// &iv[0]
	movups	(%rsi), %xmm7			// in_iv
	mov		%rdx, %r13				// num_blk
	mov		%rcx, %r14				// obuf 
	mov		%r8, %r15				// ctx	

	#define	ibuf	%rbx
	#define	num_blk	%r13d
	#define	obuf	%r14	
	#define	ctx		%r15

#endif
           // memcpy(tmp, ibuf, AES_BLOCK_SIZE);
           // aes_decrypt(ibuf, obuf, ctx);
			//	obuf ^= iv;
           // memcpy(iv, tmp, AES_BLOCK_SIZE);
           // ibuf += AES_BLOCK_SIZE;
           // obuf += AES_BLOCK_SIZE;

	cmp		$1, num_blk					// num_blk vs 1
	jl		L_crypt_cbc_done			// if num_blk < 1, bypass the main loop, jump to finishing code
0:
	movups	(ibuf), %xmm6				// tmp
#if defined	__i386__
	mov		ibuf, (sp)					// ibuf
	mov		obuf, 4(sp)					// obuf
#else
	mov		ibuf, %rdi					// ibuf 
	mov		obuf, %rsi					// obuf
	mov		ctx, %rdx					// ctx
#endif
	call	_aes_decrypt_xmm_no_save	// aes_decrypt(ibuf, obuf, ctx)
	movups	(obuf), %xmm0				// obuf
	pxor	%xmm7, %xmm0				// obuf ^= iv;
	movaps	%xmm6, %xmm7				// memcpy(iv, tmp, AES_BLOCK_SIZE);
	movups	%xmm0, (obuf)				// update obuf
	add		$16, ibuf					// ibuf += AES_BLOCK_SIZE; 
	add		$16, obuf					// obuf += AES_BLOCK_SIZE;	
	sub		$1, num_blk					// num_blk --
	jg		0b							// if num_blk > 0, repeat the loop
9:	

	// we are done here, the finishing code is identical to that in aesedp_encrypt_cbc, so just jump to there
	jmp		L_crypt_cbc_done
#endif /* x86 based build */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/aes_modes_hw.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
/*
 ---------------------------------------------------------------------------
 Copyright (c) 2003, Dr Brian Gladman, Worcester, UK.   All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue 31/01/2006

 These subroutines implement multiple block AES modes for ECB, CBC, CFB,
 OFB and CTR encryption,  The code provides support for the VIA Advanced 
 Cryptography Engine (ACE).

 NOTE: In the following subroutines, the AES contexts (ctx) must be
 16 byte aligned if VIA ACE is being used
*/

#if defined __i386__ || defined __x86_64__

/* modified 3/5/10 cclee */
/* Clean up those related to VIA ACE and hand optimize aes_cbc_encrypt and aes_cbc_decrypt */
/* move the xmm registers save/restore originally inside the callee functions into these 2 caller functions */

/* HW-AES specific implementation cclee 3-12-10 */
/* In aes_encrypt_cbc and aes_decrypt_cbc, __cpu_capabilities is polled, 
	and if kHasAES is detected, branch to the hw-specific functions here */


/* 	
	This files defines _aesedp_encrypt_cbc_hw and _aesedp_decrypt_cbc_hw --- Intel Westmere HW AES-based implementation
	of _aes_encrypt_cbc and _aes_decrypt_cbc. 

	These 2 functions SHOULD BE entried ONLY after the AES HW is verified to be available. 
	They SHOULD NOT be called without AES HW detection. It might cause xnu to crash.

	The AES HW is detected 1st thing in 
		_aes_encrypt_cbc (aes_modes_asm.s) 
		_aes_decrypt_cbc (aes_modes_asm.s)
	and, if AES HW is detected, branch without link (ie, jump) to the functions here.

	The implementation here follows the examples in an Intel White Paper
	"Intel Advanced Encryption Standard (AES) Instruction Set" Rev.2 01

	Note: Rev. 03 Final 2010 01 26 is available. Looks like some code change from Rev.2 01

	cclee 3-13-10
*/

/* 
	The function _aesedp_decrypt_cbc_hw previously simply serially decrypts block by block
	in our group meeting, Eric/Ali suggested that I perhaps should take a look of combining multiple blocks
	in a loop and interleaving multiple aesdec instructions to absorb/hide stalls to improve the decrypt thoughput.

	The idea was actually described in the Intel AES Instruction Set White Paper (Rev. 2.0 page 53-55) 

	This modification interleaves the aesdec/aesdeclast instructions for 4 blocks in cbc mode.
	On a 2.4GHz core-i5/2.66GHz core-i7, the x86_64 decrypt throughput (in xnu-iokit) has been improved
	from 1180/1332 to 1667/1858 MBytes/sec. This is approximately 1.40 times speedup in the decryption.
	The encrypt throughput is not changed.  

	I also enhanced the assembly code comments.

	cclee-4-30-10 (Do you know 4-30 is National Honesty Day in the US? No need to know. I've been honest all the time.)

*/

/* cclee 7-30-10
    per murf's request, I changed the type of the 2nd argument iv in aes_encrypt_cbc/aes_decrypt_cbc
    from "const unsigned char *" to "unsigned char *". That is, the updated *iv (16-bytes) is written back
    to the memory in the caller function pointed by the input argument.
    In the implementation, *iv is locally saved in %xmm7.
    Before return, we now write %xmm7 back to *iv.

    Note: we only do this in CommonCrypto. In the kernel, there are some other functions (IOKit/vm_pageout, e.g.)
    that might assume *iv is read only, and therefore should not be changed. This is being tracked in

    <rdar://problem/8256020> xnu : add cbc feature in bsd/crypto/aes/i386/
    
*/

/* ---------------------------------------------------------------------------------------------------------------- 

	aes_encrypt_cbc function (see aes_modes.c or aes_modes_asm.s) :

	For simplicity, I am assuming all variables are in 128-bit data type.

	aes_rval aes_encrypt_cbc(const __m128 *ibuf, __m128 *iv, int num_blk, __m128 *obuf, const aes_encrypt_ctx *ctx)
	{
		while(num_blk--) {
			*iv ^= *ibuf++;
			aes_encrypt(iv, iv, ctx);
			*obuf++ = *iv;
		}
		return 0;
	}

	The following is an implementation of this function using Intel AESNI.
	This function _aesedp_encrypt_cbc_hw SHOULD NOT be called directly. 
	Developer should still call _aes_encrypt_cbc (in aes_modes_asm.s) which will poll cpu_capabilities and branch
	to this aesni-based function should it detecs that aesni is available.
	Blindly call this function SURELY will cause a CRASH on systems with no aesni support. 

	Note that each block starts with *iv, which is the output of the previous block. Therefore, the cbc blocks
	are serially chained. This prevents us from arranging several blocks for encryption in parallel.

   ----------------------------------------------------------------------------------------------------------------*/

	.text
	.align	4,0x90
	.globl	_aesedp_encrypt_cbc_hw
_aesedp_encrypt_cbc_hw:

	// push/save registers for local use
#if	defined	__i386__

	push	%ebp
	movl	%esp, %ebp
	push	%ebx
	push	%edi

	#define	sp	%esp

#else	// __x86_64__

	push	%rbp
	mov		%rsp, %rbp
	push	%rbx
	push	%r13
	push	%r14
	push	%r15

	#define	sp	%rsp

#endif

	// if this is kernel code, need to save used xmm registers
#ifdef	KERNEL

#if defined __i386__
	sub		$(8*16), %esp			// for possible xmm0-xmm7 save/restore
#else
	sub		$(16*16), %rsp		// xmm0-xmm15 save/restore	
#endif

	movaps	%xmm0, (sp)
	movaps	%xmm1, 16(sp)
	movaps	%xmm2, 32(sp)
	movaps	%xmm3, 48(sp)
	movaps	%xmm4, 64(sp)
	movaps	%xmm5, 80(sp)
	movaps	%xmm6, 96(sp)
	movaps	%xmm7, 112(sp)
#if defined	__x86_64__
	movaps	%xmm8, 16*8(sp)
	movaps	%xmm9, 16*9(sp)
	movaps	%xmm10, 16*10(sp)
	movaps	%xmm11, 16*11(sp)
	movaps	%xmm12, 16*12(sp)
	movaps	%xmm13, 16*13(sp)
	movaps	%xmm14, 16*14(sp)
	movaps	%xmm15, 16*15(sp)
#endif	// __x86_64__

#endif	// KERNEL

	#define	iv	%xmm0

#ifdef	__i386__

	mov		12(%ebp), %eax			// &iv[0]
	mov		24(%ebp), %edx			// ctx
	movups	(%eax), iv				// iv = in_iv	
	mov		8(%ebp), %ebx			// ibuf
	mov		16(%ebp), %ecx			// num_blk
	mov		20(%ebp), %edi			// obuf

	#define	ibuf	%ebx
	#define	obuf	%edi
	#define num_blk	%ecx	
	#define	ctx		%edx

#else

	mov		%rdi, %rbx				// ibuf
	movups	(%rsi), iv				// iv = in_iv
	mov		%rdx, %r13				// num_blk
	mov		%rcx, %r14				// obuf
	mov		%r8, %r15				// ctx	

	#define	ibuf	%rbx
	#define	num_blk	%r13d
	#define	obuf	%r14	
	#define	ctx		%r15

#endif

	mov		240(ctx), %eax			// aes length
	cmp		$160, %eax				// aes-128 encrypt ?
	je		L_encrypt_128
	cmp		$192, %eax				// aes-192 encrypt ?
	je		L_encrypt_192
	cmp		$224, %eax				// aes-256 encrypt ?
	je		L_encrypt_256
	mov		$-1, %eax				// return error
	jmp		L_error	

	//
	// aes-128 encrypt_cbc operation, up to L_HW_cbc_done
	//

L_encrypt_128:

	cmp		$1, num_blk				// check number of block
	jl		L_HW_cbc_done			// should it be less than 1, nothing to do

	movups	(ctx), %xmm2			// key0
	movups	16(ctx), %xmm3			// key1
	movups	32(ctx), %xmm4			// key2
	movups	48(ctx), %xmm5			// key3
	movups	64(ctx), %xmm6			// key4
	movups	80(ctx), %xmm7			// key5
#if defined	__x86_64__
	movups	96(ctx), %xmm8			// key6
	movups	112(ctx), %xmm9			// key7
	movups	128(ctx), %xmm10		// key8
	movups	144(ctx), %xmm11		// key9
	movups	160(ctx), %xmm12		// keyA
#endif

	// while (num_blk--) {
	//			*iv ^= *ibuf++;
	//			aes_encrypt(iv, iv, ctx);
	//			*obuf++ = *iv;
	// }
0:
	movups	(ibuf), %xmm1				// *ibuf
	pxor    %xmm2, iv					// 1st instruction inside aes_encrypt
	pxor	%xmm1, iv					// *iv ^= *ibuf

	// finishing up the rest of aes_encrypt
    aesenc  %xmm3, iv
    aesenc  %xmm4, iv
    aesenc  %xmm5, iv
    aesenc  %xmm6, iv
    aesenc  %xmm7, iv
#if defined	__x86_64__
    aesenc  %xmm8, iv
    aesenc  %xmm9, iv
    aesenc  %xmm10, iv
    aesenc  %xmm11, iv
    aesenclast  %xmm12, iv
#else
	movups	96(ctx), %xmm1				// key6
    aesenc  %xmm1, iv
	movups	112(ctx), %xmm1				// key7
    aesenc  %xmm1, iv
	movups	128(ctx), %xmm1				// key8
    aesenc  %xmm1, iv
	movups	144(ctx), %xmm1				// key9
    aesenc  %xmm1, iv
	movups	160(ctx), %xmm1				// keyA
    aesenclast  %xmm1, iv
#endif

	movups	iv, (obuf)					// *obuf = *iv;
	add		$16, obuf					// obuf++;
	add		$16, ibuf					// ibuf++;
	sub		$1, num_blk					// num_blk --
	jg		0b							// if num_blk > 0, repeat the loop

	// the following will be branched to from all other cases (encrypt/decrypt 128/192/256)

L_HW_cbc_done:

	// save the updated *iv
#if defined __i386__
	mov		12(%ebp), %eax
	movups	iv, (%eax)
#else
	movups	iv, (%rsi)
#endif

	xor		%eax, %eax				// to return CRYPT_OK

L_error:

	// if kernel, restore xmm registers
#ifdef	KERNEL 
	movaps	0(sp), %xmm0
	movaps	16(sp), %xmm1
	movaps	32(sp), %xmm2
	movaps	48(sp), %xmm3
	movaps	64(sp), %xmm4
	movaps	80(sp), %xmm5
	movaps	96(sp), %xmm6
	movaps	112(sp), %xmm7
#if defined	__x86_64__
	movaps	16*8(sp), %xmm8
	movaps	16*9(sp), %xmm9
	movaps	16*10(sp), %xmm10
	movaps	16*11(sp), %xmm11
	movaps	16*12(sp), %xmm12
	movaps	16*13(sp), %xmm13
	movaps	16*14(sp), %xmm14
	movaps	16*15(sp), %xmm15
#endif	// __x86_64__
#endif	// KERNEL

	// release used stack memory, restore used callee-saved registers, and return 
#if	defined	__i386__
#ifdef	KERNEL
	add		$(8*16), %esp
#endif
	pop		%edi
	pop		%ebx
#else
#ifdef	KERNEL
	add		$(16*16), %rsp	
#endif
	pop		%r15
	pop		%r14
	pop		%r13
	pop		%rbx
#endif
	leave
	ret

	//
	// aes-192 encrypt_cbc operation, after completion, branch to L_HW_cbc_done
	//

L_encrypt_192:

	cmp		$1, num_blk				// check number of block
	jl		L_HW_cbc_done			// should it be less than 1, nothing to do

	movups	(ctx), %xmm2			// key0
	movups	16(ctx), %xmm3			// key1
	movups	32(ctx), %xmm4			// key2
	movups	48(ctx), %xmm5			// key3
	movups	64(ctx), %xmm6			// key4
	movups	80(ctx), %xmm7			// key5
#if defined	__x86_64__
	movups	96(ctx), %xmm8			// key6
	movups	112(ctx), %xmm9			// key7
	movups	128(ctx), %xmm10		// key8
	movups	144(ctx), %xmm11		// key9
	movups	160(ctx), %xmm12		// keyA
	movups	176(ctx), %xmm13		// keyB
	movups	192(ctx), %xmm14		// keyC
#endif
	
	// while (num_blk--) {
	//			*iv ^= *ibuf++;
	//			aes_encrypt(iv, iv, ctx);
	//			*obuf++ = *iv;
	// }
0:
	movups	(ibuf), %xmm1			// *ibuf
	pxor	%xmm1, iv				// *iv ^= ibuf

	// aes_encrypt(iv, iv, ctx);

	pxor    %xmm2, iv
    aesenc  %xmm3, iv
    aesenc  %xmm4, iv
    aesenc  %xmm5, iv
    aesenc  %xmm6, iv
    aesenc  %xmm7, iv
#if defined	__x86_64__
    aesenc  %xmm8, iv
    aesenc  %xmm9, iv
    aesenc  %xmm10, iv
    aesenc  %xmm11, iv
    aesenc  %xmm12, iv
    aesenc  %xmm13, iv
    aesenclast  %xmm14, iv
#else
	movups	96(ctx), %xmm1
    aesenc  %xmm1, iv
	movups	112(ctx), %xmm1
    aesenc  %xmm1, iv
	movups	128(ctx), %xmm1
    aesenc  %xmm1, iv
	movups	144(ctx), %xmm1
    aesenc  %xmm1, iv
	movups	160(ctx), %xmm1
    aesenc  %xmm1, iv
	movups	176(ctx), %xmm1
    aesenc  %xmm1, iv
	movups	192(ctx), %xmm1
    aesenclast  %xmm1, iv
#endif

	movups	iv, (obuf)				// *obuf = *iv;
	add		$16, ibuf				// ibuf++
	add		$16, obuf				// obuf++

	sub		$1, num_blk				// num_blk --
	jg		0b						// if num_blk > 0, repeat the loop

	jmp		L_HW_cbc_done			// share with the common exit code

	//
	// aes-256 encrypt_cbc operation, after completion, branch to L_HW_cbc_done
	//

L_encrypt_256:

	cmp		$1, num_blk				// check number of block
	jl		L_HW_cbc_done			// should it be less than 1, nothing to do

	movups	(ctx), %xmm2			// key0
	movups	16(ctx), %xmm3			// key1
	movups	32(ctx), %xmm4			// key2
	movups	48(ctx), %xmm5			// key3
	movups	64(ctx), %xmm6			// key4
	movups	80(ctx), %xmm7			// key5
#if defined	__x86_64__
	movups	96(ctx), %xmm8			// key6
	movups	112(ctx), %xmm9			// key7
	movups	128(ctx), %xmm10		// key8
	movups	144(ctx), %xmm11		// key9
	movups	160(ctx), %xmm12		// keyA
	movups	176(ctx), %xmm13		// keyB
	movups	192(ctx), %xmm14		// keyC
	movups	208(ctx), %xmm15		// keyD
	// movups	224(ctx), %xmm1		// keyE
#endif

	// while (num_blk--) {
	//			*iv ^= *ibuf++;
	//			aes_encrypt(iv, iv, ctx);
	//			*obuf++ = *iv;
	// }
0:
	movups	(ibuf), %xmm1			// *ibuf
	pxor	%xmm1, iv				// *iv ^= ibuf
	
	// aes_encrypt(iv, iv, ctx);
	pxor    %xmm2, iv
    aesenc  %xmm3, iv
    aesenc  %xmm4, iv
    aesenc  %xmm5, iv
    aesenc  %xmm6, iv
    aesenc  %xmm7, iv
#if defined	__x86_64__
	movups	224(ctx), %xmm1			// keyE
    aesenc  %xmm8, iv
    aesenc  %xmm9, iv
    aesenc  %xmm10, iv
    aesenc  %xmm11, iv
    aesenc  %xmm12, iv
    aesenc  %xmm13, iv
    aesenc  %xmm14, iv
    aesenc  %xmm15, iv
    aesenclast  %xmm1, iv
#else
	movups	96(ctx), %xmm1			// key6
    aesenc  %xmm1, iv
	movups	112(ctx), %xmm1			// key7
    aesenc  %xmm1, iv
	movups	128(ctx), %xmm1			// key8
    aesenc  %xmm1, iv
	movups	144(ctx), %xmm1			// key9
    aesenc  %xmm1, iv
	movups	160(ctx), %xmm1			// keyA
    aesenc  %xmm1, iv
	movups	176(ctx), %xmm1			// keyB
    aesenc  %xmm1, iv
	movups	192(ctx), %xmm1			// keyC
    aesenc  %xmm1, iv
	movups	208(ctx), %xmm1			// keyD
    aesenc  %xmm1, iv
	movups	224(ctx), %xmm1			// keyE
    aesenclast  %xmm1, iv
#endif

	movups	iv, (obuf)				// *obuf = *iv;
	add		$16, ibuf				// ibuf++
	add		$16, obuf				// obuf++

	sub		$1, num_blk				// num_blk --
	jg		0b						// if num_blk > 0, repeat the loop

	jmp		L_HW_cbc_done			// share with the common exit code



	//
	// --------- END of aesedp_encrypt_cbc_hw  -------------------
	//


/* ---------------------------------------------------------------------------------------------------------------- 

	aes_decrypt_cbc function (see aes_modes.c or aes_modes_asm.s) :

	For simplicity, I am assuming all variables are in 128-bit data type.

	aes_rval aes_decrypt_cbc(const __m128 *ibuf, __m128 *iv, int num_blk, __m128 *obuf, const aes_decrypt_ctx *ctx)
	{
		while(num_blk--) {
			aes_decrypt(ibuf, obuf, ctx);
			*obuf++ ^= *iv;
			*iv = *ibuf++;
		}
		return 0;
	}

	The following is an implementation of this function using Intel AESNI.
	This function _aesedp_decrypt_cbc_hw SHOULD NOT be called directly. 
	Developer should still call _aes_decrypt_cbc (in aes_modes_asm.s) which will poll cpu_capabilities and branch
	to this aesni-based function should it detecs that aesni is available.
	Blindly call this function SURELY will cause a CRASH on systems with no aesni support. 

	Note that the decryption operation is not related over blocks.
	This gives opportunity of arranging aes_decrypt operations in parallel to speed up code.
	This is equivalent to what has been described in the Intel AES Instruction Set White Paper (Rev. 2.0 page 53-55)
	The following assembly code exploits this idea to achieve ~ 1.4 speed up in aes_decrypt_cbc.

	Example C code for packing 4 blocks in an iteration is shown as follows:

		while ((num_blk-=4)>=0) {

			// the following 4 functions can be interleaved to exploit parallelism
			aes_decrypt(ibuf, obuf, ctx);
			aes_decrypt(ibuf+1, obuf+1, ctx);
			aes_decrypt(ibuf+2, obuf+2, ctx);
			aes_decrypt(ibuf+3, obuf+3, ctx);

			obuf[0] ^= *iv; obuf[1] ^= ibuf[1]; obuf[2] ^= ibuf[1]; obuf[3] ^= ibuf[2];
			*iv = ibuf[3];		ibuf += 4; 	obuf += 4;
		}
		num_blk+=4;

   ----------------------------------------------------------------------------------------------------------------*/

	.text
	.align	4,0x90
	.globl	_aesedp_decrypt_cbc_hw
_aesedp_decrypt_cbc_hw:

	// push/save registers for local use
#if	defined	__i386__

	push	%ebp
	movl	%esp, %ebp
	push	%ebx					// ibuf
	push	%edi					// obuf

	#define	sp	%esp

#else	// __x86_64__

	push	%rbp
	mov		%rsp, %rbp
	push	%rbx
	push	%r13
	push	%r14
	push	%r15

	#define	sp	%rsp

#endif


	// if kernel, allocate stack space to save xmm registers
#ifdef	KERNEL
#if defined __i386__
	sub		$(8*16), %esp
#else
	sub		$(16*16), %rsp
#endif
	movaps	%xmm0, (sp)
	movaps	%xmm1, 16(sp)
	movaps	%xmm2, 32(sp)
	movaps	%xmm3, 48(sp)
	movaps	%xmm4, 64(sp)
	movaps	%xmm5, 80(sp)
	movaps	%xmm6, 96(sp)
	movaps	%xmm7, 112(sp)
#if defined	__x86_64__
	movaps	%xmm8, 16*8(sp)
	movaps	%xmm9, 16*9(sp)
	movaps	%xmm10, 16*10(sp)
	movaps	%xmm11, 16*11(sp)
	movaps	%xmm12, 16*12(sp)
	movaps	%xmm13, 16*13(sp)
	movaps	%xmm14, 16*14(sp)
	movaps	%xmm15, 16*15(sp)
#endif	// __x86_64__
#endif

	#undef	iv
	#define	iv	%xmm0

#if defined	__i386__
	mov		12(%ebp), %eax			// &iv[0]
	mov		24(%ebp), %edx			// ctx
	movups	(%eax), iv				// iv = in_iv	
	mov		8(%ebp), %ebx			// ibuf
	mov		16(%ebp), %ecx			// num_blk
	mov		20(%ebp), %edi			// obuf

	#define	ibuf	%ebx
	#define	obuf	%edi
	#define num_blk	%ecx	
	#define	ctx		%edx

#else	//	__x86_64__, rdi/rsi/rdx/rcx/r8

	mov		%rdi, %rbx				// ibuf
	movups	(%rsi), iv				// iv = in_iv
	mov		%rdx, %r13				// num_blk
	mov		%rcx, %r14				// obuf
	mov		%r8, %r15				// ctx	

	#define	ibuf	%rbx
	#define	num_blk	%r13d
	#define	obuf	%r14	
	#define	ctx		%r15

#endif

	mov		240(ctx), %eax			// aes length
	cmp		$160, %eax				// aes-128 decrypt
	je		L_decrypt_128
	cmp		$192, %eax				// aes-192 decrypt
	je		L_decrypt_192
	cmp		$224, %eax				// aes-256 decrypt
	je		L_decrypt_256

	mov		$-1, %eax				// wrong aes length, to return -1
	jmp		L_error					// early exit due to wrong aes length


	//
	// aes-128 decrypt_cbc operation, after completion, branch to L_HW_cbc_done
	//

L_decrypt_128:

	cmp		$1, num_blk
	jl		L_HW_cbc_done			// if num_blk < 1, early return

	// aes-128 decrypt expanded keys
	movups	160(ctx), %xmm3
	movups	144(ctx), %xmm4
	movups	128(ctx), %xmm5
	movups	112(ctx), %xmm6
	movups	96(ctx), %xmm7
#if defined	__x86_64__
	movups	80(ctx), %xmm8
	movups	64(ctx), %xmm9
	movups	48(ctx), %xmm10
	movups	32(ctx), %xmm11
	movups	16(ctx), %xmm12
	movups	0(ctx), %xmm13
#endif

	// performs 4 block decryption in an iteration to exploit decrypt in parallel

	//		while ((num_blk-=4)>=0) {
	//			aes_decrypt(ibuf, obuf, ctx);
	//			aes_decrypt(ibuf+1, obuf+1, ctx);
	//			aes_decrypt(ibuf+2, obuf+2, ctx);
	//			aes_decrypt(ibuf+3, obuf+3, ctx);
	//			obuf[0] ^= *iv; obuf[1] ^= ibuf[1]; obuf[2] ^= ibuf[1]; obuf[3] ^= ibuf[2];
	//			*iv = ibuf[3]; ibuf += 4; obuf += 4;
	//		}

	sub		$4, num_blk					// pre decrement num_blk by 4
	jl		9f							// if num_blk < 4, skip the per-4-blocks processing code

0:


#if defined	__x86_64__

	movups	(ibuf), %xmm1				// tmp = 1st ibuf
	movups	16(ibuf), %xmm2				// tmp = 2nd ibuf
	movups	32(ibuf), %xmm14			// tmp = 3rd ibuf
	movups	48(ibuf), %xmm15			// tmp = 4th ibuf

	// for x86_64, the expanded keys are already stored in xmm3-xmm13

	// aes-128 decrypt round 0 per 4 blocks
	pxor    %xmm3, %xmm1
	pxor    %xmm3, %xmm2
	pxor    %xmm3, %xmm14
	pxor    %xmm3, %xmm15

	// aes-128 decrypt round 1 per 4 blocks
    aesdec  %xmm4, %xmm1
    aesdec  %xmm4, %xmm2
    aesdec  %xmm4, %xmm14
    aesdec  %xmm4, %xmm15

	// aes-128 decrypt round 2 per 4 blocks
    aesdec  %xmm5, %xmm1
    aesdec  %xmm5, %xmm2
    aesdec  %xmm5, %xmm14
    aesdec  %xmm5, %xmm15

	// aes-128 decrypt round 3 per 4 blocks
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm14
    aesdec  %xmm6, %xmm15

	// aes-128 decrypt round 4 per 4 blocks
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm14
    aesdec  %xmm7, %xmm15

	// aes-128 decrypt round 5 per 4 blocks
    aesdec  %xmm8, %xmm1
    aesdec  %xmm8, %xmm2
    aesdec  %xmm8, %xmm14
    aesdec  %xmm8, %xmm15

	// aes-128 decrypt round 6 per 4 blocks
    aesdec  %xmm9, %xmm1
    aesdec  %xmm9, %xmm2
    aesdec  %xmm9, %xmm14
    aesdec  %xmm9, %xmm15

	// aes-128 decrypt round 7 per 4 blocks
    aesdec  %xmm10, %xmm1
    aesdec  %xmm10, %xmm2
    aesdec  %xmm10, %xmm14
    aesdec  %xmm10, %xmm15

	// aes-128 decrypt round 8 per 4 blocks
    aesdec  %xmm11, %xmm1
    aesdec  %xmm11, %xmm2
    aesdec  %xmm11, %xmm14
    aesdec  %xmm11, %xmm15

	// aes-128 decrypt round 9 per 4 blocks
    aesdec  %xmm12, %xmm1
    aesdec  %xmm12, %xmm2
    aesdec  %xmm12, %xmm14
    aesdec  %xmm12, %xmm15

	// aes-128 decrypt round 10 (last) per 4 blocks
    aesdeclast  %xmm13, %xmm1
    aesdeclast  %xmm13, %xmm2
    aesdeclast  %xmm13, %xmm14
    aesdeclast  %xmm13, %xmm15

	pxor	iv, %xmm1				// obuf[0] ^= *iv; 
	movups	(ibuf), iv				// ibuf[0]
	pxor	iv, %xmm2				// obuf[1] ^= ibuf[0]; 
	movups	16(ibuf), iv			// ibuf[1]
	pxor	iv, %xmm14				// obuf[2] ^= ibuf[1]; 
	movups	32(ibuf), iv			// ibuf[2] 
	pxor	iv, %xmm15				// obuf[3] ^= obuf[2]; 
	movups	48(ibuf), iv			// *iv = ibuf[3]

	movups	%xmm1, (obuf)			// write 1st obuf
	movups	%xmm2, 16(obuf)			// write 2nd obuf
	movups	%xmm14, 32(obuf)		// write 3rd obuf
	movups	%xmm15, 48(obuf)		// write 4th obuf


#else

	// aes_decrypt_cbc per 4 blocks using aes-128 for i386
	// xmm1/xmm2/xmm4/xmm5 used for obuf per block
	// xmm3 = key0
	// xmm0 = iv
	// xmm6/xmm7 dynamically load with other expanded keys

	movups	(ibuf), %xmm1			// tmp = 1st ibuf
	movups	16(ibuf), %xmm2			// tmp = 2nd ibuf
	movups	32(ibuf), %xmm4			// tmp = 3rd ibuf
	movups	48(ibuf), %xmm5			// tmp = 4th ibuf

	// aes_decrypt
	// for i386, sequentially load expanded keys into xmm6/xmm7

	movups	144(ctx), %xmm6			// key1

	// aes-128 decrypt round 0 per 4 blocks
	pxor    %xmm3, %xmm1
	pxor    %xmm3, %xmm2
	pxor    %xmm3, %xmm4
	pxor    %xmm3, %xmm5

	movups	128(ctx), %xmm7			// key2

	// aes-128 decrypt round 1 per 4 blocks
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	112(ctx), %xmm6			// key3

	// aes-128 decrypt round 2 per 4 blocks
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	96(ctx), %xmm7			// key4

	// aes-128 decrypt round 3 per 4 blocks
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	80(ctx), %xmm6			// key5

	// aes-128 decrypt round 4 per 4 blocks
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	64(ctx), %xmm7			// key6

	// aes-128 decrypt round 5 per 4 blocks
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	48(ctx), %xmm6			// key7

	// aes-128 decrypt round 6 per 4 blocks
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	32(ctx), %xmm7			// key8

	// aes-128 decrypt round 7 per 4 blocks
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	16(ctx), %xmm6			// key9

	// aes-128 decrypt round 8 per 4 blocks
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	0(ctx), %xmm7			// keyA

	// aes-128 decrypt round 9 per 4 blocks
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	// aes-128 decrypt round 10 (last) per 4 blocks
    aesdeclast  %xmm7, %xmm1
    aesdeclast  %xmm7, %xmm2
    aesdeclast  %xmm7, %xmm4
    aesdeclast  %xmm7, %xmm5

	pxor	iv, %xmm1				// 1st obuf ^= iv; 
	movups	(ibuf), iv				// 1st memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm2				// 2nd obuf ^= iv; 
	movups	16(ibuf), iv			// 2nd memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm4				// 3rd obuf ^= iv; 
	movups	32(ibuf), iv			// 3rd memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm5				// 4th obuf ^= iv; 
	movups	48(ibuf), iv			// 4th memcpy(iv, tmp, AES_BLOCK_SIZE);

	movups	%xmm1, (obuf)			// write 1st obuf
	movups	%xmm2, 16(obuf)			// write 2nd obuf
	movups	%xmm4, 32(obuf)			// write 3rd obuf
	movups	%xmm5, 48(obuf)			// write 4th obuf
#endif

	add		$64, ibuf				// ibuf += 4; 
	add		$64, obuf				// obuf += 4;	

	sub		$4, num_blk				// num_blk -= 4
	jge		0b						// if num_blk > 0, repeat the loop

9:	add		$4, num_blk				// post incremtn num_blk by 4
	je		L_HW_cbc_done			// if num_blk == 0, no need for forthur processing code

#if defined	__i386__
	// updated as they might be needed as expanded keys in the remaining
	movups	144(ctx), %xmm4
	movups	128(ctx), %xmm5
	movups	112(ctx), %xmm6
	movups	96(ctx), %xmm7
#endif

	test	$2, num_blk				// check whether num_blk has 2 blocks
	je		9f						// if num_blk & 2 == 0, skip the per-pair processing code

	// do the remaining 2 blocks together

	movups	(ibuf), %xmm1				// tmp = 1st ibuf
	movups	16(ibuf), %xmm2				// tmp = 2nd ibuf

	// aes_decrypt
	pxor    %xmm3, %xmm1
	pxor    %xmm3, %xmm2
    aesdec  %xmm4, %xmm1
    aesdec  %xmm4, %xmm2
    aesdec  %xmm5, %xmm1
    aesdec  %xmm5, %xmm2
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
#if defined	__x86_64__
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm8, %xmm1
    aesdec  %xmm8, %xmm2
    aesdec  %xmm9, %xmm1
    aesdec  %xmm9, %xmm2
    aesdec  %xmm10, %xmm1
    aesdec  %xmm10, %xmm2
    aesdec  %xmm11, %xmm1
    aesdec  %xmm11, %xmm2
    aesdec  %xmm12, %xmm1
    aesdec  %xmm12, %xmm2
    aesdeclast  %xmm13, %xmm1
    aesdeclast  %xmm13, %xmm2
#else
	movups	80(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
	movups	64(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
	movups	48(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
	movups	32(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
	movups	16(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
	movups	0(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdeclast  %xmm7, %xmm1
    aesdeclast  %xmm7, %xmm2
	movups	112(ctx), %xmm6
	movups	96(ctx), %xmm7
#endif

	pxor	iv, %xmm1				// obuf[0] ^= *iv; 
	movups	(ibuf), iv				// ibuf[0]
	pxor	iv, %xmm2				// obuf[1] ^= ibuf[0]
	movups	16(ibuf), iv			// *iv = ibuf[1]

	movups	%xmm1, (obuf)			// write obuf[0]
	movups	%xmm2, 16(obuf)			// write obuf[1]

	add		$32, ibuf				// ibuf += 2
	add		$32, obuf				// obuf += 2

9:
	test	$1, num_blk				// check whether num_blk has residual 1 block
	je		L_HW_cbc_done			// if num_blk == 0, no need for residual processing code
	
	movups	(ibuf), %xmm2				// tmp = ibuf
	// aes_decrypt
	pxor    %xmm3, %xmm2
    aesdec  %xmm4, %xmm2
    aesdec  %xmm5, %xmm2
    aesdec  %xmm6, %xmm2
    aesdec  %xmm7, %xmm2
#if defined	__x86_64__
    aesdec  %xmm8, %xmm2
    aesdec  %xmm9, %xmm2
    aesdec  %xmm10, %xmm2
    aesdec  %xmm11, %xmm2
    aesdec  %xmm12, %xmm2
    aesdeclast  %xmm13, %xmm2
#else
	movups	80(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	64(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	48(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	32(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	16(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	(ctx), %xmm1
    aesdeclast  %xmm1, %xmm2
#endif

	pxor	iv, %xmm2			// *obuf ^= *iv; 
	movups	(ibuf), iv			// *iv = *ibuf;
	movups	%xmm2, (obuf)		// write *obuf

	jmp		L_HW_cbc_done

	//
	// aes-192 decrypt_cbc operation, after completion, branch to L_HW_cbc_done
	//

L_decrypt_192:

	cmp		$1, num_blk
	jl		L_HW_cbc_done			// if num_blk < 1, early return

	// aes-192 decryp expanded keys
	movups	192(ctx), %xmm3
	movups	176(ctx), %xmm4
	movups	160(ctx), %xmm5
	movups	144(ctx), %xmm6
	movups	128(ctx), %xmm7
#if defined	__x86_64__
	movups	112(ctx), %xmm8
	movups	96(ctx), %xmm9
	movups	80(ctx), %xmm10
	movups	64(ctx), %xmm11
	movups	48(ctx), %xmm12
	movups	32(ctx), %xmm13
	movups	16(ctx), %xmm14
	movups	(ctx), %xmm15
#endif

	// performs 4 block decryption in an iteration to exploit decrypt in parallel

	//		while ((num_blk-=4)>=0) {
	//			aes_decrypt(ibuf, obuf, ctx);
	//			aes_decrypt(ibuf+1, obuf+1, ctx);
	//			aes_decrypt(ibuf+2, obuf+2, ctx);
	//			aes_decrypt(ibuf+3, obuf+3, ctx);
	//			obuf[0] ^= *iv; obuf[1] ^= ibuf[1]; obuf[2] ^= ibuf[1]; obuf[3] ^= ibuf[2];
	//			*iv = ibuf[3]; ibuf += 4; obuf += 4;
	//		}

	sub		$4, num_blk					// pre decrement num_blk by 4
	jl		9f							// if num_blk < 4, skip the per-4-blocks processing code
0:

#if defined	__x86_64__

	movups	(ibuf), %xmm1				// tmp = 1st ibuf
	movups	16(ibuf), %xmm2				// tmp = 2nd ibuf
	movups	32(ibuf), %xmm14			// tmp = 3rd ibuf
	movups	48(ibuf), %xmm15			// tmp = 4th ibuf

	// aes_decrypt, for x86_64, the expanded keys are already stored in xmm3-xmm13
	// use %xmm12/%xmm13 ts dynamic keys in the middle, restored afterwards

	// round 0 for 4 blocks
	pxor    %xmm3, %xmm1
	pxor    %xmm3, %xmm2
	pxor    %xmm3, %xmm14
	pxor    %xmm3, %xmm15

	// round 1 for 4 blocks
    aesdec  %xmm4, %xmm1
    aesdec  %xmm4, %xmm2
    aesdec  %xmm4, %xmm14
    aesdec  %xmm4, %xmm15

	// round 2 for 4 blocks
    aesdec  %xmm5, %xmm1
    aesdec  %xmm5, %xmm2
    aesdec  %xmm5, %xmm14
    aesdec  %xmm5, %xmm15

	// round 3 for 4 blocks
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm14
    aesdec  %xmm6, %xmm15

	// round 4 for 4 blocks
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm14
    aesdec  %xmm7, %xmm15

	// round 5 for 4 blocks
    aesdec  %xmm8, %xmm1
    aesdec  %xmm8, %xmm2
    aesdec  %xmm8, %xmm14
    aesdec  %xmm8, %xmm15

	// round 6 for 4 blocks
    aesdec  %xmm9, %xmm1
    aesdec  %xmm9, %xmm2
    aesdec  %xmm9, %xmm14
    aesdec  %xmm9, %xmm15

	// round 7 for 4 blocks
    aesdec  %xmm10, %xmm1
    aesdec  %xmm10, %xmm2
    aesdec  %xmm10, %xmm14
    aesdec  %xmm10, %xmm15

	// round 8 for 4 blocks
    aesdec  %xmm11, %xmm1
    aesdec  %xmm11, %xmm2
    aesdec  %xmm11, %xmm14
    aesdec  %xmm11, %xmm15

	// round 9 for 4 blocks
    aesdec  %xmm12, %xmm1
    aesdec  %xmm12, %xmm2
    aesdec  %xmm12, %xmm14
    aesdec  %xmm12, %xmm15

	movups	16(ctx), %xmm12

	// round A for 4 blocks
    aesdec  %xmm13, %xmm1
    aesdec  %xmm13, %xmm2
    aesdec  %xmm13, %xmm14
    aesdec  %xmm13, %xmm15

	movups	(ctx), %xmm13

	// round B for 4 blocks
    aesdec  %xmm12, %xmm1
    aesdec  %xmm12, %xmm2
    aesdec  %xmm12, %xmm14
    aesdec  %xmm12, %xmm15

	movups	48(ctx), %xmm12		// restore %xmm12 to its original key

	// round C (last) for 4 blocks
    aesdeclast  %xmm13, %xmm1
    aesdeclast  %xmm13, %xmm2
    aesdeclast  %xmm13, %xmm14
    aesdeclast  %xmm13, %xmm15

	movups	32(ctx), %xmm13		// restore %xmm13 to its original key

	pxor	iv, %xmm1				// obuf[0] ^= *iv; 
	movups	(ibuf), iv				// ibuf[0]
	pxor	iv, %xmm2				// obuf[1] ^= ibuf[0] 
	movups	16(ibuf), iv			// ibuf[1]
	pxor	iv, %xmm14				// obuf[2] ^= ibuf[1] 
	movups	32(ibuf), iv			// ibuf[2] 
	pxor	iv, %xmm15				// obuf[3] ^= ibuf[2] 
	movups	48(ibuf), iv			// *iv = ibuf[3] 

	movups	%xmm1, (obuf)			// write 1st obuf
	movups	%xmm2, 16(obuf)			// write 2nd obuf
	movups	%xmm14, 32(obuf)		// write 3rd obuf
	movups	%xmm15, 48(obuf)		// write 4th obuf

	add		$64, ibuf				// ibuf += 4; 
	add		$64, obuf				// obuf += 4;	

	sub		$4, num_blk				// num_blk -= 4
	jge		0b						// if num_blk > 0, repeat the loop

9:	add		$4, num_blk				// post incremtn num_blk by 4
	je		L_HW_cbc_done			// if num_blk == 0, prepare to return 

	movups	16(ctx), %xmm14			// restore %xmm14 to its key
	movups	(ctx), %xmm15			// restore %xmm15 to its key

#else

	movups	(ibuf), %xmm1			// tmp = 1st ibuf
	movups	16(ibuf), %xmm2			// tmp = 2nd ibuf
	movups	32(ibuf), %xmm4			// tmp = 3rd ibuf
	movups	48(ibuf), %xmm5			// tmp = 4th ibuf

	// aes_decrypt
	// for i386, sequentially load expanded keys into xmm6/xmm7
	movups	176(ctx), %xmm6
	pxor    %xmm3, %xmm1
	pxor    %xmm3, %xmm2
	pxor    %xmm3, %xmm4
	pxor    %xmm3, %xmm5

	movups	160(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	144(ctx), %xmm6
	aesdec    %xmm7, %xmm1
	aesdec    %xmm7, %xmm2
	aesdec    %xmm7, %xmm4
	aesdec    %xmm7, %xmm5

	movups	128(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	112(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	96(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	80(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	64(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	48(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	32(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	16(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	0(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

    aesdeclast  %xmm7, %xmm1
    aesdeclast  %xmm7, %xmm2
    aesdeclast  %xmm7, %xmm4
    aesdeclast  %xmm7, %xmm5

	pxor	iv, %xmm1				// 1st obuf ^= iv; 
	movups	(ibuf), iv				// 1st memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm2				// 2nd obuf ^= iv; 
	movups	16(ibuf), iv			// 2nd memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm4				// 3rd obuf ^= iv; 
	movups	32(ibuf), iv			// 3rd memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm5				// 4th obuf ^= iv; 
	movups	48(ibuf), iv			// 4th memcpy(iv, tmp, AES_BLOCK_SIZE);
	movups	%xmm1, (obuf)			// write 1st obuf
	movups	%xmm2, 16(obuf)			// write 2nd obuf
	movups	%xmm4, 32(obuf)			// write 3rd obuf
	movups	%xmm5, 48(obuf)			// write 4th obuf

	add		$64, ibuf				// ibuf += AES_BLOCK_SIZE * 4; 
	add		$64, obuf				// obuf += AES_BLOCK_SIZE * 4;	

	sub		$4, num_blk				// num_blk -= 4
	jge		0b						// if num_blk > 0, repeat the loop


9:	add		$4, num_blk				//	post incremtn num_blk by 4
	je		L_HW_cbc_done			// if num_blk == 0, no need for forthur processing code

	movups	176(ctx), %xmm4
	movups	160(ctx), %xmm5
	movups	144(ctx), %xmm6
	movups	128(ctx), %xmm7

#endif

	// per-block aes_decrypt_cbc loop

0:
	movups	(ibuf), %xmm2				// tmp = ibuf

	// aes_decrypt
	pxor    %xmm3, %xmm2
    aesdec  %xmm4, %xmm2
    aesdec  %xmm5, %xmm2
    aesdec  %xmm6, %xmm2
    aesdec  %xmm7, %xmm2
#if defined	__x86_64__
    aesdec  %xmm8, %xmm2
    aesdec  %xmm9, %xmm2
    aesdec  %xmm10, %xmm2
    aesdec  %xmm11, %xmm2
    aesdec  %xmm12, %xmm2
    aesdec  %xmm13, %xmm2
    aesdec  %xmm14, %xmm2
    aesdeclast  %xmm15, %xmm2
#else
	movups	112(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	96(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	80(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	64(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	48(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	32(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	16(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	(ctx), %xmm1
    aesdeclast  %xmm1, %xmm2
#endif

	pxor	iv, %xmm2			// obuf ^= iv; 
	movups	(ibuf), iv			// memcpy(iv, tmp, AES_BLOCK_SIZE);

	movups	%xmm2, (obuf)		// write obuf

	add		$16, ibuf				// ibuf += AES_BLOCK_SIZE; 
	add		$16, obuf				// obuf += AES_BLOCK_SIZE;	
	sub		$1, num_blk				// num_blk --
	jg		0b						// if num_blk > 0, repeat the loop

	jmp		L_HW_cbc_done

	//
	// aes-256 decrypt_cbc operation, after completion, branch to L_HW_cbc_done
	//

L_decrypt_256:

	cmp		$1, num_blk
	jl		L_HW_cbc_done	

	movups	224(ctx), %xmm3
	movups	208(ctx), %xmm4
	movups	192(ctx), %xmm5
	movups	176(ctx), %xmm6
	movups	160(ctx), %xmm7
#if defined	__x86_64__
	movups	144(ctx), %xmm8
	movups	128(ctx), %xmm9
	movups	112(ctx), %xmm10
	movups	96(ctx), %xmm11
	movups	80(ctx), %xmm12
	movups	64(ctx), %xmm13
	movups	48(ctx), %xmm14
	movups	32(ctx), %xmm15
//	movups	16(ctx), %xmm14
//	movups	(ctx), %xmm15
#endif

#if defined	__x86_64__

	sub		$4, num_blk					// pre decrement num_blk by 4
	jl		9f							// if num_blk < 4, skip the per-4-blocks processing code
0:
	movups	(ibuf), %xmm1				// tmp = 1st ibuf
	movups	16(ibuf), %xmm2				// tmp = 2nd ibuf
	movups	32(ibuf), %xmm14			// tmp = 3rd ibuf
	movups	48(ibuf), %xmm15			// tmp = 4th ibuf

	// aes_decrypt, for x86_64, the expanded keys are already stored in xmm3-xmm13
	pxor    %xmm3, %xmm1
	pxor    %xmm3, %xmm2
	pxor    %xmm3, %xmm14
	pxor    %xmm3, %xmm15

    aesdec  %xmm4, %xmm1
    aesdec  %xmm4, %xmm2
    aesdec  %xmm4, %xmm14
    aesdec  %xmm4, %xmm15

    aesdec  %xmm5, %xmm1
    aesdec  %xmm5, %xmm2
    aesdec  %xmm5, %xmm14
    aesdec  %xmm5, %xmm15

    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm14
    aesdec  %xmm6, %xmm15

    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm14
    aesdec  %xmm7, %xmm15

    aesdec  %xmm8, %xmm1
    aesdec  %xmm8, %xmm2
    aesdec  %xmm8, %xmm14
    aesdec  %xmm8, %xmm15

    aesdec  %xmm9, %xmm1
    aesdec  %xmm9, %xmm2
    aesdec  %xmm9, %xmm14
    aesdec  %xmm9, %xmm15

    aesdec  %xmm10, %xmm1
    aesdec  %xmm10, %xmm2
    aesdec  %xmm10, %xmm14
    aesdec  %xmm10, %xmm15

    aesdec  %xmm11, %xmm1
    aesdec  %xmm11, %xmm2
    aesdec  %xmm11, %xmm14
    aesdec  %xmm11, %xmm15

    aesdec  %xmm12, %xmm1
    aesdec  %xmm12, %xmm2
    aesdec  %xmm12, %xmm14
    aesdec  %xmm12, %xmm15
	movups	48(ctx), %xmm12

    aesdec  %xmm13, %xmm1
    aesdec  %xmm13, %xmm2
    aesdec  %xmm13, %xmm14
    aesdec  %xmm13, %xmm15
	movups	32(ctx), %xmm13

    aesdec  %xmm12, %xmm1
    aesdec  %xmm12, %xmm2
    aesdec  %xmm12, %xmm14
    aesdec  %xmm12, %xmm15
	movups	16(ctx), %xmm12

    aesdec  %xmm13, %xmm1
    aesdec  %xmm13, %xmm2
    aesdec  %xmm13, %xmm14
    aesdec  %xmm13, %xmm15
	movups	(ctx), %xmm13

    aesdec  %xmm12, %xmm1
    aesdec  %xmm12, %xmm2
    aesdec  %xmm12, %xmm14
    aesdec  %xmm12, %xmm15
	movups	80(ctx), %xmm12

    aesdeclast  %xmm13, %xmm1
    aesdeclast  %xmm13, %xmm2
    aesdeclast  %xmm13, %xmm14
    aesdeclast  %xmm13, %xmm15
	movups	64(ctx), %xmm13

	pxor	iv, %xmm1				// obuf ^= iv; 
	movups	(ibuf), iv				// memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm2				// obuf ^= iv; 
	movups	16(ibuf), iv			// memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm14				// obuf ^= iv; 
	movups	32(ibuf), iv			// memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm15				// obuf ^= iv; 
	movups	48(ibuf), iv			// memcpy(iv, tmp, AES_BLOCK_SIZE);

	movups	%xmm1, (obuf)			// write 1st obuf
	movups	%xmm2, 16(obuf)			// write 2nd obuf
	movups	%xmm14, 32(obuf)		// write 3rd obuf
	movups	%xmm15, 48(obuf)		// write 4th obuf

	add		$64, ibuf				// ibuf += AES_BLOCK_SIZE*4; 
	add		$64, obuf				// obuf += AES_BLOCK_SIZE*4;	

	sub		$4, num_blk				// num_blk -= 4
	jge		0b						// if num_blk > 0, repeat the loop

9:	add		$4, num_blk				//	post incremtn num_blk by 4
	je		L_HW_cbc_done			// if num_blk == 0, no need for forthur processing code

	movups	48(ctx), %xmm14
	movups	32(ctx), %xmm15

#else

	sub		$4, num_blk				// pre decrement num_blk by 4
	jl		9f						// if num_blk < 4, skip the per-pair processing code
0:
	movups	(ibuf), %xmm1			// tmp = 1st ibuf
	movups	16(ibuf), %xmm2			// tmp = 2nd ibuf
	movups	32(ibuf), %xmm4			// tmp = 3rd ibuf
	movups	48(ibuf), %xmm5			// tmp = 4th ibuf

	// aes_decrypt
	// for i386, sequentially load expanded keys into xmm6/xmm7
	movups	208(ctx), %xmm6
	pxor    %xmm3, %xmm1
	pxor    %xmm3, %xmm2
	pxor    %xmm3, %xmm4
	pxor    %xmm3, %xmm5

	movups	192(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	176(ctx), %xmm6
	aesdec  %xmm7, %xmm1
	aesdec	%xmm7, %xmm2
	aesdec	%xmm7, %xmm4
	aesdec	%xmm7, %xmm5

	movups	160(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	144(ctx), %xmm6
	aesdec	%xmm7, %xmm1
	aesdec	%xmm7, %xmm2
	aesdec	%xmm7, %xmm4
	aesdec	%xmm7, %xmm5

	movups	128(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	112(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	96(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	80(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	64(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	48(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	32(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

	movups	16(ctx), %xmm6
    aesdec  %xmm7, %xmm1
    aesdec  %xmm7, %xmm2
    aesdec  %xmm7, %xmm4
    aesdec  %xmm7, %xmm5

	movups	0(ctx), %xmm7
    aesdec  %xmm6, %xmm1
    aesdec  %xmm6, %xmm2
    aesdec  %xmm6, %xmm4
    aesdec  %xmm6, %xmm5

    aesdeclast  %xmm7, %xmm1
    aesdeclast  %xmm7, %xmm2
    aesdeclast  %xmm7, %xmm4
    aesdeclast  %xmm7, %xmm5

	pxor	iv, %xmm1				// 1st obuf ^= iv; 
	movups	(ibuf), iv				// 1st memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm2				// 2nd obuf ^= iv; 
	movups	16(ibuf), iv			// 2nd memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm4				// 3rd obuf ^= iv; 
	movups	32(ibuf), iv			// 3rd memcpy(iv, tmp, AES_BLOCK_SIZE);
	pxor	iv, %xmm5				// 4th obuf ^= iv; 
	movups	48(ibuf), iv			// 4th memcpy(iv, tmp, AES_BLOCK_SIZE);
	movups	%xmm1, (obuf)			// write 1st obuf
	movups	%xmm2, 16(obuf)			// write 2nd obuf
	movups	%xmm4, 32(obuf)			// write 3rd obuf
	movups	%xmm5, 48(obuf)			// write 4th obuf

	add		$64, ibuf				// ibuf += AES_BLOCK_SIZE * 4; 
	add		$64, obuf				// obuf += AES_BLOCK_SIZE * 4;	

	sub		$4, num_blk				// num_blk -= 4
	jge		0b						// if num_blk > 0, repeat the loop


9:	add		$4, num_blk				//	post incremtn num_blk by 4
	je		L_HW_cbc_done			// if num_blk == 0, no need for forthur processing code

	movups	208(ctx), %xmm4
	movups	192(ctx), %xmm5
	movups	176(ctx), %xmm6
	movups	160(ctx), %xmm7

#endif

0:
	movups	(ibuf), %xmm2				// tmp = ibuf

	// aes_decrypt
	pxor	%xmm3, %xmm2
    aesdec  %xmm4, %xmm2
    aesdec  %xmm5, %xmm2
    aesdec  %xmm6, %xmm2
    aesdec  %xmm7, %xmm2
#if defined	__x86_64__
    aesdec  %xmm8, %xmm2
    aesdec  %xmm9, %xmm2
    aesdec  %xmm10, %xmm2
    aesdec  %xmm11, %xmm2
    aesdec  %xmm12, %xmm2
    aesdec  %xmm13, %xmm2
    aesdec  %xmm14, %xmm2
    aesdec  %xmm15, %xmm2
#else
	movups	144(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	128(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	112(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	96(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	80(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	64(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	48(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	32(ctx), %xmm1
    aesdec  %xmm1, %xmm2
#endif
	movups	16(ctx), %xmm1
    aesdec  %xmm1, %xmm2
	movups	(ctx), %xmm1
    aesdeclast  %xmm1, %xmm2

	pxor	iv, %xmm2			// obuf ^= iv; 
	movups	(ibuf), iv			// memcpy(iv, tmp, AES_BLOCK_SIZE);

	movups	%xmm2, (obuf)		// write obuf

	add		$16, ibuf				// ibuf += AES_BLOCK_SIZE; 
	add		$16, obuf				// obuf += AES_BLOCK_SIZE;	
	sub		$1, num_blk				// num_blk --
	jg		0b						// if num_blk > 0, repeat the loop

	jmp		L_HW_cbc_done

	//
	// --------- END of aesedp_decrypt_cbc_hw  -------------------
	//
#endif /* x86 based build */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/aesedp.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*
 *  aesedp.c
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */


#include "tomcrypt.h"
#include "aesedpPriv.h"
#include "aesxts.h"
#include "ccdebug.h"
const struct ltc_cipher_descriptor aesedp_desc =
{
    "aesedp", // Name
    65,       // Internal ID
    16, 32, 16, 10, // Min KeySize, Max Keysize, Block Size, Rounds
    aesedp_setup, aesedp_ecb_encrypt, aesedp_ecb_decrypt, aesedp_test, aesedp_done, aesedp_keysize,
    /* ECB Accelerators */
    NULL, NULL, 
    /* CBC Accelerators */
#if defined (__i386__) || defined (__x86_64__)
    aesedp_cbc_encrypt, aesedp_cbc_decrypt,
#else
    NULL, NULL,
#endif
    /* CTR Accelerator */
    NULL, 
    /* LRW Accelerators */
    NULL, NULL,
#if defined (__i386__) || defined (__x86_64__)
    /* XTS Accelerators */
    aesxts_encrypt, aesxts_decrypt,
#else
    NULL, NULL,
#endif
    /* CCM Accelerator */
    NULL, 
    /* GCM Accelerator */
    NULL, 
    /* OMAC Accelerator */
    NULL,
    /* XCBC Accelerator */
    NULL, 
    /* F9 Accelerator */
    NULL
};


int 
aesedp_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
{
#if defined (__i386__) || defined (__x86_64__)

	aesedp_ctx *ctx = &skey->aesedp;
	int retval;

	if((retval = aesedp_keysize(&keylen)) != CRYPT_OK) return retval;
	
	if((retval = aes_encrypt_key(key, keylen, &ctx->encrypt)) != CRYPT_OK) return CRYPT_ERROR;
	if((retval = aes_decrypt_key(key, keylen, &ctx->decrypt)) != CRYPT_OK) return CRYPT_ERROR;
	return CRYPT_OK;

#else
	return CRYPT_UNIMPLEMENTED;
#endif
}


int 
aesedp_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
{
#if defined (__i386__) || defined (__x86_64__)

	aesedp_ctx *ctx = &skey->aesedp;
	return aes_encrypt(pt, ct, &ctx->encrypt);

#else
	return CRYPT_UNIMPLEMENTED;
#endif
}



int 
aesedp_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
{
#if defined (__i386__) || defined (__x86_64__)

	aesedp_ctx *ctx = &skey->aesedp;
    return aes_decrypt(ct, pt, &ctx->decrypt);

#else
	return CRYPT_UNIMPLEMENTED;
#endif
}



int 
aesedp_test(void)
{
#if defined (__i386__) || defined (__x86_64__)
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
 int err;
 static const struct {
     int keylen;
     unsigned char key[32], pt[16], ct[16];
 } tests[] = {
    { 16,
      { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, 
      { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
        0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },
      { 0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30, 
        0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a }
    }, { 
      24,
      { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 },
      { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
        0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },
      { 0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 
        0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71, 0x91 }
    }, {
      32,
      { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 
        0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f },
      { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
        0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },
      { 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 
        0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 }
    }
 };
 
 symmetric_key key;
 unsigned char tmp[2][16];
 int i, y;
 
 for (i = 0; i < (int)(sizeof(tests)/sizeof(tests[0])); i++) {
    zeromem(&key, sizeof(key));
    if ((err = aesedp_setup(tests[i].key, tests[i].keylen, 0, &key)) != CRYPT_OK) { 
       return err;
    }
  
    aesedp_ecb_encrypt(tests[i].pt, tmp[0], &key);
    aesedp_ecb_decrypt(tmp[0], tmp[1], &key);
    if (XMEMCMP(tmp[0], tests[i].ct, 16) || XMEMCMP(tmp[1], tests[i].pt, 16)) { 
#if 0
       printf("\n\nTest %d failed\n", i);
       if (XMEMCMP(tmp[0], tests[i].ct, 16)) {
          printf("CT: ");
          for (i = 0; i < 16; i++) {
             printf("%02x ", tmp[0][i]);
          }
          printf("\n");
       } else {
          printf("PT: ");
          for (i = 0; i < 16; i++) {
             printf("%02x ", tmp[1][i]);
          }
          printf("\n");
       }
#endif       
        return CRYPT_FAIL_TESTVECTOR;
    }

      /* now see if we can encrypt all zero bytes 1000 times, decrypt and come back where we started */
      for (y = 0; y < 16; y++) tmp[0][y] = 0;
      for (y = 0; y < 1000; y++) aesedp_ecb_encrypt(tmp[0], tmp[0], &key);
      for (y = 0; y < 1000; y++) aesedp_ecb_decrypt(tmp[0], tmp[0], &key);
      for (y = 0; y < 16; y++) if (tmp[0][y] != 0) return CRYPT_FAIL_TESTVECTOR;
 }       
 return CRYPT_OK;
 #endif
#else
	return CRYPT_UNIMPLEMENTED;
#endif

}



void 
aesedp_done(symmetric_key *skey)
{
}


int 
aesedp_cbc_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *iv, symmetric_key *skey)
{
    aesedp_ctx *ctx = &skey->aesedp;
    return aesedp_encrypt_cbc((const unsigned char *) pt, (const unsigned char *) iv, blocks, ct, &ctx->encrypt);
}

int 
aesedp_cbc_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long blocks, unsigned char *iv, symmetric_key *skey)
{
    aesedp_ctx *ctx = &skey->aesedp;
    return aesedp_decrypt_cbc((const unsigned char *) ct, (const unsigned char *) iv, blocks, pt, &ctx->decrypt);
}


int 
aesedp_keysize(int *keysize)
{
#if defined (__i386__) || defined (__x86_64__)
	switch (*keysize) {
		case 16:
		case 24:
		case 32:
			return CRYPT_OK;
		default:
			return CRYPT_INVALID_KEYSIZE;
	}
#else
	return CRYPT_UNIMPLEMENTED;
#endif
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/aesedp.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  aesedp.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#ifndef AESEDP_H_
#define AESEDP_H_
#if defined(__cplusplus)
extern "C"
{
#endif
    
#define KS_LENGTH       60

typedef struct {   
	ulong32 ks[KS_LENGTH];
    ulong32 rn;
} aesedp_encrypt_ctx;

typedef struct {   
	ulong32 ks[KS_LENGTH];
    ulong32 rn;
} aesedp_decrypt_ctx;

typedef struct {   
    aesedp_encrypt_ctx encrypt;
	aesedp_decrypt_ctx decrypt;
} aesedp_ctx;

#if defined(__cplusplus)
}
#endif
#endif /* AESEDP_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/aesedpPriv.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  aesedpPriv.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#ifndef AESEDPPRIV_H_
#define AESEDPPRIV_H_
#if defined(__cplusplus)
extern "C"
{
#endif
    
#include "aesedp.h"
// Assembly level interfaces for basic AES.

int 
aes_encrypt_key(const unsigned char *key, int key_len, aesedp_encrypt_ctx cx[1]);

int 
aes_decrypt_key(const unsigned char *key, int key_len, aesedp_decrypt_ctx cx[1]);

int
aes_encrypt(const unsigned char *Plaintext, unsigned char *Ciphertext, aesedp_encrypt_ctx *ctx);

int
aes_decrypt(const unsigned char *Ciphertext, unsigned char *Plaintext, aesedp_decrypt_ctx *ctx);
    
extern int aesedp_decrypt_cbc(const unsigned char *ibuf, const unsigned char *in_iv, unsigned int num_blk,
                              unsigned char *obuf, const aesedp_encrypt_ctx cx[1]);
extern int aesedp_encrypt_cbc(const unsigned char *ibuf, const unsigned char *in_iv, unsigned int num_blk,
                                       unsigned char *obuf, const aesedp_decrypt_ctx ctx[1]);

// MURF ZZZ REMOVE
void AESEncryptCBC(void *Output, const void *Input,
                   void *ChainBuffer, void *Key, long Blocks, long Rounds);
void AESDecryptCBC(void *Output, const void *Input,
                   void *ChainBuffer, void *Key, long Blocks, long Rounds);
    

#if defined(__cplusplus)
}
#endif

#endif /* AESEDPPRIV_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/aesxts.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include "aesxts.h"
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include "aesedpPriv.h"


/** Start XTS mode
 @param cipher      The index of the cipher to use
 @param key1        The encrypt key
 @param key2        The tweak encrypt key
 @param keylen      The length of the keys (each) in octets
 @param num_rounds  The number of rounds for the cipher (0 == default)
 @param xts         [out] XTS structure
 Returns CRYPT_OK upon success.
 */

uint32_t
aesxts_start(uint32_t cipher, // ignored - we're doing this for xts-aes only
             const uint8_t *IV __unused, // ignored
             const uint8_t *key1, int keylen,
             const uint8_t *key2, int tweaklen __unused, // both keys are the same size for xts
             uint32_t num_rounds, // ignored
             uint32_t options __unused,    // ignored
             symmetric_xts *xts)
{
    uint32_t err;
    
    /* check inputs */
    if((key1 == NULL)|| (key2 == NULL) || (xts == NULL)) return CRYPT_INVALID_ARG;
    
    /* schedule the two ciphers */
    if ((err = aesedp_setup(key1, keylen, num_rounds, &xts->key1)) != 0) {
        return err;
    }
    if ((err = aesedp_setup(key2, keylen, num_rounds, &xts->key2)) != 0) {
        return err;
    }
    xts->cipher = cipher;
    
    return err;
}




/** multiply by x 
 @param I      The value to multiply by x (LFSR shift)
 */
#if defined __x86_64__ || defined __i386__
extern void aesxts_mult_x(uint8_t *I);
#else
static void aesxts_mult_x(uint8_t *I)
{
    uint32_t x;
    uint8_t t, tt;
    
    for (x = t = 0; x < 16; x++) {
        tt   = I[x] >> 7;
        I[x] = ((I[x] << 1) | t) & 0xFF;
        t    = tt;
    }
    if (tt) {
        I[0] ^= 0x87;
    } 
}
#endif

#if defined __x86_64__ || defined __i386__
extern int aesxts_tweak_crypt(const uint8_t *P, uint8_t *C, uint8_t *T, aesedp_encrypt_ctx *ctx);
/* extern */ int aesxts_tweak_crypt_group(const uint8_t *P, uint8_t *C, uint8_t *T, aesedp_encrypt_ctx *ctx, uint32_t lim);
#else
static int aesxts_tweak_crypt(const uint8_t *P, uint8_t *C, uint8_t *T, aesedp_encrypt_ctx *ctx)
{
    uint32_t x;
    uint32_t err;
    
    /* tweak encrypt block i */
    for (x = 0; x < 16; x += sizeof(uint64_t)) {
        *((uint64_t*)&C[x]) = *((uint64_t*)&P[x]) ^ *((uint64_t*)&T[x]);
    }
    
    if ((err = aes_encrypt(C, C, ctx)) != CRYPT_OK) {
        return CRYPT_INVALID_KEYSIZE;
    }
    
    for (x = 0; x < 16; x += sizeof(uint64_t)) {
        *((uint64_t*)&C[x]) ^= *((uint64_t*)&T[x]);
    }
    
    /* LFSR the tweak */
    aesxts_mult_x(T);
    
    return CRYPT_OK;
}   
#endif

/** XTS Encryption
 @param pt     [in]  Plaintext
 @param ptlen  Length of plaintext (and ciphertext)
 @param ct     [out] Ciphertext
 @param tweak  [in] The 128--bit encryption tweak (e.g. sector number)
 @param xts    The XTS structure
 Returns CRYPT_OK upon success
 */

int aesxts_encrypt(
                   const uint8_t *pt, unsigned long ptlen,
                   uint8_t *ct,
                   const uint8_t *tweak,
                   symmetric_xts *xts)
{
    aesedp_ctx *encKS = &xts->key1.aesedp;
    aesedp_ctx *twkKS = &xts->key2.aesedp;
    aesedp_encrypt_ctx *encrypt_ctx = &encKS->encrypt;
    aesedp_encrypt_ctx *tweak_ctx = &twkKS->encrypt;
    uint8_t PP[16], CC[16], T[16];
    uint64_t i, m, mo, lim;
    uint64_t   err;
        
    /* get number of blocks */
    m  = ptlen >> 4;
    mo = ptlen & 15;
  
    /* must have at least one full block */
    if (m == 0) {
        return CRYPT_INVALID_ARG;
    }
    
    /* encrypt the tweak */
    if ((err = aes_encrypt(tweak, T, tweak_ctx)) != 0) {
        return CRYPT_INVALID_KEYSIZE;
    }
   
    /* for i = 0 to m-2 do */
    if (mo == 0) {
        lim = m;
    } else {
        lim = m - 1;
    }
    
    
#if defined __x86_64__ || defined __i386__
    if (lim>0) {
        err = aesxts_tweak_crypt_group(pt, ct, T, encrypt_ctx, lim);
        ct += (lim<<4);
        pt += (lim<<4);
    }
#else
    for (i = 0; i < lim; i++) {
        err = aesxts_tweak_crypt(pt, ct, T, encrypt_ctx);
        ct += 16;
        pt += 16;
    }
#endif
    
    /* if ptlen not divide 16 then */
    if (mo > 0) {
        /* CC = tweak encrypt block m-1 */
        if ((err = aesxts_tweak_crypt(pt, CC, T, encrypt_ctx)) != 0) {
            return err;
        }
        
        /* Cm = first ptlen % 16 bytes of CC */
        for (i = 0; i < mo; i++) {
            PP[i] = pt[16+i];
            ct[16+i] = CC[i];
        }
        
        for (; i < 16; i++) {
            PP[i] = CC[i];
        }
        
        /* Cm-1 = Tweak encrypt PP */
        if ((err = aesxts_tweak_crypt(PP, ct, T, encrypt_ctx)) != 0) {
            return err;
        }
    }
    
    return err;
}

#if defined __x86_64__ || defined __i386__
extern int aesxts_tweak_uncrypt(const uint8_t *C, uint8_t *P, uint8_t *T, aesedp_decrypt_ctx *ctx);
extern int aesxts_tweak_uncrypt_group(const uint8_t *C, uint8_t *P, uint8_t *T, aesedp_decrypt_ctx *ctx, uint32_t lim);
#else
static int aesxts_tweak_uncrypt(const uint8_t *C, uint8_t *P, uint8_t *T, aesedp_decrypt_ctx *ctx)
{
    uint32_t x;
    uint32_t err;
    
    /* tweak encrypt block i */
    for (x = 0; x < 16; x += sizeof(uint64_t)) {
        *((uint64_t*)&P[x]) = *((uint64_t*)&C[x]) ^ *((uint64_t*)&T[x]);
    }
    
    err = aes_decrypt(P, P, ctx);  
    
    for (x = 0; x < 16; x += sizeof(uint64_t)) {
        *((uint64_t*)&P[x]) ^=  *((uint64_t*)&T[x]);
    }
    
    /* LFSR the tweak */
    aesxts_mult_x(T);
    
    return err;
}   
#endif

/** XTS Decryption
 @param ct     [in] Ciphertext
 @param ptlen  Length of plaintext (and ciphertext)
 @param pt     [out]  Plaintext
 @param tweak  [in] The 128--bit encryption tweak (e.g. sector number)
 @param xts    The XTS structure
 Returns CRYPT_OK upon success
 */

int aesxts_decrypt(
                   const uint8_t *ct, unsigned long ptlen,
                   uint8_t *pt,
                   const uint8_t *tweak,
                   symmetric_xts *xts)
{
    aesedp_ctx *encKS = (aesedp_ctx *) &xts->key1;
    aesedp_ctx *twkKS = (aesedp_ctx *) &xts->key2;
    aesedp_encrypt_ctx *decrypt_ctx = &encKS->decrypt;
    uint8_t PP[16], CC[16], T[16];
    uint64_t i, m, mo, lim;
    uint64_t err;
    
    /* check inputs */
    if((pt == NULL) || (ct == NULL)|| (tweak == NULL) || (xts == NULL)) return 1;
    
    /* get number of blocks */
    m  = ptlen >> 4;
    mo = ptlen & 15;
    
    /* must have at least one full block */
    if (m == 0) {
        return CRYPT_INVALID_ARG;
    }
   
    /* encrypt the tweak , yes - encrypt */
    if ((err = aes_encrypt(tweak, T, &twkKS->encrypt)) != 0) {
        return CRYPT_INVALID_KEYSIZE;
    }
    
    /* for i = 0 to m-2 do */
    if (mo == 0) {
        lim = m;
    } else {
        lim = m - 1;
    }
    
#if defined __x86_64__ || defined __i386__
    if (lim>0) {
        err = aesxts_tweak_uncrypt_group(ct, pt, T, decrypt_ctx, lim);
        ct += (lim<<4);
        pt += (lim<<4);
    }
#else
    for (i = 0; i < lim; i++) {
        err = aesxts_tweak_uncrypt(ct, pt, T, decrypt_ctx);
        ct += 16;
        pt += 16;
    }
#endif
    
    /* if ptlen not divide 16 then */
    if (mo > 0) {
        memcpy(CC, T, 16);
        aesxts_mult_x(CC);
        
        /* PP = tweak decrypt block m-1 */
        if ((err = aesxts_tweak_uncrypt(ct, PP, CC, decrypt_ctx)) != CRYPT_OK) {
            return err;
        }
        
        /* Pm = first ptlen % 16 bytes of PP */
        for (i = 0; i < mo; i++) {
            CC[i]    = ct[16+i];
            pt[16+i] = PP[i];
        }
        for (; i < 16; i++) {
            CC[i] = PP[i];
        }
        
        /* Pm-1 = Tweak uncrypt CC */
        if ((err = aesxts_tweak_uncrypt(CC, pt, T, decrypt_ctx)) != CRYPT_OK) {
            return err;
        }
    }
    
    return CRYPT_OK;
}



void aesxts_done(symmetric_xts *xts)
{
    if(xts == NULL) return;
    aesedp_done(&xts->key1);
    aesedp_done(&xts->key2);
}

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/aesxts.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  aesxts.h
 *
 *
 */

#include "stdint.h"
#include "tomcrypt.h"

#ifndef _AESXTS_H
#define _AESXTS_H

#if defined(__cplusplus)
extern "C"
{
#endif

/*
 * The context for XTS-AES
 */

#ifdef NEVER
#define KS_LENGTH       60

typedef struct {   
	uint32_t ks[KS_LENGTH];
	uint32_t rn;
} aesedp_encrypt_ctx;

typedef struct {   
	uint32_t ks[KS_LENGTH];
	uint32_t rn;
} aesedp_decrypt_ctx;

typedef struct {   
	aesedp_decrypt_ctx decrypt;
	aesedp_encrypt_ctx encrypt;
} aesedp_ctx;

// xts mode context

typedef struct {
   aesedp_ctx				key1, key2;
   uint32_t						cipher; // ignore - this is to fit with the library, but in this case we're only using aes
} symmetric_xts;

#endif
    
/*
 * These are the interfaces required for XTS-AES support
 */
 
uint32_t
aesxts_start(uint32_t cipher, // ignored - we're doing this for xts-aes only
						const uint8_t *IV, // ignored
						const uint8_t *key1, int keylen,
						const uint8_t *key2, int tweaklen, // both keys are the same size for xts
						uint32_t num_rounds, // ignored
						uint32_t options,    // ignored
						symmetric_xts *xts);

int aesxts_encrypt(
   const uint8_t *pt, unsigned long ptlen,
         uint8_t *ct,
   const uint8_t *tweak, // this can be considered the sector IV for this use
         symmetric_xts *xts);
		 
int aesxts_decrypt(
   const uint8_t *ct, unsigned long ptlen,
         uint8_t *pt,
   const uint8_t *tweak, // this can be considered the sector IV for this use
         symmetric_xts *xts);


void aesxts_done(symmetric_xts *xts);

#if defined(__cplusplus)
}
#endif

#endif /* _AESXTS_H */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































Deleted Source/libtomcrypt/src/ciphers/aesedpport/aesxts_asm.s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
/*
	This file "aesxts.s" provides x86_64 / i386 optimization of the following functions

	0. xts_mult_x_on_xmm7 : a code macro that is used throughout all other functions
	1. void xts_mult_x(uint8_t *I);
	2. int tweak_crypt(const uint8_t *P, uint8_t *C, uint8_t *T, aesedp_encrypt_ctx *ctx);
	3. int tweak_crypt_group(const uint8_t *P, uint8_t *C, uint8_t *T, aesedp_encrypt_ctx *ctx, uint32_t lim); 
	4. int tweak_uncrypt(const uint8_t *C, uint8_t *P, uint8_t *T, aesedp_decrypt_ctx *ctx);
	5. int tweak_uncrypt_group(const uint8_t *C, uint8_t *P, uint8_t *T, aesedp_decrypt_ctx *ctx, uint32_t lim); 

	This file should be compiled together with xtsClearC.c

	functions 1,2,4 are supposed to replace the C functions in xtsClearC.c for x86_64/i386 architectures
	functions 3,5 are only given here, no C code is available, they are called in xts_encrypt/xts_decrypt (xtsClearC.c)
	  - we can possibly add C code for functions 3 and 5 for future porting to other architectures

	cclee 4-29-10

*/

#if defined __i386__ || defined __x86_64__
#include <System/i386/cpu_capabilities.h>
#define	CRYPT_OK	0		// can not include "crypt.h" in which CRYPT_OK is from enum  

/*
	The following macro is used throughout the functions in this file.
	It is the core function within the function xts_mult_x defined in (xtsClearC.c)

	upon entry, %xmm7 = the input tweak (128-bit), 
	on return, %xmm7 = the updated tweak (128-bit)
	the macro uses %xmm1/%xmm2/%ecx in the computation
	the operation can be described as follows :
	0. let x = %xmm7; 					// 128-bit little-endian input 
	1. x = rotate_left(x,1);			// rotate left by 1 -bit
	2. if (x&1) x ^= 0x0000...0086;		// if least significant bit = 1, least significant byte ^= 0x86;
	3. return x; 

	It's a pity that SSE does not support shifting of the whole 128-bit xmm registers.
	The workaround is 
		1. using parallel dual quad (8-byte) shifting, 1 for the 2 bottom 63-bits, 1 for the 2 leading bits
		2. manipulating the shifted quad words to form the 128-bit shifted result.

	Input : %xmm7
	Output : %xmm7
	Used : %xmm1/%xmm2/%ecx

	The macro is good for both x86_64 and i386. 

*/	

	.macro		xts_mult_x_on_xmm7			// input : x = %xmm7, MS = most significant, LS = least significant
	movaps		%xmm7, %xmm1				// %xmm1 = a copy of x 
	movaps		%xmm7, %xmm2				// %xmm2 = a copy of x
	psllq		$$1, %xmm7					// 1-bit left shift of 2 quad words (x1<<1, x0<<1), zero-filled 
	psrlq		$$63, %xmm1					// 2 leading bits, each in the least significant bit of a quad word 
	psrad		$$31, %xmm2					// the MS 32-bit will be either 0 or -1, depending on the MS bit of x
	pshufd		$$0xc6, %xmm1, %xmm1		// switch the positions of the 2 leading bits
	pshufd		$$0x03, %xmm2, %xmm2		// the LS 32-bit will be either 0 or -1, depending on the MS bit of x
	por			%xmm1, %xmm7				// we finally has %xmm7 = rotate_left(x,1);
	movl		$$0x86, %ecx				// a potential byte to xor the bottom byte
	movd		%ecx, %xmm1					// copy it to %xmm1, the other is 0
	pand		%xmm2, %xmm1				// %xmm1 = 0 or 0x86, depending on the MS bit of x
	pxor		%xmm1, %xmm7				// rotate_left(x,1) ^= 0 or 0x86 depending on the MS bit of x
	.endm


/* 
	function : void xts_mult_x(uint8_t *I);

	1. load (__m128*) (I) into xmm7
	2. macro xts_mult_x_on_xmm7 (i/o @ xmm7, used xmm1/xmm2/ecx) 
	3. save output (%xmm7) to memory pointed by I

	input : 16-byte memory pointed by I
	output : same 16-byte memory pointed by I

	if kernel code, xmm1/xmm2/xmm7 saved and restored
	other used registers : eax/ecx

 */	
	.text
	.align  4,0x90
	.globl	_aesxts_mult_x
_aesxts_mult_x:

#if defined __x86_64__
	#define	I 	%rdi						// 1st argument at %rdi for x86_64
	#define	sp	%rsp
#else
	mov		4(%esp), %eax					// 1st argument at stack, offset 4 for ret_addr for i386
	#define	I	%eax
	#define	sp	%esp
#endif	

	// if KERNEL code, allocate memory and save xmm1/xmm2/xmm7
#ifdef	KERNEL
#if defined __x86_64__
	sub		$0x38, sp						// 8-bytes alignment + 3 * 16 bytes	
#else
	sub		$0x3c, sp						// 12-bytes alignment + 3 * 16 bytes 
#endif
	movaps	%xmm1, (sp)
	movaps	%xmm2, 16(sp)
	movaps	%xmm7, 32(sp)
#endif

	// load, compute, and save
	movups	(I), %xmm7						// load input tweak 128-bit into %xmm7
	xts_mult_x_on_xmm7						// the macro (also used else where) will update %xmm7 as the output
	movups	%xmm7, (I)						// save the xts_mult_x output 

	// if KERNEL code, restore xmm1/xmm2/xmm7 and deallocate stack memory
#ifdef	KERNEL
	movaps	(sp), %xmm1
	movaps	16(sp), %xmm2
	movaps	32(sp), %xmm7
#if defined __x86_64__
	add		$0x38, sp						// 8-bytes alignment + 3 * 16 bytes	
#else
	add		$0x3c, sp						// 12-bytes alignment + 3 * 16 bytes	
#endif
#endif

	ret										// return

	#undef	I
	#undef	sp

/* 
	The following is x86_64/i386 assembly implementation of 

	int tweak_crypt(const uint8_t *P, uint8_t *C, uint8_t *T, aesedp_encrypt_ctx *ctx);

	Its C code implementation is given in xtsClearC.c

	all pointers P/C/T points to a block of 16 bytes. In the following description, P/C/T represent 128-bit data.

	The operation of tweak_crypt

	1. C = P ^ T
	2. err = aes_encryp(C, C, ctx); if (err != CRYPT_OK) return err;
	3. C = C ^ T
	4. xts_mult_x(T)
	5. return CRYPT_OK;

	The following is the assembly implementation flow

	1. save used xmm registers (xmm1/xmm7) if kernel code 
	2. load xmm1 = P, xmm7 = T
	3. xmm1 = C = P ^ T
	4. write xmm1 to C
	5. call aes_encryp(C,C,ctx); note that it will use aesni if available, also xmm will return intact
	6. load xmm1 = C
	7. xmm1 = C = C^T = xmm1 ^ xmm7
	8. write xmm1 to C
	9. update T (in xmm7) via xts_mult_x macro
	a. restore xmm registers (xmm1/xmm7) if kernel code
	b. return CRYPT_OK (in eax) 

	Note: used xmm registers : xmm1/xmm2/xmm7, xmm2 in xts_mult_x macro

*/

	.text
	.align  4,0x90
	.globl	_aesxts_tweak_crypt
_aesxts_tweak_crypt:
#if defined	__i386__

	// push into stack for local use
	push	%ebp
	mov		%esp, %ebp
	push	%ebx
	push	%edi
	push	%esi

	// alllocate stack memory for local use
	sub		$12+16*4, %esp				// 12 (alignment) + 3*16 (xmm save/restore) + 16 (aes_crypt calling arguments)

	// load with called arguments
	mov		8(%ebp), %eax				// P, we need this only briefly, so eax is fine
	mov		12(%ebp), %edi				// C
	mov		16(%ebp), %ebx				// T
	mov		20(%ebp), %esi				// ctx

	#define	P	%eax
	#define	C	%edi
	#define	T	%ebx
	#define	ctx	%esi
	#define	sp	%esp

#else
	// x86_64 calling argument order : rdi/rsi/rdx/rcx/r8

	// push into stack for local use
	push	%rbp
	mov		%rsp, %rbp
	push	%r12
	push	%r13
	push	%r14
	push	%r15

	// alllocate stack memory for local use, if kernel code, need to save/restore xmm registers
#ifdef KERNEL
	sub		$4*16, %rsp					// only need 3*16, add 16 extra so to make save/restore xmm common to i386
#endif

	// load with called arguments, release rdi/rsi/rdx/rcx/r8, as need to call aes_encrypt
	mov		%rsi, %r13
	mov		%rdx, %r14
	mov		%rcx, %r15

	#define	P 	%rdi
	#define	C	%r13
	#define	T	%r14
	#define	ctx	%r15
	#define	sp	%rsp

#endif

	// if kernel, save used xmm registers
#ifdef	KERNEL
	movaps	%xmm1, 16(sp)
	movaps	%xmm2, 32(sp)
	movaps	%xmm7, 48(sp)
#endif

	movups	(P), %xmm1					// P
	movups	(T), %xmm7					// T

	// setup caliing arguments for aes_encrypt
#if defined	__i386__
	mov		C, (%esp)					// C
	mov		C, 4(%esp)					// C
	mov		ctx, 8(%esp)				// ctx
#else
	mov		C, %rdi						// C
	mov		C, %rsi						// C
	mov		ctx, %rdx					// ctx
#endif

	pxor	%xmm7, %xmm1				// C = P ^ T	
	movups	%xmm1, (C)					// save C into memory

	call	_aes_encrypt				// err = aes_encrypt(C,C,ctx);

	cmp		$CRYPT_OK, %eax				// check err == CRYPT_OK
	jne		9f							// if err != CRYPT_OK, exit

	movups	(C), %xmm1					// load xmm1 = C
	pxor	%xmm7, %xmm1				// C ^= T
	movups	%xmm1, (C)					// write C with xmm1, xmm1 is freed now, will be changed in the following macro

	xts_mult_x_on_xmm7					// update T (on xmm7)

	movups	%xmm7, (T)					// write xmm7 to T
9:

	// restore used xmm registers if this is for kernel
#ifdef	KERNEL
	movaps	16(sp), %xmm1
	movaps	32(sp), %xmm2
	movaps	48(sp), %xmm7
#endif

	// free stack memory and restore callee registers
#if defined	__i386__
	add		$12+16*4, %esp				// 12 (alignment) + 3*16 (xmm save/restore) + 16 (aes_crypt calling arguments)
	pop		%esi
	pop		%edi
	pop		%ebx
#else
#ifdef	KERNEL
	add		$4*16, %rsp					// only need 3*16, add 16 extra so make save/restore xmm common to i386
#endif
	pop		%r15
	pop		%r14
	pop		%r13
	pop		%r12
#endif

	// return, eax/rax already has the return val
	leave
	ret

	#undef	P
	#undef	C
	#undef	T
	#undef	ctx
	#undef	sp

/* 
	The following is x86_64/i386 assembly implementation of 

	int tweak_crypt_group(const uint8_t *P, uint8_t *C, uint8_t *T, aesedp_encrypt_ctx *ctx, uint32_t lim);

	TODO : Its C code implementation is YET to be provided in xtsClearC.c (for the benefit of porting to other ISAs)
	This function is grouped version of the above function tweak_crypt(), so xmm registers save/restore only need
	to happen once for all grouped blocks.

	The implementation here probes __cpu_capabilities to detect whether aesni (or hw-aes instruction) is available.
	If aesni is available, the code branch to optimized code that uses aesni.

	The optimized aesni code operates as follows:

	while (more than 4 consecutive blocks available) {

		do xts_mult_x macro 4 times and write the 4 tweaks on stack (16-byte aligned)
	
		perform 4 C = P ^ T;	// T is on 16-byte aligned stack

		perform 4 aes_encrypt (all aes_encrypt instruction interleaved to achieve better throughtput)

		perform 4 C = C ^ T		// T is on 16-byte aligned stack

	}

	The code then falls through to the scalar code, that sequentially performs what tweak_crypt does

	1. C = P ^ T
	2. err = aes_encryp(C, C, ctx); if (err != CRYPT_OK) return err;
	3. C = C ^ T
	4. xts_mult_x(T)

	Note: used xmm registers : 
			xmm0-xmm5, xmm7 if aesni is available
			xmm0-xmm4, xmm7 if aesni is not available.

*/


    .text
	.align  4,0x90
	.globl	_aesxts_tweak_crypt_group
_aesxts_tweak_crypt_group:

#if defined	__i386__

	// push callee-saved registers for local use
	push	%ebp
	mov		%esp, %ebp
	push	%ebx
	push	%edi
	push	%esi

	// allocate stack memory for local use and/or xmm register save for kernel code
	sub		$(12+8*16+16*4), %esp		// 12 (alignment) + 8*16 (xmm) + 4*16 (pre-computed tweaks) aesni
										// 12 (alignment) + 8*16 (xmm) + 4*16 (only 12 used for aes_encrypt) no aesni 
	// transfer calling arguments
	mov		20(%ebp), %eax				// ctx
	mov		12(%ebp), %edi				// C
	mov		16(%ebp), %ebx				// T
	mov		8(%ebp), %esi				// P
	mov		%eax, 8(%esp)				// ctx as the 3rd parameter to aes_decrypt

	#define	P	%esi
	#define	C	%edi
	#define	T	%ebx
	#define	lim	24(%ebp)
	#define	sp	%esp

#else

	// push callee-saved registers for local use
	push	%rbp
	mov		%rsp, %rbp
	push	%rbx
	push	%r12
	push	%r13
	push	%r14
	push	%r15

	// allocate stack memory for local use and/or xmm register save for kernel code
	sub		$(8+8*16+16*5), %rsp		// 8 (alignment) + 8*16 (xmm) + 4*16 (pre-computed tweaks) + 16 (common to i386)

	// rdi/rsi/rdx/rcx/r8
	// transfer calling arguments
	mov		%rdi, %r12	
	mov		%rsi, %r13
	mov		%rdx, %r14
	mov		%rcx, %r15
	mov		%r8,  %rbx

	#define	P 	%r12
	#define	C	%r13
	#define	T	%r14
	#define	ctx	%r15
	#define	lim	%ebx
	#define	sp	%rsp
#endif

#ifdef	KERNEL
	movaps	%xmm0, 0x50(sp)
	movaps	%xmm1, 0x60(sp)
	movaps	%xmm2, 0x70(sp)
	movaps	%xmm3, 0x80(sp)
	movaps	%xmm4, 0x90(sp)
	movaps	%xmm7, 0xa0(sp)
#endif

	// probe __cpu_capabilities to detect aesni
#if defined __x86_64__
    movq    __cpu_capabilities@GOTPCREL(%rip), %rax         // %rax -> __cpu_capabilities
    mov     (%rax), %eax                                    // %eax = __cpu_capabilities
#else		// i386
#if defined KERNEL
    leal    __cpu_capabilities, %eax                        // %eax -> __cpu_capabilities
    mov     (%eax), %eax                                    // %eax = __cpu_capabilities
#else
    mov     _COMM_PAGE_CPU_CAPABILITIES, %eax
#endif
#endif
	test    $(kHasAES), %eax
	je		L_crypt_group_sw								// if aesni not available, jump to sw-based implementation

	// aesni-based implementation

	sub		$4, lim											// pre-decrement lim by 4
	jl		9f												// if lim < 4, skip the following code

	movups	(T), %xmm7										// xmm7 is the tweak before encrypting every 4 blocks	
#ifdef	KERNEL
	movaps	%xmm5, 0xb0(sp)									// hw-aes-based uses extra xmm5
#endif

0:
	// derive 4 tweaks using xts_mult_x macro, and save on aligned stack space
	// xmm7 will be the tweak for next 4-blocks iteration

	#define	tweak1	16(sp)
	#define	tweak2	32(sp)
	#define	tweak3	48(sp)
	#define	tweak4	64(sp)

	movaps	%xmm7, tweak1									// save 1st tweak on stack
	xts_mult_x_on_xmm7										// compute 2nd tweak
	movaps	%xmm7, tweak2									// save 2nd tweak on stack
	xts_mult_x_on_xmm7										// compute 3rd tweak
	movaps	%xmm7, tweak3									// save 3rd tweak on stack
	xts_mult_x_on_xmm7										// compute 4th tweak
	movaps	%xmm7, tweak4									// save 4th tweak on stack
	xts_mult_x_on_xmm7										// compute 1st tweak for next iteration

	// read 4 Ps
	movups	(P), %xmm0
	movups	16(P), %xmm1
	movups	32(P), %xmm2
	movups	48(P), %xmm3

	// 4 C = P ^ T
	pxor	tweak1, %xmm0
	pxor	tweak2, %xmm1
	pxor	tweak3, %xmm2
	pxor	tweak4, %xmm3

	// 4 interleaved aes_encrypt

#if defined	__i386__
	mov		8(sp), %ecx	// ctx
	#undef	ctx
	#define	ctx	%ecx
#endif

	mov		240(ctx), %eax					// aes length 

	cmp		$160, %eax						// AES-128 ?
	je		160f
	cmp		$192, %eax						// AES-192 ?
	je		192f
	cmp		$224, %eax						// AES-256 ?
	je		224f
	mov		$-1, %eax						// error : non-supported aes length
#ifdef	KERNEL
	movaps	0xb0(sp), %xmm5					// hw-aes-based uses extra xmm5
#endif
	jmp		L_error_crypt

	// definitions, macros, and constructs for 4 blocks hw-aes-encrypt

	// the following key definitions will also be used in tweak_uncrypt_group 
	#define	key0			0(ctx)
	#define	key1			16(ctx)
	#define	key2			32(ctx)
	#define	key3			48(ctx)
	#define	key4			64(ctx)
	#define	key5			80(ctx)
	#define	key6			96(ctx)
	#define	key7			112(ctx)
	#define	key8			128(ctx)
	#define	key9			144(ctx)
	#define	keyA			160(ctx)
	#define	keyB			176(ctx)
	#define	keyC			192(ctx)
	#define	keyD			208(ctx)
	#define	keyE			224(ctx)

	#define	aes		aesenc
	#define	aeslast	aesenclast

	// all aes encrypt operations start with the following sequence
	.macro	aes_common_part
	movups	key0, %xmm4
	movups	key1, %xmm5
	pxor	%xmm4, %xmm0
	pxor	%xmm4, %xmm1
	pxor	%xmm4, %xmm2
	pxor	%xmm4, %xmm3
	movups	key2, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	key3, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	key4, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	key5, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	key6, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	key7, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	key8, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	key9, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	keyA, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	.endm

	// all aes encypt operations end with the following 4 instructions	
	.macro	aes_last
	aeslast	%xmm4, %xmm0
	aeslast	%xmm4, %xmm1
	aeslast	%xmm4, %xmm2
	aeslast	%xmm4, %xmm3
	.endm

	.macro	aes_128
	aes_common_part			// encrypt common part
	aes_last				// encrypt ending part
	.endm
	
	.macro	aes_192
	aes_common_part			// encrypt common part

	// 10 extra instructions in between common and ending
	movups	keyB, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	keyC, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3

	aes_last				// encrypt ending part
	.endm

	.macro	aes_256
	aes_common_part			// encrypt common part

	// 20 extra instructions in between common and ending
	movups	keyB, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	keyC, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	keyD, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	keyE, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3

	aes_last				// encrypt ending part
	.endm

160:	// AES-128 encrypt
	aes_128
	jmp		8f

192:	// AES-192 encrypt
	aes_192
	jmp		8f

224:	// AES-256 encrypt	
	aes_256

8:	

	// 4 C = C ^ T
	pxor	tweak1, %xmm0
	pxor	tweak2, %xmm1
	pxor	tweak3, %xmm2
	pxor	tweak4, %xmm3

	// write 4 Cs
	movups	%xmm0, (C)
	movups	%xmm1, 16(C)
	movups	%xmm2, 32(C)
	movups	%xmm3, 48(C)

	add	$64, P
	add	$64, C

	sub		$4, lim
	jge		0b

#ifdef	KERNEL
	movaps	0xb0(sp), %xmm5				// hw-aes-based uses extra xmm5
#endif
	movups	%xmm7, (T)

9:
	xor		%eax, %eax					// to return CRYPT_OK
	add		$4, lim						// post-increment lim by 4
	je		9f							// if lim==0, branch to prepare to return	

L_crypt_group_sw:

	movups	(T), %xmm7					// T, xmm7 will be used as T (128-bit) throughtout the loop

	sub		$1, lim						// pre-decrement lim by 1	
	jl		1f							// if lim < 1, branch to prepare to return
0:
	movups	(P), %xmm0					// P

	// prepare for calling aes_encrypt
#if defined	__i386__
	mov		C, (%esp)					// C
	mov		C, 4(%esp)					// C
										// ctx was prepared previously in preamble
#else
	mov		C, %rdi						// C
	mov		C, %rsi						// C
	mov		ctx, %rdx					// ctx
#endif

	pxor	%xmm7, %xmm0				// C = P ^ T	
	movups	%xmm0, (C)					// save C into memory

	call	_aes_encrypt_xmm_no_save	// err = aes_encrypt(C,C,ctx);

	cmp		$CRYPT_OK, %eax				// err == CRYPT_OK ? 
	jne		9f							// if err != CRYPT_OK, branch to exit with error

	movups	(C), %xmm0					// load xmm0 with C
	pxor	%xmm7, %xmm0				// C ^= T
	movups	%xmm0, (C)					// save output C

	xts_mult_x_on_xmm7

	add		$16, C						// next C
	add		$16, P						// next P
	sub		$1, lim						// lim--
	jge		0b							// if (lim>0) repeat the scalar loop

1:	movups	%xmm7, (T)					// save final tweak 
L_error_crypt:
9:
	// if kernel, restore used xmm registers
#ifdef	KERNEL
	movaps	0x50(sp), %xmm0
	movaps	0x60(sp), %xmm1
	movaps	0x70(sp), %xmm2
	movaps	0x80(sp), %xmm3
	movaps	0x90(sp), %xmm4
	movaps	0xa0(sp), %xmm7
#endif

#if defined	__i386__
	add		$(12+16*8+16*4), %esp
	pop		%esi
	pop		%edi
	pop		%ebx
#else
	add		$(8+16*8+16*5), %rsp
	pop		%r15
	pop		%r14
	pop		%r13
	pop		%r12
	pop		%rbx
#endif
	leave
	ret

	#undef	P
	#undef	C
	#undef	T
	#undef	ctx
	#undef	sp

/* 
	The following is x86_64/i386 assembly implementation of 

	int tweak_uncrypt(const uint8_t *C, uint8_t *P, uint8_t *T, aesedp_decrypt_ctx *ctx);

	Its C code implementation is given in xtsClearC.c

	all pointers C/P/T points to a block of 16 bytes. In the following description, C/P/T represent 128-bit data.

	The operation of tweak_crypt

	1. P = C ^ T
	2. err = aes_decryp(P, P, ctx); if (err != CRYPT_OK) return err;
	3. P = P ^ T
	4. xts_mult_x(T)
	5. return CRYPT_OK;

	The following is the assembly implementation flow

	1. save used xmm registers (xmm1/xmm7) if kernel code 
	2. load xmm1 = C, xmm7 = T
	3. xmm1 = P = C ^ T
	4. write xmm1 to P
	5. call aes_decryp(P,P,ctx); note that it will use aesni if available, also xmm will return intact
	6. load xmm1 = P
	7. xmm1 = P = P^T = xmm1 ^ xmm7
	8. write xmm1 to P
	9. update T (in xmm7) via xts_mult_x macro
	a. restore xmm registers (xmm1/xmm7) if kernel code
	b. return CRYPT_OK (in eax) 

	Note: used xmm registers : xmm1/xmm2/xmm7, xmm2 in xts_mult_x macro

*/

	.text
	.align  4,0x90
	.globl	_aesxts_tweak_uncrypt
_aesxts_tweak_uncrypt:
#if defined	__i386__

	// push into stack for local use
	push	%ebp
	mov		%esp, %ebp
	push	%ebx
	push	%edi
	push	%esi

	// alllocate stack memory for local use
	sub		$12+16*4, %esp				// 12 (alignment) + 3*16 (xmm save/restore) + 16 (aes_crypt calling arguments)

	// load with called arguments
	mov		8(%ebp), %eax				// C, we need this only briefly, so eax is fine
	mov		12(%ebp), %edi				// P
	mov		16(%ebp), %ebx				// T
	mov		20(%ebp), %esi				// ctx

	#define	C	%eax
	#define	P	%edi
	#define	T	%ebx
	#define	ctx	%esi
	#define	sp	%esp

#else
	// x86_64 calling argument order : rdi/rsi/rdx/rcx/r8

	// push into stack for local use
	push	%rbp
	mov		%rsp, %rbp
	push	%r12
	push	%r13
	push	%r14
	push	%r15

	// alllocate stack memory for local use, if kernel code, need to save/restore xmm registers
#ifdef KERNEL
	sub		$4*16, %rsp					// only need 3*16, add 16 extra so to make save/restore xmm common to i386
#endif

	// load with called arguments, release rdi/rsi/rdx/rcx/r8, as need to call aes_decrypt
	mov		%rsi, %r13
	mov		%rdx, %r14
	mov		%rcx, %r15

	#define	C 	%rdi
	#define	P	%r13
	#define	T	%r14
	#define	ctx	%r15
	#define	sp	%rsp

#endif

	// if kernel, save used xmm registers
#ifdef	KERNEL
	movaps	%xmm1, 16(sp)
	movaps	%xmm2, 32(sp)
	movaps	%xmm7, 48(sp)
#endif

	movups	(C), %xmm1					// C
	movups	(T), %xmm7					// T

	// setup caliing arguments for aes_decrypt
#if defined	__i386__
	mov		P, (%esp)					// P
	mov		P, 4(%esp)					// P
	mov		ctx, 8(%esp)				// ctx
#else
	mov		P, %rdi						// P
	mov		P, %rsi						// P
	mov		ctx, %rdx					// ctx
#endif

	pxor	%xmm7, %xmm1				// P = C ^ T	
	movups	%xmm1, (P)					// save P into memory

	call	_aes_decrypt				// err = aes_decrypt(P,P,ctx);

	cmp		$CRYPT_OK, %eax				// check err == CRYPT_OK
	jne		9f							// if err != CRYPT_OK, exit

	movups	(P), %xmm1					// load xmm1 = P
	pxor	%xmm7, %xmm1				// P ^= T
	movups	%xmm1, (P)					// write P with xmm1, xmm1 is freed now, will be changed in the following macro

	xts_mult_x_on_xmm7					// update T (on xmm7)

	movups	%xmm7, (T)					// write xmm7 to T
9:

	// restore used xmm registers if this is for kernel
#ifdef	KERNEL
	movaps	16(sp), %xmm1
	movaps	32(sp), %xmm2
	movaps	48(sp), %xmm7
#endif

	// free stack memory and restore callee registers
#if defined	__i386__
	add		$12+16*4, %esp				// 12 (alignment) + 3*16 (xmm save/restore) + 16 (aes_crypt calling arguments)
	pop		%esi
	pop		%edi
	pop		%ebx
#else
#ifdef	KERNEL
	add		$4*16, %rsp					// only need 3*16, add 16 extra so make save/restore xmm common to i386
#endif
	pop		%r15
	pop		%r14
	pop		%r13
	pop		%r12
#endif

	// return, eax/rax already has the return val
	leave
	ret

	#undef	P
	#undef	C
	#undef	T
	#undef	ctx
	#undef	sp

/* 
	The following is x86_64/i386 assembly implementation of 

	int tweak_uncrypt_group(const uint8_t *C, uint8_t *P, uint8_t *T, aesedp_decrypt_ctx *ctx, uint32_t lim);

	TODO : Its C code implementation is YET to be provided in xtsClearC.c (for the benefit of porting to other ISAs)
	This function is grouped version of the above function tweak_uncrypt(), so xmm registers save/restore only need
	to happen once for all grouped blocks.

	The implementation here probes __cpu_capabilities to detect whether aesni (or hw-aes instruction) is available.
	If aesni is available, the code branch to optimized code that uses aesni.

	The optimized aesni code operates as follows:

	while (more than 4 consecutive blocks available) {

		do xts_mult_x macro 4 times and write the 4 tweaks on stack (16-byte aligned)
	
		perform 4 P = C ^ T;	// T is on 16-byte aligned stack

		perform 4 aes_decrypt (all aes_decrypt instruction interleaved to achieve better throughtput)

		perform 4 P = P ^ T		// T is on 16-byte aligned stack

	}

	The code then falls through to the scalar code, that sequentially performs what tweak_crypt does

	1. P = C ^ T
	2. err = aes_decryp(P, P, ctx); if (err != CRYPT_OK) return err;
	3. P = P ^ T
	4. xts_mult_x(T)

	Note: used xmm registers : 
			xmm0-xmm5, xmm7 if aesni is available
			xmm0-xmm4, xmm7 if aesni is not available.

*/


    .text
	.align  4,0x90
	.globl	_aesxts_tweak_uncrypt_group
_aesxts_tweak_uncrypt_group:

#if defined	__i386__

	// push callee-saved registers for local use
	push	%ebp
	mov		%esp, %ebp
	push	%ebx
	push	%edi
	push	%esi

	// allocate stack memory for local use and/or xmm register save for kernel code
	sub		$(12+8*16+16*4), %esp		// 12 (alignment) + 8*16 (xmm) + 4*16 (pre-computed tweaks) aesni
										// 12 (alignment) + 8*16 (xmm) + 4*16 (only 12 used for aes_decrypt) no aesni 
	// transfer calling arguments
	mov		20(%ebp), %eax				// ctx
	mov		12(%ebp), %edi				// P
	mov		16(%ebp), %ebx				// T
	mov		8(%ebp), %esi				// C
	mov		%eax, 8(%esp)				// ctx as the 3rd parameter to aes_decrypt

	#define	C	%esi
	#define	P	%edi
	#define	T	%ebx
	#define	lim	24(%ebp)
	#define	sp	%esp

#else

	// push callee-saved registers for local use
	push	%rbp
	mov		%rsp, %rbp
	push	%rbx
	push	%r12
	push	%r13
	push	%r14
	push	%r15

	// allocate stack memory for local use and/or xmm register save for kernel code
	sub		$(8+8*16+16*5), %rsp		// 8 (alignment) + 8*16 (xmm) + 4*16 (pre-computed tweaks) + 16 (common to i386)

	// rdi/rsi/rdx/rcx/r8
	// transfer calling arguments
	mov		%rdi, %r12	
	mov		%rsi, %r13
	mov		%rdx, %r14
	mov		%rcx, %r15
	mov		%r8,  %rbx

	#define	C 	%r12
	#define	P	%r13
	#define	T	%r14
	#define	ctx	%r15
	#define	lim	%ebx
	#define	sp	%rsp
#endif

#ifdef	KERNEL
	movaps	%xmm0, 0x50(sp)
	movaps	%xmm1, 0x60(sp)
	movaps	%xmm2, 0x70(sp)
	movaps	%xmm3, 0x80(sp)
	movaps	%xmm4, 0x90(sp)
	movaps	%xmm7, 0xa0(sp)
#endif

	// probe __cpu_capabilities to detect aesni
#if defined __x86_64__
    movq    __cpu_capabilities@GOTPCREL(%rip), %rax         // %rax -> __cpu_capabilities
    mov     (%rax), %eax                                    // %eax = __cpu_capabilities
#else		// i386
#if defined KERNEL
    leal    __cpu_capabilities, %eax                        // %eax -> __cpu_capabilities
    mov     (%eax), %eax                                    // %eax = __cpu_capabilities
#else
    movl     _COMM_PAGE_CPU_CAPABILITIES, %eax
#endif
#endif
	test    $(kHasAES), %eax
	je		L_uncrypt_group_sw								// if aesni not available, jump to sw-based implementation

	// aesni-based implementation

	sub		$4, lim											// pre-decrement lim by 4
	jl		9f												// if lim < 4, skip the following code

	movups	(T), %xmm7										// xmm7 is the tweak before decrypting every 4 blocks	
#ifdef	KERNEL
	movaps	%xmm5, 0xb0(sp)									// hw-aes-based uses extra xmm5
#endif

0:
	// derive 4 tweaks using xts_mult_x macro, and save on aligned stack space
	// xmm7 will be the tweak for next 4-blocks iteration

	#define	tweak1	16(sp)
	#define	tweak2	32(sp)
	#define	tweak3	48(sp)
	#define	tweak4	64(sp)

	movaps	%xmm7, tweak1									// save 1st tweak on stack
	xts_mult_x_on_xmm7										// compute 2nd tweak
	movaps	%xmm7, tweak2									// save 2nd tweak on stack
	xts_mult_x_on_xmm7										// compute 3rd tweak
	movaps	%xmm7, tweak3									// save 3rd tweak on stack
	xts_mult_x_on_xmm7										// compute 4th tweak
	movaps	%xmm7, tweak4									// save 4th tweak on stack
	xts_mult_x_on_xmm7										// compute 1st tweak for next iteration

	// read 4 Cs
	movups	(C), %xmm0
	movups	16(C), %xmm1
	movups	32(C), %xmm2
	movups	48(C), %xmm3

	// 4 P = C ^ T
	pxor	tweak1, %xmm0
	pxor	tweak2, %xmm1
	pxor	tweak3, %xmm2
	pxor	tweak4, %xmm3

	// 4 interleaved aes_decrypt

#if defined	__i386__
	mov		8(sp), %ecx	// ctx
	#undef	ctx
	#define	ctx	%ecx
#endif

	mov		240(ctx), %eax					// aes length 

	cmp		$160, %eax						// AES-128 ?
	je		160f
	cmp		$192, %eax						// AES-192 ?
	je		192f
	cmp		$224, %eax						// AES-256 ?
	je		224f
	mov		$-1, %eax						// error : non-supported aes length
#ifdef	KERNEL
	movaps	0xb0(sp), %xmm5					// hw-aes-based uses extra xmm5
#endif
	jmp		L_error_uncrypt

	// definitions, macros to construc hw-aes-decrypt
	// will reuse previously defined key0 = (ctx), key1 = 16(ctx), ....
	#undef	aes
	#undef	aeslast
	#define aes	aesdec
	#define	aeslast aesdeclast

	.macro	aes_decrypt_common
	movups	key8, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	key7, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	key6, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	key5, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	key4, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	key3, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	key2, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	key1, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	key0, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	aeslast	%xmm4, %xmm0
	aeslast	%xmm4, %xmm1
	aeslast	%xmm4, %xmm2
	aeslast	%xmm4, %xmm3
	.endm

	.macro	aes_dec_128
	movups	keyA, %xmm4
	movups	key9, %xmm5
	pxor	%xmm4, %xmm0
	pxor	%xmm4, %xmm1
	pxor	%xmm4, %xmm2
	pxor	%xmm4, %xmm3
	aes_decrypt_common
	.endm

	.macro	aes_dec_192
	movups	keyC, %xmm4
	movups	keyB, %xmm5
	pxor	%xmm4, %xmm0
	pxor	%xmm4, %xmm1
	pxor	%xmm4, %xmm2
	pxor	%xmm4, %xmm3
	movups	keyA, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	key9, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	aes_decrypt_common
	.endm

	.macro	aes_dec_256
	movups	keyE, %xmm4
	movups	keyD, %xmm5
	pxor	%xmm4, %xmm0
	pxor	%xmm4, %xmm1
	pxor	%xmm4, %xmm2
	pxor	%xmm4, %xmm3
	movups	keyC, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	keyB, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	movups	keyA, %xmm4
	aes		%xmm5, %xmm0
	aes		%xmm5, %xmm1
	aes		%xmm5, %xmm2
	aes		%xmm5, %xmm3
	movups	key9, %xmm5
	aes		%xmm4, %xmm0
	aes		%xmm4, %xmm1
	aes		%xmm4, %xmm2
	aes		%xmm4, %xmm3
	aes_decrypt_common
	.endm

160:	// AES-128 decrypt
	aes_dec_128
	jmp		8f

192:	// AES-192 decrypt
	aes_dec_192
	jmp		8f

224:	// AES-256 decrypt	
	aes_dec_256

8:	

	// 4 P = P ^ T
	pxor	tweak1, %xmm0
	pxor	tweak2, %xmm1
	pxor	tweak3, %xmm2
	pxor	tweak4, %xmm3

	// write 4 Ps
	movups	%xmm0, (P)
	movups	%xmm1, 16(P)
	movups	%xmm2, 32(P)
	movups	%xmm3, 48(P)

	add	$64, C
	add	$64, P

	sub		$4, lim
	jge		0b

#ifdef	KERNEL
	movaps	0xb0(sp), %xmm5				// hw-aes-based uses extra xmm5
#endif
	movups	%xmm7, (T)

9:
	xor		%eax, %eax					// to return CRYPT_OK
	add		$4, lim						// post-increment lim by 4
	je		9f							// if lim==0, branch to prepare to return	

L_uncrypt_group_sw:

	movups	(T), %xmm7					// T, xmm7 will be used as T (128-bit) throughtout the loop

	sub		$1, lim						// pre-decrement lim by 1	
	jl		1f							// if lim < 1, branch to prepare to return
0:
	movups	(C), %xmm0					// C

	// prepare for calling aes_decrypt
#if defined	__i386__
	mov		P, (%esp)					// P
	mov		P, 4(%esp)					// P
										// ctx was prepared previously in preamble
#else
	mov		P, %rdi						// P
	mov		P, %rsi						// P
	mov		ctx, %rdx					// ctx
#endif

	pxor	%xmm7, %xmm0				// P = C ^ T	
	movups	%xmm0, (P)					// save P into memory

	call	_aes_decrypt_xmm_no_save	// err = aes_decrypt(P,P,ctx);

	cmp		$CRYPT_OK, %eax				// err == CRYPT_OK ? 
	jne		9f							// if err != CRYPT_OK, branch to exit with error

	movups	(P), %xmm0					// load xmm0 with P
	pxor	%xmm7, %xmm0				// P ^= T
	movups	%xmm0, (P)					// save output P

	xts_mult_x_on_xmm7

	add		$16, C						// next C
	add		$16, P						// next P
	sub		$1, lim						// lim--
	jge		0b							// if (lim>0) repeat the scalar loop

1:	movups	%xmm7, (T)					// save final tweak 
L_error_uncrypt:
9:
	// if kernel, restore used xmm registers
#ifdef	KERNEL
	movaps	0x50(sp), %xmm0
	movaps	0x60(sp), %xmm1
	movaps	0x70(sp), %xmm2
	movaps	0x80(sp), %xmm3
	movaps	0x90(sp), %xmm4
	movaps	0xa0(sp), %xmm7
#endif

#if defined	__i386__
	add		$(12+16*8+16*4), %esp
	pop		%esi
	pop		%edi
	pop		%ebx
#else
	add		$(8+16*8+16*5), %rsp
	pop		%r15
	pop		%r14
	pop		%r13
	pop		%r12
	pop		%rbx
#endif
	leave
	ret
#endif /* x86 based build */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/cast5.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
 
 /** 
   @file cast5.c
   Implementation of LTC_CAST5 (RFC 2144) by Tom St Denis 
 */
#include "tomcrypt.h"

#ifdef LTC_CAST5

const struct ltc_cipher_descriptor cast5_desc = {
   "cast5",
   15,
   5, 16, 8, 16,
   &cast5_setup,
   &cast5_ecb_encrypt,
   &cast5_ecb_decrypt,
   &cast5_test,
   &cast5_done,
   &cast5_keysize,
    /* ECB Accelerators */
    NULL, NULL, 
    /* CBC Accelerators */
    NULL, NULL,
    /* CTR Accelerators */
    NULL, 
    /* LRW Accelerators */
    NULL, NULL,
    /* XTS Accelerators */
    NULL, NULL,
    /* CCM Accelerator */
    NULL, 
    /* GCM Accelerator */
    NULL, 
    /* OMAC Accelerator */
    NULL,
    /* XCBC Accelerator */
    NULL, 
    /* F9 Accelerator */
    NULL
};

static const ulong32 S1[256] = {
0x30fb40d4UL, 0x9fa0ff0bUL, 0x6beccd2fUL, 0x3f258c7aUL, 0x1e213f2fUL, 0x9c004dd3UL, 
0x6003e540UL, 0xcf9fc949UL, 0xbfd4af27UL, 0x88bbbdb5UL, 0xe2034090UL, 0x98d09675UL, 
0x6e63a0e0UL, 0x15c361d2UL, 0xc2e7661dUL, 0x22d4ff8eUL, 0x28683b6fUL, 0xc07fd059UL, 
0xff2379c8UL, 0x775f50e2UL, 0x43c340d3UL, 0xdf2f8656UL, 0x887ca41aUL, 0xa2d2bd2dUL, 
0xa1c9e0d6UL, 0x346c4819UL, 0x61b76d87UL, 0x22540f2fUL, 0x2abe32e1UL, 0xaa54166bUL, 
0x22568e3aUL, 0xa2d341d0UL, 0x66db40c8UL, 0xa784392fUL, 0x004dff2fUL, 0x2db9d2deUL, 
0x97943facUL, 0x4a97c1d8UL, 0x527644b7UL, 0xb5f437a7UL, 0xb82cbaefUL, 0xd751d159UL, 
0x6ff7f0edUL, 0x5a097a1fUL, 0x827b68d0UL, 0x90ecf52eUL, 0x22b0c054UL, 0xbc8e5935UL, 
0x4b6d2f7fUL, 0x50bb64a2UL, 0xd2664910UL, 0xbee5812dUL, 0xb7332290UL, 0xe93b159fUL, 
0xb48ee411UL, 0x4bff345dUL, 0xfd45c240UL, 0xad31973fUL, 0xc4f6d02eUL, 0x55fc8165UL, 
0xd5b1caadUL, 0xa1ac2daeUL, 0xa2d4b76dUL, 0xc19b0c50UL, 0x882240f2UL, 0x0c6e4f38UL, 
0xa4e4bfd7UL, 0x4f5ba272UL, 0x564c1d2fUL, 0xc59c5319UL, 0xb949e354UL, 0xb04669feUL, 
0xb1b6ab8aUL, 0xc71358ddUL, 0x6385c545UL, 0x110f935dUL, 0x57538ad5UL, 0x6a390493UL, 
0xe63d37e0UL, 0x2a54f6b3UL, 0x3a787d5fUL, 0x6276a0b5UL, 0x19a6fcdfUL, 0x7a42206aUL, 
0x29f9d4d5UL, 0xf61b1891UL, 0xbb72275eUL, 0xaa508167UL, 0x38901091UL, 0xc6b505ebUL, 
0x84c7cb8cUL, 0x2ad75a0fUL, 0x874a1427UL, 0xa2d1936bUL, 0x2ad286afUL, 0xaa56d291UL, 
0xd7894360UL, 0x425c750dUL, 0x93b39e26UL, 0x187184c9UL, 0x6c00b32dUL, 0x73e2bb14UL, 
0xa0bebc3cUL, 0x54623779UL, 0x64459eabUL, 0x3f328b82UL, 0x7718cf82UL, 0x59a2cea6UL, 
0x04ee002eUL, 0x89fe78e6UL, 0x3fab0950UL, 0x325ff6c2UL, 0x81383f05UL, 0x6963c5c8UL, 
0x76cb5ad6UL, 0xd49974c9UL, 0xca180dcfUL, 0x380782d5UL, 0xc7fa5cf6UL, 0x8ac31511UL, 
0x35e79e13UL, 0x47da91d0UL, 0xf40f9086UL, 0xa7e2419eUL, 0x31366241UL, 0x051ef495UL, 
0xaa573b04UL, 0x4a805d8dUL, 0x548300d0UL, 0x00322a3cUL, 0xbf64cddfUL, 0xba57a68eUL, 
0x75c6372bUL, 0x50afd341UL, 0xa7c13275UL, 0x915a0bf5UL, 0x6b54bfabUL, 0x2b0b1426UL, 
0xab4cc9d7UL, 0x449ccd82UL, 0xf7fbf265UL, 0xab85c5f3UL, 0x1b55db94UL, 0xaad4e324UL, 
0xcfa4bd3fUL, 0x2deaa3e2UL, 0x9e204d02UL, 0xc8bd25acUL, 0xeadf55b3UL, 0xd5bd9e98UL, 
0xe31231b2UL, 0x2ad5ad6cUL, 0x954329deUL, 0xadbe4528UL, 0xd8710f69UL, 0xaa51c90fUL, 
0xaa786bf6UL, 0x22513f1eUL, 0xaa51a79bUL, 0x2ad344ccUL, 0x7b5a41f0UL, 0xd37cfbadUL, 
0x1b069505UL, 0x41ece491UL, 0xb4c332e6UL, 0x032268d4UL, 0xc9600accUL, 0xce387e6dUL, 
0xbf6bb16cUL, 0x6a70fb78UL, 0x0d03d9c9UL, 0xd4df39deUL, 0xe01063daUL, 0x4736f464UL, 
0x5ad328d8UL, 0xb347cc96UL, 0x75bb0fc3UL, 0x98511bfbUL, 0x4ffbcc35UL, 0xb58bcf6aUL, 
0xe11f0abcUL, 0xbfc5fe4aUL, 0xa70aec10UL, 0xac39570aUL, 0x3f04442fUL, 0x6188b153UL, 
0xe0397a2eUL, 0x5727cb79UL, 0x9ceb418fUL, 0x1cacd68dUL, 0x2ad37c96UL, 0x0175cb9dUL, 
0xc69dff09UL, 0xc75b65f0UL, 0xd9db40d8UL, 0xec0e7779UL, 0x4744ead4UL, 0xb11c3274UL, 
0xdd24cb9eUL, 0x7e1c54bdUL, 0xf01144f9UL, 0xd2240eb1UL, 0x9675b3fdUL, 0xa3ac3755UL, 
0xd47c27afUL, 0x51c85f4dUL, 0x56907596UL, 0xa5bb15e6UL, 0x580304f0UL, 0xca042cf1UL, 
0x011a37eaUL, 0x8dbfaadbUL, 0x35ba3e4aUL, 0x3526ffa0UL, 0xc37b4d09UL, 0xbc306ed9UL, 
0x98a52666UL, 0x5648f725UL, 0xff5e569dUL, 0x0ced63d0UL, 0x7c63b2cfUL, 0x700b45e1UL, 
0xd5ea50f1UL, 0x85a92872UL, 0xaf1fbda7UL, 0xd4234870UL, 0xa7870bf3UL, 0x2d3b4d79UL, 
0x42e04198UL, 0x0cd0ede7UL, 0x26470db8UL, 0xf881814cUL, 0x474d6ad7UL, 0x7c0c5e5cUL, 
0xd1231959UL, 0x381b7298UL, 0xf5d2f4dbUL, 0xab838653UL, 0x6e2f1e23UL, 0x83719c9eUL, 
0xbd91e046UL, 0x9a56456eUL, 0xdc39200cUL, 0x20c8c571UL, 0x962bda1cUL, 0xe1e696ffUL, 
0xb141ab08UL, 0x7cca89b9UL, 0x1a69e783UL, 0x02cc4843UL, 0xa2f7c579UL, 0x429ef47dUL, 
0x427b169cUL, 0x5ac9f049UL, 0xdd8f0f00UL, 0x5c8165bfUL};

static const ulong32 S2[256] = {
0x1f201094UL, 0xef0ba75bUL, 0x69e3cf7eUL, 0x393f4380UL, 0xfe61cf7aUL, 0xeec5207aUL, 
0x55889c94UL, 0x72fc0651UL, 0xada7ef79UL, 0x4e1d7235UL, 0xd55a63ceUL, 0xde0436baUL, 
0x99c430efUL, 0x5f0c0794UL, 0x18dcdb7dUL, 0xa1d6eff3UL, 0xa0b52f7bUL, 0x59e83605UL, 
0xee15b094UL, 0xe9ffd909UL, 0xdc440086UL, 0xef944459UL, 0xba83ccb3UL, 0xe0c3cdfbUL, 
0xd1da4181UL, 0x3b092ab1UL, 0xf997f1c1UL, 0xa5e6cf7bUL, 0x01420ddbUL, 0xe4e7ef5bUL, 
0x25a1ff41UL, 0xe180f806UL, 0x1fc41080UL, 0x179bee7aUL, 0xd37ac6a9UL, 0xfe5830a4UL, 
0x98de8b7fUL, 0x77e83f4eUL, 0x79929269UL, 0x24fa9f7bUL, 0xe113c85bUL, 0xacc40083UL, 
0xd7503525UL, 0xf7ea615fUL, 0x62143154UL, 0x0d554b63UL, 0x5d681121UL, 0xc866c359UL, 
0x3d63cf73UL, 0xcee234c0UL, 0xd4d87e87UL, 0x5c672b21UL, 0x071f6181UL, 0x39f7627fUL, 
0x361e3084UL, 0xe4eb573bUL, 0x602f64a4UL, 0xd63acd9cUL, 0x1bbc4635UL, 0x9e81032dUL, 
0x2701f50cUL, 0x99847ab4UL, 0xa0e3df79UL, 0xba6cf38cUL, 0x10843094UL, 0x2537a95eUL, 
0xf46f6ffeUL, 0xa1ff3b1fUL, 0x208cfb6aUL, 0x8f458c74UL, 0xd9e0a227UL, 0x4ec73a34UL, 
0xfc884f69UL, 0x3e4de8dfUL, 0xef0e0088UL, 0x3559648dUL, 0x8a45388cUL, 0x1d804366UL, 
0x721d9bfdUL, 0xa58684bbUL, 0xe8256333UL, 0x844e8212UL, 0x128d8098UL, 0xfed33fb4UL, 
0xce280ae1UL, 0x27e19ba5UL, 0xd5a6c252UL, 0xe49754bdUL, 0xc5d655ddUL, 0xeb667064UL, 
0x77840b4dUL, 0xa1b6a801UL, 0x84db26a9UL, 0xe0b56714UL, 0x21f043b7UL, 0xe5d05860UL, 
0x54f03084UL, 0x066ff472UL, 0xa31aa153UL, 0xdadc4755UL, 0xb5625dbfUL, 0x68561be6UL, 
0x83ca6b94UL, 0x2d6ed23bUL, 0xeccf01dbUL, 0xa6d3d0baUL, 0xb6803d5cUL, 0xaf77a709UL, 
0x33b4a34cUL, 0x397bc8d6UL, 0x5ee22b95UL, 0x5f0e5304UL, 0x81ed6f61UL, 0x20e74364UL, 
0xb45e1378UL, 0xde18639bUL, 0x881ca122UL, 0xb96726d1UL, 0x8049a7e8UL, 0x22b7da7bUL, 
0x5e552d25UL, 0x5272d237UL, 0x79d2951cUL, 0xc60d894cUL, 0x488cb402UL, 0x1ba4fe5bUL, 
0xa4b09f6bUL, 0x1ca815cfUL, 0xa20c3005UL, 0x8871df63UL, 0xb9de2fcbUL, 0x0cc6c9e9UL, 
0x0beeff53UL, 0xe3214517UL, 0xb4542835UL, 0x9f63293cUL, 0xee41e729UL, 0x6e1d2d7cUL, 
0x50045286UL, 0x1e6685f3UL, 0xf33401c6UL, 0x30a22c95UL, 0x31a70850UL, 0x60930f13UL, 
0x73f98417UL, 0xa1269859UL, 0xec645c44UL, 0x52c877a9UL, 0xcdff33a6UL, 0xa02b1741UL, 
0x7cbad9a2UL, 0x2180036fUL, 0x50d99c08UL, 0xcb3f4861UL, 0xc26bd765UL, 0x64a3f6abUL, 
0x80342676UL, 0x25a75e7bUL, 0xe4e6d1fcUL, 0x20c710e6UL, 0xcdf0b680UL, 0x17844d3bUL, 
0x31eef84dUL, 0x7e0824e4UL, 0x2ccb49ebUL, 0x846a3baeUL, 0x8ff77888UL, 0xee5d60f6UL, 
0x7af75673UL, 0x2fdd5cdbUL, 0xa11631c1UL, 0x30f66f43UL, 0xb3faec54UL, 0x157fd7faUL, 
0xef8579ccUL, 0xd152de58UL, 0xdb2ffd5eUL, 0x8f32ce19UL, 0x306af97aUL, 0x02f03ef8UL, 
0x99319ad5UL, 0xc242fa0fUL, 0xa7e3ebb0UL, 0xc68e4906UL, 0xb8da230cUL, 0x80823028UL, 
0xdcdef3c8UL, 0xd35fb171UL, 0x088a1bc8UL, 0xbec0c560UL, 0x61a3c9e8UL, 0xbca8f54dUL, 
0xc72feffaUL, 0x22822e99UL, 0x82c570b4UL, 0xd8d94e89UL, 0x8b1c34bcUL, 0x301e16e6UL, 
0x273be979UL, 0xb0ffeaa6UL, 0x61d9b8c6UL, 0x00b24869UL, 0xb7ffce3fUL, 0x08dc283bUL, 
0x43daf65aUL, 0xf7e19798UL, 0x7619b72fUL, 0x8f1c9ba4UL, 0xdc8637a0UL, 0x16a7d3b1UL, 
0x9fc393b7UL, 0xa7136eebUL, 0xc6bcc63eUL, 0x1a513742UL, 0xef6828bcUL, 0x520365d6UL, 
0x2d6a77abUL, 0x3527ed4bUL, 0x821fd216UL, 0x095c6e2eUL, 0xdb92f2fbUL, 0x5eea29cbUL, 
0x145892f5UL, 0x91584f7fUL, 0x5483697bUL, 0x2667a8ccUL, 0x85196048UL, 0x8c4baceaUL, 
0x833860d4UL, 0x0d23e0f9UL, 0x6c387e8aUL, 0x0ae6d249UL, 0xb284600cUL, 0xd835731dUL, 
0xdcb1c647UL, 0xac4c56eaUL, 0x3ebd81b3UL, 0x230eabb0UL, 0x6438bc87UL, 0xf0b5b1faUL, 
0x8f5ea2b3UL, 0xfc184642UL, 0x0a036b7aUL, 0x4fb089bdUL, 0x649da589UL, 0xa345415eUL, 
0x5c038323UL, 0x3e5d3bb9UL, 0x43d79572UL, 0x7e6dd07cUL, 0x06dfdf1eUL, 0x6c6cc4efUL, 
0x7160a539UL, 0x73bfbe70UL, 0x83877605UL, 0x4523ecf1UL};

static const ulong32 S3[256] = {
0x8defc240UL, 0x25fa5d9fUL, 0xeb903dbfUL, 0xe810c907UL, 0x47607fffUL, 0x369fe44bUL, 
0x8c1fc644UL, 0xaececa90UL, 0xbeb1f9bfUL, 0xeefbcaeaUL, 0xe8cf1950UL, 0x51df07aeUL, 
0x920e8806UL, 0xf0ad0548UL, 0xe13c8d83UL, 0x927010d5UL, 0x11107d9fUL, 0x07647db9UL, 
0xb2e3e4d4UL, 0x3d4f285eUL, 0xb9afa820UL, 0xfade82e0UL, 0xa067268bUL, 0x8272792eUL, 
0x553fb2c0UL, 0x489ae22bUL, 0xd4ef9794UL, 0x125e3fbcUL, 0x21fffceeUL, 0x825b1bfdUL, 
0x9255c5edUL, 0x1257a240UL, 0x4e1a8302UL, 0xbae07fffUL, 0x528246e7UL, 0x8e57140eUL, 
0x3373f7bfUL, 0x8c9f8188UL, 0xa6fc4ee8UL, 0xc982b5a5UL, 0xa8c01db7UL, 0x579fc264UL, 
0x67094f31UL, 0xf2bd3f5fUL, 0x40fff7c1UL, 0x1fb78dfcUL, 0x8e6bd2c1UL, 0x437be59bUL, 
0x99b03dbfUL, 0xb5dbc64bUL, 0x638dc0e6UL, 0x55819d99UL, 0xa197c81cUL, 0x4a012d6eUL, 
0xc5884a28UL, 0xccc36f71UL, 0xb843c213UL, 0x6c0743f1UL, 0x8309893cUL, 0x0feddd5fUL, 
0x2f7fe850UL, 0xd7c07f7eUL, 0x02507fbfUL, 0x5afb9a04UL, 0xa747d2d0UL, 0x1651192eUL, 
0xaf70bf3eUL, 0x58c31380UL, 0x5f98302eUL, 0x727cc3c4UL, 0x0a0fb402UL, 0x0f7fef82UL, 
0x8c96fdadUL, 0x5d2c2aaeUL, 0x8ee99a49UL, 0x50da88b8UL, 0x8427f4a0UL, 0x1eac5790UL, 
0x796fb449UL, 0x8252dc15UL, 0xefbd7d9bUL, 0xa672597dUL, 0xada840d8UL, 0x45f54504UL, 
0xfa5d7403UL, 0xe83ec305UL, 0x4f91751aUL, 0x925669c2UL, 0x23efe941UL, 0xa903f12eUL, 
0x60270df2UL, 0x0276e4b6UL, 0x94fd6574UL, 0x927985b2UL, 0x8276dbcbUL, 0x02778176UL, 
0xf8af918dUL, 0x4e48f79eUL, 0x8f616ddfUL, 0xe29d840eUL, 0x842f7d83UL, 0x340ce5c8UL, 
0x96bbb682UL, 0x93b4b148UL, 0xef303cabUL, 0x984faf28UL, 0x779faf9bUL, 0x92dc560dUL, 
0x224d1e20UL, 0x8437aa88UL, 0x7d29dc96UL, 0x2756d3dcUL, 0x8b907ceeUL, 0xb51fd240UL, 
0xe7c07ce3UL, 0xe566b4a1UL, 0xc3e9615eUL, 0x3cf8209dUL, 0x6094d1e3UL, 0xcd9ca341UL, 
0x5c76460eUL, 0x00ea983bUL, 0xd4d67881UL, 0xfd47572cUL, 0xf76cedd9UL, 0xbda8229cUL, 
0x127dadaaUL, 0x438a074eUL, 0x1f97c090UL, 0x081bdb8aUL, 0x93a07ebeUL, 0xb938ca15UL, 
0x97b03cffUL, 0x3dc2c0f8UL, 0x8d1ab2ecUL, 0x64380e51UL, 0x68cc7bfbUL, 0xd90f2788UL, 
0x12490181UL, 0x5de5ffd4UL, 0xdd7ef86aUL, 0x76a2e214UL, 0xb9a40368UL, 0x925d958fUL, 
0x4b39fffaUL, 0xba39aee9UL, 0xa4ffd30bUL, 0xfaf7933bUL, 0x6d498623UL, 0x193cbcfaUL, 
0x27627545UL, 0x825cf47aUL, 0x61bd8ba0UL, 0xd11e42d1UL, 0xcead04f4UL, 0x127ea392UL, 
0x10428db7UL, 0x8272a972UL, 0x9270c4a8UL, 0x127de50bUL, 0x285ba1c8UL, 0x3c62f44fUL, 
0x35c0eaa5UL, 0xe805d231UL, 0x428929fbUL, 0xb4fcdf82UL, 0x4fb66a53UL, 0x0e7dc15bUL, 
0x1f081fabUL, 0x108618aeUL, 0xfcfd086dUL, 0xf9ff2889UL, 0x694bcc11UL, 0x236a5caeUL, 
0x12deca4dUL, 0x2c3f8cc5UL, 0xd2d02dfeUL, 0xf8ef5896UL, 0xe4cf52daUL, 0x95155b67UL, 
0x494a488cUL, 0xb9b6a80cUL, 0x5c8f82bcUL, 0x89d36b45UL, 0x3a609437UL, 0xec00c9a9UL, 
0x44715253UL, 0x0a874b49UL, 0xd773bc40UL, 0x7c34671cUL, 0x02717ef6UL, 0x4feb5536UL, 
0xa2d02fffUL, 0xd2bf60c4UL, 0xd43f03c0UL, 0x50b4ef6dUL, 0x07478cd1UL, 0x006e1888UL, 
0xa2e53f55UL, 0xb9e6d4bcUL, 0xa2048016UL, 0x97573833UL, 0xd7207d67UL, 0xde0f8f3dUL, 
0x72f87b33UL, 0xabcc4f33UL, 0x7688c55dUL, 0x7b00a6b0UL, 0x947b0001UL, 0x570075d2UL, 
0xf9bb88f8UL, 0x8942019eUL, 0x4264a5ffUL, 0x856302e0UL, 0x72dbd92bUL, 0xee971b69UL, 
0x6ea22fdeUL, 0x5f08ae2bUL, 0xaf7a616dUL, 0xe5c98767UL, 0xcf1febd2UL, 0x61efc8c2UL, 
0xf1ac2571UL, 0xcc8239c2UL, 0x67214cb8UL, 0xb1e583d1UL, 0xb7dc3e62UL, 0x7f10bdceUL, 
0xf90a5c38UL, 0x0ff0443dUL, 0x606e6dc6UL, 0x60543a49UL, 0x5727c148UL, 0x2be98a1dUL, 
0x8ab41738UL, 0x20e1be24UL, 0xaf96da0fUL, 0x68458425UL, 0x99833be5UL, 0x600d457dUL, 
0x282f9350UL, 0x8334b362UL, 0xd91d1120UL, 0x2b6d8da0UL, 0x642b1e31UL, 0x9c305a00UL, 
0x52bce688UL, 0x1b03588aUL, 0xf7baefd5UL, 0x4142ed9cUL, 0xa4315c11UL, 0x83323ec5UL, 
0xdfef4636UL, 0xa133c501UL, 0xe9d3531cUL, 0xee353783UL};

static const ulong32 S4[256] = {
0x9db30420UL, 0x1fb6e9deUL, 0xa7be7befUL, 0xd273a298UL, 0x4a4f7bdbUL, 0x64ad8c57UL, 
0x85510443UL, 0xfa020ed1UL, 0x7e287affUL, 0xe60fb663UL, 0x095f35a1UL, 0x79ebf120UL, 
0xfd059d43UL, 0x6497b7b1UL, 0xf3641f63UL, 0x241e4adfUL, 0x28147f5fUL, 0x4fa2b8cdUL, 
0xc9430040UL, 0x0cc32220UL, 0xfdd30b30UL, 0xc0a5374fUL, 0x1d2d00d9UL, 0x24147b15UL, 
0xee4d111aUL, 0x0fca5167UL, 0x71ff904cUL, 0x2d195ffeUL, 0x1a05645fUL, 0x0c13fefeUL, 
0x081b08caUL, 0x05170121UL, 0x80530100UL, 0xe83e5efeUL, 0xac9af4f8UL, 0x7fe72701UL, 
0xd2b8ee5fUL, 0x06df4261UL, 0xbb9e9b8aUL, 0x7293ea25UL, 0xce84ffdfUL, 0xf5718801UL, 
0x3dd64b04UL, 0xa26f263bUL, 0x7ed48400UL, 0x547eebe6UL, 0x446d4ca0UL, 0x6cf3d6f5UL, 
0x2649abdfUL, 0xaea0c7f5UL, 0x36338cc1UL, 0x503f7e93UL, 0xd3772061UL, 0x11b638e1UL, 
0x72500e03UL, 0xf80eb2bbUL, 0xabe0502eUL, 0xec8d77deUL, 0x57971e81UL, 0xe14f6746UL, 
0xc9335400UL, 0x6920318fUL, 0x081dbb99UL, 0xffc304a5UL, 0x4d351805UL, 0x7f3d5ce3UL, 
0xa6c866c6UL, 0x5d5bcca9UL, 0xdaec6feaUL, 0x9f926f91UL, 0x9f46222fUL, 0x3991467dUL, 
0xa5bf6d8eUL, 0x1143c44fUL, 0x43958302UL, 0xd0214eebUL, 0x022083b8UL, 0x3fb6180cUL, 
0x18f8931eUL, 0x281658e6UL, 0x26486e3eUL, 0x8bd78a70UL, 0x7477e4c1UL, 0xb506e07cUL, 
0xf32d0a25UL, 0x79098b02UL, 0xe4eabb81UL, 0x28123b23UL, 0x69dead38UL, 0x1574ca16UL, 
0xdf871b62UL, 0x211c40b7UL, 0xa51a9ef9UL, 0x0014377bUL, 0x041e8ac8UL, 0x09114003UL, 
0xbd59e4d2UL, 0xe3d156d5UL, 0x4fe876d5UL, 0x2f91a340UL, 0x557be8deUL, 0x00eae4a7UL, 
0x0ce5c2ecUL, 0x4db4bba6UL, 0xe756bdffUL, 0xdd3369acUL, 0xec17b035UL, 0x06572327UL, 
0x99afc8b0UL, 0x56c8c391UL, 0x6b65811cUL, 0x5e146119UL, 0x6e85cb75UL, 0xbe07c002UL, 
0xc2325577UL, 0x893ff4ecUL, 0x5bbfc92dUL, 0xd0ec3b25UL, 0xb7801ab7UL, 0x8d6d3b24UL, 
0x20c763efUL, 0xc366a5fcUL, 0x9c382880UL, 0x0ace3205UL, 0xaac9548aUL, 0xeca1d7c7UL, 
0x041afa32UL, 0x1d16625aUL, 0x6701902cUL, 0x9b757a54UL, 0x31d477f7UL, 0x9126b031UL, 
0x36cc6fdbUL, 0xc70b8b46UL, 0xd9e66a48UL, 0x56e55a79UL, 0x026a4cebUL, 0x52437effUL, 
0x2f8f76b4UL, 0x0df980a5UL, 0x8674cde3UL, 0xedda04ebUL, 0x17a9be04UL, 0x2c18f4dfUL, 
0xb7747f9dUL, 0xab2af7b4UL, 0xefc34d20UL, 0x2e096b7cUL, 0x1741a254UL, 0xe5b6a035UL, 
0x213d42f6UL, 0x2c1c7c26UL, 0x61c2f50fUL, 0x6552daf9UL, 0xd2c231f8UL, 0x25130f69UL, 
0xd8167fa2UL, 0x0418f2c8UL, 0x001a96a6UL, 0x0d1526abUL, 0x63315c21UL, 0x5e0a72ecUL, 
0x49bafefdUL, 0x187908d9UL, 0x8d0dbd86UL, 0x311170a7UL, 0x3e9b640cUL, 0xcc3e10d7UL, 
0xd5cad3b6UL, 0x0caec388UL, 0xf73001e1UL, 0x6c728affUL, 0x71eae2a1UL, 0x1f9af36eUL, 
0xcfcbd12fUL, 0xc1de8417UL, 0xac07be6bUL, 0xcb44a1d8UL, 0x8b9b0f56UL, 0x013988c3UL, 
0xb1c52fcaUL, 0xb4be31cdUL, 0xd8782806UL, 0x12a3a4e2UL, 0x6f7de532UL, 0x58fd7eb6UL, 
0xd01ee900UL, 0x24adffc2UL, 0xf4990fc5UL, 0x9711aac5UL, 0x001d7b95UL, 0x82e5e7d2UL, 
0x109873f6UL, 0x00613096UL, 0xc32d9521UL, 0xada121ffUL, 0x29908415UL, 0x7fbb977fUL, 
0xaf9eb3dbUL, 0x29c9ed2aUL, 0x5ce2a465UL, 0xa730f32cUL, 0xd0aa3fe8UL, 0x8a5cc091UL, 
0xd49e2ce7UL, 0x0ce454a9UL, 0xd60acd86UL, 0x015f1919UL, 0x77079103UL, 0xdea03af6UL, 
0x78a8565eUL, 0xdee356dfUL, 0x21f05cbeUL, 0x8b75e387UL, 0xb3c50651UL, 0xb8a5c3efUL, 
0xd8eeb6d2UL, 0xe523be77UL, 0xc2154529UL, 0x2f69efdfUL, 0xafe67afbUL, 0xf470c4b2UL, 
0xf3e0eb5bUL, 0xd6cc9876UL, 0x39e4460cUL, 0x1fda8538UL, 0x1987832fUL, 0xca007367UL, 
0xa99144f8UL, 0x296b299eUL, 0x492fc295UL, 0x9266beabUL, 0xb5676e69UL, 0x9bd3dddaUL, 
0xdf7e052fUL, 0xdb25701cUL, 0x1b5e51eeUL, 0xf65324e6UL, 0x6afce36cUL, 0x0316cc04UL, 
0x8644213eUL, 0xb7dc59d0UL, 0x7965291fUL, 0xccd6fd43UL, 0x41823979UL, 0x932bcdf6UL, 
0xb657c34dUL, 0x4edfd282UL, 0x7ae5290cUL, 0x3cb9536bUL, 0x851e20feUL, 0x9833557eUL, 
0x13ecf0b0UL, 0xd3ffb372UL, 0x3f85c5c1UL, 0x0aef7ed2UL};

static const ulong32 S5[256] = {
0x7ec90c04UL, 0x2c6e74b9UL, 0x9b0e66dfUL, 0xa6337911UL, 0xb86a7fffUL, 0x1dd358f5UL, 
0x44dd9d44UL, 0x1731167fUL, 0x08fbf1faUL, 0xe7f511ccUL, 0xd2051b00UL, 0x735aba00UL, 
0x2ab722d8UL, 0x386381cbUL, 0xacf6243aUL, 0x69befd7aUL, 0xe6a2e77fUL, 0xf0c720cdUL, 
0xc4494816UL, 0xccf5c180UL, 0x38851640UL, 0x15b0a848UL, 0xe68b18cbUL, 0x4caadeffUL, 
0x5f480a01UL, 0x0412b2aaUL, 0x259814fcUL, 0x41d0efe2UL, 0x4e40b48dUL, 0x248eb6fbUL, 
0x8dba1cfeUL, 0x41a99b02UL, 0x1a550a04UL, 0xba8f65cbUL, 0x7251f4e7UL, 0x95a51725UL, 
0xc106ecd7UL, 0x97a5980aUL, 0xc539b9aaUL, 0x4d79fe6aUL, 0xf2f3f763UL, 0x68af8040UL, 
0xed0c9e56UL, 0x11b4958bUL, 0xe1eb5a88UL, 0x8709e6b0UL, 0xd7e07156UL, 0x4e29fea7UL, 
0x6366e52dUL, 0x02d1c000UL, 0xc4ac8e05UL, 0x9377f571UL, 0x0c05372aUL, 0x578535f2UL, 
0x2261be02UL, 0xd642a0c9UL, 0xdf13a280UL, 0x74b55bd2UL, 0x682199c0UL, 0xd421e5ecUL, 
0x53fb3ce8UL, 0xc8adedb3UL, 0x28a87fc9UL, 0x3d959981UL, 0x5c1ff900UL, 0xfe38d399UL, 
0x0c4eff0bUL, 0x062407eaUL, 0xaa2f4fb1UL, 0x4fb96976UL, 0x90c79505UL, 0xb0a8a774UL, 
0xef55a1ffUL, 0xe59ca2c2UL, 0xa6b62d27UL, 0xe66a4263UL, 0xdf65001fUL, 0x0ec50966UL, 
0xdfdd55bcUL, 0x29de0655UL, 0x911e739aUL, 0x17af8975UL, 0x32c7911cUL, 0x89f89468UL, 
0x0d01e980UL, 0x524755f4UL, 0x03b63cc9UL, 0x0cc844b2UL, 0xbcf3f0aaUL, 0x87ac36e9UL, 
0xe53a7426UL, 0x01b3d82bUL, 0x1a9e7449UL, 0x64ee2d7eUL, 0xcddbb1daUL, 0x01c94910UL, 
0xb868bf80UL, 0x0d26f3fdUL, 0x9342ede7UL, 0x04a5c284UL, 0x636737b6UL, 0x50f5b616UL, 
0xf24766e3UL, 0x8eca36c1UL, 0x136e05dbUL, 0xfef18391UL, 0xfb887a37UL, 0xd6e7f7d4UL, 
0xc7fb7dc9UL, 0x3063fcdfUL, 0xb6f589deUL, 0xec2941daUL, 0x26e46695UL, 0xb7566419UL, 
0xf654efc5UL, 0xd08d58b7UL, 0x48925401UL, 0xc1bacb7fUL, 0xe5ff550fUL, 0xb6083049UL, 
0x5bb5d0e8UL, 0x87d72e5aUL, 0xab6a6ee1UL, 0x223a66ceUL, 0xc62bf3cdUL, 0x9e0885f9UL, 
0x68cb3e47UL, 0x086c010fUL, 0xa21de820UL, 0xd18b69deUL, 0xf3f65777UL, 0xfa02c3f6UL, 
0x407edac3UL, 0xcbb3d550UL, 0x1793084dUL, 0xb0d70ebaUL, 0x0ab378d5UL, 0xd951fb0cUL, 
0xded7da56UL, 0x4124bbe4UL, 0x94ca0b56UL, 0x0f5755d1UL, 0xe0e1e56eUL, 0x6184b5beUL, 
0x580a249fUL, 0x94f74bc0UL, 0xe327888eUL, 0x9f7b5561UL, 0xc3dc0280UL, 0x05687715UL, 
0x646c6bd7UL, 0x44904db3UL, 0x66b4f0a3UL, 0xc0f1648aUL, 0x697ed5afUL, 0x49e92ff6UL, 
0x309e374fUL, 0x2cb6356aUL, 0x85808573UL, 0x4991f840UL, 0x76f0ae02UL, 0x083be84dUL, 
0x28421c9aUL, 0x44489406UL, 0x736e4cb8UL, 0xc1092910UL, 0x8bc95fc6UL, 0x7d869cf4UL, 
0x134f616fUL, 0x2e77118dUL, 0xb31b2be1UL, 0xaa90b472UL, 0x3ca5d717UL, 0x7d161bbaUL, 
0x9cad9010UL, 0xaf462ba2UL, 0x9fe459d2UL, 0x45d34559UL, 0xd9f2da13UL, 0xdbc65487UL, 
0xf3e4f94eUL, 0x176d486fUL, 0x097c13eaUL, 0x631da5c7UL, 0x445f7382UL, 0x175683f4UL, 
0xcdc66a97UL, 0x70be0288UL, 0xb3cdcf72UL, 0x6e5dd2f3UL, 0x20936079UL, 0x459b80a5UL, 
0xbe60e2dbUL, 0xa9c23101UL, 0xeba5315cUL, 0x224e42f2UL, 0x1c5c1572UL, 0xf6721b2cUL, 
0x1ad2fff3UL, 0x8c25404eUL, 0x324ed72fUL, 0x4067b7fdUL, 0x0523138eUL, 0x5ca3bc78UL, 
0xdc0fd66eUL, 0x75922283UL, 0x784d6b17UL, 0x58ebb16eUL, 0x44094f85UL, 0x3f481d87UL, 
0xfcfeae7bUL, 0x77b5ff76UL, 0x8c2302bfUL, 0xaaf47556UL, 0x5f46b02aUL, 0x2b092801UL, 
0x3d38f5f7UL, 0x0ca81f36UL, 0x52af4a8aUL, 0x66d5e7c0UL, 0xdf3b0874UL, 0x95055110UL, 
0x1b5ad7a8UL, 0xf61ed5adUL, 0x6cf6e479UL, 0x20758184UL, 0xd0cefa65UL, 0x88f7be58UL, 
0x4a046826UL, 0x0ff6f8f3UL, 0xa09c7f70UL, 0x5346aba0UL, 0x5ce96c28UL, 0xe176eda3UL, 
0x6bac307fUL, 0x376829d2UL, 0x85360fa9UL, 0x17e3fe2aUL, 0x24b79767UL, 0xf5a96b20UL, 
0xd6cd2595UL, 0x68ff1ebfUL, 0x7555442cUL, 0xf19f06beUL, 0xf9e0659aUL, 0xeeb9491dUL, 
0x34010718UL, 0xbb30cab8UL, 0xe822fe15UL, 0x88570983UL, 0x750e6249UL, 0xda627e55UL, 
0x5e76ffa8UL, 0xb1534546UL, 0x6d47de08UL, 0xefe9e7d4UL};

static const ulong32 S6[256] = {
0xf6fa8f9dUL, 0x2cac6ce1UL, 0x4ca34867UL, 0xe2337f7cUL, 0x95db08e7UL, 0x016843b4UL, 
0xeced5cbcUL, 0x325553acUL, 0xbf9f0960UL, 0xdfa1e2edUL, 0x83f0579dUL, 0x63ed86b9UL, 
0x1ab6a6b8UL, 0xde5ebe39UL, 0xf38ff732UL, 0x8989b138UL, 0x33f14961UL, 0xc01937bdUL, 
0xf506c6daUL, 0xe4625e7eUL, 0xa308ea99UL, 0x4e23e33cUL, 0x79cbd7ccUL, 0x48a14367UL, 
0xa3149619UL, 0xfec94bd5UL, 0xa114174aUL, 0xeaa01866UL, 0xa084db2dUL, 0x09a8486fUL, 
0xa888614aUL, 0x2900af98UL, 0x01665991UL, 0xe1992863UL, 0xc8f30c60UL, 0x2e78ef3cUL, 
0xd0d51932UL, 0xcf0fec14UL, 0xf7ca07d2UL, 0xd0a82072UL, 0xfd41197eUL, 0x9305a6b0UL, 
0xe86be3daUL, 0x74bed3cdUL, 0x372da53cUL, 0x4c7f4448UL, 0xdab5d440UL, 0x6dba0ec3UL, 
0x083919a7UL, 0x9fbaeed9UL, 0x49dbcfb0UL, 0x4e670c53UL, 0x5c3d9c01UL, 0x64bdb941UL, 
0x2c0e636aUL, 0xba7dd9cdUL, 0xea6f7388UL, 0xe70bc762UL, 0x35f29adbUL, 0x5c4cdd8dUL, 
0xf0d48d8cUL, 0xb88153e2UL, 0x08a19866UL, 0x1ae2eac8UL, 0x284caf89UL, 0xaa928223UL, 
0x9334be53UL, 0x3b3a21bfUL, 0x16434be3UL, 0x9aea3906UL, 0xefe8c36eUL, 0xf890cdd9UL, 
0x80226daeUL, 0xc340a4a3UL, 0xdf7e9c09UL, 0xa694a807UL, 0x5b7c5eccUL, 0x221db3a6UL, 
0x9a69a02fUL, 0x68818a54UL, 0xceb2296fUL, 0x53c0843aUL, 0xfe893655UL, 0x25bfe68aUL, 
0xb4628abcUL, 0xcf222ebfUL, 0x25ac6f48UL, 0xa9a99387UL, 0x53bddb65UL, 0xe76ffbe7UL, 
0xe967fd78UL, 0x0ba93563UL, 0x8e342bc1UL, 0xe8a11be9UL, 0x4980740dUL, 0xc8087dfcUL, 
0x8de4bf99UL, 0xa11101a0UL, 0x7fd37975UL, 0xda5a26c0UL, 0xe81f994fUL, 0x9528cd89UL, 
0xfd339fedUL, 0xb87834bfUL, 0x5f04456dUL, 0x22258698UL, 0xc9c4c83bUL, 0x2dc156beUL, 
0x4f628daaUL, 0x57f55ec5UL, 0xe2220abeUL, 0xd2916ebfUL, 0x4ec75b95UL, 0x24f2c3c0UL, 
0x42d15d99UL, 0xcd0d7fa0UL, 0x7b6e27ffUL, 0xa8dc8af0UL, 0x7345c106UL, 0xf41e232fUL, 
0x35162386UL, 0xe6ea8926UL, 0x3333b094UL, 0x157ec6f2UL, 0x372b74afUL, 0x692573e4UL, 
0xe9a9d848UL, 0xf3160289UL, 0x3a62ef1dUL, 0xa787e238UL, 0xf3a5f676UL, 0x74364853UL, 
0x20951063UL, 0x4576698dUL, 0xb6fad407UL, 0x592af950UL, 0x36f73523UL, 0x4cfb6e87UL, 
0x7da4cec0UL, 0x6c152daaUL, 0xcb0396a8UL, 0xc50dfe5dUL, 0xfcd707abUL, 0x0921c42fUL, 
0x89dff0bbUL, 0x5fe2be78UL, 0x448f4f33UL, 0x754613c9UL, 0x2b05d08dUL, 0x48b9d585UL, 
0xdc049441UL, 0xc8098f9bUL, 0x7dede786UL, 0xc39a3373UL, 0x42410005UL, 0x6a091751UL, 
0x0ef3c8a6UL, 0x890072d6UL, 0x28207682UL, 0xa9a9f7beUL, 0xbf32679dUL, 0xd45b5b75UL, 
0xb353fd00UL, 0xcbb0e358UL, 0x830f220aUL, 0x1f8fb214UL, 0xd372cf08UL, 0xcc3c4a13UL, 
0x8cf63166UL, 0x061c87beUL, 0x88c98f88UL, 0x6062e397UL, 0x47cf8e7aUL, 0xb6c85283UL, 
0x3cc2acfbUL, 0x3fc06976UL, 0x4e8f0252UL, 0x64d8314dUL, 0xda3870e3UL, 0x1e665459UL, 
0xc10908f0UL, 0x513021a5UL, 0x6c5b68b7UL, 0x822f8aa0UL, 0x3007cd3eUL, 0x74719eefUL, 
0xdc872681UL, 0x073340d4UL, 0x7e432fd9UL, 0x0c5ec241UL, 0x8809286cUL, 0xf592d891UL, 
0x08a930f6UL, 0x957ef305UL, 0xb7fbffbdUL, 0xc266e96fUL, 0x6fe4ac98UL, 0xb173ecc0UL, 
0xbc60b42aUL, 0x953498daUL, 0xfba1ae12UL, 0x2d4bd736UL, 0x0f25faabUL, 0xa4f3fcebUL, 
0xe2969123UL, 0x257f0c3dUL, 0x9348af49UL, 0x361400bcUL, 0xe8816f4aUL, 0x3814f200UL, 
0xa3f94043UL, 0x9c7a54c2UL, 0xbc704f57UL, 0xda41e7f9UL, 0xc25ad33aUL, 0x54f4a084UL, 
0xb17f5505UL, 0x59357cbeUL, 0xedbd15c8UL, 0x7f97c5abUL, 0xba5ac7b5UL, 0xb6f6deafUL, 
0x3a479c3aUL, 0x5302da25UL, 0x653d7e6aUL, 0x54268d49UL, 0x51a477eaUL, 0x5017d55bUL, 
0xd7d25d88UL, 0x44136c76UL, 0x0404a8c8UL, 0xb8e5a121UL, 0xb81a928aUL, 0x60ed5869UL, 
0x97c55b96UL, 0xeaec991bUL, 0x29935913UL, 0x01fdb7f1UL, 0x088e8dfaUL, 0x9ab6f6f5UL, 
0x3b4cbf9fUL, 0x4a5de3abUL, 0xe6051d35UL, 0xa0e1d855UL, 0xd36b4cf1UL, 0xf544edebUL, 
0xb0e93524UL, 0xbebb8fbdUL, 0xa2d762cfUL, 0x49c92f54UL, 0x38b5f331UL, 0x7128a454UL, 
0x48392905UL, 0xa65b1db8UL, 0x851c97bdUL, 0xd675cf2fUL};

static const ulong32 S7[256] = {
0x85e04019UL, 0x332bf567UL, 0x662dbfffUL, 0xcfc65693UL, 0x2a8d7f6fUL, 0xab9bc912UL, 
0xde6008a1UL, 0x2028da1fUL, 0x0227bce7UL, 0x4d642916UL, 0x18fac300UL, 0x50f18b82UL, 
0x2cb2cb11UL, 0xb232e75cUL, 0x4b3695f2UL, 0xb28707deUL, 0xa05fbcf6UL, 0xcd4181e9UL, 
0xe150210cUL, 0xe24ef1bdUL, 0xb168c381UL, 0xfde4e789UL, 0x5c79b0d8UL, 0x1e8bfd43UL, 
0x4d495001UL, 0x38be4341UL, 0x913cee1dUL, 0x92a79c3fUL, 0x089766beUL, 0xbaeeadf4UL, 
0x1286becfUL, 0xb6eacb19UL, 0x2660c200UL, 0x7565bde4UL, 0x64241f7aUL, 0x8248dca9UL, 
0xc3b3ad66UL, 0x28136086UL, 0x0bd8dfa8UL, 0x356d1cf2UL, 0x107789beUL, 0xb3b2e9ceUL, 
0x0502aa8fUL, 0x0bc0351eUL, 0x166bf52aUL, 0xeb12ff82UL, 0xe3486911UL, 0xd34d7516UL, 
0x4e7b3affUL, 0x5f43671bUL, 0x9cf6e037UL, 0x4981ac83UL, 0x334266ceUL, 0x8c9341b7UL, 
0xd0d854c0UL, 0xcb3a6c88UL, 0x47bc2829UL, 0x4725ba37UL, 0xa66ad22bUL, 0x7ad61f1eUL, 
0x0c5cbafaUL, 0x4437f107UL, 0xb6e79962UL, 0x42d2d816UL, 0x0a961288UL, 0xe1a5c06eUL, 
0x13749e67UL, 0x72fc081aUL, 0xb1d139f7UL, 0xf9583745UL, 0xcf19df58UL, 0xbec3f756UL, 
0xc06eba30UL, 0x07211b24UL, 0x45c28829UL, 0xc95e317fUL, 0xbc8ec511UL, 0x38bc46e9UL, 
0xc6e6fa14UL, 0xbae8584aUL, 0xad4ebc46UL, 0x468f508bUL, 0x7829435fUL, 0xf124183bUL, 
0x821dba9fUL, 0xaff60ff4UL, 0xea2c4e6dUL, 0x16e39264UL, 0x92544a8bUL, 0x009b4fc3UL, 
0xaba68cedUL, 0x9ac96f78UL, 0x06a5b79aUL, 0xb2856e6eUL, 0x1aec3ca9UL, 0xbe838688UL, 
0x0e0804e9UL, 0x55f1be56UL, 0xe7e5363bUL, 0xb3a1f25dUL, 0xf7debb85UL, 0x61fe033cUL, 
0x16746233UL, 0x3c034c28UL, 0xda6d0c74UL, 0x79aac56cUL, 0x3ce4e1adUL, 0x51f0c802UL, 
0x98f8f35aUL, 0x1626a49fUL, 0xeed82b29UL, 0x1d382fe3UL, 0x0c4fb99aUL, 0xbb325778UL, 
0x3ec6d97bUL, 0x6e77a6a9UL, 0xcb658b5cUL, 0xd45230c7UL, 0x2bd1408bUL, 0x60c03eb7UL, 
0xb9068d78UL, 0xa33754f4UL, 0xf430c87dUL, 0xc8a71302UL, 0xb96d8c32UL, 0xebd4e7beUL, 
0xbe8b9d2dUL, 0x7979fb06UL, 0xe7225308UL, 0x8b75cf77UL, 0x11ef8da4UL, 0xe083c858UL, 
0x8d6b786fUL, 0x5a6317a6UL, 0xfa5cf7a0UL, 0x5dda0033UL, 0xf28ebfb0UL, 0xf5b9c310UL, 
0xa0eac280UL, 0x08b9767aUL, 0xa3d9d2b0UL, 0x79d34217UL, 0x021a718dUL, 0x9ac6336aUL, 
0x2711fd60UL, 0x438050e3UL, 0x069908a8UL, 0x3d7fedc4UL, 0x826d2befUL, 0x4eeb8476UL, 
0x488dcf25UL, 0x36c9d566UL, 0x28e74e41UL, 0xc2610acaUL, 0x3d49a9cfUL, 0xbae3b9dfUL, 
0xb65f8de6UL, 0x92aeaf64UL, 0x3ac7d5e6UL, 0x9ea80509UL, 0xf22b017dUL, 0xa4173f70UL, 
0xdd1e16c3UL, 0x15e0d7f9UL, 0x50b1b887UL, 0x2b9f4fd5UL, 0x625aba82UL, 0x6a017962UL, 
0x2ec01b9cUL, 0x15488aa9UL, 0xd716e740UL, 0x40055a2cUL, 0x93d29a22UL, 0xe32dbf9aUL, 
0x058745b9UL, 0x3453dc1eUL, 0xd699296eUL, 0x496cff6fUL, 0x1c9f4986UL, 0xdfe2ed07UL, 
0xb87242d1UL, 0x19de7eaeUL, 0x053e561aUL, 0x15ad6f8cUL, 0x66626c1cUL, 0x7154c24cUL, 
0xea082b2aUL, 0x93eb2939UL, 0x17dcb0f0UL, 0x58d4f2aeUL, 0x9ea294fbUL, 0x52cf564cUL, 
0x9883fe66UL, 0x2ec40581UL, 0x763953c3UL, 0x01d6692eUL, 0xd3a0c108UL, 0xa1e7160eUL, 
0xe4f2dfa6UL, 0x693ed285UL, 0x74904698UL, 0x4c2b0eddUL, 0x4f757656UL, 0x5d393378UL, 
0xa132234fUL, 0x3d321c5dUL, 0xc3f5e194UL, 0x4b269301UL, 0xc79f022fUL, 0x3c997e7eUL, 
0x5e4f9504UL, 0x3ffafbbdUL, 0x76f7ad0eUL, 0x296693f4UL, 0x3d1fce6fUL, 0xc61e45beUL, 
0xd3b5ab34UL, 0xf72bf9b7UL, 0x1b0434c0UL, 0x4e72b567UL, 0x5592a33dUL, 0xb5229301UL, 
0xcfd2a87fUL, 0x60aeb767UL, 0x1814386bUL, 0x30bcc33dUL, 0x38a0c07dUL, 0xfd1606f2UL, 
0xc363519bUL, 0x589dd390UL, 0x5479f8e6UL, 0x1cb8d647UL, 0x97fd61a9UL, 0xea7759f4UL, 
0x2d57539dUL, 0x569a58cfUL, 0xe84e63adUL, 0x462e1b78UL, 0x6580f87eUL, 0xf3817914UL, 
0x91da55f4UL, 0x40a230f3UL, 0xd1988f35UL, 0xb6e318d2UL, 0x3ffa50bcUL, 0x3d40f021UL, 
0xc3c0bdaeUL, 0x4958c24cUL, 0x518f36b2UL, 0x84b1d370UL, 0x0fedce83UL, 0x878ddadaUL, 
0xf2a279c7UL, 0x94e01be8UL, 0x90716f4bUL, 0x954b8aa3UL};

static const ulong32 S8[256] = {
0xe216300dUL, 0xbbddfffcUL, 0xa7ebdabdUL, 0x35648095UL, 0x7789f8b7UL, 0xe6c1121bUL, 
0x0e241600UL, 0x052ce8b5UL, 0x11a9cfb0UL, 0xe5952f11UL, 0xece7990aUL, 0x9386d174UL, 
0x2a42931cUL, 0x76e38111UL, 0xb12def3aUL, 0x37ddddfcUL, 0xde9adeb1UL, 0x0a0cc32cUL, 
0xbe197029UL, 0x84a00940UL, 0xbb243a0fUL, 0xb4d137cfUL, 0xb44e79f0UL, 0x049eedfdUL, 
0x0b15a15dUL, 0x480d3168UL, 0x8bbbde5aUL, 0x669ded42UL, 0xc7ece831UL, 0x3f8f95e7UL, 
0x72df191bUL, 0x7580330dUL, 0x94074251UL, 0x5c7dcdfaUL, 0xabbe6d63UL, 0xaa402164UL, 
0xb301d40aUL, 0x02e7d1caUL, 0x53571daeUL, 0x7a3182a2UL, 0x12a8ddecUL, 0xfdaa335dUL, 
0x176f43e8UL, 0x71fb46d4UL, 0x38129022UL, 0xce949ad4UL, 0xb84769adUL, 0x965bd862UL, 
0x82f3d055UL, 0x66fb9767UL, 0x15b80b4eUL, 0x1d5b47a0UL, 0x4cfde06fUL, 0xc28ec4b8UL, 
0x57e8726eUL, 0x647a78fcUL, 0x99865d44UL, 0x608bd593UL, 0x6c200e03UL, 0x39dc5ff6UL, 
0x5d0b00a3UL, 0xae63aff2UL, 0x7e8bd632UL, 0x70108c0cUL, 0xbbd35049UL, 0x2998df04UL, 
0x980cf42aUL, 0x9b6df491UL, 0x9e7edd53UL, 0x06918548UL, 0x58cb7e07UL, 0x3b74ef2eUL, 
0x522fffb1UL, 0xd24708ccUL, 0x1c7e27cdUL, 0xa4eb215bUL, 0x3cf1d2e2UL, 0x19b47a38UL, 
0x424f7618UL, 0x35856039UL, 0x9d17dee7UL, 0x27eb35e6UL, 0xc9aff67bUL, 0x36baf5b8UL, 
0x09c467cdUL, 0xc18910b1UL, 0xe11dbf7bUL, 0x06cd1af8UL, 0x7170c608UL, 0x2d5e3354UL, 
0xd4de495aUL, 0x64c6d006UL, 0xbcc0c62cUL, 0x3dd00db3UL, 0x708f8f34UL, 0x77d51b42UL, 
0x264f620fUL, 0x24b8d2bfUL, 0x15c1b79eUL, 0x46a52564UL, 0xf8d7e54eUL, 0x3e378160UL, 
0x7895cda5UL, 0x859c15a5UL, 0xe6459788UL, 0xc37bc75fUL, 0xdb07ba0cUL, 0x0676a3abUL, 
0x7f229b1eUL, 0x31842e7bUL, 0x24259fd7UL, 0xf8bef472UL, 0x835ffcb8UL, 0x6df4c1f2UL, 
0x96f5b195UL, 0xfd0af0fcUL, 0xb0fe134cUL, 0xe2506d3dUL, 0x4f9b12eaUL, 0xf215f225UL, 
0xa223736fUL, 0x9fb4c428UL, 0x25d04979UL, 0x34c713f8UL, 0xc4618187UL, 0xea7a6e98UL, 
0x7cd16efcUL, 0x1436876cUL, 0xf1544107UL, 0xbedeee14UL, 0x56e9af27UL, 0xa04aa441UL, 
0x3cf7c899UL, 0x92ecbae6UL, 0xdd67016dUL, 0x151682ebUL, 0xa842eedfUL, 0xfdba60b4UL, 
0xf1907b75UL, 0x20e3030fUL, 0x24d8c29eUL, 0xe139673bUL, 0xefa63fb8UL, 0x71873054UL, 
0xb6f2cf3bUL, 0x9f326442UL, 0xcb15a4ccUL, 0xb01a4504UL, 0xf1e47d8dUL, 0x844a1be5UL, 
0xbae7dfdcUL, 0x42cbda70UL, 0xcd7dae0aUL, 0x57e85b7aUL, 0xd53f5af6UL, 0x20cf4d8cUL, 
0xcea4d428UL, 0x79d130a4UL, 0x3486ebfbUL, 0x33d3cddcUL, 0x77853b53UL, 0x37effcb5UL, 
0xc5068778UL, 0xe580b3e6UL, 0x4e68b8f4UL, 0xc5c8b37eUL, 0x0d809ea2UL, 0x398feb7cUL, 
0x132a4f94UL, 0x43b7950eUL, 0x2fee7d1cUL, 0x223613bdUL, 0xdd06caa2UL, 0x37df932bUL, 
0xc4248289UL, 0xacf3ebc3UL, 0x5715f6b7UL, 0xef3478ddUL, 0xf267616fUL, 0xc148cbe4UL, 
0x9052815eUL, 0x5e410fabUL, 0xb48a2465UL, 0x2eda7fa4UL, 0xe87b40e4UL, 0xe98ea084UL, 
0x5889e9e1UL, 0xefd390fcUL, 0xdd07d35bUL, 0xdb485694UL, 0x38d7e5b2UL, 0x57720101UL, 
0x730edebcUL, 0x5b643113UL, 0x94917e4fUL, 0x503c2fbaUL, 0x646f1282UL, 0x7523d24aUL, 
0xe0779695UL, 0xf9c17a8fUL, 0x7a5b2121UL, 0xd187b896UL, 0x29263a4dUL, 0xba510cdfUL, 
0x81f47c9fUL, 0xad1163edUL, 0xea7b5965UL, 0x1a00726eUL, 0x11403092UL, 0x00da6d77UL, 
0x4a0cdd61UL, 0xad1f4603UL, 0x605bdfb0UL, 0x9eedc364UL, 0x22ebe6a8UL, 0xcee7d28aUL, 
0xa0e736a0UL, 0x5564a6b9UL, 0x10853209UL, 0xc7eb8f37UL, 0x2de705caUL, 0x8951570fUL, 
0xdf09822bUL, 0xbd691a6cUL, 0xaa12e4f2UL, 0x87451c0fUL, 0xe0f6a27aUL, 0x3ada4819UL, 
0x4cf1764fUL, 0x0d771c2bUL, 0x67cdb156UL, 0x350d8384UL, 0x5938fa0fUL, 0x42399ef3UL, 
0x36997b07UL, 0x0e84093dUL, 0x4aa93e61UL, 0x8360d87bUL, 0x1fa98b0cUL, 0x1149382cUL, 
0xe97625a5UL, 0x0614d1b7UL, 0x0e25244bUL, 0x0c768347UL, 0x589e8d82UL, 0x0d2059d1UL, 
0xa466bb1eUL, 0xf8da0a82UL, 0x04f19130UL, 0xba6e4ec0UL, 0x99265164UL, 0x1ee7230dUL, 
0x50b2ad80UL, 0xeaee6801UL, 0x8db2a283UL, 0xea8bf59eUL};

/* returns the i'th byte of a variable */
#ifdef _MSC_VER
   #define GB(x, i) ((unsigned char)((x[(15-i)>>2])>>(unsigned)(8*((15-i)&3))))
#else   
   #define GB(x, i) (((x[(15-i)>>2])>>(unsigned)(8*((15-i)&3)))&255)
#endif   

 /**
    Initialize the LTC_CAST5 block cipher
    @param key The symmetric key you wish to pass
    @param keylen The key length in bytes
    @param num_rounds The number of rounds desired (0 for default)
    @param skey The key in as scheduled by this function.
    @return CRYPT_OK if successful
 */
#ifdef LTC_CLEAN_STACK
static int _cast5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
#else
int cast5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
#endif
{
   ulong32 x[4], z[4];
   unsigned char buf[16];
   int y, i;

   LTC_ARGCHK(key != NULL);
   LTC_ARGCHK(skey != NULL);

   if (num_rounds != 12 && num_rounds != 16 && num_rounds != 0) {
      return CRYPT_INVALID_ROUNDS; 
   }
 
   if (num_rounds == 12 && keylen > 10) {
      return CRYPT_INVALID_ROUNDS;
   }

   if (keylen < 5 || keylen > 16) {
      return CRYPT_INVALID_KEYSIZE;
   }

   /* extend the key as required */
   zeromem(buf, sizeof(buf));
   XMEMCPY(buf, key, (size_t)keylen);

   /* load and start the awful looking network */
   for (y = 0; y < 4; y++) {
       LOAD32H(x[3-y],buf+4*y);
   }

   for (i = y = 0; y < 2; y++) {
        z[3] = x[3] ^ S5[GB(x, 0xD)] ^ S6[GB(x, 0xF)] ^ S7[GB(x, 0xC)] ^ S8[GB(x, 0xE)] ^ S7[GB(x, 0x8)];
        z[2] = x[1] ^ S5[GB(z, 0x0)] ^ S6[GB(z, 0x2)] ^ S7[GB(z, 0x1)] ^ S8[GB(z, 0x3)] ^ S8[GB(x, 0xA)];
        z[1] = x[0] ^ S5[GB(z, 0x7)] ^ S6[GB(z, 0x6)] ^ S7[GB(z, 0x5)] ^ S8[GB(z, 0x4)] ^ S5[GB(x, 0x9)];
        z[0] = x[2] ^ S5[GB(z, 0xA)] ^ S6[GB(z, 0x9)] ^ S7[GB(z, 0xb)] ^ S8[GB(z, 0x8)] ^ S6[GB(x, 0xB)];
        skey->cast5.K[i++] = S5[GB(z, 0x8)] ^ S6[GB(z, 0x9)] ^ S7[GB(z, 0x7)] ^ S8[GB(z, 0x6)] ^ S5[GB(z, 0x2)];
        skey->cast5.K[i++] = S5[GB(z, 0xA)] ^ S6[GB(z, 0xB)] ^ S7[GB(z, 0x5)] ^ S8[GB(z, 0x4)] ^ S6[GB(z, 0x6)];
        skey->cast5.K[i++] = S5[GB(z, 0xC)] ^ S6[GB(z, 0xd)] ^ S7[GB(z, 0x3)] ^ S8[GB(z, 0x2)] ^ S7[GB(z, 0x9)];
        skey->cast5.K[i++] = S5[GB(z, 0xE)] ^ S6[GB(z, 0xF)] ^ S7[GB(z, 0x1)] ^ S8[GB(z, 0x0)] ^ S8[GB(z, 0xc)];

        x[3] = z[1] ^ S5[GB(z, 0x5)] ^ S6[GB(z, 0x7)] ^ S7[GB(z, 0x4)] ^ S8[GB(z, 0x6)] ^ S7[GB(z, 0x0)];
        x[2] = z[3] ^ S5[GB(x, 0x0)] ^ S6[GB(x, 0x2)] ^ S7[GB(x, 0x1)] ^ S8[GB(x, 0x3)] ^ S8[GB(z, 0x2)];
        x[1] = z[2] ^ S5[GB(x, 0x7)] ^ S6[GB(x, 0x6)] ^ S7[GB(x, 0x5)] ^ S8[GB(x, 0x4)] ^ S5[GB(z, 0x1)];
        x[0] = z[0] ^ S5[GB(x, 0xA)] ^ S6[GB(x, 0x9)] ^ S7[GB(x, 0xb)] ^ S8[GB(x, 0x8)] ^ S6[GB(z, 0x3)];
        skey->cast5.K[i++] = S5[GB(x, 0x3)] ^ S6[GB(x, 0x2)] ^ S7[GB(x, 0xc)] ^ S8[GB(x, 0xd)] ^ S5[GB(x, 0x8)];
        skey->cast5.K[i++] = S5[GB(x, 0x1)] ^ S6[GB(x, 0x0)] ^ S7[GB(x, 0xe)] ^ S8[GB(x, 0xf)] ^ S6[GB(x, 0xd)];
        skey->cast5.K[i++] = S5[GB(x, 0x7)] ^ S6[GB(x, 0x6)] ^ S7[GB(x, 0x8)] ^ S8[GB(x, 0x9)] ^ S7[GB(x, 0x3)];
        skey->cast5.K[i++] = S5[GB(x, 0x5)] ^ S6[GB(x, 0x4)] ^ S7[GB(x, 0xa)] ^ S8[GB(x, 0xb)] ^ S8[GB(x, 0x7)];

        /* second half */
        z[3] = x[3] ^ S5[GB(x, 0xD)] ^ S6[GB(x, 0xF)] ^ S7[GB(x, 0xC)] ^ S8[GB(x, 0xE)] ^ S7[GB(x, 0x8)];
        z[2] = x[1] ^ S5[GB(z, 0x0)] ^ S6[GB(z, 0x2)] ^ S7[GB(z, 0x1)] ^ S8[GB(z, 0x3)] ^ S8[GB(x, 0xA)];
        z[1] = x[0] ^ S5[GB(z, 0x7)] ^ S6[GB(z, 0x6)] ^ S7[GB(z, 0x5)] ^ S8[GB(z, 0x4)] ^ S5[GB(x, 0x9)];
        z[0] = x[2] ^ S5[GB(z, 0xA)] ^ S6[GB(z, 0x9)] ^ S7[GB(z, 0xb)] ^ S8[GB(z, 0x8)] ^ S6[GB(x, 0xB)];
        skey->cast5.K[i++] = S5[GB(z, 0x3)] ^ S6[GB(z, 0x2)] ^ S7[GB(z, 0xc)] ^ S8[GB(z, 0xd)] ^ S5[GB(z, 0x9)];
        skey->cast5.K[i++] = S5[GB(z, 0x1)] ^ S6[GB(z, 0x0)] ^ S7[GB(z, 0xe)] ^ S8[GB(z, 0xf)] ^ S6[GB(z, 0xc)];
        skey->cast5.K[i++] = S5[GB(z, 0x7)] ^ S6[GB(z, 0x6)] ^ S7[GB(z, 0x8)] ^ S8[GB(z, 0x9)] ^ S7[GB(z, 0x2)];
        skey->cast5.K[i++] = S5[GB(z, 0x5)] ^ S6[GB(z, 0x4)] ^ S7[GB(z, 0xa)] ^ S8[GB(z, 0xb)] ^ S8[GB(z, 0x6)];

        x[3] = z[1] ^ S5[GB(z, 0x5)] ^ S6[GB(z, 0x7)] ^ S7[GB(z, 0x4)] ^ S8[GB(z, 0x6)] ^ S7[GB(z, 0x0)];
        x[2] = z[3] ^ S5[GB(x, 0x0)] ^ S6[GB(x, 0x2)] ^ S7[GB(x, 0x1)] ^ S8[GB(x, 0x3)] ^ S8[GB(z, 0x2)];
        x[1] = z[2] ^ S5[GB(x, 0x7)] ^ S6[GB(x, 0x6)] ^ S7[GB(x, 0x5)] ^ S8[GB(x, 0x4)] ^ S5[GB(z, 0x1)];
        x[0] = z[0] ^ S5[GB(x, 0xA)] ^ S6[GB(x, 0x9)] ^ S7[GB(x, 0xb)] ^ S8[GB(x, 0x8)] ^ S6[GB(z, 0x3)];
        skey->cast5.K[i++] = S5[GB(x, 0x8)] ^ S6[GB(x, 0x9)] ^ S7[GB(x, 0x7)] ^ S8[GB(x, 0x6)] ^ S5[GB(x, 0x3)];
        skey->cast5.K[i++] = S5[GB(x, 0xa)] ^ S6[GB(x, 0xb)] ^ S7[GB(x, 0x5)] ^ S8[GB(x, 0x4)] ^ S6[GB(x, 0x7)];
        skey->cast5.K[i++] = S5[GB(x, 0xc)] ^ S6[GB(x, 0xd)] ^ S7[GB(x, 0x3)] ^ S8[GB(x, 0x2)] ^ S7[GB(x, 0x8)];
        skey->cast5.K[i++] = S5[GB(x, 0xe)] ^ S6[GB(x, 0xf)] ^ S7[GB(x, 0x1)] ^ S8[GB(x, 0x0)] ^ S8[GB(x, 0xd)];
   }

   skey->cast5.keylen = keylen;

#ifdef LTC_CLEAN_STACK
   zeromem(buf, sizeof(buf));
   zeromem(x, sizeof(x));
   zeromem(z, sizeof(z));
#endif  

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
int cast5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
{
   int z;
   z = _cast5_setup(key, keylen, num_rounds, skey);
   burn_stack(sizeof(ulong32)*8 + 16 + sizeof(int)*2);
   return z;
}
#endif

#ifdef _MSC_VER
   #define INLINE __inline
#else
   #define INLINE 
#endif   
   
INLINE static ulong32 FI(ulong32 R, ulong32 Km, ulong32 Kr)
{
   ulong32 I;
   I = (Km + R);
   I = ROL(I, Kr);
   return ((S1[byte(I, 3)] ^ S2[byte(I,2)]) - S3[byte(I,1)]) + S4[byte(I,0)];
}
   
INLINE static ulong32 FII(ulong32 R, ulong32 Km, ulong32 Kr)
{
   ulong32 I;
   I = (Km ^ R);
   I = ROL(I, Kr);
   return ((S1[byte(I, 3)] - S2[byte(I,2)]) + S3[byte(I,1)]) ^ S4[byte(I,0)];
}

INLINE static ulong32 FIII(ulong32 R, ulong32 Km, ulong32 Kr)
{
   ulong32 I;
   I = (Km - R);
   I = ROL(I, Kr);
   return ((S1[byte(I, 3)] + S2[byte(I,2)]) ^ S3[byte(I,1)]) - S4[byte(I,0)];
}

/**
  Encrypts a block of text with LTC_CAST5
  @param pt The input plaintext (8 bytes)
  @param ct The output ciphertext (8 bytes)
  @param skey The key as scheduled
*/
#ifdef LTC_CLEAN_STACK
static int _cast5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
#else
int cast5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
#endif
{
   ulong32 R, L;

   LTC_ARGCHK(pt   != NULL);
   LTC_ARGCHK(ct   != NULL);
   LTC_ARGCHK(skey != NULL);

   LOAD32H(L,&pt[0]); 
   LOAD32H(R,&pt[4]);
   L ^= FI(R, skey->cast5.K[0], skey->cast5.K[16]);
   R ^= FII(L, skey->cast5.K[1], skey->cast5.K[17]);
   L ^= FIII(R, skey->cast5.K[2], skey->cast5.K[18]);
   R ^= FI(L, skey->cast5.K[3], skey->cast5.K[19]);
   L ^= FII(R, skey->cast5.K[4], skey->cast5.K[20]);
   R ^= FIII(L, skey->cast5.K[5], skey->cast5.K[21]);
   L ^= FI(R, skey->cast5.K[6], skey->cast5.K[22]);
   R ^= FII(L, skey->cast5.K[7], skey->cast5.K[23]);
   L ^= FIII(R, skey->cast5.K[8], skey->cast5.K[24]);
   R ^= FI(L, skey->cast5.K[9], skey->cast5.K[25]);
   L ^= FII(R, skey->cast5.K[10], skey->cast5.K[26]);
   R ^= FIII(L, skey->cast5.K[11], skey->cast5.K[27]);
   if (skey->cast5.keylen > 10) {
      L ^= FI(R, skey->cast5.K[12], skey->cast5.K[28]);
      R ^= FII(L, skey->cast5.K[13], skey->cast5.K[29]);
      L ^= FIII(R, skey->cast5.K[14], skey->cast5.K[30]);
      R ^= FI(L, skey->cast5.K[15], skey->cast5.K[31]);
   }
   STORE32H(R,&ct[0]);
   STORE32H(L,&ct[4]);
   return CRYPT_OK;
}


#ifdef LTC_CLEAN_STACK
int cast5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
{
   int err =_cast5_ecb_encrypt(pt,ct,skey);
   burn_stack(sizeof(ulong32)*3);
   return err;
}
#endif

/**
  Decrypts a block of text with LTC_CAST5
  @param ct The input ciphertext (8 bytes)
  @param pt The output plaintext (8 bytes)
  @param skey The key as scheduled 
*/
#ifdef LTC_CLEAN_STACK
static int _cast5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
#else
int cast5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
#endif
{
   ulong32 R, L;

   LTC_ARGCHK(pt   != NULL);
   LTC_ARGCHK(ct   != NULL);
   LTC_ARGCHK(skey != NULL);

   LOAD32H(R,&ct[0]); 
   LOAD32H(L,&ct[4]);
   if (skey->cast5.keylen > 10) {
      R ^= FI(L, skey->cast5.K[15], skey->cast5.K[31]);
      L ^= FIII(R, skey->cast5.K[14], skey->cast5.K[30]);
      R ^= FII(L, skey->cast5.K[13], skey->cast5.K[29]);
      L ^= FI(R, skey->cast5.K[12], skey->cast5.K[28]);
   }
   R ^= FIII(L, skey->cast5.K[11], skey->cast5.K[27]);
   L ^= FII(R, skey->cast5.K[10], skey->cast5.K[26]);
   R ^= FI(L, skey->cast5.K[9], skey->cast5.K[25]);
   L ^= FIII(R, skey->cast5.K[8], skey->cast5.K[24]);
   R ^= FII(L, skey->cast5.K[7], skey->cast5.K[23]);
   L ^= FI(R, skey->cast5.K[6], skey->cast5.K[22]);
   R ^= FIII(L, skey->cast5.K[5], skey->cast5.K[21]);
   L ^= FII(R, skey->cast5.K[4], skey->cast5.K[20]);
   R ^= FI(L, skey->cast5.K[3], skey->cast5.K[19]);
   L ^= FIII(R, skey->cast5.K[2], skey->cast5.K[18]);
   R ^= FII(L, skey->cast5.K[1], skey->cast5.K[17]);
   L ^= FI(R, skey->cast5.K[0], skey->cast5.K[16]);
   STORE32H(L,&pt[0]);
   STORE32H(R,&pt[4]);

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
int cast5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
{
   int err = _cast5_ecb_decrypt(ct,pt,skey);
   burn_stack(sizeof(ulong32)*3);
   return err;
}
#endif

/**
  Performs a self-test of the LTC_CAST5 block cipher
  @return CRYPT_OK if functional, CRYPT_NOP if self-test has been disabled
*/
int cast5_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
   static const struct {
       int keylen;
       unsigned char key[16];
       unsigned char pt[8];
       unsigned char ct[8];
   } tests[] = {
     { 16,
       {0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78, 0x23, 0x45, 0x67, 0x89, 0x34, 0x56, 0x78, 0x9A},
       {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
       {0x23, 0x8B, 0x4F, 0xE5, 0x84, 0x7E, 0x44, 0xB2}
     },
     { 10,
       {0x01, 0x23, 0x45, 0x67, 0x12, 0x34, 0x56, 0x78, 0x23, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
       {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
       {0xEB, 0x6A, 0x71, 0x1A, 0x2C, 0x02, 0x27, 0x1B},
     },
     { 5,
       {0x01, 0x23, 0x45, 0x67, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
       {0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF},
       {0x7A, 0xC8, 0x16, 0xD1, 0x6E, 0x9B, 0x30, 0x2E}
     }
   };
   int i, y, err;
   symmetric_key key;
   unsigned char tmp[2][8];

   for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
       if ((err = cast5_setup(tests[i].key, tests[i].keylen, 0, &key)) != CRYPT_OK) {
          return err;
       }
       cast5_ecb_encrypt(tests[i].pt, tmp[0], &key);
       cast5_ecb_decrypt(tmp[0], tmp[1], &key);
       if ((XMEMCMP(tmp[0], tests[i].ct, 8) != 0) || (XMEMCMP(tmp[1], tests[i].pt, 8) != 0)) {
          return CRYPT_FAIL_TESTVECTOR;
       }
      /* now see if we can encrypt all zero bytes 1000 times, decrypt and come back where we started */
      for (y = 0; y < 8; y++) tmp[0][y] = 0;
      for (y = 0; y < 1000; y++) cast5_ecb_encrypt(tmp[0], tmp[0], &key);
      for (y = 0; y < 1000; y++) cast5_ecb_decrypt(tmp[0], tmp[0], &key);
      for (y = 0; y < 8; y++) if (tmp[0][y] != 0) return CRYPT_FAIL_TESTVECTOR;
   
   }
   return CRYPT_OK;
 #endif
}

/** Terminate the context 
   @param skey    The scheduled key
*/
void cast5_done(symmetric_key *skey)
{
}

/**
  Gets suitable key size
  @param keysize [in/out] The length of the recommended key (in bytes).  This function will store the suitable size back in this variable.
  @return CRYPT_OK if the input key size is acceptable.
*/
int cast5_keysize(int *keysize)
{
   LTC_ARGCHK(keysize != NULL);
   if (*keysize < 5) {
      return CRYPT_INVALID_KEYSIZE;
   } else if (*keysize > 16) {
      *keysize = 16;
   }
   return CRYPT_OK;
} 

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/ciphers/cast5.c,v $ */
/* $Revision: 1.14 $ */
/* $Date: 2007/05/12 14:13:00 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/des.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/** 
  @file des.c
  LTC_DES code submitted by Dobes Vandermeer 
*/

#ifdef LTC_DES

#define LTC_SMALL_CODE 1 /* Do IP/FP as geometics transforms */

#define EN0 0 
#define DE1 1

const struct ltc_cipher_descriptor des_desc =
{
    "des",
    13,
    8, 8, 8, 16,
    &des_setup,
    &des_ecb_encrypt,
    &des_ecb_decrypt,
    &des_test,
    &des_done,
    &des_keysize,
    /* ECB Accelerators */
    NULL, NULL, 
    /* CBC Accelerators */
    NULL, NULL,
    /* CTR Accelerators */
    NULL, 
    /* LRW Accelerators */
    NULL, NULL,
    /* XTS Accelerators */
    NULL, NULL,
    /* CCM Accelerator */
    NULL, 
    /* GCM Accelerator */
    NULL, 
    /* OMAC Accelerator */
    NULL,
    /* XCBC Accelerator */
    NULL, 
    /* F9 Accelerator */
    NULL
};

const struct ltc_cipher_descriptor des3_desc =
{
    "3des",
    14,
    24, 24, 8, 16,
    &des3_setup,
    &des3_ecb_encrypt,
    &des3_ecb_decrypt,
    &des3_test,
    &des3_done,
    &des3_keysize,
    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};

static const ulong32 bytebit[8] =
{
    0200, 0100, 040, 020, 010, 04, 02, 01 
};

static const ulong32 bigbyte[24] =
{
    0x800000UL,  0x400000UL,  0x200000UL,  0x100000UL,
    0x80000UL,   0x40000UL,   0x20000UL,   0x10000UL,
    0x8000UL,    0x4000UL,    0x2000UL,    0x1000UL,
    0x800UL,     0x400UL,     0x200UL,     0x100UL,
    0x80UL,      0x40UL,      0x20UL,      0x10UL,
    0x8UL,       0x4UL,       0x2UL,       0x1L 
};

/* Use the key schedule specific in the standard (ANSI X3.92-1981) */

static const unsigned char pc1[56] = {
    56, 48, 40, 32, 24, 16,  8,  0, 57, 49, 41, 33, 25, 17,  
     9,  1, 58, 50, 42, 34, 26, 18, 10,  2, 59, 51, 43, 35, 
    62, 54, 46, 38, 30, 22, 14,  6, 61, 53, 45, 37, 29, 21,
    13,  5, 60, 52, 44, 36, 28, 20, 12,  4, 27, 19, 11,  3 
};

static const unsigned char totrot[16] = {
    1,   2,  4,  6,
    8,  10, 12, 14, 
    15, 17, 19, 21, 
    23, 25, 27, 28
};

static const unsigned char pc2[48] = {
    13, 16, 10, 23,  0,  4,      2, 27, 14,  5, 20,  9,
    22, 18, 11,  3, 25,  7,     15,  6, 26, 19, 12,  1,
    40, 51, 30, 36, 46, 54,     29, 39, 50, 44, 32, 47,
    43, 48, 38, 55, 33, 52,     45, 41, 49, 35, 28, 31
};


static const ulong32 SP1[64] =
{
    0x01010400UL, 0x00000000UL, 0x00010000UL, 0x01010404UL,
    0x01010004UL, 0x00010404UL, 0x00000004UL, 0x00010000UL,
    0x00000400UL, 0x01010400UL, 0x01010404UL, 0x00000400UL,
    0x01000404UL, 0x01010004UL, 0x01000000UL, 0x00000004UL,
    0x00000404UL, 0x01000400UL, 0x01000400UL, 0x00010400UL,
    0x00010400UL, 0x01010000UL, 0x01010000UL, 0x01000404UL,
    0x00010004UL, 0x01000004UL, 0x01000004UL, 0x00010004UL,
    0x00000000UL, 0x00000404UL, 0x00010404UL, 0x01000000UL,
    0x00010000UL, 0x01010404UL, 0x00000004UL, 0x01010000UL,
    0x01010400UL, 0x01000000UL, 0x01000000UL, 0x00000400UL,
    0x01010004UL, 0x00010000UL, 0x00010400UL, 0x01000004UL,
    0x00000400UL, 0x00000004UL, 0x01000404UL, 0x00010404UL,
    0x01010404UL, 0x00010004UL, 0x01010000UL, 0x01000404UL,
    0x01000004UL, 0x00000404UL, 0x00010404UL, 0x01010400UL,
    0x00000404UL, 0x01000400UL, 0x01000400UL, 0x00000000UL,
    0x00010004UL, 0x00010400UL, 0x00000000UL, 0x01010004UL
};

static const ulong32 SP2[64] =
{
    0x80108020UL, 0x80008000UL, 0x00008000UL, 0x00108020UL,
    0x00100000UL, 0x00000020UL, 0x80100020UL, 0x80008020UL,
    0x80000020UL, 0x80108020UL, 0x80108000UL, 0x80000000UL,
    0x80008000UL, 0x00100000UL, 0x00000020UL, 0x80100020UL,
    0x00108000UL, 0x00100020UL, 0x80008020UL, 0x00000000UL,
    0x80000000UL, 0x00008000UL, 0x00108020UL, 0x80100000UL,
    0x00100020UL, 0x80000020UL, 0x00000000UL, 0x00108000UL,
    0x00008020UL, 0x80108000UL, 0x80100000UL, 0x00008020UL,
    0x00000000UL, 0x00108020UL, 0x80100020UL, 0x00100000UL,
    0x80008020UL, 0x80100000UL, 0x80108000UL, 0x00008000UL,
    0x80100000UL, 0x80008000UL, 0x00000020UL, 0x80108020UL,
    0x00108020UL, 0x00000020UL, 0x00008000UL, 0x80000000UL,
    0x00008020UL, 0x80108000UL, 0x00100000UL, 0x80000020UL,
    0x00100020UL, 0x80008020UL, 0x80000020UL, 0x00100020UL,
    0x00108000UL, 0x00000000UL, 0x80008000UL, 0x00008020UL,
    0x80000000UL, 0x80100020UL, 0x80108020UL, 0x00108000UL
};

static const ulong32 SP3[64] =
{
    0x00000208UL, 0x08020200UL, 0x00000000UL, 0x08020008UL,
    0x08000200UL, 0x00000000UL, 0x00020208UL, 0x08000200UL,
    0x00020008UL, 0x08000008UL, 0x08000008UL, 0x00020000UL,
    0x08020208UL, 0x00020008UL, 0x08020000UL, 0x00000208UL,
    0x08000000UL, 0x00000008UL, 0x08020200UL, 0x00000200UL,
    0x00020200UL, 0x08020000UL, 0x08020008UL, 0x00020208UL,
    0x08000208UL, 0x00020200UL, 0x00020000UL, 0x08000208UL,
    0x00000008UL, 0x08020208UL, 0x00000200UL, 0x08000000UL,
    0x08020200UL, 0x08000000UL, 0x00020008UL, 0x00000208UL,
    0x00020000UL, 0x08020200UL, 0x08000200UL, 0x00000000UL,
    0x00000200UL, 0x00020008UL, 0x08020208UL, 0x08000200UL,
    0x08000008UL, 0x00000200UL, 0x00000000UL, 0x08020008UL,
    0x08000208UL, 0x00020000UL, 0x08000000UL, 0x08020208UL,
    0x00000008UL, 0x00020208UL, 0x00020200UL, 0x08000008UL,
    0x08020000UL, 0x08000208UL, 0x00000208UL, 0x08020000UL,
    0x00020208UL, 0x00000008UL, 0x08020008UL, 0x00020200UL
};

static const ulong32 SP4[64] =
{
    0x00802001UL, 0x00002081UL, 0x00002081UL, 0x00000080UL,
    0x00802080UL, 0x00800081UL, 0x00800001UL, 0x00002001UL,
    0x00000000UL, 0x00802000UL, 0x00802000UL, 0x00802081UL,
    0x00000081UL, 0x00000000UL, 0x00800080UL, 0x00800001UL,
    0x00000001UL, 0x00002000UL, 0x00800000UL, 0x00802001UL,
    0x00000080UL, 0x00800000UL, 0x00002001UL, 0x00002080UL,
    0x00800081UL, 0x00000001UL, 0x00002080UL, 0x00800080UL,
    0x00002000UL, 0x00802080UL, 0x00802081UL, 0x00000081UL,
    0x00800080UL, 0x00800001UL, 0x00802000UL, 0x00802081UL,
    0x00000081UL, 0x00000000UL, 0x00000000UL, 0x00802000UL,
    0x00002080UL, 0x00800080UL, 0x00800081UL, 0x00000001UL,
    0x00802001UL, 0x00002081UL, 0x00002081UL, 0x00000080UL,
    0x00802081UL, 0x00000081UL, 0x00000001UL, 0x00002000UL,
    0x00800001UL, 0x00002001UL, 0x00802080UL, 0x00800081UL,
    0x00002001UL, 0x00002080UL, 0x00800000UL, 0x00802001UL,
    0x00000080UL, 0x00800000UL, 0x00002000UL, 0x00802080UL
};

static const ulong32 SP5[64] =
{
    0x00000100UL, 0x02080100UL, 0x02080000UL, 0x42000100UL,
    0x00080000UL, 0x00000100UL, 0x40000000UL, 0x02080000UL,
    0x40080100UL, 0x00080000UL, 0x02000100UL, 0x40080100UL,
    0x42000100UL, 0x42080000UL, 0x00080100UL, 0x40000000UL,
    0x02000000UL, 0x40080000UL, 0x40080000UL, 0x00000000UL,
    0x40000100UL, 0x42080100UL, 0x42080100UL, 0x02000100UL,
    0x42080000UL, 0x40000100UL, 0x00000000UL, 0x42000000UL,
    0x02080100UL, 0x02000000UL, 0x42000000UL, 0x00080100UL,
    0x00080000UL, 0x42000100UL, 0x00000100UL, 0x02000000UL,
    0x40000000UL, 0x02080000UL, 0x42000100UL, 0x40080100UL,
    0x02000100UL, 0x40000000UL, 0x42080000UL, 0x02080100UL,
    0x40080100UL, 0x00000100UL, 0x02000000UL, 0x42080000UL,
    0x42080100UL, 0x00080100UL, 0x42000000UL, 0x42080100UL,
    0x02080000UL, 0x00000000UL, 0x40080000UL, 0x42000000UL,
    0x00080100UL, 0x02000100UL, 0x40000100UL, 0x00080000UL,
    0x00000000UL, 0x40080000UL, 0x02080100UL, 0x40000100UL
};

static const ulong32 SP6[64] =
{
    0x20000010UL, 0x20400000UL, 0x00004000UL, 0x20404010UL,
    0x20400000UL, 0x00000010UL, 0x20404010UL, 0x00400000UL,
    0x20004000UL, 0x00404010UL, 0x00400000UL, 0x20000010UL,
    0x00400010UL, 0x20004000UL, 0x20000000UL, 0x00004010UL,
    0x00000000UL, 0x00400010UL, 0x20004010UL, 0x00004000UL,
    0x00404000UL, 0x20004010UL, 0x00000010UL, 0x20400010UL,
    0x20400010UL, 0x00000000UL, 0x00404010UL, 0x20404000UL,
    0x00004010UL, 0x00404000UL, 0x20404000UL, 0x20000000UL,
    0x20004000UL, 0x00000010UL, 0x20400010UL, 0x00404000UL,
    0x20404010UL, 0x00400000UL, 0x00004010UL, 0x20000010UL,
    0x00400000UL, 0x20004000UL, 0x20000000UL, 0x00004010UL,
    0x20000010UL, 0x20404010UL, 0x00404000UL, 0x20400000UL,
    0x00404010UL, 0x20404000UL, 0x00000000UL, 0x20400010UL,
    0x00000010UL, 0x00004000UL, 0x20400000UL, 0x00404010UL,
    0x00004000UL, 0x00400010UL, 0x20004010UL, 0x00000000UL,
    0x20404000UL, 0x20000000UL, 0x00400010UL, 0x20004010UL
};

static const ulong32 SP7[64] =
{
    0x00200000UL, 0x04200002UL, 0x04000802UL, 0x00000000UL,
    0x00000800UL, 0x04000802UL, 0x00200802UL, 0x04200800UL,
    0x04200802UL, 0x00200000UL, 0x00000000UL, 0x04000002UL,
    0x00000002UL, 0x04000000UL, 0x04200002UL, 0x00000802UL,
    0x04000800UL, 0x00200802UL, 0x00200002UL, 0x04000800UL,
    0x04000002UL, 0x04200000UL, 0x04200800UL, 0x00200002UL,
    0x04200000UL, 0x00000800UL, 0x00000802UL, 0x04200802UL,
    0x00200800UL, 0x00000002UL, 0x04000000UL, 0x00200800UL,
    0x04000000UL, 0x00200800UL, 0x00200000UL, 0x04000802UL,
    0x04000802UL, 0x04200002UL, 0x04200002UL, 0x00000002UL,
    0x00200002UL, 0x04000000UL, 0x04000800UL, 0x00200000UL,
    0x04200800UL, 0x00000802UL, 0x00200802UL, 0x04200800UL,
    0x00000802UL, 0x04000002UL, 0x04200802UL, 0x04200000UL,
    0x00200800UL, 0x00000000UL, 0x00000002UL, 0x04200802UL,
    0x00000000UL, 0x00200802UL, 0x04200000UL, 0x00000800UL,
    0x04000002UL, 0x04000800UL, 0x00000800UL, 0x00200002UL
};

static const ulong32 SP8[64] =
{
    0x10001040UL, 0x00001000UL, 0x00040000UL, 0x10041040UL,
    0x10000000UL, 0x10001040UL, 0x00000040UL, 0x10000000UL,
    0x00040040UL, 0x10040000UL, 0x10041040UL, 0x00041000UL,
    0x10041000UL, 0x00041040UL, 0x00001000UL, 0x00000040UL,
    0x10040000UL, 0x10000040UL, 0x10001000UL, 0x00001040UL,
    0x00041000UL, 0x00040040UL, 0x10040040UL, 0x10041000UL,
    0x00001040UL, 0x00000000UL, 0x00000000UL, 0x10040040UL,
    0x10000040UL, 0x10001000UL, 0x00041040UL, 0x00040000UL,
    0x00041040UL, 0x00040000UL, 0x10041000UL, 0x00001000UL,
    0x00000040UL, 0x10040040UL, 0x00001000UL, 0x00041040UL,
    0x10001000UL, 0x00000040UL, 0x10000040UL, 0x10040000UL,
    0x10040040UL, 0x10000000UL, 0x00040000UL, 0x10001040UL,
    0x00000000UL, 0x10041040UL, 0x00040040UL, 0x10000040UL,
    0x10040000UL, 0x10001000UL, 0x10001040UL, 0x00000000UL,
    0x10041040UL, 0x00041000UL, 0x00041000UL, 0x00001040UL,
    0x00001040UL, 0x00040040UL, 0x10000000UL, 0x10041000UL
};

#ifndef LTC_SMALL_CODE

static const ulong64 des_ip[8][256] = {

{ CONST64(0x0000000000000000), CONST64(0x0000001000000000), CONST64(0x0000000000000010), CONST64(0x0000001000000010), 
  CONST64(0x0000100000000000), CONST64(0x0000101000000000), CONST64(0x0000100000000010), CONST64(0x0000101000000010), 
  CONST64(0x0000000000001000), CONST64(0x0000001000001000), CONST64(0x0000000000001010), CONST64(0x0000001000001010), 
  CONST64(0x0000100000001000), CONST64(0x0000101000001000), CONST64(0x0000100000001010), CONST64(0x0000101000001010), 
  CONST64(0x0010000000000000), CONST64(0x0010001000000000), CONST64(0x0010000000000010), CONST64(0x0010001000000010), 
  CONST64(0x0010100000000000), CONST64(0x0010101000000000), CONST64(0x0010100000000010), CONST64(0x0010101000000010), 
  CONST64(0x0010000000001000), CONST64(0x0010001000001000), CONST64(0x0010000000001010), CONST64(0x0010001000001010), 
  CONST64(0x0010100000001000), CONST64(0x0010101000001000), CONST64(0x0010100000001010), CONST64(0x0010101000001010), 
  CONST64(0x0000000000100000), CONST64(0x0000001000100000), CONST64(0x0000000000100010), CONST64(0x0000001000100010), 
  CONST64(0x0000100000100000), CONST64(0x0000101000100000), CONST64(0x0000100000100010), CONST64(0x0000101000100010), 
  CONST64(0x0000000000101000), CONST64(0x0000001000101000), CONST64(0x0000000000101010), CONST64(0x0000001000101010), 
  CONST64(0x0000100000101000), CONST64(0x0000101000101000), CONST64(0x0000100000101010), CONST64(0x0000101000101010), 
  CONST64(0x0010000000100000), CONST64(0x0010001000100000), CONST64(0x0010000000100010), CONST64(0x0010001000100010), 
  CONST64(0x0010100000100000), CONST64(0x0010101000100000), CONST64(0x0010100000100010), CONST64(0x0010101000100010), 
  CONST64(0x0010000000101000), CONST64(0x0010001000101000), CONST64(0x0010000000101010), CONST64(0x0010001000101010), 
  CONST64(0x0010100000101000), CONST64(0x0010101000101000), CONST64(0x0010100000101010), CONST64(0x0010101000101010), 
  CONST64(0x1000000000000000), CONST64(0x1000001000000000), CONST64(0x1000000000000010), CONST64(0x1000001000000010), 
  CONST64(0x1000100000000000), CONST64(0x1000101000000000), CONST64(0x1000100000000010), CONST64(0x1000101000000010), 
  CONST64(0x1000000000001000), CONST64(0x1000001000001000), CONST64(0x1000000000001010), CONST64(0x1000001000001010), 
  CONST64(0x1000100000001000), CONST64(0x1000101000001000), CONST64(0x1000100000001010), CONST64(0x1000101000001010), 
  CONST64(0x1010000000000000), CONST64(0x1010001000000000), CONST64(0x1010000000000010), CONST64(0x1010001000000010), 
  CONST64(0x1010100000000000), CONST64(0x1010101000000000), CONST64(0x1010100000000010), CONST64(0x1010101000000010), 
  CONST64(0x1010000000001000), CONST64(0x1010001000001000), CONST64(0x1010000000001010), CONST64(0x1010001000001010), 
  CONST64(0x1010100000001000), CONST64(0x1010101000001000), CONST64(0x1010100000001010), CONST64(0x1010101000001010), 
  CONST64(0x1000000000100000), CONST64(0x1000001000100000), CONST64(0x1000000000100010), CONST64(0x1000001000100010), 
  CONST64(0x1000100000100000), CONST64(0x1000101000100000), CONST64(0x1000100000100010), CONST64(0x1000101000100010), 
  CONST64(0x1000000000101000), CONST64(0x1000001000101000), CONST64(0x1000000000101010), CONST64(0x1000001000101010), 
  CONST64(0x1000100000101000), CONST64(0x1000101000101000), CONST64(0x1000100000101010), CONST64(0x1000101000101010), 
  CONST64(0x1010000000100000), CONST64(0x1010001000100000), CONST64(0x1010000000100010), CONST64(0x1010001000100010), 
  CONST64(0x1010100000100000), CONST64(0x1010101000100000), CONST64(0x1010100000100010), CONST64(0x1010101000100010), 
  CONST64(0x1010000000101000), CONST64(0x1010001000101000), CONST64(0x1010000000101010), CONST64(0x1010001000101010), 
  CONST64(0x1010100000101000), CONST64(0x1010101000101000), CONST64(0x1010100000101010), CONST64(0x1010101000101010), 
  CONST64(0x0000000010000000), CONST64(0x0000001010000000), CONST64(0x0000000010000010), CONST64(0x0000001010000010), 
  CONST64(0x0000100010000000), CONST64(0x0000101010000000), CONST64(0x0000100010000010), CONST64(0x0000101010000010), 
  CONST64(0x0000000010001000), CONST64(0x0000001010001000), CONST64(0x0000000010001010), CONST64(0x0000001010001010), 
  CONST64(0x0000100010001000), CONST64(0x0000101010001000), CONST64(0x0000100010001010), CONST64(0x0000101010001010), 
  CONST64(0x0010000010000000), CONST64(0x0010001010000000), CONST64(0x0010000010000010), CONST64(0x0010001010000010), 
  CONST64(0x0010100010000000), CONST64(0x0010101010000000), CONST64(0x0010100010000010), CONST64(0x0010101010000010), 
  CONST64(0x0010000010001000), CONST64(0x0010001010001000), CONST64(0x0010000010001010), CONST64(0x0010001010001010), 
  CONST64(0x0010100010001000), CONST64(0x0010101010001000), CONST64(0x0010100010001010), CONST64(0x0010101010001010), 
  CONST64(0x0000000010100000), CONST64(0x0000001010100000), CONST64(0x0000000010100010), CONST64(0x0000001010100010), 
  CONST64(0x0000100010100000), CONST64(0x0000101010100000), CONST64(0x0000100010100010), CONST64(0x0000101010100010), 
  CONST64(0x0000000010101000), CONST64(0x0000001010101000), CONST64(0x0000000010101010), CONST64(0x0000001010101010), 
  CONST64(0x0000100010101000), CONST64(0x0000101010101000), CONST64(0x0000100010101010), CONST64(0x0000101010101010), 
  CONST64(0x0010000010100000), CONST64(0x0010001010100000), CONST64(0x0010000010100010), CONST64(0x0010001010100010), 
  CONST64(0x0010100010100000), CONST64(0x0010101010100000), CONST64(0x0010100010100010), CONST64(0x0010101010100010), 
  CONST64(0x0010000010101000), CONST64(0x0010001010101000), CONST64(0x0010000010101010), CONST64(0x0010001010101010), 
  CONST64(0x0010100010101000), CONST64(0x0010101010101000), CONST64(0x0010100010101010), CONST64(0x0010101010101010), 
  CONST64(0x1000000010000000), CONST64(0x1000001010000000), CONST64(0x1000000010000010), CONST64(0x1000001010000010), 
  CONST64(0x1000100010000000), CONST64(0x1000101010000000), CONST64(0x1000100010000010), CONST64(0x1000101010000010), 
  CONST64(0x1000000010001000), CONST64(0x1000001010001000), CONST64(0x1000000010001010), CONST64(0x1000001010001010), 
  CONST64(0x1000100010001000), CONST64(0x1000101010001000), CONST64(0x1000100010001010), CONST64(0x1000101010001010), 
  CONST64(0x1010000010000000), CONST64(0x1010001010000000), CONST64(0x1010000010000010), CONST64(0x1010001010000010), 
  CONST64(0x1010100010000000), CONST64(0x1010101010000000), CONST64(0x1010100010000010), CONST64(0x1010101010000010), 
  CONST64(0x1010000010001000), CONST64(0x1010001010001000), CONST64(0x1010000010001010), CONST64(0x1010001010001010), 
  CONST64(0x1010100010001000), CONST64(0x1010101010001000), CONST64(0x1010100010001010), CONST64(0x1010101010001010), 
  CONST64(0x1000000010100000), CONST64(0x1000001010100000), CONST64(0x1000000010100010), CONST64(0x1000001010100010), 
  CONST64(0x1000100010100000), CONST64(0x1000101010100000), CONST64(0x1000100010100010), CONST64(0x1000101010100010), 
  CONST64(0x1000000010101000), CONST64(0x1000001010101000), CONST64(0x1000000010101010), CONST64(0x1000001010101010), 
  CONST64(0x1000100010101000), CONST64(0x1000101010101000), CONST64(0x1000100010101010), CONST64(0x1000101010101010), 
  CONST64(0x1010000010100000), CONST64(0x1010001010100000), CONST64(0x1010000010100010), CONST64(0x1010001010100010), 
  CONST64(0x1010100010100000), CONST64(0x1010101010100000), CONST64(0x1010100010100010), CONST64(0x1010101010100010), 
  CONST64(0x1010000010101000), CONST64(0x1010001010101000), CONST64(0x1010000010101010), CONST64(0x1010001010101010), 
  CONST64(0x1010100010101000), CONST64(0x1010101010101000), CONST64(0x1010100010101010), CONST64(0x1010101010101010)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000000800000000), CONST64(0x0000000000000008), CONST64(0x0000000800000008), 
  CONST64(0x0000080000000000), CONST64(0x0000080800000000), CONST64(0x0000080000000008), CONST64(0x0000080800000008), 
  CONST64(0x0000000000000800), CONST64(0x0000000800000800), CONST64(0x0000000000000808), CONST64(0x0000000800000808), 
  CONST64(0x0000080000000800), CONST64(0x0000080800000800), CONST64(0x0000080000000808), CONST64(0x0000080800000808), 
  CONST64(0x0008000000000000), CONST64(0x0008000800000000), CONST64(0x0008000000000008), CONST64(0x0008000800000008), 
  CONST64(0x0008080000000000), CONST64(0x0008080800000000), CONST64(0x0008080000000008), CONST64(0x0008080800000008), 
  CONST64(0x0008000000000800), CONST64(0x0008000800000800), CONST64(0x0008000000000808), CONST64(0x0008000800000808), 
  CONST64(0x0008080000000800), CONST64(0x0008080800000800), CONST64(0x0008080000000808), CONST64(0x0008080800000808), 
  CONST64(0x0000000000080000), CONST64(0x0000000800080000), CONST64(0x0000000000080008), CONST64(0x0000000800080008), 
  CONST64(0x0000080000080000), CONST64(0x0000080800080000), CONST64(0x0000080000080008), CONST64(0x0000080800080008), 
  CONST64(0x0000000000080800), CONST64(0x0000000800080800), CONST64(0x0000000000080808), CONST64(0x0000000800080808), 
  CONST64(0x0000080000080800), CONST64(0x0000080800080800), CONST64(0x0000080000080808), CONST64(0x0000080800080808), 
  CONST64(0x0008000000080000), CONST64(0x0008000800080000), CONST64(0x0008000000080008), CONST64(0x0008000800080008), 
  CONST64(0x0008080000080000), CONST64(0x0008080800080000), CONST64(0x0008080000080008), CONST64(0x0008080800080008), 
  CONST64(0x0008000000080800), CONST64(0x0008000800080800), CONST64(0x0008000000080808), CONST64(0x0008000800080808), 
  CONST64(0x0008080000080800), CONST64(0x0008080800080800), CONST64(0x0008080000080808), CONST64(0x0008080800080808), 
  CONST64(0x0800000000000000), CONST64(0x0800000800000000), CONST64(0x0800000000000008), CONST64(0x0800000800000008), 
  CONST64(0x0800080000000000), CONST64(0x0800080800000000), CONST64(0x0800080000000008), CONST64(0x0800080800000008), 
  CONST64(0x0800000000000800), CONST64(0x0800000800000800), CONST64(0x0800000000000808), CONST64(0x0800000800000808), 
  CONST64(0x0800080000000800), CONST64(0x0800080800000800), CONST64(0x0800080000000808), CONST64(0x0800080800000808), 
  CONST64(0x0808000000000000), CONST64(0x0808000800000000), CONST64(0x0808000000000008), CONST64(0x0808000800000008), 
  CONST64(0x0808080000000000), CONST64(0x0808080800000000), CONST64(0x0808080000000008), CONST64(0x0808080800000008), 
  CONST64(0x0808000000000800), CONST64(0x0808000800000800), CONST64(0x0808000000000808), CONST64(0x0808000800000808), 
  CONST64(0x0808080000000800), CONST64(0x0808080800000800), CONST64(0x0808080000000808), CONST64(0x0808080800000808), 
  CONST64(0x0800000000080000), CONST64(0x0800000800080000), CONST64(0x0800000000080008), CONST64(0x0800000800080008), 
  CONST64(0x0800080000080000), CONST64(0x0800080800080000), CONST64(0x0800080000080008), CONST64(0x0800080800080008), 
  CONST64(0x0800000000080800), CONST64(0x0800000800080800), CONST64(0x0800000000080808), CONST64(0x0800000800080808), 
  CONST64(0x0800080000080800), CONST64(0x0800080800080800), CONST64(0x0800080000080808), CONST64(0x0800080800080808), 
  CONST64(0x0808000000080000), CONST64(0x0808000800080000), CONST64(0x0808000000080008), CONST64(0x0808000800080008), 
  CONST64(0x0808080000080000), CONST64(0x0808080800080000), CONST64(0x0808080000080008), CONST64(0x0808080800080008), 
  CONST64(0x0808000000080800), CONST64(0x0808000800080800), CONST64(0x0808000000080808), CONST64(0x0808000800080808), 
  CONST64(0x0808080000080800), CONST64(0x0808080800080800), CONST64(0x0808080000080808), CONST64(0x0808080800080808), 
  CONST64(0x0000000008000000), CONST64(0x0000000808000000), CONST64(0x0000000008000008), CONST64(0x0000000808000008), 
  CONST64(0x0000080008000000), CONST64(0x0000080808000000), CONST64(0x0000080008000008), CONST64(0x0000080808000008), 
  CONST64(0x0000000008000800), CONST64(0x0000000808000800), CONST64(0x0000000008000808), CONST64(0x0000000808000808), 
  CONST64(0x0000080008000800), CONST64(0x0000080808000800), CONST64(0x0000080008000808), CONST64(0x0000080808000808), 
  CONST64(0x0008000008000000), CONST64(0x0008000808000000), CONST64(0x0008000008000008), CONST64(0x0008000808000008), 
  CONST64(0x0008080008000000), CONST64(0x0008080808000000), CONST64(0x0008080008000008), CONST64(0x0008080808000008), 
  CONST64(0x0008000008000800), CONST64(0x0008000808000800), CONST64(0x0008000008000808), CONST64(0x0008000808000808), 
  CONST64(0x0008080008000800), CONST64(0x0008080808000800), CONST64(0x0008080008000808), CONST64(0x0008080808000808), 
  CONST64(0x0000000008080000), CONST64(0x0000000808080000), CONST64(0x0000000008080008), CONST64(0x0000000808080008), 
  CONST64(0x0000080008080000), CONST64(0x0000080808080000), CONST64(0x0000080008080008), CONST64(0x0000080808080008), 
  CONST64(0x0000000008080800), CONST64(0x0000000808080800), CONST64(0x0000000008080808), CONST64(0x0000000808080808), 
  CONST64(0x0000080008080800), CONST64(0x0000080808080800), CONST64(0x0000080008080808), CONST64(0x0000080808080808), 
  CONST64(0x0008000008080000), CONST64(0x0008000808080000), CONST64(0x0008000008080008), CONST64(0x0008000808080008), 
  CONST64(0x0008080008080000), CONST64(0x0008080808080000), CONST64(0x0008080008080008), CONST64(0x0008080808080008), 
  CONST64(0x0008000008080800), CONST64(0x0008000808080800), CONST64(0x0008000008080808), CONST64(0x0008000808080808), 
  CONST64(0x0008080008080800), CONST64(0x0008080808080800), CONST64(0x0008080008080808), CONST64(0x0008080808080808), 
  CONST64(0x0800000008000000), CONST64(0x0800000808000000), CONST64(0x0800000008000008), CONST64(0x0800000808000008), 
  CONST64(0x0800080008000000), CONST64(0x0800080808000000), CONST64(0x0800080008000008), CONST64(0x0800080808000008), 
  CONST64(0x0800000008000800), CONST64(0x0800000808000800), CONST64(0x0800000008000808), CONST64(0x0800000808000808), 
  CONST64(0x0800080008000800), CONST64(0x0800080808000800), CONST64(0x0800080008000808), CONST64(0x0800080808000808), 
  CONST64(0x0808000008000000), CONST64(0x0808000808000000), CONST64(0x0808000008000008), CONST64(0x0808000808000008), 
  CONST64(0x0808080008000000), CONST64(0x0808080808000000), CONST64(0x0808080008000008), CONST64(0x0808080808000008), 
  CONST64(0x0808000008000800), CONST64(0x0808000808000800), CONST64(0x0808000008000808), CONST64(0x0808000808000808), 
  CONST64(0x0808080008000800), CONST64(0x0808080808000800), CONST64(0x0808080008000808), CONST64(0x0808080808000808), 
  CONST64(0x0800000008080000), CONST64(0x0800000808080000), CONST64(0x0800000008080008), CONST64(0x0800000808080008), 
  CONST64(0x0800080008080000), CONST64(0x0800080808080000), CONST64(0x0800080008080008), CONST64(0x0800080808080008), 
  CONST64(0x0800000008080800), CONST64(0x0800000808080800), CONST64(0x0800000008080808), CONST64(0x0800000808080808), 
  CONST64(0x0800080008080800), CONST64(0x0800080808080800), CONST64(0x0800080008080808), CONST64(0x0800080808080808), 
  CONST64(0x0808000008080000), CONST64(0x0808000808080000), CONST64(0x0808000008080008), CONST64(0x0808000808080008), 
  CONST64(0x0808080008080000), CONST64(0x0808080808080000), CONST64(0x0808080008080008), CONST64(0x0808080808080008), 
  CONST64(0x0808000008080800), CONST64(0x0808000808080800), CONST64(0x0808000008080808), CONST64(0x0808000808080808), 
  CONST64(0x0808080008080800), CONST64(0x0808080808080800), CONST64(0x0808080008080808), CONST64(0x0808080808080808)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000000400000000), CONST64(0x0000000000000004), CONST64(0x0000000400000004), 
  CONST64(0x0000040000000000), CONST64(0x0000040400000000), CONST64(0x0000040000000004), CONST64(0x0000040400000004), 
  CONST64(0x0000000000000400), CONST64(0x0000000400000400), CONST64(0x0000000000000404), CONST64(0x0000000400000404), 
  CONST64(0x0000040000000400), CONST64(0x0000040400000400), CONST64(0x0000040000000404), CONST64(0x0000040400000404), 
  CONST64(0x0004000000000000), CONST64(0x0004000400000000), CONST64(0x0004000000000004), CONST64(0x0004000400000004), 
  CONST64(0x0004040000000000), CONST64(0x0004040400000000), CONST64(0x0004040000000004), CONST64(0x0004040400000004), 
  CONST64(0x0004000000000400), CONST64(0x0004000400000400), CONST64(0x0004000000000404), CONST64(0x0004000400000404), 
  CONST64(0x0004040000000400), CONST64(0x0004040400000400), CONST64(0x0004040000000404), CONST64(0x0004040400000404), 
  CONST64(0x0000000000040000), CONST64(0x0000000400040000), CONST64(0x0000000000040004), CONST64(0x0000000400040004), 
  CONST64(0x0000040000040000), CONST64(0x0000040400040000), CONST64(0x0000040000040004), CONST64(0x0000040400040004), 
  CONST64(0x0000000000040400), CONST64(0x0000000400040400), CONST64(0x0000000000040404), CONST64(0x0000000400040404), 
  CONST64(0x0000040000040400), CONST64(0x0000040400040400), CONST64(0x0000040000040404), CONST64(0x0000040400040404), 
  CONST64(0x0004000000040000), CONST64(0x0004000400040000), CONST64(0x0004000000040004), CONST64(0x0004000400040004), 
  CONST64(0x0004040000040000), CONST64(0x0004040400040000), CONST64(0x0004040000040004), CONST64(0x0004040400040004), 
  CONST64(0x0004000000040400), CONST64(0x0004000400040400), CONST64(0x0004000000040404), CONST64(0x0004000400040404), 
  CONST64(0x0004040000040400), CONST64(0x0004040400040400), CONST64(0x0004040000040404), CONST64(0x0004040400040404), 
  CONST64(0x0400000000000000), CONST64(0x0400000400000000), CONST64(0x0400000000000004), CONST64(0x0400000400000004), 
  CONST64(0x0400040000000000), CONST64(0x0400040400000000), CONST64(0x0400040000000004), CONST64(0x0400040400000004), 
  CONST64(0x0400000000000400), CONST64(0x0400000400000400), CONST64(0x0400000000000404), CONST64(0x0400000400000404), 
  CONST64(0x0400040000000400), CONST64(0x0400040400000400), CONST64(0x0400040000000404), CONST64(0x0400040400000404), 
  CONST64(0x0404000000000000), CONST64(0x0404000400000000), CONST64(0x0404000000000004), CONST64(0x0404000400000004), 
  CONST64(0x0404040000000000), CONST64(0x0404040400000000), CONST64(0x0404040000000004), CONST64(0x0404040400000004), 
  CONST64(0x0404000000000400), CONST64(0x0404000400000400), CONST64(0x0404000000000404), CONST64(0x0404000400000404), 
  CONST64(0x0404040000000400), CONST64(0x0404040400000400), CONST64(0x0404040000000404), CONST64(0x0404040400000404), 
  CONST64(0x0400000000040000), CONST64(0x0400000400040000), CONST64(0x0400000000040004), CONST64(0x0400000400040004), 
  CONST64(0x0400040000040000), CONST64(0x0400040400040000), CONST64(0x0400040000040004), CONST64(0x0400040400040004), 
  CONST64(0x0400000000040400), CONST64(0x0400000400040400), CONST64(0x0400000000040404), CONST64(0x0400000400040404), 
  CONST64(0x0400040000040400), CONST64(0x0400040400040400), CONST64(0x0400040000040404), CONST64(0x0400040400040404), 
  CONST64(0x0404000000040000), CONST64(0x0404000400040000), CONST64(0x0404000000040004), CONST64(0x0404000400040004), 
  CONST64(0x0404040000040000), CONST64(0x0404040400040000), CONST64(0x0404040000040004), CONST64(0x0404040400040004), 
  CONST64(0x0404000000040400), CONST64(0x0404000400040400), CONST64(0x0404000000040404), CONST64(0x0404000400040404), 
  CONST64(0x0404040000040400), CONST64(0x0404040400040400), CONST64(0x0404040000040404), CONST64(0x0404040400040404), 
  CONST64(0x0000000004000000), CONST64(0x0000000404000000), CONST64(0x0000000004000004), CONST64(0x0000000404000004), 
  CONST64(0x0000040004000000), CONST64(0x0000040404000000), CONST64(0x0000040004000004), CONST64(0x0000040404000004), 
  CONST64(0x0000000004000400), CONST64(0x0000000404000400), CONST64(0x0000000004000404), CONST64(0x0000000404000404), 
  CONST64(0x0000040004000400), CONST64(0x0000040404000400), CONST64(0x0000040004000404), CONST64(0x0000040404000404), 
  CONST64(0x0004000004000000), CONST64(0x0004000404000000), CONST64(0x0004000004000004), CONST64(0x0004000404000004), 
  CONST64(0x0004040004000000), CONST64(0x0004040404000000), CONST64(0x0004040004000004), CONST64(0x0004040404000004), 
  CONST64(0x0004000004000400), CONST64(0x0004000404000400), CONST64(0x0004000004000404), CONST64(0x0004000404000404), 
  CONST64(0x0004040004000400), CONST64(0x0004040404000400), CONST64(0x0004040004000404), CONST64(0x0004040404000404), 
  CONST64(0x0000000004040000), CONST64(0x0000000404040000), CONST64(0x0000000004040004), CONST64(0x0000000404040004), 
  CONST64(0x0000040004040000), CONST64(0x0000040404040000), CONST64(0x0000040004040004), CONST64(0x0000040404040004), 
  CONST64(0x0000000004040400), CONST64(0x0000000404040400), CONST64(0x0000000004040404), CONST64(0x0000000404040404), 
  CONST64(0x0000040004040400), CONST64(0x0000040404040400), CONST64(0x0000040004040404), CONST64(0x0000040404040404), 
  CONST64(0x0004000004040000), CONST64(0x0004000404040000), CONST64(0x0004000004040004), CONST64(0x0004000404040004), 
  CONST64(0x0004040004040000), CONST64(0x0004040404040000), CONST64(0x0004040004040004), CONST64(0x0004040404040004), 
  CONST64(0x0004000004040400), CONST64(0x0004000404040400), CONST64(0x0004000004040404), CONST64(0x0004000404040404), 
  CONST64(0x0004040004040400), CONST64(0x0004040404040400), CONST64(0x0004040004040404), CONST64(0x0004040404040404), 
  CONST64(0x0400000004000000), CONST64(0x0400000404000000), CONST64(0x0400000004000004), CONST64(0x0400000404000004), 
  CONST64(0x0400040004000000), CONST64(0x0400040404000000), CONST64(0x0400040004000004), CONST64(0x0400040404000004), 
  CONST64(0x0400000004000400), CONST64(0x0400000404000400), CONST64(0x0400000004000404), CONST64(0x0400000404000404), 
  CONST64(0x0400040004000400), CONST64(0x0400040404000400), CONST64(0x0400040004000404), CONST64(0x0400040404000404), 
  CONST64(0x0404000004000000), CONST64(0x0404000404000000), CONST64(0x0404000004000004), CONST64(0x0404000404000004), 
  CONST64(0x0404040004000000), CONST64(0x0404040404000000), CONST64(0x0404040004000004), CONST64(0x0404040404000004), 
  CONST64(0x0404000004000400), CONST64(0x0404000404000400), CONST64(0x0404000004000404), CONST64(0x0404000404000404), 
  CONST64(0x0404040004000400), CONST64(0x0404040404000400), CONST64(0x0404040004000404), CONST64(0x0404040404000404), 
  CONST64(0x0400000004040000), CONST64(0x0400000404040000), CONST64(0x0400000004040004), CONST64(0x0400000404040004), 
  CONST64(0x0400040004040000), CONST64(0x0400040404040000), CONST64(0x0400040004040004), CONST64(0x0400040404040004), 
  CONST64(0x0400000004040400), CONST64(0x0400000404040400), CONST64(0x0400000004040404), CONST64(0x0400000404040404), 
  CONST64(0x0400040004040400), CONST64(0x0400040404040400), CONST64(0x0400040004040404), CONST64(0x0400040404040404), 
  CONST64(0x0404000004040000), CONST64(0x0404000404040000), CONST64(0x0404000004040004), CONST64(0x0404000404040004), 
  CONST64(0x0404040004040000), CONST64(0x0404040404040000), CONST64(0x0404040004040004), CONST64(0x0404040404040004), 
  CONST64(0x0404000004040400), CONST64(0x0404000404040400), CONST64(0x0404000004040404), CONST64(0x0404000404040404), 
  CONST64(0x0404040004040400), CONST64(0x0404040404040400), CONST64(0x0404040004040404), CONST64(0x0404040404040404)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000000200000000), CONST64(0x0000000000000002), CONST64(0x0000000200000002), 
  CONST64(0x0000020000000000), CONST64(0x0000020200000000), CONST64(0x0000020000000002), CONST64(0x0000020200000002), 
  CONST64(0x0000000000000200), CONST64(0x0000000200000200), CONST64(0x0000000000000202), CONST64(0x0000000200000202), 
  CONST64(0x0000020000000200), CONST64(0x0000020200000200), CONST64(0x0000020000000202), CONST64(0x0000020200000202), 
  CONST64(0x0002000000000000), CONST64(0x0002000200000000), CONST64(0x0002000000000002), CONST64(0x0002000200000002), 
  CONST64(0x0002020000000000), CONST64(0x0002020200000000), CONST64(0x0002020000000002), CONST64(0x0002020200000002), 
  CONST64(0x0002000000000200), CONST64(0x0002000200000200), CONST64(0x0002000000000202), CONST64(0x0002000200000202), 
  CONST64(0x0002020000000200), CONST64(0x0002020200000200), CONST64(0x0002020000000202), CONST64(0x0002020200000202), 
  CONST64(0x0000000000020000), CONST64(0x0000000200020000), CONST64(0x0000000000020002), CONST64(0x0000000200020002), 
  CONST64(0x0000020000020000), CONST64(0x0000020200020000), CONST64(0x0000020000020002), CONST64(0x0000020200020002), 
  CONST64(0x0000000000020200), CONST64(0x0000000200020200), CONST64(0x0000000000020202), CONST64(0x0000000200020202), 
  CONST64(0x0000020000020200), CONST64(0x0000020200020200), CONST64(0x0000020000020202), CONST64(0x0000020200020202), 
  CONST64(0x0002000000020000), CONST64(0x0002000200020000), CONST64(0x0002000000020002), CONST64(0x0002000200020002), 
  CONST64(0x0002020000020000), CONST64(0x0002020200020000), CONST64(0x0002020000020002), CONST64(0x0002020200020002), 
  CONST64(0x0002000000020200), CONST64(0x0002000200020200), CONST64(0x0002000000020202), CONST64(0x0002000200020202), 
  CONST64(0x0002020000020200), CONST64(0x0002020200020200), CONST64(0x0002020000020202), CONST64(0x0002020200020202), 
  CONST64(0x0200000000000000), CONST64(0x0200000200000000), CONST64(0x0200000000000002), CONST64(0x0200000200000002), 
  CONST64(0x0200020000000000), CONST64(0x0200020200000000), CONST64(0x0200020000000002), CONST64(0x0200020200000002), 
  CONST64(0x0200000000000200), CONST64(0x0200000200000200), CONST64(0x0200000000000202), CONST64(0x0200000200000202), 
  CONST64(0x0200020000000200), CONST64(0x0200020200000200), CONST64(0x0200020000000202), CONST64(0x0200020200000202), 
  CONST64(0x0202000000000000), CONST64(0x0202000200000000), CONST64(0x0202000000000002), CONST64(0x0202000200000002), 
  CONST64(0x0202020000000000), CONST64(0x0202020200000000), CONST64(0x0202020000000002), CONST64(0x0202020200000002), 
  CONST64(0x0202000000000200), CONST64(0x0202000200000200), CONST64(0x0202000000000202), CONST64(0x0202000200000202), 
  CONST64(0x0202020000000200), CONST64(0x0202020200000200), CONST64(0x0202020000000202), CONST64(0x0202020200000202), 
  CONST64(0x0200000000020000), CONST64(0x0200000200020000), CONST64(0x0200000000020002), CONST64(0x0200000200020002), 
  CONST64(0x0200020000020000), CONST64(0x0200020200020000), CONST64(0x0200020000020002), CONST64(0x0200020200020002), 
  CONST64(0x0200000000020200), CONST64(0x0200000200020200), CONST64(0x0200000000020202), CONST64(0x0200000200020202), 
  CONST64(0x0200020000020200), CONST64(0x0200020200020200), CONST64(0x0200020000020202), CONST64(0x0200020200020202), 
  CONST64(0x0202000000020000), CONST64(0x0202000200020000), CONST64(0x0202000000020002), CONST64(0x0202000200020002), 
  CONST64(0x0202020000020000), CONST64(0x0202020200020000), CONST64(0x0202020000020002), CONST64(0x0202020200020002), 
  CONST64(0x0202000000020200), CONST64(0x0202000200020200), CONST64(0x0202000000020202), CONST64(0x0202000200020202), 
  CONST64(0x0202020000020200), CONST64(0x0202020200020200), CONST64(0x0202020000020202), CONST64(0x0202020200020202), 
  CONST64(0x0000000002000000), CONST64(0x0000000202000000), CONST64(0x0000000002000002), CONST64(0x0000000202000002), 
  CONST64(0x0000020002000000), CONST64(0x0000020202000000), CONST64(0x0000020002000002), CONST64(0x0000020202000002), 
  CONST64(0x0000000002000200), CONST64(0x0000000202000200), CONST64(0x0000000002000202), CONST64(0x0000000202000202), 
  CONST64(0x0000020002000200), CONST64(0x0000020202000200), CONST64(0x0000020002000202), CONST64(0x0000020202000202), 
  CONST64(0x0002000002000000), CONST64(0x0002000202000000), CONST64(0x0002000002000002), CONST64(0x0002000202000002), 
  CONST64(0x0002020002000000), CONST64(0x0002020202000000), CONST64(0x0002020002000002), CONST64(0x0002020202000002), 
  CONST64(0x0002000002000200), CONST64(0x0002000202000200), CONST64(0x0002000002000202), CONST64(0x0002000202000202), 
  CONST64(0x0002020002000200), CONST64(0x0002020202000200), CONST64(0x0002020002000202), CONST64(0x0002020202000202), 
  CONST64(0x0000000002020000), CONST64(0x0000000202020000), CONST64(0x0000000002020002), CONST64(0x0000000202020002), 
  CONST64(0x0000020002020000), CONST64(0x0000020202020000), CONST64(0x0000020002020002), CONST64(0x0000020202020002), 
  CONST64(0x0000000002020200), CONST64(0x0000000202020200), CONST64(0x0000000002020202), CONST64(0x0000000202020202), 
  CONST64(0x0000020002020200), CONST64(0x0000020202020200), CONST64(0x0000020002020202), CONST64(0x0000020202020202), 
  CONST64(0x0002000002020000), CONST64(0x0002000202020000), CONST64(0x0002000002020002), CONST64(0x0002000202020002), 
  CONST64(0x0002020002020000), CONST64(0x0002020202020000), CONST64(0x0002020002020002), CONST64(0x0002020202020002), 
  CONST64(0x0002000002020200), CONST64(0x0002000202020200), CONST64(0x0002000002020202), CONST64(0x0002000202020202), 
  CONST64(0x0002020002020200), CONST64(0x0002020202020200), CONST64(0x0002020002020202), CONST64(0x0002020202020202), 
  CONST64(0x0200000002000000), CONST64(0x0200000202000000), CONST64(0x0200000002000002), CONST64(0x0200000202000002), 
  CONST64(0x0200020002000000), CONST64(0x0200020202000000), CONST64(0x0200020002000002), CONST64(0x0200020202000002), 
  CONST64(0x0200000002000200), CONST64(0x0200000202000200), CONST64(0x0200000002000202), CONST64(0x0200000202000202), 
  CONST64(0x0200020002000200), CONST64(0x0200020202000200), CONST64(0x0200020002000202), CONST64(0x0200020202000202), 
  CONST64(0x0202000002000000), CONST64(0x0202000202000000), CONST64(0x0202000002000002), CONST64(0x0202000202000002), 
  CONST64(0x0202020002000000), CONST64(0x0202020202000000), CONST64(0x0202020002000002), CONST64(0x0202020202000002), 
  CONST64(0x0202000002000200), CONST64(0x0202000202000200), CONST64(0x0202000002000202), CONST64(0x0202000202000202), 
  CONST64(0x0202020002000200), CONST64(0x0202020202000200), CONST64(0x0202020002000202), CONST64(0x0202020202000202), 
  CONST64(0x0200000002020000), CONST64(0x0200000202020000), CONST64(0x0200000002020002), CONST64(0x0200000202020002), 
  CONST64(0x0200020002020000), CONST64(0x0200020202020000), CONST64(0x0200020002020002), CONST64(0x0200020202020002), 
  CONST64(0x0200000002020200), CONST64(0x0200000202020200), CONST64(0x0200000002020202), CONST64(0x0200000202020202), 
  CONST64(0x0200020002020200), CONST64(0x0200020202020200), CONST64(0x0200020002020202), CONST64(0x0200020202020202), 
  CONST64(0x0202000002020000), CONST64(0x0202000202020000), CONST64(0x0202000002020002), CONST64(0x0202000202020002), 
  CONST64(0x0202020002020000), CONST64(0x0202020202020000), CONST64(0x0202020002020002), CONST64(0x0202020202020002), 
  CONST64(0x0202000002020200), CONST64(0x0202000202020200), CONST64(0x0202000002020202), CONST64(0x0202000202020202), 
  CONST64(0x0202020002020200), CONST64(0x0202020202020200), CONST64(0x0202020002020202), CONST64(0x0202020202020202)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000010000000000), CONST64(0x0000000000000100), CONST64(0x0000010000000100), 
  CONST64(0x0001000000000000), CONST64(0x0001010000000000), CONST64(0x0001000000000100), CONST64(0x0001010000000100), 
  CONST64(0x0000000000010000), CONST64(0x0000010000010000), CONST64(0x0000000000010100), CONST64(0x0000010000010100), 
  CONST64(0x0001000000010000), CONST64(0x0001010000010000), CONST64(0x0001000000010100), CONST64(0x0001010000010100), 
  CONST64(0x0100000000000000), CONST64(0x0100010000000000), CONST64(0x0100000000000100), CONST64(0x0100010000000100), 
  CONST64(0x0101000000000000), CONST64(0x0101010000000000), CONST64(0x0101000000000100), CONST64(0x0101010000000100), 
  CONST64(0x0100000000010000), CONST64(0x0100010000010000), CONST64(0x0100000000010100), CONST64(0x0100010000010100), 
  CONST64(0x0101000000010000), CONST64(0x0101010000010000), CONST64(0x0101000000010100), CONST64(0x0101010000010100), 
  CONST64(0x0000000001000000), CONST64(0x0000010001000000), CONST64(0x0000000001000100), CONST64(0x0000010001000100), 
  CONST64(0x0001000001000000), CONST64(0x0001010001000000), CONST64(0x0001000001000100), CONST64(0x0001010001000100), 
  CONST64(0x0000000001010000), CONST64(0x0000010001010000), CONST64(0x0000000001010100), CONST64(0x0000010001010100), 
  CONST64(0x0001000001010000), CONST64(0x0001010001010000), CONST64(0x0001000001010100), CONST64(0x0001010001010100), 
  CONST64(0x0100000001000000), CONST64(0x0100010001000000), CONST64(0x0100000001000100), CONST64(0x0100010001000100), 
  CONST64(0x0101000001000000), CONST64(0x0101010001000000), CONST64(0x0101000001000100), CONST64(0x0101010001000100), 
  CONST64(0x0100000001010000), CONST64(0x0100010001010000), CONST64(0x0100000001010100), CONST64(0x0100010001010100), 
  CONST64(0x0101000001010000), CONST64(0x0101010001010000), CONST64(0x0101000001010100), CONST64(0x0101010001010100), 
  CONST64(0x0000000100000000), CONST64(0x0000010100000000), CONST64(0x0000000100000100), CONST64(0x0000010100000100), 
  CONST64(0x0001000100000000), CONST64(0x0001010100000000), CONST64(0x0001000100000100), CONST64(0x0001010100000100), 
  CONST64(0x0000000100010000), CONST64(0x0000010100010000), CONST64(0x0000000100010100), CONST64(0x0000010100010100), 
  CONST64(0x0001000100010000), CONST64(0x0001010100010000), CONST64(0x0001000100010100), CONST64(0x0001010100010100), 
  CONST64(0x0100000100000000), CONST64(0x0100010100000000), CONST64(0x0100000100000100), CONST64(0x0100010100000100), 
  CONST64(0x0101000100000000), CONST64(0x0101010100000000), CONST64(0x0101000100000100), CONST64(0x0101010100000100), 
  CONST64(0x0100000100010000), CONST64(0x0100010100010000), CONST64(0x0100000100010100), CONST64(0x0100010100010100), 
  CONST64(0x0101000100010000), CONST64(0x0101010100010000), CONST64(0x0101000100010100), CONST64(0x0101010100010100), 
  CONST64(0x0000000101000000), CONST64(0x0000010101000000), CONST64(0x0000000101000100), CONST64(0x0000010101000100), 
  CONST64(0x0001000101000000), CONST64(0x0001010101000000), CONST64(0x0001000101000100), CONST64(0x0001010101000100), 
  CONST64(0x0000000101010000), CONST64(0x0000010101010000), CONST64(0x0000000101010100), CONST64(0x0000010101010100), 
  CONST64(0x0001000101010000), CONST64(0x0001010101010000), CONST64(0x0001000101010100), CONST64(0x0001010101010100), 
  CONST64(0x0100000101000000), CONST64(0x0100010101000000), CONST64(0x0100000101000100), CONST64(0x0100010101000100), 
  CONST64(0x0101000101000000), CONST64(0x0101010101000000), CONST64(0x0101000101000100), CONST64(0x0101010101000100), 
  CONST64(0x0100000101010000), CONST64(0x0100010101010000), CONST64(0x0100000101010100), CONST64(0x0100010101010100), 
  CONST64(0x0101000101010000), CONST64(0x0101010101010000), CONST64(0x0101000101010100), CONST64(0x0101010101010100), 
  CONST64(0x0000000000000001), CONST64(0x0000010000000001), CONST64(0x0000000000000101), CONST64(0x0000010000000101), 
  CONST64(0x0001000000000001), CONST64(0x0001010000000001), CONST64(0x0001000000000101), CONST64(0x0001010000000101), 
  CONST64(0x0000000000010001), CONST64(0x0000010000010001), CONST64(0x0000000000010101), CONST64(0x0000010000010101), 
  CONST64(0x0001000000010001), CONST64(0x0001010000010001), CONST64(0x0001000000010101), CONST64(0x0001010000010101), 
  CONST64(0x0100000000000001), CONST64(0x0100010000000001), CONST64(0x0100000000000101), CONST64(0x0100010000000101), 
  CONST64(0x0101000000000001), CONST64(0x0101010000000001), CONST64(0x0101000000000101), CONST64(0x0101010000000101), 
  CONST64(0x0100000000010001), CONST64(0x0100010000010001), CONST64(0x0100000000010101), CONST64(0x0100010000010101), 
  CONST64(0x0101000000010001), CONST64(0x0101010000010001), CONST64(0x0101000000010101), CONST64(0x0101010000010101), 
  CONST64(0x0000000001000001), CONST64(0x0000010001000001), CONST64(0x0000000001000101), CONST64(0x0000010001000101), 
  CONST64(0x0001000001000001), CONST64(0x0001010001000001), CONST64(0x0001000001000101), CONST64(0x0001010001000101), 
  CONST64(0x0000000001010001), CONST64(0x0000010001010001), CONST64(0x0000000001010101), CONST64(0x0000010001010101), 
  CONST64(0x0001000001010001), CONST64(0x0001010001010001), CONST64(0x0001000001010101), CONST64(0x0001010001010101), 
  CONST64(0x0100000001000001), CONST64(0x0100010001000001), CONST64(0x0100000001000101), CONST64(0x0100010001000101), 
  CONST64(0x0101000001000001), CONST64(0x0101010001000001), CONST64(0x0101000001000101), CONST64(0x0101010001000101), 
  CONST64(0x0100000001010001), CONST64(0x0100010001010001), CONST64(0x0100000001010101), CONST64(0x0100010001010101), 
  CONST64(0x0101000001010001), CONST64(0x0101010001010001), CONST64(0x0101000001010101), CONST64(0x0101010001010101), 
  CONST64(0x0000000100000001), CONST64(0x0000010100000001), CONST64(0x0000000100000101), CONST64(0x0000010100000101), 
  CONST64(0x0001000100000001), CONST64(0x0001010100000001), CONST64(0x0001000100000101), CONST64(0x0001010100000101), 
  CONST64(0x0000000100010001), CONST64(0x0000010100010001), CONST64(0x0000000100010101), CONST64(0x0000010100010101), 
  CONST64(0x0001000100010001), CONST64(0x0001010100010001), CONST64(0x0001000100010101), CONST64(0x0001010100010101), 
  CONST64(0x0100000100000001), CONST64(0x0100010100000001), CONST64(0x0100000100000101), CONST64(0x0100010100000101), 
  CONST64(0x0101000100000001), CONST64(0x0101010100000001), CONST64(0x0101000100000101), CONST64(0x0101010100000101), 
  CONST64(0x0100000100010001), CONST64(0x0100010100010001), CONST64(0x0100000100010101), CONST64(0x0100010100010101), 
  CONST64(0x0101000100010001), CONST64(0x0101010100010001), CONST64(0x0101000100010101), CONST64(0x0101010100010101), 
  CONST64(0x0000000101000001), CONST64(0x0000010101000001), CONST64(0x0000000101000101), CONST64(0x0000010101000101), 
  CONST64(0x0001000101000001), CONST64(0x0001010101000001), CONST64(0x0001000101000101), CONST64(0x0001010101000101), 
  CONST64(0x0000000101010001), CONST64(0x0000010101010001), CONST64(0x0000000101010101), CONST64(0x0000010101010101), 
  CONST64(0x0001000101010001), CONST64(0x0001010101010001), CONST64(0x0001000101010101), CONST64(0x0001010101010101), 
  CONST64(0x0100000101000001), CONST64(0x0100010101000001), CONST64(0x0100000101000101), CONST64(0x0100010101000101), 
  CONST64(0x0101000101000001), CONST64(0x0101010101000001), CONST64(0x0101000101000101), CONST64(0x0101010101000101), 
  CONST64(0x0100000101010001), CONST64(0x0100010101010001), CONST64(0x0100000101010101), CONST64(0x0100010101010101), 
  CONST64(0x0101000101010001), CONST64(0x0101010101010001), CONST64(0x0101000101010101), CONST64(0x0101010101010101)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000008000000000), CONST64(0x0000000000000080), CONST64(0x0000008000000080), 
  CONST64(0x0000800000000000), CONST64(0x0000808000000000), CONST64(0x0000800000000080), CONST64(0x0000808000000080), 
  CONST64(0x0000000000008000), CONST64(0x0000008000008000), CONST64(0x0000000000008080), CONST64(0x0000008000008080), 
  CONST64(0x0000800000008000), CONST64(0x0000808000008000), CONST64(0x0000800000008080), CONST64(0x0000808000008080), 
  CONST64(0x0080000000000000), CONST64(0x0080008000000000), CONST64(0x0080000000000080), CONST64(0x0080008000000080), 
  CONST64(0x0080800000000000), CONST64(0x0080808000000000), CONST64(0x0080800000000080), CONST64(0x0080808000000080), 
  CONST64(0x0080000000008000), CONST64(0x0080008000008000), CONST64(0x0080000000008080), CONST64(0x0080008000008080), 
  CONST64(0x0080800000008000), CONST64(0x0080808000008000), CONST64(0x0080800000008080), CONST64(0x0080808000008080), 
  CONST64(0x0000000000800000), CONST64(0x0000008000800000), CONST64(0x0000000000800080), CONST64(0x0000008000800080), 
  CONST64(0x0000800000800000), CONST64(0x0000808000800000), CONST64(0x0000800000800080), CONST64(0x0000808000800080), 
  CONST64(0x0000000000808000), CONST64(0x0000008000808000), CONST64(0x0000000000808080), CONST64(0x0000008000808080), 
  CONST64(0x0000800000808000), CONST64(0x0000808000808000), CONST64(0x0000800000808080), CONST64(0x0000808000808080), 
  CONST64(0x0080000000800000), CONST64(0x0080008000800000), CONST64(0x0080000000800080), CONST64(0x0080008000800080), 
  CONST64(0x0080800000800000), CONST64(0x0080808000800000), CONST64(0x0080800000800080), CONST64(0x0080808000800080), 
  CONST64(0x0080000000808000), CONST64(0x0080008000808000), CONST64(0x0080000000808080), CONST64(0x0080008000808080), 
  CONST64(0x0080800000808000), CONST64(0x0080808000808000), CONST64(0x0080800000808080), CONST64(0x0080808000808080), 
  CONST64(0x8000000000000000), CONST64(0x8000008000000000), CONST64(0x8000000000000080), CONST64(0x8000008000000080), 
  CONST64(0x8000800000000000), CONST64(0x8000808000000000), CONST64(0x8000800000000080), CONST64(0x8000808000000080), 
  CONST64(0x8000000000008000), CONST64(0x8000008000008000), CONST64(0x8000000000008080), CONST64(0x8000008000008080), 
  CONST64(0x8000800000008000), CONST64(0x8000808000008000), CONST64(0x8000800000008080), CONST64(0x8000808000008080), 
  CONST64(0x8080000000000000), CONST64(0x8080008000000000), CONST64(0x8080000000000080), CONST64(0x8080008000000080), 
  CONST64(0x8080800000000000), CONST64(0x8080808000000000), CONST64(0x8080800000000080), CONST64(0x8080808000000080), 
  CONST64(0x8080000000008000), CONST64(0x8080008000008000), CONST64(0x8080000000008080), CONST64(0x8080008000008080), 
  CONST64(0x8080800000008000), CONST64(0x8080808000008000), CONST64(0x8080800000008080), CONST64(0x8080808000008080), 
  CONST64(0x8000000000800000), CONST64(0x8000008000800000), CONST64(0x8000000000800080), CONST64(0x8000008000800080), 
  CONST64(0x8000800000800000), CONST64(0x8000808000800000), CONST64(0x8000800000800080), CONST64(0x8000808000800080), 
  CONST64(0x8000000000808000), CONST64(0x8000008000808000), CONST64(0x8000000000808080), CONST64(0x8000008000808080), 
  CONST64(0x8000800000808000), CONST64(0x8000808000808000), CONST64(0x8000800000808080), CONST64(0x8000808000808080), 
  CONST64(0x8080000000800000), CONST64(0x8080008000800000), CONST64(0x8080000000800080), CONST64(0x8080008000800080), 
  CONST64(0x8080800000800000), CONST64(0x8080808000800000), CONST64(0x8080800000800080), CONST64(0x8080808000800080), 
  CONST64(0x8080000000808000), CONST64(0x8080008000808000), CONST64(0x8080000000808080), CONST64(0x8080008000808080), 
  CONST64(0x8080800000808000), CONST64(0x8080808000808000), CONST64(0x8080800000808080), CONST64(0x8080808000808080), 
  CONST64(0x0000000080000000), CONST64(0x0000008080000000), CONST64(0x0000000080000080), CONST64(0x0000008080000080), 
  CONST64(0x0000800080000000), CONST64(0x0000808080000000), CONST64(0x0000800080000080), CONST64(0x0000808080000080), 
  CONST64(0x0000000080008000), CONST64(0x0000008080008000), CONST64(0x0000000080008080), CONST64(0x0000008080008080), 
  CONST64(0x0000800080008000), CONST64(0x0000808080008000), CONST64(0x0000800080008080), CONST64(0x0000808080008080), 
  CONST64(0x0080000080000000), CONST64(0x0080008080000000), CONST64(0x0080000080000080), CONST64(0x0080008080000080), 
  CONST64(0x0080800080000000), CONST64(0x0080808080000000), CONST64(0x0080800080000080), CONST64(0x0080808080000080), 
  CONST64(0x0080000080008000), CONST64(0x0080008080008000), CONST64(0x0080000080008080), CONST64(0x0080008080008080), 
  CONST64(0x0080800080008000), CONST64(0x0080808080008000), CONST64(0x0080800080008080), CONST64(0x0080808080008080), 
  CONST64(0x0000000080800000), CONST64(0x0000008080800000), CONST64(0x0000000080800080), CONST64(0x0000008080800080), 
  CONST64(0x0000800080800000), CONST64(0x0000808080800000), CONST64(0x0000800080800080), CONST64(0x0000808080800080), 
  CONST64(0x0000000080808000), CONST64(0x0000008080808000), CONST64(0x0000000080808080), CONST64(0x0000008080808080), 
  CONST64(0x0000800080808000), CONST64(0x0000808080808000), CONST64(0x0000800080808080), CONST64(0x0000808080808080), 
  CONST64(0x0080000080800000), CONST64(0x0080008080800000), CONST64(0x0080000080800080), CONST64(0x0080008080800080), 
  CONST64(0x0080800080800000), CONST64(0x0080808080800000), CONST64(0x0080800080800080), CONST64(0x0080808080800080), 
  CONST64(0x0080000080808000), CONST64(0x0080008080808000), CONST64(0x0080000080808080), CONST64(0x0080008080808080), 
  CONST64(0x0080800080808000), CONST64(0x0080808080808000), CONST64(0x0080800080808080), CONST64(0x0080808080808080), 
  CONST64(0x8000000080000000), CONST64(0x8000008080000000), CONST64(0x8000000080000080), CONST64(0x8000008080000080), 
  CONST64(0x8000800080000000), CONST64(0x8000808080000000), CONST64(0x8000800080000080), CONST64(0x8000808080000080), 
  CONST64(0x8000000080008000), CONST64(0x8000008080008000), CONST64(0x8000000080008080), CONST64(0x8000008080008080), 
  CONST64(0x8000800080008000), CONST64(0x8000808080008000), CONST64(0x8000800080008080), CONST64(0x8000808080008080), 
  CONST64(0x8080000080000000), CONST64(0x8080008080000000), CONST64(0x8080000080000080), CONST64(0x8080008080000080), 
  CONST64(0x8080800080000000), CONST64(0x8080808080000000), CONST64(0x8080800080000080), CONST64(0x8080808080000080), 
  CONST64(0x8080000080008000), CONST64(0x8080008080008000), CONST64(0x8080000080008080), CONST64(0x8080008080008080), 
  CONST64(0x8080800080008000), CONST64(0x8080808080008000), CONST64(0x8080800080008080), CONST64(0x8080808080008080), 
  CONST64(0x8000000080800000), CONST64(0x8000008080800000), CONST64(0x8000000080800080), CONST64(0x8000008080800080), 
  CONST64(0x8000800080800000), CONST64(0x8000808080800000), CONST64(0x8000800080800080), CONST64(0x8000808080800080), 
  CONST64(0x8000000080808000), CONST64(0x8000008080808000), CONST64(0x8000000080808080), CONST64(0x8000008080808080), 
  CONST64(0x8000800080808000), CONST64(0x8000808080808000), CONST64(0x8000800080808080), CONST64(0x8000808080808080), 
  CONST64(0x8080000080800000), CONST64(0x8080008080800000), CONST64(0x8080000080800080), CONST64(0x8080008080800080), 
  CONST64(0x8080800080800000), CONST64(0x8080808080800000), CONST64(0x8080800080800080), CONST64(0x8080808080800080), 
  CONST64(0x8080000080808000), CONST64(0x8080008080808000), CONST64(0x8080000080808080), CONST64(0x8080008080808080), 
  CONST64(0x8080800080808000), CONST64(0x8080808080808000), CONST64(0x8080800080808080), CONST64(0x8080808080808080)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000004000000000), CONST64(0x0000000000000040), CONST64(0x0000004000000040), 
  CONST64(0x0000400000000000), CONST64(0x0000404000000000), CONST64(0x0000400000000040), CONST64(0x0000404000000040), 
  CONST64(0x0000000000004000), CONST64(0x0000004000004000), CONST64(0x0000000000004040), CONST64(0x0000004000004040), 
  CONST64(0x0000400000004000), CONST64(0x0000404000004000), CONST64(0x0000400000004040), CONST64(0x0000404000004040), 
  CONST64(0x0040000000000000), CONST64(0x0040004000000000), CONST64(0x0040000000000040), CONST64(0x0040004000000040), 
  CONST64(0x0040400000000000), CONST64(0x0040404000000000), CONST64(0x0040400000000040), CONST64(0x0040404000000040), 
  CONST64(0x0040000000004000), CONST64(0x0040004000004000), CONST64(0x0040000000004040), CONST64(0x0040004000004040), 
  CONST64(0x0040400000004000), CONST64(0x0040404000004000), CONST64(0x0040400000004040), CONST64(0x0040404000004040), 
  CONST64(0x0000000000400000), CONST64(0x0000004000400000), CONST64(0x0000000000400040), CONST64(0x0000004000400040), 
  CONST64(0x0000400000400000), CONST64(0x0000404000400000), CONST64(0x0000400000400040), CONST64(0x0000404000400040), 
  CONST64(0x0000000000404000), CONST64(0x0000004000404000), CONST64(0x0000000000404040), CONST64(0x0000004000404040), 
  CONST64(0x0000400000404000), CONST64(0x0000404000404000), CONST64(0x0000400000404040), CONST64(0x0000404000404040), 
  CONST64(0x0040000000400000), CONST64(0x0040004000400000), CONST64(0x0040000000400040), CONST64(0x0040004000400040), 
  CONST64(0x0040400000400000), CONST64(0x0040404000400000), CONST64(0x0040400000400040), CONST64(0x0040404000400040), 
  CONST64(0x0040000000404000), CONST64(0x0040004000404000), CONST64(0x0040000000404040), CONST64(0x0040004000404040), 
  CONST64(0x0040400000404000), CONST64(0x0040404000404000), CONST64(0x0040400000404040), CONST64(0x0040404000404040), 
  CONST64(0x4000000000000000), CONST64(0x4000004000000000), CONST64(0x4000000000000040), CONST64(0x4000004000000040), 
  CONST64(0x4000400000000000), CONST64(0x4000404000000000), CONST64(0x4000400000000040), CONST64(0x4000404000000040), 
  CONST64(0x4000000000004000), CONST64(0x4000004000004000), CONST64(0x4000000000004040), CONST64(0x4000004000004040), 
  CONST64(0x4000400000004000), CONST64(0x4000404000004000), CONST64(0x4000400000004040), CONST64(0x4000404000004040), 
  CONST64(0x4040000000000000), CONST64(0x4040004000000000), CONST64(0x4040000000000040), CONST64(0x4040004000000040), 
  CONST64(0x4040400000000000), CONST64(0x4040404000000000), CONST64(0x4040400000000040), CONST64(0x4040404000000040), 
  CONST64(0x4040000000004000), CONST64(0x4040004000004000), CONST64(0x4040000000004040), CONST64(0x4040004000004040), 
  CONST64(0x4040400000004000), CONST64(0x4040404000004000), CONST64(0x4040400000004040), CONST64(0x4040404000004040), 
  CONST64(0x4000000000400000), CONST64(0x4000004000400000), CONST64(0x4000000000400040), CONST64(0x4000004000400040), 
  CONST64(0x4000400000400000), CONST64(0x4000404000400000), CONST64(0x4000400000400040), CONST64(0x4000404000400040), 
  CONST64(0x4000000000404000), CONST64(0x4000004000404000), CONST64(0x4000000000404040), CONST64(0x4000004000404040), 
  CONST64(0x4000400000404000), CONST64(0x4000404000404000), CONST64(0x4000400000404040), CONST64(0x4000404000404040), 
  CONST64(0x4040000000400000), CONST64(0x4040004000400000), CONST64(0x4040000000400040), CONST64(0x4040004000400040), 
  CONST64(0x4040400000400000), CONST64(0x4040404000400000), CONST64(0x4040400000400040), CONST64(0x4040404000400040), 
  CONST64(0x4040000000404000), CONST64(0x4040004000404000), CONST64(0x4040000000404040), CONST64(0x4040004000404040), 
  CONST64(0x4040400000404000), CONST64(0x4040404000404000), CONST64(0x4040400000404040), CONST64(0x4040404000404040), 
  CONST64(0x0000000040000000), CONST64(0x0000004040000000), CONST64(0x0000000040000040), CONST64(0x0000004040000040), 
  CONST64(0x0000400040000000), CONST64(0x0000404040000000), CONST64(0x0000400040000040), CONST64(0x0000404040000040), 
  CONST64(0x0000000040004000), CONST64(0x0000004040004000), CONST64(0x0000000040004040), CONST64(0x0000004040004040), 
  CONST64(0x0000400040004000), CONST64(0x0000404040004000), CONST64(0x0000400040004040), CONST64(0x0000404040004040), 
  CONST64(0x0040000040000000), CONST64(0x0040004040000000), CONST64(0x0040000040000040), CONST64(0x0040004040000040), 
  CONST64(0x0040400040000000), CONST64(0x0040404040000000), CONST64(0x0040400040000040), CONST64(0x0040404040000040), 
  CONST64(0x0040000040004000), CONST64(0x0040004040004000), CONST64(0x0040000040004040), CONST64(0x0040004040004040), 
  CONST64(0x0040400040004000), CONST64(0x0040404040004000), CONST64(0x0040400040004040), CONST64(0x0040404040004040), 
  CONST64(0x0000000040400000), CONST64(0x0000004040400000), CONST64(0x0000000040400040), CONST64(0x0000004040400040), 
  CONST64(0x0000400040400000), CONST64(0x0000404040400000), CONST64(0x0000400040400040), CONST64(0x0000404040400040), 
  CONST64(0x0000000040404000), CONST64(0x0000004040404000), CONST64(0x0000000040404040), CONST64(0x0000004040404040), 
  CONST64(0x0000400040404000), CONST64(0x0000404040404000), CONST64(0x0000400040404040), CONST64(0x0000404040404040), 
  CONST64(0x0040000040400000), CONST64(0x0040004040400000), CONST64(0x0040000040400040), CONST64(0x0040004040400040), 
  CONST64(0x0040400040400000), CONST64(0x0040404040400000), CONST64(0x0040400040400040), CONST64(0x0040404040400040), 
  CONST64(0x0040000040404000), CONST64(0x0040004040404000), CONST64(0x0040000040404040), CONST64(0x0040004040404040), 
  CONST64(0x0040400040404000), CONST64(0x0040404040404000), CONST64(0x0040400040404040), CONST64(0x0040404040404040), 
  CONST64(0x4000000040000000), CONST64(0x4000004040000000), CONST64(0x4000000040000040), CONST64(0x4000004040000040), 
  CONST64(0x4000400040000000), CONST64(0x4000404040000000), CONST64(0x4000400040000040), CONST64(0x4000404040000040), 
  CONST64(0x4000000040004000), CONST64(0x4000004040004000), CONST64(0x4000000040004040), CONST64(0x4000004040004040), 
  CONST64(0x4000400040004000), CONST64(0x4000404040004000), CONST64(0x4000400040004040), CONST64(0x4000404040004040), 
  CONST64(0x4040000040000000), CONST64(0x4040004040000000), CONST64(0x4040000040000040), CONST64(0x4040004040000040), 
  CONST64(0x4040400040000000), CONST64(0x4040404040000000), CONST64(0x4040400040000040), CONST64(0x4040404040000040), 
  CONST64(0x4040000040004000), CONST64(0x4040004040004000), CONST64(0x4040000040004040), CONST64(0x4040004040004040), 
  CONST64(0x4040400040004000), CONST64(0x4040404040004000), CONST64(0x4040400040004040), CONST64(0x4040404040004040), 
  CONST64(0x4000000040400000), CONST64(0x4000004040400000), CONST64(0x4000000040400040), CONST64(0x4000004040400040), 
  CONST64(0x4000400040400000), CONST64(0x4000404040400000), CONST64(0x4000400040400040), CONST64(0x4000404040400040), 
  CONST64(0x4000000040404000), CONST64(0x4000004040404000), CONST64(0x4000000040404040), CONST64(0x4000004040404040), 
  CONST64(0x4000400040404000), CONST64(0x4000404040404000), CONST64(0x4000400040404040), CONST64(0x4000404040404040), 
  CONST64(0x4040000040400000), CONST64(0x4040004040400000), CONST64(0x4040000040400040), CONST64(0x4040004040400040), 
  CONST64(0x4040400040400000), CONST64(0x4040404040400000), CONST64(0x4040400040400040), CONST64(0x4040404040400040), 
  CONST64(0x4040000040404000), CONST64(0x4040004040404000), CONST64(0x4040000040404040), CONST64(0x4040004040404040), 
  CONST64(0x4040400040404000), CONST64(0x4040404040404000), CONST64(0x4040400040404040), CONST64(0x4040404040404040)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000002000000000), CONST64(0x0000000000000020), CONST64(0x0000002000000020), 
  CONST64(0x0000200000000000), CONST64(0x0000202000000000), CONST64(0x0000200000000020), CONST64(0x0000202000000020), 
  CONST64(0x0000000000002000), CONST64(0x0000002000002000), CONST64(0x0000000000002020), CONST64(0x0000002000002020), 
  CONST64(0x0000200000002000), CONST64(0x0000202000002000), CONST64(0x0000200000002020), CONST64(0x0000202000002020), 
  CONST64(0x0020000000000000), CONST64(0x0020002000000000), CONST64(0x0020000000000020), CONST64(0x0020002000000020), 
  CONST64(0x0020200000000000), CONST64(0x0020202000000000), CONST64(0x0020200000000020), CONST64(0x0020202000000020), 
  CONST64(0x0020000000002000), CONST64(0x0020002000002000), CONST64(0x0020000000002020), CONST64(0x0020002000002020), 
  CONST64(0x0020200000002000), CONST64(0x0020202000002000), CONST64(0x0020200000002020), CONST64(0x0020202000002020), 
  CONST64(0x0000000000200000), CONST64(0x0000002000200000), CONST64(0x0000000000200020), CONST64(0x0000002000200020), 
  CONST64(0x0000200000200000), CONST64(0x0000202000200000), CONST64(0x0000200000200020), CONST64(0x0000202000200020), 
  CONST64(0x0000000000202000), CONST64(0x0000002000202000), CONST64(0x0000000000202020), CONST64(0x0000002000202020), 
  CONST64(0x0000200000202000), CONST64(0x0000202000202000), CONST64(0x0000200000202020), CONST64(0x0000202000202020), 
  CONST64(0x0020000000200000), CONST64(0x0020002000200000), CONST64(0x0020000000200020), CONST64(0x0020002000200020), 
  CONST64(0x0020200000200000), CONST64(0x0020202000200000), CONST64(0x0020200000200020), CONST64(0x0020202000200020), 
  CONST64(0x0020000000202000), CONST64(0x0020002000202000), CONST64(0x0020000000202020), CONST64(0x0020002000202020), 
  CONST64(0x0020200000202000), CONST64(0x0020202000202000), CONST64(0x0020200000202020), CONST64(0x0020202000202020), 
  CONST64(0x2000000000000000), CONST64(0x2000002000000000), CONST64(0x2000000000000020), CONST64(0x2000002000000020), 
  CONST64(0x2000200000000000), CONST64(0x2000202000000000), CONST64(0x2000200000000020), CONST64(0x2000202000000020), 
  CONST64(0x2000000000002000), CONST64(0x2000002000002000), CONST64(0x2000000000002020), CONST64(0x2000002000002020), 
  CONST64(0x2000200000002000), CONST64(0x2000202000002000), CONST64(0x2000200000002020), CONST64(0x2000202000002020), 
  CONST64(0x2020000000000000), CONST64(0x2020002000000000), CONST64(0x2020000000000020), CONST64(0x2020002000000020), 
  CONST64(0x2020200000000000), CONST64(0x2020202000000000), CONST64(0x2020200000000020), CONST64(0x2020202000000020), 
  CONST64(0x2020000000002000), CONST64(0x2020002000002000), CONST64(0x2020000000002020), CONST64(0x2020002000002020), 
  CONST64(0x2020200000002000), CONST64(0x2020202000002000), CONST64(0x2020200000002020), CONST64(0x2020202000002020), 
  CONST64(0x2000000000200000), CONST64(0x2000002000200000), CONST64(0x2000000000200020), CONST64(0x2000002000200020), 
  CONST64(0x2000200000200000), CONST64(0x2000202000200000), CONST64(0x2000200000200020), CONST64(0x2000202000200020), 
  CONST64(0x2000000000202000), CONST64(0x2000002000202000), CONST64(0x2000000000202020), CONST64(0x2000002000202020), 
  CONST64(0x2000200000202000), CONST64(0x2000202000202000), CONST64(0x2000200000202020), CONST64(0x2000202000202020), 
  CONST64(0x2020000000200000), CONST64(0x2020002000200000), CONST64(0x2020000000200020), CONST64(0x2020002000200020), 
  CONST64(0x2020200000200000), CONST64(0x2020202000200000), CONST64(0x2020200000200020), CONST64(0x2020202000200020), 
  CONST64(0x2020000000202000), CONST64(0x2020002000202000), CONST64(0x2020000000202020), CONST64(0x2020002000202020), 
  CONST64(0x2020200000202000), CONST64(0x2020202000202000), CONST64(0x2020200000202020), CONST64(0x2020202000202020), 
  CONST64(0x0000000020000000), CONST64(0x0000002020000000), CONST64(0x0000000020000020), CONST64(0x0000002020000020), 
  CONST64(0x0000200020000000), CONST64(0x0000202020000000), CONST64(0x0000200020000020), CONST64(0x0000202020000020), 
  CONST64(0x0000000020002000), CONST64(0x0000002020002000), CONST64(0x0000000020002020), CONST64(0x0000002020002020), 
  CONST64(0x0000200020002000), CONST64(0x0000202020002000), CONST64(0x0000200020002020), CONST64(0x0000202020002020), 
  CONST64(0x0020000020000000), CONST64(0x0020002020000000), CONST64(0x0020000020000020), CONST64(0x0020002020000020), 
  CONST64(0x0020200020000000), CONST64(0x0020202020000000), CONST64(0x0020200020000020), CONST64(0x0020202020000020), 
  CONST64(0x0020000020002000), CONST64(0x0020002020002000), CONST64(0x0020000020002020), CONST64(0x0020002020002020), 
  CONST64(0x0020200020002000), CONST64(0x0020202020002000), CONST64(0x0020200020002020), CONST64(0x0020202020002020), 
  CONST64(0x0000000020200000), CONST64(0x0000002020200000), CONST64(0x0000000020200020), CONST64(0x0000002020200020), 
  CONST64(0x0000200020200000), CONST64(0x0000202020200000), CONST64(0x0000200020200020), CONST64(0x0000202020200020), 
  CONST64(0x0000000020202000), CONST64(0x0000002020202000), CONST64(0x0000000020202020), CONST64(0x0000002020202020), 
  CONST64(0x0000200020202000), CONST64(0x0000202020202000), CONST64(0x0000200020202020), CONST64(0x0000202020202020), 
  CONST64(0x0020000020200000), CONST64(0x0020002020200000), CONST64(0x0020000020200020), CONST64(0x0020002020200020), 
  CONST64(0x0020200020200000), CONST64(0x0020202020200000), CONST64(0x0020200020200020), CONST64(0x0020202020200020), 
  CONST64(0x0020000020202000), CONST64(0x0020002020202000), CONST64(0x0020000020202020), CONST64(0x0020002020202020), 
  CONST64(0x0020200020202000), CONST64(0x0020202020202000), CONST64(0x0020200020202020), CONST64(0x0020202020202020), 
  CONST64(0x2000000020000000), CONST64(0x2000002020000000), CONST64(0x2000000020000020), CONST64(0x2000002020000020), 
  CONST64(0x2000200020000000), CONST64(0x2000202020000000), CONST64(0x2000200020000020), CONST64(0x2000202020000020), 
  CONST64(0x2000000020002000), CONST64(0x2000002020002000), CONST64(0x2000000020002020), CONST64(0x2000002020002020), 
  CONST64(0x2000200020002000), CONST64(0x2000202020002000), CONST64(0x2000200020002020), CONST64(0x2000202020002020), 
  CONST64(0x2020000020000000), CONST64(0x2020002020000000), CONST64(0x2020000020000020), CONST64(0x2020002020000020), 
  CONST64(0x2020200020000000), CONST64(0x2020202020000000), CONST64(0x2020200020000020), CONST64(0x2020202020000020), 
  CONST64(0x2020000020002000), CONST64(0x2020002020002000), CONST64(0x2020000020002020), CONST64(0x2020002020002020), 
  CONST64(0x2020200020002000), CONST64(0x2020202020002000), CONST64(0x2020200020002020), CONST64(0x2020202020002020), 
  CONST64(0x2000000020200000), CONST64(0x2000002020200000), CONST64(0x2000000020200020), CONST64(0x2000002020200020), 
  CONST64(0x2000200020200000), CONST64(0x2000202020200000), CONST64(0x2000200020200020), CONST64(0x2000202020200020), 
  CONST64(0x2000000020202000), CONST64(0x2000002020202000), CONST64(0x2000000020202020), CONST64(0x2000002020202020), 
  CONST64(0x2000200020202000), CONST64(0x2000202020202000), CONST64(0x2000200020202020), CONST64(0x2000202020202020), 
  CONST64(0x2020000020200000), CONST64(0x2020002020200000), CONST64(0x2020000020200020), CONST64(0x2020002020200020), 
  CONST64(0x2020200020200000), CONST64(0x2020202020200000), CONST64(0x2020200020200020), CONST64(0x2020202020200020), 
  CONST64(0x2020000020202000), CONST64(0x2020002020202000), CONST64(0x2020000020202020), CONST64(0x2020002020202020), 
  CONST64(0x2020200020202000), CONST64(0x2020202020202000), CONST64(0x2020200020202020), CONST64(0x2020202020202020)
  }};
  
static const ulong64 des_fp[8][256] = {

{ CONST64(0x0000000000000000), CONST64(0x0000008000000000), CONST64(0x0000000002000000), CONST64(0x0000008002000000), 
  CONST64(0x0000000000020000), CONST64(0x0000008000020000), CONST64(0x0000000002020000), CONST64(0x0000008002020000), 
  CONST64(0x0000000000000200), CONST64(0x0000008000000200), CONST64(0x0000000002000200), CONST64(0x0000008002000200), 
  CONST64(0x0000000000020200), CONST64(0x0000008000020200), CONST64(0x0000000002020200), CONST64(0x0000008002020200), 
  CONST64(0x0000000000000002), CONST64(0x0000008000000002), CONST64(0x0000000002000002), CONST64(0x0000008002000002), 
  CONST64(0x0000000000020002), CONST64(0x0000008000020002), CONST64(0x0000000002020002), CONST64(0x0000008002020002), 
  CONST64(0x0000000000000202), CONST64(0x0000008000000202), CONST64(0x0000000002000202), CONST64(0x0000008002000202), 
  CONST64(0x0000000000020202), CONST64(0x0000008000020202), CONST64(0x0000000002020202), CONST64(0x0000008002020202), 
  CONST64(0x0200000000000000), CONST64(0x0200008000000000), CONST64(0x0200000002000000), CONST64(0x0200008002000000), 
  CONST64(0x0200000000020000), CONST64(0x0200008000020000), CONST64(0x0200000002020000), CONST64(0x0200008002020000), 
  CONST64(0x0200000000000200), CONST64(0x0200008000000200), CONST64(0x0200000002000200), CONST64(0x0200008002000200), 
  CONST64(0x0200000000020200), CONST64(0x0200008000020200), CONST64(0x0200000002020200), CONST64(0x0200008002020200), 
  CONST64(0x0200000000000002), CONST64(0x0200008000000002), CONST64(0x0200000002000002), CONST64(0x0200008002000002), 
  CONST64(0x0200000000020002), CONST64(0x0200008000020002), CONST64(0x0200000002020002), CONST64(0x0200008002020002), 
  CONST64(0x0200000000000202), CONST64(0x0200008000000202), CONST64(0x0200000002000202), CONST64(0x0200008002000202), 
  CONST64(0x0200000000020202), CONST64(0x0200008000020202), CONST64(0x0200000002020202), CONST64(0x0200008002020202), 
  CONST64(0x0002000000000000), CONST64(0x0002008000000000), CONST64(0x0002000002000000), CONST64(0x0002008002000000), 
  CONST64(0x0002000000020000), CONST64(0x0002008000020000), CONST64(0x0002000002020000), CONST64(0x0002008002020000), 
  CONST64(0x0002000000000200), CONST64(0x0002008000000200), CONST64(0x0002000002000200), CONST64(0x0002008002000200), 
  CONST64(0x0002000000020200), CONST64(0x0002008000020200), CONST64(0x0002000002020200), CONST64(0x0002008002020200), 
  CONST64(0x0002000000000002), CONST64(0x0002008000000002), CONST64(0x0002000002000002), CONST64(0x0002008002000002), 
  CONST64(0x0002000000020002), CONST64(0x0002008000020002), CONST64(0x0002000002020002), CONST64(0x0002008002020002), 
  CONST64(0x0002000000000202), CONST64(0x0002008000000202), CONST64(0x0002000002000202), CONST64(0x0002008002000202), 
  CONST64(0x0002000000020202), CONST64(0x0002008000020202), CONST64(0x0002000002020202), CONST64(0x0002008002020202), 
  CONST64(0x0202000000000000), CONST64(0x0202008000000000), CONST64(0x0202000002000000), CONST64(0x0202008002000000), 
  CONST64(0x0202000000020000), CONST64(0x0202008000020000), CONST64(0x0202000002020000), CONST64(0x0202008002020000), 
  CONST64(0x0202000000000200), CONST64(0x0202008000000200), CONST64(0x0202000002000200), CONST64(0x0202008002000200), 
  CONST64(0x0202000000020200), CONST64(0x0202008000020200), CONST64(0x0202000002020200), CONST64(0x0202008002020200), 
  CONST64(0x0202000000000002), CONST64(0x0202008000000002), CONST64(0x0202000002000002), CONST64(0x0202008002000002), 
  CONST64(0x0202000000020002), CONST64(0x0202008000020002), CONST64(0x0202000002020002), CONST64(0x0202008002020002), 
  CONST64(0x0202000000000202), CONST64(0x0202008000000202), CONST64(0x0202000002000202), CONST64(0x0202008002000202), 
  CONST64(0x0202000000020202), CONST64(0x0202008000020202), CONST64(0x0202000002020202), CONST64(0x0202008002020202), 
  CONST64(0x0000020000000000), CONST64(0x0000028000000000), CONST64(0x0000020002000000), CONST64(0x0000028002000000), 
  CONST64(0x0000020000020000), CONST64(0x0000028000020000), CONST64(0x0000020002020000), CONST64(0x0000028002020000), 
  CONST64(0x0000020000000200), CONST64(0x0000028000000200), CONST64(0x0000020002000200), CONST64(0x0000028002000200), 
  CONST64(0x0000020000020200), CONST64(0x0000028000020200), CONST64(0x0000020002020200), CONST64(0x0000028002020200), 
  CONST64(0x0000020000000002), CONST64(0x0000028000000002), CONST64(0x0000020002000002), CONST64(0x0000028002000002), 
  CONST64(0x0000020000020002), CONST64(0x0000028000020002), CONST64(0x0000020002020002), CONST64(0x0000028002020002), 
  CONST64(0x0000020000000202), CONST64(0x0000028000000202), CONST64(0x0000020002000202), CONST64(0x0000028002000202), 
  CONST64(0x0000020000020202), CONST64(0x0000028000020202), CONST64(0x0000020002020202), CONST64(0x0000028002020202), 
  CONST64(0x0200020000000000), CONST64(0x0200028000000000), CONST64(0x0200020002000000), CONST64(0x0200028002000000), 
  CONST64(0x0200020000020000), CONST64(0x0200028000020000), CONST64(0x0200020002020000), CONST64(0x0200028002020000), 
  CONST64(0x0200020000000200), CONST64(0x0200028000000200), CONST64(0x0200020002000200), CONST64(0x0200028002000200), 
  CONST64(0x0200020000020200), CONST64(0x0200028000020200), CONST64(0x0200020002020200), CONST64(0x0200028002020200), 
  CONST64(0x0200020000000002), CONST64(0x0200028000000002), CONST64(0x0200020002000002), CONST64(0x0200028002000002), 
  CONST64(0x0200020000020002), CONST64(0x0200028000020002), CONST64(0x0200020002020002), CONST64(0x0200028002020002), 
  CONST64(0x0200020000000202), CONST64(0x0200028000000202), CONST64(0x0200020002000202), CONST64(0x0200028002000202), 
  CONST64(0x0200020000020202), CONST64(0x0200028000020202), CONST64(0x0200020002020202), CONST64(0x0200028002020202), 
  CONST64(0x0002020000000000), CONST64(0x0002028000000000), CONST64(0x0002020002000000), CONST64(0x0002028002000000), 
  CONST64(0x0002020000020000), CONST64(0x0002028000020000), CONST64(0x0002020002020000), CONST64(0x0002028002020000), 
  CONST64(0x0002020000000200), CONST64(0x0002028000000200), CONST64(0x0002020002000200), CONST64(0x0002028002000200), 
  CONST64(0x0002020000020200), CONST64(0x0002028000020200), CONST64(0x0002020002020200), CONST64(0x0002028002020200), 
  CONST64(0x0002020000000002), CONST64(0x0002028000000002), CONST64(0x0002020002000002), CONST64(0x0002028002000002), 
  CONST64(0x0002020000020002), CONST64(0x0002028000020002), CONST64(0x0002020002020002), CONST64(0x0002028002020002), 
  CONST64(0x0002020000000202), CONST64(0x0002028000000202), CONST64(0x0002020002000202), CONST64(0x0002028002000202), 
  CONST64(0x0002020000020202), CONST64(0x0002028000020202), CONST64(0x0002020002020202), CONST64(0x0002028002020202), 
  CONST64(0x0202020000000000), CONST64(0x0202028000000000), CONST64(0x0202020002000000), CONST64(0x0202028002000000), 
  CONST64(0x0202020000020000), CONST64(0x0202028000020000), CONST64(0x0202020002020000), CONST64(0x0202028002020000), 
  CONST64(0x0202020000000200), CONST64(0x0202028000000200), CONST64(0x0202020002000200), CONST64(0x0202028002000200), 
  CONST64(0x0202020000020200), CONST64(0x0202028000020200), CONST64(0x0202020002020200), CONST64(0x0202028002020200), 
  CONST64(0x0202020000000002), CONST64(0x0202028000000002), CONST64(0x0202020002000002), CONST64(0x0202028002000002), 
  CONST64(0x0202020000020002), CONST64(0x0202028000020002), CONST64(0x0202020002020002), CONST64(0x0202028002020002), 
  CONST64(0x0202020000000202), CONST64(0x0202028000000202), CONST64(0x0202020002000202), CONST64(0x0202028002000202), 
  CONST64(0x0202020000020202), CONST64(0x0202028000020202), CONST64(0x0202020002020202), CONST64(0x0202028002020202)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000000200000000), CONST64(0x0000000008000000), CONST64(0x0000000208000000), 
  CONST64(0x0000000000080000), CONST64(0x0000000200080000), CONST64(0x0000000008080000), CONST64(0x0000000208080000), 
  CONST64(0x0000000000000800), CONST64(0x0000000200000800), CONST64(0x0000000008000800), CONST64(0x0000000208000800), 
  CONST64(0x0000000000080800), CONST64(0x0000000200080800), CONST64(0x0000000008080800), CONST64(0x0000000208080800), 
  CONST64(0x0000000000000008), CONST64(0x0000000200000008), CONST64(0x0000000008000008), CONST64(0x0000000208000008), 
  CONST64(0x0000000000080008), CONST64(0x0000000200080008), CONST64(0x0000000008080008), CONST64(0x0000000208080008), 
  CONST64(0x0000000000000808), CONST64(0x0000000200000808), CONST64(0x0000000008000808), CONST64(0x0000000208000808), 
  CONST64(0x0000000000080808), CONST64(0x0000000200080808), CONST64(0x0000000008080808), CONST64(0x0000000208080808), 
  CONST64(0x0800000000000000), CONST64(0x0800000200000000), CONST64(0x0800000008000000), CONST64(0x0800000208000000), 
  CONST64(0x0800000000080000), CONST64(0x0800000200080000), CONST64(0x0800000008080000), CONST64(0x0800000208080000), 
  CONST64(0x0800000000000800), CONST64(0x0800000200000800), CONST64(0x0800000008000800), CONST64(0x0800000208000800), 
  CONST64(0x0800000000080800), CONST64(0x0800000200080800), CONST64(0x0800000008080800), CONST64(0x0800000208080800), 
  CONST64(0x0800000000000008), CONST64(0x0800000200000008), CONST64(0x0800000008000008), CONST64(0x0800000208000008), 
  CONST64(0x0800000000080008), CONST64(0x0800000200080008), CONST64(0x0800000008080008), CONST64(0x0800000208080008), 
  CONST64(0x0800000000000808), CONST64(0x0800000200000808), CONST64(0x0800000008000808), CONST64(0x0800000208000808), 
  CONST64(0x0800000000080808), CONST64(0x0800000200080808), CONST64(0x0800000008080808), CONST64(0x0800000208080808), 
  CONST64(0x0008000000000000), CONST64(0x0008000200000000), CONST64(0x0008000008000000), CONST64(0x0008000208000000), 
  CONST64(0x0008000000080000), CONST64(0x0008000200080000), CONST64(0x0008000008080000), CONST64(0x0008000208080000), 
  CONST64(0x0008000000000800), CONST64(0x0008000200000800), CONST64(0x0008000008000800), CONST64(0x0008000208000800), 
  CONST64(0x0008000000080800), CONST64(0x0008000200080800), CONST64(0x0008000008080800), CONST64(0x0008000208080800), 
  CONST64(0x0008000000000008), CONST64(0x0008000200000008), CONST64(0x0008000008000008), CONST64(0x0008000208000008), 
  CONST64(0x0008000000080008), CONST64(0x0008000200080008), CONST64(0x0008000008080008), CONST64(0x0008000208080008), 
  CONST64(0x0008000000000808), CONST64(0x0008000200000808), CONST64(0x0008000008000808), CONST64(0x0008000208000808), 
  CONST64(0x0008000000080808), CONST64(0x0008000200080808), CONST64(0x0008000008080808), CONST64(0x0008000208080808), 
  CONST64(0x0808000000000000), CONST64(0x0808000200000000), CONST64(0x0808000008000000), CONST64(0x0808000208000000), 
  CONST64(0x0808000000080000), CONST64(0x0808000200080000), CONST64(0x0808000008080000), CONST64(0x0808000208080000), 
  CONST64(0x0808000000000800), CONST64(0x0808000200000800), CONST64(0x0808000008000800), CONST64(0x0808000208000800), 
  CONST64(0x0808000000080800), CONST64(0x0808000200080800), CONST64(0x0808000008080800), CONST64(0x0808000208080800), 
  CONST64(0x0808000000000008), CONST64(0x0808000200000008), CONST64(0x0808000008000008), CONST64(0x0808000208000008), 
  CONST64(0x0808000000080008), CONST64(0x0808000200080008), CONST64(0x0808000008080008), CONST64(0x0808000208080008), 
  CONST64(0x0808000000000808), CONST64(0x0808000200000808), CONST64(0x0808000008000808), CONST64(0x0808000208000808), 
  CONST64(0x0808000000080808), CONST64(0x0808000200080808), CONST64(0x0808000008080808), CONST64(0x0808000208080808), 
  CONST64(0x0000080000000000), CONST64(0x0000080200000000), CONST64(0x0000080008000000), CONST64(0x0000080208000000), 
  CONST64(0x0000080000080000), CONST64(0x0000080200080000), CONST64(0x0000080008080000), CONST64(0x0000080208080000), 
  CONST64(0x0000080000000800), CONST64(0x0000080200000800), CONST64(0x0000080008000800), CONST64(0x0000080208000800), 
  CONST64(0x0000080000080800), CONST64(0x0000080200080800), CONST64(0x0000080008080800), CONST64(0x0000080208080800), 
  CONST64(0x0000080000000008), CONST64(0x0000080200000008), CONST64(0x0000080008000008), CONST64(0x0000080208000008), 
  CONST64(0x0000080000080008), CONST64(0x0000080200080008), CONST64(0x0000080008080008), CONST64(0x0000080208080008), 
  CONST64(0x0000080000000808), CONST64(0x0000080200000808), CONST64(0x0000080008000808), CONST64(0x0000080208000808), 
  CONST64(0x0000080000080808), CONST64(0x0000080200080808), CONST64(0x0000080008080808), CONST64(0x0000080208080808), 
  CONST64(0x0800080000000000), CONST64(0x0800080200000000), CONST64(0x0800080008000000), CONST64(0x0800080208000000), 
  CONST64(0x0800080000080000), CONST64(0x0800080200080000), CONST64(0x0800080008080000), CONST64(0x0800080208080000), 
  CONST64(0x0800080000000800), CONST64(0x0800080200000800), CONST64(0x0800080008000800), CONST64(0x0800080208000800), 
  CONST64(0x0800080000080800), CONST64(0x0800080200080800), CONST64(0x0800080008080800), CONST64(0x0800080208080800), 
  CONST64(0x0800080000000008), CONST64(0x0800080200000008), CONST64(0x0800080008000008), CONST64(0x0800080208000008), 
  CONST64(0x0800080000080008), CONST64(0x0800080200080008), CONST64(0x0800080008080008), CONST64(0x0800080208080008), 
  CONST64(0x0800080000000808), CONST64(0x0800080200000808), CONST64(0x0800080008000808), CONST64(0x0800080208000808), 
  CONST64(0x0800080000080808), CONST64(0x0800080200080808), CONST64(0x0800080008080808), CONST64(0x0800080208080808), 
  CONST64(0x0008080000000000), CONST64(0x0008080200000000), CONST64(0x0008080008000000), CONST64(0x0008080208000000), 
  CONST64(0x0008080000080000), CONST64(0x0008080200080000), CONST64(0x0008080008080000), CONST64(0x0008080208080000), 
  CONST64(0x0008080000000800), CONST64(0x0008080200000800), CONST64(0x0008080008000800), CONST64(0x0008080208000800), 
  CONST64(0x0008080000080800), CONST64(0x0008080200080800), CONST64(0x0008080008080800), CONST64(0x0008080208080800), 
  CONST64(0x0008080000000008), CONST64(0x0008080200000008), CONST64(0x0008080008000008), CONST64(0x0008080208000008), 
  CONST64(0x0008080000080008), CONST64(0x0008080200080008), CONST64(0x0008080008080008), CONST64(0x0008080208080008), 
  CONST64(0x0008080000000808), CONST64(0x0008080200000808), CONST64(0x0008080008000808), CONST64(0x0008080208000808), 
  CONST64(0x0008080000080808), CONST64(0x0008080200080808), CONST64(0x0008080008080808), CONST64(0x0008080208080808), 
  CONST64(0x0808080000000000), CONST64(0x0808080200000000), CONST64(0x0808080008000000), CONST64(0x0808080208000000), 
  CONST64(0x0808080000080000), CONST64(0x0808080200080000), CONST64(0x0808080008080000), CONST64(0x0808080208080000), 
  CONST64(0x0808080000000800), CONST64(0x0808080200000800), CONST64(0x0808080008000800), CONST64(0x0808080208000800), 
  CONST64(0x0808080000080800), CONST64(0x0808080200080800), CONST64(0x0808080008080800), CONST64(0x0808080208080800), 
  CONST64(0x0808080000000008), CONST64(0x0808080200000008), CONST64(0x0808080008000008), CONST64(0x0808080208000008), 
  CONST64(0x0808080000080008), CONST64(0x0808080200080008), CONST64(0x0808080008080008), CONST64(0x0808080208080008), 
  CONST64(0x0808080000000808), CONST64(0x0808080200000808), CONST64(0x0808080008000808), CONST64(0x0808080208000808), 
  CONST64(0x0808080000080808), CONST64(0x0808080200080808), CONST64(0x0808080008080808), CONST64(0x0808080208080808)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000000800000000), CONST64(0x0000000020000000), CONST64(0x0000000820000000), 
  CONST64(0x0000000000200000), CONST64(0x0000000800200000), CONST64(0x0000000020200000), CONST64(0x0000000820200000), 
  CONST64(0x0000000000002000), CONST64(0x0000000800002000), CONST64(0x0000000020002000), CONST64(0x0000000820002000), 
  CONST64(0x0000000000202000), CONST64(0x0000000800202000), CONST64(0x0000000020202000), CONST64(0x0000000820202000), 
  CONST64(0x0000000000000020), CONST64(0x0000000800000020), CONST64(0x0000000020000020), CONST64(0x0000000820000020), 
  CONST64(0x0000000000200020), CONST64(0x0000000800200020), CONST64(0x0000000020200020), CONST64(0x0000000820200020), 
  CONST64(0x0000000000002020), CONST64(0x0000000800002020), CONST64(0x0000000020002020), CONST64(0x0000000820002020), 
  CONST64(0x0000000000202020), CONST64(0x0000000800202020), CONST64(0x0000000020202020), CONST64(0x0000000820202020), 
  CONST64(0x2000000000000000), CONST64(0x2000000800000000), CONST64(0x2000000020000000), CONST64(0x2000000820000000), 
  CONST64(0x2000000000200000), CONST64(0x2000000800200000), CONST64(0x2000000020200000), CONST64(0x2000000820200000), 
  CONST64(0x2000000000002000), CONST64(0x2000000800002000), CONST64(0x2000000020002000), CONST64(0x2000000820002000), 
  CONST64(0x2000000000202000), CONST64(0x2000000800202000), CONST64(0x2000000020202000), CONST64(0x2000000820202000), 
  CONST64(0x2000000000000020), CONST64(0x2000000800000020), CONST64(0x2000000020000020), CONST64(0x2000000820000020), 
  CONST64(0x2000000000200020), CONST64(0x2000000800200020), CONST64(0x2000000020200020), CONST64(0x2000000820200020), 
  CONST64(0x2000000000002020), CONST64(0x2000000800002020), CONST64(0x2000000020002020), CONST64(0x2000000820002020), 
  CONST64(0x2000000000202020), CONST64(0x2000000800202020), CONST64(0x2000000020202020), CONST64(0x2000000820202020), 
  CONST64(0x0020000000000000), CONST64(0x0020000800000000), CONST64(0x0020000020000000), CONST64(0x0020000820000000), 
  CONST64(0x0020000000200000), CONST64(0x0020000800200000), CONST64(0x0020000020200000), CONST64(0x0020000820200000), 
  CONST64(0x0020000000002000), CONST64(0x0020000800002000), CONST64(0x0020000020002000), CONST64(0x0020000820002000), 
  CONST64(0x0020000000202000), CONST64(0x0020000800202000), CONST64(0x0020000020202000), CONST64(0x0020000820202000), 
  CONST64(0x0020000000000020), CONST64(0x0020000800000020), CONST64(0x0020000020000020), CONST64(0x0020000820000020), 
  CONST64(0x0020000000200020), CONST64(0x0020000800200020), CONST64(0x0020000020200020), CONST64(0x0020000820200020), 
  CONST64(0x0020000000002020), CONST64(0x0020000800002020), CONST64(0x0020000020002020), CONST64(0x0020000820002020), 
  CONST64(0x0020000000202020), CONST64(0x0020000800202020), CONST64(0x0020000020202020), CONST64(0x0020000820202020), 
  CONST64(0x2020000000000000), CONST64(0x2020000800000000), CONST64(0x2020000020000000), CONST64(0x2020000820000000), 
  CONST64(0x2020000000200000), CONST64(0x2020000800200000), CONST64(0x2020000020200000), CONST64(0x2020000820200000), 
  CONST64(0x2020000000002000), CONST64(0x2020000800002000), CONST64(0x2020000020002000), CONST64(0x2020000820002000), 
  CONST64(0x2020000000202000), CONST64(0x2020000800202000), CONST64(0x2020000020202000), CONST64(0x2020000820202000), 
  CONST64(0x2020000000000020), CONST64(0x2020000800000020), CONST64(0x2020000020000020), CONST64(0x2020000820000020), 
  CONST64(0x2020000000200020), CONST64(0x2020000800200020), CONST64(0x2020000020200020), CONST64(0x2020000820200020), 
  CONST64(0x2020000000002020), CONST64(0x2020000800002020), CONST64(0x2020000020002020), CONST64(0x2020000820002020), 
  CONST64(0x2020000000202020), CONST64(0x2020000800202020), CONST64(0x2020000020202020), CONST64(0x2020000820202020), 
  CONST64(0x0000200000000000), CONST64(0x0000200800000000), CONST64(0x0000200020000000), CONST64(0x0000200820000000), 
  CONST64(0x0000200000200000), CONST64(0x0000200800200000), CONST64(0x0000200020200000), CONST64(0x0000200820200000), 
  CONST64(0x0000200000002000), CONST64(0x0000200800002000), CONST64(0x0000200020002000), CONST64(0x0000200820002000), 
  CONST64(0x0000200000202000), CONST64(0x0000200800202000), CONST64(0x0000200020202000), CONST64(0x0000200820202000), 
  CONST64(0x0000200000000020), CONST64(0x0000200800000020), CONST64(0x0000200020000020), CONST64(0x0000200820000020), 
  CONST64(0x0000200000200020), CONST64(0x0000200800200020), CONST64(0x0000200020200020), CONST64(0x0000200820200020), 
  CONST64(0x0000200000002020), CONST64(0x0000200800002020), CONST64(0x0000200020002020), CONST64(0x0000200820002020), 
  CONST64(0x0000200000202020), CONST64(0x0000200800202020), CONST64(0x0000200020202020), CONST64(0x0000200820202020), 
  CONST64(0x2000200000000000), CONST64(0x2000200800000000), CONST64(0x2000200020000000), CONST64(0x2000200820000000), 
  CONST64(0x2000200000200000), CONST64(0x2000200800200000), CONST64(0x2000200020200000), CONST64(0x2000200820200000), 
  CONST64(0x2000200000002000), CONST64(0x2000200800002000), CONST64(0x2000200020002000), CONST64(0x2000200820002000), 
  CONST64(0x2000200000202000), CONST64(0x2000200800202000), CONST64(0x2000200020202000), CONST64(0x2000200820202000), 
  CONST64(0x2000200000000020), CONST64(0x2000200800000020), CONST64(0x2000200020000020), CONST64(0x2000200820000020), 
  CONST64(0x2000200000200020), CONST64(0x2000200800200020), CONST64(0x2000200020200020), CONST64(0x2000200820200020), 
  CONST64(0x2000200000002020), CONST64(0x2000200800002020), CONST64(0x2000200020002020), CONST64(0x2000200820002020), 
  CONST64(0x2000200000202020), CONST64(0x2000200800202020), CONST64(0x2000200020202020), CONST64(0x2000200820202020), 
  CONST64(0x0020200000000000), CONST64(0x0020200800000000), CONST64(0x0020200020000000), CONST64(0x0020200820000000), 
  CONST64(0x0020200000200000), CONST64(0x0020200800200000), CONST64(0x0020200020200000), CONST64(0x0020200820200000), 
  CONST64(0x0020200000002000), CONST64(0x0020200800002000), CONST64(0x0020200020002000), CONST64(0x0020200820002000), 
  CONST64(0x0020200000202000), CONST64(0x0020200800202000), CONST64(0x0020200020202000), CONST64(0x0020200820202000), 
  CONST64(0x0020200000000020), CONST64(0x0020200800000020), CONST64(0x0020200020000020), CONST64(0x0020200820000020), 
  CONST64(0x0020200000200020), CONST64(0x0020200800200020), CONST64(0x0020200020200020), CONST64(0x0020200820200020), 
  CONST64(0x0020200000002020), CONST64(0x0020200800002020), CONST64(0x0020200020002020), CONST64(0x0020200820002020), 
  CONST64(0x0020200000202020), CONST64(0x0020200800202020), CONST64(0x0020200020202020), CONST64(0x0020200820202020), 
  CONST64(0x2020200000000000), CONST64(0x2020200800000000), CONST64(0x2020200020000000), CONST64(0x2020200820000000), 
  CONST64(0x2020200000200000), CONST64(0x2020200800200000), CONST64(0x2020200020200000), CONST64(0x2020200820200000), 
  CONST64(0x2020200000002000), CONST64(0x2020200800002000), CONST64(0x2020200020002000), CONST64(0x2020200820002000), 
  CONST64(0x2020200000202000), CONST64(0x2020200800202000), CONST64(0x2020200020202000), CONST64(0x2020200820202000), 
  CONST64(0x2020200000000020), CONST64(0x2020200800000020), CONST64(0x2020200020000020), CONST64(0x2020200820000020), 
  CONST64(0x2020200000200020), CONST64(0x2020200800200020), CONST64(0x2020200020200020), CONST64(0x2020200820200020), 
  CONST64(0x2020200000002020), CONST64(0x2020200800002020), CONST64(0x2020200020002020), CONST64(0x2020200820002020), 
  CONST64(0x2020200000202020), CONST64(0x2020200800202020), CONST64(0x2020200020202020), CONST64(0x2020200820202020)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000002000000000), CONST64(0x0000000080000000), CONST64(0x0000002080000000), 
  CONST64(0x0000000000800000), CONST64(0x0000002000800000), CONST64(0x0000000080800000), CONST64(0x0000002080800000), 
  CONST64(0x0000000000008000), CONST64(0x0000002000008000), CONST64(0x0000000080008000), CONST64(0x0000002080008000), 
  CONST64(0x0000000000808000), CONST64(0x0000002000808000), CONST64(0x0000000080808000), CONST64(0x0000002080808000), 
  CONST64(0x0000000000000080), CONST64(0x0000002000000080), CONST64(0x0000000080000080), CONST64(0x0000002080000080), 
  CONST64(0x0000000000800080), CONST64(0x0000002000800080), CONST64(0x0000000080800080), CONST64(0x0000002080800080), 
  CONST64(0x0000000000008080), CONST64(0x0000002000008080), CONST64(0x0000000080008080), CONST64(0x0000002080008080), 
  CONST64(0x0000000000808080), CONST64(0x0000002000808080), CONST64(0x0000000080808080), CONST64(0x0000002080808080), 
  CONST64(0x8000000000000000), CONST64(0x8000002000000000), CONST64(0x8000000080000000), CONST64(0x8000002080000000), 
  CONST64(0x8000000000800000), CONST64(0x8000002000800000), CONST64(0x8000000080800000), CONST64(0x8000002080800000), 
  CONST64(0x8000000000008000), CONST64(0x8000002000008000), CONST64(0x8000000080008000), CONST64(0x8000002080008000), 
  CONST64(0x8000000000808000), CONST64(0x8000002000808000), CONST64(0x8000000080808000), CONST64(0x8000002080808000), 
  CONST64(0x8000000000000080), CONST64(0x8000002000000080), CONST64(0x8000000080000080), CONST64(0x8000002080000080), 
  CONST64(0x8000000000800080), CONST64(0x8000002000800080), CONST64(0x8000000080800080), CONST64(0x8000002080800080), 
  CONST64(0x8000000000008080), CONST64(0x8000002000008080), CONST64(0x8000000080008080), CONST64(0x8000002080008080), 
  CONST64(0x8000000000808080), CONST64(0x8000002000808080), CONST64(0x8000000080808080), CONST64(0x8000002080808080), 
  CONST64(0x0080000000000000), CONST64(0x0080002000000000), CONST64(0x0080000080000000), CONST64(0x0080002080000000), 
  CONST64(0x0080000000800000), CONST64(0x0080002000800000), CONST64(0x0080000080800000), CONST64(0x0080002080800000), 
  CONST64(0x0080000000008000), CONST64(0x0080002000008000), CONST64(0x0080000080008000), CONST64(0x0080002080008000), 
  CONST64(0x0080000000808000), CONST64(0x0080002000808000), CONST64(0x0080000080808000), CONST64(0x0080002080808000), 
  CONST64(0x0080000000000080), CONST64(0x0080002000000080), CONST64(0x0080000080000080), CONST64(0x0080002080000080), 
  CONST64(0x0080000000800080), CONST64(0x0080002000800080), CONST64(0x0080000080800080), CONST64(0x0080002080800080), 
  CONST64(0x0080000000008080), CONST64(0x0080002000008080), CONST64(0x0080000080008080), CONST64(0x0080002080008080), 
  CONST64(0x0080000000808080), CONST64(0x0080002000808080), CONST64(0x0080000080808080), CONST64(0x0080002080808080), 
  CONST64(0x8080000000000000), CONST64(0x8080002000000000), CONST64(0x8080000080000000), CONST64(0x8080002080000000), 
  CONST64(0x8080000000800000), CONST64(0x8080002000800000), CONST64(0x8080000080800000), CONST64(0x8080002080800000), 
  CONST64(0x8080000000008000), CONST64(0x8080002000008000), CONST64(0x8080000080008000), CONST64(0x8080002080008000), 
  CONST64(0x8080000000808000), CONST64(0x8080002000808000), CONST64(0x8080000080808000), CONST64(0x8080002080808000), 
  CONST64(0x8080000000000080), CONST64(0x8080002000000080), CONST64(0x8080000080000080), CONST64(0x8080002080000080), 
  CONST64(0x8080000000800080), CONST64(0x8080002000800080), CONST64(0x8080000080800080), CONST64(0x8080002080800080), 
  CONST64(0x8080000000008080), CONST64(0x8080002000008080), CONST64(0x8080000080008080), CONST64(0x8080002080008080), 
  CONST64(0x8080000000808080), CONST64(0x8080002000808080), CONST64(0x8080000080808080), CONST64(0x8080002080808080), 
  CONST64(0x0000800000000000), CONST64(0x0000802000000000), CONST64(0x0000800080000000), CONST64(0x0000802080000000), 
  CONST64(0x0000800000800000), CONST64(0x0000802000800000), CONST64(0x0000800080800000), CONST64(0x0000802080800000), 
  CONST64(0x0000800000008000), CONST64(0x0000802000008000), CONST64(0x0000800080008000), CONST64(0x0000802080008000), 
  CONST64(0x0000800000808000), CONST64(0x0000802000808000), CONST64(0x0000800080808000), CONST64(0x0000802080808000), 
  CONST64(0x0000800000000080), CONST64(0x0000802000000080), CONST64(0x0000800080000080), CONST64(0x0000802080000080), 
  CONST64(0x0000800000800080), CONST64(0x0000802000800080), CONST64(0x0000800080800080), CONST64(0x0000802080800080), 
  CONST64(0x0000800000008080), CONST64(0x0000802000008080), CONST64(0x0000800080008080), CONST64(0x0000802080008080), 
  CONST64(0x0000800000808080), CONST64(0x0000802000808080), CONST64(0x0000800080808080), CONST64(0x0000802080808080), 
  CONST64(0x8000800000000000), CONST64(0x8000802000000000), CONST64(0x8000800080000000), CONST64(0x8000802080000000), 
  CONST64(0x8000800000800000), CONST64(0x8000802000800000), CONST64(0x8000800080800000), CONST64(0x8000802080800000), 
  CONST64(0x8000800000008000), CONST64(0x8000802000008000), CONST64(0x8000800080008000), CONST64(0x8000802080008000), 
  CONST64(0x8000800000808000), CONST64(0x8000802000808000), CONST64(0x8000800080808000), CONST64(0x8000802080808000), 
  CONST64(0x8000800000000080), CONST64(0x8000802000000080), CONST64(0x8000800080000080), CONST64(0x8000802080000080), 
  CONST64(0x8000800000800080), CONST64(0x8000802000800080), CONST64(0x8000800080800080), CONST64(0x8000802080800080), 
  CONST64(0x8000800000008080), CONST64(0x8000802000008080), CONST64(0x8000800080008080), CONST64(0x8000802080008080), 
  CONST64(0x8000800000808080), CONST64(0x8000802000808080), CONST64(0x8000800080808080), CONST64(0x8000802080808080), 
  CONST64(0x0080800000000000), CONST64(0x0080802000000000), CONST64(0x0080800080000000), CONST64(0x0080802080000000), 
  CONST64(0x0080800000800000), CONST64(0x0080802000800000), CONST64(0x0080800080800000), CONST64(0x0080802080800000), 
  CONST64(0x0080800000008000), CONST64(0x0080802000008000), CONST64(0x0080800080008000), CONST64(0x0080802080008000), 
  CONST64(0x0080800000808000), CONST64(0x0080802000808000), CONST64(0x0080800080808000), CONST64(0x0080802080808000), 
  CONST64(0x0080800000000080), CONST64(0x0080802000000080), CONST64(0x0080800080000080), CONST64(0x0080802080000080), 
  CONST64(0x0080800000800080), CONST64(0x0080802000800080), CONST64(0x0080800080800080), CONST64(0x0080802080800080), 
  CONST64(0x0080800000008080), CONST64(0x0080802000008080), CONST64(0x0080800080008080), CONST64(0x0080802080008080), 
  CONST64(0x0080800000808080), CONST64(0x0080802000808080), CONST64(0x0080800080808080), CONST64(0x0080802080808080), 
  CONST64(0x8080800000000000), CONST64(0x8080802000000000), CONST64(0x8080800080000000), CONST64(0x8080802080000000), 
  CONST64(0x8080800000800000), CONST64(0x8080802000800000), CONST64(0x8080800080800000), CONST64(0x8080802080800000), 
  CONST64(0x8080800000008000), CONST64(0x8080802000008000), CONST64(0x8080800080008000), CONST64(0x8080802080008000), 
  CONST64(0x8080800000808000), CONST64(0x8080802000808000), CONST64(0x8080800080808000), CONST64(0x8080802080808000), 
  CONST64(0x8080800000000080), CONST64(0x8080802000000080), CONST64(0x8080800080000080), CONST64(0x8080802080000080), 
  CONST64(0x8080800000800080), CONST64(0x8080802000800080), CONST64(0x8080800080800080), CONST64(0x8080802080800080), 
  CONST64(0x8080800000008080), CONST64(0x8080802000008080), CONST64(0x8080800080008080), CONST64(0x8080802080008080), 
  CONST64(0x8080800000808080), CONST64(0x8080802000808080), CONST64(0x8080800080808080), CONST64(0x8080802080808080)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000004000000000), CONST64(0x0000000001000000), CONST64(0x0000004001000000), 
  CONST64(0x0000000000010000), CONST64(0x0000004000010000), CONST64(0x0000000001010000), CONST64(0x0000004001010000), 
  CONST64(0x0000000000000100), CONST64(0x0000004000000100), CONST64(0x0000000001000100), CONST64(0x0000004001000100), 
  CONST64(0x0000000000010100), CONST64(0x0000004000010100), CONST64(0x0000000001010100), CONST64(0x0000004001010100), 
  CONST64(0x0000000000000001), CONST64(0x0000004000000001), CONST64(0x0000000001000001), CONST64(0x0000004001000001), 
  CONST64(0x0000000000010001), CONST64(0x0000004000010001), CONST64(0x0000000001010001), CONST64(0x0000004001010001), 
  CONST64(0x0000000000000101), CONST64(0x0000004000000101), CONST64(0x0000000001000101), CONST64(0x0000004001000101), 
  CONST64(0x0000000000010101), CONST64(0x0000004000010101), CONST64(0x0000000001010101), CONST64(0x0000004001010101), 
  CONST64(0x0100000000000000), CONST64(0x0100004000000000), CONST64(0x0100000001000000), CONST64(0x0100004001000000), 
  CONST64(0x0100000000010000), CONST64(0x0100004000010000), CONST64(0x0100000001010000), CONST64(0x0100004001010000), 
  CONST64(0x0100000000000100), CONST64(0x0100004000000100), CONST64(0x0100000001000100), CONST64(0x0100004001000100), 
  CONST64(0x0100000000010100), CONST64(0x0100004000010100), CONST64(0x0100000001010100), CONST64(0x0100004001010100), 
  CONST64(0x0100000000000001), CONST64(0x0100004000000001), CONST64(0x0100000001000001), CONST64(0x0100004001000001), 
  CONST64(0x0100000000010001), CONST64(0x0100004000010001), CONST64(0x0100000001010001), CONST64(0x0100004001010001), 
  CONST64(0x0100000000000101), CONST64(0x0100004000000101), CONST64(0x0100000001000101), CONST64(0x0100004001000101), 
  CONST64(0x0100000000010101), CONST64(0x0100004000010101), CONST64(0x0100000001010101), CONST64(0x0100004001010101), 
  CONST64(0x0001000000000000), CONST64(0x0001004000000000), CONST64(0x0001000001000000), CONST64(0x0001004001000000), 
  CONST64(0x0001000000010000), CONST64(0x0001004000010000), CONST64(0x0001000001010000), CONST64(0x0001004001010000), 
  CONST64(0x0001000000000100), CONST64(0x0001004000000100), CONST64(0x0001000001000100), CONST64(0x0001004001000100), 
  CONST64(0x0001000000010100), CONST64(0x0001004000010100), CONST64(0x0001000001010100), CONST64(0x0001004001010100), 
  CONST64(0x0001000000000001), CONST64(0x0001004000000001), CONST64(0x0001000001000001), CONST64(0x0001004001000001), 
  CONST64(0x0001000000010001), CONST64(0x0001004000010001), CONST64(0x0001000001010001), CONST64(0x0001004001010001), 
  CONST64(0x0001000000000101), CONST64(0x0001004000000101), CONST64(0x0001000001000101), CONST64(0x0001004001000101), 
  CONST64(0x0001000000010101), CONST64(0x0001004000010101), CONST64(0x0001000001010101), CONST64(0x0001004001010101), 
  CONST64(0x0101000000000000), CONST64(0x0101004000000000), CONST64(0x0101000001000000), CONST64(0x0101004001000000), 
  CONST64(0x0101000000010000), CONST64(0x0101004000010000), CONST64(0x0101000001010000), CONST64(0x0101004001010000), 
  CONST64(0x0101000000000100), CONST64(0x0101004000000100), CONST64(0x0101000001000100), CONST64(0x0101004001000100), 
  CONST64(0x0101000000010100), CONST64(0x0101004000010100), CONST64(0x0101000001010100), CONST64(0x0101004001010100), 
  CONST64(0x0101000000000001), CONST64(0x0101004000000001), CONST64(0x0101000001000001), CONST64(0x0101004001000001), 
  CONST64(0x0101000000010001), CONST64(0x0101004000010001), CONST64(0x0101000001010001), CONST64(0x0101004001010001), 
  CONST64(0x0101000000000101), CONST64(0x0101004000000101), CONST64(0x0101000001000101), CONST64(0x0101004001000101), 
  CONST64(0x0101000000010101), CONST64(0x0101004000010101), CONST64(0x0101000001010101), CONST64(0x0101004001010101), 
  CONST64(0x0000010000000000), CONST64(0x0000014000000000), CONST64(0x0000010001000000), CONST64(0x0000014001000000), 
  CONST64(0x0000010000010000), CONST64(0x0000014000010000), CONST64(0x0000010001010000), CONST64(0x0000014001010000), 
  CONST64(0x0000010000000100), CONST64(0x0000014000000100), CONST64(0x0000010001000100), CONST64(0x0000014001000100), 
  CONST64(0x0000010000010100), CONST64(0x0000014000010100), CONST64(0x0000010001010100), CONST64(0x0000014001010100), 
  CONST64(0x0000010000000001), CONST64(0x0000014000000001), CONST64(0x0000010001000001), CONST64(0x0000014001000001), 
  CONST64(0x0000010000010001), CONST64(0x0000014000010001), CONST64(0x0000010001010001), CONST64(0x0000014001010001), 
  CONST64(0x0000010000000101), CONST64(0x0000014000000101), CONST64(0x0000010001000101), CONST64(0x0000014001000101), 
  CONST64(0x0000010000010101), CONST64(0x0000014000010101), CONST64(0x0000010001010101), CONST64(0x0000014001010101), 
  CONST64(0x0100010000000000), CONST64(0x0100014000000000), CONST64(0x0100010001000000), CONST64(0x0100014001000000), 
  CONST64(0x0100010000010000), CONST64(0x0100014000010000), CONST64(0x0100010001010000), CONST64(0x0100014001010000), 
  CONST64(0x0100010000000100), CONST64(0x0100014000000100), CONST64(0x0100010001000100), CONST64(0x0100014001000100), 
  CONST64(0x0100010000010100), CONST64(0x0100014000010100), CONST64(0x0100010001010100), CONST64(0x0100014001010100), 
  CONST64(0x0100010000000001), CONST64(0x0100014000000001), CONST64(0x0100010001000001), CONST64(0x0100014001000001), 
  CONST64(0x0100010000010001), CONST64(0x0100014000010001), CONST64(0x0100010001010001), CONST64(0x0100014001010001), 
  CONST64(0x0100010000000101), CONST64(0x0100014000000101), CONST64(0x0100010001000101), CONST64(0x0100014001000101), 
  CONST64(0x0100010000010101), CONST64(0x0100014000010101), CONST64(0x0100010001010101), CONST64(0x0100014001010101), 
  CONST64(0x0001010000000000), CONST64(0x0001014000000000), CONST64(0x0001010001000000), CONST64(0x0001014001000000), 
  CONST64(0x0001010000010000), CONST64(0x0001014000010000), CONST64(0x0001010001010000), CONST64(0x0001014001010000), 
  CONST64(0x0001010000000100), CONST64(0x0001014000000100), CONST64(0x0001010001000100), CONST64(0x0001014001000100), 
  CONST64(0x0001010000010100), CONST64(0x0001014000010100), CONST64(0x0001010001010100), CONST64(0x0001014001010100), 
  CONST64(0x0001010000000001), CONST64(0x0001014000000001), CONST64(0x0001010001000001), CONST64(0x0001014001000001), 
  CONST64(0x0001010000010001), CONST64(0x0001014000010001), CONST64(0x0001010001010001), CONST64(0x0001014001010001), 
  CONST64(0x0001010000000101), CONST64(0x0001014000000101), CONST64(0x0001010001000101), CONST64(0x0001014001000101), 
  CONST64(0x0001010000010101), CONST64(0x0001014000010101), CONST64(0x0001010001010101), CONST64(0x0001014001010101), 
  CONST64(0x0101010000000000), CONST64(0x0101014000000000), CONST64(0x0101010001000000), CONST64(0x0101014001000000), 
  CONST64(0x0101010000010000), CONST64(0x0101014000010000), CONST64(0x0101010001010000), CONST64(0x0101014001010000), 
  CONST64(0x0101010000000100), CONST64(0x0101014000000100), CONST64(0x0101010001000100), CONST64(0x0101014001000100), 
  CONST64(0x0101010000010100), CONST64(0x0101014000010100), CONST64(0x0101010001010100), CONST64(0x0101014001010100), 
  CONST64(0x0101010000000001), CONST64(0x0101014000000001), CONST64(0x0101010001000001), CONST64(0x0101014001000001), 
  CONST64(0x0101010000010001), CONST64(0x0101014000010001), CONST64(0x0101010001010001), CONST64(0x0101014001010001), 
  CONST64(0x0101010000000101), CONST64(0x0101014000000101), CONST64(0x0101010001000101), CONST64(0x0101014001000101), 
  CONST64(0x0101010000010101), CONST64(0x0101014000010101), CONST64(0x0101010001010101), CONST64(0x0101014001010101)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000000100000000), CONST64(0x0000000004000000), CONST64(0x0000000104000000), 
  CONST64(0x0000000000040000), CONST64(0x0000000100040000), CONST64(0x0000000004040000), CONST64(0x0000000104040000), 
  CONST64(0x0000000000000400), CONST64(0x0000000100000400), CONST64(0x0000000004000400), CONST64(0x0000000104000400), 
  CONST64(0x0000000000040400), CONST64(0x0000000100040400), CONST64(0x0000000004040400), CONST64(0x0000000104040400), 
  CONST64(0x0000000000000004), CONST64(0x0000000100000004), CONST64(0x0000000004000004), CONST64(0x0000000104000004), 
  CONST64(0x0000000000040004), CONST64(0x0000000100040004), CONST64(0x0000000004040004), CONST64(0x0000000104040004), 
  CONST64(0x0000000000000404), CONST64(0x0000000100000404), CONST64(0x0000000004000404), CONST64(0x0000000104000404), 
  CONST64(0x0000000000040404), CONST64(0x0000000100040404), CONST64(0x0000000004040404), CONST64(0x0000000104040404), 
  CONST64(0x0400000000000000), CONST64(0x0400000100000000), CONST64(0x0400000004000000), CONST64(0x0400000104000000), 
  CONST64(0x0400000000040000), CONST64(0x0400000100040000), CONST64(0x0400000004040000), CONST64(0x0400000104040000), 
  CONST64(0x0400000000000400), CONST64(0x0400000100000400), CONST64(0x0400000004000400), CONST64(0x0400000104000400), 
  CONST64(0x0400000000040400), CONST64(0x0400000100040400), CONST64(0x0400000004040400), CONST64(0x0400000104040400), 
  CONST64(0x0400000000000004), CONST64(0x0400000100000004), CONST64(0x0400000004000004), CONST64(0x0400000104000004), 
  CONST64(0x0400000000040004), CONST64(0x0400000100040004), CONST64(0x0400000004040004), CONST64(0x0400000104040004), 
  CONST64(0x0400000000000404), CONST64(0x0400000100000404), CONST64(0x0400000004000404), CONST64(0x0400000104000404), 
  CONST64(0x0400000000040404), CONST64(0x0400000100040404), CONST64(0x0400000004040404), CONST64(0x0400000104040404), 
  CONST64(0x0004000000000000), CONST64(0x0004000100000000), CONST64(0x0004000004000000), CONST64(0x0004000104000000), 
  CONST64(0x0004000000040000), CONST64(0x0004000100040000), CONST64(0x0004000004040000), CONST64(0x0004000104040000), 
  CONST64(0x0004000000000400), CONST64(0x0004000100000400), CONST64(0x0004000004000400), CONST64(0x0004000104000400), 
  CONST64(0x0004000000040400), CONST64(0x0004000100040400), CONST64(0x0004000004040400), CONST64(0x0004000104040400), 
  CONST64(0x0004000000000004), CONST64(0x0004000100000004), CONST64(0x0004000004000004), CONST64(0x0004000104000004), 
  CONST64(0x0004000000040004), CONST64(0x0004000100040004), CONST64(0x0004000004040004), CONST64(0x0004000104040004), 
  CONST64(0x0004000000000404), CONST64(0x0004000100000404), CONST64(0x0004000004000404), CONST64(0x0004000104000404), 
  CONST64(0x0004000000040404), CONST64(0x0004000100040404), CONST64(0x0004000004040404), CONST64(0x0004000104040404), 
  CONST64(0x0404000000000000), CONST64(0x0404000100000000), CONST64(0x0404000004000000), CONST64(0x0404000104000000), 
  CONST64(0x0404000000040000), CONST64(0x0404000100040000), CONST64(0x0404000004040000), CONST64(0x0404000104040000), 
  CONST64(0x0404000000000400), CONST64(0x0404000100000400), CONST64(0x0404000004000400), CONST64(0x0404000104000400), 
  CONST64(0x0404000000040400), CONST64(0x0404000100040400), CONST64(0x0404000004040400), CONST64(0x0404000104040400), 
  CONST64(0x0404000000000004), CONST64(0x0404000100000004), CONST64(0x0404000004000004), CONST64(0x0404000104000004), 
  CONST64(0x0404000000040004), CONST64(0x0404000100040004), CONST64(0x0404000004040004), CONST64(0x0404000104040004), 
  CONST64(0x0404000000000404), CONST64(0x0404000100000404), CONST64(0x0404000004000404), CONST64(0x0404000104000404), 
  CONST64(0x0404000000040404), CONST64(0x0404000100040404), CONST64(0x0404000004040404), CONST64(0x0404000104040404), 
  CONST64(0x0000040000000000), CONST64(0x0000040100000000), CONST64(0x0000040004000000), CONST64(0x0000040104000000), 
  CONST64(0x0000040000040000), CONST64(0x0000040100040000), CONST64(0x0000040004040000), CONST64(0x0000040104040000), 
  CONST64(0x0000040000000400), CONST64(0x0000040100000400), CONST64(0x0000040004000400), CONST64(0x0000040104000400), 
  CONST64(0x0000040000040400), CONST64(0x0000040100040400), CONST64(0x0000040004040400), CONST64(0x0000040104040400), 
  CONST64(0x0000040000000004), CONST64(0x0000040100000004), CONST64(0x0000040004000004), CONST64(0x0000040104000004), 
  CONST64(0x0000040000040004), CONST64(0x0000040100040004), CONST64(0x0000040004040004), CONST64(0x0000040104040004), 
  CONST64(0x0000040000000404), CONST64(0x0000040100000404), CONST64(0x0000040004000404), CONST64(0x0000040104000404), 
  CONST64(0x0000040000040404), CONST64(0x0000040100040404), CONST64(0x0000040004040404), CONST64(0x0000040104040404), 
  CONST64(0x0400040000000000), CONST64(0x0400040100000000), CONST64(0x0400040004000000), CONST64(0x0400040104000000), 
  CONST64(0x0400040000040000), CONST64(0x0400040100040000), CONST64(0x0400040004040000), CONST64(0x0400040104040000), 
  CONST64(0x0400040000000400), CONST64(0x0400040100000400), CONST64(0x0400040004000400), CONST64(0x0400040104000400), 
  CONST64(0x0400040000040400), CONST64(0x0400040100040400), CONST64(0x0400040004040400), CONST64(0x0400040104040400), 
  CONST64(0x0400040000000004), CONST64(0x0400040100000004), CONST64(0x0400040004000004), CONST64(0x0400040104000004), 
  CONST64(0x0400040000040004), CONST64(0x0400040100040004), CONST64(0x0400040004040004), CONST64(0x0400040104040004), 
  CONST64(0x0400040000000404), CONST64(0x0400040100000404), CONST64(0x0400040004000404), CONST64(0x0400040104000404), 
  CONST64(0x0400040000040404), CONST64(0x0400040100040404), CONST64(0x0400040004040404), CONST64(0x0400040104040404), 
  CONST64(0x0004040000000000), CONST64(0x0004040100000000), CONST64(0x0004040004000000), CONST64(0x0004040104000000), 
  CONST64(0x0004040000040000), CONST64(0x0004040100040000), CONST64(0x0004040004040000), CONST64(0x0004040104040000), 
  CONST64(0x0004040000000400), CONST64(0x0004040100000400), CONST64(0x0004040004000400), CONST64(0x0004040104000400), 
  CONST64(0x0004040000040400), CONST64(0x0004040100040400), CONST64(0x0004040004040400), CONST64(0x0004040104040400), 
  CONST64(0x0004040000000004), CONST64(0x0004040100000004), CONST64(0x0004040004000004), CONST64(0x0004040104000004), 
  CONST64(0x0004040000040004), CONST64(0x0004040100040004), CONST64(0x0004040004040004), CONST64(0x0004040104040004), 
  CONST64(0x0004040000000404), CONST64(0x0004040100000404), CONST64(0x0004040004000404), CONST64(0x0004040104000404), 
  CONST64(0x0004040000040404), CONST64(0x0004040100040404), CONST64(0x0004040004040404), CONST64(0x0004040104040404), 
  CONST64(0x0404040000000000), CONST64(0x0404040100000000), CONST64(0x0404040004000000), CONST64(0x0404040104000000), 
  CONST64(0x0404040000040000), CONST64(0x0404040100040000), CONST64(0x0404040004040000), CONST64(0x0404040104040000), 
  CONST64(0x0404040000000400), CONST64(0x0404040100000400), CONST64(0x0404040004000400), CONST64(0x0404040104000400), 
  CONST64(0x0404040000040400), CONST64(0x0404040100040400), CONST64(0x0404040004040400), CONST64(0x0404040104040400), 
  CONST64(0x0404040000000004), CONST64(0x0404040100000004), CONST64(0x0404040004000004), CONST64(0x0404040104000004), 
  CONST64(0x0404040000040004), CONST64(0x0404040100040004), CONST64(0x0404040004040004), CONST64(0x0404040104040004), 
  CONST64(0x0404040000000404), CONST64(0x0404040100000404), CONST64(0x0404040004000404), CONST64(0x0404040104000404), 
  CONST64(0x0404040000040404), CONST64(0x0404040100040404), CONST64(0x0404040004040404), CONST64(0x0404040104040404)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000000400000000), CONST64(0x0000000010000000), CONST64(0x0000000410000000), 
  CONST64(0x0000000000100000), CONST64(0x0000000400100000), CONST64(0x0000000010100000), CONST64(0x0000000410100000), 
  CONST64(0x0000000000001000), CONST64(0x0000000400001000), CONST64(0x0000000010001000), CONST64(0x0000000410001000), 
  CONST64(0x0000000000101000), CONST64(0x0000000400101000), CONST64(0x0000000010101000), CONST64(0x0000000410101000), 
  CONST64(0x0000000000000010), CONST64(0x0000000400000010), CONST64(0x0000000010000010), CONST64(0x0000000410000010), 
  CONST64(0x0000000000100010), CONST64(0x0000000400100010), CONST64(0x0000000010100010), CONST64(0x0000000410100010), 
  CONST64(0x0000000000001010), CONST64(0x0000000400001010), CONST64(0x0000000010001010), CONST64(0x0000000410001010), 
  CONST64(0x0000000000101010), CONST64(0x0000000400101010), CONST64(0x0000000010101010), CONST64(0x0000000410101010), 
  CONST64(0x1000000000000000), CONST64(0x1000000400000000), CONST64(0x1000000010000000), CONST64(0x1000000410000000), 
  CONST64(0x1000000000100000), CONST64(0x1000000400100000), CONST64(0x1000000010100000), CONST64(0x1000000410100000), 
  CONST64(0x1000000000001000), CONST64(0x1000000400001000), CONST64(0x1000000010001000), CONST64(0x1000000410001000), 
  CONST64(0x1000000000101000), CONST64(0x1000000400101000), CONST64(0x1000000010101000), CONST64(0x1000000410101000), 
  CONST64(0x1000000000000010), CONST64(0x1000000400000010), CONST64(0x1000000010000010), CONST64(0x1000000410000010), 
  CONST64(0x1000000000100010), CONST64(0x1000000400100010), CONST64(0x1000000010100010), CONST64(0x1000000410100010), 
  CONST64(0x1000000000001010), CONST64(0x1000000400001010), CONST64(0x1000000010001010), CONST64(0x1000000410001010), 
  CONST64(0x1000000000101010), CONST64(0x1000000400101010), CONST64(0x1000000010101010), CONST64(0x1000000410101010), 
  CONST64(0x0010000000000000), CONST64(0x0010000400000000), CONST64(0x0010000010000000), CONST64(0x0010000410000000), 
  CONST64(0x0010000000100000), CONST64(0x0010000400100000), CONST64(0x0010000010100000), CONST64(0x0010000410100000), 
  CONST64(0x0010000000001000), CONST64(0x0010000400001000), CONST64(0x0010000010001000), CONST64(0x0010000410001000), 
  CONST64(0x0010000000101000), CONST64(0x0010000400101000), CONST64(0x0010000010101000), CONST64(0x0010000410101000), 
  CONST64(0x0010000000000010), CONST64(0x0010000400000010), CONST64(0x0010000010000010), CONST64(0x0010000410000010), 
  CONST64(0x0010000000100010), CONST64(0x0010000400100010), CONST64(0x0010000010100010), CONST64(0x0010000410100010), 
  CONST64(0x0010000000001010), CONST64(0x0010000400001010), CONST64(0x0010000010001010), CONST64(0x0010000410001010), 
  CONST64(0x0010000000101010), CONST64(0x0010000400101010), CONST64(0x0010000010101010), CONST64(0x0010000410101010), 
  CONST64(0x1010000000000000), CONST64(0x1010000400000000), CONST64(0x1010000010000000), CONST64(0x1010000410000000), 
  CONST64(0x1010000000100000), CONST64(0x1010000400100000), CONST64(0x1010000010100000), CONST64(0x1010000410100000), 
  CONST64(0x1010000000001000), CONST64(0x1010000400001000), CONST64(0x1010000010001000), CONST64(0x1010000410001000), 
  CONST64(0x1010000000101000), CONST64(0x1010000400101000), CONST64(0x1010000010101000), CONST64(0x1010000410101000), 
  CONST64(0x1010000000000010), CONST64(0x1010000400000010), CONST64(0x1010000010000010), CONST64(0x1010000410000010), 
  CONST64(0x1010000000100010), CONST64(0x1010000400100010), CONST64(0x1010000010100010), CONST64(0x1010000410100010), 
  CONST64(0x1010000000001010), CONST64(0x1010000400001010), CONST64(0x1010000010001010), CONST64(0x1010000410001010), 
  CONST64(0x1010000000101010), CONST64(0x1010000400101010), CONST64(0x1010000010101010), CONST64(0x1010000410101010), 
  CONST64(0x0000100000000000), CONST64(0x0000100400000000), CONST64(0x0000100010000000), CONST64(0x0000100410000000), 
  CONST64(0x0000100000100000), CONST64(0x0000100400100000), CONST64(0x0000100010100000), CONST64(0x0000100410100000), 
  CONST64(0x0000100000001000), CONST64(0x0000100400001000), CONST64(0x0000100010001000), CONST64(0x0000100410001000), 
  CONST64(0x0000100000101000), CONST64(0x0000100400101000), CONST64(0x0000100010101000), CONST64(0x0000100410101000), 
  CONST64(0x0000100000000010), CONST64(0x0000100400000010), CONST64(0x0000100010000010), CONST64(0x0000100410000010), 
  CONST64(0x0000100000100010), CONST64(0x0000100400100010), CONST64(0x0000100010100010), CONST64(0x0000100410100010), 
  CONST64(0x0000100000001010), CONST64(0x0000100400001010), CONST64(0x0000100010001010), CONST64(0x0000100410001010), 
  CONST64(0x0000100000101010), CONST64(0x0000100400101010), CONST64(0x0000100010101010), CONST64(0x0000100410101010), 
  CONST64(0x1000100000000000), CONST64(0x1000100400000000), CONST64(0x1000100010000000), CONST64(0x1000100410000000), 
  CONST64(0x1000100000100000), CONST64(0x1000100400100000), CONST64(0x1000100010100000), CONST64(0x1000100410100000), 
  CONST64(0x1000100000001000), CONST64(0x1000100400001000), CONST64(0x1000100010001000), CONST64(0x1000100410001000), 
  CONST64(0x1000100000101000), CONST64(0x1000100400101000), CONST64(0x1000100010101000), CONST64(0x1000100410101000), 
  CONST64(0x1000100000000010), CONST64(0x1000100400000010), CONST64(0x1000100010000010), CONST64(0x1000100410000010), 
  CONST64(0x1000100000100010), CONST64(0x1000100400100010), CONST64(0x1000100010100010), CONST64(0x1000100410100010), 
  CONST64(0x1000100000001010), CONST64(0x1000100400001010), CONST64(0x1000100010001010), CONST64(0x1000100410001010), 
  CONST64(0x1000100000101010), CONST64(0x1000100400101010), CONST64(0x1000100010101010), CONST64(0x1000100410101010), 
  CONST64(0x0010100000000000), CONST64(0x0010100400000000), CONST64(0x0010100010000000), CONST64(0x0010100410000000), 
  CONST64(0x0010100000100000), CONST64(0x0010100400100000), CONST64(0x0010100010100000), CONST64(0x0010100410100000), 
  CONST64(0x0010100000001000), CONST64(0x0010100400001000), CONST64(0x0010100010001000), CONST64(0x0010100410001000), 
  CONST64(0x0010100000101000), CONST64(0x0010100400101000), CONST64(0x0010100010101000), CONST64(0x0010100410101000), 
  CONST64(0x0010100000000010), CONST64(0x0010100400000010), CONST64(0x0010100010000010), CONST64(0x0010100410000010), 
  CONST64(0x0010100000100010), CONST64(0x0010100400100010), CONST64(0x0010100010100010), CONST64(0x0010100410100010), 
  CONST64(0x0010100000001010), CONST64(0x0010100400001010), CONST64(0x0010100010001010), CONST64(0x0010100410001010), 
  CONST64(0x0010100000101010), CONST64(0x0010100400101010), CONST64(0x0010100010101010), CONST64(0x0010100410101010), 
  CONST64(0x1010100000000000), CONST64(0x1010100400000000), CONST64(0x1010100010000000), CONST64(0x1010100410000000), 
  CONST64(0x1010100000100000), CONST64(0x1010100400100000), CONST64(0x1010100010100000), CONST64(0x1010100410100000), 
  CONST64(0x1010100000001000), CONST64(0x1010100400001000), CONST64(0x1010100010001000), CONST64(0x1010100410001000), 
  CONST64(0x1010100000101000), CONST64(0x1010100400101000), CONST64(0x1010100010101000), CONST64(0x1010100410101000), 
  CONST64(0x1010100000000010), CONST64(0x1010100400000010), CONST64(0x1010100010000010), CONST64(0x1010100410000010), 
  CONST64(0x1010100000100010), CONST64(0x1010100400100010), CONST64(0x1010100010100010), CONST64(0x1010100410100010), 
  CONST64(0x1010100000001010), CONST64(0x1010100400001010), CONST64(0x1010100010001010), CONST64(0x1010100410001010), 
  CONST64(0x1010100000101010), CONST64(0x1010100400101010), CONST64(0x1010100010101010), CONST64(0x1010100410101010)
  }, 
{ CONST64(0x0000000000000000), CONST64(0x0000001000000000), CONST64(0x0000000040000000), CONST64(0x0000001040000000), 
  CONST64(0x0000000000400000), CONST64(0x0000001000400000), CONST64(0x0000000040400000), CONST64(0x0000001040400000), 
  CONST64(0x0000000000004000), CONST64(0x0000001000004000), CONST64(0x0000000040004000), CONST64(0x0000001040004000), 
  CONST64(0x0000000000404000), CONST64(0x0000001000404000), CONST64(0x0000000040404000), CONST64(0x0000001040404000), 
  CONST64(0x0000000000000040), CONST64(0x0000001000000040), CONST64(0x0000000040000040), CONST64(0x0000001040000040), 
  CONST64(0x0000000000400040), CONST64(0x0000001000400040), CONST64(0x0000000040400040), CONST64(0x0000001040400040), 
  CONST64(0x0000000000004040), CONST64(0x0000001000004040), CONST64(0x0000000040004040), CONST64(0x0000001040004040), 
  CONST64(0x0000000000404040), CONST64(0x0000001000404040), CONST64(0x0000000040404040), CONST64(0x0000001040404040), 
  CONST64(0x4000000000000000), CONST64(0x4000001000000000), CONST64(0x4000000040000000), CONST64(0x4000001040000000), 
  CONST64(0x4000000000400000), CONST64(0x4000001000400000), CONST64(0x4000000040400000), CONST64(0x4000001040400000), 
  CONST64(0x4000000000004000), CONST64(0x4000001000004000), CONST64(0x4000000040004000), CONST64(0x4000001040004000), 
  CONST64(0x4000000000404000), CONST64(0x4000001000404000), CONST64(0x4000000040404000), CONST64(0x4000001040404000), 
  CONST64(0x4000000000000040), CONST64(0x4000001000000040), CONST64(0x4000000040000040), CONST64(0x4000001040000040), 
  CONST64(0x4000000000400040), CONST64(0x4000001000400040), CONST64(0x4000000040400040), CONST64(0x4000001040400040), 
  CONST64(0x4000000000004040), CONST64(0x4000001000004040), CONST64(0x4000000040004040), CONST64(0x4000001040004040), 
  CONST64(0x4000000000404040), CONST64(0x4000001000404040), CONST64(0x4000000040404040), CONST64(0x4000001040404040), 
  CONST64(0x0040000000000000), CONST64(0x0040001000000000), CONST64(0x0040000040000000), CONST64(0x0040001040000000), 
  CONST64(0x0040000000400000), CONST64(0x0040001000400000), CONST64(0x0040000040400000), CONST64(0x0040001040400000), 
  CONST64(0x0040000000004000), CONST64(0x0040001000004000), CONST64(0x0040000040004000), CONST64(0x0040001040004000), 
  CONST64(0x0040000000404000), CONST64(0x0040001000404000), CONST64(0x0040000040404000), CONST64(0x0040001040404000), 
  CONST64(0x0040000000000040), CONST64(0x0040001000000040), CONST64(0x0040000040000040), CONST64(0x0040001040000040), 
  CONST64(0x0040000000400040), CONST64(0x0040001000400040), CONST64(0x0040000040400040), CONST64(0x0040001040400040), 
  CONST64(0x0040000000004040), CONST64(0x0040001000004040), CONST64(0x0040000040004040), CONST64(0x0040001040004040), 
  CONST64(0x0040000000404040), CONST64(0x0040001000404040), CONST64(0x0040000040404040), CONST64(0x0040001040404040), 
  CONST64(0x4040000000000000), CONST64(0x4040001000000000), CONST64(0x4040000040000000), CONST64(0x4040001040000000), 
  CONST64(0x4040000000400000), CONST64(0x4040001000400000), CONST64(0x4040000040400000), CONST64(0x4040001040400000), 
  CONST64(0x4040000000004000), CONST64(0x4040001000004000), CONST64(0x4040000040004000), CONST64(0x4040001040004000), 
  CONST64(0x4040000000404000), CONST64(0x4040001000404000), CONST64(0x4040000040404000), CONST64(0x4040001040404000), 
  CONST64(0x4040000000000040), CONST64(0x4040001000000040), CONST64(0x4040000040000040), CONST64(0x4040001040000040), 
  CONST64(0x4040000000400040), CONST64(0x4040001000400040), CONST64(0x4040000040400040), CONST64(0x4040001040400040), 
  CONST64(0x4040000000004040), CONST64(0x4040001000004040), CONST64(0x4040000040004040), CONST64(0x4040001040004040), 
  CONST64(0x4040000000404040), CONST64(0x4040001000404040), CONST64(0x4040000040404040), CONST64(0x4040001040404040), 
  CONST64(0x0000400000000000), CONST64(0x0000401000000000), CONST64(0x0000400040000000), CONST64(0x0000401040000000), 
  CONST64(0x0000400000400000), CONST64(0x0000401000400000), CONST64(0x0000400040400000), CONST64(0x0000401040400000), 
  CONST64(0x0000400000004000), CONST64(0x0000401000004000), CONST64(0x0000400040004000), CONST64(0x0000401040004000), 
  CONST64(0x0000400000404000), CONST64(0x0000401000404000), CONST64(0x0000400040404000), CONST64(0x0000401040404000), 
  CONST64(0x0000400000000040), CONST64(0x0000401000000040), CONST64(0x0000400040000040), CONST64(0x0000401040000040), 
  CONST64(0x0000400000400040), CONST64(0x0000401000400040), CONST64(0x0000400040400040), CONST64(0x0000401040400040), 
  CONST64(0x0000400000004040), CONST64(0x0000401000004040), CONST64(0x0000400040004040), CONST64(0x0000401040004040), 
  CONST64(0x0000400000404040), CONST64(0x0000401000404040), CONST64(0x0000400040404040), CONST64(0x0000401040404040), 
  CONST64(0x4000400000000000), CONST64(0x4000401000000000), CONST64(0x4000400040000000), CONST64(0x4000401040000000), 
  CONST64(0x4000400000400000), CONST64(0x4000401000400000), CONST64(0x4000400040400000), CONST64(0x4000401040400000), 
  CONST64(0x4000400000004000), CONST64(0x4000401000004000), CONST64(0x4000400040004000), CONST64(0x4000401040004000), 
  CONST64(0x4000400000404000), CONST64(0x4000401000404000), CONST64(0x4000400040404000), CONST64(0x4000401040404000), 
  CONST64(0x4000400000000040), CONST64(0x4000401000000040), CONST64(0x4000400040000040), CONST64(0x4000401040000040), 
  CONST64(0x4000400000400040), CONST64(0x4000401000400040), CONST64(0x4000400040400040), CONST64(0x4000401040400040), 
  CONST64(0x4000400000004040), CONST64(0x4000401000004040), CONST64(0x4000400040004040), CONST64(0x4000401040004040), 
  CONST64(0x4000400000404040), CONST64(0x4000401000404040), CONST64(0x4000400040404040), CONST64(0x4000401040404040), 
  CONST64(0x0040400000000000), CONST64(0x0040401000000000), CONST64(0x0040400040000000), CONST64(0x0040401040000000), 
  CONST64(0x0040400000400000), CONST64(0x0040401000400000), CONST64(0x0040400040400000), CONST64(0x0040401040400000), 
  CONST64(0x0040400000004000), CONST64(0x0040401000004000), CONST64(0x0040400040004000), CONST64(0x0040401040004000), 
  CONST64(0x0040400000404000), CONST64(0x0040401000404000), CONST64(0x0040400040404000), CONST64(0x0040401040404000), 
  CONST64(0x0040400000000040), CONST64(0x0040401000000040), CONST64(0x0040400040000040), CONST64(0x0040401040000040), 
  CONST64(0x0040400000400040), CONST64(0x0040401000400040), CONST64(0x0040400040400040), CONST64(0x0040401040400040), 
  CONST64(0x0040400000004040), CONST64(0x0040401000004040), CONST64(0x0040400040004040), CONST64(0x0040401040004040), 
  CONST64(0x0040400000404040), CONST64(0x0040401000404040), CONST64(0x0040400040404040), CONST64(0x0040401040404040), 
  CONST64(0x4040400000000000), CONST64(0x4040401000000000), CONST64(0x4040400040000000), CONST64(0x4040401040000000), 
  CONST64(0x4040400000400000), CONST64(0x4040401000400000), CONST64(0x4040400040400000), CONST64(0x4040401040400000), 
  CONST64(0x4040400000004000), CONST64(0x4040401000004000), CONST64(0x4040400040004000), CONST64(0x4040401040004000), 
  CONST64(0x4040400000404000), CONST64(0x4040401000404000), CONST64(0x4040400040404000), CONST64(0x4040401040404000), 
  CONST64(0x4040400000000040), CONST64(0x4040401000000040), CONST64(0x4040400040000040), CONST64(0x4040401040000040), 
  CONST64(0x4040400000400040), CONST64(0x4040401000400040), CONST64(0x4040400040400040), CONST64(0x4040401040400040), 
  CONST64(0x4040400000004040), CONST64(0x4040401000004040), CONST64(0x4040400040004040), CONST64(0x4040401040004040), 
  CONST64(0x4040400000404040), CONST64(0x4040401000404040), CONST64(0x4040400040404040), CONST64(0x4040401040404040)
  }};
  
#endif


static void cookey(const ulong32 *raw1, ulong32 *keyout);

#ifdef LTC_CLEAN_STACK
static void _deskey(const unsigned char *key, short edf, ulong32 *keyout)
#else
static void deskey(const unsigned char *key, short edf, ulong32 *keyout)
#endif
{
    ulong32 i, j, l, m, n, kn[32];
    unsigned char pc1m[56], pcr[56];

    for (j=0; j < 56; j++) {
        l = (ulong32)pc1[j];
        m = l & 7;
        pc1m[j] = (unsigned char)((key[l >> 3U] & bytebit[m]) == bytebit[m] ? 1 : 0);
    }

    for (i=0; i < 16; i++) {
        if (edf == DE1) {
           m = (15 - i) << 1;
        } else {
           m = i << 1;
        }
        n = m + 1;
        kn[m] = kn[n] = 0L;
        for (j=0; j < 28; j++) {
            l = j + (ulong32)totrot[i];
            if (l < 28) {
               pcr[j] = pc1m[l];
            } else {
               pcr[j] = pc1m[l - 28];
            }
        }
        for (/*j = 28*/; j < 56; j++) {
            l = j + (ulong32)totrot[i];
            if (l < 56) {
               pcr[j] = pc1m[l];
            } else {
               pcr[j] = pc1m[l - 28];
            }
        }
        for (j=0; j < 24; j++)  {
            if ((int)pcr[(int)pc2[j]] != 0) {
               kn[m] |= bigbyte[j];
            }
            if ((int)pcr[(int)pc2[j+24]] != 0) {
               kn[n] |= bigbyte[j];
            }
        }
    }

    cookey(kn, keyout);
}

#ifdef LTC_CLEAN_STACK
static void deskey(const unsigned char *key, short edf, ulong32 *keyout)
{
   _deskey(key, edf, keyout);
   burn_stack(sizeof(int)*5 + sizeof(ulong32)*32 + sizeof(unsigned char)*112);
}
#endif

#ifdef LTC_CLEAN_STACK
static void _cookey(const ulong32 *raw1, ulong32 *keyout)
#else
static void cookey(const ulong32 *raw1, ulong32 *keyout)
#endif
{
    ulong32 *cook;
    const ulong32 *raw0;
    ulong32 dough[32];
    int i;

    cook = dough;
    for(i=0; i < 16; i++, raw1++)
    {
        raw0 = raw1++;
        *cook    = (*raw0 & 0x00fc0000L) << 6;
        *cook   |= (*raw0 & 0x00000fc0L) << 10;
        *cook   |= (*raw1 & 0x00fc0000L) >> 10;
        *cook++ |= (*raw1 & 0x00000fc0L) >> 6;
        *cook    = (*raw0 & 0x0003f000L) << 12;
        *cook   |= (*raw0 & 0x0000003fL) << 16;
        *cook   |= (*raw1 & 0x0003f000L) >> 4;
        *cook++ |= (*raw1 & 0x0000003fL);
    }

    XMEMCPY(keyout, dough, sizeof dough);
}

#ifdef LTC_CLEAN_STACK
static void cookey(const ulong32 *raw1, ulong32 *keyout)
{
   _cookey(raw1, keyout);
   burn_stack(sizeof(ulong32 *) * 2 + sizeof(ulong32)*32 + sizeof(int));
}
#endif

#ifndef LTC_CLEAN_STACK
static void desfunc(ulong32 *block, const ulong32 *keys)
#else
static void _desfunc(ulong32 *block, const ulong32 *keys)
#endif
{
    ulong32 work, right, leftt;
    int cur_round;

    leftt = block[0];
    right = block[1];

#ifdef LTC_SMALL_CODE
    work = ((leftt >> 4)  ^ right) & 0x0f0f0f0fL;
    right ^= work;
    leftt ^= (work << 4);

    work = ((leftt >> 16) ^ right) & 0x0000ffffL;
    right ^= work;
    leftt ^= (work << 16);

    work = ((right >> 2)  ^ leftt) & 0x33333333L;
    leftt ^= work;
    right ^= (work << 2);

    work = ((right >> 8)  ^ leftt) & 0x00ff00ffL;
    leftt ^= work;
    right ^= (work << 8);

    right = ROLc(right, 1);
    work = (leftt ^ right) & 0xaaaaaaaaL;
    
    leftt ^= work;
    right ^= work;
    leftt = ROLc(leftt, 1);
#else 
   {
      ulong64 tmp;
      tmp = des_ip[0][byte(leftt, 0)] ^
            des_ip[1][byte(leftt, 1)] ^
            des_ip[2][byte(leftt, 2)] ^
            des_ip[3][byte(leftt, 3)] ^
            des_ip[4][byte(right, 0)] ^
            des_ip[5][byte(right, 1)] ^
            des_ip[6][byte(right, 2)] ^
            des_ip[7][byte(right, 3)];
      leftt = (ulong32)(tmp >> 32);
      right = (ulong32)(tmp & 0xFFFFFFFFUL);
   }
#endif

    for (cur_round = 0; cur_round < 8; cur_round++) {
        work  = RORc(right, 4) ^ *keys++;
        leftt ^= SP7[work        & 0x3fL]
              ^ SP5[(work >>  8) & 0x3fL]
              ^ SP3[(work >> 16) & 0x3fL]
              ^ SP1[(work >> 24) & 0x3fL];
        work  = right ^ *keys++;
        leftt ^= SP8[ work        & 0x3fL]
              ^  SP6[(work >>  8) & 0x3fL]
              ^  SP4[(work >> 16) & 0x3fL]
              ^  SP2[(work >> 24) & 0x3fL];

        work = RORc(leftt, 4) ^ *keys++;
        right ^= SP7[ work        & 0x3fL]
              ^  SP5[(work >>  8) & 0x3fL]
              ^  SP3[(work >> 16) & 0x3fL]
              ^  SP1[(work >> 24) & 0x3fL];
        work  = leftt ^ *keys++;
        right ^= SP8[ work        & 0x3fL]
              ^  SP6[(work >>  8) & 0x3fL]
              ^  SP4[(work >> 16) & 0x3fL]
              ^  SP2[(work >> 24) & 0x3fL];
    }

#ifdef LTC_SMALL_CODE    
    right = RORc(right, 1);
    work = (leftt ^ right) & 0xaaaaaaaaL;
    leftt ^= work;
    right ^= work;
    leftt = RORc(leftt, 1);
    work = ((leftt >> 8) ^ right) & 0x00ff00ffL;
    right ^= work;
    leftt ^= (work << 8);
    /* -- */
    work = ((leftt >> 2) ^ right) & 0x33333333L;
    right ^= work;
    leftt ^= (work << 2);
    work = ((right >> 16) ^ leftt) & 0x0000ffffL;
    leftt ^= work;
    right ^= (work << 16);
    work = ((right >> 4) ^ leftt) & 0x0f0f0f0fL;
    leftt ^= work;
    right ^= (work << 4);
#else 
   {
      ulong64 tmp;
      tmp = des_fp[0][byte(leftt, 0)] ^
            des_fp[1][byte(leftt, 1)] ^
            des_fp[2][byte(leftt, 2)] ^
            des_fp[3][byte(leftt, 3)] ^
            des_fp[4][byte(right, 0)] ^
            des_fp[5][byte(right, 1)] ^
            des_fp[6][byte(right, 2)] ^
            des_fp[7][byte(right, 3)];
      leftt = (ulong32)(tmp >> 32);
      right = (ulong32)(tmp & 0xFFFFFFFFUL);
   }
#endif
    
    block[0] = right;
    block[1] = leftt;
}

#ifdef LTC_CLEAN_STACK
static void desfunc(ulong32 *block, const ulong32 *keys)
{
   _desfunc(block, keys);
   burn_stack(sizeof(ulong32) * 4 + sizeof(int));
}
#endif

 /**
    Initialize the LTC_DES block cipher
    @param key The symmetric key you wish to pass
    @param keylen The key length in bytes
    @param num_rounds The number of rounds desired (0 for default)
    @param skey The key in as scheduled by this function.
    @return CRYPT_OK if successful
 */
int des_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
{
    LTC_ARGCHK(key != NULL);
    LTC_ARGCHK(skey != NULL);

    if (num_rounds != 0 && num_rounds != 16) {
        return CRYPT_INVALID_ROUNDS;
    }

    if (keylen != 8) {
        return CRYPT_INVALID_KEYSIZE;
    }

    deskey(key, EN0, skey->des.ek);
    deskey(key, DE1, skey->des.dk);

    return CRYPT_OK;
}

 /**
    Initialize the 3LTC_DES-EDE block cipher
    @param key The symmetric key you wish to pass
    @param keylen The key length in bytes
    @param num_rounds The number of rounds desired (0 for default)
    @param skey The key in as scheduled by this function.
    @return CRYPT_OK if successful
 */
int des3_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
{
    LTC_ARGCHK(key != NULL);
    LTC_ARGCHK(skey != NULL);

    if(num_rounds != 0 && num_rounds != 16) {
        return CRYPT_INVALID_ROUNDS;
    }

    if (keylen != 24) {
        return CRYPT_INVALID_KEYSIZE;
    }

    deskey(key,    EN0, skey->des3.ek[0]);
    deskey(key+8,  DE1, skey->des3.ek[1]);
    deskey(key+16, EN0, skey->des3.ek[2]);

    deskey(key,    DE1, skey->des3.dk[2]);
    deskey(key+8,  EN0, skey->des3.dk[1]);
    deskey(key+16, DE1, skey->des3.dk[0]);

    return CRYPT_OK;
}

/**
  Encrypts a block of text with LTC_DES
  @param pt The input plaintext (8 bytes)
  @param ct The output ciphertext (8 bytes)
  @param skey The key as scheduled
  @return CRYPT_OK if successful
*/
int des_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
{
    ulong32 work[2];
    LTC_ARGCHK(pt   != NULL);
    LTC_ARGCHK(ct   != NULL);
    LTC_ARGCHK(skey != NULL);
    LOAD32H(work[0], pt+0);
    LOAD32H(work[1], pt+4);
    desfunc(work, skey->des.ek);
    STORE32H(work[0],ct+0);
    STORE32H(work[1],ct+4);
    return CRYPT_OK;
}

/**
  Decrypts a block of text with LTC_DES
  @param ct The input ciphertext (8 bytes)
  @param pt The output plaintext (8 bytes)
  @param skey The key as scheduled 
  @return CRYPT_OK if successful
*/
int des_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
{
    ulong32 work[2];
    LTC_ARGCHK(pt   != NULL);
    LTC_ARGCHK(ct   != NULL);
    LTC_ARGCHK(skey != NULL);
    LOAD32H(work[0], ct+0);
    LOAD32H(work[1], ct+4);
    desfunc(work, skey->des.dk);
    STORE32H(work[0],pt+0);
    STORE32H(work[1],pt+4);  
    return CRYPT_OK;
}

/**
  Encrypts a block of text with 3LTC_DES-EDE
  @param pt The input plaintext (8 bytes)
  @param ct The output ciphertext (8 bytes)
  @param skey The key as scheduled
  @return CRYPT_OK if successful
*/
int des3_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
{
    ulong32 work[2];
    
    LTC_ARGCHK(pt   != NULL);
    LTC_ARGCHK(ct   != NULL);
    LTC_ARGCHK(skey != NULL);
    LOAD32H(work[0], pt+0);
    LOAD32H(work[1], pt+4);
    desfunc(work, skey->des3.ek[0]);
    desfunc(work, skey->des3.ek[1]);
    desfunc(work, skey->des3.ek[2]);
    STORE32H(work[0],ct+0);
    STORE32H(work[1],ct+4);
    return CRYPT_OK;
}

/**
  Decrypts a block of text with 3LTC_DES-EDE
  @param ct The input ciphertext (8 bytes)
  @param pt The output plaintext (8 bytes)
  @param skey The key as scheduled 
  @return CRYPT_OK if successful
*/
int des3_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
{
    ulong32 work[2];
    LTC_ARGCHK(pt   != NULL);
    LTC_ARGCHK(ct   != NULL);
    LTC_ARGCHK(skey != NULL);
    LOAD32H(work[0], ct+0);
    LOAD32H(work[1], ct+4);
    desfunc(work, skey->des3.dk[0]);
    desfunc(work, skey->des3.dk[1]);
    desfunc(work, skey->des3.dk[2]);
    STORE32H(work[0],pt+0);
    STORE32H(work[1],pt+4);
    return CRYPT_OK;
}

/**
  Performs a self-test of the LTC_DES block cipher
  @return CRYPT_OK if functional, CRYPT_NOP if self-test has been disabled
*/
int des_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
    int err;
    static const struct des_test_case {
        int num, mode; /* mode 1 = encrypt */
        unsigned char key[8], txt[8], out[8];
    } cases[] = {
        { 1, 1,     { 0x10, 0x31, 0x6E, 0x02, 0x8C, 0x8F, 0x3B, 0x4A },
                    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                    { 0x82, 0xDC, 0xBA, 0xFB, 0xDE, 0xAB, 0x66, 0x02 } },
        { 2, 1,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x95, 0xF8, 0xA5, 0xE5, 0xDD, 0x31, 0xD9, 0x00 },
                    { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } },
        { 3, 1,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0xDD, 0x7F, 0x12, 0x1C, 0xA5, 0x01, 0x56, 0x19 },
                    { 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } },
        { 4, 1,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x2E, 0x86, 0x53, 0x10, 0x4F, 0x38, 0x34, 0xEA },
                    { 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } },
        { 5, 1,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x4B, 0xD3, 0x88, 0xFF, 0x6C, 0xD8, 0x1D, 0x4F },
                    { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } },
        { 6, 1,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x20, 0xB9, 0xE7, 0x67, 0xB2, 0xFB, 0x14, 0x56 },
                    { 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } },
        { 7, 1,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x55, 0x57, 0x93, 0x80, 0xD7, 0x71, 0x38, 0xEF },
                    { 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } },
        { 8, 1,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x6C, 0xC5, 0xDE, 0xFA, 0xAF, 0x04, 0x51, 0x2F },
                    { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } },
        { 9, 1,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x0D, 0x9F, 0x27, 0x9B, 0xA5, 0xD8, 0x72, 0x60 }, 
                    { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } },
        {10, 1,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0xD9, 0x03, 0x1B, 0x02, 0x71, 0xBD, 0x5A, 0x0A },
                    { 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } },

        { 1, 0,     { 0x10, 0x31, 0x6E, 0x02, 0x8C, 0x8F, 0x3B, 0x4A },
                    { 0x82, 0xDC, 0xBA, 0xFB, 0xDE, 0xAB, 0x66, 0x02 },
                    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } },
        { 2, 0,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                    { 0x95, 0xF8, 0xA5, 0xE5, 0xDD, 0x31, 0xD9, 0x00 } },
        { 3, 0,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                    { 0xDD, 0x7F, 0x12, 0x1C, 0xA5, 0x01, 0x56, 0x19 } },
        { 4, 0,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                    { 0x2E, 0x86, 0x53, 0x10, 0x4F, 0x38, 0x34, 0xEA } },
        { 5, 0,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                    { 0x4B, 0xD3, 0x88, 0xFF, 0x6C, 0xD8, 0x1D, 0x4F } },
        { 6, 0,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                    { 0x20, 0xB9, 0xE7, 0x67, 0xB2, 0xFB, 0x14, 0x56 } },
        { 7, 0,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                    { 0x55, 0x57, 0x93, 0x80, 0xD7, 0x71, 0x38, 0xEF } },
        { 8, 0,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                    { 0x6C, 0xC5, 0xDE, 0xFA, 0xAF, 0x04, 0x51, 0x2F } },
        { 9, 0,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                    { 0x0D, 0x9F, 0x27, 0x9B, 0xA5, 0xD8, 0x72, 0x60 } }, 
        {10, 0,     { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
                    { 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
                    { 0xD9, 0x03, 0x1B, 0x02, 0x71, 0xBD, 0x5A, 0x0A } }

        /*** more test cases you could add if you are not convinced (the above test cases aren't really too good):

                key              plaintext        ciphertext
                0000000000000000 0000000000000000 8CA64DE9C1B123A7
                FFFFFFFFFFFFFFFF FFFFFFFFFFFFFFFF 7359B2163E4EDC58
                3000000000000000 1000000000000001 958E6E627A05557B
                1111111111111111 1111111111111111 F40379AB9E0EC533
                0123456789ABCDEF 1111111111111111 17668DFC7292532D
                1111111111111111 0123456789ABCDEF 8A5AE1F81AB8F2DD
                0000000000000000 0000000000000000 8CA64DE9C1B123A7
                FEDCBA9876543210 0123456789ABCDEF ED39D950FA74BCC4
                7CA110454A1A6E57 01A1D6D039776742 690F5B0D9A26939B
                0131D9619DC1376E 5CD54CA83DEF57DA 7A389D10354BD271
                07A1133E4A0B2686 0248D43806F67172 868EBB51CAB4599A
                3849674C2602319E 51454B582DDF440A 7178876E01F19B2A
                04B915BA43FEB5B6 42FD443059577FA2 AF37FB421F8C4095
                0113B970FD34F2CE 059B5E0851CF143A 86A560F10EC6D85B
                0170F175468FB5E6 0756D8E0774761D2 0CD3DA020021DC09
                43297FAD38E373FE 762514B829BF486A EA676B2CB7DB2B7A
                07A7137045DA2A16 3BDD119049372802 DFD64A815CAF1A0F
                04689104C2FD3B2F 26955F6835AF609A 5C513C9C4886C088
                37D06BB516CB7546 164D5E404F275232 0A2AEEAE3FF4AB77
                1F08260D1AC2465E 6B056E18759F5CCA EF1BF03E5DFA575A
                584023641ABA6176 004BD6EF09176062 88BF0DB6D70DEE56
                025816164629B007 480D39006EE762F2 A1F9915541020B56
                49793EBC79B3258F 437540C8698F3CFA 6FBF1CAFCFFD0556
                4FB05E1515AB73A7 072D43A077075292 2F22E49BAB7CA1AC
                49E95D6D4CA229BF 02FE55778117F12A 5A6B612CC26CCE4A
                018310DC409B26D6 1D9D5C5018F728C2 5F4C038ED12B2E41
                1C587F1C13924FEF 305532286D6F295A 63FAC0D034D9F793
                0101010101010101 0123456789ABCDEF 617B3A0CE8F07100
                1F1F1F1F0E0E0E0E 0123456789ABCDEF DB958605F8C8C606
                E0FEE0FEF1FEF1FE 0123456789ABCDEF EDBFD1C66C29CCC7
                0000000000000000 FFFFFFFFFFFFFFFF 355550B2150E2451
                FFFFFFFFFFFFFFFF 0000000000000000 CAAAAF4DEAF1DBAE
                0123456789ABCDEF 0000000000000000 D5D44FF720683D0D
                FEDCBA9876543210 FFFFFFFFFFFFFFFF 2A2BB008DF97C2F2

            http://www.ecs.soton.ac.uk/~prw99r/ez438/vectors.txt
        ***/
    };
    int i, y;
    unsigned char tmp[8];
    symmetric_key des;

    for(i=0; i < (int)(sizeof(cases)/sizeof(cases[0])); i++)
    {
        if ((err = des_setup(cases[i].key, 8, 0, &des)) != CRYPT_OK) {
           return err;
        }
        if (cases[i].mode != 0) { 
           des_ecb_encrypt(cases[i].txt, tmp, &des);
        } else {
           des_ecb_decrypt(cases[i].txt, tmp, &des);
        }

        if (XMEMCMP(cases[i].out, tmp, sizeof(tmp)) != 0) {
           return CRYPT_FAIL_TESTVECTOR;
        }

      /* now see if we can encrypt all zero bytes 1000 times, decrypt and come back where we started */
      for (y = 0; y < 8; y++) tmp[y] = 0;
      for (y = 0; y < 1000; y++) des_ecb_encrypt(tmp, tmp, &des);
      for (y = 0; y < 1000; y++) des_ecb_decrypt(tmp, tmp, &des);
      for (y = 0; y < 8; y++) if (tmp[y] != 0) return CRYPT_FAIL_TESTVECTOR;
}

    return CRYPT_OK;
  #endif
}

int des3_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
   unsigned char key[24], pt[8], ct[8], tmp[8];
   symmetric_key skey;
   int x, err;

   if ((err = des_test()) != CRYPT_OK) {
      return err;
   }

   for (x = 0; x < 8; x++) {
       pt[x] = x;
   }
   
   for (x = 0; x < 24; x++) {
       key[x] = x;
   }

   if ((err = des3_setup(key, 24, 0, &skey)) != CRYPT_OK) {
      return err;
   }
   
   des3_ecb_encrypt(pt, ct, &skey);
   des3_ecb_decrypt(ct, tmp, &skey);
   
   if (XMEMCMP(pt, tmp, 8) != 0) {
      return CRYPT_FAIL_TESTVECTOR;
   }
   
   return CRYPT_OK;
 #endif
}

/** Terminate the context 
   @param skey    The scheduled key
*/
void des_done(symmetric_key *skey)
{
}

/** Terminate the context 
   @param skey    The scheduled key
*/
void des3_done(symmetric_key *skey)
{
}


/**
  Gets suitable key size
  @param keysize [in/out] The length of the recommended key (in bytes).  This function will store the suitable size back in this variable.
  @return CRYPT_OK if the input key size is acceptable.
*/
int des_keysize(int *keysize)
{
    LTC_ARGCHK(keysize != NULL);
    if(*keysize < 8) {
        return CRYPT_INVALID_KEYSIZE;
    }
    *keysize = 8;
    return CRYPT_OK;
}

/**
  Gets suitable key size
  @param keysize [in/out] The length of the recommended key (in bytes).  This function will store the suitable size back in this variable.
  @return CRYPT_OK if the input key size is acceptable.
*/
int des3_keysize(int *keysize)
{
    LTC_ARGCHK(keysize != NULL);
    if(*keysize < 24) {
        return CRYPT_INVALID_KEYSIZE;
    }
    *keysize = 24;
    return CRYPT_OK;
}

#include "CommonCryptor.h"
#include "CommonCryptorSPI.h"

static uint8_t weak_keys[][8] = {
    {0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01}, /* weak keys */
    {0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE},
    {0x1F,0x1F,0x1F,0x1F,0x0E,0x0E,0x0E,0x0E},
    {0xE0,0xE0,0xE0,0xE0,0xF1,0xF1,0xF1,0xF1},
    {0x01,0xFE,0x01,0xFE,0x01,0xFE,0x01,0xFE}, /* semi-weak keys */
    {0xFE,0x01,0xFE,0x01,0xFE,0x01,0xFE,0x01},
    {0x1F,0xE0,0x1F,0xE0,0x0E,0xF1,0x0E,0xF1},
    {0xE0,0x1F,0xE0,0x1F,0xF1,0x0E,0xF1,0x0E},
    {0x01,0xE0,0x01,0xE0,0x01,0xF1,0x01,0xF1},
    {0xE0,0x01,0xE0,0x01,0xF1,0x01,0xF1,0x01},
    {0x1F,0xFE,0x1F,0xFE,0x0E,0xFE,0x0E,0xFE},
    {0xFE,0x1F,0xFE,0x1F,0xFE,0x0E,0xFE,0x0E},
    {0x01,0x1F,0x01,0x1F,0x01,0x0E,0x01,0x0E},
    {0x1F,0x01,0x1F,0x01,0x0E,0x01,0x0E,0x01},
    {0xE0,0xFE,0xE0,0xFE,0xF1,0xFE,0xF1,0xFE},
    {0xFE,0xE0,0xFE,0xE0,0xFE,0xF1,0xFE,0xF1}
};

CCCryptorStatus CCDesIsWeakKey(
                               void *key,
                               size_t length)
{
    size_t n;
    
    LTC_ARGCHK(key != NULL);
    
    if (length != 8)
        return CRYPT_INVALID_KEYSIZE;
    
    for (n = 0; n < sizeof(weak_keys) / sizeof(weak_keys[0]); n++)
        if (memcmp(weak_keys[n], key, 8) == 0)
            return CRYPT_INVALID_KEYSIZE;
    
    return CRYPT_OK;
}

static uint8_t odd_parity[256] = {
    1,  1,  2,  2,  4,  4,  7,  7,  8,  8, 11, 11, 13, 13, 14, 14,
    16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31,
    32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47,
    49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62,
    64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79,
    81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94,
    97, 97, 98, 98,100,100,103,103,104,104,107,107,109,109,110,110,
    112,112,115,115,117,117,118,118,121,121,122,122,124,124,127,127,
    128,128,131,131,133,133,134,134,137,137,138,138,140,140,143,143,
    145,145,146,146,148,148,151,151,152,152,155,155,157,157,158,158,
    161,161,162,162,164,164,167,167,168,168,171,171,173,173,174,174,
    176,176,179,179,181,181,182,182,185,185,186,186,188,188,191,191,
    193,193,194,194,196,196,199,199,200,200,203,203,205,205,206,206,
    208,208,211,211,213,213,214,214,217,217,218,218,220,220,223,223,
    224,224,227,227,229,229,230,230,233,233,234,234,236,236,239,239,
    241,241,242,242,244,244,247,247,248,248,251,251,253,253,254,254,
};

void CCDesSetOddParity(void *key,
                       size_t Length)
{
    uint8_t *p = key;
    size_t n;
    
    for (n = 0; n < Length; n++)
        p[n] = odd_parity[p[n]];
    
}

uint32_t CCDesCBCCksum(void *in, void *out,
                       size_t length, void *key, size_t keylen,
                       void *ivec)
{
    const uint8_t *input = in;
    const uint8_t *inputiv = ivec;
    uint32_t uiv[2];
    uint32_t work[2] = { 0, 0 };
    symmetric_key des;
    
    des_setup(key, 8, 0, &des);
    
    LOAD32H(uiv[0], inputiv+0);
    LOAD32H(uiv[1], inputiv+4);
    
    while (length >= 8) {
        LOAD32H(work[0], input+0);
        LOAD32H(work[1], input+4);
        
        work[0] ^= uiv[0]; work[1] ^= uiv[1];
        desfunc(work, &des);
        uiv[0] = work[0]; uiv[1] = work[1];
        
        length -= 8;
        input += 8;
    }
    if (length) {
        uint8_t tmp[8];
        memcpy(tmp, input, length);
        memset(tmp + length, 0, 8 - length);
        LOAD32H(work[0], tmp+0);
        LOAD32H(work[1], tmp+4);
        
        work[0] ^= uiv[0]; work[1] ^= uiv[1];
        desfunc(work, &des);
    }
    if (out) {
        uint8_t *output = out;
        STORE32H(work[0],output+0);
        STORE32H(work[1],output+4);
    }
    
    uiv[0] = 0; work[0] = 0; uiv[1] = 0;
    return work[1];
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/ciphers/des.c,v $ */
/* $Revision: 1.15 $ */
/* $Date: 2007/05/12 14:20:27 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/ltc_aes/aes.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */

/* AES implementation by Tom St Denis
 *
 * Derived from the Public Domain source code by
 
 ---  
 * rijndael-alg-fst.c
 *
 * @version 3.0 (December 2000)
 *
 * Optimised ANSI C code for the Rijndael cipher (now AES)
 *
 * @author Vincent Rijmen <vincent.rijmen@esat.kuleuven.ac.be>
 * @author Antoon Bosselaers <antoon.bosselaers@esat.kuleuven.ac.be>
 * @author Paulo Barreto <paulo.barreto@terra.com.br>
 ---
 */
/**
 @file aes.c
 Implementation of AES
 */   

#include "tomcrypt.h"

#ifdef LTC_RIJNDAEL

#ifndef ENCRYPT_ONLY 

#define SETUP    rijndael_setup
#define ECB_ENC  rijndael_ecb_encrypt
#define ECB_DEC  rijndael_ecb_decrypt
#define ECB_DONE rijndael_done
#define ECB_TEST rijndael_test
#define ECB_KS   rijndael_keysize

const struct ltc_cipher_descriptor rijndael_desc =
{
    "rijndael",
    6,
    16, 32, 16, 10,
    SETUP, ECB_ENC, ECB_DEC, ECB_TEST, ECB_DONE, ECB_KS,
    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};

const struct ltc_cipher_descriptor aesedp_desc =
{
    "aesedp",
    6,
    16, 32, 16, 10,
    SETUP, ECB_ENC, ECB_DEC, ECB_TEST, ECB_DONE, ECB_KS,
    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};

#else

#define SETUP    rijndael_enc_setup
#define ECB_ENC  rijndael_enc_ecb_encrypt
#define ECB_KS   rijndael_enc_keysize
#define ECB_DONE rijndael_enc_done

const struct ltc_cipher_descriptor rijndael_enc_desc =
{
    "rijndael",
    6,
    16, 32, 16, 10,
    SETUP, ECB_ENC, NULL, NULL, ECB_DONE, ECB_KS,
    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};

const struct ltc_cipher_descriptor aes_enc_desc =
{
    "aes",
    6,
    16, 32, 16, 10,
    SETUP, ECB_ENC, NULL, NULL, ECB_DONE, ECB_KS,
    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
};

#endif

#include "aes_tab.c"

static ulong32 setup_mix(ulong32 temp)
{
    return (Te4_3[byte(temp, 2)]) ^
    (Te4_2[byte(temp, 1)]) ^
    (Te4_1[byte(temp, 0)]) ^
    (Te4_0[byte(temp, 3)]);
}

#ifndef ENCRYPT_ONLY
#ifdef LTC_SMALL_CODE
static ulong32 setup_mix2(ulong32 temp)
{
    return Td0(255 & Te4[byte(temp, 3)]) ^
    Td1(255 & Te4[byte(temp, 2)]) ^
    Td2(255 & Te4[byte(temp, 1)]) ^
    Td3(255 & Te4[byte(temp, 0)]);
}
#endif
#endif

/**
 Initialize the AES (Rijndael) block cipher
 @param key The symmetric key you wish to pass
 @param keylen The key length in bytes
 @param num_rounds The number of rounds desired (0 for default)
 @param skey The key in as scheduled by this function.
 @return CRYPT_OK if successful
 */
int SETUP(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
{
    int i, j;
    ulong32 temp, *rk;
#ifndef ENCRYPT_ONLY
    ulong32 *rrk;
#endif    
    LTC_ARGCHK(key  != NULL);
    LTC_ARGCHK(skey != NULL);
    
    if (keylen != 16 && keylen != 24 && keylen != 32) {
        return CRYPT_INVALID_KEYSIZE;
    }
    
    if (num_rounds != 0 && num_rounds != (10 + ((keylen/8)-2)*2)) {
        return CRYPT_INVALID_ROUNDS;
    }
    
    skey->rijndael.Nr = 10 + ((keylen/8)-2)*2;
    
    /* setup the forward key */
    i                 = 0;
    rk                = skey->rijndael.eK;
    LOAD32H(rk[0], key     );
    LOAD32H(rk[1], key +  4);
    LOAD32H(rk[2], key +  8);
    LOAD32H(rk[3], key + 12);
    if (keylen == 16) {
        j = 44;
        for (;;) {
            temp  = rk[3];
            rk[4] = rk[0] ^ setup_mix(temp) ^ rcon[i];
            rk[5] = rk[1] ^ rk[4];
            rk[6] = rk[2] ^ rk[5];
            rk[7] = rk[3] ^ rk[6];
            if (++i == 10) {
                break;
            }
            rk += 4;
        }
    } else if (keylen == 24) {
        j = 52;   
        LOAD32H(rk[4], key + 16);
        LOAD32H(rk[5], key + 20);
        for (;;) {
#ifdef _MSC_VER
            temp = skey->rijndael.eK[rk - skey->rijndael.eK + 5]; 
#else
            temp = rk[5];
#endif
            rk[ 6] = rk[ 0] ^ setup_mix(temp) ^ rcon[i];
            rk[ 7] = rk[ 1] ^ rk[ 6];
            rk[ 8] = rk[ 2] ^ rk[ 7];
            rk[ 9] = rk[ 3] ^ rk[ 8];
            if (++i == 8) {
                break;
            }
            rk[10] = rk[ 4] ^ rk[ 9];
            rk[11] = rk[ 5] ^ rk[10];
            rk += 6;
        }
    } else if (keylen == 32) {
        j = 60;
        LOAD32H(rk[4], key + 16);
        LOAD32H(rk[5], key + 20);
        LOAD32H(rk[6], key + 24);
        LOAD32H(rk[7], key + 28);
        for (;;) {
#ifdef _MSC_VER
            temp = skey->rijndael.eK[rk - skey->rijndael.eK + 7]; 
#else
            temp = rk[7];
#endif
            rk[ 8] = rk[ 0] ^ setup_mix(temp) ^ rcon[i];
            rk[ 9] = rk[ 1] ^ rk[ 8];
            rk[10] = rk[ 2] ^ rk[ 9];
            rk[11] = rk[ 3] ^ rk[10];
            if (++i == 7) {
                break;
            }
            temp = rk[11];
            rk[12] = rk[ 4] ^ setup_mix(RORc(temp, 8));
            rk[13] = rk[ 5] ^ rk[12];
            rk[14] = rk[ 6] ^ rk[13];
            rk[15] = rk[ 7] ^ rk[14];
            rk += 8;
        }
    } else {
        /* this can't happen */
        return CRYPT_ERROR;
    }
    
#ifndef ENCRYPT_ONLY    
    /* setup the inverse key now */
    rk   = skey->rijndael.dK;
    rrk  = skey->rijndael.eK + j - 4; 
    
    /* apply the inverse MixColumn transform to all round keys but the first and the last: */
    /* copy first */
    *rk++ = *rrk++;
    *rk++ = *rrk++;
    *rk++ = *rrk++;
    *rk   = *rrk;
    rk -= 3; rrk -= 3;
    
    for (i = 1; i < skey->rijndael.Nr; i++) {
        rrk -= 4;
        rk  += 4;
#ifdef LTC_SMALL_CODE        
        temp = rrk[0];
        rk[0] = setup_mix2(temp);
        temp = rrk[1];
        rk[1] = setup_mix2(temp);
        temp = rrk[2];
        rk[2] = setup_mix2(temp);
        temp = rrk[3];
        rk[3] = setup_mix2(temp);
#else
        temp = rrk[0];
        rk[0] =
        Tks0[byte(temp, 3)] ^
        Tks1[byte(temp, 2)] ^
        Tks2[byte(temp, 1)] ^
        Tks3[byte(temp, 0)];
        temp = rrk[1];
        rk[1] =
        Tks0[byte(temp, 3)] ^
        Tks1[byte(temp, 2)] ^
        Tks2[byte(temp, 1)] ^
        Tks3[byte(temp, 0)];
        temp = rrk[2];
        rk[2] =
        Tks0[byte(temp, 3)] ^
        Tks1[byte(temp, 2)] ^
        Tks2[byte(temp, 1)] ^
        Tks3[byte(temp, 0)];
        temp = rrk[3];
        rk[3] =
        Tks0[byte(temp, 3)] ^
        Tks1[byte(temp, 2)] ^
        Tks2[byte(temp, 1)] ^
        Tks3[byte(temp, 0)];
#endif            
        
    }
    
    /* copy last */
    rrk -= 4;
    rk  += 4;
    *rk++ = *rrk++;
    *rk++ = *rrk++;
    *rk++ = *rrk++;
    *rk   = *rrk;
#endif /* ENCRYPT_ONLY */
    
    return CRYPT_OK;   
}

/**
 Encrypts a block of text with AES
 @param pt The input plaintext (16 bytes)
 @param ct The output ciphertext (16 bytes)
 @param skey The key as scheduled
 @return CRYPT_OK if successful
 */
#ifdef LTC_CLEAN_STACK
static int _rijndael_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey) 
#else
int ECB_ENC(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
#endif
{
    ulong32 s0, s1, s2, s3, t0, t1, t2, t3, *rk;
    int Nr, r;
    
    LTC_ARGCHK(pt != NULL);
    LTC_ARGCHK(ct != NULL);
    LTC_ARGCHK(skey != NULL);
    
    Nr = skey->rijndael.Nr;
    rk = skey->rijndael.eK;
    
    /*
     * map byte array block to cipher state
     * and add initial round key:
     */
    LOAD32H(s0, pt      ); s0 ^= rk[0];
    LOAD32H(s1, pt  +  4); s1 ^= rk[1];
    LOAD32H(s2, pt  +  8); s2 ^= rk[2];
    LOAD32H(s3, pt  + 12); s3 ^= rk[3];
    
#ifdef LTC_SMALL_CODE
    
    for (r = 0; ; r++) {
        rk += 4;
        t0 =
        Te0(byte(s0, 3)) ^
        Te1(byte(s1, 2)) ^
        Te2(byte(s2, 1)) ^
        Te3(byte(s3, 0)) ^
        rk[0];
        t1 =
        Te0(byte(s1, 3)) ^
        Te1(byte(s2, 2)) ^
        Te2(byte(s3, 1)) ^
        Te3(byte(s0, 0)) ^
        rk[1];
        t2 =
        Te0(byte(s2, 3)) ^
        Te1(byte(s3, 2)) ^
        Te2(byte(s0, 1)) ^
        Te3(byte(s1, 0)) ^
        rk[2];
        t3 =
        Te0(byte(s3, 3)) ^
        Te1(byte(s0, 2)) ^
        Te2(byte(s1, 1)) ^
        Te3(byte(s2, 0)) ^
        rk[3];
        if (r == Nr-2) { 
            break;
        }
        s0 = t0; s1 = t1; s2 = t2; s3 = t3;
    }
    rk += 4;
    
#else
    
    /*
     * Nr - 1 full rounds:
     */
    r = Nr >> 1;
    for (;;) {
        t0 =
        Te0(byte(s0, 3)) ^
        Te1(byte(s1, 2)) ^
        Te2(byte(s2, 1)) ^
        Te3(byte(s3, 0)) ^
        rk[4];
        t1 =
        Te0(byte(s1, 3)) ^
        Te1(byte(s2, 2)) ^
        Te2(byte(s3, 1)) ^
        Te3(byte(s0, 0)) ^
        rk[5];
        t2 =
        Te0(byte(s2, 3)) ^
        Te1(byte(s3, 2)) ^
        Te2(byte(s0, 1)) ^
        Te3(byte(s1, 0)) ^
        rk[6];
        t3 =
        Te0(byte(s3, 3)) ^
        Te1(byte(s0, 2)) ^
        Te2(byte(s1, 1)) ^
        Te3(byte(s2, 0)) ^
        rk[7];
        
        rk += 8;
        if (--r == 0) {
            break;
        }
        
        s0 =
        Te0(byte(t0, 3)) ^
        Te1(byte(t1, 2)) ^
        Te2(byte(t2, 1)) ^
        Te3(byte(t3, 0)) ^
        rk[0];
        s1 =
        Te0(byte(t1, 3)) ^
        Te1(byte(t2, 2)) ^
        Te2(byte(t3, 1)) ^
        Te3(byte(t0, 0)) ^
        rk[1];
        s2 =
        Te0(byte(t2, 3)) ^
        Te1(byte(t3, 2)) ^
        Te2(byte(t0, 1)) ^
        Te3(byte(t1, 0)) ^
        rk[2];
        s3 =
        Te0(byte(t3, 3)) ^
        Te1(byte(t0, 2)) ^
        Te2(byte(t1, 1)) ^
        Te3(byte(t2, 0)) ^
        rk[3];
    }
    
#endif
    
    /*
     * apply last round and
     * map cipher state to byte array block:
     */
    s0 =
    (Te4_3[byte(t0, 3)]) ^
    (Te4_2[byte(t1, 2)]) ^
    (Te4_1[byte(t2, 1)]) ^
    (Te4_0[byte(t3, 0)]) ^
    rk[0];
    STORE32H(s0, ct);
    s1 =
    (Te4_3[byte(t1, 3)]) ^
    (Te4_2[byte(t2, 2)]) ^
    (Te4_1[byte(t3, 1)]) ^
    (Te4_0[byte(t0, 0)]) ^
    rk[1];
    STORE32H(s1, ct+4);
    s2 =
    (Te4_3[byte(t2, 3)]) ^
    (Te4_2[byte(t3, 2)]) ^
    (Te4_1[byte(t0, 1)]) ^
    (Te4_0[byte(t1, 0)]) ^
    rk[2];
    STORE32H(s2, ct+8);
    s3 =
    (Te4_3[byte(t3, 3)]) ^
    (Te4_2[byte(t0, 2)]) ^
    (Te4_1[byte(t1, 1)]) ^
    (Te4_0[byte(t2, 0)]) ^ 
    rk[3];
    STORE32H(s3, ct+12);
    
    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
int ECB_ENC(const unsigned char *pt, unsigned char *ct, symmetric_key *skey) 
{
    int err = _rijndael_ecb_encrypt(pt, ct, skey);
    burn_stack(sizeof(unsigned long)*8 + sizeof(unsigned long*) + sizeof(int)*2);
    return err;
}
#endif

#ifndef ENCRYPT_ONLY 

/**
 Decrypts a block of text with AES
 @param ct The input ciphertext (16 bytes)
 @param pt The output plaintext (16 bytes)
 @param skey The key as scheduled 
 @return CRYPT_OK if successful
 */
#ifdef LTC_CLEAN_STACK
static int _rijndael_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey) 
#else
int ECB_DEC(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
#endif
{
    ulong32 s0, s1, s2, s3, t0, t1, t2, t3, *rk;
    int Nr, r;
    
    LTC_ARGCHK(pt != NULL);
    LTC_ARGCHK(ct != NULL);
    LTC_ARGCHK(skey != NULL);
    
    Nr = skey->rijndael.Nr;
    rk = skey->rijndael.dK;
    
    /*
     * map byte array block to cipher state
     * and add initial round key:
     */
    LOAD32H(s0, ct      ); s0 ^= rk[0];
    LOAD32H(s1, ct  +  4); s1 ^= rk[1];
    LOAD32H(s2, ct  +  8); s2 ^= rk[2];
    LOAD32H(s3, ct  + 12); s3 ^= rk[3];
    
#ifdef LTC_SMALL_CODE
    for (r = 0; ; r++) {
        rk += 4;
        t0 =
        Td0(byte(s0, 3)) ^
        Td1(byte(s3, 2)) ^
        Td2(byte(s2, 1)) ^
        Td3(byte(s1, 0)) ^
        rk[0];
        t1 =
        Td0(byte(s1, 3)) ^
        Td1(byte(s0, 2)) ^
        Td2(byte(s3, 1)) ^
        Td3(byte(s2, 0)) ^
        rk[1];
        t2 =
        Td0(byte(s2, 3)) ^
        Td1(byte(s1, 2)) ^
        Td2(byte(s0, 1)) ^
        Td3(byte(s3, 0)) ^
        rk[2];
        t3 =
        Td0(byte(s3, 3)) ^
        Td1(byte(s2, 2)) ^
        Td2(byte(s1, 1)) ^
        Td3(byte(s0, 0)) ^
        rk[3];
        if (r == Nr-2) {
            break; 
        }
        s0 = t0; s1 = t1; s2 = t2; s3 = t3;
    }
    rk += 4;
    
#else       
    
    /*
     * Nr - 1 full rounds:
     */
    r = Nr >> 1;
    for (;;) {
        
        t0 =
        Td0(byte(s0, 3)) ^
        Td1(byte(s3, 2)) ^
        Td2(byte(s2, 1)) ^
        Td3(byte(s1, 0)) ^
        rk[4];
        t1 =
        Td0(byte(s1, 3)) ^
        Td1(byte(s0, 2)) ^
        Td2(byte(s3, 1)) ^
        Td3(byte(s2, 0)) ^
        rk[5];
        t2 =
        Td0(byte(s2, 3)) ^
        Td1(byte(s1, 2)) ^
        Td2(byte(s0, 1)) ^
        Td3(byte(s3, 0)) ^
        rk[6];
        t3 =
        Td0(byte(s3, 3)) ^
        Td1(byte(s2, 2)) ^
        Td2(byte(s1, 1)) ^
        Td3(byte(s0, 0)) ^
        rk[7];
        
        rk += 8;
        if (--r == 0) {
            break;
        }
        
        
        s0 =
        Td0(byte(t0, 3)) ^
        Td1(byte(t3, 2)) ^
        Td2(byte(t2, 1)) ^
        Td3(byte(t1, 0)) ^
        rk[0];
        s1 =
        Td0(byte(t1, 3)) ^
        Td1(byte(t0, 2)) ^
        Td2(byte(t3, 1)) ^
        Td3(byte(t2, 0)) ^
        rk[1];
        s2 =
        Td0(byte(t2, 3)) ^
        Td1(byte(t1, 2)) ^
        Td2(byte(t0, 1)) ^
        Td3(byte(t3, 0)) ^
        rk[2];
        s3 =
        Td0(byte(t3, 3)) ^
        Td1(byte(t2, 2)) ^
        Td2(byte(t1, 1)) ^
        Td3(byte(t0, 0)) ^
        rk[3];
    }
#endif
    
    /*
     * apply last round and
     * map cipher state to byte array block:
     */
    s0 =
    (Td4[byte(t0, 3)] & 0xff000000) ^
    (Td4[byte(t3, 2)] & 0x00ff0000) ^
    (Td4[byte(t2, 1)] & 0x0000ff00) ^
    (Td4[byte(t1, 0)] & 0x000000ff) ^
    rk[0];
    STORE32H(s0, pt);
    s1 =
    (Td4[byte(t1, 3)] & 0xff000000) ^
    (Td4[byte(t0, 2)] & 0x00ff0000) ^
    (Td4[byte(t3, 1)] & 0x0000ff00) ^
    (Td4[byte(t2, 0)] & 0x000000ff) ^
    rk[1];
    STORE32H(s1, pt+4);
    s2 =
    (Td4[byte(t2, 3)] & 0xff000000) ^
    (Td4[byte(t1, 2)] & 0x00ff0000) ^
    (Td4[byte(t0, 1)] & 0x0000ff00) ^
    (Td4[byte(t3, 0)] & 0x000000ff) ^
    rk[2];
    STORE32H(s2, pt+8);
    s3 =
    (Td4[byte(t3, 3)] & 0xff000000) ^
    (Td4[byte(t2, 2)] & 0x00ff0000) ^
    (Td4[byte(t1, 1)] & 0x0000ff00) ^
    (Td4[byte(t0, 0)] & 0x000000ff) ^
    rk[3];
    STORE32H(s3, pt+12);
    
    return CRYPT_OK;
}


#ifdef LTC_CLEAN_STACK
int ECB_DEC(const unsigned char *ct, unsigned char *pt, symmetric_key *skey) 
{
    int err = _rijndael_ecb_decrypt(ct, pt, skey);
    burn_stack(sizeof(unsigned long)*8 + sizeof(unsigned long*) + sizeof(int)*2);
    return err;
}
#endif

/**
 Performs a self-test of the AES block cipher
 @return CRYPT_OK if functional, CRYPT_NOP if self-test has been disabled
 */
int ECB_TEST(void)
{
#ifndef LTC_TEST
    return CRYPT_NOP;
#else    
    int err;
    static const struct {
        int keylen;
        unsigned char key[32], pt[16], ct[16];
    } tests[] = {
        { 16,
            { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
                0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, 
            { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
                0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },
            { 0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30, 
                0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a }
        }, { 
            24,
            { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
                0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 },
            { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
                0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },
            { 0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 
                0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71, 0x91 }
        }, {
            32,
            { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
                0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 
                0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f },
            { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
                0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff },
            { 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 
                0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 }
        }
    };
    
    symmetric_key key;
    unsigned char tmp[2][16];
    int i, y;
    
    for (i = 0; i < (int)(sizeof(tests)/sizeof(tests[0])); i++) {
        zeromem(&key, sizeof(key));
        if ((err = rijndael_setup(tests[i].key, tests[i].keylen, 0, &key)) != CRYPT_OK) { 
            return err;
        }
        
        rijndael_ecb_encrypt(tests[i].pt, tmp[0], &key);
        rijndael_ecb_decrypt(tmp[0], tmp[1], &key);
        if (XMEMCMP(tmp[0], tests[i].ct, 16) || XMEMCMP(tmp[1], tests[i].pt, 16)) { 
#if 0
            printf("\n\nTest %d failed\n", i);
            if (XMEMCMP(tmp[0], tests[i].ct, 16)) {
                printf("CT: ");
                for (i = 0; i < 16; i++) {
                    printf("%02x ", tmp[0][i]);
                }
                printf("\n");
            } else {
                printf("PT: ");
                for (i = 0; i < 16; i++) {
                    printf("%02x ", tmp[1][i]);
                }
                printf("\n");
            }
#endif       
            return CRYPT_FAIL_TESTVECTOR;
        }
        
        /* now see if we can encrypt all zero bytes 1000 times, decrypt and come back where we started */
        for (y = 0; y < 16; y++) tmp[0][y] = 0;
        for (y = 0; y < 1000; y++) rijndael_ecb_encrypt(tmp[0], tmp[0], &key);
        for (y = 0; y < 1000; y++) rijndael_ecb_decrypt(tmp[0], tmp[0], &key);
        for (y = 0; y < 16; y++) if (tmp[0][y] != 0) return CRYPT_FAIL_TESTVECTOR;
    }       
    return CRYPT_OK;
#endif
}

#endif /* ENCRYPT_ONLY */


/** Terminate the context 
 @param skey    The scheduled key
 */
void ECB_DONE(symmetric_key *skey)
{
}


/**
 Gets suitable key size
 @param keysize [in/out] The length of the recommended key (in bytes).  This function will store the suitable size back in this variable.
 @return CRYPT_OK if the input key size is acceptable.
 */
int ECB_KS(int *keysize)
{
    LTC_ARGCHK(keysize != NULL);
    
    if (*keysize < 16)
        return CRYPT_INVALID_KEYSIZE;
    if (*keysize < 24) {
        *keysize = 16;
        return CRYPT_OK;
    } else if (*keysize < 32) {
        *keysize = 24;
        return CRYPT_OK;
    } else {
        *keysize = 32;
        return CRYPT_OK;
    }
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/ciphers/aes/aes.c,v $ */
/* $Revision: 1.16 $ */
/* $Date: 2007/05/12 14:13:00 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/ltc_aes/aes_tab.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
/* The precomputed tables for AES */
/*
 Te0[x] = S [x].[02, 01, 01, 03];
 Te1[x] = S [x].[03, 02, 01, 01];
 Te2[x] = S [x].[01, 03, 02, 01];
 Te3[x] = S [x].[01, 01, 03, 02];
 Te4[x] = S [x].[01, 01, 01, 01];
 
 Td0[x] = Si[x].[0e, 09, 0d, 0b];
 Td1[x] = Si[x].[0b, 0e, 09, 0d];
 Td2[x] = Si[x].[0d, 0b, 0e, 09];
 Td3[x] = Si[x].[09, 0d, 0b, 0e];
 Td4[x] = Si[x].[01, 01, 01, 01];
 */

/**
 @file aes_tab.c
 AES tables
 */  
 
#include <stdint.h>

static const uint32_t TE0[256] = {
    0xc66363a5UL, 0xf87c7c84UL, 0xee777799UL, 0xf67b7b8dUL,
    0xfff2f20dUL, 0xd66b6bbdUL, 0xde6f6fb1UL, 0x91c5c554UL,
    0x60303050UL, 0x02010103UL, 0xce6767a9UL, 0x562b2b7dUL,
    0xe7fefe19UL, 0xb5d7d762UL, 0x4dababe6UL, 0xec76769aUL,
    0x8fcaca45UL, 0x1f82829dUL, 0x89c9c940UL, 0xfa7d7d87UL,
    0xeffafa15UL, 0xb25959ebUL, 0x8e4747c9UL, 0xfbf0f00bUL,
    0x41adadecUL, 0xb3d4d467UL, 0x5fa2a2fdUL, 0x45afafeaUL,
    0x239c9cbfUL, 0x53a4a4f7UL, 0xe4727296UL, 0x9bc0c05bUL,
    0x75b7b7c2UL, 0xe1fdfd1cUL, 0x3d9393aeUL, 0x4c26266aUL,
    0x6c36365aUL, 0x7e3f3f41UL, 0xf5f7f702UL, 0x83cccc4fUL,
    0x6834345cUL, 0x51a5a5f4UL, 0xd1e5e534UL, 0xf9f1f108UL,
    0xe2717193UL, 0xabd8d873UL, 0x62313153UL, 0x2a15153fUL,
    0x0804040cUL, 0x95c7c752UL, 0x46232365UL, 0x9dc3c35eUL,
    0x30181828UL, 0x379696a1UL, 0x0a05050fUL, 0x2f9a9ab5UL,
    0x0e070709UL, 0x24121236UL, 0x1b80809bUL, 0xdfe2e23dUL,
    0xcdebeb26UL, 0x4e272769UL, 0x7fb2b2cdUL, 0xea75759fUL,
    0x1209091bUL, 0x1d83839eUL, 0x582c2c74UL, 0x341a1a2eUL,
    0x361b1b2dUL, 0xdc6e6eb2UL, 0xb45a5aeeUL, 0x5ba0a0fbUL,
    0xa45252f6UL, 0x763b3b4dUL, 0xb7d6d661UL, 0x7db3b3ceUL,
    0x5229297bUL, 0xdde3e33eUL, 0x5e2f2f71UL, 0x13848497UL,
    0xa65353f5UL, 0xb9d1d168UL, 0x00000000UL, 0xc1eded2cUL,
    0x40202060UL, 0xe3fcfc1fUL, 0x79b1b1c8UL, 0xb65b5bedUL,
    0xd46a6abeUL, 0x8dcbcb46UL, 0x67bebed9UL, 0x7239394bUL,
    0x944a4adeUL, 0x984c4cd4UL, 0xb05858e8UL, 0x85cfcf4aUL,
    0xbbd0d06bUL, 0xc5efef2aUL, 0x4faaaae5UL, 0xedfbfb16UL,
    0x864343c5UL, 0x9a4d4dd7UL, 0x66333355UL, 0x11858594UL,
    0x8a4545cfUL, 0xe9f9f910UL, 0x04020206UL, 0xfe7f7f81UL,
    0xa05050f0UL, 0x783c3c44UL, 0x259f9fbaUL, 0x4ba8a8e3UL,
    0xa25151f3UL, 0x5da3a3feUL, 0x804040c0UL, 0x058f8f8aUL,
    0x3f9292adUL, 0x219d9dbcUL, 0x70383848UL, 0xf1f5f504UL,
    0x63bcbcdfUL, 0x77b6b6c1UL, 0xafdada75UL, 0x42212163UL,
    0x20101030UL, 0xe5ffff1aUL, 0xfdf3f30eUL, 0xbfd2d26dUL,
    0x81cdcd4cUL, 0x180c0c14UL, 0x26131335UL, 0xc3ecec2fUL,
    0xbe5f5fe1UL, 0x359797a2UL, 0x884444ccUL, 0x2e171739UL,
    0x93c4c457UL, 0x55a7a7f2UL, 0xfc7e7e82UL, 0x7a3d3d47UL,
    0xc86464acUL, 0xba5d5de7UL, 0x3219192bUL, 0xe6737395UL,
    0xc06060a0UL, 0x19818198UL, 0x9e4f4fd1UL, 0xa3dcdc7fUL,
    0x44222266UL, 0x542a2a7eUL, 0x3b9090abUL, 0x0b888883UL,
    0x8c4646caUL, 0xc7eeee29UL, 0x6bb8b8d3UL, 0x2814143cUL,
    0xa7dede79UL, 0xbc5e5ee2UL, 0x160b0b1dUL, 0xaddbdb76UL,
    0xdbe0e03bUL, 0x64323256UL, 0x743a3a4eUL, 0x140a0a1eUL,
    0x924949dbUL, 0x0c06060aUL, 0x4824246cUL, 0xb85c5ce4UL,
    0x9fc2c25dUL, 0xbdd3d36eUL, 0x43acacefUL, 0xc46262a6UL,
    0x399191a8UL, 0x319595a4UL, 0xd3e4e437UL, 0xf279798bUL,
    0xd5e7e732UL, 0x8bc8c843UL, 0x6e373759UL, 0xda6d6db7UL,
    0x018d8d8cUL, 0xb1d5d564UL, 0x9c4e4ed2UL, 0x49a9a9e0UL,
    0xd86c6cb4UL, 0xac5656faUL, 0xf3f4f407UL, 0xcfeaea25UL,
    0xca6565afUL, 0xf47a7a8eUL, 0x47aeaee9UL, 0x10080818UL,
    0x6fbabad5UL, 0xf0787888UL, 0x4a25256fUL, 0x5c2e2e72UL,
    0x381c1c24UL, 0x57a6a6f1UL, 0x73b4b4c7UL, 0x97c6c651UL,
    0xcbe8e823UL, 0xa1dddd7cUL, 0xe874749cUL, 0x3e1f1f21UL,
    0x964b4bddUL, 0x61bdbddcUL, 0x0d8b8b86UL, 0x0f8a8a85UL,
    0xe0707090UL, 0x7c3e3e42UL, 0x71b5b5c4UL, 0xcc6666aaUL,
    0x904848d8UL, 0x06030305UL, 0xf7f6f601UL, 0x1c0e0e12UL,
    0xc26161a3UL, 0x6a35355fUL, 0xae5757f9UL, 0x69b9b9d0UL,
    0x17868691UL, 0x99c1c158UL, 0x3a1d1d27UL, 0x279e9eb9UL,
    0xd9e1e138UL, 0xebf8f813UL, 0x2b9898b3UL, 0x22111133UL,
    0xd26969bbUL, 0xa9d9d970UL, 0x078e8e89UL, 0x339494a7UL,
    0x2d9b9bb6UL, 0x3c1e1e22UL, 0x15878792UL, 0xc9e9e920UL,
    0x87cece49UL, 0xaa5555ffUL, 0x50282878UL, 0xa5dfdf7aUL,
    0x038c8c8fUL, 0x59a1a1f8UL, 0x09898980UL, 0x1a0d0d17UL,
    0x65bfbfdaUL, 0xd7e6e631UL, 0x844242c6UL, 0xd06868b8UL,
    0x824141c3UL, 0x299999b0UL, 0x5a2d2d77UL, 0x1e0f0f11UL,
    0x7bb0b0cbUL, 0xa85454fcUL, 0x6dbbbbd6UL, 0x2c16163aUL,
};

#ifndef PELI_TAB
static const uint32_t Te4[256] = {
    0x63636363UL, 0x7c7c7c7cUL, 0x77777777UL, 0x7b7b7b7bUL,
    0xf2f2f2f2UL, 0x6b6b6b6bUL, 0x6f6f6f6fUL, 0xc5c5c5c5UL,
    0x30303030UL, 0x01010101UL, 0x67676767UL, 0x2b2b2b2bUL,
    0xfefefefeUL, 0xd7d7d7d7UL, 0xababababUL, 0x76767676UL,
    0xcacacacaUL, 0x82828282UL, 0xc9c9c9c9UL, 0x7d7d7d7dUL,
    0xfafafafaUL, 0x59595959UL, 0x47474747UL, 0xf0f0f0f0UL,
    0xadadadadUL, 0xd4d4d4d4UL, 0xa2a2a2a2UL, 0xafafafafUL,
    0x9c9c9c9cUL, 0xa4a4a4a4UL, 0x72727272UL, 0xc0c0c0c0UL,
    0xb7b7b7b7UL, 0xfdfdfdfdUL, 0x93939393UL, 0x26262626UL,
    0x36363636UL, 0x3f3f3f3fUL, 0xf7f7f7f7UL, 0xccccccccUL,
    0x34343434UL, 0xa5a5a5a5UL, 0xe5e5e5e5UL, 0xf1f1f1f1UL,
    0x71717171UL, 0xd8d8d8d8UL, 0x31313131UL, 0x15151515UL,
    0x04040404UL, 0xc7c7c7c7UL, 0x23232323UL, 0xc3c3c3c3UL,
    0x18181818UL, 0x96969696UL, 0x05050505UL, 0x9a9a9a9aUL,
    0x07070707UL, 0x12121212UL, 0x80808080UL, 0xe2e2e2e2UL,
    0xebebebebUL, 0x27272727UL, 0xb2b2b2b2UL, 0x75757575UL,
    0x09090909UL, 0x83838383UL, 0x2c2c2c2cUL, 0x1a1a1a1aUL,
    0x1b1b1b1bUL, 0x6e6e6e6eUL, 0x5a5a5a5aUL, 0xa0a0a0a0UL,
    0x52525252UL, 0x3b3b3b3bUL, 0xd6d6d6d6UL, 0xb3b3b3b3UL,
    0x29292929UL, 0xe3e3e3e3UL, 0x2f2f2f2fUL, 0x84848484UL,
    0x53535353UL, 0xd1d1d1d1UL, 0x00000000UL, 0xededededUL,
    0x20202020UL, 0xfcfcfcfcUL, 0xb1b1b1b1UL, 0x5b5b5b5bUL,
    0x6a6a6a6aUL, 0xcbcbcbcbUL, 0xbebebebeUL, 0x39393939UL,
    0x4a4a4a4aUL, 0x4c4c4c4cUL, 0x58585858UL, 0xcfcfcfcfUL,
    0xd0d0d0d0UL, 0xefefefefUL, 0xaaaaaaaaUL, 0xfbfbfbfbUL,
    0x43434343UL, 0x4d4d4d4dUL, 0x33333333UL, 0x85858585UL,
    0x45454545UL, 0xf9f9f9f9UL, 0x02020202UL, 0x7f7f7f7fUL,
    0x50505050UL, 0x3c3c3c3cUL, 0x9f9f9f9fUL, 0xa8a8a8a8UL,
    0x51515151UL, 0xa3a3a3a3UL, 0x40404040UL, 0x8f8f8f8fUL,
    0x92929292UL, 0x9d9d9d9dUL, 0x38383838UL, 0xf5f5f5f5UL,
    0xbcbcbcbcUL, 0xb6b6b6b6UL, 0xdadadadaUL, 0x21212121UL,
    0x10101010UL, 0xffffffffUL, 0xf3f3f3f3UL, 0xd2d2d2d2UL,
    0xcdcdcdcdUL, 0x0c0c0c0cUL, 0x13131313UL, 0xececececUL,
    0x5f5f5f5fUL, 0x97979797UL, 0x44444444UL, 0x17171717UL,
    0xc4c4c4c4UL, 0xa7a7a7a7UL, 0x7e7e7e7eUL, 0x3d3d3d3dUL,
    0x64646464UL, 0x5d5d5d5dUL, 0x19191919UL, 0x73737373UL,
    0x60606060UL, 0x81818181UL, 0x4f4f4f4fUL, 0xdcdcdcdcUL,
    0x22222222UL, 0x2a2a2a2aUL, 0x90909090UL, 0x88888888UL,
    0x46464646UL, 0xeeeeeeeeUL, 0xb8b8b8b8UL, 0x14141414UL,
    0xdedededeUL, 0x5e5e5e5eUL, 0x0b0b0b0bUL, 0xdbdbdbdbUL,
    0xe0e0e0e0UL, 0x32323232UL, 0x3a3a3a3aUL, 0x0a0a0a0aUL,
    0x49494949UL, 0x06060606UL, 0x24242424UL, 0x5c5c5c5cUL,
    0xc2c2c2c2UL, 0xd3d3d3d3UL, 0xacacacacUL, 0x62626262UL,
    0x91919191UL, 0x95959595UL, 0xe4e4e4e4UL, 0x79797979UL,
    0xe7e7e7e7UL, 0xc8c8c8c8UL, 0x37373737UL, 0x6d6d6d6dUL,
    0x8d8d8d8dUL, 0xd5d5d5d5UL, 0x4e4e4e4eUL, 0xa9a9a9a9UL,
    0x6c6c6c6cUL, 0x56565656UL, 0xf4f4f4f4UL, 0xeaeaeaeaUL,
    0x65656565UL, 0x7a7a7a7aUL, 0xaeaeaeaeUL, 0x08080808UL,
    0xbabababaUL, 0x78787878UL, 0x25252525UL, 0x2e2e2e2eUL,
    0x1c1c1c1cUL, 0xa6a6a6a6UL, 0xb4b4b4b4UL, 0xc6c6c6c6UL,
    0xe8e8e8e8UL, 0xddddddddUL, 0x74747474UL, 0x1f1f1f1fUL,
    0x4b4b4b4bUL, 0xbdbdbdbdUL, 0x8b8b8b8bUL, 0x8a8a8a8aUL,
    0x70707070UL, 0x3e3e3e3eUL, 0xb5b5b5b5UL, 0x66666666UL,
    0x48484848UL, 0x03030303UL, 0xf6f6f6f6UL, 0x0e0e0e0eUL,
    0x61616161UL, 0x35353535UL, 0x57575757UL, 0xb9b9b9b9UL,
    0x86868686UL, 0xc1c1c1c1UL, 0x1d1d1d1dUL, 0x9e9e9e9eUL,
    0xe1e1e1e1UL, 0xf8f8f8f8UL, 0x98989898UL, 0x11111111UL,
    0x69696969UL, 0xd9d9d9d9UL, 0x8e8e8e8eUL, 0x94949494UL,
    0x9b9b9b9bUL, 0x1e1e1e1eUL, 0x87878787UL, 0xe9e9e9e9UL,
    0xcecececeUL, 0x55555555UL, 0x28282828UL, 0xdfdfdfdfUL,
    0x8c8c8c8cUL, 0xa1a1a1a1UL, 0x89898989UL, 0x0d0d0d0dUL,
    0xbfbfbfbfUL, 0xe6e6e6e6UL, 0x42424242UL, 0x68686868UL,
    0x41414141UL, 0x99999999UL, 0x2d2d2d2dUL, 0x0f0f0f0fUL,
    0xb0b0b0b0UL, 0x54545454UL, 0xbbbbbbbbUL, 0x16161616UL,
};
#endif

#ifndef ENCRYPT_ONLY

static const uint32_t TD0[256] = {
    0x51f4a750UL, 0x7e416553UL, 0x1a17a4c3UL, 0x3a275e96UL,
    0x3bab6bcbUL, 0x1f9d45f1UL, 0xacfa58abUL, 0x4be30393UL,
    0x2030fa55UL, 0xad766df6UL, 0x88cc7691UL, 0xf5024c25UL,
    0x4fe5d7fcUL, 0xc52acbd7UL, 0x26354480UL, 0xb562a38fUL,
    0xdeb15a49UL, 0x25ba1b67UL, 0x45ea0e98UL, 0x5dfec0e1UL,
    0xc32f7502UL, 0x814cf012UL, 0x8d4697a3UL, 0x6bd3f9c6UL,
    0x038f5fe7UL, 0x15929c95UL, 0xbf6d7aebUL, 0x955259daUL,
    0xd4be832dUL, 0x587421d3UL, 0x49e06929UL, 0x8ec9c844UL,
    0x75c2896aUL, 0xf48e7978UL, 0x99583e6bUL, 0x27b971ddUL,
    0xbee14fb6UL, 0xf088ad17UL, 0xc920ac66UL, 0x7dce3ab4UL,
    0x63df4a18UL, 0xe51a3182UL, 0x97513360UL, 0x62537f45UL,
    0xb16477e0UL, 0xbb6bae84UL, 0xfe81a01cUL, 0xf9082b94UL,
    0x70486858UL, 0x8f45fd19UL, 0x94de6c87UL, 0x527bf8b7UL,
    0xab73d323UL, 0x724b02e2UL, 0xe31f8f57UL, 0x6655ab2aUL,
    0xb2eb2807UL, 0x2fb5c203UL, 0x86c57b9aUL, 0xd33708a5UL,
    0x302887f2UL, 0x23bfa5b2UL, 0x02036abaUL, 0xed16825cUL,
    0x8acf1c2bUL, 0xa779b492UL, 0xf307f2f0UL, 0x4e69e2a1UL,
    0x65daf4cdUL, 0x0605bed5UL, 0xd134621fUL, 0xc4a6fe8aUL,
    0x342e539dUL, 0xa2f355a0UL, 0x058ae132UL, 0xa4f6eb75UL,
    0x0b83ec39UL, 0x4060efaaUL, 0x5e719f06UL, 0xbd6e1051UL,
    0x3e218af9UL, 0x96dd063dUL, 0xdd3e05aeUL, 0x4de6bd46UL,
    0x91548db5UL, 0x71c45d05UL, 0x0406d46fUL, 0x605015ffUL,
    0x1998fb24UL, 0xd6bde997UL, 0x894043ccUL, 0x67d99e77UL,
    0xb0e842bdUL, 0x07898b88UL, 0xe7195b38UL, 0x79c8eedbUL,
    0xa17c0a47UL, 0x7c420fe9UL, 0xf8841ec9UL, 0x00000000UL,
    0x09808683UL, 0x322bed48UL, 0x1e1170acUL, 0x6c5a724eUL,
    0xfd0efffbUL, 0x0f853856UL, 0x3daed51eUL, 0x362d3927UL,
    0x0a0fd964UL, 0x685ca621UL, 0x9b5b54d1UL, 0x24362e3aUL,
    0x0c0a67b1UL, 0x9357e70fUL, 0xb4ee96d2UL, 0x1b9b919eUL,
    0x80c0c54fUL, 0x61dc20a2UL, 0x5a774b69UL, 0x1c121a16UL,
    0xe293ba0aUL, 0xc0a02ae5UL, 0x3c22e043UL, 0x121b171dUL,
    0x0e090d0bUL, 0xf28bc7adUL, 0x2db6a8b9UL, 0x141ea9c8UL,
    0x57f11985UL, 0xaf75074cUL, 0xee99ddbbUL, 0xa37f60fdUL,
    0xf701269fUL, 0x5c72f5bcUL, 0x44663bc5UL, 0x5bfb7e34UL,
    0x8b432976UL, 0xcb23c6dcUL, 0xb6edfc68UL, 0xb8e4f163UL,
    0xd731dccaUL, 0x42638510UL, 0x13972240UL, 0x84c61120UL,
    0x854a247dUL, 0xd2bb3df8UL, 0xaef93211UL, 0xc729a16dUL,
    0x1d9e2f4bUL, 0xdcb230f3UL, 0x0d8652ecUL, 0x77c1e3d0UL,
    0x2bb3166cUL, 0xa970b999UL, 0x119448faUL, 0x47e96422UL,
    0xa8fc8cc4UL, 0xa0f03f1aUL, 0x567d2cd8UL, 0x223390efUL,
    0x87494ec7UL, 0xd938d1c1UL, 0x8ccaa2feUL, 0x98d40b36UL,
    0xa6f581cfUL, 0xa57ade28UL, 0xdab78e26UL, 0x3fadbfa4UL,
    0x2c3a9de4UL, 0x5078920dUL, 0x6a5fcc9bUL, 0x547e4662UL,
    0xf68d13c2UL, 0x90d8b8e8UL, 0x2e39f75eUL, 0x82c3aff5UL,
    0x9f5d80beUL, 0x69d0937cUL, 0x6fd52da9UL, 0xcf2512b3UL,
    0xc8ac993bUL, 0x10187da7UL, 0xe89c636eUL, 0xdb3bbb7bUL,
    0xcd267809UL, 0x6e5918f4UL, 0xec9ab701UL, 0x834f9aa8UL,
    0xe6956e65UL, 0xaaffe67eUL, 0x21bccf08UL, 0xef15e8e6UL,
    0xbae79bd9UL, 0x4a6f36ceUL, 0xea9f09d4UL, 0x29b07cd6UL,
    0x31a4b2afUL, 0x2a3f2331UL, 0xc6a59430UL, 0x35a266c0UL,
    0x744ebc37UL, 0xfc82caa6UL, 0xe090d0b0UL, 0x33a7d815UL,
    0xf104984aUL, 0x41ecdaf7UL, 0x7fcd500eUL, 0x1791f62fUL,
    0x764dd68dUL, 0x43efb04dUL, 0xccaa4d54UL, 0xe49604dfUL,
    0x9ed1b5e3UL, 0x4c6a881bUL, 0xc12c1fb8UL, 0x4665517fUL,
    0x9d5eea04UL, 0x018c355dUL, 0xfa877473UL, 0xfb0b412eUL,
    0xb3671d5aUL, 0x92dbd252UL, 0xe9105633UL, 0x6dd64713UL,
    0x9ad7618cUL, 0x37a10c7aUL, 0x59f8148eUL, 0xeb133c89UL,
    0xcea927eeUL, 0xb761c935UL, 0xe11ce5edUL, 0x7a47b13cUL,
    0x9cd2df59UL, 0x55f2733fUL, 0x1814ce79UL, 0x73c737bfUL,
    0x53f7cdeaUL, 0x5ffdaa5bUL, 0xdf3d6f14UL, 0x7844db86UL,
    0xcaaff381UL, 0xb968c43eUL, 0x3824342cUL, 0xc2a3405fUL,
    0x161dc372UL, 0xbce2250cUL, 0x283c498bUL, 0xff0d9541UL,
    0x39a80171UL, 0x080cb3deUL, 0xd8b4e49cUL, 0x6456c190UL,
    0x7bcb8461UL, 0xd532b670UL, 0x486c5c74UL, 0xd0b85742UL,
};

static const uint32_t Td4[256] = {
    0x52525252UL, 0x09090909UL, 0x6a6a6a6aUL, 0xd5d5d5d5UL,
    0x30303030UL, 0x36363636UL, 0xa5a5a5a5UL, 0x38383838UL,
    0xbfbfbfbfUL, 0x40404040UL, 0xa3a3a3a3UL, 0x9e9e9e9eUL,
    0x81818181UL, 0xf3f3f3f3UL, 0xd7d7d7d7UL, 0xfbfbfbfbUL,
    0x7c7c7c7cUL, 0xe3e3e3e3UL, 0x39393939UL, 0x82828282UL,
    0x9b9b9b9bUL, 0x2f2f2f2fUL, 0xffffffffUL, 0x87878787UL,
    0x34343434UL, 0x8e8e8e8eUL, 0x43434343UL, 0x44444444UL,
    0xc4c4c4c4UL, 0xdedededeUL, 0xe9e9e9e9UL, 0xcbcbcbcbUL,
    0x54545454UL, 0x7b7b7b7bUL, 0x94949494UL, 0x32323232UL,
    0xa6a6a6a6UL, 0xc2c2c2c2UL, 0x23232323UL, 0x3d3d3d3dUL,
    0xeeeeeeeeUL, 0x4c4c4c4cUL, 0x95959595UL, 0x0b0b0b0bUL,
    0x42424242UL, 0xfafafafaUL, 0xc3c3c3c3UL, 0x4e4e4e4eUL,
    0x08080808UL, 0x2e2e2e2eUL, 0xa1a1a1a1UL, 0x66666666UL,
    0x28282828UL, 0xd9d9d9d9UL, 0x24242424UL, 0xb2b2b2b2UL,
    0x76767676UL, 0x5b5b5b5bUL, 0xa2a2a2a2UL, 0x49494949UL,
    0x6d6d6d6dUL, 0x8b8b8b8bUL, 0xd1d1d1d1UL, 0x25252525UL,
    0x72727272UL, 0xf8f8f8f8UL, 0xf6f6f6f6UL, 0x64646464UL,
    0x86868686UL, 0x68686868UL, 0x98989898UL, 0x16161616UL,
    0xd4d4d4d4UL, 0xa4a4a4a4UL, 0x5c5c5c5cUL, 0xccccccccUL,
    0x5d5d5d5dUL, 0x65656565UL, 0xb6b6b6b6UL, 0x92929292UL,
    0x6c6c6c6cUL, 0x70707070UL, 0x48484848UL, 0x50505050UL,
    0xfdfdfdfdUL, 0xededededUL, 0xb9b9b9b9UL, 0xdadadadaUL,
    0x5e5e5e5eUL, 0x15151515UL, 0x46464646UL, 0x57575757UL,
    0xa7a7a7a7UL, 0x8d8d8d8dUL, 0x9d9d9d9dUL, 0x84848484UL,
    0x90909090UL, 0xd8d8d8d8UL, 0xababababUL, 0x00000000UL,
    0x8c8c8c8cUL, 0xbcbcbcbcUL, 0xd3d3d3d3UL, 0x0a0a0a0aUL,
    0xf7f7f7f7UL, 0xe4e4e4e4UL, 0x58585858UL, 0x05050505UL,
    0xb8b8b8b8UL, 0xb3b3b3b3UL, 0x45454545UL, 0x06060606UL,
    0xd0d0d0d0UL, 0x2c2c2c2cUL, 0x1e1e1e1eUL, 0x8f8f8f8fUL,
    0xcacacacaUL, 0x3f3f3f3fUL, 0x0f0f0f0fUL, 0x02020202UL,
    0xc1c1c1c1UL, 0xafafafafUL, 0xbdbdbdbdUL, 0x03030303UL,
    0x01010101UL, 0x13131313UL, 0x8a8a8a8aUL, 0x6b6b6b6bUL,
    0x3a3a3a3aUL, 0x91919191UL, 0x11111111UL, 0x41414141UL,
    0x4f4f4f4fUL, 0x67676767UL, 0xdcdcdcdcUL, 0xeaeaeaeaUL,
    0x97979797UL, 0xf2f2f2f2UL, 0xcfcfcfcfUL, 0xcecececeUL,
    0xf0f0f0f0UL, 0xb4b4b4b4UL, 0xe6e6e6e6UL, 0x73737373UL,
    0x96969696UL, 0xacacacacUL, 0x74747474UL, 0x22222222UL,
    0xe7e7e7e7UL, 0xadadadadUL, 0x35353535UL, 0x85858585UL,
    0xe2e2e2e2UL, 0xf9f9f9f9UL, 0x37373737UL, 0xe8e8e8e8UL,
    0x1c1c1c1cUL, 0x75757575UL, 0xdfdfdfdfUL, 0x6e6e6e6eUL,
    0x47474747UL, 0xf1f1f1f1UL, 0x1a1a1a1aUL, 0x71717171UL,
    0x1d1d1d1dUL, 0x29292929UL, 0xc5c5c5c5UL, 0x89898989UL,
    0x6f6f6f6fUL, 0xb7b7b7b7UL, 0x62626262UL, 0x0e0e0e0eUL,
    0xaaaaaaaaUL, 0x18181818UL, 0xbebebebeUL, 0x1b1b1b1bUL,
    0xfcfcfcfcUL, 0x56565656UL, 0x3e3e3e3eUL, 0x4b4b4b4bUL,
    0xc6c6c6c6UL, 0xd2d2d2d2UL, 0x79797979UL, 0x20202020UL,
    0x9a9a9a9aUL, 0xdbdbdbdbUL, 0xc0c0c0c0UL, 0xfefefefeUL,
    0x78787878UL, 0xcdcdcdcdUL, 0x5a5a5a5aUL, 0xf4f4f4f4UL,
    0x1f1f1f1fUL, 0xddddddddUL, 0xa8a8a8a8UL, 0x33333333UL,
    0x88888888UL, 0x07070707UL, 0xc7c7c7c7UL, 0x31313131UL,
    0xb1b1b1b1UL, 0x12121212UL, 0x10101010UL, 0x59595959UL,
    0x27272727UL, 0x80808080UL, 0xececececUL, 0x5f5f5f5fUL,
    0x60606060UL, 0x51515151UL, 0x7f7f7f7fUL, 0xa9a9a9a9UL,
    0x19191919UL, 0xb5b5b5b5UL, 0x4a4a4a4aUL, 0x0d0d0d0dUL,
    0x2d2d2d2dUL, 0xe5e5e5e5UL, 0x7a7a7a7aUL, 0x9f9f9f9fUL,
    0x93939393UL, 0xc9c9c9c9UL, 0x9c9c9c9cUL, 0xefefefefUL,
    0xa0a0a0a0UL, 0xe0e0e0e0UL, 0x3b3b3b3bUL, 0x4d4d4d4dUL,
    0xaeaeaeaeUL, 0x2a2a2a2aUL, 0xf5f5f5f5UL, 0xb0b0b0b0UL,
    0xc8c8c8c8UL, 0xebebebebUL, 0xbbbbbbbbUL, 0x3c3c3c3cUL,
    0x83838383UL, 0x53535353UL, 0x99999999UL, 0x61616161UL,
    0x17171717UL, 0x2b2b2b2bUL, 0x04040404UL, 0x7e7e7e7eUL,
    0xbabababaUL, 0x77777777UL, 0xd6d6d6d6UL, 0x26262626UL,
    0xe1e1e1e1UL, 0x69696969UL, 0x14141414UL, 0x63636363UL,
    0x55555555UL, 0x21212121UL, 0x0c0c0c0cUL, 0x7d7d7d7dUL,
};

#endif /* ENCRYPT_ONLY */

#ifdef LTC_SMALL_CODE

#define Te0(x) TE0[x]
#define Te1(x) RORc(TE0[x], 8)
#define Te2(x) RORc(TE0[x], 16)
#define Te3(x) RORc(TE0[x], 24)

#define Td0(x) TD0[x]
#define Td1(x) RORc(TD0[x], 8)
#define Td2(x) RORc(TD0[x], 16)
#define Td3(x) RORc(TD0[x], 24)

#define Te4_0 0x000000FF & Te4
#define Te4_1 0x0000FF00 & Te4
#define Te4_2 0x00FF0000 & Te4
#define Te4_3 0xFF000000 & Te4

#else

#define Te0(x) TE0[x]
#define Te1(x) TE1[x]
#define Te2(x) TE2[x]
#define Te3(x) TE3[x]

#define Td0(x) TD0[x]
#define Td1(x) TD1[x]
#define Td2(x) TD2[x]
#define Td3(x) TD3[x]

static const uint32_t TE1[256] = {
    0xa5c66363UL, 0x84f87c7cUL, 0x99ee7777UL, 0x8df67b7bUL,
    0x0dfff2f2UL, 0xbdd66b6bUL, 0xb1de6f6fUL, 0x5491c5c5UL,
    0x50603030UL, 0x03020101UL, 0xa9ce6767UL, 0x7d562b2bUL,
    0x19e7fefeUL, 0x62b5d7d7UL, 0xe64dababUL, 0x9aec7676UL,
    0x458fcacaUL, 0x9d1f8282UL, 0x4089c9c9UL, 0x87fa7d7dUL,
    0x15effafaUL, 0xebb25959UL, 0xc98e4747UL, 0x0bfbf0f0UL,
    0xec41adadUL, 0x67b3d4d4UL, 0xfd5fa2a2UL, 0xea45afafUL,
    0xbf239c9cUL, 0xf753a4a4UL, 0x96e47272UL, 0x5b9bc0c0UL,
    0xc275b7b7UL, 0x1ce1fdfdUL, 0xae3d9393UL, 0x6a4c2626UL,
    0x5a6c3636UL, 0x417e3f3fUL, 0x02f5f7f7UL, 0x4f83ccccUL,
    0x5c683434UL, 0xf451a5a5UL, 0x34d1e5e5UL, 0x08f9f1f1UL,
    0x93e27171UL, 0x73abd8d8UL, 0x53623131UL, 0x3f2a1515UL,
    0x0c080404UL, 0x5295c7c7UL, 0x65462323UL, 0x5e9dc3c3UL,
    0x28301818UL, 0xa1379696UL, 0x0f0a0505UL, 0xb52f9a9aUL,
    0x090e0707UL, 0x36241212UL, 0x9b1b8080UL, 0x3ddfe2e2UL,
    0x26cdebebUL, 0x694e2727UL, 0xcd7fb2b2UL, 0x9fea7575UL,
    0x1b120909UL, 0x9e1d8383UL, 0x74582c2cUL, 0x2e341a1aUL,
    0x2d361b1bUL, 0xb2dc6e6eUL, 0xeeb45a5aUL, 0xfb5ba0a0UL,
    0xf6a45252UL, 0x4d763b3bUL, 0x61b7d6d6UL, 0xce7db3b3UL,
    0x7b522929UL, 0x3edde3e3UL, 0x715e2f2fUL, 0x97138484UL,
    0xf5a65353UL, 0x68b9d1d1UL, 0x00000000UL, 0x2cc1ededUL,
    0x60402020UL, 0x1fe3fcfcUL, 0xc879b1b1UL, 0xedb65b5bUL,
    0xbed46a6aUL, 0x468dcbcbUL, 0xd967bebeUL, 0x4b723939UL,
    0xde944a4aUL, 0xd4984c4cUL, 0xe8b05858UL, 0x4a85cfcfUL,
    0x6bbbd0d0UL, 0x2ac5efefUL, 0xe54faaaaUL, 0x16edfbfbUL,
    0xc5864343UL, 0xd79a4d4dUL, 0x55663333UL, 0x94118585UL,
    0xcf8a4545UL, 0x10e9f9f9UL, 0x06040202UL, 0x81fe7f7fUL,
    0xf0a05050UL, 0x44783c3cUL, 0xba259f9fUL, 0xe34ba8a8UL,
    0xf3a25151UL, 0xfe5da3a3UL, 0xc0804040UL, 0x8a058f8fUL,
    0xad3f9292UL, 0xbc219d9dUL, 0x48703838UL, 0x04f1f5f5UL,
    0xdf63bcbcUL, 0xc177b6b6UL, 0x75afdadaUL, 0x63422121UL,
    0x30201010UL, 0x1ae5ffffUL, 0x0efdf3f3UL, 0x6dbfd2d2UL,
    0x4c81cdcdUL, 0x14180c0cUL, 0x35261313UL, 0x2fc3ececUL,
    0xe1be5f5fUL, 0xa2359797UL, 0xcc884444UL, 0x392e1717UL,
    0x5793c4c4UL, 0xf255a7a7UL, 0x82fc7e7eUL, 0x477a3d3dUL,
    0xacc86464UL, 0xe7ba5d5dUL, 0x2b321919UL, 0x95e67373UL,
    0xa0c06060UL, 0x98198181UL, 0xd19e4f4fUL, 0x7fa3dcdcUL,
    0x66442222UL, 0x7e542a2aUL, 0xab3b9090UL, 0x830b8888UL,
    0xca8c4646UL, 0x29c7eeeeUL, 0xd36bb8b8UL, 0x3c281414UL,
    0x79a7dedeUL, 0xe2bc5e5eUL, 0x1d160b0bUL, 0x76addbdbUL,
    0x3bdbe0e0UL, 0x56643232UL, 0x4e743a3aUL, 0x1e140a0aUL,
    0xdb924949UL, 0x0a0c0606UL, 0x6c482424UL, 0xe4b85c5cUL,
    0x5d9fc2c2UL, 0x6ebdd3d3UL, 0xef43acacUL, 0xa6c46262UL,
    0xa8399191UL, 0xa4319595UL, 0x37d3e4e4UL, 0x8bf27979UL,
    0x32d5e7e7UL, 0x438bc8c8UL, 0x596e3737UL, 0xb7da6d6dUL,
    0x8c018d8dUL, 0x64b1d5d5UL, 0xd29c4e4eUL, 0xe049a9a9UL,
    0xb4d86c6cUL, 0xfaac5656UL, 0x07f3f4f4UL, 0x25cfeaeaUL,
    0xafca6565UL, 0x8ef47a7aUL, 0xe947aeaeUL, 0x18100808UL,
    0xd56fbabaUL, 0x88f07878UL, 0x6f4a2525UL, 0x725c2e2eUL,
    0x24381c1cUL, 0xf157a6a6UL, 0xc773b4b4UL, 0x5197c6c6UL,
    0x23cbe8e8UL, 0x7ca1ddddUL, 0x9ce87474UL, 0x213e1f1fUL,
    0xdd964b4bUL, 0xdc61bdbdUL, 0x860d8b8bUL, 0x850f8a8aUL,
    0x90e07070UL, 0x427c3e3eUL, 0xc471b5b5UL, 0xaacc6666UL,
    0xd8904848UL, 0x05060303UL, 0x01f7f6f6UL, 0x121c0e0eUL,
    0xa3c26161UL, 0x5f6a3535UL, 0xf9ae5757UL, 0xd069b9b9UL,
    0x91178686UL, 0x5899c1c1UL, 0x273a1d1dUL, 0xb9279e9eUL,
    0x38d9e1e1UL, 0x13ebf8f8UL, 0xb32b9898UL, 0x33221111UL,
    0xbbd26969UL, 0x70a9d9d9UL, 0x89078e8eUL, 0xa7339494UL,
    0xb62d9b9bUL, 0x223c1e1eUL, 0x92158787UL, 0x20c9e9e9UL,
    0x4987ceceUL, 0xffaa5555UL, 0x78502828UL, 0x7aa5dfdfUL,
    0x8f038c8cUL, 0xf859a1a1UL, 0x80098989UL, 0x171a0d0dUL,
    0xda65bfbfUL, 0x31d7e6e6UL, 0xc6844242UL, 0xb8d06868UL,
    0xc3824141UL, 0xb0299999UL, 0x775a2d2dUL, 0x111e0f0fUL,
    0xcb7bb0b0UL, 0xfca85454UL, 0xd66dbbbbUL, 0x3a2c1616UL,
};
static const uint32_t TE2[256] = {
    0x63a5c663UL, 0x7c84f87cUL, 0x7799ee77UL, 0x7b8df67bUL,
    0xf20dfff2UL, 0x6bbdd66bUL, 0x6fb1de6fUL, 0xc55491c5UL,
    0x30506030UL, 0x01030201UL, 0x67a9ce67UL, 0x2b7d562bUL,
    0xfe19e7feUL, 0xd762b5d7UL, 0xabe64dabUL, 0x769aec76UL,
    0xca458fcaUL, 0x829d1f82UL, 0xc94089c9UL, 0x7d87fa7dUL,
    0xfa15effaUL, 0x59ebb259UL, 0x47c98e47UL, 0xf00bfbf0UL,
    0xadec41adUL, 0xd467b3d4UL, 0xa2fd5fa2UL, 0xafea45afUL,
    0x9cbf239cUL, 0xa4f753a4UL, 0x7296e472UL, 0xc05b9bc0UL,
    0xb7c275b7UL, 0xfd1ce1fdUL, 0x93ae3d93UL, 0x266a4c26UL,
    0x365a6c36UL, 0x3f417e3fUL, 0xf702f5f7UL, 0xcc4f83ccUL,
    0x345c6834UL, 0xa5f451a5UL, 0xe534d1e5UL, 0xf108f9f1UL,
    0x7193e271UL, 0xd873abd8UL, 0x31536231UL, 0x153f2a15UL,
    0x040c0804UL, 0xc75295c7UL, 0x23654623UL, 0xc35e9dc3UL,
    0x18283018UL, 0x96a13796UL, 0x050f0a05UL, 0x9ab52f9aUL,
    0x07090e07UL, 0x12362412UL, 0x809b1b80UL, 0xe23ddfe2UL,
    0xeb26cdebUL, 0x27694e27UL, 0xb2cd7fb2UL, 0x759fea75UL,
    0x091b1209UL, 0x839e1d83UL, 0x2c74582cUL, 0x1a2e341aUL,
    0x1b2d361bUL, 0x6eb2dc6eUL, 0x5aeeb45aUL, 0xa0fb5ba0UL,
    0x52f6a452UL, 0x3b4d763bUL, 0xd661b7d6UL, 0xb3ce7db3UL,
    0x297b5229UL, 0xe33edde3UL, 0x2f715e2fUL, 0x84971384UL,
    0x53f5a653UL, 0xd168b9d1UL, 0x00000000UL, 0xed2cc1edUL,
    0x20604020UL, 0xfc1fe3fcUL, 0xb1c879b1UL, 0x5bedb65bUL,
    0x6abed46aUL, 0xcb468dcbUL, 0xbed967beUL, 0x394b7239UL,
    0x4ade944aUL, 0x4cd4984cUL, 0x58e8b058UL, 0xcf4a85cfUL,
    0xd06bbbd0UL, 0xef2ac5efUL, 0xaae54faaUL, 0xfb16edfbUL,
    0x43c58643UL, 0x4dd79a4dUL, 0x33556633UL, 0x85941185UL,
    0x45cf8a45UL, 0xf910e9f9UL, 0x02060402UL, 0x7f81fe7fUL,
    0x50f0a050UL, 0x3c44783cUL, 0x9fba259fUL, 0xa8e34ba8UL,
    0x51f3a251UL, 0xa3fe5da3UL, 0x40c08040UL, 0x8f8a058fUL,
    0x92ad3f92UL, 0x9dbc219dUL, 0x38487038UL, 0xf504f1f5UL,
    0xbcdf63bcUL, 0xb6c177b6UL, 0xda75afdaUL, 0x21634221UL,
    0x10302010UL, 0xff1ae5ffUL, 0xf30efdf3UL, 0xd26dbfd2UL,
    0xcd4c81cdUL, 0x0c14180cUL, 0x13352613UL, 0xec2fc3ecUL,
    0x5fe1be5fUL, 0x97a23597UL, 0x44cc8844UL, 0x17392e17UL,
    0xc45793c4UL, 0xa7f255a7UL, 0x7e82fc7eUL, 0x3d477a3dUL,
    0x64acc864UL, 0x5de7ba5dUL, 0x192b3219UL, 0x7395e673UL,
    0x60a0c060UL, 0x81981981UL, 0x4fd19e4fUL, 0xdc7fa3dcUL,
    0x22664422UL, 0x2a7e542aUL, 0x90ab3b90UL, 0x88830b88UL,
    0x46ca8c46UL, 0xee29c7eeUL, 0xb8d36bb8UL, 0x143c2814UL,
    0xde79a7deUL, 0x5ee2bc5eUL, 0x0b1d160bUL, 0xdb76addbUL,
    0xe03bdbe0UL, 0x32566432UL, 0x3a4e743aUL, 0x0a1e140aUL,
    0x49db9249UL, 0x060a0c06UL, 0x246c4824UL, 0x5ce4b85cUL,
    0xc25d9fc2UL, 0xd36ebdd3UL, 0xacef43acUL, 0x62a6c462UL,
    0x91a83991UL, 0x95a43195UL, 0xe437d3e4UL, 0x798bf279UL,
    0xe732d5e7UL, 0xc8438bc8UL, 0x37596e37UL, 0x6db7da6dUL,
    0x8d8c018dUL, 0xd564b1d5UL, 0x4ed29c4eUL, 0xa9e049a9UL,
    0x6cb4d86cUL, 0x56faac56UL, 0xf407f3f4UL, 0xea25cfeaUL,
    0x65afca65UL, 0x7a8ef47aUL, 0xaee947aeUL, 0x08181008UL,
    0xbad56fbaUL, 0x7888f078UL, 0x256f4a25UL, 0x2e725c2eUL,
    0x1c24381cUL, 0xa6f157a6UL, 0xb4c773b4UL, 0xc65197c6UL,
    0xe823cbe8UL, 0xdd7ca1ddUL, 0x749ce874UL, 0x1f213e1fUL,
    0x4bdd964bUL, 0xbddc61bdUL, 0x8b860d8bUL, 0x8a850f8aUL,
    0x7090e070UL, 0x3e427c3eUL, 0xb5c471b5UL, 0x66aacc66UL,
    0x48d89048UL, 0x03050603UL, 0xf601f7f6UL, 0x0e121c0eUL,
    0x61a3c261UL, 0x355f6a35UL, 0x57f9ae57UL, 0xb9d069b9UL,
    0x86911786UL, 0xc15899c1UL, 0x1d273a1dUL, 0x9eb9279eUL,
    0xe138d9e1UL, 0xf813ebf8UL, 0x98b32b98UL, 0x11332211UL,
    0x69bbd269UL, 0xd970a9d9UL, 0x8e89078eUL, 0x94a73394UL,
    0x9bb62d9bUL, 0x1e223c1eUL, 0x87921587UL, 0xe920c9e9UL,
    0xce4987ceUL, 0x55ffaa55UL, 0x28785028UL, 0xdf7aa5dfUL,
    0x8c8f038cUL, 0xa1f859a1UL, 0x89800989UL, 0x0d171a0dUL,
    0xbfda65bfUL, 0xe631d7e6UL, 0x42c68442UL, 0x68b8d068UL,
    0x41c38241UL, 0x99b02999UL, 0x2d775a2dUL, 0x0f111e0fUL,
    0xb0cb7bb0UL, 0x54fca854UL, 0xbbd66dbbUL, 0x163a2c16UL,
};
static const uint32_t TE3[256] = {
    
    0x6363a5c6UL, 0x7c7c84f8UL, 0x777799eeUL, 0x7b7b8df6UL,
    0xf2f20dffUL, 0x6b6bbdd6UL, 0x6f6fb1deUL, 0xc5c55491UL,
    0x30305060UL, 0x01010302UL, 0x6767a9ceUL, 0x2b2b7d56UL,
    0xfefe19e7UL, 0xd7d762b5UL, 0xababe64dUL, 0x76769aecUL,
    0xcaca458fUL, 0x82829d1fUL, 0xc9c94089UL, 0x7d7d87faUL,
    0xfafa15efUL, 0x5959ebb2UL, 0x4747c98eUL, 0xf0f00bfbUL,
    0xadadec41UL, 0xd4d467b3UL, 0xa2a2fd5fUL, 0xafafea45UL,
    0x9c9cbf23UL, 0xa4a4f753UL, 0x727296e4UL, 0xc0c05b9bUL,
    0xb7b7c275UL, 0xfdfd1ce1UL, 0x9393ae3dUL, 0x26266a4cUL,
    0x36365a6cUL, 0x3f3f417eUL, 0xf7f702f5UL, 0xcccc4f83UL,
    0x34345c68UL, 0xa5a5f451UL, 0xe5e534d1UL, 0xf1f108f9UL,
    0x717193e2UL, 0xd8d873abUL, 0x31315362UL, 0x15153f2aUL,
    0x04040c08UL, 0xc7c75295UL, 0x23236546UL, 0xc3c35e9dUL,
    0x18182830UL, 0x9696a137UL, 0x05050f0aUL, 0x9a9ab52fUL,
    0x0707090eUL, 0x12123624UL, 0x80809b1bUL, 0xe2e23ddfUL,
    0xebeb26cdUL, 0x2727694eUL, 0xb2b2cd7fUL, 0x75759feaUL,
    0x09091b12UL, 0x83839e1dUL, 0x2c2c7458UL, 0x1a1a2e34UL,
    0x1b1b2d36UL, 0x6e6eb2dcUL, 0x5a5aeeb4UL, 0xa0a0fb5bUL,
    0x5252f6a4UL, 0x3b3b4d76UL, 0xd6d661b7UL, 0xb3b3ce7dUL,
    0x29297b52UL, 0xe3e33eddUL, 0x2f2f715eUL, 0x84849713UL,
    0x5353f5a6UL, 0xd1d168b9UL, 0x00000000UL, 0xeded2cc1UL,
    0x20206040UL, 0xfcfc1fe3UL, 0xb1b1c879UL, 0x5b5bedb6UL,
    0x6a6abed4UL, 0xcbcb468dUL, 0xbebed967UL, 0x39394b72UL,
    0x4a4ade94UL, 0x4c4cd498UL, 0x5858e8b0UL, 0xcfcf4a85UL,
    0xd0d06bbbUL, 0xefef2ac5UL, 0xaaaae54fUL, 0xfbfb16edUL,
    0x4343c586UL, 0x4d4dd79aUL, 0x33335566UL, 0x85859411UL,
    0x4545cf8aUL, 0xf9f910e9UL, 0x02020604UL, 0x7f7f81feUL,
    0x5050f0a0UL, 0x3c3c4478UL, 0x9f9fba25UL, 0xa8a8e34bUL,
    0x5151f3a2UL, 0xa3a3fe5dUL, 0x4040c080UL, 0x8f8f8a05UL,
    0x9292ad3fUL, 0x9d9dbc21UL, 0x38384870UL, 0xf5f504f1UL,
    0xbcbcdf63UL, 0xb6b6c177UL, 0xdada75afUL, 0x21216342UL,
    0x10103020UL, 0xffff1ae5UL, 0xf3f30efdUL, 0xd2d26dbfUL,
    0xcdcd4c81UL, 0x0c0c1418UL, 0x13133526UL, 0xecec2fc3UL,
    0x5f5fe1beUL, 0x9797a235UL, 0x4444cc88UL, 0x1717392eUL,
    0xc4c45793UL, 0xa7a7f255UL, 0x7e7e82fcUL, 0x3d3d477aUL,
    0x6464acc8UL, 0x5d5de7baUL, 0x19192b32UL, 0x737395e6UL,
    0x6060a0c0UL, 0x81819819UL, 0x4f4fd19eUL, 0xdcdc7fa3UL,
    0x22226644UL, 0x2a2a7e54UL, 0x9090ab3bUL, 0x8888830bUL,
    0x4646ca8cUL, 0xeeee29c7UL, 0xb8b8d36bUL, 0x14143c28UL,
    0xdede79a7UL, 0x5e5ee2bcUL, 0x0b0b1d16UL, 0xdbdb76adUL,
    0xe0e03bdbUL, 0x32325664UL, 0x3a3a4e74UL, 0x0a0a1e14UL,
    0x4949db92UL, 0x06060a0cUL, 0x24246c48UL, 0x5c5ce4b8UL,
    0xc2c25d9fUL, 0xd3d36ebdUL, 0xacacef43UL, 0x6262a6c4UL,
    0x9191a839UL, 0x9595a431UL, 0xe4e437d3UL, 0x79798bf2UL,
    0xe7e732d5UL, 0xc8c8438bUL, 0x3737596eUL, 0x6d6db7daUL,
    0x8d8d8c01UL, 0xd5d564b1UL, 0x4e4ed29cUL, 0xa9a9e049UL,
    0x6c6cb4d8UL, 0x5656faacUL, 0xf4f407f3UL, 0xeaea25cfUL,
    0x6565afcaUL, 0x7a7a8ef4UL, 0xaeaee947UL, 0x08081810UL,
    0xbabad56fUL, 0x787888f0UL, 0x25256f4aUL, 0x2e2e725cUL,
    0x1c1c2438UL, 0xa6a6f157UL, 0xb4b4c773UL, 0xc6c65197UL,
    0xe8e823cbUL, 0xdddd7ca1UL, 0x74749ce8UL, 0x1f1f213eUL,
    0x4b4bdd96UL, 0xbdbddc61UL, 0x8b8b860dUL, 0x8a8a850fUL,
    0x707090e0UL, 0x3e3e427cUL, 0xb5b5c471UL, 0x6666aaccUL,
    0x4848d890UL, 0x03030506UL, 0xf6f601f7UL, 0x0e0e121cUL,
    0x6161a3c2UL, 0x35355f6aUL, 0x5757f9aeUL, 0xb9b9d069UL,
    0x86869117UL, 0xc1c15899UL, 0x1d1d273aUL, 0x9e9eb927UL,
    0xe1e138d9UL, 0xf8f813ebUL, 0x9898b32bUL, 0x11113322UL,
    0x6969bbd2UL, 0xd9d970a9UL, 0x8e8e8907UL, 0x9494a733UL,
    0x9b9bb62dUL, 0x1e1e223cUL, 0x87879215UL, 0xe9e920c9UL,
    0xcece4987UL, 0x5555ffaaUL, 0x28287850UL, 0xdfdf7aa5UL,
    0x8c8c8f03UL, 0xa1a1f859UL, 0x89898009UL, 0x0d0d171aUL,
    0xbfbfda65UL, 0xe6e631d7UL, 0x4242c684UL, 0x6868b8d0UL,
    0x4141c382UL, 0x9999b029UL, 0x2d2d775aUL, 0x0f0f111eUL,
    0xb0b0cb7bUL, 0x5454fca8UL, 0xbbbbd66dUL, 0x16163a2cUL,
};

#ifndef PELI_TAB
static const uint32_t Te4_0[] = {
    0x00000063UL, 0x0000007cUL, 0x00000077UL, 0x0000007bUL, 0x000000f2UL, 0x0000006bUL, 0x0000006fUL, 0x000000c5UL, 
    0x00000030UL, 0x00000001UL, 0x00000067UL, 0x0000002bUL, 0x000000feUL, 0x000000d7UL, 0x000000abUL, 0x00000076UL, 
    0x000000caUL, 0x00000082UL, 0x000000c9UL, 0x0000007dUL, 0x000000faUL, 0x00000059UL, 0x00000047UL, 0x000000f0UL, 
    0x000000adUL, 0x000000d4UL, 0x000000a2UL, 0x000000afUL, 0x0000009cUL, 0x000000a4UL, 0x00000072UL, 0x000000c0UL, 
    0x000000b7UL, 0x000000fdUL, 0x00000093UL, 0x00000026UL, 0x00000036UL, 0x0000003fUL, 0x000000f7UL, 0x000000ccUL, 
    0x00000034UL, 0x000000a5UL, 0x000000e5UL, 0x000000f1UL, 0x00000071UL, 0x000000d8UL, 0x00000031UL, 0x00000015UL, 
    0x00000004UL, 0x000000c7UL, 0x00000023UL, 0x000000c3UL, 0x00000018UL, 0x00000096UL, 0x00000005UL, 0x0000009aUL, 
    0x00000007UL, 0x00000012UL, 0x00000080UL, 0x000000e2UL, 0x000000ebUL, 0x00000027UL, 0x000000b2UL, 0x00000075UL, 
    0x00000009UL, 0x00000083UL, 0x0000002cUL, 0x0000001aUL, 0x0000001bUL, 0x0000006eUL, 0x0000005aUL, 0x000000a0UL, 
    0x00000052UL, 0x0000003bUL, 0x000000d6UL, 0x000000b3UL, 0x00000029UL, 0x000000e3UL, 0x0000002fUL, 0x00000084UL, 
    0x00000053UL, 0x000000d1UL, 0x00000000UL, 0x000000edUL, 0x00000020UL, 0x000000fcUL, 0x000000b1UL, 0x0000005bUL, 
    0x0000006aUL, 0x000000cbUL, 0x000000beUL, 0x00000039UL, 0x0000004aUL, 0x0000004cUL, 0x00000058UL, 0x000000cfUL, 
    0x000000d0UL, 0x000000efUL, 0x000000aaUL, 0x000000fbUL, 0x00000043UL, 0x0000004dUL, 0x00000033UL, 0x00000085UL, 
    0x00000045UL, 0x000000f9UL, 0x00000002UL, 0x0000007fUL, 0x00000050UL, 0x0000003cUL, 0x0000009fUL, 0x000000a8UL, 
    0x00000051UL, 0x000000a3UL, 0x00000040UL, 0x0000008fUL, 0x00000092UL, 0x0000009dUL, 0x00000038UL, 0x000000f5UL, 
    0x000000bcUL, 0x000000b6UL, 0x000000daUL, 0x00000021UL, 0x00000010UL, 0x000000ffUL, 0x000000f3UL, 0x000000d2UL, 
    0x000000cdUL, 0x0000000cUL, 0x00000013UL, 0x000000ecUL, 0x0000005fUL, 0x00000097UL, 0x00000044UL, 0x00000017UL, 
    0x000000c4UL, 0x000000a7UL, 0x0000007eUL, 0x0000003dUL, 0x00000064UL, 0x0000005dUL, 0x00000019UL, 0x00000073UL, 
    0x00000060UL, 0x00000081UL, 0x0000004fUL, 0x000000dcUL, 0x00000022UL, 0x0000002aUL, 0x00000090UL, 0x00000088UL, 
    0x00000046UL, 0x000000eeUL, 0x000000b8UL, 0x00000014UL, 0x000000deUL, 0x0000005eUL, 0x0000000bUL, 0x000000dbUL, 
    0x000000e0UL, 0x00000032UL, 0x0000003aUL, 0x0000000aUL, 0x00000049UL, 0x00000006UL, 0x00000024UL, 0x0000005cUL, 
    0x000000c2UL, 0x000000d3UL, 0x000000acUL, 0x00000062UL, 0x00000091UL, 0x00000095UL, 0x000000e4UL, 0x00000079UL, 
    0x000000e7UL, 0x000000c8UL, 0x00000037UL, 0x0000006dUL, 0x0000008dUL, 0x000000d5UL, 0x0000004eUL, 0x000000a9UL, 
    0x0000006cUL, 0x00000056UL, 0x000000f4UL, 0x000000eaUL, 0x00000065UL, 0x0000007aUL, 0x000000aeUL, 0x00000008UL, 
    0x000000baUL, 0x00000078UL, 0x00000025UL, 0x0000002eUL, 0x0000001cUL, 0x000000a6UL, 0x000000b4UL, 0x000000c6UL, 
    0x000000e8UL, 0x000000ddUL, 0x00000074UL, 0x0000001fUL, 0x0000004bUL, 0x000000bdUL, 0x0000008bUL, 0x0000008aUL, 
    0x00000070UL, 0x0000003eUL, 0x000000b5UL, 0x00000066UL, 0x00000048UL, 0x00000003UL, 0x000000f6UL, 0x0000000eUL, 
    0x00000061UL, 0x00000035UL, 0x00000057UL, 0x000000b9UL, 0x00000086UL, 0x000000c1UL, 0x0000001dUL, 0x0000009eUL, 
    0x000000e1UL, 0x000000f8UL, 0x00000098UL, 0x00000011UL, 0x00000069UL, 0x000000d9UL, 0x0000008eUL, 0x00000094UL, 
    0x0000009bUL, 0x0000001eUL, 0x00000087UL, 0x000000e9UL, 0x000000ceUL, 0x00000055UL, 0x00000028UL, 0x000000dfUL, 
    0x0000008cUL, 0x000000a1UL, 0x00000089UL, 0x0000000dUL, 0x000000bfUL, 0x000000e6UL, 0x00000042UL, 0x00000068UL, 
    0x00000041UL, 0x00000099UL, 0x0000002dUL, 0x0000000fUL, 0x000000b0UL, 0x00000054UL, 0x000000bbUL, 0x00000016UL
};

static const uint32_t Te4_1[] = {
    0x00006300UL, 0x00007c00UL, 0x00007700UL, 0x00007b00UL, 0x0000f200UL, 0x00006b00UL, 0x00006f00UL, 0x0000c500UL, 
    0x00003000UL, 0x00000100UL, 0x00006700UL, 0x00002b00UL, 0x0000fe00UL, 0x0000d700UL, 0x0000ab00UL, 0x00007600UL, 
    0x0000ca00UL, 0x00008200UL, 0x0000c900UL, 0x00007d00UL, 0x0000fa00UL, 0x00005900UL, 0x00004700UL, 0x0000f000UL, 
    0x0000ad00UL, 0x0000d400UL, 0x0000a200UL, 0x0000af00UL, 0x00009c00UL, 0x0000a400UL, 0x00007200UL, 0x0000c000UL, 
    0x0000b700UL, 0x0000fd00UL, 0x00009300UL, 0x00002600UL, 0x00003600UL, 0x00003f00UL, 0x0000f700UL, 0x0000cc00UL, 
    0x00003400UL, 0x0000a500UL, 0x0000e500UL, 0x0000f100UL, 0x00007100UL, 0x0000d800UL, 0x00003100UL, 0x00001500UL, 
    0x00000400UL, 0x0000c700UL, 0x00002300UL, 0x0000c300UL, 0x00001800UL, 0x00009600UL, 0x00000500UL, 0x00009a00UL, 
    0x00000700UL, 0x00001200UL, 0x00008000UL, 0x0000e200UL, 0x0000eb00UL, 0x00002700UL, 0x0000b200UL, 0x00007500UL, 
    0x00000900UL, 0x00008300UL, 0x00002c00UL, 0x00001a00UL, 0x00001b00UL, 0x00006e00UL, 0x00005a00UL, 0x0000a000UL, 
    0x00005200UL, 0x00003b00UL, 0x0000d600UL, 0x0000b300UL, 0x00002900UL, 0x0000e300UL, 0x00002f00UL, 0x00008400UL, 
    0x00005300UL, 0x0000d100UL, 0x00000000UL, 0x0000ed00UL, 0x00002000UL, 0x0000fc00UL, 0x0000b100UL, 0x00005b00UL, 
    0x00006a00UL, 0x0000cb00UL, 0x0000be00UL, 0x00003900UL, 0x00004a00UL, 0x00004c00UL, 0x00005800UL, 0x0000cf00UL, 
    0x0000d000UL, 0x0000ef00UL, 0x0000aa00UL, 0x0000fb00UL, 0x00004300UL, 0x00004d00UL, 0x00003300UL, 0x00008500UL, 
    0x00004500UL, 0x0000f900UL, 0x00000200UL, 0x00007f00UL, 0x00005000UL, 0x00003c00UL, 0x00009f00UL, 0x0000a800UL, 
    0x00005100UL, 0x0000a300UL, 0x00004000UL, 0x00008f00UL, 0x00009200UL, 0x00009d00UL, 0x00003800UL, 0x0000f500UL, 
    0x0000bc00UL, 0x0000b600UL, 0x0000da00UL, 0x00002100UL, 0x00001000UL, 0x0000ff00UL, 0x0000f300UL, 0x0000d200UL, 
    0x0000cd00UL, 0x00000c00UL, 0x00001300UL, 0x0000ec00UL, 0x00005f00UL, 0x00009700UL, 0x00004400UL, 0x00001700UL, 
    0x0000c400UL, 0x0000a700UL, 0x00007e00UL, 0x00003d00UL, 0x00006400UL, 0x00005d00UL, 0x00001900UL, 0x00007300UL, 
    0x00006000UL, 0x00008100UL, 0x00004f00UL, 0x0000dc00UL, 0x00002200UL, 0x00002a00UL, 0x00009000UL, 0x00008800UL, 
    0x00004600UL, 0x0000ee00UL, 0x0000b800UL, 0x00001400UL, 0x0000de00UL, 0x00005e00UL, 0x00000b00UL, 0x0000db00UL, 
    0x0000e000UL, 0x00003200UL, 0x00003a00UL, 0x00000a00UL, 0x00004900UL, 0x00000600UL, 0x00002400UL, 0x00005c00UL, 
    0x0000c200UL, 0x0000d300UL, 0x0000ac00UL, 0x00006200UL, 0x00009100UL, 0x00009500UL, 0x0000e400UL, 0x00007900UL, 
    0x0000e700UL, 0x0000c800UL, 0x00003700UL, 0x00006d00UL, 0x00008d00UL, 0x0000d500UL, 0x00004e00UL, 0x0000a900UL, 
    0x00006c00UL, 0x00005600UL, 0x0000f400UL, 0x0000ea00UL, 0x00006500UL, 0x00007a00UL, 0x0000ae00UL, 0x00000800UL, 
    0x0000ba00UL, 0x00007800UL, 0x00002500UL, 0x00002e00UL, 0x00001c00UL, 0x0000a600UL, 0x0000b400UL, 0x0000c600UL, 
    0x0000e800UL, 0x0000dd00UL, 0x00007400UL, 0x00001f00UL, 0x00004b00UL, 0x0000bd00UL, 0x00008b00UL, 0x00008a00UL, 
    0x00007000UL, 0x00003e00UL, 0x0000b500UL, 0x00006600UL, 0x00004800UL, 0x00000300UL, 0x0000f600UL, 0x00000e00UL, 
    0x00006100UL, 0x00003500UL, 0x00005700UL, 0x0000b900UL, 0x00008600UL, 0x0000c100UL, 0x00001d00UL, 0x00009e00UL, 
    0x0000e100UL, 0x0000f800UL, 0x00009800UL, 0x00001100UL, 0x00006900UL, 0x0000d900UL, 0x00008e00UL, 0x00009400UL, 
    0x00009b00UL, 0x00001e00UL, 0x00008700UL, 0x0000e900UL, 0x0000ce00UL, 0x00005500UL, 0x00002800UL, 0x0000df00UL, 
    0x00008c00UL, 0x0000a100UL, 0x00008900UL, 0x00000d00UL, 0x0000bf00UL, 0x0000e600UL, 0x00004200UL, 0x00006800UL, 
    0x00004100UL, 0x00009900UL, 0x00002d00UL, 0x00000f00UL, 0x0000b000UL, 0x00005400UL, 0x0000bb00UL, 0x00001600UL
};

static const uint32_t Te4_2[] = {
    0x00630000UL, 0x007c0000UL, 0x00770000UL, 0x007b0000UL, 0x00f20000UL, 0x006b0000UL, 0x006f0000UL, 0x00c50000UL, 
    0x00300000UL, 0x00010000UL, 0x00670000UL, 0x002b0000UL, 0x00fe0000UL, 0x00d70000UL, 0x00ab0000UL, 0x00760000UL, 
    0x00ca0000UL, 0x00820000UL, 0x00c90000UL, 0x007d0000UL, 0x00fa0000UL, 0x00590000UL, 0x00470000UL, 0x00f00000UL, 
    0x00ad0000UL, 0x00d40000UL, 0x00a20000UL, 0x00af0000UL, 0x009c0000UL, 0x00a40000UL, 0x00720000UL, 0x00c00000UL, 
    0x00b70000UL, 0x00fd0000UL, 0x00930000UL, 0x00260000UL, 0x00360000UL, 0x003f0000UL, 0x00f70000UL, 0x00cc0000UL, 
    0x00340000UL, 0x00a50000UL, 0x00e50000UL, 0x00f10000UL, 0x00710000UL, 0x00d80000UL, 0x00310000UL, 0x00150000UL, 
    0x00040000UL, 0x00c70000UL, 0x00230000UL, 0x00c30000UL, 0x00180000UL, 0x00960000UL, 0x00050000UL, 0x009a0000UL, 
    0x00070000UL, 0x00120000UL, 0x00800000UL, 0x00e20000UL, 0x00eb0000UL, 0x00270000UL, 0x00b20000UL, 0x00750000UL, 
    0x00090000UL, 0x00830000UL, 0x002c0000UL, 0x001a0000UL, 0x001b0000UL, 0x006e0000UL, 0x005a0000UL, 0x00a00000UL, 
    0x00520000UL, 0x003b0000UL, 0x00d60000UL, 0x00b30000UL, 0x00290000UL, 0x00e30000UL, 0x002f0000UL, 0x00840000UL, 
    0x00530000UL, 0x00d10000UL, 0x00000000UL, 0x00ed0000UL, 0x00200000UL, 0x00fc0000UL, 0x00b10000UL, 0x005b0000UL, 
    0x006a0000UL, 0x00cb0000UL, 0x00be0000UL, 0x00390000UL, 0x004a0000UL, 0x004c0000UL, 0x00580000UL, 0x00cf0000UL, 
    0x00d00000UL, 0x00ef0000UL, 0x00aa0000UL, 0x00fb0000UL, 0x00430000UL, 0x004d0000UL, 0x00330000UL, 0x00850000UL, 
    0x00450000UL, 0x00f90000UL, 0x00020000UL, 0x007f0000UL, 0x00500000UL, 0x003c0000UL, 0x009f0000UL, 0x00a80000UL, 
    0x00510000UL, 0x00a30000UL, 0x00400000UL, 0x008f0000UL, 0x00920000UL, 0x009d0000UL, 0x00380000UL, 0x00f50000UL, 
    0x00bc0000UL, 0x00b60000UL, 0x00da0000UL, 0x00210000UL, 0x00100000UL, 0x00ff0000UL, 0x00f30000UL, 0x00d20000UL, 
    0x00cd0000UL, 0x000c0000UL, 0x00130000UL, 0x00ec0000UL, 0x005f0000UL, 0x00970000UL, 0x00440000UL, 0x00170000UL, 
    0x00c40000UL, 0x00a70000UL, 0x007e0000UL, 0x003d0000UL, 0x00640000UL, 0x005d0000UL, 0x00190000UL, 0x00730000UL, 
    0x00600000UL, 0x00810000UL, 0x004f0000UL, 0x00dc0000UL, 0x00220000UL, 0x002a0000UL, 0x00900000UL, 0x00880000UL, 
    0x00460000UL, 0x00ee0000UL, 0x00b80000UL, 0x00140000UL, 0x00de0000UL, 0x005e0000UL, 0x000b0000UL, 0x00db0000UL, 
    0x00e00000UL, 0x00320000UL, 0x003a0000UL, 0x000a0000UL, 0x00490000UL, 0x00060000UL, 0x00240000UL, 0x005c0000UL, 
    0x00c20000UL, 0x00d30000UL, 0x00ac0000UL, 0x00620000UL, 0x00910000UL, 0x00950000UL, 0x00e40000UL, 0x00790000UL, 
    0x00e70000UL, 0x00c80000UL, 0x00370000UL, 0x006d0000UL, 0x008d0000UL, 0x00d50000UL, 0x004e0000UL, 0x00a90000UL, 
    0x006c0000UL, 0x00560000UL, 0x00f40000UL, 0x00ea0000UL, 0x00650000UL, 0x007a0000UL, 0x00ae0000UL, 0x00080000UL, 
    0x00ba0000UL, 0x00780000UL, 0x00250000UL, 0x002e0000UL, 0x001c0000UL, 0x00a60000UL, 0x00b40000UL, 0x00c60000UL, 
    0x00e80000UL, 0x00dd0000UL, 0x00740000UL, 0x001f0000UL, 0x004b0000UL, 0x00bd0000UL, 0x008b0000UL, 0x008a0000UL, 
    0x00700000UL, 0x003e0000UL, 0x00b50000UL, 0x00660000UL, 0x00480000UL, 0x00030000UL, 0x00f60000UL, 0x000e0000UL, 
    0x00610000UL, 0x00350000UL, 0x00570000UL, 0x00b90000UL, 0x00860000UL, 0x00c10000UL, 0x001d0000UL, 0x009e0000UL, 
    0x00e10000UL, 0x00f80000UL, 0x00980000UL, 0x00110000UL, 0x00690000UL, 0x00d90000UL, 0x008e0000UL, 0x00940000UL, 
    0x009b0000UL, 0x001e0000UL, 0x00870000UL, 0x00e90000UL, 0x00ce0000UL, 0x00550000UL, 0x00280000UL, 0x00df0000UL, 
    0x008c0000UL, 0x00a10000UL, 0x00890000UL, 0x000d0000UL, 0x00bf0000UL, 0x00e60000UL, 0x00420000UL, 0x00680000UL, 
    0x00410000UL, 0x00990000UL, 0x002d0000UL, 0x000f0000UL, 0x00b00000UL, 0x00540000UL, 0x00bb0000UL, 0x00160000UL
};

static const uint32_t Te4_3[] = {
    0x63000000UL, 0x7c000000UL, 0x77000000UL, 0x7b000000UL, 0xf2000000UL, 0x6b000000UL, 0x6f000000UL, 0xc5000000UL, 
    0x30000000UL, 0x01000000UL, 0x67000000UL, 0x2b000000UL, 0xfe000000UL, 0xd7000000UL, 0xab000000UL, 0x76000000UL, 
    0xca000000UL, 0x82000000UL, 0xc9000000UL, 0x7d000000UL, 0xfa000000UL, 0x59000000UL, 0x47000000UL, 0xf0000000UL, 
    0xad000000UL, 0xd4000000UL, 0xa2000000UL, 0xaf000000UL, 0x9c000000UL, 0xa4000000UL, 0x72000000UL, 0xc0000000UL, 
    0xb7000000UL, 0xfd000000UL, 0x93000000UL, 0x26000000UL, 0x36000000UL, 0x3f000000UL, 0xf7000000UL, 0xcc000000UL, 
    0x34000000UL, 0xa5000000UL, 0xe5000000UL, 0xf1000000UL, 0x71000000UL, 0xd8000000UL, 0x31000000UL, 0x15000000UL, 
    0x04000000UL, 0xc7000000UL, 0x23000000UL, 0xc3000000UL, 0x18000000UL, 0x96000000UL, 0x05000000UL, 0x9a000000UL, 
    0x07000000UL, 0x12000000UL, 0x80000000UL, 0xe2000000UL, 0xeb000000UL, 0x27000000UL, 0xb2000000UL, 0x75000000UL, 
    0x09000000UL, 0x83000000UL, 0x2c000000UL, 0x1a000000UL, 0x1b000000UL, 0x6e000000UL, 0x5a000000UL, 0xa0000000UL, 
    0x52000000UL, 0x3b000000UL, 0xd6000000UL, 0xb3000000UL, 0x29000000UL, 0xe3000000UL, 0x2f000000UL, 0x84000000UL, 
    0x53000000UL, 0xd1000000UL, 0x00000000UL, 0xed000000UL, 0x20000000UL, 0xfc000000UL, 0xb1000000UL, 0x5b000000UL, 
    0x6a000000UL, 0xcb000000UL, 0xbe000000UL, 0x39000000UL, 0x4a000000UL, 0x4c000000UL, 0x58000000UL, 0xcf000000UL, 
    0xd0000000UL, 0xef000000UL, 0xaa000000UL, 0xfb000000UL, 0x43000000UL, 0x4d000000UL, 0x33000000UL, 0x85000000UL, 
    0x45000000UL, 0xf9000000UL, 0x02000000UL, 0x7f000000UL, 0x50000000UL, 0x3c000000UL, 0x9f000000UL, 0xa8000000UL, 
    0x51000000UL, 0xa3000000UL, 0x40000000UL, 0x8f000000UL, 0x92000000UL, 0x9d000000UL, 0x38000000UL, 0xf5000000UL, 
    0xbc000000UL, 0xb6000000UL, 0xda000000UL, 0x21000000UL, 0x10000000UL, 0xff000000UL, 0xf3000000UL, 0xd2000000UL, 
    0xcd000000UL, 0x0c000000UL, 0x13000000UL, 0xec000000UL, 0x5f000000UL, 0x97000000UL, 0x44000000UL, 0x17000000UL, 
    0xc4000000UL, 0xa7000000UL, 0x7e000000UL, 0x3d000000UL, 0x64000000UL, 0x5d000000UL, 0x19000000UL, 0x73000000UL, 
    0x60000000UL, 0x81000000UL, 0x4f000000UL, 0xdc000000UL, 0x22000000UL, 0x2a000000UL, 0x90000000UL, 0x88000000UL, 
    0x46000000UL, 0xee000000UL, 0xb8000000UL, 0x14000000UL, 0xde000000UL, 0x5e000000UL, 0x0b000000UL, 0xdb000000UL, 
    0xe0000000UL, 0x32000000UL, 0x3a000000UL, 0x0a000000UL, 0x49000000UL, 0x06000000UL, 0x24000000UL, 0x5c000000UL, 
    0xc2000000UL, 0xd3000000UL, 0xac000000UL, 0x62000000UL, 0x91000000UL, 0x95000000UL, 0xe4000000UL, 0x79000000UL, 
    0xe7000000UL, 0xc8000000UL, 0x37000000UL, 0x6d000000UL, 0x8d000000UL, 0xd5000000UL, 0x4e000000UL, 0xa9000000UL, 
    0x6c000000UL, 0x56000000UL, 0xf4000000UL, 0xea000000UL, 0x65000000UL, 0x7a000000UL, 0xae000000UL, 0x08000000UL, 
    0xba000000UL, 0x78000000UL, 0x25000000UL, 0x2e000000UL, 0x1c000000UL, 0xa6000000UL, 0xb4000000UL, 0xc6000000UL, 
    0xe8000000UL, 0xdd000000UL, 0x74000000UL, 0x1f000000UL, 0x4b000000UL, 0xbd000000UL, 0x8b000000UL, 0x8a000000UL, 
    0x70000000UL, 0x3e000000UL, 0xb5000000UL, 0x66000000UL, 0x48000000UL, 0x03000000UL, 0xf6000000UL, 0x0e000000UL, 
    0x61000000UL, 0x35000000UL, 0x57000000UL, 0xb9000000UL, 0x86000000UL, 0xc1000000UL, 0x1d000000UL, 0x9e000000UL, 
    0xe1000000UL, 0xf8000000UL, 0x98000000UL, 0x11000000UL, 0x69000000UL, 0xd9000000UL, 0x8e000000UL, 0x94000000UL, 
    0x9b000000UL, 0x1e000000UL, 0x87000000UL, 0xe9000000UL, 0xce000000UL, 0x55000000UL, 0x28000000UL, 0xdf000000UL, 
    0x8c000000UL, 0xa1000000UL, 0x89000000UL, 0x0d000000UL, 0xbf000000UL, 0xe6000000UL, 0x42000000UL, 0x68000000UL, 
    0x41000000UL, 0x99000000UL, 0x2d000000UL, 0x0f000000UL, 0xb0000000UL, 0x54000000UL, 0xbb000000UL, 0x16000000UL
};
#endif /* pelimac */

#ifndef ENCRYPT_ONLY

static const uint32_t TD1[256] = {
    0x5051f4a7UL, 0x537e4165UL, 0xc31a17a4UL, 0x963a275eUL,
    0xcb3bab6bUL, 0xf11f9d45UL, 0xabacfa58UL, 0x934be303UL,
    0x552030faUL, 0xf6ad766dUL, 0x9188cc76UL, 0x25f5024cUL,
    0xfc4fe5d7UL, 0xd7c52acbUL, 0x80263544UL, 0x8fb562a3UL,
    0x49deb15aUL, 0x6725ba1bUL, 0x9845ea0eUL, 0xe15dfec0UL,
    0x02c32f75UL, 0x12814cf0UL, 0xa38d4697UL, 0xc66bd3f9UL,
    0xe7038f5fUL, 0x9515929cUL, 0xebbf6d7aUL, 0xda955259UL,
    0x2dd4be83UL, 0xd3587421UL, 0x2949e069UL, 0x448ec9c8UL,
    0x6a75c289UL, 0x78f48e79UL, 0x6b99583eUL, 0xdd27b971UL,
    0xb6bee14fUL, 0x17f088adUL, 0x66c920acUL, 0xb47dce3aUL,
    0x1863df4aUL, 0x82e51a31UL, 0x60975133UL, 0x4562537fUL,
    0xe0b16477UL, 0x84bb6baeUL, 0x1cfe81a0UL, 0x94f9082bUL,
    0x58704868UL, 0x198f45fdUL, 0x8794de6cUL, 0xb7527bf8UL,
    0x23ab73d3UL, 0xe2724b02UL, 0x57e31f8fUL, 0x2a6655abUL,
    0x07b2eb28UL, 0x032fb5c2UL, 0x9a86c57bUL, 0xa5d33708UL,
    0xf2302887UL, 0xb223bfa5UL, 0xba02036aUL, 0x5ced1682UL,
    0x2b8acf1cUL, 0x92a779b4UL, 0xf0f307f2UL, 0xa14e69e2UL,
    0xcd65daf4UL, 0xd50605beUL, 0x1fd13462UL, 0x8ac4a6feUL,
    0x9d342e53UL, 0xa0a2f355UL, 0x32058ae1UL, 0x75a4f6ebUL,
    0x390b83ecUL, 0xaa4060efUL, 0x065e719fUL, 0x51bd6e10UL,
    0xf93e218aUL, 0x3d96dd06UL, 0xaedd3e05UL, 0x464de6bdUL,
    0xb591548dUL, 0x0571c45dUL, 0x6f0406d4UL, 0xff605015UL,
    0x241998fbUL, 0x97d6bde9UL, 0xcc894043UL, 0x7767d99eUL,
    0xbdb0e842UL, 0x8807898bUL, 0x38e7195bUL, 0xdb79c8eeUL,
    0x47a17c0aUL, 0xe97c420fUL, 0xc9f8841eUL, 0x00000000UL,
    0x83098086UL, 0x48322bedUL, 0xac1e1170UL, 0x4e6c5a72UL,
    0xfbfd0effUL, 0x560f8538UL, 0x1e3daed5UL, 0x27362d39UL,
    0x640a0fd9UL, 0x21685ca6UL, 0xd19b5b54UL, 0x3a24362eUL,
    0xb10c0a67UL, 0x0f9357e7UL, 0xd2b4ee96UL, 0x9e1b9b91UL,
    0x4f80c0c5UL, 0xa261dc20UL, 0x695a774bUL, 0x161c121aUL,
    0x0ae293baUL, 0xe5c0a02aUL, 0x433c22e0UL, 0x1d121b17UL,
    0x0b0e090dUL, 0xadf28bc7UL, 0xb92db6a8UL, 0xc8141ea9UL,
    0x8557f119UL, 0x4caf7507UL, 0xbbee99ddUL, 0xfda37f60UL,
    0x9ff70126UL, 0xbc5c72f5UL, 0xc544663bUL, 0x345bfb7eUL,
    0x768b4329UL, 0xdccb23c6UL, 0x68b6edfcUL, 0x63b8e4f1UL,
    0xcad731dcUL, 0x10426385UL, 0x40139722UL, 0x2084c611UL,
    0x7d854a24UL, 0xf8d2bb3dUL, 0x11aef932UL, 0x6dc729a1UL,
    0x4b1d9e2fUL, 0xf3dcb230UL, 0xec0d8652UL, 0xd077c1e3UL,
    0x6c2bb316UL, 0x99a970b9UL, 0xfa119448UL, 0x2247e964UL,
    0xc4a8fc8cUL, 0x1aa0f03fUL, 0xd8567d2cUL, 0xef223390UL,
    0xc787494eUL, 0xc1d938d1UL, 0xfe8ccaa2UL, 0x3698d40bUL,
    0xcfa6f581UL, 0x28a57adeUL, 0x26dab78eUL, 0xa43fadbfUL,
    0xe42c3a9dUL, 0x0d507892UL, 0x9b6a5fccUL, 0x62547e46UL,
    0xc2f68d13UL, 0xe890d8b8UL, 0x5e2e39f7UL, 0xf582c3afUL,
    0xbe9f5d80UL, 0x7c69d093UL, 0xa96fd52dUL, 0xb3cf2512UL,
    0x3bc8ac99UL, 0xa710187dUL, 0x6ee89c63UL, 0x7bdb3bbbUL,
    0x09cd2678UL, 0xf46e5918UL, 0x01ec9ab7UL, 0xa8834f9aUL,
    0x65e6956eUL, 0x7eaaffe6UL, 0x0821bccfUL, 0xe6ef15e8UL,
    0xd9bae79bUL, 0xce4a6f36UL, 0xd4ea9f09UL, 0xd629b07cUL,
    0xaf31a4b2UL, 0x312a3f23UL, 0x30c6a594UL, 0xc035a266UL,
    0x37744ebcUL, 0xa6fc82caUL, 0xb0e090d0UL, 0x1533a7d8UL,
    0x4af10498UL, 0xf741ecdaUL, 0x0e7fcd50UL, 0x2f1791f6UL,
    0x8d764dd6UL, 0x4d43efb0UL, 0x54ccaa4dUL, 0xdfe49604UL,
    0xe39ed1b5UL, 0x1b4c6a88UL, 0xb8c12c1fUL, 0x7f466551UL,
    0x049d5eeaUL, 0x5d018c35UL, 0x73fa8774UL, 0x2efb0b41UL,
    0x5ab3671dUL, 0x5292dbd2UL, 0x33e91056UL, 0x136dd647UL,
    0x8c9ad761UL, 0x7a37a10cUL, 0x8e59f814UL, 0x89eb133cUL,
    0xeecea927UL, 0x35b761c9UL, 0xede11ce5UL, 0x3c7a47b1UL,
    0x599cd2dfUL, 0x3f55f273UL, 0x791814ceUL, 0xbf73c737UL,
    0xea53f7cdUL, 0x5b5ffdaaUL, 0x14df3d6fUL, 0x867844dbUL,
    0x81caaff3UL, 0x3eb968c4UL, 0x2c382434UL, 0x5fc2a340UL,
    0x72161dc3UL, 0x0cbce225UL, 0x8b283c49UL, 0x41ff0d95UL,
    0x7139a801UL, 0xde080cb3UL, 0x9cd8b4e4UL, 0x906456c1UL,
    0x617bcb84UL, 0x70d532b6UL, 0x74486c5cUL, 0x42d0b857UL,
};
static const uint32_t TD2[256] = {
    0xa75051f4UL, 0x65537e41UL, 0xa4c31a17UL, 0x5e963a27UL,
    0x6bcb3babUL, 0x45f11f9dUL, 0x58abacfaUL, 0x03934be3UL,
    0xfa552030UL, 0x6df6ad76UL, 0x769188ccUL, 0x4c25f502UL,
    0xd7fc4fe5UL, 0xcbd7c52aUL, 0x44802635UL, 0xa38fb562UL,
    0x5a49deb1UL, 0x1b6725baUL, 0x0e9845eaUL, 0xc0e15dfeUL,
    0x7502c32fUL, 0xf012814cUL, 0x97a38d46UL, 0xf9c66bd3UL,
    0x5fe7038fUL, 0x9c951592UL, 0x7aebbf6dUL, 0x59da9552UL,
    0x832dd4beUL, 0x21d35874UL, 0x692949e0UL, 0xc8448ec9UL,
    0x896a75c2UL, 0x7978f48eUL, 0x3e6b9958UL, 0x71dd27b9UL,
    0x4fb6bee1UL, 0xad17f088UL, 0xac66c920UL, 0x3ab47dceUL,
    0x4a1863dfUL, 0x3182e51aUL, 0x33609751UL, 0x7f456253UL,
    0x77e0b164UL, 0xae84bb6bUL, 0xa01cfe81UL, 0x2b94f908UL,
    0x68587048UL, 0xfd198f45UL, 0x6c8794deUL, 0xf8b7527bUL,
    0xd323ab73UL, 0x02e2724bUL, 0x8f57e31fUL, 0xab2a6655UL,
    0x2807b2ebUL, 0xc2032fb5UL, 0x7b9a86c5UL, 0x08a5d337UL,
    0x87f23028UL, 0xa5b223bfUL, 0x6aba0203UL, 0x825ced16UL,
    0x1c2b8acfUL, 0xb492a779UL, 0xf2f0f307UL, 0xe2a14e69UL,
    0xf4cd65daUL, 0xbed50605UL, 0x621fd134UL, 0xfe8ac4a6UL,
    0x539d342eUL, 0x55a0a2f3UL, 0xe132058aUL, 0xeb75a4f6UL,
    0xec390b83UL, 0xefaa4060UL, 0x9f065e71UL, 0x1051bd6eUL,
    0x8af93e21UL, 0x063d96ddUL, 0x05aedd3eUL, 0xbd464de6UL,
    0x8db59154UL, 0x5d0571c4UL, 0xd46f0406UL, 0x15ff6050UL,
    0xfb241998UL, 0xe997d6bdUL, 0x43cc8940UL, 0x9e7767d9UL,
    0x42bdb0e8UL, 0x8b880789UL, 0x5b38e719UL, 0xeedb79c8UL,
    0x0a47a17cUL, 0x0fe97c42UL, 0x1ec9f884UL, 0x00000000UL,
    0x86830980UL, 0xed48322bUL, 0x70ac1e11UL, 0x724e6c5aUL,
    0xfffbfd0eUL, 0x38560f85UL, 0xd51e3daeUL, 0x3927362dUL,
    0xd9640a0fUL, 0xa621685cUL, 0x54d19b5bUL, 0x2e3a2436UL,
    0x67b10c0aUL, 0xe70f9357UL, 0x96d2b4eeUL, 0x919e1b9bUL,
    0xc54f80c0UL, 0x20a261dcUL, 0x4b695a77UL, 0x1a161c12UL,
    0xba0ae293UL, 0x2ae5c0a0UL, 0xe0433c22UL, 0x171d121bUL,
    0x0d0b0e09UL, 0xc7adf28bUL, 0xa8b92db6UL, 0xa9c8141eUL,
    0x198557f1UL, 0x074caf75UL, 0xddbbee99UL, 0x60fda37fUL,
    0x269ff701UL, 0xf5bc5c72UL, 0x3bc54466UL, 0x7e345bfbUL,
    0x29768b43UL, 0xc6dccb23UL, 0xfc68b6edUL, 0xf163b8e4UL,
    0xdccad731UL, 0x85104263UL, 0x22401397UL, 0x112084c6UL,
    0x247d854aUL, 0x3df8d2bbUL, 0x3211aef9UL, 0xa16dc729UL,
    0x2f4b1d9eUL, 0x30f3dcb2UL, 0x52ec0d86UL, 0xe3d077c1UL,
    0x166c2bb3UL, 0xb999a970UL, 0x48fa1194UL, 0x642247e9UL,
    0x8cc4a8fcUL, 0x3f1aa0f0UL, 0x2cd8567dUL, 0x90ef2233UL,
    0x4ec78749UL, 0xd1c1d938UL, 0xa2fe8ccaUL, 0x0b3698d4UL,
    0x81cfa6f5UL, 0xde28a57aUL, 0x8e26dab7UL, 0xbfa43fadUL,
    0x9de42c3aUL, 0x920d5078UL, 0xcc9b6a5fUL, 0x4662547eUL,
    0x13c2f68dUL, 0xb8e890d8UL, 0xf75e2e39UL, 0xaff582c3UL,
    0x80be9f5dUL, 0x937c69d0UL, 0x2da96fd5UL, 0x12b3cf25UL,
    0x993bc8acUL, 0x7da71018UL, 0x636ee89cUL, 0xbb7bdb3bUL,
    0x7809cd26UL, 0x18f46e59UL, 0xb701ec9aUL, 0x9aa8834fUL,
    0x6e65e695UL, 0xe67eaaffUL, 0xcf0821bcUL, 0xe8e6ef15UL,
    0x9bd9bae7UL, 0x36ce4a6fUL, 0x09d4ea9fUL, 0x7cd629b0UL,
    0xb2af31a4UL, 0x23312a3fUL, 0x9430c6a5UL, 0x66c035a2UL,
    0xbc37744eUL, 0xcaa6fc82UL, 0xd0b0e090UL, 0xd81533a7UL,
    0x984af104UL, 0xdaf741ecUL, 0x500e7fcdUL, 0xf62f1791UL,
    0xd68d764dUL, 0xb04d43efUL, 0x4d54ccaaUL, 0x04dfe496UL,
    0xb5e39ed1UL, 0x881b4c6aUL, 0x1fb8c12cUL, 0x517f4665UL,
    0xea049d5eUL, 0x355d018cUL, 0x7473fa87UL, 0x412efb0bUL,
    0x1d5ab367UL, 0xd25292dbUL, 0x5633e910UL, 0x47136dd6UL,
    0x618c9ad7UL, 0x0c7a37a1UL, 0x148e59f8UL, 0x3c89eb13UL,
    0x27eecea9UL, 0xc935b761UL, 0xe5ede11cUL, 0xb13c7a47UL,
    0xdf599cd2UL, 0x733f55f2UL, 0xce791814UL, 0x37bf73c7UL,
    0xcdea53f7UL, 0xaa5b5ffdUL, 0x6f14df3dUL, 0xdb867844UL,
    0xf381caafUL, 0xc43eb968UL, 0x342c3824UL, 0x405fc2a3UL,
    0xc372161dUL, 0x250cbce2UL, 0x498b283cUL, 0x9541ff0dUL,
    0x017139a8UL, 0xb3de080cUL, 0xe49cd8b4UL, 0xc1906456UL,
    0x84617bcbUL, 0xb670d532UL, 0x5c74486cUL, 0x5742d0b8UL,
};
static const uint32_t TD3[256] = {
    0xf4a75051UL, 0x4165537eUL, 0x17a4c31aUL, 0x275e963aUL,
    0xab6bcb3bUL, 0x9d45f11fUL, 0xfa58abacUL, 0xe303934bUL,
    0x30fa5520UL, 0x766df6adUL, 0xcc769188UL, 0x024c25f5UL,
    0xe5d7fc4fUL, 0x2acbd7c5UL, 0x35448026UL, 0x62a38fb5UL,
    0xb15a49deUL, 0xba1b6725UL, 0xea0e9845UL, 0xfec0e15dUL,
    0x2f7502c3UL, 0x4cf01281UL, 0x4697a38dUL, 0xd3f9c66bUL,
    0x8f5fe703UL, 0x929c9515UL, 0x6d7aebbfUL, 0x5259da95UL,
    0xbe832dd4UL, 0x7421d358UL, 0xe0692949UL, 0xc9c8448eUL,
    0xc2896a75UL, 0x8e7978f4UL, 0x583e6b99UL, 0xb971dd27UL,
    0xe14fb6beUL, 0x88ad17f0UL, 0x20ac66c9UL, 0xce3ab47dUL,
    0xdf4a1863UL, 0x1a3182e5UL, 0x51336097UL, 0x537f4562UL,
    0x6477e0b1UL, 0x6bae84bbUL, 0x81a01cfeUL, 0x082b94f9UL,
    0x48685870UL, 0x45fd198fUL, 0xde6c8794UL, 0x7bf8b752UL,
    0x73d323abUL, 0x4b02e272UL, 0x1f8f57e3UL, 0x55ab2a66UL,
    0xeb2807b2UL, 0xb5c2032fUL, 0xc57b9a86UL, 0x3708a5d3UL,
    0x2887f230UL, 0xbfa5b223UL, 0x036aba02UL, 0x16825cedUL,
    0xcf1c2b8aUL, 0x79b492a7UL, 0x07f2f0f3UL, 0x69e2a14eUL,
    0xdaf4cd65UL, 0x05bed506UL, 0x34621fd1UL, 0xa6fe8ac4UL,
    0x2e539d34UL, 0xf355a0a2UL, 0x8ae13205UL, 0xf6eb75a4UL,
    0x83ec390bUL, 0x60efaa40UL, 0x719f065eUL, 0x6e1051bdUL,
    0x218af93eUL, 0xdd063d96UL, 0x3e05aeddUL, 0xe6bd464dUL,
    0x548db591UL, 0xc45d0571UL, 0x06d46f04UL, 0x5015ff60UL,
    0x98fb2419UL, 0xbde997d6UL, 0x4043cc89UL, 0xd99e7767UL,
    0xe842bdb0UL, 0x898b8807UL, 0x195b38e7UL, 0xc8eedb79UL,
    0x7c0a47a1UL, 0x420fe97cUL, 0x841ec9f8UL, 0x00000000UL,
    0x80868309UL, 0x2bed4832UL, 0x1170ac1eUL, 0x5a724e6cUL,
    0x0efffbfdUL, 0x8538560fUL, 0xaed51e3dUL, 0x2d392736UL,
    0x0fd9640aUL, 0x5ca62168UL, 0x5b54d19bUL, 0x362e3a24UL,
    0x0a67b10cUL, 0x57e70f93UL, 0xee96d2b4UL, 0x9b919e1bUL,
    0xc0c54f80UL, 0xdc20a261UL, 0x774b695aUL, 0x121a161cUL,
    0x93ba0ae2UL, 0xa02ae5c0UL, 0x22e0433cUL, 0x1b171d12UL,
    0x090d0b0eUL, 0x8bc7adf2UL, 0xb6a8b92dUL, 0x1ea9c814UL,
    0xf1198557UL, 0x75074cafUL, 0x99ddbbeeUL, 0x7f60fda3UL,
    0x01269ff7UL, 0x72f5bc5cUL, 0x663bc544UL, 0xfb7e345bUL,
    0x4329768bUL, 0x23c6dccbUL, 0xedfc68b6UL, 0xe4f163b8UL,
    0x31dccad7UL, 0x63851042UL, 0x97224013UL, 0xc6112084UL,
    0x4a247d85UL, 0xbb3df8d2UL, 0xf93211aeUL, 0x29a16dc7UL,
    0x9e2f4b1dUL, 0xb230f3dcUL, 0x8652ec0dUL, 0xc1e3d077UL,
    0xb3166c2bUL, 0x70b999a9UL, 0x9448fa11UL, 0xe9642247UL,
    0xfc8cc4a8UL, 0xf03f1aa0UL, 0x7d2cd856UL, 0x3390ef22UL,
    0x494ec787UL, 0x38d1c1d9UL, 0xcaa2fe8cUL, 0xd40b3698UL,
    0xf581cfa6UL, 0x7ade28a5UL, 0xb78e26daUL, 0xadbfa43fUL,
    0x3a9de42cUL, 0x78920d50UL, 0x5fcc9b6aUL, 0x7e466254UL,
    0x8d13c2f6UL, 0xd8b8e890UL, 0x39f75e2eUL, 0xc3aff582UL,
    0x5d80be9fUL, 0xd0937c69UL, 0xd52da96fUL, 0x2512b3cfUL,
    0xac993bc8UL, 0x187da710UL, 0x9c636ee8UL, 0x3bbb7bdbUL,
    0x267809cdUL, 0x5918f46eUL, 0x9ab701ecUL, 0x4f9aa883UL,
    0x956e65e6UL, 0xffe67eaaUL, 0xbccf0821UL, 0x15e8e6efUL,
    0xe79bd9baUL, 0x6f36ce4aUL, 0x9f09d4eaUL, 0xb07cd629UL,
    0xa4b2af31UL, 0x3f23312aUL, 0xa59430c6UL, 0xa266c035UL,
    0x4ebc3774UL, 0x82caa6fcUL, 0x90d0b0e0UL, 0xa7d81533UL,
    0x04984af1UL, 0xecdaf741UL, 0xcd500e7fUL, 0x91f62f17UL,
    0x4dd68d76UL, 0xefb04d43UL, 0xaa4d54ccUL, 0x9604dfe4UL,
    0xd1b5e39eUL, 0x6a881b4cUL, 0x2c1fb8c1UL, 0x65517f46UL,
    0x5eea049dUL, 0x8c355d01UL, 0x877473faUL, 0x0b412efbUL,
    0x671d5ab3UL, 0xdbd25292UL, 0x105633e9UL, 0xd647136dUL,
    0xd7618c9aUL, 0xa10c7a37UL, 0xf8148e59UL, 0x133c89ebUL,
    0xa927eeceUL, 0x61c935b7UL, 0x1ce5ede1UL, 0x47b13c7aUL,
    0xd2df599cUL, 0xf2733f55UL, 0x14ce7918UL, 0xc737bf73UL,
    0xf7cdea53UL, 0xfdaa5b5fUL, 0x3d6f14dfUL, 0x44db8678UL,
    0xaff381caUL, 0x68c43eb9UL, 0x24342c38UL, 0xa3405fc2UL,
    0x1dc37216UL, 0xe2250cbcUL, 0x3c498b28UL, 0x0d9541ffUL,
    0xa8017139UL, 0x0cb3de08UL, 0xb4e49cd8UL, 0x56c19064UL,
    0xcb84617bUL, 0x32b670d5UL, 0x6c5c7448UL, 0xb85742d0UL,
};

static const uint32_t Tks0[] = {
    0x00000000UL, 0x0e090d0bUL, 0x1c121a16UL, 0x121b171dUL, 0x3824342cUL, 0x362d3927UL, 0x24362e3aUL, 0x2a3f2331UL, 
    0x70486858UL, 0x7e416553UL, 0x6c5a724eUL, 0x62537f45UL, 0x486c5c74UL, 0x4665517fUL, 0x547e4662UL, 0x5a774b69UL, 
    0xe090d0b0UL, 0xee99ddbbUL, 0xfc82caa6UL, 0xf28bc7adUL, 0xd8b4e49cUL, 0xd6bde997UL, 0xc4a6fe8aUL, 0xcaaff381UL, 
    0x90d8b8e8UL, 0x9ed1b5e3UL, 0x8ccaa2feUL, 0x82c3aff5UL, 0xa8fc8cc4UL, 0xa6f581cfUL, 0xb4ee96d2UL, 0xbae79bd9UL, 
    0xdb3bbb7bUL, 0xd532b670UL, 0xc729a16dUL, 0xc920ac66UL, 0xe31f8f57UL, 0xed16825cUL, 0xff0d9541UL, 0xf104984aUL, 
    0xab73d323UL, 0xa57ade28UL, 0xb761c935UL, 0xb968c43eUL, 0x9357e70fUL, 0x9d5eea04UL, 0x8f45fd19UL, 0x814cf012UL, 
    0x3bab6bcbUL, 0x35a266c0UL, 0x27b971ddUL, 0x29b07cd6UL, 0x038f5fe7UL, 0x0d8652ecUL, 0x1f9d45f1UL, 0x119448faUL, 
    0x4be30393UL, 0x45ea0e98UL, 0x57f11985UL, 0x59f8148eUL, 0x73c737bfUL, 0x7dce3ab4UL, 0x6fd52da9UL, 0x61dc20a2UL, 
    0xad766df6UL, 0xa37f60fdUL, 0xb16477e0UL, 0xbf6d7aebUL, 0x955259daUL, 0x9b5b54d1UL, 0x894043ccUL, 0x87494ec7UL, 
    0xdd3e05aeUL, 0xd33708a5UL, 0xc12c1fb8UL, 0xcf2512b3UL, 0xe51a3182UL, 0xeb133c89UL, 0xf9082b94UL, 0xf701269fUL, 
    0x4de6bd46UL, 0x43efb04dUL, 0x51f4a750UL, 0x5ffdaa5bUL, 0x75c2896aUL, 0x7bcb8461UL, 0x69d0937cUL, 0x67d99e77UL, 
    0x3daed51eUL, 0x33a7d815UL, 0x21bccf08UL, 0x2fb5c203UL, 0x058ae132UL, 0x0b83ec39UL, 0x1998fb24UL, 0x1791f62fUL, 
    0x764dd68dUL, 0x7844db86UL, 0x6a5fcc9bUL, 0x6456c190UL, 0x4e69e2a1UL, 0x4060efaaUL, 0x527bf8b7UL, 0x5c72f5bcUL, 
    0x0605bed5UL, 0x080cb3deUL, 0x1a17a4c3UL, 0x141ea9c8UL, 0x3e218af9UL, 0x302887f2UL, 0x223390efUL, 0x2c3a9de4UL, 
    0x96dd063dUL, 0x98d40b36UL, 0x8acf1c2bUL, 0x84c61120UL, 0xaef93211UL, 0xa0f03f1aUL, 0xb2eb2807UL, 0xbce2250cUL, 
    0xe6956e65UL, 0xe89c636eUL, 0xfa877473UL, 0xf48e7978UL, 0xdeb15a49UL, 0xd0b85742UL, 0xc2a3405fUL, 0xccaa4d54UL, 
    0x41ecdaf7UL, 0x4fe5d7fcUL, 0x5dfec0e1UL, 0x53f7cdeaUL, 0x79c8eedbUL, 0x77c1e3d0UL, 0x65daf4cdUL, 0x6bd3f9c6UL, 
    0x31a4b2afUL, 0x3fadbfa4UL, 0x2db6a8b9UL, 0x23bfa5b2UL, 0x09808683UL, 0x07898b88UL, 0x15929c95UL, 0x1b9b919eUL, 
    0xa17c0a47UL, 0xaf75074cUL, 0xbd6e1051UL, 0xb3671d5aUL, 0x99583e6bUL, 0x97513360UL, 0x854a247dUL, 0x8b432976UL, 
    0xd134621fUL, 0xdf3d6f14UL, 0xcd267809UL, 0xc32f7502UL, 0xe9105633UL, 0xe7195b38UL, 0xf5024c25UL, 0xfb0b412eUL, 
    0x9ad7618cUL, 0x94de6c87UL, 0x86c57b9aUL, 0x88cc7691UL, 0xa2f355a0UL, 0xacfa58abUL, 0xbee14fb6UL, 0xb0e842bdUL, 
    0xea9f09d4UL, 0xe49604dfUL, 0xf68d13c2UL, 0xf8841ec9UL, 0xd2bb3df8UL, 0xdcb230f3UL, 0xcea927eeUL, 0xc0a02ae5UL, 
    0x7a47b13cUL, 0x744ebc37UL, 0x6655ab2aUL, 0x685ca621UL, 0x42638510UL, 0x4c6a881bUL, 0x5e719f06UL, 0x5078920dUL, 
    0x0a0fd964UL, 0x0406d46fUL, 0x161dc372UL, 0x1814ce79UL, 0x322bed48UL, 0x3c22e043UL, 0x2e39f75eUL, 0x2030fa55UL, 
    0xec9ab701UL, 0xe293ba0aUL, 0xf088ad17UL, 0xfe81a01cUL, 0xd4be832dUL, 0xdab78e26UL, 0xc8ac993bUL, 0xc6a59430UL, 
    0x9cd2df59UL, 0x92dbd252UL, 0x80c0c54fUL, 0x8ec9c844UL, 0xa4f6eb75UL, 0xaaffe67eUL, 0xb8e4f163UL, 0xb6edfc68UL, 
    0x0c0a67b1UL, 0x02036abaUL, 0x10187da7UL, 0x1e1170acUL, 0x342e539dUL, 0x3a275e96UL, 0x283c498bUL, 0x26354480UL, 
    0x7c420fe9UL, 0x724b02e2UL, 0x605015ffUL, 0x6e5918f4UL, 0x44663bc5UL, 0x4a6f36ceUL, 0x587421d3UL, 0x567d2cd8UL, 
    0x37a10c7aUL, 0x39a80171UL, 0x2bb3166cUL, 0x25ba1b67UL, 0x0f853856UL, 0x018c355dUL, 0x13972240UL, 0x1d9e2f4bUL, 
    0x47e96422UL, 0x49e06929UL, 0x5bfb7e34UL, 0x55f2733fUL, 0x7fcd500eUL, 0x71c45d05UL, 0x63df4a18UL, 0x6dd64713UL, 
    0xd731dccaUL, 0xd938d1c1UL, 0xcb23c6dcUL, 0xc52acbd7UL, 0xef15e8e6UL, 0xe11ce5edUL, 0xf307f2f0UL, 0xfd0efffbUL, 
    0xa779b492UL, 0xa970b999UL, 0xbb6bae84UL, 0xb562a38fUL, 0x9f5d80beUL, 0x91548db5UL, 0x834f9aa8UL, 0x8d4697a3UL
};

static const uint32_t Tks1[] = {
    0x00000000UL, 0x0b0e090dUL, 0x161c121aUL, 0x1d121b17UL, 0x2c382434UL, 0x27362d39UL, 0x3a24362eUL, 0x312a3f23UL, 
    0x58704868UL, 0x537e4165UL, 0x4e6c5a72UL, 0x4562537fUL, 0x74486c5cUL, 0x7f466551UL, 0x62547e46UL, 0x695a774bUL, 
    0xb0e090d0UL, 0xbbee99ddUL, 0xa6fc82caUL, 0xadf28bc7UL, 0x9cd8b4e4UL, 0x97d6bde9UL, 0x8ac4a6feUL, 0x81caaff3UL, 
    0xe890d8b8UL, 0xe39ed1b5UL, 0xfe8ccaa2UL, 0xf582c3afUL, 0xc4a8fc8cUL, 0xcfa6f581UL, 0xd2b4ee96UL, 0xd9bae79bUL, 
    0x7bdb3bbbUL, 0x70d532b6UL, 0x6dc729a1UL, 0x66c920acUL, 0x57e31f8fUL, 0x5ced1682UL, 0x41ff0d95UL, 0x4af10498UL, 
    0x23ab73d3UL, 0x28a57adeUL, 0x35b761c9UL, 0x3eb968c4UL, 0x0f9357e7UL, 0x049d5eeaUL, 0x198f45fdUL, 0x12814cf0UL, 
    0xcb3bab6bUL, 0xc035a266UL, 0xdd27b971UL, 0xd629b07cUL, 0xe7038f5fUL, 0xec0d8652UL, 0xf11f9d45UL, 0xfa119448UL, 
    0x934be303UL, 0x9845ea0eUL, 0x8557f119UL, 0x8e59f814UL, 0xbf73c737UL, 0xb47dce3aUL, 0xa96fd52dUL, 0xa261dc20UL, 
    0xf6ad766dUL, 0xfda37f60UL, 0xe0b16477UL, 0xebbf6d7aUL, 0xda955259UL, 0xd19b5b54UL, 0xcc894043UL, 0xc787494eUL, 
    0xaedd3e05UL, 0xa5d33708UL, 0xb8c12c1fUL, 0xb3cf2512UL, 0x82e51a31UL, 0x89eb133cUL, 0x94f9082bUL, 0x9ff70126UL, 
    0x464de6bdUL, 0x4d43efb0UL, 0x5051f4a7UL, 0x5b5ffdaaUL, 0x6a75c289UL, 0x617bcb84UL, 0x7c69d093UL, 0x7767d99eUL, 
    0x1e3daed5UL, 0x1533a7d8UL, 0x0821bccfUL, 0x032fb5c2UL, 0x32058ae1UL, 0x390b83ecUL, 0x241998fbUL, 0x2f1791f6UL, 
    0x8d764dd6UL, 0x867844dbUL, 0x9b6a5fccUL, 0x906456c1UL, 0xa14e69e2UL, 0xaa4060efUL, 0xb7527bf8UL, 0xbc5c72f5UL, 
    0xd50605beUL, 0xde080cb3UL, 0xc31a17a4UL, 0xc8141ea9UL, 0xf93e218aUL, 0xf2302887UL, 0xef223390UL, 0xe42c3a9dUL, 
    0x3d96dd06UL, 0x3698d40bUL, 0x2b8acf1cUL, 0x2084c611UL, 0x11aef932UL, 0x1aa0f03fUL, 0x07b2eb28UL, 0x0cbce225UL, 
    0x65e6956eUL, 0x6ee89c63UL, 0x73fa8774UL, 0x78f48e79UL, 0x49deb15aUL, 0x42d0b857UL, 0x5fc2a340UL, 0x54ccaa4dUL, 
    0xf741ecdaUL, 0xfc4fe5d7UL, 0xe15dfec0UL, 0xea53f7cdUL, 0xdb79c8eeUL, 0xd077c1e3UL, 0xcd65daf4UL, 0xc66bd3f9UL, 
    0xaf31a4b2UL, 0xa43fadbfUL, 0xb92db6a8UL, 0xb223bfa5UL, 0x83098086UL, 0x8807898bUL, 0x9515929cUL, 0x9e1b9b91UL, 
    0x47a17c0aUL, 0x4caf7507UL, 0x51bd6e10UL, 0x5ab3671dUL, 0x6b99583eUL, 0x60975133UL, 0x7d854a24UL, 0x768b4329UL, 
    0x1fd13462UL, 0x14df3d6fUL, 0x09cd2678UL, 0x02c32f75UL, 0x33e91056UL, 0x38e7195bUL, 0x25f5024cUL, 0x2efb0b41UL, 
    0x8c9ad761UL, 0x8794de6cUL, 0x9a86c57bUL, 0x9188cc76UL, 0xa0a2f355UL, 0xabacfa58UL, 0xb6bee14fUL, 0xbdb0e842UL, 
    0xd4ea9f09UL, 0xdfe49604UL, 0xc2f68d13UL, 0xc9f8841eUL, 0xf8d2bb3dUL, 0xf3dcb230UL, 0xeecea927UL, 0xe5c0a02aUL, 
    0x3c7a47b1UL, 0x37744ebcUL, 0x2a6655abUL, 0x21685ca6UL, 0x10426385UL, 0x1b4c6a88UL, 0x065e719fUL, 0x0d507892UL, 
    0x640a0fd9UL, 0x6f0406d4UL, 0x72161dc3UL, 0x791814ceUL, 0x48322bedUL, 0x433c22e0UL, 0x5e2e39f7UL, 0x552030faUL, 
    0x01ec9ab7UL, 0x0ae293baUL, 0x17f088adUL, 0x1cfe81a0UL, 0x2dd4be83UL, 0x26dab78eUL, 0x3bc8ac99UL, 0x30c6a594UL, 
    0x599cd2dfUL, 0x5292dbd2UL, 0x4f80c0c5UL, 0x448ec9c8UL, 0x75a4f6ebUL, 0x7eaaffe6UL, 0x63b8e4f1UL, 0x68b6edfcUL, 
    0xb10c0a67UL, 0xba02036aUL, 0xa710187dUL, 0xac1e1170UL, 0x9d342e53UL, 0x963a275eUL, 0x8b283c49UL, 0x80263544UL, 
    0xe97c420fUL, 0xe2724b02UL, 0xff605015UL, 0xf46e5918UL, 0xc544663bUL, 0xce4a6f36UL, 0xd3587421UL, 0xd8567d2cUL, 
    0x7a37a10cUL, 0x7139a801UL, 0x6c2bb316UL, 0x6725ba1bUL, 0x560f8538UL, 0x5d018c35UL, 0x40139722UL, 0x4b1d9e2fUL, 
    0x2247e964UL, 0x2949e069UL, 0x345bfb7eUL, 0x3f55f273UL, 0x0e7fcd50UL, 0x0571c45dUL, 0x1863df4aUL, 0x136dd647UL, 
    0xcad731dcUL, 0xc1d938d1UL, 0xdccb23c6UL, 0xd7c52acbUL, 0xe6ef15e8UL, 0xede11ce5UL, 0xf0f307f2UL, 0xfbfd0effUL, 
    0x92a779b4UL, 0x99a970b9UL, 0x84bb6baeUL, 0x8fb562a3UL, 0xbe9f5d80UL, 0xb591548dUL, 0xa8834f9aUL, 0xa38d4697UL
};

static const uint32_t Tks2[] = {
    0x00000000UL, 0x0d0b0e09UL, 0x1a161c12UL, 0x171d121bUL, 0x342c3824UL, 0x3927362dUL, 0x2e3a2436UL, 0x23312a3fUL, 
    0x68587048UL, 0x65537e41UL, 0x724e6c5aUL, 0x7f456253UL, 0x5c74486cUL, 0x517f4665UL, 0x4662547eUL, 0x4b695a77UL, 
    0xd0b0e090UL, 0xddbbee99UL, 0xcaa6fc82UL, 0xc7adf28bUL, 0xe49cd8b4UL, 0xe997d6bdUL, 0xfe8ac4a6UL, 0xf381caafUL, 
    0xb8e890d8UL, 0xb5e39ed1UL, 0xa2fe8ccaUL, 0xaff582c3UL, 0x8cc4a8fcUL, 0x81cfa6f5UL, 0x96d2b4eeUL, 0x9bd9bae7UL, 
    0xbb7bdb3bUL, 0xb670d532UL, 0xa16dc729UL, 0xac66c920UL, 0x8f57e31fUL, 0x825ced16UL, 0x9541ff0dUL, 0x984af104UL, 
    0xd323ab73UL, 0xde28a57aUL, 0xc935b761UL, 0xc43eb968UL, 0xe70f9357UL, 0xea049d5eUL, 0xfd198f45UL, 0xf012814cUL, 
    0x6bcb3babUL, 0x66c035a2UL, 0x71dd27b9UL, 0x7cd629b0UL, 0x5fe7038fUL, 0x52ec0d86UL, 0x45f11f9dUL, 0x48fa1194UL, 
    0x03934be3UL, 0x0e9845eaUL, 0x198557f1UL, 0x148e59f8UL, 0x37bf73c7UL, 0x3ab47dceUL, 0x2da96fd5UL, 0x20a261dcUL, 
    0x6df6ad76UL, 0x60fda37fUL, 0x77e0b164UL, 0x7aebbf6dUL, 0x59da9552UL, 0x54d19b5bUL, 0x43cc8940UL, 0x4ec78749UL, 
    0x05aedd3eUL, 0x08a5d337UL, 0x1fb8c12cUL, 0x12b3cf25UL, 0x3182e51aUL, 0x3c89eb13UL, 0x2b94f908UL, 0x269ff701UL, 
    0xbd464de6UL, 0xb04d43efUL, 0xa75051f4UL, 0xaa5b5ffdUL, 0x896a75c2UL, 0x84617bcbUL, 0x937c69d0UL, 0x9e7767d9UL, 
    0xd51e3daeUL, 0xd81533a7UL, 0xcf0821bcUL, 0xc2032fb5UL, 0xe132058aUL, 0xec390b83UL, 0xfb241998UL, 0xf62f1791UL, 
    0xd68d764dUL, 0xdb867844UL, 0xcc9b6a5fUL, 0xc1906456UL, 0xe2a14e69UL, 0xefaa4060UL, 0xf8b7527bUL, 0xf5bc5c72UL, 
    0xbed50605UL, 0xb3de080cUL, 0xa4c31a17UL, 0xa9c8141eUL, 0x8af93e21UL, 0x87f23028UL, 0x90ef2233UL, 0x9de42c3aUL, 
    0x063d96ddUL, 0x0b3698d4UL, 0x1c2b8acfUL, 0x112084c6UL, 0x3211aef9UL, 0x3f1aa0f0UL, 0x2807b2ebUL, 0x250cbce2UL, 
    0x6e65e695UL, 0x636ee89cUL, 0x7473fa87UL, 0x7978f48eUL, 0x5a49deb1UL, 0x5742d0b8UL, 0x405fc2a3UL, 0x4d54ccaaUL, 
    0xdaf741ecUL, 0xd7fc4fe5UL, 0xc0e15dfeUL, 0xcdea53f7UL, 0xeedb79c8UL, 0xe3d077c1UL, 0xf4cd65daUL, 0xf9c66bd3UL, 
    0xb2af31a4UL, 0xbfa43fadUL, 0xa8b92db6UL, 0xa5b223bfUL, 0x86830980UL, 0x8b880789UL, 0x9c951592UL, 0x919e1b9bUL, 
    0x0a47a17cUL, 0x074caf75UL, 0x1051bd6eUL, 0x1d5ab367UL, 0x3e6b9958UL, 0x33609751UL, 0x247d854aUL, 0x29768b43UL, 
    0x621fd134UL, 0x6f14df3dUL, 0x7809cd26UL, 0x7502c32fUL, 0x5633e910UL, 0x5b38e719UL, 0x4c25f502UL, 0x412efb0bUL, 
    0x618c9ad7UL, 0x6c8794deUL, 0x7b9a86c5UL, 0x769188ccUL, 0x55a0a2f3UL, 0x58abacfaUL, 0x4fb6bee1UL, 0x42bdb0e8UL, 
    0x09d4ea9fUL, 0x04dfe496UL, 0x13c2f68dUL, 0x1ec9f884UL, 0x3df8d2bbUL, 0x30f3dcb2UL, 0x27eecea9UL, 0x2ae5c0a0UL, 
    0xb13c7a47UL, 0xbc37744eUL, 0xab2a6655UL, 0xa621685cUL, 0x85104263UL, 0x881b4c6aUL, 0x9f065e71UL, 0x920d5078UL, 
    0xd9640a0fUL, 0xd46f0406UL, 0xc372161dUL, 0xce791814UL, 0xed48322bUL, 0xe0433c22UL, 0xf75e2e39UL, 0xfa552030UL, 
    0xb701ec9aUL, 0xba0ae293UL, 0xad17f088UL, 0xa01cfe81UL, 0x832dd4beUL, 0x8e26dab7UL, 0x993bc8acUL, 0x9430c6a5UL, 
    0xdf599cd2UL, 0xd25292dbUL, 0xc54f80c0UL, 0xc8448ec9UL, 0xeb75a4f6UL, 0xe67eaaffUL, 0xf163b8e4UL, 0xfc68b6edUL, 
    0x67b10c0aUL, 0x6aba0203UL, 0x7da71018UL, 0x70ac1e11UL, 0x539d342eUL, 0x5e963a27UL, 0x498b283cUL, 0x44802635UL, 
    0x0fe97c42UL, 0x02e2724bUL, 0x15ff6050UL, 0x18f46e59UL, 0x3bc54466UL, 0x36ce4a6fUL, 0x21d35874UL, 0x2cd8567dUL, 
    0x0c7a37a1UL, 0x017139a8UL, 0x166c2bb3UL, 0x1b6725baUL, 0x38560f85UL, 0x355d018cUL, 0x22401397UL, 0x2f4b1d9eUL, 
    0x642247e9UL, 0x692949e0UL, 0x7e345bfbUL, 0x733f55f2UL, 0x500e7fcdUL, 0x5d0571c4UL, 0x4a1863dfUL, 0x47136dd6UL, 
    0xdccad731UL, 0xd1c1d938UL, 0xc6dccb23UL, 0xcbd7c52aUL, 0xe8e6ef15UL, 0xe5ede11cUL, 0xf2f0f307UL, 0xfffbfd0eUL, 
    0xb492a779UL, 0xb999a970UL, 0xae84bb6bUL, 0xa38fb562UL, 0x80be9f5dUL, 0x8db59154UL, 0x9aa8834fUL, 0x97a38d46UL
};

static const uint32_t Tks3[] = {
    0x00000000UL, 0x090d0b0eUL, 0x121a161cUL, 0x1b171d12UL, 0x24342c38UL, 0x2d392736UL, 0x362e3a24UL, 0x3f23312aUL, 
    0x48685870UL, 0x4165537eUL, 0x5a724e6cUL, 0x537f4562UL, 0x6c5c7448UL, 0x65517f46UL, 0x7e466254UL, 0x774b695aUL, 
    0x90d0b0e0UL, 0x99ddbbeeUL, 0x82caa6fcUL, 0x8bc7adf2UL, 0xb4e49cd8UL, 0xbde997d6UL, 0xa6fe8ac4UL, 0xaff381caUL, 
    0xd8b8e890UL, 0xd1b5e39eUL, 0xcaa2fe8cUL, 0xc3aff582UL, 0xfc8cc4a8UL, 0xf581cfa6UL, 0xee96d2b4UL, 0xe79bd9baUL, 
    0x3bbb7bdbUL, 0x32b670d5UL, 0x29a16dc7UL, 0x20ac66c9UL, 0x1f8f57e3UL, 0x16825cedUL, 0x0d9541ffUL, 0x04984af1UL, 
    0x73d323abUL, 0x7ade28a5UL, 0x61c935b7UL, 0x68c43eb9UL, 0x57e70f93UL, 0x5eea049dUL, 0x45fd198fUL, 0x4cf01281UL, 
    0xab6bcb3bUL, 0xa266c035UL, 0xb971dd27UL, 0xb07cd629UL, 0x8f5fe703UL, 0x8652ec0dUL, 0x9d45f11fUL, 0x9448fa11UL, 
    0xe303934bUL, 0xea0e9845UL, 0xf1198557UL, 0xf8148e59UL, 0xc737bf73UL, 0xce3ab47dUL, 0xd52da96fUL, 0xdc20a261UL, 
    0x766df6adUL, 0x7f60fda3UL, 0x6477e0b1UL, 0x6d7aebbfUL, 0x5259da95UL, 0x5b54d19bUL, 0x4043cc89UL, 0x494ec787UL, 
    0x3e05aeddUL, 0x3708a5d3UL, 0x2c1fb8c1UL, 0x2512b3cfUL, 0x1a3182e5UL, 0x133c89ebUL, 0x082b94f9UL, 0x01269ff7UL, 
    0xe6bd464dUL, 0xefb04d43UL, 0xf4a75051UL, 0xfdaa5b5fUL, 0xc2896a75UL, 0xcb84617bUL, 0xd0937c69UL, 0xd99e7767UL, 
    0xaed51e3dUL, 0xa7d81533UL, 0xbccf0821UL, 0xb5c2032fUL, 0x8ae13205UL, 0x83ec390bUL, 0x98fb2419UL, 0x91f62f17UL, 
    0x4dd68d76UL, 0x44db8678UL, 0x5fcc9b6aUL, 0x56c19064UL, 0x69e2a14eUL, 0x60efaa40UL, 0x7bf8b752UL, 0x72f5bc5cUL, 
    0x05bed506UL, 0x0cb3de08UL, 0x17a4c31aUL, 0x1ea9c814UL, 0x218af93eUL, 0x2887f230UL, 0x3390ef22UL, 0x3a9de42cUL, 
    0xdd063d96UL, 0xd40b3698UL, 0xcf1c2b8aUL, 0xc6112084UL, 0xf93211aeUL, 0xf03f1aa0UL, 0xeb2807b2UL, 0xe2250cbcUL, 
    0x956e65e6UL, 0x9c636ee8UL, 0x877473faUL, 0x8e7978f4UL, 0xb15a49deUL, 0xb85742d0UL, 0xa3405fc2UL, 0xaa4d54ccUL, 
    0xecdaf741UL, 0xe5d7fc4fUL, 0xfec0e15dUL, 0xf7cdea53UL, 0xc8eedb79UL, 0xc1e3d077UL, 0xdaf4cd65UL, 0xd3f9c66bUL, 
    0xa4b2af31UL, 0xadbfa43fUL, 0xb6a8b92dUL, 0xbfa5b223UL, 0x80868309UL, 0x898b8807UL, 0x929c9515UL, 0x9b919e1bUL, 
    0x7c0a47a1UL, 0x75074cafUL, 0x6e1051bdUL, 0x671d5ab3UL, 0x583e6b99UL, 0x51336097UL, 0x4a247d85UL, 0x4329768bUL, 
    0x34621fd1UL, 0x3d6f14dfUL, 0x267809cdUL, 0x2f7502c3UL, 0x105633e9UL, 0x195b38e7UL, 0x024c25f5UL, 0x0b412efbUL, 
    0xd7618c9aUL, 0xde6c8794UL, 0xc57b9a86UL, 0xcc769188UL, 0xf355a0a2UL, 0xfa58abacUL, 0xe14fb6beUL, 0xe842bdb0UL, 
    0x9f09d4eaUL, 0x9604dfe4UL, 0x8d13c2f6UL, 0x841ec9f8UL, 0xbb3df8d2UL, 0xb230f3dcUL, 0xa927eeceUL, 0xa02ae5c0UL, 
    0x47b13c7aUL, 0x4ebc3774UL, 0x55ab2a66UL, 0x5ca62168UL, 0x63851042UL, 0x6a881b4cUL, 0x719f065eUL, 0x78920d50UL, 
    0x0fd9640aUL, 0x06d46f04UL, 0x1dc37216UL, 0x14ce7918UL, 0x2bed4832UL, 0x22e0433cUL, 0x39f75e2eUL, 0x30fa5520UL, 
    0x9ab701ecUL, 0x93ba0ae2UL, 0x88ad17f0UL, 0x81a01cfeUL, 0xbe832dd4UL, 0xb78e26daUL, 0xac993bc8UL, 0xa59430c6UL, 
    0xd2df599cUL, 0xdbd25292UL, 0xc0c54f80UL, 0xc9c8448eUL, 0xf6eb75a4UL, 0xffe67eaaUL, 0xe4f163b8UL, 0xedfc68b6UL, 
    0x0a67b10cUL, 0x036aba02UL, 0x187da710UL, 0x1170ac1eUL, 0x2e539d34UL, 0x275e963aUL, 0x3c498b28UL, 0x35448026UL, 
    0x420fe97cUL, 0x4b02e272UL, 0x5015ff60UL, 0x5918f46eUL, 0x663bc544UL, 0x6f36ce4aUL, 0x7421d358UL, 0x7d2cd856UL, 
    0xa10c7a37UL, 0xa8017139UL, 0xb3166c2bUL, 0xba1b6725UL, 0x8538560fUL, 0x8c355d01UL, 0x97224013UL, 0x9e2f4b1dUL, 
    0xe9642247UL, 0xe0692949UL, 0xfb7e345bUL, 0xf2733f55UL, 0xcd500e7fUL, 0xc45d0571UL, 0xdf4a1863UL, 0xd647136dUL, 
    0x31dccad7UL, 0x38d1c1d9UL, 0x23c6dccbUL, 0x2acbd7c5UL, 0x15e8e6efUL, 0x1ce5ede1UL, 0x07f2f0f3UL, 0x0efffbfdUL, 
    0x79b492a7UL, 0x70b999a9UL, 0x6bae84bbUL, 0x62a38fb5UL, 0x5d80be9fUL, 0x548db591UL, 0x4f9aa883UL, 0x4697a38dUL
};

#endif /* ENCRYPT_ONLY */

#endif /* SMALL CODE */

static const uint32_t rcon[] = {
    0x01000000UL, 0x02000000UL, 0x04000000UL, 0x08000000UL,
    0x10000000UL, 0x20000000UL, 0x40000000UL, 0x80000000UL,
    0x1B000000UL, 0x36000000UL, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */
};

/* $Source: /cvs/libtom/libtomcrypt/src/ciphers/aes/aes_tab.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:23 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/ltc_aes/ltc_aes.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ltc_aes.h
 *  MacTomCrypt
 *
 *  InfoSec Standard Configuration
 *  Copyright 2010 Apple Inc. All rights reserved.
 *
 */

#ifndef _LTC_AES_H_
#define	_LTC_AES_H_

#include <stdint.h>
#include <stddef.h>

#if defined(__cplusplus)
extern "C"
{
#endif

typedef struct ltc_rijndael_key {
    uint32_t eK[60], dK[60];
    int Nr;
} ltc_rijndael_keysched;

/* make aes an alias */
#define ltc_aes_setup           ltc_rijndael_setup
#define ltc_aes_ecb_encrypt     ltc_rijndael_ecb_encrypt
#define ltc_aes_ecb_decrypt     ltc_rijndael_ecb_decrypt
#define ltc_aes_test            ltc_rijndael_test
#define ltc_aes_done            ltc_rijndael_done
#define ltc_aes_keysize         ltc_rijndael_keysize

#define ltc_aes_enc_setup           ltc_rijndael_enc_setup
#define ltc_aes_enc_ecb_encrypt     ltc_rijndael_enc_ecb_encrypt
#define ltc_aes_enc_keysize         ltc_rijndael_enc_keysize

int ltc_rijndael_setup(const unsigned char *key, int keylen, int num_rounds,
    ltc_rijndael_keysched *skey);
int ltc_rijndael_ecb_encrypt(const unsigned char *pt, unsigned char *ct,
    ltc_rijndael_keysched *skey);
int ltc_rijndael_ecb_decrypt(const unsigned char *ct, unsigned char *pt,
    ltc_rijndael_keysched *skey);
int ltc_rijndael_test(void);
void ltc_rijndael_done(ltc_rijndael_keysched *skey);
int ltc_rijndael_keysize(int *keysize);
int ltc_rijndael_enc_setup(const unsigned char *key, int keylen, int num_rounds,
    ltc_rijndael_keysched *skey);
int ltc_rijndael_enc_ecb_encrypt(const unsigned char *pt, unsigned char *ct,
    ltc_rijndael_keysched *skey);
void ltc_rijndael_enc_done(ltc_rijndael_keysched *skey);
int ltc_rijndael_enc_keysize(int *keysize);
extern const struct ltc_cipher_descriptor ltc_rijndael_desc, ltc_aes_desc;
extern const struct ltc_cipher_descriptor ltc_rijndael_enc_desc,
       ltc_aes_enc_desc;

#if defined(__cplusplus)
}
#endif

#endif /* _LTC_AES_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































Deleted Source/libtomcrypt/src/ciphers/rc2.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
/**********************************************************************\
* To commemorate the 1996 RSA Data Security Conference, the following  *
* code is released into the public domain by its author.  Prost!       *
*                                                                      *
* This cipher uses 16-bit words and little-endian byte ordering.       *
* I wonder which processor it was optimized for?                       *
*                                                                      *
* Thanks to CodeView, SoftIce, and D86 for helping bring this code to  *
* the public.                                                          *
\**********************************************************************/
#include <tomcrypt.h>

/**
  @file rc2.c
  Implementation of LTC_RC2
*/  

#ifdef LTC_RC2

const struct ltc_cipher_descriptor rc2_desc = {
   "rc2",
   12, 8, 128, 8, 16,
   &rc2_setup,
   &rc2_ecb_encrypt,
   &rc2_ecb_decrypt,
   &rc2_test,
   &rc2_done,
   &rc2_keysize,
    /* ECB Accelerators */
    NULL, NULL, 
    /* CBC Accelerators */
    NULL, NULL,
    /* CTR Accelerators */
    NULL, 
    /* LRW Accelerators */
    NULL, NULL,
    /* XTS Accelerators */
    NULL, NULL,
    /* CCM Accelerator */
    NULL, 
    /* GCM Accelerator */
    NULL, 
    /* OMAC Accelerator */
    NULL,
    /* XCBC Accelerator */
    NULL, 
    /* F9 Accelerator */
    NULL
};

/* 256-entry permutation table, probably derived somehow from pi */
static const unsigned char permute[256] = {
        217,120,249,196, 25,221,181,237, 40,233,253,121, 74,160,216,157,
        198,126, 55,131, 43,118, 83,142, 98, 76,100,136, 68,139,251,162,
         23,154, 89,245,135,179, 79, 19, 97, 69,109,141,  9,129,125, 50,
        189,143, 64,235,134,183,123, 11,240,149, 33, 34, 92,107, 78,130,
         84,214,101,147,206, 96,178, 28,115, 86,192, 20,167,140,241,220,
         18,117,202, 31, 59,190,228,209, 66, 61,212, 48,163, 60,182, 38,
        111,191, 14,218, 70,105,  7, 87, 39,242, 29,155,188,148, 67,  3,
        248, 17,199,246,144,239, 62,231,  6,195,213, 47,200,102, 30,215,
          8,232,234,222,128, 82,238,247,132,170,114,172, 53, 77,106, 42,
        150, 26,210,113, 90, 21, 73,116, 75,159,208, 94,  4, 24,164,236,
        194,224, 65,110, 15, 81,203,204, 36,145,175, 80,161,244,112, 57,
        153,124, 58,133, 35,184,180,122,252,  2, 54, 91, 37, 85,151, 49,
         45, 93,250,152,227,138,146,174,  5,223, 41, 16,103,108,186,201,
        211,  0,230,207,225,158,168, 44, 99, 22,  1, 63, 88,226,137,169,
         13, 56, 52, 27,171, 51,255,176,187, 72, 12, 95,185,177,205, 46,
        197,243,219, 71,229,165,156,119, 10,166, 32,104,254,127,193,173
};

 /**
    Initialize the LTC_RC2 block cipher
    @param key The symmetric key you wish to pass
    @param keylen The key length in bytes
    @param num_rounds The number of rounds desired (0 for default)
    @param skey The key in as scheduled by this function.
    @return CRYPT_OK if successful
 */
int rc2_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
{
   unsigned *xkey = skey->rc2.xkey;
   unsigned char tmp[128];
   unsigned T8, TM;
   int i, bits;

   LTC_ARGCHK(key  != NULL);
   LTC_ARGCHK(skey != NULL);

   if (keylen < 8 || keylen > 128) {
      return CRYPT_INVALID_KEYSIZE;
   }

   if (num_rounds != 0 && num_rounds != 16) {
      return CRYPT_INVALID_ROUNDS;
   }

   for (i = 0; i < keylen; i++) {
       tmp[i] = key[i] & 255;
   }

    /* Phase 1: Expand input key to 128 bytes */
    if (keylen < 128) {
        for (i = keylen; i < 128; i++) {
            tmp[i] = permute[(tmp[i - 1] + tmp[i - keylen]) & 255];
        }
    }
    
    /* Phase 2 - reduce effective key size to "bits" */
    bits = keylen<<3;
    T8   = (unsigned)(bits+7)>>3;
    TM   = (255 >> (unsigned)(7 & -bits));
    tmp[128 - T8] = permute[tmp[128 - T8] & TM];
    for (i = 127 - T8; i >= 0; i--) {
        tmp[i] = permute[tmp[i + 1] ^ tmp[i + T8]];
    }

    /* Phase 3 - copy to xkey in little-endian order */
    for (i = 0; i < 64; i++) {
        xkey[i] =  (unsigned)tmp[2*i] + ((unsigned)tmp[2*i+1] << 8);
    }        

#ifdef LTC_CLEAN_STACK
    zeromem(tmp, sizeof(tmp));
#endif
    
    return CRYPT_OK;
}

/**********************************************************************\
* Encrypt an 8-byte block of plaintext using the given key.            *
\**********************************************************************/
/**
  Encrypts a block of text with LTC_RC2
  @param pt The input plaintext (8 bytes)
  @param ct The output ciphertext (8 bytes)
  @param skey The key as scheduled
  @return CRYPT_OK if successful
*/
#ifdef LTC_CLEAN_STACK
static int _rc2_ecb_encrypt( const unsigned char *pt,
                            unsigned char *ct,
                            symmetric_key *skey)
#else
int rc2_ecb_encrypt( const unsigned char *pt,
                            unsigned char *ct,
                            symmetric_key *skey)
#endif
{
    unsigned *xkey;
    unsigned x76, x54, x32, x10, i;

    LTC_ARGCHK(pt  != NULL);
    LTC_ARGCHK(ct != NULL);
    LTC_ARGCHK(skey   != NULL);

    xkey = skey->rc2.xkey;

    x76 = ((unsigned)pt[7] << 8) + (unsigned)pt[6];
    x54 = ((unsigned)pt[5] << 8) + (unsigned)pt[4];
    x32 = ((unsigned)pt[3] << 8) + (unsigned)pt[2];
    x10 = ((unsigned)pt[1] << 8) + (unsigned)pt[0];

    for (i = 0; i < 16; i++) {
        x10 = (x10 + (x32 & ~x76) + (x54 & x76) + xkey[4*i+0]) & 0xFFFF;
        x10 = ((x10 << 1) | (x10 >> 15));

        x32 = (x32 + (x54 & ~x10) + (x76 & x10) + xkey[4*i+1]) & 0xFFFF;
        x32 = ((x32 << 2) | (x32 >> 14));

        x54 = (x54 + (x76 & ~x32) + (x10 & x32) + xkey[4*i+2]) & 0xFFFF;
        x54 = ((x54 << 3) | (x54 >> 13));

        x76 = (x76 + (x10 & ~x54) + (x32 & x54) + xkey[4*i+3]) & 0xFFFF;
        x76 = ((x76 << 5) | (x76 >> 11));

        if (i == 4 || i == 10) {
            x10 = (x10 + xkey[x76 & 63]) & 0xFFFF;
            x32 = (x32 + xkey[x10 & 63]) & 0xFFFF;
            x54 = (x54 + xkey[x32 & 63]) & 0xFFFF;
            x76 = (x76 + xkey[x54 & 63]) & 0xFFFF;
        }
    }

    ct[0] = (unsigned char)x10;
    ct[1] = (unsigned char)(x10 >> 8);
    ct[2] = (unsigned char)x32;
    ct[3] = (unsigned char)(x32 >> 8);
    ct[4] = (unsigned char)x54;
    ct[5] = (unsigned char)(x54 >> 8);
    ct[6] = (unsigned char)x76;
    ct[7] = (unsigned char)(x76 >> 8);
 
    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
int rc2_ecb_encrypt( const unsigned char *pt,
                            unsigned char *ct,
                            symmetric_key *skey)
{
    int err = _rc2_ecb_encrypt(pt, ct, skey);
    burn_stack(sizeof(unsigned *) + sizeof(unsigned) * 5);
    return err;
}
#endif

/**********************************************************************\
* Decrypt an 8-byte block of ciphertext using the given key.           *
\**********************************************************************/
/**
  Decrypts a block of text with LTC_RC2
  @param ct The input ciphertext (8 bytes)
  @param pt The output plaintext (8 bytes)
  @param skey The key as scheduled 
  @return CRYPT_OK if successful
*/
#ifdef LTC_CLEAN_STACK
static int _rc2_ecb_decrypt( const unsigned char *ct,
                            unsigned char *pt,
                            symmetric_key *skey)
#else
int rc2_ecb_decrypt( const unsigned char *ct,
                            unsigned char *pt,
                            symmetric_key *skey)
#endif
{
    unsigned x76, x54, x32, x10;
    unsigned *xkey;
    int i;

    LTC_ARGCHK(pt  != NULL);
    LTC_ARGCHK(ct != NULL);
    LTC_ARGCHK(skey   != NULL);

    xkey = skey->rc2.xkey;

    x76 = ((unsigned)ct[7] << 8) + (unsigned)ct[6];
    x54 = ((unsigned)ct[5] << 8) + (unsigned)ct[4];
    x32 = ((unsigned)ct[3] << 8) + (unsigned)ct[2];
    x10 = ((unsigned)ct[1] << 8) + (unsigned)ct[0];

    for (i = 15; i >= 0; i--) {
        if (i == 4 || i == 10) {
            x76 = (x76 - xkey[x54 & 63]) & 0xFFFF;
            x54 = (x54 - xkey[x32 & 63]) & 0xFFFF;
            x32 = (x32 - xkey[x10 & 63]) & 0xFFFF;
            x10 = (x10 - xkey[x76 & 63]) & 0xFFFF;
        }

        x76 = ((x76 << 11) | (x76 >> 5));
        x76 = (x76 - ((x10 & ~x54) + (x32 & x54) + xkey[4*i+3])) & 0xFFFF;

        x54 = ((x54 << 13) | (x54 >> 3));
        x54 = (x54 - ((x76 & ~x32) + (x10 & x32) + xkey[4*i+2])) & 0xFFFF;

        x32 = ((x32 << 14) | (x32 >> 2));
        x32 = (x32 - ((x54 & ~x10) + (x76 & x10) + xkey[4*i+1])) & 0xFFFF;

        x10 = ((x10 << 15) | (x10 >> 1));
        x10 = (x10 - ((x32 & ~x76) + (x54 & x76) + xkey[4*i+0])) & 0xFFFF;
    }

    pt[0] = (unsigned char)x10;
    pt[1] = (unsigned char)(x10 >> 8);
    pt[2] = (unsigned char)x32;
    pt[3] = (unsigned char)(x32 >> 8);
    pt[4] = (unsigned char)x54;
    pt[5] = (unsigned char)(x54 >> 8);
    pt[6] = (unsigned char)x76;
    pt[7] = (unsigned char)(x76 >> 8);

    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
int rc2_ecb_decrypt( const unsigned char *ct,
                            unsigned char *pt,
                            symmetric_key *skey)
{
    int err = _rc2_ecb_decrypt(ct, pt, skey);
    burn_stack(sizeof(unsigned *) + sizeof(unsigned) * 4 + sizeof(int));
    return err;
}
#endif

/**
  Performs a self-test of the LTC_RC2 block cipher
  @return CRYPT_OK if functional, CRYPT_NOP if self-test has been disabled
*/
int rc2_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
   static const struct {
        int keylen;
        unsigned char key[16], pt[8], ct[8];
   } tests[] = {

   { 8,
     { 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
     { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 },
     { 0x30, 0x64, 0x9e, 0xdf, 0x9b, 0xe7, 0xd2, 0xc2 }

   },
   { 16,
     { 0x88, 0xbc, 0xa9, 0x0e, 0x90, 0x87, 0x5a, 0x7f,
       0x0f, 0x79, 0xc3, 0x84, 0x62, 0x7b, 0xaf, 0xb2 },
     { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
     { 0x22, 0x69, 0x55, 0x2a, 0xb0, 0xf8, 0x5c, 0xa6 }
   }
  };
    int x, y, err;
    symmetric_key skey;
    unsigned char tmp[2][8];

    for (x = 0; x < (int)(sizeof(tests) / sizeof(tests[0])); x++) {
        zeromem(tmp, sizeof(tmp));
        if ((err = rc2_setup(tests[x].key, tests[x].keylen, 0, &skey)) != CRYPT_OK) {
           return err;
        }
        
        rc2_ecb_encrypt(tests[x].pt, tmp[0], &skey);
        rc2_ecb_decrypt(tmp[0], tmp[1], &skey);
        
        if (XMEMCMP(tmp[0], tests[x].ct, 8) != 0 || XMEMCMP(tmp[1], tests[x].pt, 8) != 0) {
           return CRYPT_FAIL_TESTVECTOR;
        }

      /* now see if we can encrypt all zero bytes 1000 times, decrypt and come back where we started */
      for (y = 0; y < 8; y++) tmp[0][y] = 0;
      for (y = 0; y < 1000; y++) rc2_ecb_encrypt(tmp[0], tmp[0], &skey);
      for (y = 0; y < 1000; y++) rc2_ecb_decrypt(tmp[0], tmp[0], &skey);
      for (y = 0; y < 8; y++) if (tmp[0][y] != 0) return CRYPT_FAIL_TESTVECTOR;
    }
    return CRYPT_OK;
   #endif
}

/** Terminate the context 
   @param skey    The scheduled key
*/
void rc2_done(symmetric_key *skey)
{
}

/**
  Gets suitable key size
  @param keysize [in/out] The length of the recommended key (in bytes).  This function will store the suitable size back in this variable.
  @return CRYPT_OK if the input key size is acceptable.
*/
int rc2_keysize(int *keysize)
{
   LTC_ARGCHK(keysize != NULL);
   if (*keysize < 8) {
       return CRYPT_INVALID_KEYSIZE;
   } else if (*keysize > 128) {
       *keysize = 128;
   }
   return CRYPT_OK;
}

#endif




/* $Source: /cvs/libtom/libtomcrypt/src/ciphers/rc2.c,v $ */
/* $Revision: 1.14 $ */
/* $Date: 2007/05/12 14:13:00 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/ciphers/rc5.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */

/**
   @file rc5.c
   LTC_RC5 code by Tom St Denis 
*/

#include "tomcrypt.h"

#ifdef LTC_RC5

const struct ltc_cipher_descriptor rc5_desc =
{
    "rc5",
    2,
    8, 128, 8, 12,
    &rc5_setup,
    &rc5_ecb_encrypt,
    &rc5_ecb_decrypt,
    &rc5_test,
    &rc5_done,
    &rc5_keysize,
    /* ECB Accelerators */
    NULL, NULL, 
    /* CBC Accelerators */
    NULL, NULL,
    /* CTR Accelerators */
    NULL, 
    /* LRW Accelerators */
    NULL, NULL,
    /* XTS Accelerators */
    NULL, NULL,
    /* CCM Accelerator */
    NULL, 
    /* GCM Accelerator */
    NULL, 
    /* OMAC Accelerator */
    NULL,
    /* XCBC Accelerator */
    NULL, 
    /* F9 Accelerator */
    NULL
};

static const ulong32 stab[50] = {
0xb7e15163UL, 0x5618cb1cUL, 0xf45044d5UL, 0x9287be8eUL, 0x30bf3847UL, 0xcef6b200UL, 0x6d2e2bb9UL, 0x0b65a572UL,
0xa99d1f2bUL, 0x47d498e4UL, 0xe60c129dUL, 0x84438c56UL, 0x227b060fUL, 0xc0b27fc8UL, 0x5ee9f981UL, 0xfd21733aUL,
0x9b58ecf3UL, 0x399066acUL, 0xd7c7e065UL, 0x75ff5a1eUL, 0x1436d3d7UL, 0xb26e4d90UL, 0x50a5c749UL, 0xeedd4102UL,
0x8d14babbUL, 0x2b4c3474UL, 0xc983ae2dUL, 0x67bb27e6UL, 0x05f2a19fUL, 0xa42a1b58UL, 0x42619511UL, 0xe0990ecaUL,
0x7ed08883UL, 0x1d08023cUL, 0xbb3f7bf5UL, 0x5976f5aeUL, 0xf7ae6f67UL, 0x95e5e920UL, 0x341d62d9UL, 0xd254dc92UL,
0x708c564bUL, 0x0ec3d004UL, 0xacfb49bdUL, 0x4b32c376UL, 0xe96a3d2fUL, 0x87a1b6e8UL, 0x25d930a1UL, 0xc410aa5aUL,
0x62482413UL, 0x007f9dccUL
};

 /**
    Initialize the LTC_RC5 block cipher
    @param key The symmetric key you wish to pass
    @param keylen The key length in bytes
    @param num_rounds The number of rounds desired (0 for default)
    @param skey The key in as scheduled by this function.
    @return CRYPT_OK if successful
 */
#ifdef LTC_CLEAN_STACK
static int _rc5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
#else
int rc5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
#endif
{
    ulong32 L[64], *S, A, B, i, j, v, s, t, l;

    LTC_ARGCHK(skey != NULL);
    LTC_ARGCHK(key  != NULL);
    
    /* test parameters */
    if (num_rounds == 0) { 
       num_rounds = rc5_desc.default_rounds;
    }

    if (num_rounds < 12 || num_rounds > 24) { 
       return CRYPT_INVALID_ROUNDS;
    }

    /* key must be between 64 and 1024 bits */
    if (keylen < 8 || keylen > 128) {
       return CRYPT_INVALID_KEYSIZE;
    }
    
    skey->rc5.rounds = num_rounds;
    S = skey->rc5.K;

    /* copy the key into the L array */
    for (A = i = j = 0; i < (ulong32)keylen; ) { 
        A = (A << 8) | ((ulong32)(key[i++] & 255));
        if ((i & 3) == 0) {
           L[j++] = BSWAP(A);
           A = 0;
        }
    }

    if ((keylen & 3) != 0) { 
       A <<= (ulong32)((8 * (4 - (keylen&3)))); 
       L[j++] = BSWAP(A);
    }

    /* setup the S array */
    t = (ulong32)(2 * (num_rounds + 1));
    XMEMCPY(S, stab, t * sizeof(*S));

    /* mix buffer */
    s = 3 * MAX(t, j);
    l = j;
    for (A = B = i = j = v = 0; v < s; v++) { 
        A = S[i] = ROLc(S[i] + A + B, 3);
        B = L[j] = ROL(L[j] + A + B, (A+B));
        if (++i == t) { i = 0; }
        if (++j == l) { j = 0; }
    }
    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
int rc5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey)
{
   int x;
   x = _rc5_setup(key, keylen, num_rounds, skey);
   burn_stack(sizeof(ulong32) * 122 + sizeof(int));
   return x;
}
#endif

/**
  Encrypts a block of text with LTC_RC5
  @param pt The input plaintext (8 bytes)
  @param ct The output ciphertext (8 bytes)
  @param skey The key as scheduled
  @return CRYPT_OK if successful
*/
#ifdef LTC_CLEAN_STACK
static int _rc5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
#else
int rc5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
#endif
{
   ulong32 A, B, *K;
   int r;
   LTC_ARGCHK(skey != NULL);
   LTC_ARGCHK(pt   != NULL);
   LTC_ARGCHK(ct   != NULL);

   LOAD32L(A, &pt[0]);
   LOAD32L(B, &pt[4]);
   A += skey->rc5.K[0];
   B += skey->rc5.K[1];
   K  = skey->rc5.K + 2;
   
   if ((skey->rc5.rounds & 1) == 0) {
      for (r = 0; r < skey->rc5.rounds; r += 2) {
          A = ROL(A ^ B, B) + K[0];
          B = ROL(B ^ A, A) + K[1];
          A = ROL(A ^ B, B) + K[2];
          B = ROL(B ^ A, A) + K[3];
          K += 4;
      }
   } else {
      for (r = 0; r < skey->rc5.rounds; r++) {
          A = ROL(A ^ B, B) + K[0];
          B = ROL(B ^ A, A) + K[1];
          K += 2;
      }
   }
   STORE32L(A, &ct[0]);
   STORE32L(B, &ct[4]);

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
int rc5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey)
{
   int err = _rc5_ecb_encrypt(pt, ct, skey);
   burn_stack(sizeof(ulong32) * 2 + sizeof(int));
   return err;
}
#endif

/**
  Decrypts a block of text with LTC_RC5
  @param ct The input ciphertext (8 bytes)
  @param pt The output plaintext (8 bytes)
  @param skey The key as scheduled 
  @return CRYPT_OK if successful
*/
#ifdef LTC_CLEAN_STACK
static int _rc5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
#else
int rc5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
#endif
{
   ulong32 A, B, *K;
   int r;
   LTC_ARGCHK(skey != NULL);
   LTC_ARGCHK(pt   != NULL);
   LTC_ARGCHK(ct   != NULL);

   LOAD32L(A, &ct[0]);
   LOAD32L(B, &ct[4]);
   K = skey->rc5.K + (skey->rc5.rounds << 1);
   
   if ((skey->rc5.rounds & 1) == 0) {
       K -= 2;
       for (r = skey->rc5.rounds - 1; r >= 0; r -= 2) {
          B = ROR(B - K[3], A) ^ A;
          A = ROR(A - K[2], B) ^ B;
          B = ROR(B - K[1], A) ^ A;
          A = ROR(A - K[0], B) ^ B;
          K -= 4;
        }
   } else {
      for (r = skey->rc5.rounds - 1; r >= 0; r--) {
          B = ROR(B - K[1], A) ^ A;
          A = ROR(A - K[0], B) ^ B;
          K -= 2;
      }
   }
   A -= skey->rc5.K[0];
   B -= skey->rc5.K[1];
   STORE32L(A, &pt[0]);
   STORE32L(B, &pt[4]);

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
int rc5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey)
{
   int err = _rc5_ecb_decrypt(ct, pt, skey);
   burn_stack(sizeof(ulong32) * 2 + sizeof(int));
   return err;
}
#endif

/**
  Performs a self-test of the LTC_RC5 block cipher
  @return CRYPT_OK if functional, CRYPT_NOP if self-test has been disabled
*/
int rc5_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
   static const struct {
       unsigned char key[16], pt[8], ct[8];
   } tests[] = {
   {
       { 0x91, 0x5f, 0x46, 0x19, 0xbe, 0x41, 0xb2, 0x51,
         0x63, 0x55, 0xa5, 0x01, 0x10, 0xa9, 0xce, 0x91 },
       { 0x21, 0xa5, 0xdb, 0xee, 0x15, 0x4b, 0x8f, 0x6d },
       { 0xf7, 0xc0, 0x13, 0xac, 0x5b, 0x2b, 0x89, 0x52 }
   },
   {
       { 0x78, 0x33, 0x48, 0xe7, 0x5a, 0xeb, 0x0f, 0x2f,
         0xd7, 0xb1, 0x69, 0xbb, 0x8d, 0xc1, 0x67, 0x87 },
       { 0xF7, 0xC0, 0x13, 0xAC, 0x5B, 0x2B, 0x89, 0x52 },
       { 0x2F, 0x42, 0xB3, 0xB7, 0x03, 0x69, 0xFC, 0x92 }
   },
   {
       { 0xDC, 0x49, 0xdb, 0x13, 0x75, 0xa5, 0x58, 0x4f,
         0x64, 0x85, 0xb4, 0x13, 0xb5, 0xf1, 0x2b, 0xaf },
       { 0x2F, 0x42, 0xB3, 0xB7, 0x03, 0x69, 0xFC, 0x92 },
       { 0x65, 0xc1, 0x78, 0xb2, 0x84, 0xd1, 0x97, 0xcc }
   }
   };
   unsigned char tmp[2][8];
   int x, y, err;
   symmetric_key key;

   for (x = 0; x < (int)(sizeof(tests) / sizeof(tests[0])); x++) {
      /* setup key */
      if ((err = rc5_setup(tests[x].key, 16, 12, &key)) != CRYPT_OK) {
         return err;
      }

      /* encrypt and decrypt */
      rc5_ecb_encrypt(tests[x].pt, tmp[0], &key);
      rc5_ecb_decrypt(tmp[0], tmp[1], &key);

      /* compare */
      if (XMEMCMP(tmp[0], tests[x].ct, 8) != 0 || XMEMCMP(tmp[1], tests[x].pt, 8) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }

      /* now see if we can encrypt all zero bytes 1000 times, decrypt and come back where we started */
      for (y = 0; y < 8; y++) tmp[0][y] = 0;
      for (y = 0; y < 1000; y++) rc5_ecb_encrypt(tmp[0], tmp[0], &key);
      for (y = 0; y < 1000; y++) rc5_ecb_decrypt(tmp[0], tmp[0], &key);
      for (y = 0; y < 8; y++) if (tmp[0][y] != 0) return CRYPT_FAIL_TESTVECTOR;
   }
   return CRYPT_OK;
  #endif
}

/** Terminate the context 
   @param skey    The scheduled key
*/
void rc5_done(symmetric_key *skey)
{
}

/**
  Gets suitable key size
  @param keysize [in/out] The length of the recommended key (in bytes).  This function will store the suitable size back in this variable.
  @return CRYPT_OK if the input key size is acceptable.
*/
int rc5_keysize(int *keysize)
{
   LTC_ARGCHK(keysize != NULL);
   if (*keysize < 8) {
      return CRYPT_INVALID_KEYSIZE;
   } else if (*keysize > 128) {
      *keysize = 128;
   }
   return CRYPT_OK;
}

#endif




/* $Source: /cvs/libtom/libtomcrypt/src/ciphers/rc5.c,v $ */
/* $Revision: 1.14 $ */
/* $Date: 2007/05/12 14:13:00 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/helper/hash_file.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/** 
  @file hash_file.c
  Hash a file, Tom St Denis
*/

/**
  @param hash   The index of the hash desired
  @param fname  The name of the file you wish to hash
  @param out    [out] The destination of the digest
  @param outlen [in/out] The max size and resulting size of the message digest
  @result CRYPT_OK if successful
*/
int hash_file(int hash, const char *fname, unsigned char *out, unsigned long *outlen)
{
#ifdef LTC_NO_FILE
    return CRYPT_NOP;
#else
    FILE *in;
    int err;
    LTC_ARGCHK(fname  != NULL);
    LTC_ARGCHK(out    != NULL);
    LTC_ARGCHK(outlen != NULL);

    if ((err = hash_is_valid(hash)) != CRYPT_OK) {
        return err;
    }

    in = fopen(fname, "rb");
    if (in == NULL) { 
       return CRYPT_FILE_NOTFOUND;
    }

    err = hash_filehandle(hash, in, out, outlen);
    if (fclose(in) != 0) {
       return CRYPT_ERROR;
    }

    return err;
#endif
}


/* $Source: /cvs/libtom/libtomcrypt/src/hashes/helper/hash_file.c,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2006/12/28 01:27:23 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































Deleted Source/libtomcrypt/src/hashes/helper/hash_filehandle.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file hash_filehandle.c
   Hash open files, Tom St Denis
*/

/** 
  Hash data from an open file handle.  
  @param hash   The index of the hash you want to use
  @param in     The FILE* handle of the file you want to hash
  @param out    [out] The destination of the digest
  @param outlen [in/out] The max size and resulting size of the digest
  @result CRYPT_OK if successful   
*/
int hash_filehandle(int hash, FILE *in, unsigned char *out, unsigned long *outlen)
{
#ifdef LTC_NO_FILE
    return CRYPT_NOP;
#else
    hash_state md;
    unsigned char buf[512];
    size_t x;
    int err;

    LTC_ARGCHK(out    != NULL);
    LTC_ARGCHK(outlen != NULL);
    LTC_ARGCHK(in     != NULL);

    if ((err = hash_is_valid(hash)) != CRYPT_OK) {
        return err;
    }

    if (*outlen < hash_descriptor[hash].hashsize) {
       *outlen = hash_descriptor[hash].hashsize;
       return CRYPT_BUFFER_OVERFLOW;
    }
    if ((err = hash_descriptor[hash].init(&md)) != CRYPT_OK) {
       return err;
    }

    *outlen = hash_descriptor[hash].hashsize;
    do {
        x = fread(buf, 1, sizeof(buf), in);
        if ((err = hash_descriptor[hash].process(&md, buf, x)) != CRYPT_OK) {
           return err;
        }
    } while (x == sizeof(buf));
    err = hash_descriptor[hash].done(&md, out);

#ifdef LTC_CLEAN_STACK
    zeromem(buf, sizeof(buf));
#endif
    return err;
#endif
}


/* $Source: /cvs/libtom/libtomcrypt/src/hashes/helper/hash_filehandle.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:23 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































Deleted Source/libtomcrypt/src/hashes/helper/hash_memory.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file hash_memory.c
  Hash memory helper, Tom St Denis
*/

/**
  Hash a block of memory and store the digest.
  @param hash   The index of the hash you wish to use
  @param in     The data you wish to hash
  @param inlen  The length of the data to hash (octets)
  @param out    [out] Where to store the digest
  @param outlen [in/out] Max size and resulting size of the digest
  @return CRYPT_OK if successful
*/
int hash_memory(int hash, const unsigned char *in, unsigned long inlen, unsigned char *out, unsigned long *outlen)
{
    hash_state *md;
    int err;

    LTC_ARGCHK(in     != NULL);
    LTC_ARGCHK(out    != NULL);
    LTC_ARGCHK(outlen != NULL);

    if ((err = hash_is_valid(hash)) != CRYPT_OK) {
        return err;
    }

    if (*outlen < hash_descriptor[hash].hashsize) {
       *outlen = hash_descriptor[hash].hashsize;
       return CRYPT_BUFFER_OVERFLOW;
    }

    md = XMALLOC(sizeof(hash_state));
    if (md == NULL) {
       return CRYPT_MEM;
    }

    if ((err = hash_descriptor[hash].init(md)) != CRYPT_OK) {
       goto LBL_ERR;
    }
    if ((err = hash_descriptor[hash].process(md, in, inlen)) != CRYPT_OK) {
       goto LBL_ERR;
    }
    err = hash_descriptor[hash].done(md, out);
    *outlen = hash_descriptor[hash].hashsize;
LBL_ERR:
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
    XFREE(md);

    return err;
}

/* $Source: /cvs/libtom/libtomcrypt/src/hashes/helper/hash_memory.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:23 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































Deleted Source/libtomcrypt/src/hashes/helper/hash_memory_multi.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"
#include <stdarg.h>
/**
  @file hash_memory_multi.c
  Hash (multiple buffers) memory helper, Tom St Denis
*/

/**
  Hash multiple (non-adjacent) blocks of memory at once.  
  @param hash   The index of the hash you wish to use
  @param out    [out] Where to store the digest
  @param outlen [in/out] Max size and resulting size of the digest
  @param in     The data you wish to hash
  @param inlen  The length of the data to hash (octets)
  @param ...    tuples of (data,len) pairs to hash, terminated with a (NULL,x) (x=don't care)
  @return CRYPT_OK if successful
*/  
int hash_memory_multi(int hash, unsigned char *out, unsigned long *outlen,
                      const unsigned char *in, unsigned long inlen, ...)
{
    hash_state          *md;
    int                  err;
    va_list              args;
    const unsigned char *curptr;
    unsigned long        curlen;

    LTC_ARGCHK(in     != NULL);
    LTC_ARGCHK(out    != NULL);
    LTC_ARGCHK(outlen != NULL);

    if ((err = hash_is_valid(hash)) != CRYPT_OK) {
        return err;
    }

    if (*outlen < hash_descriptor[hash].hashsize) {
       *outlen = hash_descriptor[hash].hashsize;
       return CRYPT_BUFFER_OVERFLOW;
    }

    md = XMALLOC(sizeof(hash_state));
    if (md == NULL) {
       return CRYPT_MEM;
    }

    if ((err = hash_descriptor[hash].init(md)) != CRYPT_OK) {
       goto LBL_ERR;
    }

    va_start(args, inlen);
    curptr = in; 
    curlen = inlen;
    for (;;) {
       /* process buf */
       if ((err = hash_descriptor[hash].process(md, curptr, curlen)) != CRYPT_OK) {
          goto LBL_ERR;
       }
       /* step to next */
       curptr = va_arg(args, const unsigned char*);
       if (curptr == NULL) {
          break;
       }
       curlen = va_arg(args, unsigned long);
    }
    err = hash_descriptor[hash].done(md, out);
    *outlen = hash_descriptor[hash].hashsize;
LBL_ERR:
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
    XFREE(md);
    va_end(args);
    return err;
}

/* $Source: /cvs/libtom/libtomcrypt/src/hashes/helper/hash_memory_multi.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:23 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































Deleted Source/libtomcrypt/src/hashes/md2.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @param md2.c
   LTC_MD2 (RFC 1319) hash function implementation by Tom St Denis 
*/

#ifdef LTC_MD2

const struct ltc_hash_descriptor md2_desc =
{
    "md2",
    7,
    16,
    16,

    /* OID */
   { 1, 2, 840, 113549, 2, 2,  },
   6,

    &md2_init,
    &md2_process,
    &md2_done,
    &md2_test,
    NULL
};

static const unsigned char PI_SUBST[256] = {
  41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6,
  19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188,
  76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24,
  138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251,
  245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63,
  148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50,
  39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165,
  181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210,
  150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157,
  112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27,
  96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15,
  85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197,
  234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65,
  129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123,
  8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233,
  203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228,
  166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237,
  31, 26, 219, 153, 141, 51, 159, 17, 131, 20
};

/* adds 16 bytes to the checksum */
static void md2_update_chksum(hash_state *md)
{
   int j;
   unsigned char L;
   L = md->md2.chksum[15];
   for (j = 0; j < 16; j++) {

/* caution, the RFC says its "C[j] = S[M[i*16+j] xor L]" but the reference source code [and test vectors] say 
   otherwise.
*/
       L = (md->md2.chksum[j] ^= PI_SUBST[(int)(md->md2.buf[j] ^ L)] & 255);
   }
}

static void md2_compress(hash_state *md)
{
   int j, k;
   unsigned char t;
   
   /* copy block */
   for (j = 0; j < 16; j++) {
       md->md2.X[16+j] = md->md2.buf[j];
       md->md2.X[32+j] = md->md2.X[j] ^ md->md2.X[16+j];
   }

   t = (unsigned char)0;

   /* do 18 rounds */
   for (j = 0; j < 18; j++) {
       for (k = 0; k < 48; k++) {
           t = (md->md2.X[k] ^= PI_SUBST[(int)(t & 255)]);
       }
       t = (t + (unsigned char)j) & 255;
   }
}

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int md2_init(hash_state *md)
{
   LTC_ARGCHK(md != NULL);

   /* LTC_MD2 uses a zero'ed state... */
   zeromem(md->md2.X, sizeof(md->md2.X));
   zeromem(md->md2.chksum, sizeof(md->md2.chksum));
   zeromem(md->md2.buf, sizeof(md->md2.buf));
   md->md2.curlen = 0;
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
int md2_process(hash_state *md, const unsigned char *in, unsigned long inlen)
{
    unsigned long n;
    LTC_ARGCHK(md != NULL);
    LTC_ARGCHK(in != NULL);
    if (md-> md2 .curlen > sizeof(md-> md2 .buf)) {                            
       return CRYPT_INVALID_ARG;                                                           
    }                                                                                       
    while (inlen > 0) {
        n = MIN(inlen, (16 - md->md2.curlen));
        XMEMCPY(md->md2.buf + md->md2.curlen, in, (size_t)n);
        md->md2.curlen += n;
        in             += n;
        inlen          -= n;

        /* is 16 bytes full? */
        if (md->md2.curlen == 16) {
            md2_compress(md);
            md2_update_chksum(md);
            md->md2.curlen = 0;
        }
    }
    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (16 bytes)
   @return CRYPT_OK if successful
*/
int md2_done(hash_state * md, unsigned char *out)
{
    unsigned long i, k;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    if (md->md2.curlen >= sizeof(md->md2.buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* pad the message */
    k = 16 - md->md2.curlen;
    for (i = md->md2.curlen; i < 16; i++) {
        md->md2.buf[i] = (unsigned char)k;
    }

    /* hash and update */
    md2_compress(md);
    md2_update_chksum(md);

    /* hash checksum */
    XMEMCPY(md->md2.buf, md->md2.chksum, 16);
    md2_compress(md);

    /* output is lower 16 bytes of X */
    XMEMCPY(out, md->md2.X, 16);

#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int md2_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
   static const struct {
        char *msg;
        unsigned char md[16];
   } tests[] = {
      { "",
        {0x83,0x50,0xe5,0xa3,0xe2,0x4c,0x15,0x3d,
         0xf2,0x27,0x5c,0x9f,0x80,0x69,0x27,0x73
        }
      },
      { "a",
        {0x32,0xec,0x01,0xec,0x4a,0x6d,0xac,0x72,
         0xc0,0xab,0x96,0xfb,0x34,0xc0,0xb5,0xd1
        }
      },
      { "message digest",
        {0xab,0x4f,0x49,0x6b,0xfb,0x2a,0x53,0x0b,
         0x21,0x9f,0xf3,0x30,0x31,0xfe,0x06,0xb0
        }
      },
      { "abcdefghijklmnopqrstuvwxyz",
        {0x4e,0x8d,0xdf,0xf3,0x65,0x02,0x92,0xab,
         0x5a,0x41,0x08,0xc3,0xaa,0x47,0x94,0x0b
        }
      },
      { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
        {0xda,0x33,0xde,0xf2,0xa4,0x2d,0xf1,0x39,
         0x75,0x35,0x28,0x46,0xc3,0x03,0x38,0xcd
        }
      },
      { "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
        {0xd5,0x97,0x6f,0x79,0xd8,0x3d,0x3a,0x0d,
         0xc9,0x80,0x6c,0x3c,0x66,0xf3,0xef,0xd8
        }
      }
   };
   int i;
   hash_state md;
   unsigned char buf[16];

   for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
       md2_init(&md);
       md2_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
       md2_done(&md, buf);
       if (XMEMCMP(buf, tests[i].md, 16) != 0) {
          return CRYPT_FAIL_TESTVECTOR;
       }
   }
   return CRYPT_OK;        
  #endif
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/hashes/md2.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/md4.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @param md4.c
   Submitted by Dobes Vandermeer  (dobes@smartt.com) 
*/

#ifdef LTC_MD4

const struct ltc_hash_descriptor md4_desc =
{
    "md4",
    6,
    16,
    64,
 
    /* OID */
   { 1, 2, 840, 113549, 2, 4,  },
   6,

    &md4_init,
    &md4_process,
    &md4_done,
    &md4_test,
    NULL
};

#define S11 3
#define S12 7
#define S13 11
#define S14 19
#define S21 3
#define S22 5
#define S23 9
#define S24 13
#define S31 3
#define S32 9
#define S33 11
#define S34 15

/* F, G and H are basic LTC_MD4 functions. */
#define F(x, y, z) (z ^ (x & (y ^ z)))
#define G(x, y, z) ((x & y) | (z & (x | y)))
#define H(x, y, z) ((x) ^ (y) ^ (z))

/* ROTATE_LEFT rotates x left n bits. */
#define ROTATE_LEFT(x, n) ROLc(x, n)

/* FF, GG and HH are transformations for rounds 1, 2 and 3 */ 
/* Rotation is separate from addition to prevent recomputation */ 

#define FF(a, b, c, d, x, s) { \
    (a) += F ((b), (c), (d)) + (x); \
    (a) = ROTATE_LEFT ((a), (s)); \
  }
#define GG(a, b, c, d, x, s) { \
    (a) += G ((b), (c), (d)) + (x) + 0x5a827999UL; \
    (a) = ROTATE_LEFT ((a), (s)); \
  }
#define HH(a, b, c, d, x, s) { \
    (a) += H ((b), (c), (d)) + (x) + 0x6ed9eba1UL; \
    (a) = ROTATE_LEFT ((a), (s)); \
  }

#ifdef LTC_CLEAN_STACK
static int _md4_compress(hash_state *md, unsigned char *buf)
#else
static int  md4_compress(hash_state *md, unsigned char *buf)
#endif
{
    ulong32 x[16], a, b, c, d;
    int i;

    /* copy state */
    a = md->md4.state[0];
    b = md->md4.state[1];
    c = md->md4.state[2];
    d = md->md4.state[3];

    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LOAD32L(x[i], buf + (4*i));
    }
 
    /* Round 1 */ 
    FF (a, b, c, d, x[ 0], S11); /* 1 */ 
    FF (d, a, b, c, x[ 1], S12); /* 2 */ 
    FF (c, d, a, b, x[ 2], S13); /* 3 */ 
    FF (b, c, d, a, x[ 3], S14); /* 4 */ 
    FF (a, b, c, d, x[ 4], S11); /* 5 */ 
    FF (d, a, b, c, x[ 5], S12); /* 6 */ 
    FF (c, d, a, b, x[ 6], S13); /* 7 */ 
    FF (b, c, d, a, x[ 7], S14); /* 8 */ 
    FF (a, b, c, d, x[ 8], S11); /* 9 */ 
    FF (d, a, b, c, x[ 9], S12); /* 10 */
    FF (c, d, a, b, x[10], S13); /* 11 */ 
    FF (b, c, d, a, x[11], S14); /* 12 */
    FF (a, b, c, d, x[12], S11); /* 13 */
    FF (d, a, b, c, x[13], S12); /* 14 */ 
    FF (c, d, a, b, x[14], S13); /* 15 */ 
    FF (b, c, d, a, x[15], S14); /* 16 */ 
    
    /* Round 2 */ 
    GG (a, b, c, d, x[ 0], S21); /* 17 */ 
    GG (d, a, b, c, x[ 4], S22); /* 18 */ 
    GG (c, d, a, b, x[ 8], S23); /* 19 */ 
    GG (b, c, d, a, x[12], S24); /* 20 */ 
    GG (a, b, c, d, x[ 1], S21); /* 21 */ 
    GG (d, a, b, c, x[ 5], S22); /* 22 */ 
    GG (c, d, a, b, x[ 9], S23); /* 23 */ 
    GG (b, c, d, a, x[13], S24); /* 24 */ 
    GG (a, b, c, d, x[ 2], S21); /* 25 */ 
    GG (d, a, b, c, x[ 6], S22); /* 26 */ 
    GG (c, d, a, b, x[10], S23); /* 27 */ 
    GG (b, c, d, a, x[14], S24); /* 28 */ 
    GG (a, b, c, d, x[ 3], S21); /* 29 */ 
    GG (d, a, b, c, x[ 7], S22); /* 30 */ 
    GG (c, d, a, b, x[11], S23); /* 31 */ 
    GG (b, c, d, a, x[15], S24); /* 32 */ 
    
    /* Round 3 */
    HH (a, b, c, d, x[ 0], S31); /* 33 */ 
    HH (d, a, b, c, x[ 8], S32); /* 34 */ 
    HH (c, d, a, b, x[ 4], S33); /* 35 */ 
    HH (b, c, d, a, x[12], S34); /* 36 */ 
    HH (a, b, c, d, x[ 2], S31); /* 37 */ 
    HH (d, a, b, c, x[10], S32); /* 38 */ 
    HH (c, d, a, b, x[ 6], S33); /* 39 */ 
    HH (b, c, d, a, x[14], S34); /* 40 */ 
    HH (a, b, c, d, x[ 1], S31); /* 41 */ 
    HH (d, a, b, c, x[ 9], S32); /* 42 */ 
    HH (c, d, a, b, x[ 5], S33); /* 43 */ 
    HH (b, c, d, a, x[13], S34); /* 44 */ 
    HH (a, b, c, d, x[ 3], S31); /* 45 */ 
    HH (d, a, b, c, x[11], S32); /* 46 */ 
    HH (c, d, a, b, x[ 7], S33); /* 47 */ 
    HH (b, c, d, a, x[15], S34); /* 48 */ 
    

    /* Update our state */
    md->md4.state[0] = md->md4.state[0] + a;
    md->md4.state[1] = md->md4.state[1] + b;
    md->md4.state[2] = md->md4.state[2] + c;
    md->md4.state[3] = md->md4.state[3] + d;

    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int md4_compress(hash_state *md, unsigned char *buf)
{
   int err;
   err = _md4_compress(md, buf);
   burn_stack(sizeof(ulong32) * 20 + sizeof(int));
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int md4_init(hash_state * md)
{
   LTC_ARGCHK(md != NULL);
   md->md4.state[0] = 0x67452301UL;
   md->md4.state[1] = 0xefcdab89UL;
   md->md4.state[2] = 0x98badcfeUL;
   md->md4.state[3] = 0x10325476UL;
   md->md4.length  = 0;
   md->md4.curlen  = 0;
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
HASH_PROCESS(md4_process, md4_compress, md4, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (16 bytes)
   @return CRYPT_OK if successful
*/
int md4_done(hash_state * md, unsigned char *out)
{
    int i;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    if (md->md4.curlen >= sizeof(md->md4.buf)) {
       return CRYPT_INVALID_ARG;
    }

    /* increase the length of the message */
    md->md4.length += md->md4.curlen * 8;

    /* append the '1' bit */
    md->md4.buf[md->md4.curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->md4.curlen > 56) {
        while (md->md4.curlen < 64) {
            md->md4.buf[md->md4.curlen++] = (unsigned char)0;
        }
        md4_compress(md, md->md4.buf);
        md->md4.curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (md->md4.curlen < 56) {
        md->md4.buf[md->md4.curlen++] = (unsigned char)0;
    }

    /* store length */
    STORE64L(md->md4.length, md->md4.buf+56);
    md4_compress(md, md->md4.buf);

    /* copy output */
    for (i = 0; i < 4; i++) {
        STORE32L(md->md4.state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif 
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int md4_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
    static const struct md4_test_case {
        char *input;
        unsigned char digest[16];
    } cases[] = {
        { "", 
          {0x31, 0xd6, 0xcf, 0xe0, 0xd1, 0x6a, 0xe9, 0x31,
           0xb7, 0x3c, 0x59, 0xd7, 0xe0, 0xc0, 0x89, 0xc0} },
        { "a",
          {0xbd, 0xe5, 0x2c, 0xb3, 0x1d, 0xe3, 0x3e, 0x46,
           0x24, 0x5e, 0x05, 0xfb, 0xdb, 0xd6, 0xfb, 0x24} },
        { "abc",
          {0xa4, 0x48, 0x01, 0x7a, 0xaf, 0x21, 0xd8, 0x52, 
           0x5f, 0xc1, 0x0a, 0xe8, 0x7a, 0xa6, 0x72, 0x9d} },
        { "message digest", 
          {0xd9, 0x13, 0x0a, 0x81, 0x64, 0x54, 0x9f, 0xe8, 
           0x18, 0x87, 0x48, 0x06, 0xe1, 0xc7, 0x01, 0x4b} },
        { "abcdefghijklmnopqrstuvwxyz", 
          {0xd7, 0x9e, 0x1c, 0x30, 0x8a, 0xa5, 0xbb, 0xcd, 
           0xee, 0xa8, 0xed, 0x63, 0xdf, 0x41, 0x2d, 0xa9} },
        { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 
          {0x04, 0x3f, 0x85, 0x82, 0xf2, 0x41, 0xdb, 0x35, 
           0x1c, 0xe6, 0x27, 0xe1, 0x53, 0xe7, 0xf0, 0xe4} },
        { "12345678901234567890123456789012345678901234567890123456789012345678901234567890", 
          {0xe3, 0x3b, 0x4d, 0xdc, 0x9c, 0x38, 0xf2, 0x19, 
           0x9c, 0x3e, 0x7b, 0x16, 0x4f, 0xcc, 0x05, 0x36} },
    };
    int i;
    hash_state md;
    unsigned char digest[16];

    for(i = 0; i < (int)(sizeof(cases) / sizeof(cases[0])); i++) {
        md4_init(&md);
        md4_process(&md, (unsigned char *)cases[i].input, (unsigned long)strlen(cases[i].input));
        md4_done(&md, digest);
        if (XMEMCMP(digest, cases[i].digest, 16) != 0) {
           return CRYPT_FAIL_TESTVECTOR;
        }

    }
    return CRYPT_OK;
  #endif
}

#endif



/* $Source: /cvs/libtom/libtomcrypt/src/hashes/md4.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/md5.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"


/**
  @file md5.c
  LTC_MD5 hash function by Tom St Denis 
*/

#ifdef LTC_MD5

const struct ltc_hash_descriptor ltc_md5_desc =
{
    "md5",
    3,
    16,
    64,

    /* OID */
   { 1, 2, 840, 113549, 2, 5,  },
   6,

    &ltc_md5_init,
    &ltc_md5_process,
    &ltc_md5_done,
    &ltc_md5_test,
    NULL
};

#define F(x,y,z)  (z ^ (x & (y ^ z)))
#define G(x,y,z)  (y ^ (z & (y ^ x)))
#define H(x,y,z)  (x^y^z)
#define I(x,y,z)  (y^(x|(~z)))

#ifdef LTC_SMALL_CODE

#define FF(a,b,c,d,M,s,t) \
    a = (a + F(b,c,d) + M + t); a = ROL(a, s) + b;

#define GG(a,b,c,d,M,s,t) \
    a = (a + G(b,c,d) + M + t); a = ROL(a, s) + b;

#define HH(a,b,c,d,M,s,t) \
    a = (a + H(b,c,d) + M + t); a = ROL(a, s) + b;

#define II(a,b,c,d,M,s,t) \
    a = (a + I(b,c,d) + M + t); a = ROL(a, s) + b;

static const unsigned char Worder[64] = {
   0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
   1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,
   5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,
   0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9
};

static const unsigned char Rorder[64] = {
   7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,
   5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,
   4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,
   6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21
};

static const ulong32 Korder[64] = {
0xd76aa478UL, 0xe8c7b756UL, 0x242070dbUL, 0xc1bdceeeUL, 0xf57c0fafUL, 0x4787c62aUL, 0xa8304613UL, 0xfd469501UL,
0x698098d8UL, 0x8b44f7afUL, 0xffff5bb1UL, 0x895cd7beUL, 0x6b901122UL, 0xfd987193UL, 0xa679438eUL, 0x49b40821UL,
0xf61e2562UL, 0xc040b340UL, 0x265e5a51UL, 0xe9b6c7aaUL, 0xd62f105dUL, 0x02441453UL, 0xd8a1e681UL, 0xe7d3fbc8UL,
0x21e1cde6UL, 0xc33707d6UL, 0xf4d50d87UL, 0x455a14edUL, 0xa9e3e905UL, 0xfcefa3f8UL, 0x676f02d9UL, 0x8d2a4c8aUL,
0xfffa3942UL, 0x8771f681UL, 0x6d9d6122UL, 0xfde5380cUL, 0xa4beea44UL, 0x4bdecfa9UL, 0xf6bb4b60UL, 0xbebfbc70UL,
0x289b7ec6UL, 0xeaa127faUL, 0xd4ef3085UL, 0x04881d05UL, 0xd9d4d039UL, 0xe6db99e5UL, 0x1fa27cf8UL, 0xc4ac5665UL,
0xf4292244UL, 0x432aff97UL, 0xab9423a7UL, 0xfc93a039UL, 0x655b59c3UL, 0x8f0ccc92UL, 0xffeff47dUL, 0x85845dd1UL,
0x6fa87e4fUL, 0xfe2ce6e0UL, 0xa3014314UL, 0x4e0811a1UL, 0xf7537e82UL, 0xbd3af235UL, 0x2ad7d2bbUL, 0xeb86d391UL
};

#else

#define FF(a,b,c,d,M,s,t) \
    a = (a + F(b,c,d) + M + t); a = ROLc(a, s) + b;

#define GG(a,b,c,d,M,s,t) \
    a = (a + G(b,c,d) + M + t); a = ROLc(a, s) + b;

#define HH(a,b,c,d,M,s,t) \
    a = (a + H(b,c,d) + M + t); a = ROLc(a, s) + b;

#define II(a,b,c,d,M,s,t) \
    a = (a + I(b,c,d) + M + t); a = ROLc(a, s) + b;


#endif   

#ifdef LTC_CLEAN_STACK
static int _md5_compress(hash_state *md, unsigned char *buf)
#else
static int  md5_compress(hash_state *md, unsigned char *buf)
#endif
{
    ulong32 i, W[16], a, b, c, d;
#ifdef LTC_SMALL_CODE
    ulong32 t;
#endif

    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LOAD32L(W[i], buf + (4*i));
    }
 
    /* copy state */
    a = md->md5.state[0];
    b = md->md5.state[1];
    c = md->md5.state[2];
    d = md->md5.state[3];

#ifdef LTC_SMALL_CODE
    for (i = 0; i < 16; ++i) {
        FF(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 32; ++i) {
        GG(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 48; ++i) {
        HH(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 64; ++i) {
        II(a,b,c,d,W[Worder[i]],Rorder[i],Korder[i]);
        t = d; d = c; c = b; b = a; a = t;
    }

#else
    FF(a,b,c,d,W[0],7,0xd76aa478UL)
    FF(d,a,b,c,W[1],12,0xe8c7b756UL)
    FF(c,d,a,b,W[2],17,0x242070dbUL)
    FF(b,c,d,a,W[3],22,0xc1bdceeeUL)
    FF(a,b,c,d,W[4],7,0xf57c0fafUL)
    FF(d,a,b,c,W[5],12,0x4787c62aUL)
    FF(c,d,a,b,W[6],17,0xa8304613UL)
    FF(b,c,d,a,W[7],22,0xfd469501UL)
    FF(a,b,c,d,W[8],7,0x698098d8UL)
    FF(d,a,b,c,W[9],12,0x8b44f7afUL)
    FF(c,d,a,b,W[10],17,0xffff5bb1UL)
    FF(b,c,d,a,W[11],22,0x895cd7beUL)
    FF(a,b,c,d,W[12],7,0x6b901122UL)
    FF(d,a,b,c,W[13],12,0xfd987193UL)
    FF(c,d,a,b,W[14],17,0xa679438eUL)
    FF(b,c,d,a,W[15],22,0x49b40821UL)
    GG(a,b,c,d,W[1],5,0xf61e2562UL)
    GG(d,a,b,c,W[6],9,0xc040b340UL)
    GG(c,d,a,b,W[11],14,0x265e5a51UL)
    GG(b,c,d,a,W[0],20,0xe9b6c7aaUL)
    GG(a,b,c,d,W[5],5,0xd62f105dUL)
    GG(d,a,b,c,W[10],9,0x02441453UL)
    GG(c,d,a,b,W[15],14,0xd8a1e681UL)
    GG(b,c,d,a,W[4],20,0xe7d3fbc8UL)
    GG(a,b,c,d,W[9],5,0x21e1cde6UL)
    GG(d,a,b,c,W[14],9,0xc33707d6UL)
    GG(c,d,a,b,W[3],14,0xf4d50d87UL)
    GG(b,c,d,a,W[8],20,0x455a14edUL)
    GG(a,b,c,d,W[13],5,0xa9e3e905UL)
    GG(d,a,b,c,W[2],9,0xfcefa3f8UL)
    GG(c,d,a,b,W[7],14,0x676f02d9UL)
    GG(b,c,d,a,W[12],20,0x8d2a4c8aUL)
    HH(a,b,c,d,W[5],4,0xfffa3942UL)
    HH(d,a,b,c,W[8],11,0x8771f681UL)
    HH(c,d,a,b,W[11],16,0x6d9d6122UL)
    HH(b,c,d,a,W[14],23,0xfde5380cUL)
    HH(a,b,c,d,W[1],4,0xa4beea44UL)
    HH(d,a,b,c,W[4],11,0x4bdecfa9UL)
    HH(c,d,a,b,W[7],16,0xf6bb4b60UL)
    HH(b,c,d,a,W[10],23,0xbebfbc70UL)
    HH(a,b,c,d,W[13],4,0x289b7ec6UL)
    HH(d,a,b,c,W[0],11,0xeaa127faUL)
    HH(c,d,a,b,W[3],16,0xd4ef3085UL)
    HH(b,c,d,a,W[6],23,0x04881d05UL)
    HH(a,b,c,d,W[9],4,0xd9d4d039UL)
    HH(d,a,b,c,W[12],11,0xe6db99e5UL)
    HH(c,d,a,b,W[15],16,0x1fa27cf8UL)
    HH(b,c,d,a,W[2],23,0xc4ac5665UL)
    II(a,b,c,d,W[0],6,0xf4292244UL)
    II(d,a,b,c,W[7],10,0x432aff97UL)
    II(c,d,a,b,W[14],15,0xab9423a7UL)
    II(b,c,d,a,W[5],21,0xfc93a039UL)
    II(a,b,c,d,W[12],6,0x655b59c3UL)
    II(d,a,b,c,W[3],10,0x8f0ccc92UL)
    II(c,d,a,b,W[10],15,0xffeff47dUL)
    II(b,c,d,a,W[1],21,0x85845dd1UL)
    II(a,b,c,d,W[8],6,0x6fa87e4fUL)
    II(d,a,b,c,W[15],10,0xfe2ce6e0UL)
    II(c,d,a,b,W[6],15,0xa3014314UL)
    II(b,c,d,a,W[13],21,0x4e0811a1UL)
    II(a,b,c,d,W[4],6,0xf7537e82UL)
    II(d,a,b,c,W[11],10,0xbd3af235UL)
    II(c,d,a,b,W[2],15,0x2ad7d2bbUL)
    II(b,c,d,a,W[9],21,0xeb86d391UL)
#endif

    md->md5.state[0] = md->md5.state[0] + a;
    md->md5.state[1] = md->md5.state[1] + b;
    md->md5.state[2] = md->md5.state[2] + c;
    md->md5.state[3] = md->md5.state[3] + d;

    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int md5_compress(hash_state *md, unsigned char *buf)
{
   int err;
   err = _md5_compress(md, buf);
   burn_stack(sizeof(ulong32) * 21);
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int ltc_md5_init(hash_state * md)
{
   LTC_ARGCHK(md != NULL);
   md->md5.state[0] = 0x67452301UL;
   md->md5.state[1] = 0xefcdab89UL;
   md->md5.state[2] = 0x98badcfeUL;
   md->md5.state[3] = 0x10325476UL;
   md->md5.curlen = 0;
   md->md5.length = 0;
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
HASH_PROCESS(ltc_md5_process, md5_compress, md5, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (16 bytes)
   @return CRYPT_OK if successful
*/
int ltc_md5_done(hash_state * md, unsigned char *out)
{
    int i;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    if (md->md5.curlen >= sizeof(md->md5.buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    md->md5.length += md->md5.curlen * 8;

    /* append the '1' bit */
    md->md5.buf[md->md5.curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->md5.curlen > 56) {
        while (md->md5.curlen < 64) {
            md->md5.buf[md->md5.curlen++] = (unsigned char)0;
        }
        md5_compress(md, md->md5.buf);
        md->md5.curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (md->md5.curlen < 56) {
        md->md5.buf[md->md5.curlen++] = (unsigned char)0;
    }

    /* store length */
    STORE64L(md->md5.length, md->md5.buf+56);
    md5_compress(md, md->md5.buf);

    /* copy output */
    for (i = 0; i < 4; i++) {
        STORE32L(md->md5.state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  ltc_md5_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      char *msg;
      unsigned char hash[16];
  } tests[] = {
    { "",
      { 0xd4, 0x1d, 0x8c, 0xd9, 0x8f, 0x00, 0xb2, 0x04, 
        0xe9, 0x80, 0x09, 0x98, 0xec, 0xf8, 0x42, 0x7e } },
    { "a",
      {0x0c, 0xc1, 0x75, 0xb9, 0xc0, 0xf1, 0xb6, 0xa8, 
       0x31, 0xc3, 0x99, 0xe2, 0x69, 0x77, 0x26, 0x61 } },
    { "abc",
      { 0x90, 0x01, 0x50, 0x98, 0x3c, 0xd2, 0x4f, 0xb0, 
        0xd6, 0x96, 0x3f, 0x7d, 0x28, 0xe1, 0x7f, 0x72 } },
    { "message digest", 
      { 0xf9, 0x6b, 0x69, 0x7d, 0x7c, 0xb7, 0x93, 0x8d, 
        0x52, 0x5a, 0x2f, 0x31, 0xaa, 0xf1, 0x61, 0xd0 } }, 
    { "abcdefghijklmnopqrstuvwxyz",
      { 0xc3, 0xfc, 0xd3, 0xd7, 0x61, 0x92, 0xe4, 0x00, 
        0x7d, 0xfb, 0x49, 0x6c, 0xca, 0x67, 0xe1, 0x3b } },
    { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
      { 0xd1, 0x74, 0xab, 0x98, 0xd2, 0x77, 0xd9, 0xf5, 
        0xa5, 0x61, 0x1c, 0x2c, 0x9f, 0x41, 0x9d, 0x9f } },
    { "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
      { 0x57, 0xed, 0xf4, 0xa2, 0x2b, 0xe3, 0xc9, 0x55, 
        0xac, 0x49, 0xda, 0x2e, 0x21, 0x07, 0xb6, 0x7a } }, 
    { NULL, { 0 } }
  };

  int i;
  unsigned char tmp[16];
  hash_state md;

  for (i = 0; tests[i].msg != NULL; i++) {
      ltc_md5_init(&md);
      ltc_md5_process(&md, (unsigned char *)tests[i].msg, (unsigned long)strlen(tests[i].msg));
      ltc_md5_done(&md, tmp);
      if (XMEMCMP(tmp, tests[i].hash, 16) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
 #endif
}

#endif



/* $Source: /cvs/libtom/libtomcrypt/src/hashes/md5.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/rmd128.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @param rmd128.c
   RMD128 Hash function
*/   

/* Implementation of LTC_RIPEMD-128 based on the source by Antoon Bosselaers, ESAT-COSIC
 *
 * This source has been radically overhauled to be portable and work within
 * the LibTomCrypt API by Tom St Denis
 */

#ifdef LTC_RIPEMD128

const struct ltc_hash_descriptor rmd128_desc =
{
    "rmd128",
    8,
    16,
    64,

    /* OID */
   { 1, 0, 10118, 3, 0, 50 },
   6,

    &rmd128_init,
    &rmd128_process,
    &rmd128_done,
    &rmd128_test,
    NULL
};

/* the four basic functions F(), G() and H() */
#define F(x, y, z)        ((x) ^ (y) ^ (z)) 
#define G(x, y, z)        (((x) & (y)) | (~(x) & (z))) 
#define H(x, y, z)        (((x) | ~(y)) ^ (z))
#define I(x, y, z)        (((x) & (z)) | ((y) & ~(z))) 
  
/* the eight basic operations FF() through III() */
#define FF(a, b, c, d, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = ROLc((a), (s));

#define GG(a, b, c, d, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
      (a) = ROLc((a), (s));

#define HH(a, b, c, d, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
      (a) = ROLc((a), (s));

#define II(a, b, c, d, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
      (a) = ROLc((a), (s));

#define FFF(a, b, c, d, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = ROLc((a), (s));

#define GGG(a, b, c, d, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x6d703ef3UL;\
      (a) = ROLc((a), (s));

#define HHH(a, b, c, d, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x5c4dd124UL;\
      (a) = ROLc((a), (s));

#define III(a, b, c, d, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x50a28be6UL;\
      (a) = ROLc((a), (s));

#ifdef LTC_CLEAN_STACK
static int _rmd128_compress(hash_state *md, unsigned char *buf)
#else
static int  rmd128_compress(hash_state *md, unsigned char *buf)
#endif
{
   ulong32 aa,bb,cc,dd,aaa,bbb,ccc,ddd,X[16];
   int i;
   
   /* load words X */
   for (i = 0; i < 16; i++){
      LOAD32L(X[i], buf + (4 * i));
   }

   /* load state */
   aa = aaa = md->rmd128.state[0];
   bb = bbb = md->rmd128.state[1];
   cc = ccc = md->rmd128.state[2];
   dd = ddd = md->rmd128.state[3];

   /* round 1 */
   FF(aa, bb, cc, dd, X[ 0], 11);
   FF(dd, aa, bb, cc, X[ 1], 14);
   FF(cc, dd, aa, bb, X[ 2], 15);
   FF(bb, cc, dd, aa, X[ 3], 12);
   FF(aa, bb, cc, dd, X[ 4],  5);
   FF(dd, aa, bb, cc, X[ 5],  8);
   FF(cc, dd, aa, bb, X[ 6],  7);
   FF(bb, cc, dd, aa, X[ 7],  9);
   FF(aa, bb, cc, dd, X[ 8], 11);
   FF(dd, aa, bb, cc, X[ 9], 13);
   FF(cc, dd, aa, bb, X[10], 14);
   FF(bb, cc, dd, aa, X[11], 15);
   FF(aa, bb, cc, dd, X[12],  6);
   FF(dd, aa, bb, cc, X[13],  7);
   FF(cc, dd, aa, bb, X[14],  9);
   FF(bb, cc, dd, aa, X[15],  8);
                             
   /* round 2 */
   GG(aa, bb, cc, dd, X[ 7],  7);
   GG(dd, aa, bb, cc, X[ 4],  6);
   GG(cc, dd, aa, bb, X[13],  8);
   GG(bb, cc, dd, aa, X[ 1], 13);
   GG(aa, bb, cc, dd, X[10], 11);
   GG(dd, aa, bb, cc, X[ 6],  9);
   GG(cc, dd, aa, bb, X[15],  7);
   GG(bb, cc, dd, aa, X[ 3], 15);
   GG(aa, bb, cc, dd, X[12],  7);
   GG(dd, aa, bb, cc, X[ 0], 12);
   GG(cc, dd, aa, bb, X[ 9], 15);
   GG(bb, cc, dd, aa, X[ 5],  9);
   GG(aa, bb, cc, dd, X[ 2], 11);
   GG(dd, aa, bb, cc, X[14],  7);
   GG(cc, dd, aa, bb, X[11], 13);
   GG(bb, cc, dd, aa, X[ 8], 12);

   /* round 3 */
   HH(aa, bb, cc, dd, X[ 3], 11);
   HH(dd, aa, bb, cc, X[10], 13);
   HH(cc, dd, aa, bb, X[14],  6);
   HH(bb, cc, dd, aa, X[ 4],  7);
   HH(aa, bb, cc, dd, X[ 9], 14);
   HH(dd, aa, bb, cc, X[15],  9);
   HH(cc, dd, aa, bb, X[ 8], 13);
   HH(bb, cc, dd, aa, X[ 1], 15);
   HH(aa, bb, cc, dd, X[ 2], 14);
   HH(dd, aa, bb, cc, X[ 7],  8);
   HH(cc, dd, aa, bb, X[ 0], 13);
   HH(bb, cc, dd, aa, X[ 6],  6);
   HH(aa, bb, cc, dd, X[13],  5);
   HH(dd, aa, bb, cc, X[11], 12);
   HH(cc, dd, aa, bb, X[ 5],  7);
   HH(bb, cc, dd, aa, X[12],  5);

   /* round 4 */
   II(aa, bb, cc, dd, X[ 1], 11);
   II(dd, aa, bb, cc, X[ 9], 12);
   II(cc, dd, aa, bb, X[11], 14);
   II(bb, cc, dd, aa, X[10], 15);
   II(aa, bb, cc, dd, X[ 0], 14);
   II(dd, aa, bb, cc, X[ 8], 15);
   II(cc, dd, aa, bb, X[12],  9);
   II(bb, cc, dd, aa, X[ 4],  8);
   II(aa, bb, cc, dd, X[13],  9);
   II(dd, aa, bb, cc, X[ 3], 14);
   II(cc, dd, aa, bb, X[ 7],  5);
   II(bb, cc, dd, aa, X[15],  6);
   II(aa, bb, cc, dd, X[14],  8);
   II(dd, aa, bb, cc, X[ 5],  6);
   II(cc, dd, aa, bb, X[ 6],  5);
   II(bb, cc, dd, aa, X[ 2], 12);

   /* parallel round 1 */
   III(aaa, bbb, ccc, ddd, X[ 5],  8); 
   III(ddd, aaa, bbb, ccc, X[14],  9);
   III(ccc, ddd, aaa, bbb, X[ 7],  9);
   III(bbb, ccc, ddd, aaa, X[ 0], 11);
   III(aaa, bbb, ccc, ddd, X[ 9], 13);
   III(ddd, aaa, bbb, ccc, X[ 2], 15);
   III(ccc, ddd, aaa, bbb, X[11], 15);
   III(bbb, ccc, ddd, aaa, X[ 4],  5);
   III(aaa, bbb, ccc, ddd, X[13],  7);
   III(ddd, aaa, bbb, ccc, X[ 6],  7);
   III(ccc, ddd, aaa, bbb, X[15],  8);
   III(bbb, ccc, ddd, aaa, X[ 8], 11);
   III(aaa, bbb, ccc, ddd, X[ 1], 14);
   III(ddd, aaa, bbb, ccc, X[10], 14);
   III(ccc, ddd, aaa, bbb, X[ 3], 12);
   III(bbb, ccc, ddd, aaa, X[12],  6);

   /* parallel round 2 */
   HHH(aaa, bbb, ccc, ddd, X[ 6],  9);
   HHH(ddd, aaa, bbb, ccc, X[11], 13);
   HHH(ccc, ddd, aaa, bbb, X[ 3], 15);
   HHH(bbb, ccc, ddd, aaa, X[ 7],  7);
   HHH(aaa, bbb, ccc, ddd, X[ 0], 12);
   HHH(ddd, aaa, bbb, ccc, X[13],  8);
   HHH(ccc, ddd, aaa, bbb, X[ 5],  9);
   HHH(bbb, ccc, ddd, aaa, X[10], 11);
   HHH(aaa, bbb, ccc, ddd, X[14],  7);
   HHH(ddd, aaa, bbb, ccc, X[15],  7);
   HHH(ccc, ddd, aaa, bbb, X[ 8], 12);
   HHH(bbb, ccc, ddd, aaa, X[12],  7);
   HHH(aaa, bbb, ccc, ddd, X[ 4],  6);
   HHH(ddd, aaa, bbb, ccc, X[ 9], 15);
   HHH(ccc, ddd, aaa, bbb, X[ 1], 13);
   HHH(bbb, ccc, ddd, aaa, X[ 2], 11);

   /* parallel round 3 */   
   GGG(aaa, bbb, ccc, ddd, X[15],  9);
   GGG(ddd, aaa, bbb, ccc, X[ 5],  7);
   GGG(ccc, ddd, aaa, bbb, X[ 1], 15);
   GGG(bbb, ccc, ddd, aaa, X[ 3], 11);
   GGG(aaa, bbb, ccc, ddd, X[ 7],  8);
   GGG(ddd, aaa, bbb, ccc, X[14],  6);
   GGG(ccc, ddd, aaa, bbb, X[ 6],  6);
   GGG(bbb, ccc, ddd, aaa, X[ 9], 14);
   GGG(aaa, bbb, ccc, ddd, X[11], 12);
   GGG(ddd, aaa, bbb, ccc, X[ 8], 13);
   GGG(ccc, ddd, aaa, bbb, X[12],  5);
   GGG(bbb, ccc, ddd, aaa, X[ 2], 14);
   GGG(aaa, bbb, ccc, ddd, X[10], 13);
   GGG(ddd, aaa, bbb, ccc, X[ 0], 13);
   GGG(ccc, ddd, aaa, bbb, X[ 4],  7);
   GGG(bbb, ccc, ddd, aaa, X[13],  5);

   /* parallel round 4 */
   FFF(aaa, bbb, ccc, ddd, X[ 8], 15);
   FFF(ddd, aaa, bbb, ccc, X[ 6],  5);
   FFF(ccc, ddd, aaa, bbb, X[ 4],  8);
   FFF(bbb, ccc, ddd, aaa, X[ 1], 11);
   FFF(aaa, bbb, ccc, ddd, X[ 3], 14);
   FFF(ddd, aaa, bbb, ccc, X[11], 14);
   FFF(ccc, ddd, aaa, bbb, X[15],  6);
   FFF(bbb, ccc, ddd, aaa, X[ 0], 14);
   FFF(aaa, bbb, ccc, ddd, X[ 5],  6);
   FFF(ddd, aaa, bbb, ccc, X[12],  9);
   FFF(ccc, ddd, aaa, bbb, X[ 2], 12);
   FFF(bbb, ccc, ddd, aaa, X[13],  9);
   FFF(aaa, bbb, ccc, ddd, X[ 9], 12);
   FFF(ddd, aaa, bbb, ccc, X[ 7],  5);
   FFF(ccc, ddd, aaa, bbb, X[10], 15);
   FFF(bbb, ccc, ddd, aaa, X[14],  8);

   /* combine results */
   ddd += cc + md->rmd128.state[1];               /* final result for MDbuf[0] */
   md->rmd128.state[1] = md->rmd128.state[2] + dd + aaa;
   md->rmd128.state[2] = md->rmd128.state[3] + aa + bbb;
   md->rmd128.state[3] = md->rmd128.state[0] + bb + ccc;
   md->rmd128.state[0] = ddd;

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int rmd128_compress(hash_state *md, unsigned char *buf)
{
   int err;
   err = _rmd128_compress(md, buf);
   burn_stack(sizeof(ulong32) * 24 + sizeof(int));
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int rmd128_init(hash_state * md)
{
   LTC_ARGCHK(md != NULL);
   md->rmd128.state[0] = 0x67452301UL;
   md->rmd128.state[1] = 0xefcdab89UL;
   md->rmd128.state[2] = 0x98badcfeUL;
   md->rmd128.state[3] = 0x10325476UL;
   md->rmd128.curlen   = 0;
   md->rmd128.length   = 0;
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
HASH_PROCESS(rmd128_process, rmd128_compress, rmd128, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (16 bytes)
   @return CRYPT_OK if successful
*/
int rmd128_done(hash_state * md, unsigned char *out)
{
    int i;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    if (md->rmd128.curlen >= sizeof(md->rmd128.buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    md->rmd128.length += md->rmd128.curlen * 8;

    /* append the '1' bit */
    md->rmd128.buf[md->rmd128.curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->rmd128.curlen > 56) {
        while (md->rmd128.curlen < 64) {
            md->rmd128.buf[md->rmd128.curlen++] = (unsigned char)0;
        }
        rmd128_compress(md, md->rmd128.buf);
        md->rmd128.curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (md->rmd128.curlen < 56) {
        md->rmd128.buf[md->rmd128.curlen++] = (unsigned char)0;
    }

    /* store length */
    STORE64L(md->rmd128.length, md->rmd128.buf+56);
    rmd128_compress(md, md->rmd128.buf);

    /* copy output */
    for (i = 0; i < 4; i++) {
        STORE32L(md->rmd128.state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
   return CRYPT_OK;  
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int rmd128_test(void)
{
#ifndef LTC_TEST
   return CRYPT_NOP;
#else
   static const struct {
        char *msg;
        unsigned char md[16];
   } tests[] = {
   { "",
     { 0xcd, 0xf2, 0x62, 0x13, 0xa1, 0x50, 0xdc, 0x3e,
       0xcb, 0x61, 0x0f, 0x18, 0xf6, 0xb3, 0x8b, 0x46 }
   },
   { "a",
     { 0x86, 0xbe, 0x7a, 0xfa, 0x33, 0x9d, 0x0f, 0xc7,
       0xcf, 0xc7, 0x85, 0xe7, 0x2f, 0x57, 0x8d, 0x33 }
   },
   { "abc",
     { 0xc1, 0x4a, 0x12, 0x19, 0x9c, 0x66, 0xe4, 0xba,
       0x84, 0x63, 0x6b, 0x0f, 0x69, 0x14, 0x4c, 0x77 }
   },
   { "message digest",
     { 0x9e, 0x32, 0x7b, 0x3d, 0x6e, 0x52, 0x30, 0x62,
       0xaf, 0xc1, 0x13, 0x2d, 0x7d, 0xf9, 0xd1, 0xb8 }
   },
   { "abcdefghijklmnopqrstuvwxyz",
     { 0xfd, 0x2a, 0xa6, 0x07, 0xf7, 0x1d, 0xc8, 0xf5,
       0x10, 0x71, 0x49, 0x22, 0xb3, 0x71, 0x83, 0x4e }
   },
   { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
     { 0xd1, 0xe9, 0x59, 0xeb, 0x17, 0x9c, 0x91, 0x1f,
       0xae, 0xa4, 0x62, 0x4c, 0x60, 0xc5, 0xc7, 0x02 }
   }
   };
   int x;
   unsigned char buf[16];
   hash_state md;

   for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
       rmd128_init(&md);
       rmd128_process(&md, (unsigned char *)tests[x].msg, strlen(tests[x].msg));
       rmd128_done(&md, buf);
       if (XMEMCMP(buf, tests[x].md, 16) != 0) {
       #if 0
          printf("Failed test %d\n", x);
       #endif
          return CRYPT_FAIL_TESTVECTOR;
       }
   }
   return CRYPT_OK;
#endif
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/hashes/rmd128.c,v $ */
/* $Revision: 1.11 $ */
/* $Date: 2007/05/12 14:25:28 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/rmd160.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file rmd160.c
   RMD160 hash function
*/   

/* Implementation of LTC_RIPEMD-160 based on the source by Antoon Bosselaers, ESAT-COSIC
 *
 * This source has been radically overhauled to be portable and work within
 * the LibTomCrypt API by Tom St Denis
 */

#ifdef LTC_RIPEMD160

const struct ltc_hash_descriptor rmd160_desc =
{
    "rmd160",
    9,
    20,
    64,

    /* OID */
   { 1, 3, 36, 3, 2, 1,  },
   6,

    &rmd160_init,
    &rmd160_process,
    &rmd160_done,
    &rmd160_test,
    NULL
};

/* the five basic functions F(), G() and H() */
#define F(x, y, z)        ((x) ^ (y) ^ (z)) 
#define G(x, y, z)        (((x) & (y)) | (~(x) & (z))) 
#define H(x, y, z)        (((x) | ~(y)) ^ (z))
#define I(x, y, z)        (((x) & (z)) | ((y) & ~(z))) 
#define J(x, y, z)        ((x) ^ ((y) | ~(z)))
  
/* the ten basic operations FF() through III() */
#define FF(a, b, c, d, e, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define GG(a, b, c, d, e, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define HH(a, b, c, d, e, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define II(a, b, c, d, e, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define JJ(a, b, c, d, e, x, s)        \
      (a) += J((b), (c), (d)) + (x) + 0xa953fd4eUL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define FFF(a, b, c, d, e, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define GGG(a, b, c, d, e, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define HHH(a, b, c, d, e, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6d703ef3UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define III(a, b, c, d, e, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x5c4dd124UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define JJJ(a, b, c, d, e, x, s)        \
      (a) += J((b), (c), (d)) + (x) + 0x50a28be6UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);


#ifdef LTC_CLEAN_STACK
static int _rmd160_compress(hash_state *md, unsigned char *buf)
#else
static int  rmd160_compress(hash_state *md, unsigned char *buf)
#endif
{
   ulong32 aa,bb,cc,dd,ee,aaa,bbb,ccc,ddd,eee,X[16];
   int i;

   /* load words X */
   for (i = 0; i < 16; i++){
      LOAD32L(X[i], buf + (4 * i));
   }

   /* load state */
   aa = aaa = md->rmd160.state[0];
   bb = bbb = md->rmd160.state[1];
   cc = ccc = md->rmd160.state[2];
   dd = ddd = md->rmd160.state[3];
   ee = eee = md->rmd160.state[4];

   /* round 1 */
   FF(aa, bb, cc, dd, ee, X[ 0], 11);
   FF(ee, aa, bb, cc, dd, X[ 1], 14);
   FF(dd, ee, aa, bb, cc, X[ 2], 15);
   FF(cc, dd, ee, aa, bb, X[ 3], 12);
   FF(bb, cc, dd, ee, aa, X[ 4],  5);
   FF(aa, bb, cc, dd, ee, X[ 5],  8);
   FF(ee, aa, bb, cc, dd, X[ 6],  7);
   FF(dd, ee, aa, bb, cc, X[ 7],  9);
   FF(cc, dd, ee, aa, bb, X[ 8], 11);
   FF(bb, cc, dd, ee, aa, X[ 9], 13);
   FF(aa, bb, cc, dd, ee, X[10], 14);
   FF(ee, aa, bb, cc, dd, X[11], 15);
   FF(dd, ee, aa, bb, cc, X[12],  6);
   FF(cc, dd, ee, aa, bb, X[13],  7);
   FF(bb, cc, dd, ee, aa, X[14],  9);
   FF(aa, bb, cc, dd, ee, X[15],  8);
                             
   /* round 2 */
   GG(ee, aa, bb, cc, dd, X[ 7],  7);
   GG(dd, ee, aa, bb, cc, X[ 4],  6);
   GG(cc, dd, ee, aa, bb, X[13],  8);
   GG(bb, cc, dd, ee, aa, X[ 1], 13);
   GG(aa, bb, cc, dd, ee, X[10], 11);
   GG(ee, aa, bb, cc, dd, X[ 6],  9);
   GG(dd, ee, aa, bb, cc, X[15],  7);
   GG(cc, dd, ee, aa, bb, X[ 3], 15);
   GG(bb, cc, dd, ee, aa, X[12],  7);
   GG(aa, bb, cc, dd, ee, X[ 0], 12);
   GG(ee, aa, bb, cc, dd, X[ 9], 15);
   GG(dd, ee, aa, bb, cc, X[ 5],  9);
   GG(cc, dd, ee, aa, bb, X[ 2], 11);
   GG(bb, cc, dd, ee, aa, X[14],  7);
   GG(aa, bb, cc, dd, ee, X[11], 13);
   GG(ee, aa, bb, cc, dd, X[ 8], 12);

   /* round 3 */
   HH(dd, ee, aa, bb, cc, X[ 3], 11);
   HH(cc, dd, ee, aa, bb, X[10], 13);
   HH(bb, cc, dd, ee, aa, X[14],  6);
   HH(aa, bb, cc, dd, ee, X[ 4],  7);
   HH(ee, aa, bb, cc, dd, X[ 9], 14);
   HH(dd, ee, aa, bb, cc, X[15],  9);
   HH(cc, dd, ee, aa, bb, X[ 8], 13);
   HH(bb, cc, dd, ee, aa, X[ 1], 15);
   HH(aa, bb, cc, dd, ee, X[ 2], 14);
   HH(ee, aa, bb, cc, dd, X[ 7],  8);
   HH(dd, ee, aa, bb, cc, X[ 0], 13);
   HH(cc, dd, ee, aa, bb, X[ 6],  6);
   HH(bb, cc, dd, ee, aa, X[13],  5);
   HH(aa, bb, cc, dd, ee, X[11], 12);
   HH(ee, aa, bb, cc, dd, X[ 5],  7);
   HH(dd, ee, aa, bb, cc, X[12],  5);

   /* round 4 */
   II(cc, dd, ee, aa, bb, X[ 1], 11);
   II(bb, cc, dd, ee, aa, X[ 9], 12);
   II(aa, bb, cc, dd, ee, X[11], 14);
   II(ee, aa, bb, cc, dd, X[10], 15);
   II(dd, ee, aa, bb, cc, X[ 0], 14);
   II(cc, dd, ee, aa, bb, X[ 8], 15);
   II(bb, cc, dd, ee, aa, X[12],  9);
   II(aa, bb, cc, dd, ee, X[ 4],  8);
   II(ee, aa, bb, cc, dd, X[13],  9);
   II(dd, ee, aa, bb, cc, X[ 3], 14);
   II(cc, dd, ee, aa, bb, X[ 7],  5);
   II(bb, cc, dd, ee, aa, X[15],  6);
   II(aa, bb, cc, dd, ee, X[14],  8);
   II(ee, aa, bb, cc, dd, X[ 5],  6);
   II(dd, ee, aa, bb, cc, X[ 6],  5);
   II(cc, dd, ee, aa, bb, X[ 2], 12);

   /* round 5 */
   JJ(bb, cc, dd, ee, aa, X[ 4],  9);
   JJ(aa, bb, cc, dd, ee, X[ 0], 15);
   JJ(ee, aa, bb, cc, dd, X[ 5],  5);
   JJ(dd, ee, aa, bb, cc, X[ 9], 11);
   JJ(cc, dd, ee, aa, bb, X[ 7],  6);
   JJ(bb, cc, dd, ee, aa, X[12],  8);
   JJ(aa, bb, cc, dd, ee, X[ 2], 13);
   JJ(ee, aa, bb, cc, dd, X[10], 12);
   JJ(dd, ee, aa, bb, cc, X[14],  5);
   JJ(cc, dd, ee, aa, bb, X[ 1], 12);
   JJ(bb, cc, dd, ee, aa, X[ 3], 13);
   JJ(aa, bb, cc, dd, ee, X[ 8], 14);
   JJ(ee, aa, bb, cc, dd, X[11], 11);
   JJ(dd, ee, aa, bb, cc, X[ 6],  8);
   JJ(cc, dd, ee, aa, bb, X[15],  5);
   JJ(bb, cc, dd, ee, aa, X[13],  6);

   /* parallel round 1 */
   JJJ(aaa, bbb, ccc, ddd, eee, X[ 5],  8);
   JJJ(eee, aaa, bbb, ccc, ddd, X[14],  9);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 7],  9);
   JJJ(ccc, ddd, eee, aaa, bbb, X[ 0], 11);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 9], 13);
   JJJ(aaa, bbb, ccc, ddd, eee, X[ 2], 15);
   JJJ(eee, aaa, bbb, ccc, ddd, X[11], 15);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 4],  5);
   JJJ(ccc, ddd, eee, aaa, bbb, X[13],  7);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 6],  7);
   JJJ(aaa, bbb, ccc, ddd, eee, X[15],  8);
   JJJ(eee, aaa, bbb, ccc, ddd, X[ 8], 11);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 1], 14);
   JJJ(ccc, ddd, eee, aaa, bbb, X[10], 14);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 3], 12);
   JJJ(aaa, bbb, ccc, ddd, eee, X[12],  6);

   /* parallel round 2 */
   III(eee, aaa, bbb, ccc, ddd, X[ 6],  9); 
   III(ddd, eee, aaa, bbb, ccc, X[11], 13);
   III(ccc, ddd, eee, aaa, bbb, X[ 3], 15);
   III(bbb, ccc, ddd, eee, aaa, X[ 7],  7);
   III(aaa, bbb, ccc, ddd, eee, X[ 0], 12);
   III(eee, aaa, bbb, ccc, ddd, X[13],  8);
   III(ddd, eee, aaa, bbb, ccc, X[ 5],  9);
   III(ccc, ddd, eee, aaa, bbb, X[10], 11);
   III(bbb, ccc, ddd, eee, aaa, X[14],  7);
   III(aaa, bbb, ccc, ddd, eee, X[15],  7);
   III(eee, aaa, bbb, ccc, ddd, X[ 8], 12);
   III(ddd, eee, aaa, bbb, ccc, X[12],  7);
   III(ccc, ddd, eee, aaa, bbb, X[ 4],  6);
   III(bbb, ccc, ddd, eee, aaa, X[ 9], 15);
   III(aaa, bbb, ccc, ddd, eee, X[ 1], 13);
   III(eee, aaa, bbb, ccc, ddd, X[ 2], 11);

   /* parallel round 3 */
   HHH(ddd, eee, aaa, bbb, ccc, X[15],  9);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 5],  7);
   HHH(bbb, ccc, ddd, eee, aaa, X[ 1], 15);
   HHH(aaa, bbb, ccc, ddd, eee, X[ 3], 11);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 7],  8);
   HHH(ddd, eee, aaa, bbb, ccc, X[14],  6);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 6],  6);
   HHH(bbb, ccc, ddd, eee, aaa, X[ 9], 14);
   HHH(aaa, bbb, ccc, ddd, eee, X[11], 12);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 8], 13);
   HHH(ddd, eee, aaa, bbb, ccc, X[12],  5);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 2], 14);
   HHH(bbb, ccc, ddd, eee, aaa, X[10], 13);
   HHH(aaa, bbb, ccc, ddd, eee, X[ 0], 13);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 4],  7);
   HHH(ddd, eee, aaa, bbb, ccc, X[13],  5);

   /* parallel round 4 */   
   GGG(ccc, ddd, eee, aaa, bbb, X[ 8], 15);
   GGG(bbb, ccc, ddd, eee, aaa, X[ 6],  5);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 4],  8);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 1], 11);
   GGG(ddd, eee, aaa, bbb, ccc, X[ 3], 14);
   GGG(ccc, ddd, eee, aaa, bbb, X[11], 14);
   GGG(bbb, ccc, ddd, eee, aaa, X[15],  6);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 0], 14);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 5],  6);
   GGG(ddd, eee, aaa, bbb, ccc, X[12],  9);
   GGG(ccc, ddd, eee, aaa, bbb, X[ 2], 12);
   GGG(bbb, ccc, ddd, eee, aaa, X[13],  9);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 9], 12);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 7],  5);
   GGG(ddd, eee, aaa, bbb, ccc, X[10], 15);
   GGG(ccc, ddd, eee, aaa, bbb, X[14],  8);

   /* parallel round 5 */
   FFF(bbb, ccc, ddd, eee, aaa, X[12] ,  8);
   FFF(aaa, bbb, ccc, ddd, eee, X[15] ,  5);
   FFF(eee, aaa, bbb, ccc, ddd, X[10] , 12);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 4] ,  9);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 1] , 12);
   FFF(bbb, ccc, ddd, eee, aaa, X[ 5] ,  5);
   FFF(aaa, bbb, ccc, ddd, eee, X[ 8] , 14);
   FFF(eee, aaa, bbb, ccc, ddd, X[ 7] ,  6);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 6] ,  8);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 2] , 13);
   FFF(bbb, ccc, ddd, eee, aaa, X[13] ,  6);
   FFF(aaa, bbb, ccc, ddd, eee, X[14] ,  5);
   FFF(eee, aaa, bbb, ccc, ddd, X[ 0] , 15);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 3] , 13);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 9] , 11);
   FFF(bbb, ccc, ddd, eee, aaa, X[11] , 11);

   /* combine results */
   ddd += cc + md->rmd160.state[1];               /* final result for md->rmd160.state[0] */
   md->rmd160.state[1] = md->rmd160.state[2] + dd + eee;
   md->rmd160.state[2] = md->rmd160.state[3] + ee + aaa;
   md->rmd160.state[3] = md->rmd160.state[4] + aa + bbb;
   md->rmd160.state[4] = md->rmd160.state[0] + bb + ccc;
   md->rmd160.state[0] = ddd;

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int rmd160_compress(hash_state *md, unsigned char *buf)
{
   int err;
   err = _rmd160_compress(md, buf);
   burn_stack(sizeof(ulong32) * 26 + sizeof(int));
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int rmd160_init(hash_state * md)
{
   LTC_ARGCHK(md != NULL);
   md->rmd160.state[0] = 0x67452301UL;
   md->rmd160.state[1] = 0xefcdab89UL;
   md->rmd160.state[2] = 0x98badcfeUL;
   md->rmd160.state[3] = 0x10325476UL;
   md->rmd160.state[4] = 0xc3d2e1f0UL;
   md->rmd160.curlen   = 0;
   md->rmd160.length   = 0;
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
HASH_PROCESS(rmd160_process, rmd160_compress, rmd160, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (20 bytes)
   @return CRYPT_OK if successful
*/
int rmd160_done(hash_state * md, unsigned char *out)
{
    int i;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    if (md->rmd160.curlen >= sizeof(md->rmd160.buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    md->rmd160.length += md->rmd160.curlen * 8;

    /* append the '1' bit */
    md->rmd160.buf[md->rmd160.curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->rmd160.curlen > 56) {
        while (md->rmd160.curlen < 64) {
            md->rmd160.buf[md->rmd160.curlen++] = (unsigned char)0;
        }
        rmd160_compress(md, md->rmd160.buf);
        md->rmd160.curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (md->rmd160.curlen < 56) {
        md->rmd160.buf[md->rmd160.curlen++] = (unsigned char)0;
    }

    /* store length */
    STORE64L(md->rmd160.length, md->rmd160.buf+56);
    rmd160_compress(md, md->rmd160.buf);

    /* copy output */
    for (i = 0; i < 5; i++) {
        STORE32L(md->rmd160.state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int rmd160_test(void)
{
#ifndef LTC_TEST
   return CRYPT_NOP;
#else
   static const struct {
        char *msg;
        unsigned char md[20];
   } tests[] = {
   { "",
     { 0x9c, 0x11, 0x85, 0xa5, 0xc5, 0xe9, 0xfc, 0x54, 0x61, 0x28,
       0x08, 0x97, 0x7e, 0xe8, 0xf5, 0x48, 0xb2, 0x25, 0x8d, 0x31 }
   },
   { "a",
     { 0x0b, 0xdc, 0x9d, 0x2d, 0x25, 0x6b, 0x3e, 0xe9, 0xda, 0xae,
       0x34, 0x7b, 0xe6, 0xf4, 0xdc, 0x83, 0x5a, 0x46, 0x7f, 0xfe }
   },
   { "abc",
     { 0x8e, 0xb2, 0x08, 0xf7, 0xe0, 0x5d, 0x98, 0x7a, 0x9b, 0x04,
       0x4a, 0x8e, 0x98, 0xc6, 0xb0, 0x87, 0xf1, 0x5a, 0x0b, 0xfc }
   },
   { "message digest",
     { 0x5d, 0x06, 0x89, 0xef, 0x49, 0xd2, 0xfa, 0xe5, 0x72, 0xb8,
       0x81, 0xb1, 0x23, 0xa8, 0x5f, 0xfa, 0x21, 0x59, 0x5f, 0x36 }
   },
   { "abcdefghijklmnopqrstuvwxyz",
     { 0xf7, 0x1c, 0x27, 0x10, 0x9c, 0x69, 0x2c, 0x1b, 0x56, 0xbb,
       0xdc, 0xeb, 0x5b, 0x9d, 0x28, 0x65, 0xb3, 0x70, 0x8d, 0xbc }
   },
   { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
     { 0x12, 0xa0, 0x53, 0x38, 0x4a, 0x9c, 0x0c, 0x88, 0xe4, 0x05,
       0xa0, 0x6c, 0x27, 0xdc, 0xf4, 0x9a, 0xda, 0x62, 0xeb, 0x2b }
   }
   };
   int x;
   unsigned char buf[20];
   hash_state md;

   for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
       rmd160_init(&md);
       rmd160_process(&md, (unsigned char *)tests[x].msg, strlen(tests[x].msg));
       rmd160_done(&md, buf);
       if (XMEMCMP(buf, tests[x].md, 20) != 0) {
#if 0
          printf("Failed test %d\n", x);
#endif
          return CRYPT_FAIL_TESTVECTOR;
       }
   }
   return CRYPT_OK;
#endif
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/hashes/rmd160.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/rmd256.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @param rmd256.c
   RLTC_MD256 Hash function
*/

#ifdef LTC_RIPEMD256

const struct ltc_hash_descriptor rmd256_desc =
{
    "rmd256",
    11,
    32,
    64,

    /* OID */
   { 1, 3, 36, 3, 2, 3 },
   6,

    &rmd256_init,
    &rmd256_process,
    &rmd256_done,
    &rmd256_test,
    NULL
};

/* the four basic functions F(), G() and H() */
#define F(x, y, z)        ((x) ^ (y) ^ (z))
#define G(x, y, z)        (((x) & (y)) | (~(x) & (z)))
#define H(x, y, z)        (((x) | ~(y)) ^ (z))
#define I(x, y, z)        (((x) & (z)) | ((y) & ~(z)))

/* the eight basic operations FF() through III() */
#define FF(a, b, c, d, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = ROLc((a), (s));

#define GG(a, b, c, d, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
      (a) = ROLc((a), (s));

#define HH(a, b, c, d, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
      (a) = ROLc((a), (s));

#define II(a, b, c, d, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
      (a) = ROLc((a), (s));

#define FFF(a, b, c, d, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = ROLc((a), (s));

#define GGG(a, b, c, d, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x6d703ef3UL;\
      (a) = ROLc((a), (s));

#define HHH(a, b, c, d, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x5c4dd124UL;\
      (a) = ROLc((a), (s));

#define III(a, b, c, d, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x50a28be6UL;\
      (a) = ROLc((a), (s));

#ifdef LTC_CLEAN_STACK
static int _rmd256_compress(hash_state *md, unsigned char *buf)
#else
static int  rmd256_compress(hash_state *md, unsigned char *buf)
#endif
{
   ulong32 aa,bb,cc,dd,aaa,bbb,ccc,ddd,tmp,X[16];
   int i;

   /* load words X */
   for (i = 0; i < 16; i++){
      LOAD32L(X[i], buf + (4 * i));
   }

   /* load state */
   aa = md->rmd256.state[0];
   bb = md->rmd256.state[1];
   cc = md->rmd256.state[2];
   dd = md->rmd256.state[3];
   aaa = md->rmd256.state[4];
   bbb = md->rmd256.state[5];
   ccc = md->rmd256.state[6];
   ddd = md->rmd256.state[7];

   /* round 1 */
   FF(aa, bb, cc, dd, X[ 0], 11);
   FF(dd, aa, bb, cc, X[ 1], 14);
   FF(cc, dd, aa, bb, X[ 2], 15);
   FF(bb, cc, dd, aa, X[ 3], 12);
   FF(aa, bb, cc, dd, X[ 4],  5);
   FF(dd, aa, bb, cc, X[ 5],  8);
   FF(cc, dd, aa, bb, X[ 6],  7);
   FF(bb, cc, dd, aa, X[ 7],  9);
   FF(aa, bb, cc, dd, X[ 8], 11);
   FF(dd, aa, bb, cc, X[ 9], 13);
   FF(cc, dd, aa, bb, X[10], 14);
   FF(bb, cc, dd, aa, X[11], 15);
   FF(aa, bb, cc, dd, X[12],  6);
   FF(dd, aa, bb, cc, X[13],  7);
   FF(cc, dd, aa, bb, X[14],  9);
   FF(bb, cc, dd, aa, X[15],  8);

   /* parallel round 1 */
   III(aaa, bbb, ccc, ddd, X[ 5],  8);
   III(ddd, aaa, bbb, ccc, X[14],  9);
   III(ccc, ddd, aaa, bbb, X[ 7],  9);
   III(bbb, ccc, ddd, aaa, X[ 0], 11);
   III(aaa, bbb, ccc, ddd, X[ 9], 13);
   III(ddd, aaa, bbb, ccc, X[ 2], 15);
   III(ccc, ddd, aaa, bbb, X[11], 15);
   III(bbb, ccc, ddd, aaa, X[ 4],  5);
   III(aaa, bbb, ccc, ddd, X[13],  7);
   III(ddd, aaa, bbb, ccc, X[ 6],  7);
   III(ccc, ddd, aaa, bbb, X[15],  8);
   III(bbb, ccc, ddd, aaa, X[ 8], 11);
   III(aaa, bbb, ccc, ddd, X[ 1], 14);
   III(ddd, aaa, bbb, ccc, X[10], 14);
   III(ccc, ddd, aaa, bbb, X[ 3], 12);
   III(bbb, ccc, ddd, aaa, X[12],  6);

   tmp = aa; aa = aaa; aaa = tmp;

   /* round 2 */
   GG(aa, bb, cc, dd, X[ 7],  7);
   GG(dd, aa, bb, cc, X[ 4],  6);
   GG(cc, dd, aa, bb, X[13],  8);
   GG(bb, cc, dd, aa, X[ 1], 13);
   GG(aa, bb, cc, dd, X[10], 11);
   GG(dd, aa, bb, cc, X[ 6],  9);
   GG(cc, dd, aa, bb, X[15],  7);
   GG(bb, cc, dd, aa, X[ 3], 15);
   GG(aa, bb, cc, dd, X[12],  7);
   GG(dd, aa, bb, cc, X[ 0], 12);
   GG(cc, dd, aa, bb, X[ 9], 15);
   GG(bb, cc, dd, aa, X[ 5],  9);
   GG(aa, bb, cc, dd, X[ 2], 11);
   GG(dd, aa, bb, cc, X[14],  7);
   GG(cc, dd, aa, bb, X[11], 13);
   GG(bb, cc, dd, aa, X[ 8], 12);

   /* parallel round 2 */
   HHH(aaa, bbb, ccc, ddd, X[ 6],  9);
   HHH(ddd, aaa, bbb, ccc, X[11], 13);
   HHH(ccc, ddd, aaa, bbb, X[ 3], 15);
   HHH(bbb, ccc, ddd, aaa, X[ 7],  7);
   HHH(aaa, bbb, ccc, ddd, X[ 0], 12);
   HHH(ddd, aaa, bbb, ccc, X[13],  8);
   HHH(ccc, ddd, aaa, bbb, X[ 5],  9);
   HHH(bbb, ccc, ddd, aaa, X[10], 11);
   HHH(aaa, bbb, ccc, ddd, X[14],  7);
   HHH(ddd, aaa, bbb, ccc, X[15],  7);
   HHH(ccc, ddd, aaa, bbb, X[ 8], 12);
   HHH(bbb, ccc, ddd, aaa, X[12],  7);
   HHH(aaa, bbb, ccc, ddd, X[ 4],  6);
   HHH(ddd, aaa, bbb, ccc, X[ 9], 15);
   HHH(ccc, ddd, aaa, bbb, X[ 1], 13);
   HHH(bbb, ccc, ddd, aaa, X[ 2], 11);

   tmp = bb; bb = bbb; bbb = tmp;

   /* round 3 */
   HH(aa, bb, cc, dd, X[ 3], 11);
   HH(dd, aa, bb, cc, X[10], 13);
   HH(cc, dd, aa, bb, X[14],  6);
   HH(bb, cc, dd, aa, X[ 4],  7);
   HH(aa, bb, cc, dd, X[ 9], 14);
   HH(dd, aa, bb, cc, X[15],  9);
   HH(cc, dd, aa, bb, X[ 8], 13);
   HH(bb, cc, dd, aa, X[ 1], 15);
   HH(aa, bb, cc, dd, X[ 2], 14);
   HH(dd, aa, bb, cc, X[ 7],  8);
   HH(cc, dd, aa, bb, X[ 0], 13);
   HH(bb, cc, dd, aa, X[ 6],  6);
   HH(aa, bb, cc, dd, X[13],  5);
   HH(dd, aa, bb, cc, X[11], 12);
   HH(cc, dd, aa, bb, X[ 5],  7);
   HH(bb, cc, dd, aa, X[12],  5);

   /* parallel round 3 */
   GGG(aaa, bbb, ccc, ddd, X[15],  9);
   GGG(ddd, aaa, bbb, ccc, X[ 5],  7);
   GGG(ccc, ddd, aaa, bbb, X[ 1], 15);
   GGG(bbb, ccc, ddd, aaa, X[ 3], 11);
   GGG(aaa, bbb, ccc, ddd, X[ 7],  8);
   GGG(ddd, aaa, bbb, ccc, X[14],  6);
   GGG(ccc, ddd, aaa, bbb, X[ 6],  6);
   GGG(bbb, ccc, ddd, aaa, X[ 9], 14);
   GGG(aaa, bbb, ccc, ddd, X[11], 12);
   GGG(ddd, aaa, bbb, ccc, X[ 8], 13);
   GGG(ccc, ddd, aaa, bbb, X[12],  5);
   GGG(bbb, ccc, ddd, aaa, X[ 2], 14);
   GGG(aaa, bbb, ccc, ddd, X[10], 13);
   GGG(ddd, aaa, bbb, ccc, X[ 0], 13);
   GGG(ccc, ddd, aaa, bbb, X[ 4],  7);
   GGG(bbb, ccc, ddd, aaa, X[13],  5);

   tmp = cc; cc = ccc; ccc = tmp;

   /* round 4 */
   II(aa, bb, cc, dd, X[ 1], 11);
   II(dd, aa, bb, cc, X[ 9], 12);
   II(cc, dd, aa, bb, X[11], 14);
   II(bb, cc, dd, aa, X[10], 15);
   II(aa, bb, cc, dd, X[ 0], 14);
   II(dd, aa, bb, cc, X[ 8], 15);
   II(cc, dd, aa, bb, X[12],  9);
   II(bb, cc, dd, aa, X[ 4],  8);
   II(aa, bb, cc, dd, X[13],  9);
   II(dd, aa, bb, cc, X[ 3], 14);
   II(cc, dd, aa, bb, X[ 7],  5);
   II(bb, cc, dd, aa, X[15],  6);
   II(aa, bb, cc, dd, X[14],  8);
   II(dd, aa, bb, cc, X[ 5],  6);
   II(cc, dd, aa, bb, X[ 6],  5);
   II(bb, cc, dd, aa, X[ 2], 12);

   /* parallel round 4 */
   FFF(aaa, bbb, ccc, ddd, X[ 8], 15);
   FFF(ddd, aaa, bbb, ccc, X[ 6],  5);
   FFF(ccc, ddd, aaa, bbb, X[ 4],  8);
   FFF(bbb, ccc, ddd, aaa, X[ 1], 11);
   FFF(aaa, bbb, ccc, ddd, X[ 3], 14);
   FFF(ddd, aaa, bbb, ccc, X[11], 14);
   FFF(ccc, ddd, aaa, bbb, X[15],  6);
   FFF(bbb, ccc, ddd, aaa, X[ 0], 14);
   FFF(aaa, bbb, ccc, ddd, X[ 5],  6);
   FFF(ddd, aaa, bbb, ccc, X[12],  9);
   FFF(ccc, ddd, aaa, bbb, X[ 2], 12);
   FFF(bbb, ccc, ddd, aaa, X[13],  9);
   FFF(aaa, bbb, ccc, ddd, X[ 9], 12);
   FFF(ddd, aaa, bbb, ccc, X[ 7],  5);
   FFF(ccc, ddd, aaa, bbb, X[10], 15);
   FFF(bbb, ccc, ddd, aaa, X[14],  8);

   tmp = dd; dd = ddd; ddd = tmp;

   /* combine results */
   md->rmd256.state[0] += aa;
   md->rmd256.state[1] += bb;
   md->rmd256.state[2] += cc;
   md->rmd256.state[3] += dd;
   md->rmd256.state[4] += aaa;
   md->rmd256.state[5] += bbb;
   md->rmd256.state[6] += ccc;
   md->rmd256.state[7] += ddd;

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int rmd256_compress(hash_state *md, unsigned char *buf)
{
   int err;
   err = _rmd256_compress(md, buf);
   burn_stack(sizeof(ulong32) * 25 + sizeof(int));
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int rmd256_init(hash_state * md)
{
   LTC_ARGCHK(md != NULL);
   md->rmd256.state[0] = 0x67452301UL;
   md->rmd256.state[1] = 0xefcdab89UL;
   md->rmd256.state[2] = 0x98badcfeUL;
   md->rmd256.state[3] = 0x10325476UL;
   md->rmd256.state[4] = 0x76543210UL;
   md->rmd256.state[5] = 0xfedcba98UL;
   md->rmd256.state[6] = 0x89abcdefUL;
   md->rmd256.state[7] = 0x01234567UL;
   md->rmd256.curlen   = 0;
   md->rmd256.length   = 0;
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
HASH_PROCESS(rmd256_process, rmd256_compress, rmd256, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (16 bytes)
   @return CRYPT_OK if successful
*/
int rmd256_done(hash_state * md, unsigned char *out)
{
    int i;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    if (md->rmd256.curlen >= sizeof(md->rmd256.buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    md->rmd256.length += md->rmd256.curlen * 8;

    /* append the '1' bit */
    md->rmd256.buf[md->rmd256.curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->rmd256.curlen > 56) {
        while (md->rmd256.curlen < 64) {
            md->rmd256.buf[md->rmd256.curlen++] = (unsigned char)0;
        }
        rmd256_compress(md, md->rmd256.buf);
        md->rmd256.curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (md->rmd256.curlen < 56) {
        md->rmd256.buf[md->rmd256.curlen++] = (unsigned char)0;
    }

    /* store length */
    STORE64L(md->rmd256.length, md->rmd256.buf+56);
    rmd256_compress(md, md->rmd256.buf);

    /* copy output */
    for (i = 0; i < 8; i++) {
        STORE32L(md->rmd256.state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
   return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int rmd256_test(void)
{
#ifndef LTC_TEST
   return CRYPT_NOP;
#else
   static const struct {
        char *msg;
        unsigned char md[32];
   } tests[] = {
   { "",
     { 0x02, 0xba, 0x4c, 0x4e, 0x5f, 0x8e, 0xcd, 0x18,
       0x77, 0xfc, 0x52, 0xd6, 0x4d, 0x30, 0xe3, 0x7a,
       0x2d, 0x97, 0x74, 0xfb, 0x1e, 0x5d, 0x02, 0x63,
       0x80, 0xae, 0x01, 0x68, 0xe3, 0xc5, 0x52, 0x2d }
   },
   { "a",
     { 0xf9, 0x33, 0x3e, 0x45, 0xd8, 0x57, 0xf5, 0xd9,
       0x0a, 0x91, 0xba, 0xb7, 0x0a, 0x1e, 0xba, 0x0c,
       0xfb, 0x1b, 0xe4, 0xb0, 0x78, 0x3c, 0x9a, 0xcf,
       0xcd, 0x88, 0x3a, 0x91, 0x34, 0x69, 0x29, 0x25 }
   },
   { "abc",
     { 0xaf, 0xbd, 0x6e, 0x22, 0x8b, 0x9d, 0x8c, 0xbb,
       0xce, 0xf5, 0xca, 0x2d, 0x03, 0xe6, 0xdb, 0xa1,
       0x0a, 0xc0, 0xbc, 0x7d, 0xcb, 0xe4, 0x68, 0x0e,
       0x1e, 0x42, 0xd2, 0xe9, 0x75, 0x45, 0x9b, 0x65 }
   },
   { "message digest",
     { 0x87, 0xe9, 0x71, 0x75, 0x9a, 0x1c, 0xe4, 0x7a,
       0x51, 0x4d, 0x5c, 0x91, 0x4c, 0x39, 0x2c, 0x90,
       0x18, 0xc7, 0xc4, 0x6b, 0xc1, 0x44, 0x65, 0x55,
       0x4a, 0xfc, 0xdf, 0x54, 0xa5, 0x07, 0x0c, 0x0e }
   },
   { "abcdefghijklmnopqrstuvwxyz",
     { 0x64, 0x9d, 0x30, 0x34, 0x75, 0x1e, 0xa2, 0x16,
       0x77, 0x6b, 0xf9, 0xa1, 0x8a, 0xcc, 0x81, 0xbc,
       0x78, 0x96, 0x11, 0x8a, 0x51, 0x97, 0x96, 0x87,
       0x82, 0xdd, 0x1f, 0xd9, 0x7d, 0x8d, 0x51, 0x33 }
   },
   { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
     { 0x57, 0x40, 0xa4, 0x08, 0xac, 0x16, 0xb7, 0x20,
       0xb8, 0x44, 0x24, 0xae, 0x93, 0x1c, 0xbb, 0x1f,
       0xe3, 0x63, 0xd1, 0xd0, 0xbf, 0x40, 0x17, 0xf1,
       0xa8, 0x9f, 0x7e, 0xa6, 0xde, 0x77, 0xa0, 0xb8 }
   }
   };
   int x;
   unsigned char buf[32];
   hash_state md;

   for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
       rmd256_init(&md);
       rmd256_process(&md, (unsigned char *)tests[x].msg, strlen(tests[x].msg));
       rmd256_done(&md, buf);
       if (XMEMCMP(buf, tests[x].md, 32) != 0) {
       #if 0
          printf("Failed test %d\n", x);
       #endif
          return CRYPT_FAIL_TESTVECTOR;
       }
   }
   return CRYPT_OK;
#endif
}

#endif

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/rmd320.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file rmd320.c
   RMD320 hash function
*/

#ifdef LTC_RIPEMD320

const struct ltc_hash_descriptor rmd320_desc =
{
    "rmd320",
    12,
    40,
    64,

    /* OID */
   { 0 },
   0,

    &rmd320_init,
    &rmd320_process,
    &rmd320_done,
    &rmd320_test,
    NULL
};

/* the five basic functions F(), G() and H() */
#define F(x, y, z)        ((x) ^ (y) ^ (z))
#define G(x, y, z)        (((x) & (y)) | (~(x) & (z)))
#define H(x, y, z)        (((x) | ~(y)) ^ (z))
#define I(x, y, z)        (((x) & (z)) | ((y) & ~(z)))
#define J(x, y, z)        ((x) ^ ((y) | ~(z)))

/* the ten basic operations FF() through III() */
#define FF(a, b, c, d, e, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define GG(a, b, c, d, e, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define HH(a, b, c, d, e, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6ed9eba1UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define II(a, b, c, d, e, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x8f1bbcdcUL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define JJ(a, b, c, d, e, x, s)        \
      (a) += J((b), (c), (d)) + (x) + 0xa953fd4eUL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define FFF(a, b, c, d, e, x, s)        \
      (a) += F((b), (c), (d)) + (x);\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define GGG(a, b, c, d, e, x, s)        \
      (a) += G((b), (c), (d)) + (x) + 0x7a6d76e9UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define HHH(a, b, c, d, e, x, s)        \
      (a) += H((b), (c), (d)) + (x) + 0x6d703ef3UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define III(a, b, c, d, e, x, s)        \
      (a) += I((b), (c), (d)) + (x) + 0x5c4dd124UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);

#define JJJ(a, b, c, d, e, x, s)        \
      (a) += J((b), (c), (d)) + (x) + 0x50a28be6UL;\
      (a) = ROLc((a), (s)) + (e);\
      (c) = ROLc((c), 10);


#ifdef LTC_CLEAN_STACK
static int _rmd320_compress(hash_state *md, unsigned char *buf)
#else
static int  rmd320_compress(hash_state *md, unsigned char *buf)
#endif
{
   ulong32 aa,bb,cc,dd,ee,aaa,bbb,ccc,ddd,eee,tmp,X[16];
   int i;

   /* load words X */
   for (i = 0; i < 16; i++){
      LOAD32L(X[i], buf + (4 * i));
   }

   /* load state */
   aa = md->rmd320.state[0];
   bb = md->rmd320.state[1];
   cc = md->rmd320.state[2];
   dd = md->rmd320.state[3];
   ee = md->rmd320.state[4];
   aaa = md->rmd320.state[5];
   bbb = md->rmd320.state[6];
   ccc = md->rmd320.state[7];
   ddd = md->rmd320.state[8];
   eee = md->rmd320.state[9];

   /* round 1 */
   FF(aa, bb, cc, dd, ee, X[ 0], 11);
   FF(ee, aa, bb, cc, dd, X[ 1], 14);
   FF(dd, ee, aa, bb, cc, X[ 2], 15);
   FF(cc, dd, ee, aa, bb, X[ 3], 12);
   FF(bb, cc, dd, ee, aa, X[ 4],  5);
   FF(aa, bb, cc, dd, ee, X[ 5],  8);
   FF(ee, aa, bb, cc, dd, X[ 6],  7);
   FF(dd, ee, aa, bb, cc, X[ 7],  9);
   FF(cc, dd, ee, aa, bb, X[ 8], 11);
   FF(bb, cc, dd, ee, aa, X[ 9], 13);
   FF(aa, bb, cc, dd, ee, X[10], 14);
   FF(ee, aa, bb, cc, dd, X[11], 15);
   FF(dd, ee, aa, bb, cc, X[12],  6);
   FF(cc, dd, ee, aa, bb, X[13],  7);
   FF(bb, cc, dd, ee, aa, X[14],  9);
   FF(aa, bb, cc, dd, ee, X[15],  8);

   /* parallel round 1 */
   JJJ(aaa, bbb, ccc, ddd, eee, X[ 5],  8);
   JJJ(eee, aaa, bbb, ccc, ddd, X[14],  9);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 7],  9);
   JJJ(ccc, ddd, eee, aaa, bbb, X[ 0], 11);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 9], 13);
   JJJ(aaa, bbb, ccc, ddd, eee, X[ 2], 15);
   JJJ(eee, aaa, bbb, ccc, ddd, X[11], 15);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 4],  5);
   JJJ(ccc, ddd, eee, aaa, bbb, X[13],  7);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 6],  7);
   JJJ(aaa, bbb, ccc, ddd, eee, X[15],  8);
   JJJ(eee, aaa, bbb, ccc, ddd, X[ 8], 11);
   JJJ(ddd, eee, aaa, bbb, ccc, X[ 1], 14);
   JJJ(ccc, ddd, eee, aaa, bbb, X[10], 14);
   JJJ(bbb, ccc, ddd, eee, aaa, X[ 3], 12);
   JJJ(aaa, bbb, ccc, ddd, eee, X[12],  6);

   tmp = aa; aa = aaa; aaa = tmp;

   /* round 2 */
   GG(ee, aa, bb, cc, dd, X[ 7],  7);
   GG(dd, ee, aa, bb, cc, X[ 4],  6);
   GG(cc, dd, ee, aa, bb, X[13],  8);
   GG(bb, cc, dd, ee, aa, X[ 1], 13);
   GG(aa, bb, cc, dd, ee, X[10], 11);
   GG(ee, aa, bb, cc, dd, X[ 6],  9);
   GG(dd, ee, aa, bb, cc, X[15],  7);
   GG(cc, dd, ee, aa, bb, X[ 3], 15);
   GG(bb, cc, dd, ee, aa, X[12],  7);
   GG(aa, bb, cc, dd, ee, X[ 0], 12);
   GG(ee, aa, bb, cc, dd, X[ 9], 15);
   GG(dd, ee, aa, bb, cc, X[ 5],  9);
   GG(cc, dd, ee, aa, bb, X[ 2], 11);
   GG(bb, cc, dd, ee, aa, X[14],  7);
   GG(aa, bb, cc, dd, ee, X[11], 13);
   GG(ee, aa, bb, cc, dd, X[ 8], 12);

   /* parallel round 2 */
   III(eee, aaa, bbb, ccc, ddd, X[ 6],  9);
   III(ddd, eee, aaa, bbb, ccc, X[11], 13);
   III(ccc, ddd, eee, aaa, bbb, X[ 3], 15);
   III(bbb, ccc, ddd, eee, aaa, X[ 7],  7);
   III(aaa, bbb, ccc, ddd, eee, X[ 0], 12);
   III(eee, aaa, bbb, ccc, ddd, X[13],  8);
   III(ddd, eee, aaa, bbb, ccc, X[ 5],  9);
   III(ccc, ddd, eee, aaa, bbb, X[10], 11);
   III(bbb, ccc, ddd, eee, aaa, X[14],  7);
   III(aaa, bbb, ccc, ddd, eee, X[15],  7);
   III(eee, aaa, bbb, ccc, ddd, X[ 8], 12);
   III(ddd, eee, aaa, bbb, ccc, X[12],  7);
   III(ccc, ddd, eee, aaa, bbb, X[ 4],  6);
   III(bbb, ccc, ddd, eee, aaa, X[ 9], 15);
   III(aaa, bbb, ccc, ddd, eee, X[ 1], 13);
   III(eee, aaa, bbb, ccc, ddd, X[ 2], 11);

   tmp = bb; bb = bbb; bbb = tmp;

   /* round 3 */
   HH(dd, ee, aa, bb, cc, X[ 3], 11);
   HH(cc, dd, ee, aa, bb, X[10], 13);
   HH(bb, cc, dd, ee, aa, X[14],  6);
   HH(aa, bb, cc, dd, ee, X[ 4],  7);
   HH(ee, aa, bb, cc, dd, X[ 9], 14);
   HH(dd, ee, aa, bb, cc, X[15],  9);
   HH(cc, dd, ee, aa, bb, X[ 8], 13);
   HH(bb, cc, dd, ee, aa, X[ 1], 15);
   HH(aa, bb, cc, dd, ee, X[ 2], 14);
   HH(ee, aa, bb, cc, dd, X[ 7],  8);
   HH(dd, ee, aa, bb, cc, X[ 0], 13);
   HH(cc, dd, ee, aa, bb, X[ 6],  6);
   HH(bb, cc, dd, ee, aa, X[13],  5);
   HH(aa, bb, cc, dd, ee, X[11], 12);
   HH(ee, aa, bb, cc, dd, X[ 5],  7);
   HH(dd, ee, aa, bb, cc, X[12],  5);

   /* parallel round 3 */
   HHH(ddd, eee, aaa, bbb, ccc, X[15],  9);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 5],  7);
   HHH(bbb, ccc, ddd, eee, aaa, X[ 1], 15);
   HHH(aaa, bbb, ccc, ddd, eee, X[ 3], 11);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 7],  8);
   HHH(ddd, eee, aaa, bbb, ccc, X[14],  6);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 6],  6);
   HHH(bbb, ccc, ddd, eee, aaa, X[ 9], 14);
   HHH(aaa, bbb, ccc, ddd, eee, X[11], 12);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 8], 13);
   HHH(ddd, eee, aaa, bbb, ccc, X[12],  5);
   HHH(ccc, ddd, eee, aaa, bbb, X[ 2], 14);
   HHH(bbb, ccc, ddd, eee, aaa, X[10], 13);
   HHH(aaa, bbb, ccc, ddd, eee, X[ 0], 13);
   HHH(eee, aaa, bbb, ccc, ddd, X[ 4],  7);
   HHH(ddd, eee, aaa, bbb, ccc, X[13],  5);

   tmp = cc; cc = ccc; ccc = tmp;

   /* round 4 */
   II(cc, dd, ee, aa, bb, X[ 1], 11);
   II(bb, cc, dd, ee, aa, X[ 9], 12);
   II(aa, bb, cc, dd, ee, X[11], 14);
   II(ee, aa, bb, cc, dd, X[10], 15);
   II(dd, ee, aa, bb, cc, X[ 0], 14);
   II(cc, dd, ee, aa, bb, X[ 8], 15);
   II(bb, cc, dd, ee, aa, X[12],  9);
   II(aa, bb, cc, dd, ee, X[ 4],  8);
   II(ee, aa, bb, cc, dd, X[13],  9);
   II(dd, ee, aa, bb, cc, X[ 3], 14);
   II(cc, dd, ee, aa, bb, X[ 7],  5);
   II(bb, cc, dd, ee, aa, X[15],  6);
   II(aa, bb, cc, dd, ee, X[14],  8);
   II(ee, aa, bb, cc, dd, X[ 5],  6);
   II(dd, ee, aa, bb, cc, X[ 6],  5);
   II(cc, dd, ee, aa, bb, X[ 2], 12);

   /* parallel round 4 */
   GGG(ccc, ddd, eee, aaa, bbb, X[ 8], 15);
   GGG(bbb, ccc, ddd, eee, aaa, X[ 6],  5);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 4],  8);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 1], 11);
   GGG(ddd, eee, aaa, bbb, ccc, X[ 3], 14);
   GGG(ccc, ddd, eee, aaa, bbb, X[11], 14);
   GGG(bbb, ccc, ddd, eee, aaa, X[15],  6);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 0], 14);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 5],  6);
   GGG(ddd, eee, aaa, bbb, ccc, X[12],  9);
   GGG(ccc, ddd, eee, aaa, bbb, X[ 2], 12);
   GGG(bbb, ccc, ddd, eee, aaa, X[13],  9);
   GGG(aaa, bbb, ccc, ddd, eee, X[ 9], 12);
   GGG(eee, aaa, bbb, ccc, ddd, X[ 7],  5);
   GGG(ddd, eee, aaa, bbb, ccc, X[10], 15);
   GGG(ccc, ddd, eee, aaa, bbb, X[14],  8);

   tmp = dd; dd = ddd; ddd = tmp;

   /* round 5 */
   JJ(bb, cc, dd, ee, aa, X[ 4],  9);
   JJ(aa, bb, cc, dd, ee, X[ 0], 15);
   JJ(ee, aa, bb, cc, dd, X[ 5],  5);
   JJ(dd, ee, aa, bb, cc, X[ 9], 11);
   JJ(cc, dd, ee, aa, bb, X[ 7],  6);
   JJ(bb, cc, dd, ee, aa, X[12],  8);
   JJ(aa, bb, cc, dd, ee, X[ 2], 13);
   JJ(ee, aa, bb, cc, dd, X[10], 12);
   JJ(dd, ee, aa, bb, cc, X[14],  5);
   JJ(cc, dd, ee, aa, bb, X[ 1], 12);
   JJ(bb, cc, dd, ee, aa, X[ 3], 13);
   JJ(aa, bb, cc, dd, ee, X[ 8], 14);
   JJ(ee, aa, bb, cc, dd, X[11], 11);
   JJ(dd, ee, aa, bb, cc, X[ 6],  8);
   JJ(cc, dd, ee, aa, bb, X[15],  5);
   JJ(bb, cc, dd, ee, aa, X[13],  6);

   /* parallel round 5 */
   FFF(bbb, ccc, ddd, eee, aaa, X[12] ,  8);
   FFF(aaa, bbb, ccc, ddd, eee, X[15] ,  5);
   FFF(eee, aaa, bbb, ccc, ddd, X[10] , 12);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 4] ,  9);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 1] , 12);
   FFF(bbb, ccc, ddd, eee, aaa, X[ 5] ,  5);
   FFF(aaa, bbb, ccc, ddd, eee, X[ 8] , 14);
   FFF(eee, aaa, bbb, ccc, ddd, X[ 7] ,  6);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 6] ,  8);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 2] , 13);
   FFF(bbb, ccc, ddd, eee, aaa, X[13] ,  6);
   FFF(aaa, bbb, ccc, ddd, eee, X[14] ,  5);
   FFF(eee, aaa, bbb, ccc, ddd, X[ 0] , 15);
   FFF(ddd, eee, aaa, bbb, ccc, X[ 3] , 13);
   FFF(ccc, ddd, eee, aaa, bbb, X[ 9] , 11);
   FFF(bbb, ccc, ddd, eee, aaa, X[11] , 11);

   tmp = ee; ee = eee; eee = tmp;

   /* combine results */
   md->rmd320.state[0] += aa;
   md->rmd320.state[1] += bb;
   md->rmd320.state[2] += cc;
   md->rmd320.state[3] += dd;
   md->rmd320.state[4] += ee;
   md->rmd320.state[5] += aaa;
   md->rmd320.state[6] += bbb;
   md->rmd320.state[7] += ccc;
   md->rmd320.state[8] += ddd;
   md->rmd320.state[9] += eee;

   return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int rmd320_compress(hash_state *md, unsigned char *buf)
{
   int err;
   err = _rmd320_compress(md, buf);
   burn_stack(sizeof(ulong32) * 27 + sizeof(int));
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int rmd320_init(hash_state * md)
{
   LTC_ARGCHK(md != NULL);
   md->rmd320.state[0] = 0x67452301UL;
   md->rmd320.state[1] = 0xefcdab89UL;
   md->rmd320.state[2] = 0x98badcfeUL;
   md->rmd320.state[3] = 0x10325476UL;
   md->rmd320.state[4] = 0xc3d2e1f0UL;
   md->rmd320.state[5] = 0x76543210UL;
   md->rmd320.state[6] = 0xfedcba98UL;
   md->rmd320.state[7] = 0x89abcdefUL;
   md->rmd320.state[8] = 0x01234567UL;
   md->rmd320.state[9] = 0x3c2d1e0fUL;
   md->rmd320.curlen   = 0;
   md->rmd320.length   = 0;
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
HASH_PROCESS(rmd320_process, rmd320_compress, rmd320, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (20 bytes)
   @return CRYPT_OK if successful
*/
int rmd320_done(hash_state * md, unsigned char *out)
{
    int i;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    if (md->rmd320.curlen >= sizeof(md->rmd320.buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    md->rmd320.length += md->rmd320.curlen * 8;

    /* append the '1' bit */
    md->rmd320.buf[md->rmd320.curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->rmd320.curlen > 56) {
        while (md->rmd320.curlen < 64) {
            md->rmd320.buf[md->rmd320.curlen++] = (unsigned char)0;
        }
        rmd320_compress(md, md->rmd320.buf);
        md->rmd320.curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (md->rmd320.curlen < 56) {
        md->rmd320.buf[md->rmd320.curlen++] = (unsigned char)0;
    }

    /* store length */
    STORE64L(md->rmd320.length, md->rmd320.buf+56);
    rmd320_compress(md, md->rmd320.buf);

    /* copy output */
    for (i = 0; i < 10; i++) {
        STORE32L(md->rmd320.state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/
int rmd320_test(void)
{
#ifndef LTC_TEST
   return CRYPT_NOP;
#else
   static const struct {
        char *msg;
        unsigned char md[40];
   } tests[] = {
   { "",
     { 0x22, 0xd6, 0x5d, 0x56, 0x61, 0x53, 0x6c, 0xdc, 0x75, 0xc1,
       0xfd, 0xf5, 0xc6, 0xde, 0x7b, 0x41, 0xb9, 0xf2, 0x73, 0x25,
       0xeb, 0xc6, 0x1e, 0x85, 0x57, 0x17, 0x7d, 0x70, 0x5a, 0x0e,
       0xc8, 0x80, 0x15, 0x1c, 0x3a, 0x32, 0xa0, 0x08, 0x99, 0xb8 }
   },
   { "a",
     { 0xce, 0x78, 0x85, 0x06, 0x38, 0xf9, 0x26, 0x58, 0xa5, 0xa5,
       0x85, 0x09, 0x75, 0x79, 0x92, 0x6d, 0xda, 0x66, 0x7a, 0x57,
       0x16, 0x56, 0x2c, 0xfc, 0xf6, 0xfb, 0xe7, 0x7f, 0x63, 0x54,
       0x2f, 0x99, 0xb0, 0x47, 0x05, 0xd6, 0x97, 0x0d, 0xff, 0x5d }
   },
   { "abc",
     { 0xde, 0x4c, 0x01, 0xb3, 0x05, 0x4f, 0x89, 0x30, 0xa7, 0x9d,
       0x09, 0xae, 0x73, 0x8e, 0x92, 0x30, 0x1e, 0x5a, 0x17, 0x08,
       0x5b, 0xef, 0xfd, 0xc1, 0xb8, 0xd1, 0x16, 0x71, 0x3e, 0x74,
       0xf8, 0x2f, 0xa9, 0x42, 0xd6, 0x4c, 0xdb, 0xc4, 0x68, 0x2d }
   },
   { "message digest",
     { 0x3a, 0x8e, 0x28, 0x50, 0x2e, 0xd4, 0x5d, 0x42, 0x2f, 0x68,
       0x84, 0x4f, 0x9d, 0xd3, 0x16, 0xe7, 0xb9, 0x85, 0x33, 0xfa,
       0x3f, 0x2a, 0x91, 0xd2, 0x9f, 0x84, 0xd4, 0x25, 0xc8, 0x8d,
       0x6b, 0x4e, 0xff, 0x72, 0x7d, 0xf6, 0x6a, 0x7c, 0x01, 0x97 }
   },
   { "abcdefghijklmnopqrstuvwxyz",
     { 0xca, 0xbd, 0xb1, 0x81, 0x0b, 0x92, 0x47, 0x0a, 0x20, 0x93,
       0xaa, 0x6b, 0xce, 0x05, 0x95, 0x2c, 0x28, 0x34, 0x8c, 0xf4,
       0x3f, 0xf6, 0x08, 0x41, 0x97, 0x51, 0x66, 0xbb, 0x40, 0xed,
       0x23, 0x40, 0x04, 0xb8, 0x82, 0x44, 0x63, 0xe6, 0xb0, 0x09 }
   },
   { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
     { 0xd0, 0x34, 0xa7, 0x95, 0x0c, 0xf7, 0x22, 0x02, 0x1b, 0xa4,
       0xb8, 0x4d, 0xf7, 0x69, 0xa5, 0xde, 0x20, 0x60, 0xe2, 0x59,
       0xdf, 0x4c, 0x9b, 0xb4, 0xa4, 0x26, 0x8c, 0x0e, 0x93, 0x5b,
       0xbc, 0x74, 0x70, 0xa9, 0x69, 0xc9, 0xd0, 0x72, 0xa1, 0xac }
   }
   };
   int x;
   unsigned char buf[40];
   hash_state md;

   for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
       rmd320_init(&md);
       rmd320_process(&md, (unsigned char *)tests[x].msg, strlen(tests[x].msg));
       rmd320_done(&md, buf);
       if (XMEMCMP(buf, tests[x].md, 40) != 0) {
#if 0
          printf("Failed test %d\n", x);
#endif
          return CRYPT_FAIL_TESTVECTOR;
       }
   }
   return CRYPT_OK;
#endif
}

#endif

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/sha1.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file sha1.c
  LTC_SHA1 code by Tom St Denis 
*/


#ifdef LTC_SHA1

const struct ltc_hash_descriptor sha1_desc =
{
    "sha1",
    2,
    20,
    64,

    /* OID */
   { 1, 3, 14, 3, 2, 26,  },
   6,

    &sha1_init,
    &sha1_process,
    &sha1_done,
    &sha1_test,
    NULL
};

#define F0(x,y,z)  (z ^ (x & (y ^ z)))
#define F1(x,y,z)  (x ^ y ^ z)
#define F2(x,y,z)  ((x & y) | (z & (x | y)))
#define F3(x,y,z)  (x ^ y ^ z)

#ifdef LTC_CLEAN_STACK
static int _sha1_compress(hash_state *md, unsigned char *buf)
#else
static int  sha1_compress(hash_state *md, unsigned char *buf)
#endif
{
    ulong32 a,b,c,d,e,W[80],i;
#ifdef LTC_SMALL_CODE
    ulong32 t;
#endif

    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LOAD32H(W[i], buf + (4*i));
    }

    /* copy state */
    a = md->sha1.state[0];
    b = md->sha1.state[1];
    c = md->sha1.state[2];
    d = md->sha1.state[3];
    e = md->sha1.state[4];

    /* expand it */
    for (i = 16; i < 80; i++) {
        W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); 
    }

    /* compress */
    /* round one */
    #define FF0(a,b,c,d,e,i) e = (ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROLc(b, 30);
    #define FF1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30);
    #define FF2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30);
    #define FF3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30);
 
#ifdef LTC_SMALL_CODE
 
    for (i = 0; i < 20; ) {
       FF0(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 40; ) {
       FF1(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 60; ) {
       FF2(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }

    for (; i < 80; ) {
       FF3(a,b,c,d,e,i++); t = e; e = d; d = c; c = b; b = a; a = t;
    }

#else

    for (i = 0; i < 20; ) {
       FF0(a,b,c,d,e,i++);
       FF0(e,a,b,c,d,i++);
       FF0(d,e,a,b,c,i++);
       FF0(c,d,e,a,b,i++);
       FF0(b,c,d,e,a,i++);
    }

    /* round two */
    for (; i < 40; )  { 
       FF1(a,b,c,d,e,i++);
       FF1(e,a,b,c,d,i++);
       FF1(d,e,a,b,c,i++);
       FF1(c,d,e,a,b,i++);
       FF1(b,c,d,e,a,i++);
    }

    /* round three */
    for (; i < 60; )  { 
       FF2(a,b,c,d,e,i++);
       FF2(e,a,b,c,d,i++);
       FF2(d,e,a,b,c,i++);
       FF2(c,d,e,a,b,i++);
       FF2(b,c,d,e,a,i++);
    }

    /* round four */
    for (; i < 80; )  { 
       FF3(a,b,c,d,e,i++);
       FF3(e,a,b,c,d,i++);
       FF3(d,e,a,b,c,i++);
       FF3(c,d,e,a,b,i++);
       FF3(b,c,d,e,a,i++);
    }
#endif

    #undef FF0
    #undef FF1
    #undef FF2
    #undef FF3

    /* store */
    md->sha1.state[0] = md->sha1.state[0] + a;
    md->sha1.state[1] = md->sha1.state[1] + b;
    md->sha1.state[2] = md->sha1.state[2] + c;
    md->sha1.state[3] = md->sha1.state[3] + d;
    md->sha1.state[4] = md->sha1.state[4] + e;

    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int sha1_compress(hash_state *md, unsigned char *buf)
{
   int err;
   err = _sha1_compress(md, buf);
   burn_stack(sizeof(ulong32) * 87);
   return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int sha1_init(hash_state * md)
{
   LTC_ARGCHK(md != NULL);
   md->sha1.state[0] = 0x67452301UL;
   md->sha1.state[1] = 0xefcdab89UL;
   md->sha1.state[2] = 0x98badcfeUL;
   md->sha1.state[3] = 0x10325476UL;
   md->sha1.state[4] = 0xc3d2e1f0UL;
   md->sha1.curlen = 0;
   md->sha1.length = 0;
   return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
HASH_PROCESS(sha1_process, sha1_compress, sha1, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (20 bytes)
   @return CRYPT_OK if successful
*/
int sha1_done(hash_state * md, unsigned char *out)
{
    int i;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    if (md->sha1.curlen >= sizeof(md->sha1.buf)) {
       return CRYPT_INVALID_ARG;
    }

    /* increase the length of the message */
    md->sha1.length += md->sha1.curlen * 8;

    /* append the '1' bit */
    md->sha1.buf[md->sha1.curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->sha1.curlen > 56) {
        while (md->sha1.curlen < 64) {
            md->sha1.buf[md->sha1.curlen++] = (unsigned char)0;
        }
        sha1_compress(md, md->sha1.buf);
        md->sha1.curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (md->sha1.curlen < 56) {
        md->sha1.buf[md->sha1.curlen++] = (unsigned char)0;
    }

    /* store length */
    STORE64H(md->sha1.length, md->sha1.buf+56);
    sha1_compress(md, md->sha1.buf);

    /* copy output */
    for (i = 0; i < 5; i++) {
        STORE32H(md->sha1.state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  sha1_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      char *msg;
      unsigned char hash[20];
  } tests[] = {
    { "abc",
      { 0xa9, 0x99, 0x3e, 0x36, 0x47, 0x06, 0x81, 0x6a,
        0xba, 0x3e, 0x25, 0x71, 0x78, 0x50, 0xc2, 0x6c,
        0x9c, 0xd0, 0xd8, 0x9d }
    },
    { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
      { 0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E,
        0xBA, 0xAE, 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5,
        0xE5, 0x46, 0x70, 0xF1 }
    }
  };

  int i;
  unsigned char tmp[20];
  hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0]));  i++) {
      sha1_init(&md);
      sha1_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
      sha1_done(&md, tmp);
      if (XMEMCMP(tmp, tests[i].hash, 20) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
  #endif
}

#endif



/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha1.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/sha2/sha224.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
/**
   @param sha224.c
   LTC_SHA-224 new NIST standard based off of LTC_SHA-256 truncated to 224 bits (Tom St Denis)
*/

const struct ltc_hash_descriptor sha224_desc =
{
    "sha224",
    10,
    28,
    64,

    /* OID */
   { 2, 16, 840, 1, 101, 3, 4, 2, 4,  },
   9,

    &sha224_init,
    &sha256_process,
    &sha224_done,
    &sha224_test,
    NULL
};

/* init the sha256 er... sha224 state ;-) */
/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int sha224_init(hash_state * md)
{
    LTC_ARGCHK(md != NULL);

    md->sha256.curlen = 0;
    md->sha256.length = 0;
    md->sha256.state[0] = 0xc1059ed8UL;
    md->sha256.state[1] = 0x367cd507UL;
    md->sha256.state[2] = 0x3070dd17UL;
    md->sha256.state[3] = 0xf70e5939UL;
    md->sha256.state[4] = 0xffc00b31UL;
    md->sha256.state[5] = 0x68581511UL;
    md->sha256.state[6] = 0x64f98fa7UL;
    md->sha256.state[7] = 0xbefa4fa4UL;
    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (28 bytes)
   @return CRYPT_OK if successful
*/
int sha224_done(hash_state * md, unsigned char *out)
{
    unsigned char buf[32];
    int err;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    err = sha256_done(md, buf);
    XMEMCPY(out, buf, 28);
#ifdef LTC_CLEAN_STACK
    zeromem(buf, sizeof(buf));
#endif 
    return err;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  sha224_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      char *msg;
      unsigned char hash[28];
  } tests[] = {
    { "abc",
      { 0x23, 0x09, 0x7d, 0x22, 0x34, 0x05, 0xd8,
        0x22, 0x86, 0x42, 0xa4, 0x77, 0xbd, 0xa2,
        0x55, 0xb3, 0x2a, 0xad, 0xbc, 0xe4, 0xbd,
        0xa0, 0xb3, 0xf7, 0xe3, 0x6c, 0x9d, 0xa7 }
    },
    { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
      { 0x75, 0x38, 0x8b, 0x16, 0x51, 0x27, 0x76,
        0xcc, 0x5d, 0xba, 0x5d, 0xa1, 0xfd, 0x89,
        0x01, 0x50, 0xb0, 0xc6, 0x45, 0x5c, 0xb4,
        0xf5, 0x8b, 0x19, 0x52, 0x52, 0x25, 0x25 }
    },
  };

  int i;
  unsigned char tmp[28];
  hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
      sha224_init(&md);
      sha224_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
      sha224_done(&md, tmp);
      if (XMEMCMP(tmp, tests[i].hash, 28) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
 #endif
}


/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha2/sha224.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































































Deleted Source/libtomcrypt/src/hashes/sha2/sha256.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file sha256.c
  LTC_SHA256 by Tom St Denis 
*/

#ifdef LTC_SHA256 

const struct ltc_hash_descriptor sha256_desc =
{
    "sha256",
    0,
    32,
    64,

    /* OID */
   { 2, 16, 840, 1, 101, 3, 4, 2, 1,  },
   9,
    
    &sha256_init,
    &sha256_process,
    &sha256_done,
    &sha256_test,
    NULL
};

#ifdef LTC_SMALL_CODE
/* the K array */
static const ulong32 K[64] = {
    0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, 0x3956c25bUL,
    0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, 0xd807aa98UL, 0x12835b01UL,
    0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL,
    0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL,
    0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, 0x983e5152UL,
    0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, 0xc6e00bf3UL, 0xd5a79147UL,
    0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL,
    0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL,
    0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, 0xd192e819UL,
    0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, 0x19a4c116UL, 0x1e376c08UL,
    0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL,
    0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL,
    0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL
};
#endif

/* Various logical functions */
#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
#define Maj(x,y,z)      (((x | y) & z) | (x & y)) 
#define S(x, n)         RORc((x),(n))
#define R(x, n)         (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x)       (S(x, 2) ^ S(x, 13) ^ S(x, 22))
#define Sigma1(x)       (S(x, 6) ^ S(x, 11) ^ S(x, 25))
#define Gamma0(x)       (S(x, 7) ^ S(x, 18) ^ R(x, 3))
#define Gamma1(x)       (S(x, 17) ^ S(x, 19) ^ R(x, 10))

/* compress 512-bits */
#ifdef LTC_CLEAN_STACK
static int _sha256_compress(hash_state * md, unsigned char *buf)
#else
static int  sha256_compress(hash_state * md, unsigned char *buf)
#endif
{
    ulong32 S[8], W[64], t0, t1;
#ifdef LTC_SMALL_CODE
    ulong32 t;
#endif
    int i;

    /* copy state into S */
    for (i = 0; i < 8; i++) {
        S[i] = md->sha256.state[i];
    }

    /* copy the state into 512-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LOAD32H(W[i], buf + (4*i));
    }

    /* fill W[16..63] */
    for (i = 16; i < 64; i++) {
        W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
    }        

    /* Compress */
#ifdef LTC_SMALL_CODE   
#define RND(a,b,c,d,e,f,g,h,i)                         \
     t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i];   \
     t1 = Sigma0(a) + Maj(a, b, c);                    \
     d += t0;                                          \
     h  = t0 + t1;

     for (i = 0; i < 64; ++i) {
         RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i);
         t = S[7]; S[7] = S[6]; S[6] = S[5]; S[5] = S[4]; 
         S[4] = S[3]; S[3] = S[2]; S[2] = S[1]; S[1] = S[0]; S[0] = t;
     }  
#else 
#define RND(a,b,c,d,e,f,g,h,i,ki)                    \
     t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i];   \
     t1 = Sigma0(a) + Maj(a, b, c);                  \
     d += t0;                                        \
     h  = t0 + t1;

    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x71374491);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcf);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba5);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25b);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],5,0x59f111f1);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],6,0x923f82a4);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],7,0xab1c5ed5);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],8,0xd807aa98);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],9,0x12835b01);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],10,0x243185be);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],11,0x550c7dc3);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],12,0x72be5d74);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],13,0x80deb1fe);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],14,0x9bdc06a7);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],15,0xc19bf174);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],16,0xe49b69c1);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],17,0xefbe4786);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],18,0x0fc19dc6);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],19,0x240ca1cc);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],20,0x2de92c6f);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],21,0x4a7484aa);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],22,0x5cb0a9dc);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],23,0x76f988da);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],24,0x983e5152);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],25,0xa831c66d);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],26,0xb00327c8);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],27,0xbf597fc7);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],28,0xc6e00bf3);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],29,0xd5a79147);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],30,0x06ca6351);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],31,0x14292967);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],32,0x27b70a85);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],33,0x2e1b2138);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],34,0x4d2c6dfc);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],35,0x53380d13);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],36,0x650a7354);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],37,0x766a0abb);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],38,0x81c2c92e);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],39,0x92722c85);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],40,0xa2bfe8a1);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],41,0xa81a664b);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],42,0xc24b8b70);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],43,0xc76c51a3);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],44,0xd192e819);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],45,0xd6990624);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],46,0xf40e3585);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],47,0x106aa070);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],48,0x19a4c116);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],49,0x1e376c08);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],50,0x2748774c);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],51,0x34b0bcb5);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],52,0x391c0cb3);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],53,0x4ed8aa4a);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],54,0x5b9cca4f);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],55,0x682e6ff3);
    RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],56,0x748f82ee);
    RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],57,0x78a5636f);
    RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],58,0x84c87814);
    RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],59,0x8cc70208);
    RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],60,0x90befffa);
    RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],61,0xa4506ceb);
    RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);
    RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);

#undef RND     
    
#endif     

    /* feedback */
    for (i = 0; i < 8; i++) {
        md->sha256.state[i] = md->sha256.state[i] + S[i];
    }
    return CRYPT_OK;
}

#ifdef LTC_CLEAN_STACK
static int sha256_compress(hash_state * md, unsigned char *buf)
{
    int err;
    err = _sha256_compress(md, buf);
    burn_stack(sizeof(ulong32) * 74);
    return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int sha256_init(hash_state * md)
{
    LTC_ARGCHK(md != NULL);

    md->sha256.curlen = 0;
    md->sha256.length = 0;
    md->sha256.state[0] = 0x6A09E667UL;
    md->sha256.state[1] = 0xBB67AE85UL;
    md->sha256.state[2] = 0x3C6EF372UL;
    md->sha256.state[3] = 0xA54FF53AUL;
    md->sha256.state[4] = 0x510E527FUL;
    md->sha256.state[5] = 0x9B05688CUL;
    md->sha256.state[6] = 0x1F83D9ABUL;
    md->sha256.state[7] = 0x5BE0CD19UL;
    return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
HASH_PROCESS(sha256_process, sha256_compress, sha256, 64)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (32 bytes)
   @return CRYPT_OK if successful
*/
int sha256_done(hash_state * md, unsigned char *out)
{
    int i;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    if (md->sha256.curlen >= sizeof(md->sha256.buf)) {
       return CRYPT_INVALID_ARG;
    }


    /* increase the length of the message */
    md->sha256.length += md->sha256.curlen * 8;

    /* append the '1' bit */
    md->sha256.buf[md->sha256.curlen++] = (unsigned char)0x80;

    /* if the length is currently above 56 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->sha256.curlen > 56) {
        while (md->sha256.curlen < 64) {
            md->sha256.buf[md->sha256.curlen++] = (unsigned char)0;
        }
        sha256_compress(md, md->sha256.buf);
        md->sha256.curlen = 0;
    }

    /* pad upto 56 bytes of zeroes */
    while (md->sha256.curlen < 56) {
        md->sha256.buf[md->sha256.curlen++] = (unsigned char)0;
    }

    /* store length */
    STORE64H(md->sha256.length, md->sha256.buf+56);
    sha256_compress(md, md->sha256.buf);

    /* copy output */
    for (i = 0; i < 8; i++) {
        STORE32H(md->sha256.state[i], out+(4*i));
    }
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  sha256_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      char *msg;
      unsigned char hash[32];
  } tests[] = {
    { "abc",
      { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea,
        0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23,
        0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
        0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }
    },
    { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
      { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 
        0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39,
        0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 
        0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }
    },
  };

  int i;
  unsigned char tmp[32];
  hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
      sha256_init(&md);
      sha256_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
      sha256_done(&md, tmp);
      if (XMEMCMP(tmp, tests[i].hash, 32) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
 #endif
}

#ifdef LTC_SHA224
#include "sha224.c"
#endif

#endif



/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha2/sha256.c,v $ */
/* $Revision: 1.11 $ */
/* $Date: 2007/05/12 14:25:28 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/sha2/sha384.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
/** 
   @param sha384.c
   LTC_SHA384 hash included in sha512.c, Tom St Denis
*/

const struct ltc_hash_descriptor sha384_desc =
{
    "sha384",
    4,
    48,
    128,

    /* OID */
   { 2, 16, 840, 1, 101, 3, 4, 2, 2,  },
   9,

    &sha384_init,
    &sha512_process,
    &sha384_done,
    &sha384_test,
    NULL
};

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int sha384_init(hash_state * md)
{
    LTC_ARGCHK(md != NULL);

    md->sha512.curlen = 0;
    md->sha512.length = 0;
    md->sha512.state[0] = CONST64(0xcbbb9d5dc1059ed8);
    md->sha512.state[1] = CONST64(0x629a292a367cd507);
    md->sha512.state[2] = CONST64(0x9159015a3070dd17);
    md->sha512.state[3] = CONST64(0x152fecd8f70e5939);
    md->sha512.state[4] = CONST64(0x67332667ffc00b31);
    md->sha512.state[5] = CONST64(0x8eb44a8768581511);
    md->sha512.state[6] = CONST64(0xdb0c2e0d64f98fa7);
    md->sha512.state[7] = CONST64(0x47b5481dbefa4fa4);
    return CRYPT_OK;
}

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (48 bytes)
   @return CRYPT_OK if successful
*/
int sha384_done(hash_state * md, unsigned char *out)
{
   unsigned char buf[64];

   LTC_ARGCHK(md  != NULL);
   LTC_ARGCHK(out != NULL);

    if (md->sha512.curlen >= sizeof(md->sha512.buf)) {
       return CRYPT_INVALID_ARG;
    }

   sha512_done(md, buf);
   XMEMCPY(out, buf, 48);
#ifdef LTC_CLEAN_STACK
   zeromem(buf, sizeof(buf));
#endif
   return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  sha384_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      char *msg;
      unsigned char hash[48];
  } tests[] = {
    { "abc",
      { 0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b,
        0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50, 0x07,
        0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63,
        0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff, 0x5b, 0xed,
        0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23,
        0x58, 0xba, 0xec, 0xa1, 0x34, 0xc8, 0x25, 0xa7 }
    },
    { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
      { 0x09, 0x33, 0x0c, 0x33, 0xf7, 0x11, 0x47, 0xe8,
        0x3d, 0x19, 0x2f, 0xc7, 0x82, 0xcd, 0x1b, 0x47,
        0x53, 0x11, 0x1b, 0x17, 0x3b, 0x3b, 0x05, 0xd2,
        0x2f, 0xa0, 0x80, 0x86, 0xe3, 0xb0, 0xf7, 0x12,
        0xfc, 0xc7, 0xc7, 0x1a, 0x55, 0x7e, 0x2d, 0xb9,
        0x66, 0xc3, 0xe9, 0xfa, 0x91, 0x74, 0x60, 0x39 }
    },
  };

  int i;
  unsigned char tmp[48];
  hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
      sha384_init(&md);
      sha384_process(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
      sha384_done(&md, tmp);
      if (XMEMCMP(tmp, tests[i].hash, 48) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
 #endif
}






/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha2/sha384.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































Deleted Source/libtomcrypt/src/hashes/sha2/sha512.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @param sha512.c
   LTC_SHA512 by Tom St Denis 
*/

#ifdef LTC_SHA512

const struct ltc_hash_descriptor sha512_desc =
{
    "sha512",
    5,
    64,
    128,

    /* OID */
   { 2, 16, 840, 1, 101, 3, 4, 2, 3,  },
   9,

    &sha512_init,
    &sha512_process,
    &sha512_done,
    &sha512_test,
    NULL
};

/* the K array */
static const ulong64 K[80] = {
CONST64(0x428a2f98d728ae22), CONST64(0x7137449123ef65cd), 
CONST64(0xb5c0fbcfec4d3b2f), CONST64(0xe9b5dba58189dbbc),
CONST64(0x3956c25bf348b538), CONST64(0x59f111f1b605d019), 
CONST64(0x923f82a4af194f9b), CONST64(0xab1c5ed5da6d8118),
CONST64(0xd807aa98a3030242), CONST64(0x12835b0145706fbe), 
CONST64(0x243185be4ee4b28c), CONST64(0x550c7dc3d5ffb4e2),
CONST64(0x72be5d74f27b896f), CONST64(0x80deb1fe3b1696b1), 
CONST64(0x9bdc06a725c71235), CONST64(0xc19bf174cf692694),
CONST64(0xe49b69c19ef14ad2), CONST64(0xefbe4786384f25e3), 
CONST64(0x0fc19dc68b8cd5b5), CONST64(0x240ca1cc77ac9c65),
CONST64(0x2de92c6f592b0275), CONST64(0x4a7484aa6ea6e483), 
CONST64(0x5cb0a9dcbd41fbd4), CONST64(0x76f988da831153b5),
CONST64(0x983e5152ee66dfab), CONST64(0xa831c66d2db43210), 
CONST64(0xb00327c898fb213f), CONST64(0xbf597fc7beef0ee4),
CONST64(0xc6e00bf33da88fc2), CONST64(0xd5a79147930aa725), 
CONST64(0x06ca6351e003826f), CONST64(0x142929670a0e6e70),
CONST64(0x27b70a8546d22ffc), CONST64(0x2e1b21385c26c926), 
CONST64(0x4d2c6dfc5ac42aed), CONST64(0x53380d139d95b3df),
CONST64(0x650a73548baf63de), CONST64(0x766a0abb3c77b2a8), 
CONST64(0x81c2c92e47edaee6), CONST64(0x92722c851482353b),
CONST64(0xa2bfe8a14cf10364), CONST64(0xa81a664bbc423001),
CONST64(0xc24b8b70d0f89791), CONST64(0xc76c51a30654be30),
CONST64(0xd192e819d6ef5218), CONST64(0xd69906245565a910), 
CONST64(0xf40e35855771202a), CONST64(0x106aa07032bbd1b8),
CONST64(0x19a4c116b8d2d0c8), CONST64(0x1e376c085141ab53), 
CONST64(0x2748774cdf8eeb99), CONST64(0x34b0bcb5e19b48a8),
CONST64(0x391c0cb3c5c95a63), CONST64(0x4ed8aa4ae3418acb), 
CONST64(0x5b9cca4f7763e373), CONST64(0x682e6ff3d6b2b8a3),
CONST64(0x748f82ee5defb2fc), CONST64(0x78a5636f43172f60), 
CONST64(0x84c87814a1f0ab72), CONST64(0x8cc702081a6439ec),
CONST64(0x90befffa23631e28), CONST64(0xa4506cebde82bde9), 
CONST64(0xbef9a3f7b2c67915), CONST64(0xc67178f2e372532b),
CONST64(0xca273eceea26619c), CONST64(0xd186b8c721c0c207), 
CONST64(0xeada7dd6cde0eb1e), CONST64(0xf57d4f7fee6ed178),
CONST64(0x06f067aa72176fba), CONST64(0x0a637dc5a2c898a6), 
CONST64(0x113f9804bef90dae), CONST64(0x1b710b35131c471b),
CONST64(0x28db77f523047d84), CONST64(0x32caab7b40c72493), 
CONST64(0x3c9ebe0a15c9bebc), CONST64(0x431d67c49c100d4c),
CONST64(0x4cc5d4becb3e42b6), CONST64(0x597f299cfc657e2a), 
CONST64(0x5fcb6fab3ad6faec), CONST64(0x6c44198c4a475817)
};

/* Various logical functions */
#define Ch(x,y,z)       (z ^ (x & (y ^ z)))
#define Maj(x,y,z)      (((x | y) & z) | (x & y)) 
#define S(x, n)         ROR64c(x, n)
#define R(x, n)         (((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)n))
#define Sigma0(x)       (S(x, 28) ^ S(x, 34) ^ S(x, 39))
#define Sigma1(x)       (S(x, 14) ^ S(x, 18) ^ S(x, 41))
#define Gamma0(x)       (S(x, 1) ^ S(x, 8) ^ R(x, 7))
#define Gamma1(x)       (S(x, 19) ^ S(x, 61) ^ R(x, 6))

/* compress 1024-bits */
#ifdef LTC_CLEAN_STACK
static int _sha512_compress(hash_state * md, unsigned char *buf)
#else
static int  sha512_compress(hash_state * md, unsigned char *buf)
#endif
{
    ulong64 S[8], W[80], t0, t1;
    int i;

    /* copy state into S */
    for (i = 0; i < 8; i++) {
        S[i] = md->sha512.state[i];
    }

    /* copy the state into 1024-bits into W[0..15] */
    for (i = 0; i < 16; i++) {
        LOAD64H(W[i], buf + (8*i));
    }

    /* fill W[16..79] */
    for (i = 16; i < 80; i++) {
        W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
    }        

    /* Compress */
#ifdef LTC_SMALL_CODE
    for (i = 0; i < 80; i++) {
        t0 = S[7] + Sigma1(S[4]) + Ch(S[4], S[5], S[6]) + K[i] + W[i];
        t1 = Sigma0(S[0]) + Maj(S[0], S[1], S[2]);
        S[7] = S[6];
        S[6] = S[5];
        S[5] = S[4];
        S[4] = S[3] + t0;
        S[3] = S[2];
        S[2] = S[1];
        S[1] = S[0];
        S[0] = t0 + t1;
    }
#else
#define RND(a,b,c,d,e,f,g,h,i)                    \
     t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i];   \
     t1 = Sigma0(a) + Maj(a, b, c);                  \
     d += t0;                                        \
     h  = t0 + t1;

     for (i = 0; i < 80; i += 8) {
         RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],i+0);
         RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],i+1);
         RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],i+2);
         RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],i+3);
         RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],i+4);
         RND(S[3],S[4],S[5],S[6],S[7],S[0],S[1],S[2],i+5);
         RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],i+6);
         RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],i+7);
     }
#endif     


    /* feedback */
    for (i = 0; i < 8; i++) {
        md->sha512.state[i] = md->sha512.state[i] + S[i];
    }

    return CRYPT_OK;
}

/* compress 1024-bits */
#ifdef LTC_CLEAN_STACK
static int sha512_compress(hash_state * md, unsigned char *buf)
{
    int err;
    err = _sha512_compress(md, buf);
    burn_stack(sizeof(ulong64) * 90 + sizeof(int));
    return err;
}
#endif

/**
   Initialize the hash state
   @param md   The hash state you wish to initialize
   @return CRYPT_OK if successful
*/
int sha512_init(hash_state * md)
{
    LTC_ARGCHK(md != NULL);
    md->sha512.curlen = 0;
    md->sha512.length = 0;
    md->sha512.state[0] = CONST64(0x6a09e667f3bcc908);
    md->sha512.state[1] = CONST64(0xbb67ae8584caa73b);
    md->sha512.state[2] = CONST64(0x3c6ef372fe94f82b);
    md->sha512.state[3] = CONST64(0xa54ff53a5f1d36f1);
    md->sha512.state[4] = CONST64(0x510e527fade682d1);
    md->sha512.state[5] = CONST64(0x9b05688c2b3e6c1f);
    md->sha512.state[6] = CONST64(0x1f83d9abfb41bd6b);
    md->sha512.state[7] = CONST64(0x5be0cd19137e2179);
    return CRYPT_OK;
}

/**
   Process a block of memory though the hash
   @param md     The hash state
   @param in     The data to hash
   @param inlen  The length of the data (octets)
   @return CRYPT_OK if successful
*/
HASH_PROCESS(sha512_process, sha512_compress, sha512, 128)

/**
   Terminate the hash to get the digest
   @param md  The hash state
   @param out [out] The destination of the hash (64 bytes)
   @return CRYPT_OK if successful
*/
int sha512_done(hash_state * md, unsigned char *out)
{
    int i;

    LTC_ARGCHK(md  != NULL);
    LTC_ARGCHK(out != NULL);

    if (md->sha512.curlen >= sizeof(md->sha512.buf)) {
       return CRYPT_INVALID_ARG;
    }

    /* increase the length of the message */
    md->sha512.length += md->sha512.curlen * CONST64(8);

    /* append the '1' bit */
    md->sha512.buf[md->sha512.curlen++] = (unsigned char)0x80;

    /* if the length is currently above 112 bytes we append zeros
     * then compress.  Then we can fall back to padding zeros and length
     * encoding like normal.
     */
    if (md->sha512.curlen > 112) {
        while (md->sha512.curlen < 128) {
            md->sha512.buf[md->sha512.curlen++] = (unsigned char)0;
        }
        sha512_compress(md, md->sha512.buf);
        md->sha512.curlen = 0;
    }

    /* pad upto 120 bytes of zeroes 
     * note: that from 112 to 120 is the 64 MSB of the length.  We assume that you won't hash
     * > 2^64 bits of data... :-)
     */
    while (md->sha512.curlen < 120) {
        md->sha512.buf[md->sha512.curlen++] = (unsigned char)0;
    }

    /* store length */
    STORE64H(md->sha512.length, md->sha512.buf+120);
    sha512_compress(md, md->sha512.buf);

    /* copy output */
    for (i = 0; i < 8; i++) {
        STORE64H(md->sha512.state[i], out+(8*i));
    }
#ifdef LTC_CLEAN_STACK
    zeromem(md, sizeof(hash_state));
#endif
    return CRYPT_OK;
}

/**
  Self-test the hash
  @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
*/  
int  sha512_test(void)
{
 #ifndef LTC_TEST
    return CRYPT_NOP;
 #else    
  static const struct {
      char *msg;
      unsigned char hash[64];
  } tests[] = {
    { "abc",
     { 0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba,
       0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31,
       0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2,
       0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a,
       0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8,
       0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd,
       0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e,
       0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f }
    },
    { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
     { 0x8e, 0x95, 0x9b, 0x75, 0xda, 0xe3, 0x13, 0xda,
       0x8c, 0xf4, 0xf7, 0x28, 0x14, 0xfc, 0x14, 0x3f,
       0x8f, 0x77, 0x79, 0xc6, 0xeb, 0x9f, 0x7f, 0xa1,
       0x72, 0x99, 0xae, 0xad, 0xb6, 0x88, 0x90, 0x18,
       0x50, 0x1d, 0x28, 0x9e, 0x49, 0x00, 0xf7, 0xe4,
       0x33, 0x1b, 0x99, 0xde, 0xc4, 0xb5, 0x43, 0x3a,
       0xc7, 0xd3, 0x29, 0xee, 0xb6, 0xdd, 0x26, 0x54,
       0x5e, 0x96, 0xe5, 0x5b, 0x87, 0x4b, 0xe9, 0x09 }
    },
  };

  int i;
  unsigned char tmp[64];
  hash_state md;

  for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {
      sha512_init(&md);
      sha512_process(&md, (unsigned char *)tests[i].msg, (unsigned long)strlen(tests[i].msg));
      sha512_done(&md, tmp);
      if (XMEMCMP(tmp, tests[i].hash, 64) != 0) {
         return CRYPT_FAIL_TESTVECTOR;
      }
  }
  return CRYPT_OK;
  #endif
}

#ifdef LTC_SHA384
   #include "sha384.c"
#endif

#endif




/* $Source: /cvs/libtom/libtomcrypt/src/hashes/sha2/sha512.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2007/05/12 14:25:28 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/SHA3api_ref.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/***********************************************************************
**
** Implementation of the AHS API using the Skein hash function.
**
** Source code author: Doug Whiting, 2008.
**
** This algorithm and source code is released to the public domain.
** 
************************************************************************/

#include <string.h>     /* get the memcpy/memset functions */
#include "skein.h"      /* get the Skein API definitions   */
#include "SHA3api_ref.h"/* get the  AHS  API definitions   */

/******************************************************************/
/*     AHS API code                                               */
/******************************************************************/

#if SKEIN_SHA3_API

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* select the context size and init the context */
HashReturn Init(hashState *state, int hashbitlen)
    {
    if (hashbitlen <= SKEIN_256_NIST_MAX_HASHBITS)
        {
        Skein_Assert(hashbitlen > 0,BAD_HASHLEN);
        state->statebits = 64*SKEIN_256_STATE_WORDS;
        return Skein_256_Init(&state->u.ctx_256,(size_t) hashbitlen);
        }
    if (hashbitlen <= SKEIN_512_NIST_MAX_HASHBITS)
        {
        state->statebits = 64*SKEIN_512_STATE_WORDS;
        return Skein_512_Init(&state->u.ctx_512,(size_t) hashbitlen);
        }
    else
        {
        state->statebits = 64*SKEIN1024_STATE_WORDS;
        return Skein1024_Init(&state->u.ctx1024,(size_t) hashbitlen);
        }
    }

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* process data to be hashed */
HashReturn Update(hashState *state, const BitSequence *data, DataLength databitlen)
    {
    /* only the final Update() call is allowed do partial bytes, else assert an error */
    Skein_Assert((state->u.h.T[1] & SKEIN_T1_FLAG_BIT_PAD) == 0 || databitlen == 0, FAIL);

    Skein_Assert(state->statebits % 256 == 0 && (state->statebits-256) < 1024,FAIL);
    if ((databitlen & 7) == 0)  /* partial bytes? */
        {
        switch ((state->statebits >> 8) & 3)
            {
            case 2:  return Skein_512_Update(&state->u.ctx_512,data,databitlen >> 3);
            case 1:  return Skein_256_Update(&state->u.ctx_256,data,databitlen >> 3);
            case 0:  return Skein1024_Update(&state->u.ctx1024,data,databitlen >> 3);
            default: return FAIL;
            }
        }
    else
        {   /* handle partial final byte */
        size_t bCnt = (databitlen >> 3) + 1;                  /* number of bytes to handle (nonzero here!) */
        u08b_t b,mask;

        mask = (u08b_t) (1u << (7 - (databitlen & 7)));       /* partial byte bit mask */
        b    = (u08b_t) ((data[bCnt-1] & (0-mask)) | mask);   /* apply bit padding on final byte */

        switch ((state->statebits >> 8) & 3)
            {
            case 2:  Skein_512_Update(&state->u.ctx_512,data,bCnt-1); /* process all but the final byte    */
                     Skein_512_Update(&state->u.ctx_512,&b  ,  1   ); /* process the (masked) partial byte */
                     break;
            case 1:  Skein_256_Update(&state->u.ctx_256,data,bCnt-1); /* process all but the final byte    */
                     Skein_256_Update(&state->u.ctx_256,&b  ,  1   ); /* process the (masked) partial byte */
                     break;
            case 0:  Skein1024_Update(&state->u.ctx1024,data,bCnt-1); /* process all but the final byte    */
                     Skein1024_Update(&state->u.ctx1024,&b  ,  1   ); /* process the (masked) partial byte */
                     break;
            default: return FAIL;
            }
        Skein_Set_Bit_Pad_Flag(state->u.h);                    /* set tweak flag for the final call */
        
        return SUCCESS;
        }
    }

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize hash computation and output the result (hashbitlen bits) */
HashReturn Final(hashState *state, BitSequence *hashval)
    {
    Skein_Assert(state->statebits % 256 == 0 && (state->statebits-256) < 1024,FAIL);
    switch ((state->statebits >> 8) & 3)
        {
        case 2:  return Skein_512_Final(&state->u.ctx_512,hashval);
        case 1:  return Skein_256_Final(&state->u.ctx_256,hashval);
        case 0:  return Skein1024_Final(&state->u.ctx1024,hashval);
        default: return FAIL;
        }
    }

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* all-in-one hash function */
HashReturn Hash(int hashbitlen, const BitSequence *data, /* all-in-one call */
                DataLength databitlen,BitSequence *hashval)
    {
    hashState  state;
    HashReturn r = Init(&state,hashbitlen);
    if (r == SUCCESS)
        { /* these calls do not fail when called properly */
        r = Update(&state,data,databitlen);
        Final(&state,hashval);
        }
    return r;
    }

#endif /* SKEIN_SHA3_API */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/SHA3api_ref.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#ifndef _AHS_API_H_
#define _AHS_API_H_

/***********************************************************************
**
** Interface declarations of the AHS API using the Skein hash function.
**
** Source code author: Doug Whiting, 2008.
**
** This algorithm and source code is released to the public domain.
** 
************************************************************************/

#include "skein.h"

typedef enum
    {
    SUCCESS     = SKEIN_SUCCESS,
    FAIL        = SKEIN_FAIL,
    BAD_HASHLEN = SKEIN_BAD_HASHLEN
    }
    HashReturn;

typedef size_t   DataLength;                /* bit count  type */
typedef u08b_t   BitSequence;               /* bit stream type */

typedef struct
    {
    uint_t  statebits;                      /* 256, 512, or 1024 */
    union
        {
        Skein_Ctxt_Hdr_t h;                 /* common header "overlay" */
        Skein_256_Ctxt_t ctx_256;
        Skein_512_Ctxt_t ctx_512;
        Skein1024_Ctxt_t ctx1024;
        } u;
    }
    hashState;

/* "incremental" hashing API */
HashReturn Init  (hashState *state, int hashbitlen);
HashReturn Update(hashState *state, const BitSequence *data, DataLength databitlen);
HashReturn Final (hashState *state,       BitSequence *hashval);

/* "all-in-one" call */
HashReturn Hash  (int hashbitlen,   const BitSequence *data, 
                  DataLength databitlen,  BitSequence *hashval);


/*
** Re-define the compile-time constants below to change the selection
** of the Skein state size in the Init() function in SHA3api_ref.c.
**
** That is, the NIST API does not allow for explicit selection of the
** Skein block size, so it must be done implicitly in the Init() function.
** The selection is controlled by these constants.
*/
#ifndef SKEIN_256_NIST_MAX_HASHBITS
#define SKEIN_256_NIST_MAX_HASHBITS (256)
#endif

#ifndef SKEIN_512_NIST_MAX_HASHBITS
#define SKEIN_512_NIST_MAX_HASHBITS (512)
#endif

#endif  /* ifdef _AHS_API_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/brg_endian.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/*
 ---------------------------------------------------------------------------
 Copyright (c) 2003, Dr Brian Gladman, Worcester, UK.   All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue 20/10/2006
*/

#ifndef BRG_ENDIAN_H
#define BRG_ENDIAN_H

#define IS_BIG_ENDIAN      4321 /* byte 0 is most significant (mc68k) */
#define IS_LITTLE_ENDIAN   1234 /* byte 0 is least significant (i386) */

/* Include files where endian defines and byteswap functions may reside */
#if defined( __FreeBSD__ ) || defined( __OpenBSD__ ) || defined( __NetBSD__ )
#  include <sys/endian.h>
#elif defined( BSD ) && ( BSD >= 199103 ) || defined( __APPLE__ ) || \
      defined( __CYGWIN32__ ) || defined( __DJGPP__ ) || defined( __osf__ )
#  include <machine/endian.h>
#elif defined( __linux__ ) || defined( __GNUC__ ) || defined( __GNU_LIBRARY__ )
#  if !defined( __MINGW32__ ) && !defined(AVR)
#    include <endian.h>
#    if !defined( __BEOS__ )
#      include <byteswap.h>
#    endif
#  endif
#endif

/* Now attempt to set the define for platform byte order using any  */
/* of the four forms SYMBOL, _SYMBOL, __SYMBOL & __SYMBOL__, which  */
/* seem to encompass most endian symbol definitions                 */

#if defined( BIG_ENDIAN ) && defined( LITTLE_ENDIAN )
#  if defined( BYTE_ORDER ) && BYTE_ORDER == BIG_ENDIAN
#    define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#  elif defined( BYTE_ORDER ) && BYTE_ORDER == LITTLE_ENDIAN
#    define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#  endif
#elif defined( BIG_ENDIAN )
#  define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#elif defined( LITTLE_ENDIAN )
#  define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#endif

#if defined( _BIG_ENDIAN ) && defined( _LITTLE_ENDIAN )
#  if defined( _BYTE_ORDER ) && _BYTE_ORDER == _BIG_ENDIAN
#    define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#  elif defined( _BYTE_ORDER ) && _BYTE_ORDER == _LITTLE_ENDIAN
#    define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#  endif
#elif defined( _BIG_ENDIAN )
#  define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#elif defined( _LITTLE_ENDIAN )
#  define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#endif

#if defined( __BIG_ENDIAN ) && defined( __LITTLE_ENDIAN )
#  if defined( __BYTE_ORDER ) && __BYTE_ORDER == __BIG_ENDIAN
#    define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#  elif defined( __BYTE_ORDER ) && __BYTE_ORDER == __LITTLE_ENDIAN
#    define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#  endif
#elif defined( __BIG_ENDIAN )
#  define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#elif defined( __LITTLE_ENDIAN )
#  define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#endif

#if defined( __BIG_ENDIAN__ ) && defined( __LITTLE_ENDIAN__ )
#  if defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __BIG_ENDIAN__
#    define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#  elif defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __LITTLE_ENDIAN__
#    define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#  endif
#elif defined( __BIG_ENDIAN__ )
#  define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#elif defined( __LITTLE_ENDIAN__ )
#  define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#endif

/*  if the platform byte order could not be determined, then try to */
/*  set this define using common machine defines                    */
#if !defined(PLATFORM_BYTE_ORDER)

#if   defined( __alpha__ ) || defined( __alpha ) || defined( i386 )       || \
      defined( __i386__ )  || defined( _M_I86 )  || defined( _M_IX86 )    || \
      defined( __OS2__ )   || defined( sun386 )  || defined( __TURBOC__ ) || \
      defined( vax )       || defined( vms )     || defined( VMS )        || \
      defined( __VMS )     || defined( _M_X64 )  || defined( AVR )
#  define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN

#elif defined( AMIGA )   || defined( applec )    || defined( __AS400__ )  || \
      defined( _CRAY )   || defined( __hppa )    || defined( __hp9000 )   || \
      defined( ibm370 )  || defined( mc68000 )   || defined( m68k )       || \
      defined( __MRC__ ) || defined( __MVS__ )   || defined( __MWERKS__ ) || \
      defined( sparc )   || defined( __sparc)    || defined( SYMANTEC_C ) || \
      defined( __VOS__ ) || defined( __TIGCC__ ) || defined( __TANDEM )   || \
      defined( THINK_C ) || defined( __VMCMS__ )
#  define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN

#elif 0     /* **** EDIT HERE IF NECESSARY **** */
#  define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#elif 0     /* **** EDIT HERE IF NECESSARY **** */
#  define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
#else
#  error Please edit lines 126 or 128 in brg_endian.h to set the platform byte order
#endif
#endif

/* special handler for IA64, which may be either endianness (?)  */
/* here we assume little-endian, but this may need to be changed */
#if defined(__ia64) || defined(__ia64__) || defined(_M_IA64)
#  define PLATFORM_MUST_ALIGN (1)
#ifndef PLATFORM_BYTE_ORDER
#  define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
#endif
#endif

#ifndef   PLATFORM_MUST_ALIGN
#  define PLATFORM_MUST_ALIGN (0)
#endif

#endif  /* ifndef BRG_ENDIAN_H */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/brg_types.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/*
 ---------------------------------------------------------------------------
 Copyright (c) 1998-2006, Brian Gladman, Worcester, UK. All rights reserved.

 LICENSE TERMS

 The free distribution and use of this software in both source and binary
 form is allowed (with or without changes) provided that:

   1. distributions of this source code include the above copyright
      notice, this list of conditions and the following disclaimer;

   2. distributions in binary form include the above copyright
      notice, this list of conditions and the following disclaimer
      in the documentation and/or other associated materials;

   3. the copyright holder's name is not used to endorse products
      built using this software without specific written permission.

 ALTERNATIVELY, provided that this notice is retained in full, this product
 may be distributed under the terms of the GNU General Public License (GPL),
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.
 ---------------------------------------------------------------------------
 Issue 09/09/2006

 The unsigned integer types defined here are of the form uint_<nn>t where
 <nn> is the length of the type; for example, the unsigned 32-bit type is
 'uint_32t'.  These are NOT the same as the 'C99 integer types' that are
 defined in the inttypes.h and stdint.h headers since attempts to use these
 types have shown that support for them is still highly variable.  However,
 since the latter are of the form uint<nn>_t, a regular expression search
 and replace (in VC++ search on 'uint_{:z}t' and replace with 'uint\1_t')
 can be used to convert the types used here to the C99 standard types.
*/

#ifndef BRG_TYPES_H
#define BRG_TYPES_H

#if defined(__cplusplus)
extern "C" {
#endif

#include <limits.h>

#ifndef BRG_UI8
#  define BRG_UI8
#  if UCHAR_MAX == 255u
     typedef unsigned char uint_8t;
#  else
#    error Please define uint_8t as an 8-bit unsigned integer type in brg_types.h
#  endif
#endif

#ifndef BRG_UI16
#  define BRG_UI16
#  if USHRT_MAX == 65535u
     typedef unsigned short uint_16t;
#  else
#    error Please define uint_16t as a 16-bit unsigned short type in brg_types.h
#  endif
#endif

#ifndef BRG_UI32
#  define BRG_UI32
#  if UINT_MAX == 4294967295u
#    define li_32(h) 0x##h##u
     typedef unsigned int uint_32t;
#  elif ULONG_MAX == 4294967295u
#    define li_32(h) 0x##h##ul
     typedef unsigned long uint_32t;
#  elif defined( _CRAY )
#    error This code needs 32-bit data types, which Cray machines do not provide
#  else
#    error Please define uint_32t as a 32-bit unsigned integer type in brg_types.h
#  endif
#endif

#ifndef BRG_UI64
#  if defined( __BORLANDC__ ) && !defined( __MSDOS__ )
#    define BRG_UI64
#    define li_64(h) 0x##h##ui64
     typedef unsigned __int64 uint_64t;
#  elif defined( _MSC_VER ) && ( _MSC_VER < 1300 )    /* 1300 == VC++ 7.0 */
#    define BRG_UI64
#    define li_64(h) 0x##h##ui64
     typedef unsigned __int64 uint_64t;
#  elif defined( __sun ) && defined(ULONG_MAX) && ULONG_MAX == 0xfffffffful
#    define BRG_UI64
#    define li_64(h) 0x##h##ull
     typedef unsigned long long uint_64t;
#  elif defined( UINT_MAX ) && UINT_MAX > 4294967295u
#    if UINT_MAX == 18446744073709551615u
#      define BRG_UI64
#      define li_64(h) 0x##h##u
       typedef unsigned int uint_64t;
#    endif
#  elif defined( ULONG_MAX ) && ULONG_MAX > 4294967295u
#    if ULONG_MAX == 18446744073709551615ul
#      define BRG_UI64
#      define li_64(h) 0x##h##ul
       typedef unsigned long uint_64t;
#    endif
#  elif defined( ULLONG_MAX ) && ULLONG_MAX > 4294967295u
#    if ULLONG_MAX == 18446744073709551615ull
#      define BRG_UI64
#      define li_64(h) 0x##h##ull
       typedef unsigned long long uint_64t;
#    endif
#  elif defined( ULONG_LONG_MAX ) && ULONG_LONG_MAX > 4294967295u
#    if ULONG_LONG_MAX == 18446744073709551615ull
#      define BRG_UI64
#      define li_64(h) 0x##h##ull
       typedef unsigned long long uint_64t;
#    endif
#  elif defined(__GNUC__)  /* DLW: avoid mingw problem with -ansi */
#      define BRG_UI64
#      define li_64(h) 0x##h##ull
       typedef unsigned long long uint_64t;
#  endif
#endif

#if defined( NEED_UINT_64T ) && !defined( BRG_UI64 )
#  error Please define uint_64t as an unsigned 64 bit type in brg_types.h
#endif

#ifndef RETURN_VALUES
#  define RETURN_VALUES
#  if defined( DLL_EXPORT )
#    if defined( _MSC_VER ) || defined ( __INTEL_COMPILER )
#      define VOID_RETURN    __declspec( dllexport ) void __stdcall
#      define INT_RETURN     __declspec( dllexport ) int  __stdcall
#    elif defined( __GNUC__ )
#      define VOID_RETURN    __declspec( __dllexport__ ) void
#      define INT_RETURN     __declspec( __dllexport__ ) int
#    else
#      error Use of the DLL is only available on the Microsoft, Intel and GCC compilers
#    endif
#  elif defined( DLL_IMPORT )
#    if defined( _MSC_VER ) || defined ( __INTEL_COMPILER )
#      define VOID_RETURN    __declspec( dllimport ) void __stdcall
#      define INT_RETURN     __declspec( dllimport ) int  __stdcall
#    elif defined( __GNUC__ )
#      define VOID_RETURN    __declspec( __dllimport__ ) void
#      define INT_RETURN     __declspec( __dllimport__ ) int
#    else
#      error Use of the DLL is only available on the Microsoft, Intel and GCC compilers
#    endif
#  elif defined( __WATCOMC__ )
#    define VOID_RETURN  void __cdecl
#    define INT_RETURN   int  __cdecl
#  else
#    define VOID_RETURN  void
#    define INT_RETURN   int
#  endif
#endif

/*  These defines are used to declare buffers in a way that allows
    faster operations on longer variables to be used.  In all these
    defines 'size' must be a power of 2 and >= 8

    dec_unit_type(size,x)       declares a variable 'x' of length 
                                'size' bits

    dec_bufr_type(size,bsize,x) declares a buffer 'x' of length 'bsize' 
                                bytes defined as an array of variables
                                each of 'size' bits (bsize must be a 
                                multiple of size / 8)

    ptr_cast(x,size)            casts a pointer to a pointer to a 
                                varaiable of length 'size' bits
*/

#define ui_type(size)               uint_##size##t
#define dec_unit_type(size,x)       typedef ui_type(size) x
#define dec_bufr_type(size,bsize,x) typedef ui_type(size) x[bsize / (size >> 3)]
#define ptr_cast(x,size)            ((ui_type(size)*)(x))

#if defined(__cplusplus)
}
#endif

#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/skein.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
/***********************************************************************
**
** Implementation of the Skein hash function.
**
** Source code author: Doug Whiting, 2008.
**
** This algorithm and source code is released to the public domain.
** 
************************************************************************/

#define  SKEIN_PORT_CODE /* instantiate any code in skein_port.h */

#include <string.h>      /* get the memcpy/memset functions */
#include "skein.h"       /* get the Skein API definitions   */
#include "skein_iv.h"    /* get precomputed IVs */

/*****************************************************************/
/* External function to process blkCnt (nonzero) full block(s) of data. */
void    Skein_256_Process_Block(Skein_256_Ctxt_t *ctx,const u08b_t *blkPtr,size_t blkCnt,size_t byteCntAdd);
void    Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,size_t blkCnt,size_t byteCntAdd);
void    Skein1024_Process_Block(Skein1024_Ctxt_t *ctx,const u08b_t *blkPtr,size_t blkCnt,size_t byteCntAdd);

#if SKEIN256_BUILD

/*****************************************************************/
/*     256-bit Skein                                             */
/*****************************************************************/

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a straight hashing operation  */
int Skein_256_Init(Skein_256_Ctxt_t *ctx, size_t hashBitLen)
    {
    union
        {
        u08b_t  b[SKEIN_256_STATE_BYTES];
        u64b_t  w[SKEIN_256_STATE_WORDS];
        } cfg;                              /* config block */
        
    Skein_Assert(hashBitLen > 0,SKEIN_BAD_HASHLEN);
    ctx->h.hashBitLen = hashBitLen;         /* output hash bit count */

    switch (hashBitLen)
        {             /* use pre-computed values, where available */
#ifndef SKEIN_NO_PRECOMP
        case  256: memcpy(ctx->X,SKEIN_256_IV_256,sizeof(ctx->X));  break;
        case  224: memcpy(ctx->X,SKEIN_256_IV_224,sizeof(ctx->X));  break;
        case  160: memcpy(ctx->X,SKEIN_256_IV_160,sizeof(ctx->X));  break;
        case  128: memcpy(ctx->X,SKEIN_256_IV_128,sizeof(ctx->X));  break;
#endif
        default:
            /* here if there is no precomputed IV value available */
            /* build/process the config block, type == CONFIG (could be precomputed) */
            Skein_Start_New_Type(ctx,CFG_FINAL);        /* set tweaks: T0=0; T1=CFG | FINAL */

            cfg.w[0] = Skein_Swap64(SKEIN_SCHEMA_VER);  /* set the schema, version */
            cfg.w[1] = Skein_Swap64(hashBitLen);        /* hash result length in bits */
            cfg.w[2] = Skein_Swap64(SKEIN_CFG_TREE_INFO_SEQUENTIAL);
            memset(&cfg.w[3],0,sizeof(cfg) - 3*sizeof(cfg.w[0])); /* zero pad config block */

            /* compute the initial chaining values from config block */
            memset(ctx->X,0,sizeof(ctx->X));            /* zero the chaining variables */
            Skein_256_Process_Block(ctx,cfg.b,1,SKEIN_CFG_STR_LEN);
            break;
        }
    /* The chaining vars ctx->X are now initialized for the given hashBitLen. */
    /* Set up to process the data message portion of the hash (default) */
    Skein_Start_New_Type(ctx,MSG);              /* T0=0, T1= MSG type */

    return SKEIN_SUCCESS;
    }

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a MAC and/or tree hash operation */
/* [identical to Skein_256_Init() when keyBytes == 0 && treeInfo == SKEIN_CFG_TREE_INFO_SEQUENTIAL] */
int Skein_256_InitExt(Skein_256_Ctxt_t *ctx,size_t hashBitLen,u64b_t treeInfo, const u08b_t *key, size_t keyBytes)
    {
    union
        {
        u08b_t  b[SKEIN_256_STATE_BYTES];
        u64b_t  w[SKEIN_256_STATE_WORDS];
        } cfg;                              /* config block */
        
    Skein_Assert(hashBitLen > 0,SKEIN_BAD_HASHLEN);
    Skein_Assert(keyBytes == 0 || key != NULL,SKEIN_FAIL);

    /* compute the initial chaining values ctx->X[], based on key */
    if (keyBytes == 0)                          /* is there a key? */
        {                                   
        memset(ctx->X,0,sizeof(ctx->X));        /* no key: use all zeroes as key for config block */
        }
    else                                        /* here to pre-process a key */
        {
        Skein_assert(sizeof(cfg.b) >= sizeof(ctx->X));
        /* do a mini-Init right here */
        ctx->h.hashBitLen=8*sizeof(ctx->X);     /* set output hash bit count = state size */
        Skein_Start_New_Type(ctx,KEY);          /* set tweaks: T0 = 0; T1 = KEY type */
        memset(ctx->X,0,sizeof(ctx->X));        /* zero the initial chaining variables */
        Skein_256_Update(ctx,key,keyBytes);     /* hash the key */
        Skein_256_Final_Pad(ctx,cfg.b);         /* put result into cfg.b[] */
        memcpy(ctx->X,cfg.b,sizeof(cfg.b));     /* copy over into ctx->X[] */
#if SKEIN_NEED_SWAP
        {
        uint_t i;
        for (i=0;i<SKEIN_256_STATE_WORDS;i++)   /* convert key bytes to context words */
            ctx->X[i] = Skein_Swap64(ctx->X[i]);
        }
#endif
        }
    /* build/process the config block, type == CONFIG (could be precomputed for each key) */
    ctx->h.hashBitLen = hashBitLen;             /* output hash bit count */
    Skein_Start_New_Type(ctx,CFG_FINAL);

    memset(&cfg.w,0,sizeof(cfg.w));             /* pre-pad cfg.w[] with zeroes */
    cfg.w[0] = Skein_Swap64(SKEIN_SCHEMA_VER);
    cfg.w[1] = Skein_Swap64(hashBitLen);        /* hash result length in bits */
    cfg.w[2] = Skein_Swap64(treeInfo);          /* tree hash config info (or SKEIN_CFG_TREE_INFO_SEQUENTIAL) */

    Skein_Show_Key(256,&ctx->h,key,keyBytes);

    /* compute the initial chaining values from config block */
    Skein_256_Process_Block(ctx,cfg.b,1,SKEIN_CFG_STR_LEN);

    /* The chaining vars ctx->X are now initialized */
    /* Set up to process the data message portion of the hash (default) */
    ctx->h.bCnt = 0;                            /* buffer b[] starts out empty */
    Skein_Start_New_Type(ctx,MSG);
    
    return SKEIN_SUCCESS;
    }

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* process the input bytes */
int Skein_256_Update(Skein_256_Ctxt_t *ctx, const u08b_t *msg, size_t msgByteCnt)
    {
    size_t n;

    Skein_Assert(ctx->h.bCnt <= SKEIN_256_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    /* process full blocks, if any */
    if (msgByteCnt + ctx->h.bCnt > SKEIN_256_BLOCK_BYTES)
        {
        if (ctx->h.bCnt)                              /* finish up any buffered message data */
            {
            n = SKEIN_256_BLOCK_BYTES - ctx->h.bCnt;  /* # bytes free in buffer b[] */
            if (n)
                {
                Skein_assert(n < msgByteCnt);         /* check on our logic here */
                memcpy(&ctx->b[ctx->h.bCnt],msg,n);
                msgByteCnt  -= n;
                msg         += n;
                ctx->h.bCnt += n;
                }
            Skein_assert(ctx->h.bCnt == SKEIN_256_BLOCK_BYTES);
            Skein_256_Process_Block(ctx,ctx->b,1,SKEIN_256_BLOCK_BYTES);
            ctx->h.bCnt = 0;
            }
        /* now process any remaining full blocks, directly from input message data */
        if (msgByteCnt > SKEIN_256_BLOCK_BYTES)
            {
            n = (msgByteCnt-1) / SKEIN_256_BLOCK_BYTES;   /* number of full blocks to process */
            Skein_256_Process_Block(ctx,msg,n,SKEIN_256_BLOCK_BYTES);
            msgByteCnt -= n * SKEIN_256_BLOCK_BYTES;
            msg        += n * SKEIN_256_BLOCK_BYTES;
            }
        Skein_assert(ctx->h.bCnt == 0);
        }

    /* copy any remaining source message data bytes into b[] */
    if (msgByteCnt)
        {
        Skein_assert(msgByteCnt + ctx->h.bCnt <= SKEIN_256_BLOCK_BYTES);
        memcpy(&ctx->b[ctx->h.bCnt],msg,msgByteCnt);
        ctx->h.bCnt += msgByteCnt;
        }

    return SKEIN_SUCCESS;
    }
   
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the result */
int Skein_256_Final(Skein_256_Ctxt_t *ctx, u08b_t *hashVal)
    {
    size_t i,n,byteCnt;
    u64b_t X[SKEIN_256_STATE_WORDS];
    Skein_Assert(ctx->h.bCnt <= SKEIN_256_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    ctx->h.T[1] |= SKEIN_T1_FLAG_FINAL;                 /* tag as the final block */
    if (ctx->h.bCnt < SKEIN_256_BLOCK_BYTES)            /* zero pad b[] if necessary */
        memset(&ctx->b[ctx->h.bCnt],0,SKEIN_256_BLOCK_BYTES - ctx->h.bCnt);

    Skein_256_Process_Block(ctx,ctx->b,1,ctx->h.bCnt);  /* process the final block */
    
    /* now output the result */
    byteCnt = (ctx->h.hashBitLen + 7) >> 3;             /* total number of output bytes */

    /* run Threefish in "counter mode" to generate output */
    memset(ctx->b,0,sizeof(ctx->b));  /* zero out b[], so it can hold the counter */
    memcpy(X,ctx->X,sizeof(X));       /* keep a local copy of counter mode "key" */
    for (i=0;i*SKEIN_256_BLOCK_BYTES < byteCnt;i++)
        {
        ((u64b_t *)ctx->b)[0]= Skein_Swap64((u64b_t) i); /* build the counter block */
        Skein_Start_New_Type(ctx,OUT_FINAL);
        Skein_256_Process_Block(ctx,ctx->b,1,sizeof(u64b_t)); /* run "counter mode" */
        n = byteCnt - i*SKEIN_256_BLOCK_BYTES;   /* number of output bytes left to go */
        if (n >= SKEIN_256_BLOCK_BYTES)
            n  = SKEIN_256_BLOCK_BYTES;
        Skein_Put64_LSB_First(hashVal+i*SKEIN_256_BLOCK_BYTES,ctx->X,n);   /* "output" the ctr mode bytes */
        Skein_Show_Final(256,&ctx->h,n,hashVal+i*SKEIN_256_BLOCK_BYTES);
        memcpy(ctx->X,X,sizeof(X));   /* restore the counter mode key for next time */
        }
    return SKEIN_SUCCESS;
    }

#if defined(SKEIN_CODE_SIZE) || defined(SKEIN_PERF)
size_t Skein_256_API_CodeSize(void)
    {
    return ((u08b_t *) Skein_256_API_CodeSize) -
           ((u08b_t *) Skein_256_Init);
    }
#endif

#endif /* SKEIN256_BUILD */

#if SKEIN512_BUILD

/*****************************************************************/
/*     512-bit Skein                                             */
/*****************************************************************/

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a straight hashing operation  */
int Skein_512_Init(Skein_512_Ctxt_t *ctx, size_t hashBitLen)
    {
    union
        {
        u08b_t  b[SKEIN_512_STATE_BYTES];
        u64b_t  w[SKEIN_512_STATE_WORDS];
        } cfg;                              /* config block */
        
    Skein_Assert(hashBitLen > 0,SKEIN_BAD_HASHLEN);
    ctx->h.hashBitLen = hashBitLen;         /* output hash bit count */

    switch (hashBitLen)
        {             /* use pre-computed values, where available */
#ifndef SKEIN_NO_PRECOMP
        case  512: memcpy(ctx->X,SKEIN_512_IV_512,sizeof(ctx->X));  break;
        case  384: memcpy(ctx->X,SKEIN_512_IV_384,sizeof(ctx->X));  break;
        case  256: memcpy(ctx->X,SKEIN_512_IV_256,sizeof(ctx->X));  break;
        case  224: memcpy(ctx->X,SKEIN_512_IV_224,sizeof(ctx->X));  break;
#endif
        default:
            /* here if there is no precomputed IV value available */
            /* build/process the config block, type == CONFIG (could be precomputed) */
            Skein_Start_New_Type(ctx,CFG_FINAL);        /* set tweaks: T0=0; T1=CFG | FINAL */

            cfg.w[0] = Skein_Swap64(SKEIN_SCHEMA_VER);  /* set the schema, version */
            cfg.w[1] = Skein_Swap64(hashBitLen);        /* hash result length in bits */
            cfg.w[2] = Skein_Swap64(SKEIN_CFG_TREE_INFO_SEQUENTIAL);
            memset(&cfg.w[3],0,sizeof(cfg) - 3*sizeof(cfg.w[0])); /* zero pad config block */

            /* compute the initial chaining values from config block */
            memset(ctx->X,0,sizeof(ctx->X));            /* zero the chaining variables */
            Skein_512_Process_Block(ctx,cfg.b,1,SKEIN_CFG_STR_LEN);
            break;
        }

    /* The chaining vars ctx->X are now initialized for the given hashBitLen. */
    /* Set up to process the data message portion of the hash (default) */
    Skein_Start_New_Type(ctx,MSG);              /* T0=0, T1= MSG type */

    return SKEIN_SUCCESS;
    }

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a MAC and/or tree hash operation */
/* [identical to Skein_512_Init() when keyBytes == 0 && treeInfo == SKEIN_CFG_TREE_INFO_SEQUENTIAL] */
int Skein_512_InitExt(Skein_512_Ctxt_t *ctx,size_t hashBitLen,u64b_t treeInfo, const u08b_t *key, size_t keyBytes)
    {
    union
        {
        u08b_t  b[SKEIN_512_STATE_BYTES];
        u64b_t  w[SKEIN_512_STATE_WORDS];
        } cfg;                              /* config block */
        
    Skein_Assert(hashBitLen > 0,SKEIN_BAD_HASHLEN);
    Skein_Assert(keyBytes == 0 || key != NULL,SKEIN_FAIL);

    /* compute the initial chaining values ctx->X[], based on key */
    if (keyBytes == 0)                          /* is there a key? */
        {                                   
        memset(ctx->X,0,sizeof(ctx->X));        /* no key: use all zeroes as key for config block */
        }
    else                                        /* here to pre-process a key */
        {
        Skein_assert(sizeof(cfg.b) >= sizeof(ctx->X));
        /* do a mini-Init right here */
        ctx->h.hashBitLen=8*sizeof(ctx->X);     /* set output hash bit count = state size */
        Skein_Start_New_Type(ctx,KEY);          /* set tweaks: T0 = 0; T1 = KEY type */
        memset(ctx->X,0,sizeof(ctx->X));        /* zero the initial chaining variables */
        Skein_512_Update(ctx,key,keyBytes);     /* hash the key */
        Skein_512_Final_Pad(ctx,cfg.b);         /* put result into cfg.b[] */
        memcpy(ctx->X,cfg.b,sizeof(cfg.b));     /* copy over into ctx->X[] */
#if SKEIN_NEED_SWAP
        {
        uint_t i;
        for (i=0;i<SKEIN_512_STATE_WORDS;i++)   /* convert key bytes to context words */
            ctx->X[i] = Skein_Swap64(ctx->X[i]);
        }
#endif
        }
    /* build/process the config block, type == CONFIG (could be precomputed for each key) */
    ctx->h.hashBitLen = hashBitLen;             /* output hash bit count */
    Skein_Start_New_Type(ctx,CFG_FINAL);

    memset(&cfg.w,0,sizeof(cfg.w));             /* pre-pad cfg.w[] with zeroes */
    cfg.w[0] = Skein_Swap64(SKEIN_SCHEMA_VER);
    cfg.w[1] = Skein_Swap64(hashBitLen);        /* hash result length in bits */
    cfg.w[2] = Skein_Swap64(treeInfo);          /* tree hash config info (or SKEIN_CFG_TREE_INFO_SEQUENTIAL) */

    Skein_Show_Key(512,&ctx->h,key,keyBytes);

    /* compute the initial chaining values from config block */
    Skein_512_Process_Block(ctx,cfg.b,1,SKEIN_CFG_STR_LEN);

    /* The chaining vars ctx->X are now initialized */
    /* Set up to process the data message portion of the hash (default) */
    ctx->h.bCnt = 0;                            /* buffer b[] starts out empty */
    Skein_Start_New_Type(ctx,MSG);
    
    return SKEIN_SUCCESS;
    }

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* process the input bytes */
int Skein_512_Update(Skein_512_Ctxt_t *ctx, const u08b_t *msg, size_t msgByteCnt)
    {
    size_t n;

    Skein_Assert(ctx->h.bCnt <= SKEIN_512_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    /* process full blocks, if any */
    if (msgByteCnt + ctx->h.bCnt > SKEIN_512_BLOCK_BYTES)
        {
        if (ctx->h.bCnt)                              /* finish up any buffered message data */
            {
            n = SKEIN_512_BLOCK_BYTES - ctx->h.bCnt;  /* # bytes free in buffer b[] */
            if (n)
                {
                Skein_assert(n < msgByteCnt);         /* check on our logic here */
                memcpy(&ctx->b[ctx->h.bCnt],msg,n);
                msgByteCnt  -= n;
                msg         += n;
                ctx->h.bCnt += n;
                }
            Skein_assert(ctx->h.bCnt == SKEIN_512_BLOCK_BYTES);
            Skein_512_Process_Block(ctx,ctx->b,1,SKEIN_512_BLOCK_BYTES);
            ctx->h.bCnt = 0;
            }
        /* now process any remaining full blocks, directly from input message data */
        if (msgByteCnt > SKEIN_512_BLOCK_BYTES)
            {
            n = (msgByteCnt-1) / SKEIN_512_BLOCK_BYTES;   /* number of full blocks to process */
            Skein_512_Process_Block(ctx,msg,n,SKEIN_512_BLOCK_BYTES);
            msgByteCnt -= n * SKEIN_512_BLOCK_BYTES;
            msg        += n * SKEIN_512_BLOCK_BYTES;
            }
        Skein_assert(ctx->h.bCnt == 0);
        }

    /* copy any remaining source message data bytes into b[] */
    if (msgByteCnt)
        {
        Skein_assert(msgByteCnt + ctx->h.bCnt <= SKEIN_512_BLOCK_BYTES);
        memcpy(&ctx->b[ctx->h.bCnt],msg,msgByteCnt);
        ctx->h.bCnt += msgByteCnt;
        }

    return SKEIN_SUCCESS;
    }
   
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the result */
int Skein_512_Final(Skein_512_Ctxt_t *ctx, u08b_t *hashVal)
    {
    size_t i,n,byteCnt;
    u64b_t X[SKEIN_512_STATE_WORDS];
    Skein_Assert(ctx->h.bCnt <= SKEIN_512_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    ctx->h.T[1] |= SKEIN_T1_FLAG_FINAL;                 /* tag as the final block */
    if (ctx->h.bCnt < SKEIN_512_BLOCK_BYTES)            /* zero pad b[] if necessary */
        memset(&ctx->b[ctx->h.bCnt],0,SKEIN_512_BLOCK_BYTES - ctx->h.bCnt);

    Skein_512_Process_Block(ctx,ctx->b,1,ctx->h.bCnt);  /* process the final block */
    
    /* now output the result */
    byteCnt = (ctx->h.hashBitLen + 7) >> 3;             /* total number of output bytes */

    /* run Threefish in "counter mode" to generate output */
    memset(ctx->b,0,sizeof(ctx->b));  /* zero out b[], so it can hold the counter */
    memcpy(X,ctx->X,sizeof(X));       /* keep a local copy of counter mode "key" */
    for (i=0;i*SKEIN_512_BLOCK_BYTES < byteCnt;i++)
        {
        ((u64b_t *)ctx->b)[0]= Skein_Swap64((u64b_t) i); /* build the counter block */
        Skein_Start_New_Type(ctx,OUT_FINAL);
        Skein_512_Process_Block(ctx,ctx->b,1,sizeof(u64b_t)); /* run "counter mode" */
        n = byteCnt - i*SKEIN_512_BLOCK_BYTES;   /* number of output bytes left to go */
        if (n >= SKEIN_512_BLOCK_BYTES)
            n  = SKEIN_512_BLOCK_BYTES;
        Skein_Put64_LSB_First(hashVal+i*SKEIN_512_BLOCK_BYTES,ctx->X,n);   /* "output" the ctr mode bytes */
        Skein_Show_Final(512,&ctx->h,n,hashVal+i*SKEIN_512_BLOCK_BYTES);
        memcpy(ctx->X,X,sizeof(X));   /* restore the counter mode key for next time */
        }
    return SKEIN_SUCCESS;
    }

#if defined(SKEIN_CODE_SIZE) || defined(SKEIN_PERF)
size_t Skein_512_API_CodeSize(void)
    {
    return ((u08b_t *) Skein_512_API_CodeSize) -
           ((u08b_t *) Skein_512_Init);
    }
#endif

#endif /* SKEIN512_BUILD */

#if SKEIN1024_BUILD

/*****************************************************************/
/*    1024-bit Skein                                             */
/*****************************************************************/

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a straight hashing operation  */
int Skein1024_Init(Skein1024_Ctxt_t *ctx, size_t hashBitLen)
    {
    union
        {
        u08b_t  b[SKEIN1024_STATE_BYTES];
        u64b_t  w[SKEIN1024_STATE_WORDS];
        } cfg;                              /* config block */
        
    Skein_Assert(hashBitLen > 0,SKEIN_BAD_HASHLEN);
    ctx->h.hashBitLen = hashBitLen;         /* output hash bit count */

    switch (hashBitLen)
        {              /* use pre-computed values, where available */
#ifndef SKEIN_NO_PRECOMP
        case  512: memcpy(ctx->X,SKEIN1024_IV_512 ,sizeof(ctx->X)); break;
        case  384: memcpy(ctx->X,SKEIN1024_IV_384 ,sizeof(ctx->X)); break;
        case 1024: memcpy(ctx->X,SKEIN1024_IV_1024,sizeof(ctx->X)); break;
#endif
        default:
            /* here if there is no precomputed IV value available */
            /* build/process the config block, type == CONFIG (could be precomputed) */
            Skein_Start_New_Type(ctx,CFG_FINAL);        /* set tweaks: T0=0; T1=CFG | FINAL */

            cfg.w[0] = Skein_Swap64(SKEIN_SCHEMA_VER);  /* set the schema, version */
            cfg.w[1] = Skein_Swap64(hashBitLen);        /* hash result length in bits */
            cfg.w[2] = Skein_Swap64(SKEIN_CFG_TREE_INFO_SEQUENTIAL);
            memset(&cfg.w[3],0,sizeof(cfg) - 3*sizeof(cfg.w[0])); /* zero pad config block */

            /* compute the initial chaining values from config block */
            memset(ctx->X,0,sizeof(ctx->X));            /* zero the chaining variables */
            Skein1024_Process_Block(ctx,cfg.b,1,SKEIN_CFG_STR_LEN);
            break;
        }

    /* The chaining vars ctx->X are now initialized for the given hashBitLen. */
    /* Set up to process the data message portion of the hash (default) */
    Skein_Start_New_Type(ctx,MSG);              /* T0=0, T1= MSG type */

    return SKEIN_SUCCESS;
    }

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* init the context for a MAC and/or tree hash operation */
/* [identical to Skein1024_Init() when keyBytes == 0 && treeInfo == SKEIN_CFG_TREE_INFO_SEQUENTIAL] */
int Skein1024_InitExt(Skein1024_Ctxt_t *ctx,size_t hashBitLen,u64b_t treeInfo, const u08b_t *key, size_t keyBytes)
    {
    union
        {
        u08b_t  b[SKEIN1024_STATE_BYTES];
        u64b_t  w[SKEIN1024_STATE_WORDS];
        } cfg;                              /* config block */
        
    Skein_Assert(hashBitLen > 0,SKEIN_BAD_HASHLEN);
    Skein_Assert(keyBytes == 0 || key != NULL,SKEIN_FAIL);

    /* compute the initial chaining values ctx->X[], based on key */
    if (keyBytes == 0)                          /* is there a key? */
        {                                   
        memset(ctx->X,0,sizeof(ctx->X));        /* no key: use all zeroes as key for config block */
        }
    else                                        /* here to pre-process a key */
        {
        Skein_assert(sizeof(cfg.b) >= sizeof(ctx->X));
        /* do a mini-Init right here */
        ctx->h.hashBitLen=8*sizeof(ctx->X);     /* set output hash bit count = state size */
        Skein_Start_New_Type(ctx,KEY);          /* set tweaks: T0 = 0; T1 = KEY type */
        memset(ctx->X,0,sizeof(ctx->X));        /* zero the initial chaining variables */
        Skein1024_Update(ctx,key,keyBytes);     /* hash the key */
        Skein1024_Final_Pad(ctx,cfg.b);         /* put result into cfg.b[] */
        memcpy(ctx->X,cfg.b,sizeof(cfg.b));     /* copy over into ctx->X[] */
#if SKEIN_NEED_SWAP
        {
        uint_t i;
        for (i=0;i<SKEIN1024_STATE_WORDS;i++)   /* convert key bytes to context words */
            ctx->X[i] = Skein_Swap64(ctx->X[i]);
        }
#endif
        }
    /* build/process the config block, type == CONFIG (could be precomputed for each key) */
    ctx->h.hashBitLen = hashBitLen;             /* output hash bit count */
    Skein_Start_New_Type(ctx,CFG_FINAL);

    memset(&cfg.w,0,sizeof(cfg.w));             /* pre-pad cfg.w[] with zeroes */
    cfg.w[0] = Skein_Swap64(SKEIN_SCHEMA_VER);
    cfg.w[1] = Skein_Swap64(hashBitLen);        /* hash result length in bits */
    cfg.w[2] = Skein_Swap64(treeInfo);          /* tree hash config info (or SKEIN_CFG_TREE_INFO_SEQUENTIAL) */

    Skein_Show_Key(1024,&ctx->h,key,keyBytes);

    /* compute the initial chaining values from config block */
    Skein1024_Process_Block(ctx,cfg.b,1,SKEIN_CFG_STR_LEN);

    /* The chaining vars ctx->X are now initialized */
    /* Set up to process the data message portion of the hash (default) */
    ctx->h.bCnt = 0;                            /* buffer b[] starts out empty */
    Skein_Start_New_Type(ctx,MSG);
    
    return SKEIN_SUCCESS;
    }

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* process the input bytes */
int Skein1024_Update(Skein1024_Ctxt_t *ctx, const u08b_t *msg, size_t msgByteCnt)
    {
    size_t n;

    Skein_Assert(ctx->h.bCnt <= SKEIN1024_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    /* process full blocks, if any */
    if (msgByteCnt + ctx->h.bCnt > SKEIN1024_BLOCK_BYTES)
        {
        if (ctx->h.bCnt)                              /* finish up any buffered message data */
            {
            n = SKEIN1024_BLOCK_BYTES - ctx->h.bCnt;  /* # bytes free in buffer b[] */
            if (n)
                {
                Skein_assert(n < msgByteCnt);         /* check on our logic here */
                memcpy(&ctx->b[ctx->h.bCnt],msg,n);
                msgByteCnt  -= n;
                msg         += n;
                ctx->h.bCnt += n;
                }
            Skein_assert(ctx->h.bCnt == SKEIN1024_BLOCK_BYTES);
            Skein1024_Process_Block(ctx,ctx->b,1,SKEIN1024_BLOCK_BYTES);
            ctx->h.bCnt = 0;
            }
        /* now process any remaining full blocks, directly from input message data */
        if (msgByteCnt > SKEIN1024_BLOCK_BYTES)
            {
            n = (msgByteCnt-1) / SKEIN1024_BLOCK_BYTES;   /* number of full blocks to process */
            Skein1024_Process_Block(ctx,msg,n,SKEIN1024_BLOCK_BYTES);
            msgByteCnt -= n * SKEIN1024_BLOCK_BYTES;
            msg        += n * SKEIN1024_BLOCK_BYTES;
            }
        Skein_assert(ctx->h.bCnt == 0);
        }

    /* copy any remaining source message data bytes into b[] */
    if (msgByteCnt)
        {
        Skein_assert(msgByteCnt + ctx->h.bCnt <= SKEIN1024_BLOCK_BYTES);
        memcpy(&ctx->b[ctx->h.bCnt],msg,msgByteCnt);
        ctx->h.bCnt += msgByteCnt;
        }

    return SKEIN_SUCCESS;
    }
   
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the result */
int Skein1024_Final(Skein1024_Ctxt_t *ctx, u08b_t *hashVal)
    {
    size_t i,n,byteCnt;
    u64b_t X[SKEIN1024_STATE_WORDS];
    Skein_Assert(ctx->h.bCnt <= SKEIN1024_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    ctx->h.T[1] |= SKEIN_T1_FLAG_FINAL;                 /* tag as the final block */
    if (ctx->h.bCnt < SKEIN1024_BLOCK_BYTES)            /* zero pad b[] if necessary */
        memset(&ctx->b[ctx->h.bCnt],0,SKEIN1024_BLOCK_BYTES - ctx->h.bCnt);

    Skein1024_Process_Block(ctx,ctx->b,1,ctx->h.bCnt);  /* process the final block */
    
    /* now output the result */
    byteCnt = (ctx->h.hashBitLen + 7) >> 3;             /* total number of output bytes */

    /* run Threefish in "counter mode" to generate output */
    memset(ctx->b,0,sizeof(ctx->b));  /* zero out b[], so it can hold the counter */
    memcpy(X,ctx->X,sizeof(X));       /* keep a local copy of counter mode "key" */
    for (i=0;i*SKEIN1024_BLOCK_BYTES < byteCnt;i++)
        {
        ((u64b_t *)ctx->b)[0]= Skein_Swap64((u64b_t) i); /* build the counter block */
        Skein_Start_New_Type(ctx,OUT_FINAL);
        Skein1024_Process_Block(ctx,ctx->b,1,sizeof(u64b_t)); /* run "counter mode" */
        n = byteCnt - i*SKEIN1024_BLOCK_BYTES;   /* number of output bytes left to go */
        if (n >= SKEIN1024_BLOCK_BYTES)
            n  = SKEIN1024_BLOCK_BYTES;
        Skein_Put64_LSB_First(hashVal+i*SKEIN1024_BLOCK_BYTES,ctx->X,n);   /* "output" the ctr mode bytes */
        Skein_Show_Final(1024,&ctx->h,n,hashVal+i*SKEIN1024_BLOCK_BYTES);
        memcpy(ctx->X,X,sizeof(X));   /* restore the counter mode key for next time */
        }
    return SKEIN_SUCCESS;
    }

#if defined(SKEIN_CODE_SIZE) || defined(SKEIN_PERF)
size_t Skein1024_API_CodeSize(void)
    {
    return ((u08b_t *) Skein1024_API_CodeSize) -
           ((u08b_t *) Skein1024_Init);
    }
#endif

#endif /* SKEIN1024_BUILD */

/**************** Functions to support MAC/tree hashing ***************/
/*   (this code is identical for Optimized and Reference versions)    */

#if SKEIN256_BUILD

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the block, no OUTPUT stage */
int Skein_256_Final_Pad(Skein_256_Ctxt_t *ctx, u08b_t *hashVal)
    {
    Skein_Assert(ctx->h.bCnt <= SKEIN_256_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    ctx->h.T[1] |= SKEIN_T1_FLAG_FINAL;        /* tag as the final block */
    if (ctx->h.bCnt < SKEIN_256_BLOCK_BYTES)   /* zero pad b[] if necessary */
        memset(&ctx->b[ctx->h.bCnt],0,SKEIN_256_BLOCK_BYTES - ctx->h.bCnt);
    Skein_256_Process_Block(ctx,ctx->b,1,ctx->h.bCnt);    /* process the final block */
    
    Skein_Put64_LSB_First(hashVal,ctx->X,SKEIN_256_BLOCK_BYTES);   /* "output" the state bytes */
    
    return SKEIN_SUCCESS;
    }

#endif /* SKEIN256_BUILD */

#if SKEIN512_BUILD

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the block, no OUTPUT stage */
int Skein_512_Final_Pad(Skein_512_Ctxt_t *ctx, u08b_t *hashVal)
    {
    Skein_Assert(ctx->h.bCnt <= SKEIN_512_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    ctx->h.T[1] |= SKEIN_T1_FLAG_FINAL;        /* tag as the final block */
    if (ctx->h.bCnt < SKEIN_512_BLOCK_BYTES)   /* zero pad b[] if necessary */
        memset(&ctx->b[ctx->h.bCnt],0,SKEIN_512_BLOCK_BYTES - ctx->h.bCnt);
    Skein_512_Process_Block(ctx,ctx->b,1,ctx->h.bCnt);    /* process the final block */
    
    Skein_Put64_LSB_First(hashVal,ctx->X,SKEIN_512_BLOCK_BYTES);   /* "output" the state bytes */
    
    return SKEIN_SUCCESS;
    }

#endif /* SKEIN512_BUILD */

#if SKEIN1024_BUILD

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* finalize the hash computation and output the block, no OUTPUT stage */
int Skein1024_Final_Pad(Skein1024_Ctxt_t *ctx, u08b_t *hashVal)
    {
    Skein_Assert(ctx->h.bCnt <= SKEIN1024_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    ctx->h.T[1] |= SKEIN_T1_FLAG_FINAL;        /* tag as the final block */
    if (ctx->h.bCnt < SKEIN1024_BLOCK_BYTES)   /* zero pad b[] if necessary */
        memset(&ctx->b[ctx->h.bCnt],0,SKEIN1024_BLOCK_BYTES - ctx->h.bCnt);
    Skein1024_Process_Block(ctx,ctx->b,1,ctx->h.bCnt);    /* process the final block */
    
    Skein_Put64_LSB_First(hashVal,ctx->X,SKEIN1024_BLOCK_BYTES);   /* "output" the state bytes */
    
    return SKEIN_SUCCESS;
    }

#endif /* SKEIN1024_BUILD */

#if SKEIN_TREE_HASH
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* just do the OUTPUT stage                                       */

#if SKEIN256_BUILD

int Skein_256_Output(Skein_256_Ctxt_t *ctx, u08b_t *hashVal)
    {
    size_t i,n,byteCnt;
    u64b_t X[SKEIN_256_STATE_WORDS];
    Skein_Assert(ctx->h.bCnt <= SKEIN_256_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    /* now output the result */
    byteCnt = (ctx->h.hashBitLen + 7) >> 3;    /* total number of output bytes */

    /* run Threefish in "counter mode" to generate output */
    memset(ctx->b,0,sizeof(ctx->b));  /* zero out b[], so it can hold the counter */
    memcpy(X,ctx->X,sizeof(X));       /* keep a local copy of counter mode "key" */
    for (i=0;i*SKEIN_256_BLOCK_BYTES < byteCnt;i++)
        {
        ((u64b_t *)ctx->b)[0]= Skein_Swap64((u64b_t) i); /* build the counter block */
        Skein_Start_New_Type(ctx,OUT_FINAL);
        Skein_256_Process_Block(ctx,ctx->b,1,sizeof(u64b_t)); /* run "counter mode" */
        n = byteCnt - i*SKEIN_256_BLOCK_BYTES;   /* number of output bytes left to go */
        if (n >= SKEIN_256_BLOCK_BYTES)
            n  = SKEIN_256_BLOCK_BYTES;
        Skein_Put64_LSB_First(hashVal+i*SKEIN_256_BLOCK_BYTES,ctx->X,n);   /* "output" the ctr mode bytes */
        Skein_Show_Final(256,&ctx->h,n,hashVal+i*SKEIN_256_BLOCK_BYTES);
        memcpy(ctx->X,X,sizeof(X));   /* restore the counter mode key for next time */
        }
    return SKEIN_SUCCESS;
    }

#endif /* SKEIN256_BUILD */

#if SKEIN512_BUILD

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* just do the OUTPUT stage                                       */
int Skein_512_Output(Skein_512_Ctxt_t *ctx, u08b_t *hashVal)
    {
    size_t i,n,byteCnt;
    u64b_t X[SKEIN_512_STATE_WORDS];
    Skein_Assert(ctx->h.bCnt <= SKEIN_512_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    /* now output the result */
    byteCnt = (ctx->h.hashBitLen + 7) >> 3;    /* total number of output bytes */

    /* run Threefish in "counter mode" to generate output */
    memset(ctx->b,0,sizeof(ctx->b));  /* zero out b[], so it can hold the counter */
    memcpy(X,ctx->X,sizeof(X));       /* keep a local copy of counter mode "key" */
    for (i=0;i*SKEIN_512_BLOCK_BYTES < byteCnt;i++)
        {
        ((u64b_t *)ctx->b)[0]= Skein_Swap64((u64b_t) i); /* build the counter block */
        Skein_Start_New_Type(ctx,OUT_FINAL);
        Skein_512_Process_Block(ctx,ctx->b,1,sizeof(u64b_t)); /* run "counter mode" */
        n = byteCnt - i*SKEIN_512_BLOCK_BYTES;   /* number of output bytes left to go */
        if (n >= SKEIN_512_BLOCK_BYTES)
            n  = SKEIN_512_BLOCK_BYTES;
        Skein_Put64_LSB_First(hashVal+i*SKEIN_512_BLOCK_BYTES,ctx->X,n);   /* "output" the ctr mode bytes */
        Skein_Show_Final(256,&ctx->h,n,hashVal+i*SKEIN_512_BLOCK_BYTES);
        memcpy(ctx->X,X,sizeof(X));   /* restore the counter mode key for next time */
        }
    return SKEIN_SUCCESS;
    }

#endif /* SKEIN512_BUILD */

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/* just do the OUTPUT stage                                       */

#if SKEIN1024_BUILD

int Skein1024_Output(Skein1024_Ctxt_t *ctx, u08b_t *hashVal)
    {
    size_t i,n,byteCnt;
    u64b_t X[SKEIN1024_STATE_WORDS];
    Skein_Assert(ctx->h.bCnt <= SKEIN1024_BLOCK_BYTES,SKEIN_FAIL);    /* catch uninitialized context */

    /* now output the result */
    byteCnt = (ctx->h.hashBitLen + 7) >> 3;    /* total number of output bytes */

    /* run Threefish in "counter mode" to generate output */
    memset(ctx->b,0,sizeof(ctx->b));  /* zero out b[], so it can hold the counter */
    memcpy(X,ctx->X,sizeof(X));       /* keep a local copy of counter mode "key" */
    for (i=0;i*SKEIN1024_BLOCK_BYTES < byteCnt;i++)
        {
        ((u64b_t *)ctx->b)[0]= Skein_Swap64((u64b_t) i); /* build the counter block */
        Skein_Start_New_Type(ctx,OUT_FINAL);
        Skein1024_Process_Block(ctx,ctx->b,1,sizeof(u64b_t)); /* run "counter mode" */
        n = byteCnt - i*SKEIN1024_BLOCK_BYTES;   /* number of output bytes left to go */
        if (n >= SKEIN1024_BLOCK_BYTES)
            n  = SKEIN1024_BLOCK_BYTES;
        Skein_Put64_LSB_First(hashVal+i*SKEIN1024_BLOCK_BYTES,ctx->X,n);   /* "output" the ctr mode bytes */
        Skein_Show_Final(256,&ctx->h,n,hashVal+i*SKEIN1024_BLOCK_BYTES);
        memcpy(ctx->X,X,sizeof(X));   /* restore the counter mode key for next time */
        }
    return SKEIN_SUCCESS;
    }

#endif /* SKEIN1024_BUILD */

#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/skein.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#ifndef _SKEIN_H_
#define _SKEIN_H_     1
/**************************************************************************
**
** Interface declarations and internal definitions for Skein hashing.
**
** Source code author: Doug Whiting, 2008.
 ** Changes added in for CommonCrypto/LTC: Jon Callas, 2010.
**
** This algorithm and source code is released to the public domain.
**
***************************************************************************
** 
** The following compile-time switches may be defined to control some
** tradeoffs between speed, code size, error checking, and security.
**
** The "default" note explains what happens when the switch is not defined.
**
**  SKEIN_DEBUG            -- make callouts from inside Skein code
**                            to examine/display intermediate values.
**                            [default: no callouts (no overhead)]
**
**  SKEIN_ERR_CHECK        -- how error checking is handled inside Skein
**                            code. If not defined, most error checking 
**                            is disabled (for performance). Otherwise, 
**                            the switch value is interpreted as:
**                                0: use assert()      to flag errors
**                                1: return SKEIN_FAIL to flag errors
**
***************************************************************************/

#include <stddef.h>                          /* get size_t definition */
#include "skein_port.h"                      /* get platform-specific definitions */

#ifdef __cplusplus
extern "C" {
#endif
	

#ifndef SKEIN256_BUILD
#define SKEIN256_BUILD 0
#define SKEIN512_BUILD 1
#define SKEIN1024_BUILD 0
#endif

#define SKEIN_SHA3_API 0					/* build the SHA 3 API Routines? */

#define SKEIN_TREE_HASH 0					/* build the tree hash Routines? */

enum
    {
    SKEIN_SUCCESS         =      0,          /* return codes from Skein calls */
    SKEIN_FAIL            =      1,
    SKEIN_BAD_HASHLEN     =      2
    };

#define  SKEIN_MODIFIER_WORDS  ( 2)          /* number of modifier (tweak) words */

#define  SKEIN_256_STATE_WORDS ( 4)
#define  SKEIN_512_STATE_WORDS ( 8)
#define  SKEIN1024_STATE_WORDS (16)
#define  SKEIN_MAX_STATE_WORDS (16)

#define  SKEIN_256_STATE_BYTES ( 8*SKEIN_256_STATE_WORDS)
#define  SKEIN_512_STATE_BYTES ( 8*SKEIN_512_STATE_WORDS)
#define  SKEIN1024_STATE_BYTES ( 8*SKEIN1024_STATE_WORDS)

#define  SKEIN_256_STATE_BITS  (64*SKEIN_256_STATE_WORDS)
#define  SKEIN_512_STATE_BITS  (64*SKEIN_512_STATE_WORDS)
#define  SKEIN1024_STATE_BITS  (64*SKEIN1024_STATE_WORDS)

#define  SKEIN_256_BLOCK_BYTES ( 8*SKEIN_256_STATE_WORDS)
#define  SKEIN_512_BLOCK_BYTES ( 8*SKEIN_512_STATE_WORDS)
#define  SKEIN1024_BLOCK_BYTES ( 8*SKEIN1024_STATE_WORDS)

typedef struct
    {
    size_t  hashBitLen;                      /* size of hash result, in bits */
    size_t  bCnt;                            /* current byte count in buffer b[] */
    u64b_t  T[SKEIN_MODIFIER_WORDS];         /* tweak words: T[0]=byte cnt, T[1]=flags */
    } Skein_Ctxt_Hdr_t;

typedef struct                               /*  256-bit Skein hash context structure */
    {
    Skein_Ctxt_Hdr_t h;                      /* common header context variables */
    u64b_t  X[SKEIN_256_STATE_WORDS];        /* chaining variables */
    u08b_t  b[SKEIN_256_BLOCK_BYTES];        /* partial block buffer (8-byte aligned) */
    } Skein_256_Ctxt_t;

typedef struct                               /*  512-bit Skein hash context structure */
    {
    Skein_Ctxt_Hdr_t h;                      /* common header context variables */
    u64b_t  X[SKEIN_512_STATE_WORDS];        /* chaining variables */
    u08b_t  b[SKEIN_512_BLOCK_BYTES];        /* partial block buffer (8-byte aligned) */
    } Skein_512_Ctxt_t;

typedef struct                               /* 1024-bit Skein hash context structure */
    {
    Skein_Ctxt_Hdr_t h;                      /* common header context variables */
    u64b_t  X[SKEIN1024_STATE_WORDS];        /* chaining variables */
    u08b_t  b[SKEIN1024_BLOCK_BYTES];        /* partial block buffer (8-byte aligned) */
    } Skein1024_Ctxt_t;

/*   Skein APIs for (incremental) "straight hashing" */
#if SKEIN256_BUILD
int  Skein_256_Init  (Skein_256_Ctxt_t *ctx, size_t hashBitLen);
int  Skein_256_Update(Skein_256_Ctxt_t *ctx, const u08b_t *msg, size_t msgByteCnt);
int  Skein_256_Final (Skein_256_Ctxt_t *ctx, u08b_t * hashVal);
#endif

#if SKEIN512_BUILD
extern int  Skein_512_Init  (Skein_512_Ctxt_t *ctx, size_t hashBitLen);
extern int  Skein_512_Update(Skein_512_Ctxt_t *ctx, const u08b_t *msg, size_t msgByteCnt);
extern int  Skein_512_Final (Skein_512_Ctxt_t *ctx, u08b_t * hashVal);
#endif

#if SKEIN1024_BUILD
int  Skein1024_Init  (Skein1024_Ctxt_t *ctx, size_t hashBitLen);
int  Skein1024_Update(Skein1024_Ctxt_t *ctx, const u08b_t *msg, size_t msgByteCnt);
int  Skein1024_Final (Skein1024_Ctxt_t *ctx, u08b_t * hashVal);
#endif

/*
**   Skein APIs for "extended" initialization: MAC keys, tree hashing.
**   After an InitExt() call, just use Update/Final calls as with Init().
**
**   Notes: Same parameters as _Init() calls, plus treeInfo/key/keyBytes.
**          When keyBytes == 0 and treeInfo == SKEIN_SEQUENTIAL, 
**              the results of InitExt() are identical to calling Init().
**          The function Init() may be called once to "precompute" the IV for
**              a given hashBitLen value, then by saving a copy of the context
**              the IV computation may be avoided in later calls.
**          Similarly, the function InitExt() may be called once per MAC key 
**              to precompute the MAC IV, then a copy of the context saved and
**              reused for each new MAC computation.
**/
#if SKEIN256_BUILD
int  Skein_256_InitExt(Skein_256_Ctxt_t *ctx, size_t hashBitLen, u64b_t treeInfo, const u08b_t *key, size_t keyBytes);
#endif
#if SKEIN512_BUILD
int  Skein_512_InitExt(Skein_512_Ctxt_t *ctx, size_t hashBitLen, u64b_t treeInfo, const u08b_t *key, size_t keyBytes);
#endif
#if SKEIN1024_BUILD
int  Skein1024_InitExt(Skein1024_Ctxt_t *ctx, size_t hashBitLen, u64b_t treeInfo, const u08b_t *key, size_t keyBytes);
#endif

/*
**   Skein APIs for MAC and tree hash:
**      Final_Pad:  pad, do final block, but no OUTPUT type
**      Output:     do just the output stage
*/
#if SKEIN256_BUILD
int  Skein_256_Final_Pad(Skein_256_Ctxt_t *ctx, u08b_t * hashVal);
#endif
#if SKEIN512_BUILD
int  Skein_512_Final_Pad(Skein_512_Ctxt_t *ctx, u08b_t * hashVal);
#endif
#if SKEIN1024_BUILD
int  Skein1024_Final_Pad(Skein1024_Ctxt_t *ctx, u08b_t * hashVal);
#endif

#ifndef SKEIN_TREE_HASH
#define SKEIN_TREE_HASH (1)
#endif
#if  SKEIN_TREE_HASH
#if SKEIN256_BUILD
int  Skein_256_Output   (Skein_256_Ctxt_t *ctx, u08b_t * hashVal);
#endif
#if SKEIN512_BUILD
int  Skein_512_Output   (Skein_512_Ctxt_t *ctx, u08b_t * hashVal);
#endif
#if SKEIN1024_BUILD
int  Skein1024_Output   (Skein1024_Ctxt_t *ctx, u08b_t * hashVal);
#endif
#endif

/*****************************************************************
** "Internal" Skein definitions
**    -- not needed for sequential hashing API, but will be 
**           helpful for other uses of Skein (e.g., tree hash mode).
**    -- included here so that they can be shared between
**           reference and optimized code.
******************************************************************/

/* tweak word T[1]: bit field starting positions */
#define SKEIN_T1_BIT(BIT)       ((BIT) - 64)            /* offset 64 because it's the second word  */
                                
#define SKEIN_T1_POS_TREE_LVL   SKEIN_T1_BIT(112)       /* bits 112..118: level in hash tree       */
#define SKEIN_T1_POS_BIT_PAD    SKEIN_T1_BIT(119)       /* bit  119     : partial final input byte */
#define SKEIN_T1_POS_BLK_TYPE   SKEIN_T1_BIT(120)       /* bits 120..125: type field               */
#define SKEIN_T1_POS_FIRST      SKEIN_T1_BIT(126)       /* bits 126     : first block flag         */
#define SKEIN_T1_POS_FINAL      SKEIN_T1_BIT(127)       /* bit  127     : final block flag         */
                                
/* tweak word T[1]: flag bit definition(s) */
#define SKEIN_T1_FLAG_FIRST     (((u64b_t)  1 ) << SKEIN_T1_POS_FIRST)
#define SKEIN_T1_FLAG_FINAL     (((u64b_t)  1 ) << SKEIN_T1_POS_FINAL)
#define SKEIN_T1_FLAG_BIT_PAD   (((u64b_t)  1 ) << SKEIN_T1_POS_BIT_PAD)
                                
/* tweak word T[1]: tree level bit field mask */
#define SKEIN_T1_TREE_LVL_MASK  (((u64b_t)0x7F) << SKEIN_T1_POS_TREE_LVL)
#define SKEIN_T1_TREE_LEVEL(n)  (((u64b_t) (n)) << SKEIN_T1_POS_TREE_LVL)

/* tweak word T[1]: block type field */
#define SKEIN_BLK_TYPE_KEY      ( 0)                    /* key, for MAC and KDF */
#define SKEIN_BLK_TYPE_CFG      ( 4)                    /* configuration block */
#define SKEIN_BLK_TYPE_PERS     ( 8)                    /* personalization string */
#define SKEIN_BLK_TYPE_PK       (12)                    /* public key (for digital signature hashing) */
#define SKEIN_BLK_TYPE_KDF      (16)                    /* key identifier for KDF */
#define SKEIN_BLK_TYPE_NONCE    (20)                    /* nonce for PRNG */
#define SKEIN_BLK_TYPE_MSG      (48)                    /* message processing */
#define SKEIN_BLK_TYPE_OUT      (63)                    /* output stage */
#define SKEIN_BLK_TYPE_MASK     (63)                    /* bit field mask */

#define SKEIN_T1_BLK_TYPE(T)   (((u64b_t) (SKEIN_BLK_TYPE_##T)) << SKEIN_T1_POS_BLK_TYPE)
#define SKEIN_T1_BLK_TYPE_KEY   SKEIN_T1_BLK_TYPE(KEY)  /* key, for MAC and KDF */
#define SKEIN_T1_BLK_TYPE_CFG   SKEIN_T1_BLK_TYPE(CFG)  /* configuration block */
#define SKEIN_T1_BLK_TYPE_PERS  SKEIN_T1_BLK_TYPE(PERS) /* personalization string */
#define SKEIN_T1_BLK_TYPE_PK    SKEIN_T1_BLK_TYPE(PK)   /* public key (for digital signature hashing) */
#define SKEIN_T1_BLK_TYPE_KDF   SKEIN_T1_BLK_TYPE(KDF)  /* key identifier for KDF */
#define SKEIN_T1_BLK_TYPE_NONCE SKEIN_T1_BLK_TYPE(NONCE)/* nonce for PRNG */
#define SKEIN_T1_BLK_TYPE_MSG   SKEIN_T1_BLK_TYPE(MSG)  /* message processing */
#define SKEIN_T1_BLK_TYPE_OUT   SKEIN_T1_BLK_TYPE(OUT)  /* output stage */
#define SKEIN_T1_BLK_TYPE_MASK  SKEIN_T1_BLK_TYPE(MASK) /* field bit mask */

#define SKEIN_T1_BLK_TYPE_CFG_FINAL       (SKEIN_T1_BLK_TYPE_CFG | SKEIN_T1_FLAG_FINAL)
#define SKEIN_T1_BLK_TYPE_OUT_FINAL       (SKEIN_T1_BLK_TYPE_OUT | SKEIN_T1_FLAG_FINAL)

#define SKEIN_VERSION           (1)

#ifndef SKEIN_ID_STRING_LE      /* allow compile-time personalization */
#define SKEIN_ID_STRING_LE      (0x33414853)            /* "SHA3" (little-endian)*/
#endif

#define SKEIN_MK_64(hi32,lo32)  ((lo32) + (((u64b_t) (hi32)) << 32))
#define SKEIN_SCHEMA_VER        SKEIN_MK_64(SKEIN_VERSION,SKEIN_ID_STRING_LE)
#define SKEIN_KS_PARITY         SKEIN_MK_64(0x55555555,0x55555555)

#define SKEIN_CFG_STR_LEN       (4*8)

/* bit field definitions in config block treeInfo word */
#define SKEIN_CFG_TREE_LEAF_SIZE_POS  ( 0)
#define SKEIN_CFG_TREE_NODE_SIZE_POS  ( 8)
#define SKEIN_CFG_TREE_MAX_LEVEL_POS  (16)

#define SKEIN_CFG_TREE_LEAF_SIZE_MSK  (((u64b_t) 0xFF) << SKEIN_CFG_TREE_LEAF_SIZE_POS)
#define SKEIN_CFG_TREE_NODE_SIZE_MSK  (((u64b_t) 0xFF) << SKEIN_CFG_TREE_NODE_SIZE_POS)
#define SKEIN_CFG_TREE_MAX_LEVEL_MSK  (((u64b_t) 0xFF) << SKEIN_CFG_TREE_MAX_LEVEL_POS)

#define SKEIN_CFG_TREE_INFO(leaf,node,maxLvl)                   \
    ( (((u64b_t)(leaf  )) << SKEIN_CFG_TREE_LEAF_SIZE_POS) |    \
      (((u64b_t)(node  )) << SKEIN_CFG_TREE_NODE_SIZE_POS) |    \
      (((u64b_t)(maxLvl)) << SKEIN_CFG_TREE_MAX_LEVEL_POS) )

#define SKEIN_CFG_TREE_INFO_SEQUENTIAL SKEIN_CFG_TREE_INFO(0,0,0) /* use as treeInfo in InitExt() call for sequential processing */

/*
**   Skein macros for getting/setting tweak words, etc.
**   These are useful for partial input bytes, hash tree init/update, etc.
**/
#define Skein_Get_Tweak(ctxPtr,TWK_NUM)         ((ctxPtr)->h.T[TWK_NUM])
#define Skein_Set_Tweak(ctxPtr,TWK_NUM,tVal)    {(ctxPtr)->h.T[TWK_NUM] = (tVal);}

#define Skein_Get_T0(ctxPtr)    Skein_Get_Tweak(ctxPtr,0)
#define Skein_Get_T1(ctxPtr)    Skein_Get_Tweak(ctxPtr,1)
#define Skein_Set_T0(ctxPtr,T0) Skein_Set_Tweak(ctxPtr,0,T0)
#define Skein_Set_T1(ctxPtr,T1) Skein_Set_Tweak(ctxPtr,1,T1)

/* set both tweak words at once */
#define Skein_Set_T0_T1(ctxPtr,T0,T1)           \
    {                                           \
    Skein_Set_T0(ctxPtr,(T0));                  \
    Skein_Set_T1(ctxPtr,(T1));                  \
    }

#define Skein_Set_Type(ctxPtr,BLK_TYPE)         \
    Skein_Set_T1(ctxPtr,SKEIN_T1_BLK_TYPE_##BLK_TYPE)

/* set up for starting with a new type: h.T[0]=0; h.T[1] = NEW_TYPE; h.bCnt=0; */
#define Skein_Start_New_Type(ctxPtr,BLK_TYPE)   \
    { Skein_Set_T0_T1(ctxPtr,0,SKEIN_T1_FLAG_FIRST | SKEIN_T1_BLK_TYPE_##BLK_TYPE); (ctxPtr)->h.bCnt=0; }

#define Skein_Clear_First_Flag(hdr)      { (hdr).T[1] &= ~SKEIN_T1_FLAG_FIRST;       }
#define Skein_Set_Bit_Pad_Flag(hdr)      { (hdr).T[1] |=  SKEIN_T1_FLAG_BIT_PAD;     }

#define Skein_Set_Tree_Level(hdr,height) { (hdr).T[1] |= SKEIN_T1_TREE_LEVEL(height);}

/*****************************************************************
** "Internal" Skein definitions for debugging and error checking
******************************************************************/
#ifdef  SKEIN_DEBUG             /* examine/display intermediate values? */
#include "skein_debug.h"
#else                           /* default is no callouts */
#define Skein_Show_Block(bits,ctx,X,blkPtr,wPtr,ksEvenPtr,ksOddPtr)
#define Skein_Show_Round(bits,ctx,r,X)
#define Skein_Show_R_Ptr(bits,ctx,r,X_ptr)
#define Skein_Show_Final(bits,ctx,cnt,outPtr)
#define Skein_Show_Key(bits,ctx,key,keyBytes)
#endif

#ifndef SKEIN_ERR_CHECK        /* run-time checks (e.g., bad params, uninitialized context)? */
#define Skein_Assert(x,retCode)/* default: ignore all Asserts, for performance */
#define Skein_assert(x)
#elif   defined(SKEIN_ASSERT)
#include <assert.h>     
#define Skein_Assert(x,retCode) assert(x) 
#define Skein_assert(x)         assert(x) 
#else
#include <assert.h>     
#define Skein_Assert(x,retCode) { if (!(x)) return retCode; } /*  caller  error */
#define Skein_assert(x)         assert(x)                     /* internal error */
#endif

/*****************************************************************
** Skein block function constants (shared across Ref and Opt code)
******************************************************************/
enum    
    {   
        /* Skein_256 round rotation constants */
    R_256_0_0=14, R_256_0_1=16,
    R_256_1_0=52, R_256_1_1=57,
    R_256_2_0=23, R_256_2_1=40,
    R_256_3_0= 5, R_256_3_1=37,
    R_256_4_0=25, R_256_4_1=33,
    R_256_5_0=46, R_256_5_1=12,
    R_256_6_0=58, R_256_6_1=22,
    R_256_7_0=32, R_256_7_1=32,

        /* Skein_512 round rotation constants */
    R_512_0_0=46, R_512_0_1=36, R_512_0_2=19, R_512_0_3=37,
    R_512_1_0=33, R_512_1_1=27, R_512_1_2=14, R_512_1_3=42,
    R_512_2_0=17, R_512_2_1=49, R_512_2_2=36, R_512_2_3=39,
    R_512_3_0=44, R_512_3_1= 9, R_512_3_2=54, R_512_3_3=56,
    R_512_4_0=39, R_512_4_1=30, R_512_4_2=34, R_512_4_3=24,
    R_512_5_0=13, R_512_5_1=50, R_512_5_2=10, R_512_5_3=17,
    R_512_6_0=25, R_512_6_1=29, R_512_6_2=39, R_512_6_3=43,
    R_512_7_0= 8, R_512_7_1=35, R_512_7_2=56, R_512_7_3=22,

        /* Skein1024 round rotation constants */
    R1024_0_0=24, R1024_0_1=13, R1024_0_2= 8, R1024_0_3=47, R1024_0_4= 8, R1024_0_5=17, R1024_0_6=22, R1024_0_7=37,
    R1024_1_0=38, R1024_1_1=19, R1024_1_2=10, R1024_1_3=55, R1024_1_4=49, R1024_1_5=18, R1024_1_6=23, R1024_1_7=52,
    R1024_2_0=33, R1024_2_1= 4, R1024_2_2=51, R1024_2_3=13, R1024_2_4=34, R1024_2_5=41, R1024_2_6=59, R1024_2_7=17,
    R1024_3_0= 5, R1024_3_1=20, R1024_3_2=48, R1024_3_3=41, R1024_3_4=47, R1024_3_5=28, R1024_3_6=16, R1024_3_7=25,
    R1024_4_0=41, R1024_4_1= 9, R1024_4_2=37, R1024_4_3=31, R1024_4_4=12, R1024_4_5=47, R1024_4_6=44, R1024_4_7=30,
    R1024_5_0=16, R1024_5_1=34, R1024_5_2=56, R1024_5_3=51, R1024_5_4= 4, R1024_5_5=53, R1024_5_6=42, R1024_5_7=41,
    R1024_6_0=31, R1024_6_1=44, R1024_6_2=47, R1024_6_3=46, R1024_6_4=19, R1024_6_5=42, R1024_6_6=44, R1024_6_7=25,
    R1024_7_0= 9, R1024_7_1=48, R1024_7_2=35, R1024_7_3=52, R1024_7_4=23, R1024_7_5=31, R1024_7_6=37, R1024_7_7=20
    };

#ifndef SKEIN_ROUNDS
#define SKEIN_256_ROUNDS_TOTAL (72)          /* number of rounds for the different block sizes */
#define SKEIN_512_ROUNDS_TOTAL (72)
#define SKEIN1024_ROUNDS_TOTAL (80)
#else                                        /* allow command-line define in range 8*(5..14)   */
#define SKEIN_256_ROUNDS_TOTAL (8*((((SKEIN_ROUNDS/100) + 5) % 10) + 5))
#define SKEIN_512_ROUNDS_TOTAL (8*((((SKEIN_ROUNDS/ 10) + 5) % 10) + 5))
#define SKEIN1024_ROUNDS_TOTAL (8*((((SKEIN_ROUNDS    ) + 5) % 10) + 5))
#endif

#include "skein_dropin.h"
	
#ifdef __cplusplus
}
#endif

#endif  /* ifndef _SKEIN_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/skein_block.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
/***********************************************************************
**
** Implementation of the Skein block functions.
**
** Source code author: Doug Whiting, 2008.
** Changes added in for CommonCrypto/LTC: Jon Callas, 2010.
**
** This algorithm and source code is released to the public domain.
**
** Compile-time switches:
**
**  SKEIN_USE_ASM  -- set bits (256/512/1024) to select which
**                    versions use ASM code for block processing
**                    [default: use C for all block sizes]
**
************************************************************************/

#include <string.h>
#include "skein.h"

#ifndef SKEIN_USE_ASM
#define SKEIN_USE_ASM   (0)                     /* default is all C code (no ASM) */
#endif

#define SKEIN_LOOP 101							/* unroll Skein-512 only */

#ifndef SKEIN_LOOP
#define SKEIN_LOOP 001                          /* default: unroll 256 and 512, but not 1024 */
#endif

#define BLK_BITS        (WCNT*64)               /* some useful definitions for code here */
#define KW_TWK_BASE     (0)
#define KW_KEY_BASE     (3)
#define ks              (kw + KW_KEY_BASE)                
#define ts              (kw + KW_TWK_BASE)

#ifdef SKEIN_DEBUG
#define DebugSaveTweak(ctx) { ctx->h.T[0] = ts[0]; ctx->h.T[1] = ts[1]; }
#else
#define DebugSaveTweak(ctx)
#endif

#ifndef SKEIN256_BUILD
#define SKEIN256_BUILD 0
#define SKEIN512_BUILD 1
#define SKEIN1024_BUILD 0
#endif

#if SKEIN256_BUILD
/*****************************  Skein_256 ******************************/
#if !(SKEIN_USE_ASM & 256)
void Skein_256_Process_Block(Skein_256_Ctxt_t *ctx,const u08b_t *blkPtr,size_t blkCnt,size_t byteCntAdd)
    { /* do it in C */
    enum
        {
        WCNT = SKEIN_256_STATE_WORDS
        };
#undef  RCNT
#define RCNT  (SKEIN_256_ROUNDS_TOTAL/8)

#ifdef  SKEIN_LOOP                              /* configure how much to unroll the loop */
#define SKEIN_UNROLL_256 (((SKEIN_LOOP)/100)%10)
#else
#define SKEIN_UNROLL_256 (0)
#endif

#if SKEIN_UNROLL_256
#if (RCNT % SKEIN_UNROLL_256)
//#error "Invalid SKEIN_UNROLL_256"               /* sanity check on unroll count */
#endif
    size_t  r;
    u64b_t  kw[WCNT+4+RCNT*2];                  /* key schedule words : chaining vars + tweak + "rotation"*/
#else
    u64b_t  kw[WCNT+4];                         /* key schedule words : chaining vars + tweak */
#endif
    u64b_t  X0,X1,X2,X3;                        /* local copy of context vars, for speed */
    u64b_t  w [WCNT];                           /* local copy of input block */
#ifdef SKEIN_DEBUG
    const u64b_t *Xptr[4];                      /* use for debugging (help compiler put Xn in registers) */
    Xptr[0] = &X0;  Xptr[1] = &X1;  Xptr[2] = &X2;  Xptr[3] = &X3;
#endif
    Skein_assert(blkCnt != 0);                  /* never call with blkCnt == 0! */
    ts[0] = ctx->h.T[0];
    ts[1] = ctx->h.T[1];
    do  {
        /* this implementation only supports 2**64 input bytes (no carry out here) */
        ts[0] += byteCntAdd;                    /* update processed length */

        /* precompute the key schedule for this block */
        ks[0] = ctx->X[0];     
        ks[1] = ctx->X[1];
        ks[2] = ctx->X[2];
        ks[3] = ctx->X[3];
        ks[4] = ks[0] ^ ks[1] ^ ks[2] ^ ks[3] ^ SKEIN_KS_PARITY;

        ts[2] = ts[0] ^ ts[1];

        Skein_Get64_LSB_First(w,blkPtr,WCNT);   /* get input block in little-endian format */
		DebugSaveTweak(ctx);
        Skein_Show_Block(BLK_BITS,&ctx->h,ctx->X,blkPtr,w,ks,ts);

        X0 = w[0] + ks[0];                      /* do the first full key injection */
        X1 = w[1] + ks[1] + ts[0];
        X2 = w[2] + ks[2] + ts[1];
        X3 = w[3] + ks[3];

        Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INITIAL,Xptr);    /* show starting state values */

        blkPtr += SKEIN_256_BLOCK_BYTES;

        /* run the rounds */

#define Round256(p0,p1,p2,p3,ROT,rNum)                              \
    X##p0 += X##p1; X##p1 = RotL_64(X##p1,ROT##_0); X##p1 ^= X##p0; \
    X##p2 += X##p3; X##p3 = RotL_64(X##p3,ROT##_1); X##p3 ^= X##p2; \

#if SKEIN_UNROLL_256 == 0                       
#define R256(p0,p1,p2,p3,ROT,rNum)           /* fully unrolled */   \
    Round256(p0,p1,p2,p3,ROT,rNum)                                  \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,rNum,Xptr);

#define I256(R)                                                     \
    X0   += ks[((R)+1) % 5];    /* inject the key schedule value */ \
    X1   += ks[((R)+2) % 5] + ts[((R)+1) % 3];                      \
    X2   += ks[((R)+3) % 5] + ts[((R)+2) % 3];                      \
    X3   += ks[((R)+4) % 5] +     (R)+1;                            \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INJECT,Xptr);
#else                                       /* looping version */
#define R256(p0,p1,p2,p3,ROT,rNum)                                  \
    Round256(p0,p1,p2,p3,ROT,rNum)                                  \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,4*(r-1)+rNum,Xptr);

#define I256(R)                                                     \
    X0   += ks[r+(R)+0];        /* inject the key schedule value */ \
    X1   += ks[r+(R)+1] + ts[r+(R)+0];                              \
    X2   += ks[r+(R)+2] + ts[r+(R)+1];                              \
    X3   += ks[r+(R)+3] +    r+(R)   ;                              \
    ks[r + (R)+4    ]   = ks[r+(R)-1];     /* rotate key schedule */\
    ts[r + (R)+2    ]   = ts[r+(R)-1];                              \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INJECT,Xptr);

    for (r=1;r < 2*RCNT;r+=2*SKEIN_UNROLL_256)  /* loop thru it */
#endif  
        {    
#define R256_8_rounds(R)                  \
        R256(0,1,2,3,R_256_0,8*(R) + 1);  \
        R256(0,3,2,1,R_256_1,8*(R) + 2);  \
        R256(0,1,2,3,R_256_2,8*(R) + 3);  \
        R256(0,3,2,1,R_256_3,8*(R) + 4);  \
        I256(2*(R));                      \
        R256(0,1,2,3,R_256_4,8*(R) + 5);  \
        R256(0,3,2,1,R_256_5,8*(R) + 6);  \
        R256(0,1,2,3,R_256_6,8*(R) + 7);  \
        R256(0,3,2,1,R_256_7,8*(R) + 8);  \
        I256(2*(R)+1);

        R256_8_rounds( 0);

#define R256_Unroll_R(NN) ((SKEIN_UNROLL_256 == 0 && SKEIN_256_ROUNDS_TOTAL/8 > (NN)) || (SKEIN_UNROLL_256 > (NN)))

  #if   R256_Unroll_R( 1)
        R256_8_rounds( 1);
  #endif
  #if   R256_Unroll_R( 2)
        R256_8_rounds( 2);
  #endif
  #if   R256_Unroll_R( 3)
        R256_8_rounds( 3);
  #endif
  #if   R256_Unroll_R( 4)
        R256_8_rounds( 4);
  #endif
  #if   R256_Unroll_R( 5)
        R256_8_rounds( 5);
  #endif
  #if   R256_Unroll_R( 6)
        R256_8_rounds( 6);
  #endif
  #if   R256_Unroll_R( 7)
        R256_8_rounds( 7);
  #endif
  #if   R256_Unroll_R( 8)
        R256_8_rounds( 8);
  #endif
  #if   R256_Unroll_R( 9)
        R256_8_rounds( 9);
  #endif
  #if   R256_Unroll_R(10)
        R256_8_rounds(10);
  #endif
  #if   R256_Unroll_R(11)
        R256_8_rounds(11);
  #endif
  #if   R256_Unroll_R(12)
        R256_8_rounds(12);
  #endif
  #if   R256_Unroll_R(13)
        R256_8_rounds(13);
  #endif
  #if   R256_Unroll_R(14)
        R256_8_rounds(14);
  #endif
  #if  (SKEIN_UNROLL_256 > 14)
//#error  "need more unrolling in Skein_256_Process_Block"
  #endif
        }
        /* do the final "feedforward" xor, update context chaining vars */
        ctx->X[0] = X0 ^ w[0];
        ctx->X[1] = X1 ^ w[1];
        ctx->X[2] = X2 ^ w[2];
        ctx->X[3] = X3 ^ w[3];

        Skein_Show_Round(BLK_BITS,&ctx->h,SKEIN_RND_FEED_FWD,ctx->X);

        ts[1] &= ~SKEIN_T1_FLAG_FIRST;
        }
    while (--blkCnt);
    ctx->h.T[0] = ts[0];
    ctx->h.T[1] = ts[1];
    }

#if defined(SKEIN_CODE_SIZE) || defined(SKEIN_PERF)
size_t Skein_256_Process_Block_CodeSize(void)
    {
    return ((u08b_t *) Skein_256_Process_Block_CodeSize) -
           ((u08b_t *) Skein_256_Process_Block);
    }
uint_t Skein_256_Unroll_Cnt(void)
    {
    return SKEIN_UNROLL_256;
    }
#endif
#endif

#endif /* SKEIN256_BUILD */

#if SKEIN512_BUILD

/*****************************  Skein_512 ******************************/
#if !(SKEIN_USE_ASM & 512)
void Skein_512_Process_Block(Skein_512_Ctxt_t *ctx,const u08b_t *blkPtr,size_t blkCnt,size_t byteCntAdd)
    { /* do it in C */
    enum
        {
        WCNT = SKEIN_512_STATE_WORDS
        };
#undef  RCNT
#define RCNT  (SKEIN_512_ROUNDS_TOTAL/8)

#ifdef  SKEIN_LOOP                              /* configure how much to unroll the loop */
#define SKEIN_UNROLL_512 (((SKEIN_LOOP)/10)%10)
#else
#define SKEIN_UNROLL_512 (0)
#endif

#if SKEIN_UNROLL_512
#if (RCNT % SKEIN_UNROLL_512)
//#error "Invalid SKEIN_UNROLL_512"               /* sanity check on unroll count */
#endif
    size_t  r;
    u64b_t  kw[WCNT+4+RCNT*2];                  /* key schedule words : chaining vars + tweak + "rotation"*/
#else
    u64b_t  kw[WCNT+4];                         /* key schedule words : chaining vars + tweak */
#endif
    u64b_t  X0,X1,X2,X3,X4,X5,X6,X7;            /* local copy of vars, for speed */
    u64b_t  w [WCNT];                           /* local copy of input block */
#ifdef SKEIN_DEBUG
    const u64b_t *Xptr[8];                      /* use for debugging (help compiler put Xn in registers) */
    Xptr[0] = &X0;  Xptr[1] = &X1;  Xptr[2] = &X2;  Xptr[3] = &X3;
    Xptr[4] = &X4;  Xptr[5] = &X5;  Xptr[6] = &X6;  Xptr[7] = &X7;
#endif

    Skein_assert(blkCnt != 0);                  /* never call with blkCnt == 0! */
	ts[0] = ctx->h.T[0];
	ts[1] = ctx->h.T[1];
    do  {
        /* this implementation only supports 2**64 input bytes (no carry out here) */
        ts[0] += byteCntAdd;                    /* update processed length */

        /* precompute the key schedule for this block */
        ks[0] = ctx->X[0];
        ks[1] = ctx->X[1];
        ks[2] = ctx->X[2];
        ks[3] = ctx->X[3];
        ks[4] = ctx->X[4];
        ks[5] = ctx->X[5];
        ks[6] = ctx->X[6];
        ks[7] = ctx->X[7];
        ks[8] = ks[0] ^ ks[1] ^ ks[2] ^ ks[3] ^ 
                ks[4] ^ ks[5] ^ ks[6] ^ ks[7] ^ SKEIN_KS_PARITY;

        ts[2] = ts[0] ^ ts[1];

        Skein_Get64_LSB_First(w,blkPtr,WCNT); /* get input block in little-endian format */
		DebugSaveTweak(ctx);
        Skein_Show_Block(BLK_BITS,&ctx->h,ctx->X,blkPtr,w,ks,ts);

        X0   = w[0] + ks[0];                    /* do the first full key injection */
        X1   = w[1] + ks[1];
        X2   = w[2] + ks[2];
        X3   = w[3] + ks[3];
        X4   = w[4] + ks[4];
        X5   = w[5] + ks[5] + ts[0];
        X6   = w[6] + ks[6] + ts[1];
        X7   = w[7] + ks[7];

        blkPtr += SKEIN_512_BLOCK_BYTES;

        Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INITIAL,Xptr);
        /* run the rounds */
#define Round512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum)                  \
    X##p0 += X##p1; X##p1 = RotL_64(X##p1,ROT##_0); X##p1 ^= X##p0; \
    X##p2 += X##p3; X##p3 = RotL_64(X##p3,ROT##_1); X##p3 ^= X##p2; \
    X##p4 += X##p5; X##p5 = RotL_64(X##p5,ROT##_2); X##p5 ^= X##p4; \
    X##p6 += X##p7; X##p7 = RotL_64(X##p7,ROT##_3); X##p7 ^= X##p6; \

#if SKEIN_UNROLL_512 == 0                       
#define R512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum)      /* unrolled */  \
    Round512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum)                      \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,rNum,Xptr);

#define I512(R)                                                     \
    X0   += ks[((R)+1) % 9];   /* inject the key schedule value */  \
    X1   += ks[((R)+2) % 9];                                        \
    X2   += ks[((R)+3) % 9];                                        \
    X3   += ks[((R)+4) % 9];                                        \
    X4   += ks[((R)+5) % 9];                                        \
    X5   += ks[((R)+6) % 9] + ts[((R)+1) % 3];                      \
    X6   += ks[((R)+7) % 9] + ts[((R)+2) % 3];                      \
    X7   += ks[((R)+8) % 9] +     (R)+1;                            \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INJECT,Xptr);
#else                                       /* looping version */
#define R512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum)                      \
    Round512(p0,p1,p2,p3,p4,p5,p6,p7,ROT,rNum)                      \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,4*(r-1)+rNum,Xptr);

#define I512(R)                                                     \
    X0   += ks[r+(R)+0];        /* inject the key schedule value */ \
    X1   += ks[r+(R)+1];                                            \
    X2   += ks[r+(R)+2];                                            \
    X3   += ks[r+(R)+3];                                            \
    X4   += ks[r+(R)+4];                                            \
    X5   += ks[r+(R)+5] + ts[r+(R)+0];                              \
    X6   += ks[r+(R)+6] + ts[r+(R)+1];                              \
    X7   += ks[r+(R)+7] +    r+(R)   ;                              \
    ks[r +       (R)+8] = ks[r+(R)-1];  /* rotate key schedule */   \
    ts[r +       (R)+2] = ts[r+(R)-1];                              \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INJECT,Xptr);

    for (r=1;r < 2*RCNT;r+=2*SKEIN_UNROLL_512)   /* loop thru it */
#endif                         /* end of looped code definitions */
        {
#define R512_8_rounds(R)  /* do 8 full rounds */  \
        R512(0,1,2,3,4,5,6,7,R_512_0,8*(R)+ 1);   \
        R512(2,1,4,7,6,5,0,3,R_512_1,8*(R)+ 2);   \
        R512(4,1,6,3,0,5,2,7,R_512_2,8*(R)+ 3);   \
        R512(6,1,0,7,2,5,4,3,R_512_3,8*(R)+ 4);   \
        I512(2*(R));                              \
        R512(0,1,2,3,4,5,6,7,R_512_4,8*(R)+ 5);   \
        R512(2,1,4,7,6,5,0,3,R_512_5,8*(R)+ 6);   \
        R512(4,1,6,3,0,5,2,7,R_512_6,8*(R)+ 7);   \
        R512(6,1,0,7,2,5,4,3,R_512_7,8*(R)+ 8);   \
        I512(2*(R)+1);        /* and key injection */

        R512_8_rounds( 0);

#define R512_Unroll_R(NN) ((SKEIN_UNROLL_512 == 0 && SKEIN_512_ROUNDS_TOTAL/8 > (NN)) || (SKEIN_UNROLL_512 > (NN)))

  #if   R512_Unroll_R( 1)
        R512_8_rounds( 1);
  #endif
  #if   R512_Unroll_R( 2)
        R512_8_rounds( 2);
  #endif
  #if   R512_Unroll_R( 3)
        R512_8_rounds( 3);
  #endif
  #if   R512_Unroll_R( 4)
        R512_8_rounds( 4);
  #endif
  #if   R512_Unroll_R( 5)
        R512_8_rounds( 5);
  #endif
  #if   R512_Unroll_R( 6)
        R512_8_rounds( 6);
  #endif
  #if   R512_Unroll_R( 7)
        R512_8_rounds( 7);
  #endif
  #if   R512_Unroll_R( 8)
        R512_8_rounds( 8);
  #endif
  #if   R512_Unroll_R( 9)
        R512_8_rounds( 9);
  #endif
  #if   R512_Unroll_R(10)
        R512_8_rounds(10);
  #endif
  #if   R512_Unroll_R(11)
        R512_8_rounds(11);
  #endif
  #if   R512_Unroll_R(12)
        R512_8_rounds(12);
  #endif
  #if   R512_Unroll_R(13)
        R512_8_rounds(13);
  #endif
  #if   R512_Unroll_R(14)
        R512_8_rounds(14);
  #endif
  #if  (SKEIN_UNROLL_512 > 14)
//#error  "need more unrolling in Skein_512_Process_Block"
  #endif
        }

        /* do the final "feedforward" xor, update context chaining vars */
        ctx->X[0] = X0 ^ w[0];
        ctx->X[1] = X1 ^ w[1];
        ctx->X[2] = X2 ^ w[2];
        ctx->X[3] = X3 ^ w[3];
        ctx->X[4] = X4 ^ w[4];
        ctx->X[5] = X5 ^ w[5];
        ctx->X[6] = X6 ^ w[6];
        ctx->X[7] = X7 ^ w[7];
        Skein_Show_Round(BLK_BITS,&ctx->h,SKEIN_RND_FEED_FWD,ctx->X);

        ts[1] &= ~SKEIN_T1_FLAG_FIRST;
        }
    while (--blkCnt);
    ctx->h.T[0] = ts[0];
    ctx->h.T[1] = ts[1];
    }

#if defined(SKEIN_CODE_SIZE) || defined(SKEIN_PERF)
size_t Skein_512_Process_Block_CodeSize(void)
    {
    return ((u08b_t *) Skein_512_Process_Block_CodeSize) -
           ((u08b_t *) Skein_512_Process_Block);
    }
uint_t Skein_512_Unroll_Cnt(void)
    {
    return SKEIN_UNROLL_512;
    }
#endif
#endif

#endif /* SKEIN512_BUILD */

#if SKEIN1024_BUILD

/*****************************  Skein1024 ******************************/
#if !(SKEIN_USE_ASM & 1024)
void Skein1024_Process_Block(Skein1024_Ctxt_t *ctx,const u08b_t *blkPtr,size_t blkCnt,size_t byteCntAdd)
    { /* do it in C, always looping (unrolled is bigger AND slower!) */
    enum
        {
        WCNT = SKEIN1024_STATE_WORDS
        };
#undef  RCNT
#define RCNT  (SKEIN1024_ROUNDS_TOTAL/8)

#ifdef  SKEIN_LOOP                              /* configure how much to unroll the loop */
#define SKEIN_UNROLL_1024 ((SKEIN_LOOP)%10)
#else
#define SKEIN_UNROLL_1024 (0)
#endif

#if (SKEIN_UNROLL_1024 != 0)
#if (RCNT % SKEIN_UNROLL_1024)
//#error "Invalid SKEIN_UNROLL_1024"              /* sanity check on unroll count */
#endif
    size_t  r;
    u64b_t  kw[WCNT+4+RCNT*2];                  /* key schedule words : chaining vars + tweak + "rotation"*/
#else
    u64b_t  kw[WCNT+4];                         /* key schedule words : chaining vars + tweak */
#endif

    u64b_t  X00,X01,X02,X03,X04,X05,X06,X07,    /* local copy of vars, for speed */
            X08,X09,X10,X11,X12,X13,X14,X15;
    u64b_t  w [WCNT];                           /* local copy of input block */
#ifdef SKEIN_DEBUG
    const u64b_t *Xptr[16];                     /* use for debugging (help compiler put Xn in registers) */
    Xptr[ 0] = &X00;  Xptr[ 1] = &X01;  Xptr[ 2] = &X02;  Xptr[ 3] = &X03;
    Xptr[ 4] = &X04;  Xptr[ 5] = &X05;  Xptr[ 6] = &X06;  Xptr[ 7] = &X07;
    Xptr[ 8] = &X08;  Xptr[ 9] = &X09;  Xptr[10] = &X10;  Xptr[11] = &X11;
    Xptr[12] = &X12;  Xptr[13] = &X13;  Xptr[14] = &X14;  Xptr[15] = &X15;
#endif

    Skein_assert(blkCnt != 0);                  /* never call with blkCnt == 0! */
    ts[0] = ctx->h.T[0];
    ts[1] = ctx->h.T[1];
    do  {
        /* this implementation only supports 2**64 input bytes (no carry out here) */
        ts[0] += byteCntAdd;                    /* update processed length */

        /* precompute the key schedule for this block */
        ks[ 0] = ctx->X[ 0];
        ks[ 1] = ctx->X[ 1];
        ks[ 2] = ctx->X[ 2];
        ks[ 3] = ctx->X[ 3];
        ks[ 4] = ctx->X[ 4];
        ks[ 5] = ctx->X[ 5];
        ks[ 6] = ctx->X[ 6];
        ks[ 7] = ctx->X[ 7];
        ks[ 8] = ctx->X[ 8];
        ks[ 9] = ctx->X[ 9];
        ks[10] = ctx->X[10];
        ks[11] = ctx->X[11];
        ks[12] = ctx->X[12];
        ks[13] = ctx->X[13];
        ks[14] = ctx->X[14];
        ks[15] = ctx->X[15];
        ks[16] = ks[ 0] ^ ks[ 1] ^ ks[ 2] ^ ks[ 3] ^
                 ks[ 4] ^ ks[ 5] ^ ks[ 6] ^ ks[ 7] ^
                 ks[ 8] ^ ks[ 9] ^ ks[10] ^ ks[11] ^
                 ks[12] ^ ks[13] ^ ks[14] ^ ks[15] ^ SKEIN_KS_PARITY;

        ts[2]  = ts[0] ^ ts[1];

        Skein_Get64_LSB_First(w,blkPtr,WCNT); /* get input block in little-endian format */
		DebugSaveTweak(ctx);
        Skein_Show_Block(BLK_BITS,&ctx->h,ctx->X,blkPtr,w,ks,ts);

        X00    = w[ 0] + ks[ 0];                 /* do the first full key injection */
        X01    = w[ 1] + ks[ 1];
        X02    = w[ 2] + ks[ 2];
        X03    = w[ 3] + ks[ 3];
        X04    = w[ 4] + ks[ 4];
        X05    = w[ 5] + ks[ 5];
        X06    = w[ 6] + ks[ 6];
        X07    = w[ 7] + ks[ 7];
        X08    = w[ 8] + ks[ 8];
        X09    = w[ 9] + ks[ 9];
        X10    = w[10] + ks[10];
        X11    = w[11] + ks[11];
        X12    = w[12] + ks[12];
        X13    = w[13] + ks[13] + ts[0];
        X14    = w[14] + ks[14] + ts[1];
        X15    = w[15] + ks[15];

        Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INITIAL,Xptr);

#define Round1024(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,pA,pB,pC,pD,pE,pF,ROT,rNum) \
    X##p0 += X##p1; X##p1 = RotL_64(X##p1,ROT##_0); X##p1 ^= X##p0;   \
    X##p2 += X##p3; X##p3 = RotL_64(X##p3,ROT##_1); X##p3 ^= X##p2;   \
    X##p4 += X##p5; X##p5 = RotL_64(X##p5,ROT##_2); X##p5 ^= X##p4;   \
    X##p6 += X##p7; X##p7 = RotL_64(X##p7,ROT##_3); X##p7 ^= X##p6;   \
    X##p8 += X##p9; X##p9 = RotL_64(X##p9,ROT##_4); X##p9 ^= X##p8;   \
    X##pA += X##pB; X##pB = RotL_64(X##pB,ROT##_5); X##pB ^= X##pA;   \
    X##pC += X##pD; X##pD = RotL_64(X##pD,ROT##_6); X##pD ^= X##pC;   \
    X##pE += X##pF; X##pF = RotL_64(X##pF,ROT##_7); X##pF ^= X##pE;   \

#if SKEIN_UNROLL_1024 == 0                      
#define R1024(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,pA,pB,pC,pD,pE,pF,ROT,rn) \
    Round1024(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,pA,pB,pC,pD,pE,pF,ROT,rn) \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,rn,Xptr);

#define I1024(R)                                                      \
    X00   += ks[((R)+ 1) % 17]; /* inject the key schedule value */   \
    X01   += ks[((R)+ 2) % 17];                                       \
    X02   += ks[((R)+ 3) % 17];                                       \
    X03   += ks[((R)+ 4) % 17];                                       \
    X04   += ks[((R)+ 5) % 17];                                       \
    X05   += ks[((R)+ 6) % 17];                                       \
    X06   += ks[((R)+ 7) % 17];                                       \
    X07   += ks[((R)+ 8) % 17];                                       \
    X08   += ks[((R)+ 9) % 17];                                       \
    X09   += ks[((R)+10) % 17];                                       \
    X10   += ks[((R)+11) % 17];                                       \
    X11   += ks[((R)+12) % 17];                                       \
    X12   += ks[((R)+13) % 17];                                       \
    X13   += ks[((R)+14) % 17] + ts[((R)+1) % 3];                     \
    X14   += ks[((R)+15) % 17] + ts[((R)+2) % 3];                     \
    X15   += ks[((R)+16) % 17] +     (R)+1;                           \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INJECT,Xptr); 
#else                                       /* looping version */
#define R1024(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,pA,pB,pC,pD,pE,pF,ROT,rn) \
    Round1024(p0,p1,p2,p3,p4,p5,p6,p7,p8,p9,pA,pB,pC,pD,pE,pF,ROT,rn) \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,4*(r-1)+rn,Xptr);

#define I1024(R)                                                      \
    X00   += ks[r+(R)+ 0];    /* inject the key schedule value */     \
    X01   += ks[r+(R)+ 1];                                            \
    X02   += ks[r+(R)+ 2];                                            \
    X03   += ks[r+(R)+ 3];                                            \
    X04   += ks[r+(R)+ 4];                                            \
    X05   += ks[r+(R)+ 5];                                            \
    X06   += ks[r+(R)+ 6];                                            \
    X07   += ks[r+(R)+ 7];                                            \
    X08   += ks[r+(R)+ 8];                                            \
    X09   += ks[r+(R)+ 9];                                            \
    X10   += ks[r+(R)+10];                                            \
    X11   += ks[r+(R)+11];                                            \
    X12   += ks[r+(R)+12];                                            \
    X13   += ks[r+(R)+13] + ts[r+(R)+0];                              \
    X14   += ks[r+(R)+14] + ts[r+(R)+1];                              \
    X15   += ks[r+(R)+15] +    r+(R)   ;                              \
    ks[r  +       (R)+16] = ks[r+(R)-1];  /* rotate key schedule */   \
    ts[r  +       (R)+ 2] = ts[r+(R)-1];                              \
    Skein_Show_R_Ptr(BLK_BITS,&ctx->h,SKEIN_RND_KEY_INJECT,Xptr);

    for (r=1;r <= 2*RCNT;r+=2*SKEIN_UNROLL_1024)    /* loop thru it */
#endif  
        {
#define R1024_8_rounds(R)    /* do 8 full rounds */                               \
        R1024(00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,R1024_0,8*(R) + 1); \
        R1024(00,09,02,13,06,11,04,15,10,07,12,03,14,05,08,01,R1024_1,8*(R) + 2); \
        R1024(00,07,02,05,04,03,06,01,12,15,14,13,08,11,10,09,R1024_2,8*(R) + 3); \
        R1024(00,15,02,11,06,13,04,09,14,01,08,05,10,03,12,07,R1024_3,8*(R) + 4); \
        I1024(2*(R));                                                             \
        R1024(00,01,02,03,04,05,06,07,08,09,10,11,12,13,14,15,R1024_4,8*(R) + 5); \
        R1024(00,09,02,13,06,11,04,15,10,07,12,03,14,05,08,01,R1024_5,8*(R) + 6); \
        R1024(00,07,02,05,04,03,06,01,12,15,14,13,08,11,10,09,R1024_6,8*(R) + 7); \
        R1024(00,15,02,11,06,13,04,09,14,01,08,05,10,03,12,07,R1024_7,8*(R) + 8); \
        I1024(2*(R)+1);

        R1024_8_rounds( 0);

#define R1024_Unroll_R(NN) ((SKEIN_UNROLL_1024 == 0 && SKEIN1024_ROUNDS_TOTAL/8 > (NN)) || (SKEIN_UNROLL_1024 > (NN)))

  #if   R1024_Unroll_R( 1)
        R1024_8_rounds( 1);
  #endif
  #if   R1024_Unroll_R( 2)
        R1024_8_rounds( 2);
  #endif
  #if   R1024_Unroll_R( 3)
        R1024_8_rounds( 3);
  #endif
  #if   R1024_Unroll_R( 4)
        R1024_8_rounds( 4);
  #endif
  #if   R1024_Unroll_R( 5)
        R1024_8_rounds( 5);
  #endif
  #if   R1024_Unroll_R( 6)
        R1024_8_rounds( 6);
  #endif
  #if   R1024_Unroll_R( 7)
        R1024_8_rounds( 7);
  #endif
  #if   R1024_Unroll_R( 8)
        R1024_8_rounds( 8);
  #endif
  #if   R1024_Unroll_R( 9)
        R1024_8_rounds( 9);
  #endif
  #if   R1024_Unroll_R(10)
        R1024_8_rounds(10);
  #endif
  #if   R1024_Unroll_R(11)
        R1024_8_rounds(11);
  #endif
  #if   R1024_Unroll_R(12)
        R1024_8_rounds(12);
  #endif
  #if   R1024_Unroll_R(13)
        R1024_8_rounds(13);
  #endif
  #if   R1024_Unroll_R(14)
        R1024_8_rounds(14);
  #endif
  #if  (SKEIN_UNROLL_1024 > 14)
//#error  "need more unrolling in Skein_1024_Process_Block"
  #endif
        }
        /* do the final "feedforward" xor, update context chaining vars */

        ctx->X[ 0] = X00 ^ w[ 0];
        ctx->X[ 1] = X01 ^ w[ 1];
        ctx->X[ 2] = X02 ^ w[ 2];
        ctx->X[ 3] = X03 ^ w[ 3];
        ctx->X[ 4] = X04 ^ w[ 4];
        ctx->X[ 5] = X05 ^ w[ 5];
        ctx->X[ 6] = X06 ^ w[ 6];
        ctx->X[ 7] = X07 ^ w[ 7];
        ctx->X[ 8] = X08 ^ w[ 8];
        ctx->X[ 9] = X09 ^ w[ 9];
        ctx->X[10] = X10 ^ w[10];
        ctx->X[11] = X11 ^ w[11];
        ctx->X[12] = X12 ^ w[12];
        ctx->X[13] = X13 ^ w[13];
        ctx->X[14] = X14 ^ w[14];
        ctx->X[15] = X15 ^ w[15];

        Skein_Show_Round(BLK_BITS,&ctx->h,SKEIN_RND_FEED_FWD,ctx->X);
        
        ts[1] &= ~SKEIN_T1_FLAG_FIRST;
        blkPtr += SKEIN1024_BLOCK_BYTES;
        }
    while (--blkCnt);
    ctx->h.T[0] = ts[0];
    ctx->h.T[1] = ts[1];
    }

#if defined(SKEIN_CODE_SIZE) || defined(SKEIN_PERF)
size_t Skein1024_Process_Block_CodeSize(void)
    {
    return ((u08b_t *) Skein1024_Process_Block_CodeSize) -
           ((u08b_t *) Skein1024_Process_Block);
    }
uint_t Skein1024_Unroll_Cnt(void)
    {
    return SKEIN_UNROLL_1024;
    }
#endif
#endif

#endif /* SKEIN1024_BUILD */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/skein_debug.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/***********************************************************************
**
** Debug output functions for Skein hashing.
**
** Source code author: Doug Whiting, 2008.
**
** This algorithm and source code is released to the public domain.
**
************************************************************************/
#include <stdio.h>

#ifdef SKEIN_DEBUG  /* only instantiate this code if SKEIN_DEBUG is on */
#include "skein.h"

static const char *INDENT = "    ";  /* how much to indent on new line */

uint_t skein_DebugFlag = 0;  /* off by default. Must be set externally */

static void Show64(size_t cnt,const u64b_t *X)
    {
    size_t i;
    for (i=0;i < cnt;i++)
        {
        if (i % 4 ==  0) printf(INDENT);
        printf(" %08X.%08X ",(uint_32t)(X[i] >> 32),(uint_32t)X[i]);
        if (i % 4 ==  3 || i==cnt-1) printf("\n");
        }
    }

static void Show08(size_t cnt,const u08b_t *b)
    {
    size_t i;
    for (i=0;i < cnt;i++)
        {
		if (i %16 ==  0) printf(INDENT);
		else if (i % 4 == 0) printf(" ");
        printf(" %02X",b[i]);
        if (i %16 == 15 || i==cnt-1) printf("\n");
        }
    }

static const char *AlgoHeader(uint_t bits)
	{
	if (skein_DebugFlag & SKEIN_DEBUG_THREEFISH)
		switch (bits)
			{
			case  256:	return ":Threefish-256: ";
			case  512:	return ":Threefish-512: ";
			case 1024:	return ":Threefish-1024:";
			}
	else
		switch (bits)
			{
			case  256:	return ":Skein-256: ";
			case  512:	return ":Skein-512: ";
			case 1024:	return ":Skein-1024:";
			}
	return NULL;
	}

void Skein_Show_Final(uint_t bits,const Skein_Ctxt_Hdr_t *h,size_t cnt,const u08b_t *outPtr)
    {
    if (skein_DebugFlag & SKEIN_DEBUG_CONFIG || ((h->T[1] & SKEIN_T1_BLK_TYPE_MASK) != SKEIN_T1_BLK_TYPE_CFG))
    if (skein_DebugFlag & SKEIN_DEBUG_FINAL)
        {
        printf("\n%s Final output=\n",AlgoHeader(bits));
        Show08(cnt,outPtr);
        printf("    ++++++++++\n");
        }
    }

/* show state after a round (or "pseudo-round") */
void Skein_Show_Round(uint_t bits,const Skein_Ctxt_Hdr_t *h,size_t r,const u64b_t *X)
    {
	static uint_t injectNum=0;	/* not multi-thread safe! */

    if (skein_DebugFlag & SKEIN_DEBUG_CONFIG || ((h->T[1] & SKEIN_T1_BLK_TYPE_MASK) != SKEIN_T1_BLK_TYPE_CFG))
    if (skein_DebugFlag)
        {
        if (r >= SKEIN_RND_SPECIAL) 
            {       /* a key injection (or feedforward) point */
			injectNum = (r == SKEIN_RND_KEY_INITIAL) ? 0 : injectNum+1;
			if (  skein_DebugFlag & SKEIN_DEBUG_INJECT ||
				((skein_DebugFlag & SKEIN_DEBUG_FINAL) && r == SKEIN_RND_FEED_FWD))
                {
                printf("\n%s",AlgoHeader(bits));
                switch (r)
                    {
					case SKEIN_RND_KEY_INITIAL:
						printf(" [state after initial key injection]");
						break;
					case SKEIN_RND_KEY_INJECT:
						printf(" [state after key injection #%02d]",injectNum);
						break;
					case SKEIN_RND_FEED_FWD:
						printf(" [state after plaintext feedforward]");
						injectNum = 0;
						break;
                    }
                printf("=\n");
                Show64(bits/64,X);
				if (r== SKEIN_RND_FEED_FWD)
					printf("    ----------\n");
                }
            }
		else if (skein_DebugFlag & SKEIN_DEBUG_ROUNDS)
            {
			uint_t j;
			u64b_t p[SKEIN_MAX_STATE_WORDS];
			const u08b_t *perm;
			const static u08b_t PERM_256 [4][ 4] = { { 0,1,2,3 }, { 0,3,2,1 }, { 0,1,2,3 }, { 0,3,2,1 } };
			const static u08b_t PERM_512 [4][ 8] = { { 0,1,2,3,4,5,6,7 },
													 { 2,1,4,7,6,5,0,3 },
													 { 4,1,6,3,0,5,2,7 },
													 { 6,1,0,7,2,5,4,3 }
												   };
			const static u08b_t PERM_1024[4][16] = { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15 },
												     { 0, 9, 2,13, 6,11, 4,15,10, 7,12, 3,14, 5, 8, 1 },
												     { 0, 7, 2, 5, 4, 3, 6, 1,12,15,14,13, 8,11,10, 9 },
												     { 0,15, 2,11, 6,13, 4, 9,14, 1, 8, 5,10, 3,12, 7 }
												   };
					
			if ((skein_DebugFlag & SKEIN_DEBUG_PERMUTE) && (r & 3))
				{
				printf("\n%s [state after round %2d (permuted)]=\n",AlgoHeader(bits),r);
				switch (bits)
					{
					case  256: perm = PERM_256 [r&3];	break;
					case  512: perm = PERM_512 [r&3];	break;
					default:   perm = PERM_1024[r&3];	break;
					}
				for (j=0;j<bits/64;j++)
					p[j] = X[perm[j]];
				Show64(bits/64,p);
				}
			else
				{
				printf("\n%s [state after round %2d]=\n",AlgoHeader(bits),r);
				Show64(bits/64,X);
				}
            }
        }
    }

/* show state after a round (or "pseudo-round"), given a list of pointers */
void Skein_Show_R_Ptr(uint_t bits,const Skein_Ctxt_Hdr_t *h,size_t r,const u64b_t *X_ptr[])
    {
    uint_t i;
    u64b_t X[SKEIN_MAX_STATE_WORDS];

    for (i=0;i<bits/64;i++)     /* copy over the words */ 
        X[i] = X_ptr[i][0];
    Skein_Show_Round(bits,h,r,X);
    }


/* show the state at the start of a block */
void Skein_Show_Block(uint_t bits,const Skein_Ctxt_Hdr_t *h,const u64b_t *X,const u08b_t *blkPtr,
                      const u64b_t *wPtr, const u64b_t *ksPtr, const u64b_t *tsPtr)
    {
    uint_t n;
    if (skein_DebugFlag & SKEIN_DEBUG_CONFIG || ((h->T[1] & SKEIN_T1_BLK_TYPE_MASK) != SKEIN_T1_BLK_TYPE_CFG))
    if (skein_DebugFlag)
        {
		if (skein_DebugFlag & SKEIN_DEBUG_HDR)
			{
			printf("\n%s Block: outBits=%4d. T0=%06X.",AlgoHeader(bits),(uint_t) h->hashBitLen,(uint_t)h->T[0]);
			printf(" Type=");
			n = (uint_t) ((h->T[1] & SKEIN_T1_BLK_TYPE_MASK) >> SKEIN_T1_POS_BLK_TYPE);
			switch (n)
				{
				case SKEIN_BLK_TYPE_KEY:  printf("KEY. ");  break;
				case SKEIN_BLK_TYPE_CFG:  printf("CFG. ");  break;
				case SKEIN_BLK_TYPE_PERS: printf("PERS."); break;
				case SKEIN_BLK_TYPE_PK :  printf("PK.  ");   break;
				case SKEIN_BLK_TYPE_KDF:  printf("KDF. ");  break;
				case SKEIN_BLK_TYPE_MSG:  printf("MSG. ");  break;
				case SKEIN_BLK_TYPE_OUT:  printf("OUT. ");  break;
				default:    printf("0x%02X.",n); break;
				}
			printf(" Flags=");
			printf((h->T[1] & SKEIN_T1_FLAG_FIRST)   ? " First":"      ");
			printf((h->T[1] & SKEIN_T1_FLAG_FINAL)   ? " Final":"      ");
			printf((h->T[1] & SKEIN_T1_FLAG_BIT_PAD) ? " Pad"  :"    ");
			n = (uint_t) ((h->T[1] & SKEIN_T1_TREE_LVL_MASK) >> SKEIN_T1_POS_TREE_LVL);
			if (n)
				printf("  TreeLevel = %02X",n);
			printf("\n");
			}
        if (skein_DebugFlag & SKEIN_DEBUG_TWEAK)
			{
			printf("  Tweak:\n");
			Show64(2,h->T);
			}
        if (skein_DebugFlag & SKEIN_DEBUG_STATE)
            {
            printf("  %s words:\n",(skein_DebugFlag & SKEIN_DEBUG_THREEFISH)?"Key":"State");
            Show64(bits/64,X);
            }
        if (skein_DebugFlag & SKEIN_DEBUG_KEYSCHED)
            {
            printf("  Tweak schedule:\n");
            Show64(3,tsPtr);
            printf("  Key   schedule:\n");
            Show64((bits/64)+1,ksPtr);
            }
        if (skein_DebugFlag & SKEIN_DEBUG_INPUT_64)
            {
            printf("  Input block (words):\n");
            Show64(bits/64,wPtr);
            }
        if (skein_DebugFlag & SKEIN_DEBUG_INPUT_08)
            {
            printf("  Input block (bytes):\n");
            Show08(bits/8,blkPtr);
            }
        }
    }

void Skein_Show_Key(uint_t bits,const Skein_Ctxt_Hdr_t *h,const u08b_t *key,size_t keyBytes)
    {
	if (keyBytes)
    if (skein_DebugFlag & SKEIN_DEBUG_CONFIG || ((h->T[1] & SKEIN_T1_BLK_TYPE_MASK) != SKEIN_T1_BLK_TYPE_CFG))
    if (skein_DebugFlag & SKEIN_DEBUG_KEY)
        {
        printf("\n%s MAC key = %4u bytes\n",AlgoHeader(bits),keyBytes);
        Show08(keyBytes,key);
        }
    }
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/skein_debug.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#ifndef _SKEIN_DEBUG_H_
#define _SKEIN_DEBUG_H_
/***********************************************************************
**
** Interface definitions for Skein hashing debug output.
**
** Source code author: Doug Whiting, 2008.
**
** This algorithm and source code is released to the public domain.
**
************************************************************************/

#ifdef  SKEIN_DEBUG
/* callout functions used inside Skein code */
void    Skein_Show_Block(uint_t bits,const Skein_Ctxt_Hdr_t *h,const u64b_t *X,const u08b_t *blkPtr,
                         const u64b_t *wPtr,const u64b_t *ksPtr,const u64b_t *tsPtr);
void    Skein_Show_Round(uint_t bits,const Skein_Ctxt_Hdr_t *h,size_t r,const u64b_t *X);
void    Skein_Show_R_Ptr(uint_t bits,const Skein_Ctxt_Hdr_t *h,size_t r,const u64b_t *X_ptr[]);
void    Skein_Show_Final(uint_t bits,const Skein_Ctxt_Hdr_t *h,size_t cnt,const u08b_t *outPtr);
void    Skein_Show_Key  (uint_t bits,const Skein_Ctxt_Hdr_t *h,const u08b_t *key,size_t keyBytes);

extern  uint_t skein_DebugFlag;            /* flags to control debug output (0 --> none) */

#define SKEIN_RND_SPECIAL       (1000u)
#define SKEIN_RND_KEY_INITIAL   (SKEIN_RND_SPECIAL+0u)
#define SKEIN_RND_KEY_INJECT    (SKEIN_RND_SPECIAL+1u)
#define SKEIN_RND_FEED_FWD      (SKEIN_RND_SPECIAL+2u)

/* flag bits:  skein_DebugFlag */
#define SKEIN_DEBUG_KEY         (1u << 1)  /* show MAC key */
#define SKEIN_DEBUG_CONFIG      (1u << 2)  /* show config block processing */
#define SKEIN_DEBUG_STATE       (1u << 3)  /* show input state during Show_Block() */
#define SKEIN_DEBUG_TWEAK       (1u << 4)  /* show input state during Show_Block() */
#define SKEIN_DEBUG_KEYSCHED    (1u << 5)  /* show expanded key schedule */
#define SKEIN_DEBUG_INPUT_64    (1u << 6)  /* show input block as 64-bit words */
#define SKEIN_DEBUG_INPUT_08    (1u << 7)  /* show input block as  8-bit bytes */
#define SKEIN_DEBUG_INJECT      (1u << 8)  /* show state after key injection & feedforward points */
#define SKEIN_DEBUG_ROUNDS      (1u << 9)  /* show state after all rounds */
#define SKEIN_DEBUG_FINAL       (1u <<10)  /* show final output of Skein */
#define SKEIN_DEBUG_HDR         (1u <<11)  /* show block header */
#define SKEIN_DEBUG_THREEFISH   (1u <<12)  /* use Threefish name instead of Skein */
#define SKEIN_DEBUG_PERMUTE     (1u <<13)  /* use word permutations */
#define SKEIN_DEBUG_ALL         ((~0u) & ~(SKEIN_DEBUG_THREEFISH | SKEIN_DEBUG_PERMUTE))
#define THREEFISH_DEBUG_ALL     (SKEIN_DEBUG_ALL | SKEIN_DEBUG_THREEFISH)

#endif /*  SKEIN_DEBUG    */

#endif /* _SKEIN_DEBUG_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/skein_dropin.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
/*
 *  skein_dropin.c
 *
 *  Created by Jon Callas on 5/25/10.
 *  Copyright 2010 Apple, Inc. All rights reserved.
 *
 */

#include "skein.h"

#if SKEIN512_BUILD

int Skein_512_128_Init(Skein_512_Ctxt_t *ctx)
{
	return Skein_512_Init(ctx, 128);
}

int Skein_512_160_Init(Skein_512_Ctxt_t *ctx)
{
	return Skein_512_Init(ctx, 160);
}

int Skein_512_224_Init(Skein_512_Ctxt_t *ctx)
{
	return Skein_512_Init(ctx, 224);
}

int Skein_512_256_Init(Skein_512_Ctxt_t *ctx)
{
	return Skein_512_Init(ctx, 256);
}

int Skein_512_384_Init(Skein_512_Ctxt_t *ctx)
{
	return Skein_512_Init(ctx, 384);
}

int Skein_512_512_Init(Skein_512_Ctxt_t *ctx)
{
	return Skein_512_Init(ctx, 512);
}

///// One-shot returns

int Skein_512_128(const u08b_t *msg, size_t msgByteCnt, u08b_t *output)
{
	int result;
	Skein_512_Ctxt_t ctx;
	
	result = Skein_512_Init(&ctx, 128);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Update(&ctx, msg, msgByteCnt);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Final(&ctx, output);
	
	return result;
}

int Skein_512_160(const u08b_t *msg, size_t msgByteCnt, u08b_t *output)
{
	int result;
	Skein_512_Ctxt_t ctx;
	
	result = Skein_512_Init(&ctx, 160);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Update(&ctx, msg, msgByteCnt);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Final(&ctx, output);
	
	return result;
}

int Skein_512_224(const u08b_t *msg, size_t msgByteCnt, u08b_t *output)
{
	int result;
	Skein_512_Ctxt_t ctx;
	
	result = Skein_512_Init(&ctx, 224);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Update(&ctx, msg, msgByteCnt);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Final(&ctx, output);
	
	return result;
}

int Skein_512_256(const u08b_t *msg, size_t msgByteCnt, u08b_t *output)
{
	int result;
	Skein_512_Ctxt_t ctx;
	
	result = Skein_512_Init(&ctx, 256);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Update(&ctx, msg, msgByteCnt);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Final(&ctx, output);
	
	return result;
}

int Skein_512_384(const u08b_t *msg, size_t msgByteCnt, u08b_t *output)
{
	int result;
	Skein_512_Ctxt_t ctx;
	
	result = Skein_512_Init(&ctx, 384);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Update(&ctx, msg, msgByteCnt);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Final(&ctx, output);
	
	return result;
}

int Skein_512_512(const u08b_t *msg, size_t msgByteCnt, u08b_t *output)
{
	int result;
	Skein_512_Ctxt_t ctx;
	
	result = Skein_512_Init(&ctx, 512);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Update(&ctx, msg, msgByteCnt);
	
	if (result == SKEIN_SUCCESS)
		result = Skein_512_Final(&ctx, output);
	
	return result;
}

#endif /* SKEIN512_BUILD */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/skein_dropin.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
 *  skein_dropin.h
 *
 *  Created by Jon Callas on 5/25/10.
 *  Copyright 2010 Apple, Inc. All rights reserved.
 *
 */

#ifndef _SKEIN_DROPIN_H_
#define _SKEIN_DROPIN_H_     1

#ifdef __cplusplus
extern "C" {
#endif
	
extern int Skein_512_128_Init(Skein_512_Ctxt_t *ctx);
extern int Skein_512_160_Init(Skein_512_Ctxt_t *ctx);
extern int Skein_512_224_Init(Skein_512_Ctxt_t *ctx);
extern int Skein_512_256_Init(Skein_512_Ctxt_t *ctx);
extern int Skein_512_384_Init(Skein_512_Ctxt_t *ctx);
extern int Skein_512_512_Init(Skein_512_Ctxt_t *ctx);


extern int Skein_512_128(const u08b_t *msg, size_t msgByteCnt, u08b_t *output);
extern int Skein_512_160(const u08b_t *msg, size_t msgByteCnt, u08b_t *output);
extern int Skein_512_224(const u08b_t *msg, size_t msgByteCnt, u08b_t *output);
extern int Skein_512_256(const u08b_t *msg, size_t msgByteCnt, u08b_t *output);
extern int Skein_512_384(const u08b_t *msg, size_t msgByteCnt, u08b_t *output);
extern int Skein_512_512(const u08b_t *msg, size_t msgByteCnt, u08b_t *output);
	
#ifdef __cplusplus
}
#endif


#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/skein_iv.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#ifndef _SKEIN_IV_H_
#define _SKEIN_IV_H_

#include "skein.h"    /* get Skein macros and types */

/*
***************** Pre-computed Skein IVs *******************
**
** NOTE: these values are not "magic" constants, but
** are generated using the Threefish block function.
** They are pre-computed here only for speed; i.e., to
** avoid the need for a Threefish call during Init().
**
** The IV for any fixed hash length may be pre-computed.
** Only the most common values are included here.
**
************************************************************
**/

#define MK_64 SKEIN_MK_64

/* blkSize =  256 bits. hashSize =  128 bits */
const u64b_t SKEIN_256_IV_128[] =
    {
    MK_64(0x46B39C3A,0xAA418D4F),
    MK_64(0x681229DD,0x06920827),
    MK_64(0xCBE067C9,0x78460238),
    MK_64(0xC388A1B7,0x4EC45EF3)
    };

/* blkSize =  256 bits. hashSize =  160 bits */
const u64b_t SKEIN_256_IV_160[] =
    {
    MK_64(0xD51846B9,0xDAE51FBB),
    MK_64(0x7D47BABD,0x6205526D),
    MK_64(0xA1A8703E,0x47B89F20),
    MK_64(0xB97D7234,0xC5927589)
    };

/* blkSize =  256 bits. hashSize =  224 bits */
const u64b_t SKEIN_256_IV_224[] =
    {
    MK_64(0xFE6720F4,0x5ED90A57),
    MK_64(0x352D51F3,0xB01B6FBC),
    MK_64(0xD764B04F,0x1785F14E),
    MK_64(0xE7F24611,0xDDD59B27)
    };

/* blkSize =  256 bits. hashSize =  256 bits */
const u64b_t SKEIN_256_IV_256[] =
    {
    MK_64(0x164290A9,0xD4EEEF1D),
    MK_64(0x8E7EAF44,0xB1B0CD15),
    MK_64(0xA8BA0822,0xF69D09AE),
    MK_64(0x0AF25C5E,0x364A6468)
    };

/* blkSize =  512 bits. hashSize =  128 bits */
const u64b_t SKEIN_512_IV_128[] =
    {
    MK_64(0x51AF0A1B,0x97A7DA9C),
    MK_64(0xEC77F8A5,0xF4C6004C),
    MK_64(0x0BB7182C,0x25CA1F6E),
    MK_64(0x1B22A2CB,0x9F9339C5),
    MK_64(0xC905E0A4,0x31216AA4),
    MK_64(0xAEE4D5D0,0xBD378696),
    MK_64(0x92744A50,0x1953D08A),
    MK_64(0x2DCAD6F9,0x85777E17)
    };

/* blkSize =  512 bits. hashSize =  160 bits */
const u64b_t SKEIN_512_IV_160[] =
    {
    MK_64(0x9A73479A,0xC7701247),
    MK_64(0xD657FBF8,0xFDE0DA1A),
    MK_64(0xB1EE72A6,0xB04DA375),
    MK_64(0xE87ED2A1,0xC20605B8),
    MK_64(0x220A0EFA,0x9B925E17),
    MK_64(0x6D72A217,0xEAF0B419),
    MK_64(0x6CD72290,0xAA33FA72),
    MK_64(0x5829089E,0x759C4256)
    };

/* blkSize =  512 bits. hashSize =  224 bits */
const u64b_t SKEIN_512_IV_224[] =
    {
    MK_64(0x10C55045,0x6BF94560),
    MK_64(0x59004AF1,0xF558ACCC),
    MK_64(0x82BD1BF9,0xB7461DFD),
    MK_64(0x46B0F3A4,0x7C2AF60E),
    MK_64(0xECC8498C,0xE80A8DCA),
    MK_64(0x50A1DA33,0x10C836EF),
    MK_64(0x3538F92A,0x39165A80),
    MK_64(0x896A4329,0xCD5DCF2A)
    };

/* blkSize =  512 bits. hashSize =  256 bits */
const u64b_t SKEIN_512_IV_256[] =
    {
    MK_64(0x85A195B1,0x8B2264EC),
    MK_64(0x7A6DAC64,0xC047C2B0),
    MK_64(0xE1A21465,0xEE3FE124),
    MK_64(0x1D211735,0x6504425A),
    MK_64(0xC962DC0F,0xC0046F2C),
    MK_64(0x8D5A3E90,0x4B1BE9C8),
    MK_64(0xAFB7174B,0xBD8FEEE9),
    MK_64(0x7FE63D9B,0xF94EDEB8)
    };

/* blkSize =  512 bits. hashSize =  384 bits */
const u64b_t SKEIN_512_IV_384[] =
    {
    MK_64(0x755C4957,0x16D7512B),
    MK_64(0xB4587127,0x14DF4CEF),
    MK_64(0x677D2E8C,0x027C060A),
    MK_64(0x8DA4F592,0x05232716),
    MK_64(0xCE454B58,0xC445AD7F),
    MK_64(0x23048344,0xACA8BC96),
    MK_64(0xF719BCC3,0x38768323),
    MK_64(0xD77E3686,0x50579DEC)
    };

/* blkSize =  512 bits. hashSize =  512 bits */
const u64b_t SKEIN_512_IV_512[] =
    {
    MK_64(0x1A9A721C,0x8A265CA5),
    MK_64(0xC9ABACF5,0xAA853978),
    MK_64(0x4AF6652A,0xB80A2883),
    MK_64(0x66F5E8A8,0x09A773C7),
    MK_64(0x7FA984B7,0x81BAAF5B),
    MK_64(0x0FE5D2D9,0x3233F397),
    MK_64(0x6E29F932,0xDCB412D7),
    MK_64(0xD40CD947,0x2F225C23)
    };

/* blkSize = 1024 bits. hashSize =  384 bits */
const u64b_t SKEIN1024_IV_384[] =
    {
    MK_64(0x9E887D47,0x2693F556),
    MK_64(0xF4553A5A,0xB3A902D8),
    MK_64(0x60A10790,0x28E4504E),
    MK_64(0x96FAA39D,0x943F8ABE),
    MK_64(0x2A769D27,0x828A22A7),
    MK_64(0xB2F274F5,0xB2C3A833),
    MK_64(0xC722C052,0x47F09222),
    MK_64(0x377C4A92,0xEE78B216),
    MK_64(0x97CFE7B2,0x039F4C9D),
    MK_64(0xC864ACFA,0xC83C8364),
    MK_64(0x73F26579,0x1D3CF723),
    MK_64(0x2464DC1E,0x5E327F97),
    MK_64(0x135D3954,0xF181CB1A),
    MK_64(0x244BBF13,0x24C5C669),
    MK_64(0xE1E258BC,0x446662E3),
    MK_64(0xCF1E0F47,0x934A469C)
    };

/* blkSize = 1024 bits. hashSize =  512 bits */
const u64b_t SKEIN1024_IV_512[] =
    {
    MK_64(0x76066F1F,0x612DD519),
    MK_64(0xD9B93D95,0x75D90191),
    MK_64(0x582D15EA,0x89696586),
    MK_64(0x4F1CA328,0xB5F10FB3),
    MK_64(0x686C454D,0xEC64B419),
    MK_64(0x2D7BD9B4,0x026EDABE),
    MK_64(0xEF346195,0x1ACD05C4),
    MK_64(0x1759E898,0x4446E275),
    MK_64(0xACFC075A,0xE724456D),
    MK_64(0x82F35D0A,0xE7704311),
    MK_64(0x99D0B103,0x9AD7E344),
    MK_64(0x85D6C81D,0x29F6204B),
    MK_64(0x0CA2A987,0x5D57632A),
    MK_64(0x069A8931,0x47A448FA),
    MK_64(0x3C42FB50,0x02815320),
    MK_64(0xF7E22C15,0x953E3125)
    };

/* blkSize = 1024 bits. hashSize = 1024 bits */
const u64b_t SKEIN1024_IV_1024[] =
    {
    MK_64(0x495E85B9,0x53876965),
    MK_64(0x1E3D5C1B,0x41E754EF),
    MK_64(0x23725455,0x2E9C10C7),
    MK_64(0x0B00AAB4,0xFA441407),
    MK_64(0x17DDA56A,0xA106337C),
    MK_64(0xF98200E9,0xCAE13F94),
    MK_64(0xF2DF7F00,0xADFF12BF),
    MK_64(0xA92673D0,0xD0CA7AD9),
    MK_64(0xC0DD64B0,0x4B27ED98),
    MK_64(0x87C36A6C,0xA0A26F90),
    MK_64(0x640C8526,0xD0850A10),
    MK_64(0x6EBFAD0C,0x93DA09AE),
    MK_64(0x617E3BCD,0xDEE4A85F),
    MK_64(0x05A4A1A7,0xD82737B7),
    MK_64(0x002BAF2C,0x3EB13D30),
    MK_64(0x28527A78,0xC83D554C)
    };

#endif /* _SKEIN_IV_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein/Optimized_64bit/skein_port.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#ifndef _SKEIN_PORT_H_
#define _SKEIN_PORT_H_
/*******************************************************************
**
** Platform-specific definitions for Skein hash function.
**
** Source code author: Doug Whiting, 2008.
**
** This algorithm and source code is released to the public domain.
**
** Many thanks to Brian Gladman for his portable header files.
**
** To port Skein to an "unsupported" platform, change the definitions
** in this file appropriately.
** 
********************************************************************/

#include "brg_types.h"                      /* get integer type definitions */

typedef unsigned int    uint_t;             /* native unsigned integer */
typedef uint_8t         u08b_t;             /*  8-bit unsigned integer */
typedef uint_64t        u64b_t;             /* 64-bit unsigned integer */

#ifndef RotL_64
#define RotL_64(x,N)    (((x) << (N)) | ((x) >> (64-(N))))
#endif

/*
 * Skein is "natively" little-endian (unlike SHA-xxx), for optimal
 * performance on x86 CPUs.  The Skein code requires the following
 * definitions for dealing with endianness:
 *
 *    SKEIN_NEED_SWAP:  0 for little-endian, 1 for big-endian
 *    Skein_Put64_LSB_First
 *    Skein_Get64_LSB_First
 *    Skein_Swap64
 *
 * If SKEIN_NEED_SWAP is defined at compile time, it is used here
 * along with the portable versions of Put64/Get64/Swap64, which 
 * are slow in general.
 *
 * Otherwise, an "auto-detect" of endianness is attempted below.
 * If the default handling doesn't work well, the user may insert
 * platform-specific code instead (e.g., for big-endian CPUs).
 *
 */
#ifndef SKEIN_NEED_SWAP /* compile-time "override" for endianness? */

#include "brg_endian.h"                     /* get endianness selection */
#if   PLATFORM_BYTE_ORDER == IS_BIG_ENDIAN
    /* here for big-endian CPUs */
#define SKEIN_NEED_SWAP   (1)
#elif PLATFORM_BYTE_ORDER == IS_LITTLE_ENDIAN
    /* here for x86 and x86-64 CPUs (and other detected little-endian CPUs) */
#define SKEIN_NEED_SWAP   (0)
#if   PLATFORM_MUST_ALIGN == 0              /* ok to use "fast" versions? */
#define Skein_Put64_LSB_First(dst08,src64,bCnt) memcpy(dst08,src64,bCnt)
#define Skein_Get64_LSB_First(dst64,src08,wCnt) memcpy(dst64,src08,8*(wCnt))
#endif
#else
#error "Skein needs endianness setting!"
#endif

#endif /* ifndef SKEIN_NEED_SWAP */

/*
 ******************************************************************
 *      Provide any definitions still needed.
 ******************************************************************
 */
#ifndef Skein_Swap64  /* swap for big-endian, nop for little-endian */
#if     SKEIN_NEED_SWAP
#define Skein_Swap64(w64)                       \
  ( (( ((u64b_t)(w64))       & 0xFF) << 56) |   \
    (((((u64b_t)(w64)) >> 8) & 0xFF) << 48) |   \
    (((((u64b_t)(w64)) >>16) & 0xFF) << 40) |   \
    (((((u64b_t)(w64)) >>24) & 0xFF) << 32) |   \
    (((((u64b_t)(w64)) >>32) & 0xFF) << 24) |   \
    (((((u64b_t)(w64)) >>40) & 0xFF) << 16) |   \
    (((((u64b_t)(w64)) >>48) & 0xFF) <<  8) |   \
    (((((u64b_t)(w64)) >>56) & 0xFF)      ) )
#else
#define Skein_Swap64(w64)  (w64)
#endif
#endif  /* ifndef Skein_Swap64 */


#ifndef Skein_Put64_LSB_First
void    Skein_Put64_LSB_First(u08b_t *dst,const u64b_t *src,size_t bCnt)
#ifdef  SKEIN_PORT_CODE /* instantiate the function code here? */
    { /* this version is fully portable (big-endian or little-endian), but slow */
    size_t n;

    for (n=0;n<bCnt;n++)
        dst[n] = (u08b_t) (src[n>>3] >> (8*(n&7)));
    }
#else
    ;    /* output only the function prototype */
#endif
#endif   /* ifndef Skein_Put64_LSB_First */


#ifndef Skein_Get64_LSB_First
void    Skein_Get64_LSB_First(u64b_t *dst,const u08b_t *src,size_t wCnt)
#ifdef  SKEIN_PORT_CODE /* instantiate the function code here? */
    { /* this version is fully portable (big-endian or little-endian), but slow */
    size_t n;

    for (n=0;n<8*wCnt;n+=8)
        dst[n/8] = (((u64b_t) src[n  ])      ) +
                   (((u64b_t) src[n+1]) <<  8) +
                   (((u64b_t) src[n+2]) << 16) +
                   (((u64b_t) src[n+3]) << 24) +
                   (((u64b_t) src[n+4]) << 32) +
                   (((u64b_t) src[n+5]) << 40) +
                   (((u64b_t) src[n+6]) << 48) +
                   (((u64b_t) src[n+7]) << 56) ;
    }
#else
    ;    /* output only the function prototype */
#endif
#endif   /* ifndef Skein_Get64_LSB_First */

#endif   /* ifndef _SKEIN_PORT_H_ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein_ltc.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
/*
 *  skein_ltc.c
 *  Skein-Test
 *
 *  Created by Jon Callas on 5/25/10.
 *  Copyright 2010 Apple, Inc. All rights reserved.
 *
 */

#include "tomcrypt.h"

#include "skein.h"

#ifdef LTC_SKEIN
#include "skein_ltc.h"

int skein_test(void);

const struct ltc_hash_descriptor skein512_128_desc =
{
    "skein512-128",				/** name of hash **/
    SKEIN512_128_LTC_TAG,			/** internal ID **/
    128/8,						/** Size of digest in octets **/
    64,							/** Input block size in octets */
	
    /* OID */
	{ 1, 2, 840, 113635, 100, 2, 8,  
		128},
	/** Length of DER encoding */
	sizeof("\x06\x0B\x2A\x86\x48\x86\xF7\x63\x64\x02\x08\x81\x00")-1,
	
    &Skein_512_128_Init,
    &Skein_512_Update,
    &Skein_512_Final,
    &skein_test,
    NULL
};

const struct ltc_hash_descriptor skein512_160_desc =
{
    "skein512-160",				/** name of hash **/
    SKEIN512_160_LTC_TAG,			/** internal ID **/
    160/8,						/** Size of digest in octets **/
    64,							/** Input block size in octets */
	
    /* OID */
	{ 1, 2, 840, 113635, 100, 2, 8,  
		160},
	/** Length of DER encoding */
	sizeof("\x06\x0B\x2A\x86\x48\x86\xF7\x63\x64\x02\x08\x81\x20")-1,
	
    &Skein_512_160_Init,
    &Skein_512_Update,
    &Skein_512_Final,
    &skein_test,
    NULL
};

const struct ltc_hash_descriptor skein512_224_desc =
{
    "skein512-224",				/** name of hash **/
    SKEIN512_224_LTC_TAG,			/** internal ID **/
    224/8,						/** Size of digest in octets **/
    64,							/** Input block size in octets */
	
    /* OID */
	{ 1, 2, 840, 113635, 100, 2, 8,  
		224},
	/** Length of DER encoding */
	sizeof("\x06\x0B\x2A\x86\x48\x86\xF7\x63\x64\x02\x08\x81\x60")-1,
	
    &Skein_512_224_Init,
    &Skein_512_Update,
    &Skein_512_Final,
    &skein_test,
    NULL
};

const struct ltc_hash_descriptor skein512_256_desc =
{
    "skein512-256",				/** name of hash **/
    SKEIN512_256_LTC_TAG,			/** internal ID **/
    256/8,						/** Size of digest in octets **/
    64,							/** Input block size in octets */
	
    /* OID */
	{ 1, 2, 840, 113635, 100, 2, 8,  
		256},
	/** Length of DER encoding */
	sizeof("\x06\x0B\x2A\x86\x48\x86\xF7\x63\x64\x02\x08\x82\x00")-1,
	
    &Skein_512_256_Init,
    &Skein_512_Update,
    &Skein_512_Final,
    &skein_test,
    NULL
};

const struct ltc_hash_descriptor skein512_384_desc =
{
    "skein512-384",				/** name of hash **/
    SKEIN512_384_LTC_TAG,			/** internal ID **/
    384/8,						/** Size of digest in octets **/
    64,							/** Input block size in octets */
	
    /* OID */
	{ 1, 2, 840, 113635, 100, 2, 8,  
		384},
	/** Length of DER encoding */
	sizeof("\x06\x0B\x2A\x86\x48\x86\xF7\x63\x64\x02\x08\x83\x00")-1,
	
    &Skein_512_384_Init,
    &Skein_512_Update,
    &Skein_512_Final,
    &skein_test,
    NULL
};

const struct ltc_hash_descriptor skein512_512_desc =
{
    "skein512-512",				/** name of hash **/
    SKEIN512_512_LTC_TAG,			/** internal ID **/
    512/8,						/** Size of digest in octets **/
    64,							/** Input block size in octets */
	
    /* OID */
	{ 1, 2, 840, 113635, 100, 2, 8,  
		512},
	/** Length of DER encoding */
	sizeof("\x06\x0B\x2A\x86\x48\x86\xF7\x63\x64\x02\x08\x84\x00")-1,
	
    &Skein_512_512_Init,
    &Skein_512_Update,
    &Skein_512_Final,
    &skein_test,
    NULL
};

int skein_test(void)
{
#ifndef LTC_TEST
    return CRYPT_NOP;
#else    
	static const struct {
		char *msg;
		unsigned char hash[20];
	} tests[] = {
		{ {0xFF, 0x00 },
		  { 0x42, 0xAA, 0x6B, 0xD9, 0xCA, 0x92, 0xE9, 0x0E, 0xA2, 0x8D, 0xF6, 0xF6, 0xF2, 0xD0, 0xD9, 0xB8, 
			  0x5A, 0x2D, 0x19, 0x07, 0xEE, 0x4D, 0xC1, 0xB1, 0x71, 0xAC, 0xE7, 0xEB, 0x11, 0x59, 0xBE, 0x3B, 
			  0xD1, 0xBC, 0x56, 0x58, 0x6D, 0x92, 0x49, 0x2B, 0x6E, 0xFF, 0x9B, 0xE0, 0x33, 0x06, 0x99, 0x4C, 
			  0x65, 0xA3, 0x32, 0xC4, 0xC2, 0x41, 0x60, 0xF4, 0x66, 0x55, 0x04, 0x0E, 0x55, 0x8E, 0x83, 0x29 }
		  },
		{ { 0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1, 0xF0,
			0xEF, 0xEE, 0xED, 0xEC, 0xEB, 0xEA, 0xE9, 0xE8, 0xE7, 0xE6, 0xE5, 0xE4, 0xE3, 0xE2, 0xE1, 0xE0,
			0xDF, 0xDE, 0xDD, 0xDC, 0xDB, 0xDA, 0xD9, 0xD8, 0xD7, 0xD6, 0xD5, 0xD4, 0xD3, 0xD2, 0xD1, 0xD0,
			0xCF, 0xCE, 0xCD, 0xCC, 0xCB, 0xCA, 0xC9, 0xC8, 0xC7, 0xC6, 0xC5, 0xC4, 0xC3, 0xC2, 0xC1, 0xC0,
			0x00 },
		  { 0x04, 0xF9, 0x6C, 0x6F, 0x61, 0xB3, 0xE2, 0x37, 0xA4, 0xFA, 0x77, 0x55, 0xEE, 0x4A, 0xCF, 0x34, 
			  0x49, 0x42, 0x22, 0x96, 0x89, 0x54, 0xF4, 0x95, 0xAD, 0x14, 0x7A, 0x1A, 0x71, 0x5F, 0x7A, 0x73, 
			  0xEB, 0xEC, 0xFA, 0x1E, 0xF2, 0x75, 0xBE, 0xD8, 0x7D, 0xC6, 0x0B, 0xD1, 0xA0, 0xBC, 0x60, 0x21, 
			  0x06, 0xFA, 0x98, 0xF8, 0xE7, 0x23, 0x7B, 0xD1, 0xAC, 0x09, 0x58, 0xE7, 0x6D, 0x30, 0x66, 0x78 }
		}
	};
	
	int i;
	unsigned char tmp[64];
	Skein_512_Ctxt_t md;
	
	for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0]));  i++) {
		Skein_512_Init(&md, 512);
		Skein_512_Update(&md, (unsigned char*)tests[i].msg, (unsigned long)strlen(tests[i].msg));
		Skein_512_Final(&md, tmp);
		if (XMEMCMP(tmp, tests[i].hash, 20) != 0) {
			return CRYPT_FAIL_TESTVECTOR;
		}
	}
	return CRYPT_OK;
#endif
}


#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































Deleted Source/libtomcrypt/src/hashes/skein_ltc.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
 *  skein_ltc.h
 *  Skein-Test
 *
 *  Created by Jon Callas on 5/25/10.
 *  Copyright 2010 Apple, Inc. All rights reserved.
 *
 */

#include "tomcrypt.h"

#ifndef _SKEIN_LTC_H_
#define _SKEIN_LTC_H_	1
#ifdef LTC_SKEIN

enum {
	SKEIN512_128_LTC_TAG = 30,
	SKEIN512_160_LTC_TAG = 31,
	SKEIN512_224_LTC_TAG = 32,
	SKEIN512_256_LTC_TAG = 33,
	SKEIN512_384_LTC_TAG = 34,
	SKEIN512_512_LTC_TAG = 35
};

const struct ltc_hash_descriptor skein512_128_desc;
const struct ltc_hash_descriptor skein512_160_desc;
const struct ltc_hash_descriptor skein512_224_desc;
const struct ltc_hash_descriptor skein512_256_desc;
const struct ltc_hash_descriptor skein512_384_desc;
const struct ltc_hash_descriptor skein512_512_desc;
#endif
#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































Deleted Source/libtomcrypt/src/headers/tomcrypt.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#ifndef TOMCRYPT_H_
#define TOMCRYPT_H_
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <limits.h>

/* use configuration data */
#include "tomcrypt_custom.h"

#ifdef __cplusplus
extern "C" {
#endif

/* version */
#define CRYPT   0x0117
#define SCRYPT  "1.17"

/* max size of either a cipher/hash block or symmetric key [largest of the two] */
#define MAXBLOCKSIZE  128

/* descriptor table size */
#define TAB_SIZE      32

/* error codes [will be expanded in future releases] */
enum {
   CRYPT_OK=0,             /* Result OK */
   CRYPT_ERROR,            /* Generic Error */
   CRYPT_NOP,              /* Not a failure but no operation was performed */

   CRYPT_INVALID_KEYSIZE,  /* Invalid key size given */
   CRYPT_INVALID_ROUNDS,   /* Invalid number of rounds */
   CRYPT_FAIL_TESTVECTOR,  /* Algorithm failed test vectors */

   CRYPT_BUFFER_OVERFLOW,  /* Not enough space for output */
   CRYPT_INVALID_PACKET,   /* Invalid input packet given */

   CRYPT_INVALID_PRNGSIZE, /* Invalid number of bits for a PRNG */
   CRYPT_ERROR_READPRNG,   /* Could not read enough from PRNG */

   CRYPT_INVALID_CIPHER,   /* Invalid cipher specified */
   CRYPT_INVALID_HASH,     /* Invalid hash specified */
   CRYPT_INVALID_PRNG,     /* Invalid PRNG specified */

   CRYPT_MEM,              /* Out of memory */

   CRYPT_PK_TYPE_MISMATCH, /* Not equivalent types of PK keys */
   CRYPT_PK_NOT_PRIVATE,   /* Requires a private PK key */

   CRYPT_INVALID_ARG,      /* Generic invalid argument */
   CRYPT_FILE_NOTFOUND,    /* File Not Found */

   CRYPT_PK_INVALID_TYPE,  /* Invalid type of PK key */
   CRYPT_PK_INVALID_SYSTEM,/* Invalid PK system specified */
   CRYPT_PK_DUP,           /* Duplicate key already in key ring */
   CRYPT_PK_NOT_FOUND,     /* Key not found in keyring */
   CRYPT_PK_INVALID_SIZE,  /* Invalid size input for PK parameters */

   CRYPT_INVALID_PRIME_SIZE,/* Invalid size of prime requested */
   CRYPT_PK_INVALID_PADDING, /* Invalid padding on input */

   CRYPT_HASH_OVERFLOW      /* Hash applied to too many bits */
#ifdef MACTOMCRYPT
	 , CRYPT_UNIMPLEMENTED     /* called an unimplemented routine through a function table */
#endif
};

#include "tomcrypt_cfg.h"
#include "tomcrypt_macros.h"
#include "tomcrypt_cipher.h"
#include "tomcrypt_hash.h"
#include "tomcrypt_mac.h"
#include "tomcrypt_prng.h"
#include "tomcrypt_pk.h"
#include "tomcrypt_math.h"
#include "tomcrypt_misc.h"
#include "tomcrypt_argchk.h"
#include "tomcrypt_pkcs.h"
#include "tomcrypt_mode.h"

#ifdef __cplusplus
   }
#endif

#endif /* TOMCRYPT_H_ */


/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt.h,v $ */
/* $Revision: 1.21 $ */
/* $Date: 2006/12/16 19:34:05 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_argchk.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* Defines the LTC_ARGCHK macro used within the library */
/* ARGTYPE is defined in mycrypt_cfg.h */
#if ARGTYPE == 0

#include <signal.h>

/* this is the default LibTomCrypt macro  */
void crypt_argchk(char *v, char *s, int d);
#define LTC_ARGCHK(x) if (!(x)) { crypt_argchk(#x, __FILE__, __LINE__); }
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)

#elif ARGTYPE == 1

/* fatal type of error */
#define LTC_ARGCHK(x) assert((x))
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)

#elif ARGTYPE == 2

#define LTC_ARGCHK(x) if (!(x)) { fprintf(stderr, "\nwarning: ARGCHK failed at %s:%d\n", __FILE__, __LINE__); }
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)

#elif ARGTYPE == 3

#define LTC_ARGCHK(x) 
#define LTC_ARGCHKVD(x) LTC_ARGCHK(x)

#elif ARGTYPE == 4

#define LTC_ARGCHK(x)   if (!(x)) return CRYPT_INVALID_ARG;
#define LTC_ARGCHKVD(x) if (!(x)) return;

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_argchk.h,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2006/08/27 20:50:21 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































Deleted Source/libtomcrypt/src/headers/tomcrypt_cfg.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/* This is the build config file.
 *
 * With this you can setup what to inlcude/exclude automatically during any build.  Just comment
 * out the line that #define's the word for the thing you want to remove.  phew!
 */

#ifndef TOMCRYPT_CFG_H
#define TOMCRYPT_CFG_H

#if defined(_WIN32) || defined(_MSC_VER)
#define LTC_CALL __cdecl
#else
#ifndef LTC_CALL
   #define LTC_CALL
#endif
#endif

#ifndef LTC_EXPORT
#define LTC_EXPORT
#endif

/* certain platforms use macros for these, making the prototypes broken */
#ifndef LTC_NO_PROTOTYPES

/* you can change how memory allocation works ... */
LTC_EXPORT void * LTC_CALL XMALLOC(size_t n);
LTC_EXPORT void * LTC_CALL XREALLOC(void *p, size_t n);
LTC_EXPORT void * LTC_CALL XCALLOC(size_t n, size_t s);
LTC_EXPORT void LTC_CALL XFREE(void *p);

LTC_EXPORT void LTC_CALL XQSORT(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *));


/* change the clock function too */
LTC_EXPORT clock_t LTC_CALL XCLOCK(void);

/* various other functions */
LTC_EXPORT void * LTC_CALL XMEMCPY(void *dest, const void *src, size_t n);
LTC_EXPORT int   LTC_CALL XMEMCMP(const void *s1, const void *s2, size_t n);
LTC_EXPORT void * LTC_CALL XMEMSET(void *s, int c, size_t n);

LTC_EXPORT int   LTC_CALL XSTRCMP(const char *s1, const char *s2);

#endif

/* type of argument checking, 0=default, 1=fatal and 2=error+continue, 3=nothing */
#ifndef ARGTYPE
   #define ARGTYPE  0
#endif

/* Controls endianess and size of registers.  Leave uncommented to get platform neutral [slower] code 
 * 
 * Note: in order to use the optimized macros your platform must support unaligned 32 and 64 bit read/writes.
 * The x86 platforms allow this but some others [ARM for instance] do not.  On those platforms you **MUST**
 * use the portable [slower] macros.
 */

/* detect x86-32 machines somewhat */
#if !defined(__STRICT_ANSI__) && (defined(INTEL_CC) || (defined(_MSC_VER) && defined(WIN32)) || (defined(__GNUC__) && (defined(__DJGPP__) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__i386__))))
   #define ENDIAN_LITTLE
   #define ENDIAN_32BITWORD
   #define LTC_FAST
   #define LTC_FAST_TYPE    unsigned long
#endif

/* detects MIPS R5900 processors (PS2) */
#if (defined(__R5900) || defined(R5900) || defined(__R5900__)) && (defined(_mips) || defined(__mips__) || defined(mips))
   #define ENDIAN_LITTLE
   #define ENDIAN_64BITWORD
#endif

/* detect amd64 */
#if !defined(__STRICT_ANSI__) && defined(__x86_64__)
   #define ENDIAN_LITTLE
   #define ENDIAN_64BITWORD
   #define LTC_FAST
   #define LTC_FAST_TYPE    unsigned long
#endif

/* detect PPC32 */
#if !defined(__STRICT_ANSI__) && defined(LTC_PPC32)
   #define ENDIAN_BIG
   #define ENDIAN_32BITWORD
   #define LTC_FAST
   #define LTC_FAST_TYPE    unsigned long
#endif   

/* detect sparc and sparc64 */
#if defined(__sparc__)
  #define ENDIAN_BIG
  #if defined(__arch64__)
    #define ENDIAN_64BITWORD
  #else
    #define ENDIAN_32BITWORD
  #endif
#endif


#ifdef LTC_NO_FAST
   #ifdef LTC_FAST
      #undef LTC_FAST
   #endif
#endif

/* No asm is a quick way to disable anything "not portable" */

/* ZZZ murf added this define  - we should see what blocks using assembly at some point */
#define LTC_NO_ASM

#ifdef LTC_NO_ASM
   #undef ENDIAN_LITTLE
   #undef ENDIAN_BIG
   #undef ENDIAN_32BITWORD
   #undef ENDIAN_64BITWORD
   #undef LTC_FAST
   #undef LTC_FAST_TYPE
   #define LTC_NO_ROLC
	#define LTC_NO_BSWAP
#endif

/* #define ENDIAN_LITTLE */
/* #define ENDIAN_BIG */

/* #define ENDIAN_32BITWORD */
/* #define ENDIAN_64BITWORD */

#if (defined(ENDIAN_BIG) || defined(ENDIAN_LITTLE)) && !(defined(ENDIAN_32BITWORD) || defined(ENDIAN_64BITWORD))
    #error You must specify a word size as well as endianess in tomcrypt_cfg.h
#endif

#if !(defined(ENDIAN_BIG) || defined(ENDIAN_LITTLE))
   #define ENDIAN_NEUTRAL
#endif

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_cfg.h,v $ */
/* $Revision: 1.19 $ */
/* $Date: 2006/12/04 02:19:48 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_cipher.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
/* ---- SYMMETRIC KEY STUFF -----
 *
 * We put each of the ciphers scheduled keys in their own structs then we put all of 
 * the key formats in one union.  This makes the function prototypes easier to use.
 */
#ifdef LTC_BLOWFISH
struct blowfish_key {
   ulong32 S[4][256];
   ulong32 K[18];
};
#endif

#ifdef LTC_RC5
struct rc5_key {
   int rounds;
   ulong32 K[50];
};
#endif

#ifdef LTC_RC6
struct rc6_key {
   ulong32 K[44];
};
#endif

#ifdef LTC_SAFERP
struct saferp_key {
   unsigned char K[33][16];
   long rounds;
};
#endif

#ifdef LTC_RIJNDAEL
struct rijndael_key {
   ulong32 eK[60], dK[60];
   int Nr;
};
#endif

#ifdef EDP_AES
#include "aesedp.h"
#endif

#ifdef LTC_KSEED
struct kseed_key {
    ulong32 K[32], dK[32];
};
#endif

#ifdef LTC_KASUMI
struct kasumi_key {
    ulong32 KLi1[8], KLi2[8],
            KOi1[8], KOi2[8], KOi3[8],
            KIi1[8], KIi2[8], KIi3[8];
};
#endif

#ifdef LTC_XTEA
struct xtea_key {
   unsigned long A[32], B[32];
};
#endif

#ifdef LTC_TWOFISH
#ifndef LTC_TWOFISH_SMALL
   struct twofish_key {
      ulong32 S[4][256], K[40];
   };
#else
   struct twofish_key {
      ulong32 K[40];
      unsigned char S[32], start;
   };
#endif
#endif

#ifdef LTC_SAFER
#define LTC_SAFER_K64_DEFAULT_NOF_ROUNDS     6
#define LTC_SAFER_K128_DEFAULT_NOF_ROUNDS   10
#define LTC_SAFER_SK64_DEFAULT_NOF_ROUNDS    8
#define LTC_SAFER_SK128_DEFAULT_NOF_ROUNDS  10
#define LTC_SAFER_MAX_NOF_ROUNDS            13
#define LTC_SAFER_BLOCK_LEN                  8
#define LTC_SAFER_KEY_LEN     (1 + LTC_SAFER_BLOCK_LEN * (1 + 2 * LTC_SAFER_MAX_NOF_ROUNDS))
typedef unsigned char safer_block_t[LTC_SAFER_BLOCK_LEN];
typedef unsigned char safer_key_t[LTC_SAFER_KEY_LEN];
struct safer_key { safer_key_t key; };
#endif

#ifdef LTC_RC2
struct rc2_key { unsigned xkey[64]; };
#endif

#ifdef LTC_DES
struct des_key {
    ulong32 ek[32], dk[32];
};

struct des3_key {
    ulong32 ek[3][32], dk[3][32];
};
#endif

#ifdef LTC_CAST5
struct cast5_key {
    ulong32 K[32], keylen;
};
#endif

#ifdef LTC_NOEKEON
struct noekeon_key {
    ulong32 K[4], dK[4];
};
#endif

#ifdef LTC_SKIPJACK 
struct skipjack_key {
    unsigned char key[10];
};
#endif

#ifdef LTC_KHAZAD
struct khazad_key {
   ulong64 roundKeyEnc[8 + 1]; 
   ulong64 roundKeyDec[8 + 1]; 
};
#endif

#ifdef LTC_ANUBIS
struct anubis_key { 
   int keyBits; 
   int R; 
   ulong32 roundKeyEnc[18 + 1][4]; 
   ulong32 roundKeyDec[18 + 1][4]; 
}; 
#endif

#ifdef LTC_MULTI2
struct multi2_key {
    int N;
    ulong32 uk[8];
};
#endif

#ifdef LTC_CAMELLIA
struct camellia_key {
    int R;
    ulong64 kw[4], k[24], kl[6];
};
#endif

typedef union Symmetric_key {
#ifdef LTC_DES
   struct des_key des;
   struct des3_key des3;
#endif
#ifdef LTC_RC2
   struct rc2_key rc2;
#endif

#ifdef LTC_SAFER
   struct safer_key safer;
#endif
#ifdef LTC_TWOFISH
   struct twofish_key  twofish;
#endif
#ifdef LTC_BLOWFISH
   struct blowfish_key blowfish;
#endif

#ifdef LTC_RC5
   struct rc5_key      rc5;
#endif
#ifdef LTC_RC6
   struct rc6_key      rc6;
#endif

#ifdef LTC_SAFERP
   struct saferp_key   saferp;
#endif

#ifdef LTC_RIJNDAEL
   struct rijndael_key rijndael;
#endif

#ifdef LTC_XTEA
   struct xtea_key     xtea;
#endif

#ifdef LTC_CAST5
   struct cast5_key    cast5;
#endif

#ifdef LTC_NOEKEON
   struct noekeon_key  noekeon;
#endif   
#ifdef LTC_SKIPJACK
   struct skipjack_key skipjack;
#endif
#ifdef LTC_KHAZAD
   struct khazad_key   khazad;
#endif
#ifdef LTC_ANUBIS
   struct anubis_key   anubis;
#endif
#ifdef LTC_KSEED
   struct kseed_key    kseed;
#endif
#ifdef LTC_KASUMI
   struct kasumi_key   kasumi;
#endif  
#ifdef LTC_MULTI2
   struct multi2_key   multi2;
#endif
#ifdef LTC_CAMELLIA
   struct camellia_key camellia;
#endif

#ifdef EDP_AES
   aesedp_ctx   aesedp;
#endif
   void   *data;
} symmetric_key;

#ifdef LTC_ECB_MODE
/** A block cipher ECB structure */
typedef struct {
   /** The index of the cipher chosen */
   int                 cipher, 
   /** The block size of the given cipher */
                       blocklen;
   /** The scheduled key */                       
   symmetric_key       key;
} symmetric_ECB;
#endif

#ifdef LTC_CFB_MODE
/** A block cipher CFB structure */
typedef struct {
   /** The index of the cipher chosen */
   int                 cipher, 
   /** The block size of the given cipher */                        
                       blocklen, 
   /** The padding offset */
                       padlen;
   /** The current IV */
   unsigned char       IV[MAXBLOCKSIZE], 
   /** The pad used to encrypt/decrypt */ 
                       pad[MAXBLOCKSIZE];
   /** The scheduled key */
   symmetric_key       key;
} symmetric_CFB;
#endif

#ifdef LTC_OFB_MODE
/** A block cipher OFB structure */
typedef struct {
   /** The index of the cipher chosen */
   int                 cipher, 
   /** The block size of the given cipher */                        
                       blocklen, 
   /** The padding offset */
                       padlen;
   /** The current IV */
   unsigned char       IV[MAXBLOCKSIZE];
   /** The scheduled key */
   symmetric_key       key;
} symmetric_OFB;
#endif

#ifdef LTC_CBC_MODE
/** A block cipher CBC structure */
typedef struct {
   /** The index of the cipher chosen */
   int                 cipher, 
   /** The block size of the given cipher */                        
                       blocklen;
   /** The current IV */
   unsigned char       IV[MAXBLOCKSIZE];
   /** The scheduled key */
   symmetric_key       key;
} symmetric_CBC;
#endif


#ifdef LTC_CTR_MODE
/** A block cipher CTR structure */
typedef struct {
   /** The index of the cipher chosen */
   int                 cipher,
   /** The block size of the given cipher */                        
                       blocklen, 
   /** The padding offset */
                       padlen, 
   /** The mode (endianess) of the CTR, 0==little, 1==big */
                       mode,
   /** counter width */
                       ctrlen;

   /** The counter */                       
   unsigned char       ctr[MAXBLOCKSIZE], 
   /** The pad used to encrypt/decrypt */                       
                       pad[MAXBLOCKSIZE];
   /** The scheduled key */
   symmetric_key       key;
} symmetric_CTR;
#endif


#ifdef LTC_LRW_MODE
/** A LRW structure */
typedef struct {
    /** The index of the cipher chosen (must be a 128-bit block cipher) */
    int               cipher;

    /** The current IV */
    unsigned char     IV[16],
 
    /** the tweak key */
                      tweak[16],

    /** The current pad, it's the product of the first 15 bytes against the tweak key */
                      pad[16];

    /** The scheduled symmetric key */
    symmetric_key     key;

#ifdef LRW_TABLES
    /** The pre-computed multiplication table */
    unsigned char     PC[16][256][16];
#endif
} symmetric_LRW;
#endif

#ifdef LTC_F8_MODE
/** A block cipher F8 structure */
typedef struct {
   /** The index of the cipher chosen */
   int                 cipher, 
   /** The block size of the given cipher */                        
                       blocklen, 
   /** The padding offset */
                       padlen;
   /** The current IV */
   unsigned char       IV[MAXBLOCKSIZE],
                       MIV[MAXBLOCKSIZE];
   /** Current block count */
   ulong32             blockcnt;
   /** The scheduled key */
   symmetric_key       key;
} symmetric_F8;
#endif

#ifdef LTC_XTS_MODE
typedef struct {
    symmetric_key  key1, key2;
    ulong32            cipher;
} symmetric_xts;
#endif


/** cipher descriptor table, last entry has "name == NULL" to mark the end of table */
extern struct ltc_cipher_descriptor {
   /** name of cipher */
   char *name;
   /** internal ID */
   unsigned char ID;
   /** min keysize (octets) */
   int  min_key_length, 
   /** max keysize (octets) */
        max_key_length, 
   /** block size (octets) */
        block_length, 
   /** default number of rounds */
        default_rounds;
   /** Setup the cipher 
      @param key         The input symmetric key
      @param keylen      The length of the input key (octets)
      @param num_rounds  The requested number of rounds (0==default)
      @param skey        [out] The destination of the scheduled key
      @return CRYPT_OK if successful
   */
   int  (*setup)(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
   /** Encrypt a block
      @param pt      The plaintext
      @param ct      [out] The ciphertext
      @param skey    The scheduled key
      @return CRYPT_OK if successful
   */
   int (*ecb_encrypt)(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
   /** Decrypt a block
      @param ct      The ciphertext
      @param pt      [out] The plaintext
      @param skey    The scheduled key
      @return CRYPT_OK if successful
   */
   int (*ecb_decrypt)(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
   /** Test the block cipher
       @return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
   */
   int (*test)(void);

   /** Terminate the context 
      @param skey    The scheduled key
   */
   void (*done)(symmetric_key *skey);      

   /** Determine a key size
       @param keysize    [in/out] The size of the key desired and the suggested size
       @return CRYPT_OK if successful
   */
   int  (*keysize)(int *keysize);

/** Accelerators **/
   /** Accelerated ECB encryption 
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_ecb_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, symmetric_key *skey);

   /** Accelerated ECB decryption 
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_ecb_decrypt)(const unsigned char *ct, unsigned char *pt, unsigned long blocks, symmetric_key *skey);

   /** Accelerated CBC encryption 
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param IV      The initial value (input/output)
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_cbc_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *IV, symmetric_key *skey);

   /** Accelerated CBC decryption 
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param IV      The initial value (input/output)
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_cbc_decrypt)(const unsigned char *ct, unsigned char *pt, unsigned long blocks, unsigned char *IV, symmetric_key *skey);

   /** Accelerated CTR encryption 
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param IV      The initial value (input/output)
       @param mode    little or big endian counter (mode=0 or mode=1)
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_ctr_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *IV, int mode, symmetric_key *skey);

   /** Accelerated LRW 
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param IV      The initial value (input/output)
       @param tweak   The LRW tweak
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_lrw_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *IV, const unsigned char *tweak, symmetric_key *skey);

   /** Accelerated LRW 
       @param ct      Ciphertext
       @param pt      Plaintext
       @param blocks  The number of complete blocks to process
       @param IV      The initial value (input/output)
       @param tweak   The LRW tweak
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_lrw_decrypt)(const unsigned char *ct, unsigned char *pt, unsigned long blocks, unsigned char *IV, const unsigned char *tweak, symmetric_key *skey);

    // XTS Acceleration
    /** Accelerated XTS 
     @param pt      Plaintext
     @param len     The length of the logical block to process
     @param ct      Ciphertext
     @param tweak   [in] The 128--bit encryption tweak (e.g. sector number)
     @param xts     The XTS structure
     @return CRYPT_OK if successful
     */
    int (*accel_xts_encrypt)(const unsigned char *pt, unsigned long len, unsigned char *ct, const unsigned char *tweak, symmetric_xts *xts);
    
    /** Accelerated XTS 
     @param ct      Ciphertext
     @param len     The length of the logical block to process
     @param pt      Plaintext
     @param len     The length of the logical block to process
     @param tweak   [in] The 128--bit encryption tweak (e.g. sector number)
     @param xts     The XTS structure
     @return CRYPT_OK if successful
     */
    int (*accel_xts_decrypt)(const unsigned char *ct, unsigned long len, unsigned char *pt, const unsigned char *tweak, symmetric_xts *xts);
    
    // END XTS Acceleration
    
   /** Accelerated CCM packet (one-shot)
       @param key        The secret key to use
       @param keylen     The length of the secret key (octets)
       @param uskey      A previously scheduled key [optional can be NULL]
       @param nonce      The session nonce [use once]
       @param noncelen   The length of the nonce
       @param header     The header for the session
       @param headerlen  The length of the header (octets)
       @param pt         [out] The plaintext
       @param ptlen      The length of the plaintext (octets)
       @param ct         [out] The ciphertext
       @param tag        [out] The destination tag
       @param taglen     [in/out] The max size and resulting size of the authentication tag
       @param direction  Encrypt or Decrypt direction (0 or 1)
       @return CRYPT_OK if successful
   */
   int (*accel_ccm_memory)(
       const unsigned char *key,    unsigned long keylen,
       symmetric_key       *uskey,
       const unsigned char *nonce,  unsigned long noncelen,
       const unsigned char *header, unsigned long headerlen,
             unsigned char *pt,     unsigned long ptlen,
             unsigned char *ct,
             unsigned char *tag,    unsigned long *taglen,
                       int  direction);

   /** Accelerated GCM packet (one shot)
       @param key        The secret key
       @param keylen     The length of the secret key
       @param IV         The initial vector 
       @param IVlen      The length of the initial vector
       @param adata      The additional authentication data (header)
       @param adatalen   The length of the adata
       @param pt         The plaintext
       @param ptlen      The length of the plaintext (ciphertext length is the same)
       @param ct         The ciphertext
       @param tag        [out] The MAC tag
       @param taglen     [in/out] The MAC tag length
       @param direction  Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
       @return CRYPT_OK on success
   */
   int (*accel_gcm_memory)(
       const unsigned char *key,    unsigned long keylen,
       const unsigned char *IV,     unsigned long IVlen,
       const unsigned char *adata,  unsigned long adatalen,
             unsigned char *pt,     unsigned long ptlen,
             unsigned char *ct, 
             unsigned char *tag,    unsigned long *taglen,
                       int direction);

   /** Accelerated one shot LTC_OMAC 
       @param key            The secret key
       @param keylen         The key length (octets) 
       @param in             The message 
       @param inlen          Length of message (octets)
       @param out            [out] Destination for tag
       @param outlen         [in/out] Initial and final size of out
       @return CRYPT_OK on success
   */
   int (*omac_memory)(
       const unsigned char *key, unsigned long keylen,
       const unsigned char *in,  unsigned long inlen,
             unsigned char *out, unsigned long *outlen);

   /** Accelerated one shot XCBC 
       @param key            The secret key
       @param keylen         The key length (octets) 
       @param in             The message 
       @param inlen          Length of message (octets)
       @param out            [out] Destination for tag
       @param outlen         [in/out] Initial and final size of out
       @return CRYPT_OK on success
   */
   int (*xcbc_memory)(
       const unsigned char *key, unsigned long keylen,
       const unsigned char *in,  unsigned long inlen,
             unsigned char *out, unsigned long *outlen);

   /** Accelerated one shot F9 
       @param key            The secret key
       @param keylen         The key length (octets) 
       @param in             The message 
       @param inlen          Length of message (octets)
       @param out            [out] Destination for tag
       @param outlen         [in/out] Initial and final size of out
       @return CRYPT_OK on success
       @remark Requires manual padding
   */
   int (*f9_memory)(
       const unsigned char *key, unsigned long keylen,
       const unsigned char *in,  unsigned long inlen,
             unsigned char *out, unsigned long *outlen);
} cipher_descriptor[];

#ifdef LTC_BLOWFISH
int blowfish_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int blowfish_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int blowfish_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int blowfish_test(void);
void blowfish_done(symmetric_key *skey);
int blowfish_keysize(int *keysize);
extern const struct ltc_cipher_descriptor blowfish_desc;
#endif

#ifdef LTC_RC5
int rc5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rc5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rc5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rc5_test(void);
void rc5_done(symmetric_key *skey);
int rc5_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rc5_desc;
#endif

#ifdef LTC_RC6
int rc6_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rc6_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rc6_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rc6_test(void);
void rc6_done(symmetric_key *skey);
int rc6_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rc6_desc;
#endif

#ifdef LTC_RC2
int rc2_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rc2_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rc2_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rc2_test(void);
void rc2_done(symmetric_key *skey);
int rc2_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rc2_desc;
#endif

#ifdef LTC_SAFERP
int saferp_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int saferp_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int saferp_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int saferp_test(void);
void saferp_done(symmetric_key *skey);
int saferp_keysize(int *keysize);
extern const struct ltc_cipher_descriptor saferp_desc;
#endif

#ifdef LTC_SAFER
int safer_k64_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_sk64_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_k128_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_sk128_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int safer_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *key);
int safer_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *key);
int safer_k64_test(void);
int safer_sk64_test(void);
int safer_sk128_test(void);
void safer_done(symmetric_key *skey);
int safer_64_keysize(int *keysize);
int safer_128_keysize(int *keysize);
extern const struct ltc_cipher_descriptor safer_k64_desc, safer_k128_desc, safer_sk64_desc, safer_sk128_desc;
#endif

#ifdef LTC_RIJNDAEL

/* make aes an alias */
#define aes_setup           rijndael_setup
#define aes_ecb_encrypt     rijndael_ecb_encrypt
#define aes_ecb_decrypt     rijndael_ecb_decrypt
#define aes_test            rijndael_test
#define aes_done            rijndael_done
#define aes_keysize         rijndael_keysize

#define aes_enc_setup           rijndael_enc_setup
#define aes_enc_ecb_encrypt     rijndael_enc_ecb_encrypt
#define aes_enc_keysize         rijndael_enc_keysize

int rijndael_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rijndael_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int rijndael_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int rijndael_test(void);
void rijndael_done(symmetric_key *skey);
int rijndael_keysize(int *keysize);
int rijndael_enc_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int rijndael_enc_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
void rijndael_enc_done(symmetric_key *skey);
int rijndael_enc_keysize(int *keysize);
extern const struct ltc_cipher_descriptor rijndael_desc, aes_desc;
extern const struct ltc_cipher_descriptor rijndael_enc_desc, aes_enc_desc;
#endif

#ifdef EDP_AES
int aesedp_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int aesedp_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int aesedp_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int aesedp_test(void);
void aesedp_done(symmetric_key *skey);
int aesedp_cbc_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long blocks, unsigned char *iv, symmetric_key *skey);
int aesedp_cbc_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long blocks, unsigned char *iv, symmetric_key *skey);
int aesedp_keysize(int *keysize);
extern const struct ltc_cipher_descriptor aesedp_desc;
#endif

#ifdef LTC_XTEA
int xtea_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int xtea_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int xtea_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int xtea_test(void);
void xtea_done(symmetric_key *skey);
int xtea_keysize(int *keysize);
extern const struct ltc_cipher_descriptor xtea_desc;
#endif

#ifdef LTC_TWOFISH
int twofish_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int twofish_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int twofish_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int twofish_test(void);
void twofish_done(symmetric_key *skey);
int twofish_keysize(int *keysize);
extern const struct ltc_cipher_descriptor twofish_desc;
#endif

#ifdef LTC_DES
int des_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int des_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int des_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int des_test(void);
void des_done(symmetric_key *skey);
int des_keysize(int *keysize);
int des3_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int des3_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int des3_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int des3_test(void);
void des3_done(symmetric_key *skey);
int des3_keysize(int *keysize);
extern const struct ltc_cipher_descriptor des_desc, des3_desc;
#endif

#ifdef LTC_CAST5
int cast5_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int cast5_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int cast5_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int cast5_test(void);
void cast5_done(symmetric_key *skey);
int cast5_keysize(int *keysize);
extern const struct ltc_cipher_descriptor cast5_desc;
#endif

#ifdef LTC_NOEKEON
int noekeon_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int noekeon_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int noekeon_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int noekeon_test(void);
void noekeon_done(symmetric_key *skey);
int noekeon_keysize(int *keysize);
extern const struct ltc_cipher_descriptor noekeon_desc;
#endif

#ifdef LTC_SKIPJACK
int skipjack_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int skipjack_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int skipjack_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int skipjack_test(void);
void skipjack_done(symmetric_key *skey);
int skipjack_keysize(int *keysize);
extern const struct ltc_cipher_descriptor skipjack_desc;
#endif

#ifdef LTC_KHAZAD
int khazad_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int khazad_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int khazad_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int khazad_test(void);
void khazad_done(symmetric_key *skey);
int khazad_keysize(int *keysize);
extern const struct ltc_cipher_descriptor khazad_desc;
#endif

#ifdef LTC_ANUBIS
int anubis_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int anubis_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int anubis_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int anubis_test(void);
void anubis_done(symmetric_key *skey);
int anubis_keysize(int *keysize);
extern const struct ltc_cipher_descriptor anubis_desc;
#endif

#ifdef LTC_KSEED
int kseed_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int kseed_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int kseed_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int kseed_test(void);
void kseed_done(symmetric_key *skey);
int kseed_keysize(int *keysize);
extern const struct ltc_cipher_descriptor kseed_desc;
#endif

#ifdef LTC_KASUMI
int kasumi_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int kasumi_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int kasumi_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int kasumi_test(void);
void kasumi_done(symmetric_key *skey);
int kasumi_keysize(int *keysize);
extern const struct ltc_cipher_descriptor kasumi_desc;
#endif


#ifdef LTC_MULTI2
int multi2_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int multi2_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int multi2_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int multi2_test(void);
void multi2_done(symmetric_key *skey);
int multi2_keysize(int *keysize);
extern const struct ltc_cipher_descriptor multi2_desc;
#endif

#ifdef LTC_CAMELLIA
int camellia_setup(const unsigned char *key, int keylen, int num_rounds, symmetric_key *skey);
int camellia_ecb_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_key *skey);
int camellia_ecb_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_key *skey);
int camellia_test(void);
void camellia_done(symmetric_key *skey);
int camellia_keysize(int *keysize);
extern const struct ltc_cipher_descriptor camellia_desc;
#endif

#ifdef LTC_ECB_MODE
#ifdef MACTOMCRYPT
int ecb_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *tweak, int tweaklen,
	int num_rounds, int options, symmetric_ECB *ecb);
#else
int ecb_start(int cipher, const unsigned char *key, int keylen, int num_rounds, symmetric_ECB *ecb);
#endif
int ecb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_ECB *ecb);
int ecb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_ECB *ecb);
int ecb_done(symmetric_ECB *ecb);
#endif

#ifdef LTC_CFB_MODE
#ifdef MACTOMCRYPT
int cfb_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *tweak, int tweaklen,
	int num_rounds, int options, symmetric_CFB *cfb);
#else
int cfb_start(int cipher, const unsigned char *IV, const unsigned char *key, 
              int keylen, int num_rounds, symmetric_CFB *cfb);
#endif
int cfb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CFB *cfb);
int cfb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CFB *cfb);
int cfb_getiv(unsigned char *IV, unsigned long *len, symmetric_CFB *cfb);
int cfb_setiv(const unsigned char *IV, unsigned long len, symmetric_CFB *cfb);
int cfb_done(symmetric_CFB *cfb);
#endif

#ifdef LTC_OFB_MODE
#ifdef MACTOMCRYPT
int ofb_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
	const unsigned char *tweak, int tweaklen, int num_rounds, int options, symmetric_OFB *ofb);
#else
int ofb_start(int cipher, const unsigned char *IV, const unsigned char *key, 
              int keylen, int num_rounds, symmetric_OFB *ofb);
#endif
int ofb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_OFB *ofb);
int ofb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_OFB *ofb);
int ofb_getiv(unsigned char *IV, unsigned long *len, symmetric_OFB *ofb);
int ofb_setiv(const unsigned char *IV, unsigned long len, symmetric_OFB *ofb);
int ofb_done(symmetric_OFB *ofb);
#endif

#ifdef LTC_CBC_MODE
#ifdef MACTOMCRYPT
int cbc_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
	const unsigned char *tweak, int tweaklen, int num_rounds, int options, symmetric_CBC *cbc);
#else
int cbc_start(int cipher, const unsigned char *IV, const unsigned char *key, 
              int keylen, int num_rounds, symmetric_CBC *cbc);
#endif
int cbc_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CBC *cbc);
int cbc_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CBC *cbc);
int cbc_encrypt_tweaked(const unsigned char *pt, unsigned long len, unsigned char *ct, const unsigned char *tweak, symmetric_CBC *cbc);
int cbc_decrypt_tweaked(const unsigned char *ct, unsigned long len, unsigned char *pt, const unsigned char *tweak, symmetric_CBC *cbc);
int cbc_getiv(unsigned char *IV, unsigned long *len, symmetric_CBC *cbc);
int cbc_setiv(const unsigned char *IV, unsigned long len, symmetric_CBC *cbc);
int cbc_done(symmetric_CBC *cbc);
#endif

#ifdef LTC_CTR_MODE

#define CTR_COUNTER_LITTLE_ENDIAN    0x0000
#define CTR_COUNTER_BIG_ENDIAN       0x1000
#define LTC_CTR_RFC3686              0x2000

#ifdef MACTOMCRYPT
int ctr_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *tweak, int tweaklen,
	int num_rounds, int ctr_mode, symmetric_CTR *ctr);
#else
int ctr_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, int  num_rounds, int ctr_mode, symmetric_CTR *ctr);
#endif
int ctr_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CTR *ctr);
int ctr_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CTR *ctr);
int ctr_getiv(unsigned char *IV, unsigned long *len, symmetric_CTR *ctr);
int ctr_setiv(const unsigned char *IV, unsigned long len, symmetric_CTR *ctr);
int ctr_done(symmetric_CTR *ctr);
int ctr_test(void);
#endif

#ifdef LTC_LRW_MODE

#define LRW_ENCRYPT 0
#define LRW_DECRYPT 1

#ifdef MACTOMCRYPT
int lrw_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
	const unsigned char *tweak, int tweaklen, int num_rounds, int options, symmetric_LRW *lrw);
#else
int lrw_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *tweak, int num_rounds, symmetric_LRW *lrw);
#endif
int lrw_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_LRW *lrw);
int lrw_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_LRW *lrw);
int lrw_getiv(unsigned char *IV, unsigned long *len, symmetric_LRW *lrw);
int lrw_setiv(const unsigned char *IV, unsigned long len, symmetric_LRW *lrw);
int lrw_done(symmetric_LRW *lrw);
int lrw_test(void);

/* don't call */
int lrw_process(const unsigned char *pt, unsigned char *ct, unsigned long len, int mode, symmetric_LRW *lrw);
#endif    

#ifdef LTC_F8_MODE
#ifdef MACTOMCRYPT
int f8_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
	const unsigned char *salt_key, int skeylen, int num_rounds, int options, symmetric_F8 *f8);
#else
int f8_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *salt_key, int skeylen,
	int	num_rounds,	 symmetric_F8	 *f8);
#endif
int f8_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_F8 *f8);
int f8_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_F8 *f8);
int f8_getiv(unsigned char *IV, unsigned long *len, symmetric_F8 *f8);
int f8_setiv(const unsigned char *IV, unsigned long len, symmetric_F8 *f8);
int f8_done(symmetric_F8 *f8);
int f8_test_mode(void);
#endif

#ifdef LTC_XTS_MODE
#ifdef NEVER
typedef struct {
   symmetric_key  key1, key2;
   int            cipher;
} symmetric_xts;
#endif

#ifdef MACTOMCRYPT
int xts_start(int cipher, const unsigned char *IV, const unsigned char *key1, int keylen, 
	const unsigned char *key2, int tweaklen, int num_rounds, int options, symmetric_xts *xts);
#else
int xts_start(int cipher, const unsigned char *key1, const unsigned char *key2, unsigned long keylen, int num_rounds, symmetric_xts *xts);
#endif

int xts_encrypt(
   const unsigned char *pt, unsigned long ptlen,
         unsigned char *ct,
   const unsigned char *tweak,
         symmetric_xts *xts);
int xts_decrypt(
   const unsigned char *ct, unsigned long ptlen,
         unsigned char *pt,
   const unsigned char *tweak,
         symmetric_xts *xts);

void xts_done(symmetric_xts *xts);
int  xts_test(void);
void xts_mult_x(unsigned char *I);
#endif

#ifdef MACTOMCRYPT
int cfb8_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *tweak, int tweaklen,
			  int num_rounds, int options, symmetric_CFB *cfb);
#else
int cfb8_start(int cipher, const unsigned char *IV, const unsigned char *key, 
              int keylen, int num_rounds, symmetric_CFB *cfb);
#endif
int cfb8_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CFB *cfb);
int cfb8_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CFB *cfb);
int cfb8_getiv(unsigned char *IV, unsigned long *len, symmetric_CFB *cfb);
int cfb8_setiv(const unsigned char *IV, unsigned long len, symmetric_CFB *cfb);
int cfb8_done(symmetric_CFB *cfb);

int find_cipher(const char *name);
int find_cipher_any(const char *name, int blocklen, int keylen);
int find_cipher_id(unsigned char ID);
int register_cipher(const struct ltc_cipher_descriptor *cipher);
int unregister_cipher(const struct ltc_cipher_descriptor *cipher);
int cipher_is_valid(int idx);

LTC_MUTEX_PROTO(ltc_cipher_mutex)

/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_cipher.h,v $ */
/* $Revision: 1.55 $ */
/* $Date: 2007/06/20 13:14:31 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_custom.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#ifndef TOMCRYPT_CUSTOM_H_
#define TOMCRYPT_CUSTOM_H_

/* MacTomCrypt Operation Limits */

/* ZZZ murf We use our own Yarrow derived /dev/random */
#define LTC_NO_PRNGS
/* ZZZ murf defines some needed functions in tomcrypt_math.h */
#define LTC_SOURCE
/* ZZZ murf limit algorithms to more standard ones */
#define MACTOMCRYPT
#ifdef MACTOMCRYPT
#define MAC_TOMCRYPT_STD_ROUTINES
#define LTC_SKEIN
#define EDP_AES
#endif

/* macros for various libc functions you can change for embedded targets */
#ifndef XMALLOC
   #ifdef malloc 
   #define LTC_NO_PROTOTYPES
   #endif
#define XMALLOC  malloc
#endif
#ifndef XREALLOC
   #ifdef realloc 
   #define LTC_NO_PROTOTYPES
   #endif
#define XREALLOC realloc
#endif
#ifndef XCALLOC
   #ifdef calloc 
   #define LTC_NO_PROTOTYPES
   #endif
#define XCALLOC  calloc
#endif
#ifndef XFREE
   #ifdef free
   #define LTC_NO_PROTOTYPES
   #endif
#define XFREE    free
#endif

#ifndef XMEMSET
   #ifdef memset
   #define LTC_NO_PROTOTYPES
   #endif
#define XMEMSET  memset
#endif
#ifndef XMEMCPY
   #ifdef memcpy
   #define LTC_NO_PROTOTYPES
   #endif
#define XMEMCPY  memcpy
#endif
#ifndef XMEMCMP
   #ifdef memcmp 
   #define LTC_NO_PROTOTYPES
   #endif
#define XMEMCMP  memcmp
#endif
#ifndef XSTRCMP
   #ifdef strcmp
   #define LTC_NO_PROTOTYPES
   #endif
#define XSTRCMP strcmp
#endif

#ifndef XCLOCK
#define XCLOCK   clock
#endif
#ifndef XCLOCKS_PER_SEC
#define XCLOCKS_PER_SEC CLOCKS_PER_SEC
#endif

#ifndef XQSORT
   #ifdef qsort
   #define LTC_NO_PROTOTYPES
   #endif
#define XQSORT qsort
#endif

/* Easy button? */
#ifdef LTC_EASY
   #define LTC_NO_CIPHERS
   #define LTC_RIJNDAEL
   #define LTC_BLOWFISH
   #define LTC_DES
   #define LTC_CAST5
   
   #define LTC_NO_MODES
   #define LTC_ECB_MODE
   #define LTC_CBC_MODE
   #define LTC_CTR_MODE
   
   #define LTC_NO_HASHES
   #define LTC_SHA1
   #define LTC_SHA512
   #define LTC_SHA384
   #define LTC_SHA256
   #define LTC_SHA224
   
   #define LTC_NO_MACS
   #define LTC_HMAC
   #define LTC_OMAC
   #define LTC_CCM_MODE

   #define LTC_NO_PRNGS
   #define LTC_SPRNG
   #define LTC_YARROW
   #define LTC_DEVRANDOM
   #define TRY_URANDOM_FIRST
      
   #define LTC_NO_PK
   #define LTC_MRSA
   #define LTC_MECC
#endif   

/* Use small code where possible */
/* #define LTC_SMALL_CODE */

/* Enable self-test test vector checking */
#ifndef LTC_NO_TEST
   #define LTC_TEST
#endif

/* clean the stack of functions which put private information on stack */
/* #define LTC_CLEAN_STACK */

/* disable all file related functions */
/* #define LTC_NO_FILE */

/* disable all forms of ASM */
/* #define LTC_NO_ASM */

/* disable FAST mode */
/* #define LTC_NO_FAST */

/* disable BSWAP on x86 */
/* #define LTC_NO_BSWAP */

/* ---> Symmetric Block Ciphers <--- */
#ifndef LTC_NO_CIPHERS

#define LTC_RC2
#define LTC_RC5
#define LTC_RC6
#define LTC_RIJNDAEL
/* LTC_DES includes EDE triple-LTC_DES */
#define LTC_DES
#define LTC_CAST5

/* ZZZ murf - adding easy-off for "exotic" crypto */

#if !defined(MAC_TOMCRYPT_STD_ROUTINES)
// #define LTC_XTEA
/* _TABLES tells it to use tables during setup, _SMALL means to use the smaller scheduled key format
 * (saves 4KB of ram), _ALL_TABLES enables all tables during setup */
#define LTC_TWOFISH
#ifndef LTC_NO_TABLES
   #define LTC_TWOFISH_TABLES
   /* #define LTC_TWOFISH_ALL_TABLES */
#else
   #define LTC_TWOFISH_SMALL
#endif
/* #define LTC_TWOFISH_SMALL */
#define LTC_BLOWFISH
#define LTC_SAFERP
#define LTC_NOEKEON
#define LTC_SKIPJACK
#define LTC_SAFER
#define LTC_KHAZAD
#define LTC_ANUBIS
#define LTC_ANUBIS_TWEAK
#define LTC_KSEED
#define LTC_KASUMI
#define LTC_MULTI2
#define LTC_CAMELLIA
#endif /* MAC_TOMCRYPT_STD_ROUTINES */

#endif /* LTC_NO_CIPHERS */


/* ---> Block Cipher Modes of Operation <--- */
#ifndef LTC_NO_MODES

#define LTC_CFB_MODE
#define LTC_OFB_MODE
#define LTC_ECB_MODE
#define LTC_CBC_MODE
#define LTC_CTR_MODE

/* F8 chaining mode */
#define LTC_F8_MODE

/* LRW mode */
#define LTC_LRW_MODE
#ifndef LTC_NO_TABLES
   /* like GCM mode this will enable 16 8x128 tables [64KB] that make
    * seeking very fast.  
    */
#if !defined(MAC_TOMCRYPT_STD_ROUTINES)
   #define LRW_TABLES
#endif /* MAC_TOMCRYPT_STD_ROUTINES */
#endif

/* XTS mode */
#define LTC_XTS_MODE

#endif /* LTC_NO_MODES */

/* ---> One-Way Hash Functions <--- */
#ifndef LTC_NO_HASHES 

#if !defined(MAC_TOMCRYPT_STD_ROUTINES)
#define LTC_CHC_HASH
#define LTC_WHIRLPOOL
#endif /* MAC_TOMCRYPT_STD_ROUTINES */

#define LTC_SHA512
#define LTC_SHA384
#define LTC_SHA256
#define LTC_SHA224
#define LTC_TIGER
#define LTC_SHA1
#define LTC_MD5
#define LTC_MD4
#define LTC_MD2
#define LTC_RIPEMD128
#define LTC_RIPEMD160
#define LTC_RIPEMD256
#define LTC_RIPEMD320

#endif /* LTC_NO_HASHES */

/* ---> MAC functions <--- */
#ifndef LTC_NO_MACS

#define LTC_HMAC
#define LTC_OMAC
#define LTC_PMAC
#define LTC_XCBC

#if !defined(MAC_TOMCRYPT_STD_ROUTINES)
#define LTC_F9_MODE
#define LTC_PELICAN
#endif /* MAC_TOMCRYPT_STD_ROUTINES */


#if defined(LTC_PELICAN) && !defined(LTC_RIJNDAEL)
   #error Pelican-MAC requires LTC_RIJNDAEL
#endif

/* ---> Encrypt + Authenticate Modes <--- */

#define LTC_EAX_MODE
#if defined(LTC_EAX_MODE) && !(defined(LTC_CTR_MODE) && defined(LTC_OMAC))
   #error LTC_EAX_MODE requires CTR and LTC_OMAC mode
#endif

#define LTC_OCB_MODE
#define LTC_CCM_MODE
#define LTC_GCM_MODE

/* Use 64KiB tables */
#ifndef LTC_NO_TABLES
   #define LTC_GCM_TABLES 
#endif

/* USE SSE2? requires GCC works on x86_32 and x86_64*/
#ifdef LTC_GCM_TABLES
/* #define LTC_GCM_TABLES_SSE2 */
#endif

#endif /* LTC_NO_MACS */

/* Various tidbits of modern neatoness */
#define LTC_BASE64

/* --> Pseudo Random Number Generators <--- */
#ifndef LTC_NO_PRNGS

/* Yarrow */
#define LTC_YARROW
/* which descriptor of AES to use?  */
/* 0 = rijndael_enc 1 = aes_enc, 2 = rijndael [full], 3 = aes [full] */
#define LTC_YARROW_AES 0

#if defined(LTC_YARROW) && !defined(LTC_CTR_MODE)
   #error LTC_YARROW requires LTC_CTR_MODE chaining mode to be defined!
#endif

/* a PRNG that simply reads from an available system source */
#define LTC_SPRNG

/* The LTC_RC4 stream cipher */
#define LTC_RC4

/* Fortuna PRNG */
#define LTC_FORTUNA
/* reseed every N calls to the read function */
#define LTC_FORTUNA_WD    10
/* number of pools (4..32) can save a bit of ram by lowering the count */
#define LTC_FORTUNA_POOLS 32

/* Greg's LTC_SOBER128 PRNG ;-0 */
#define LTC_SOBER128

/* the *nix style /dev/random device */
#define LTC_DEVRANDOM
/* try /dev/urandom before trying /dev/random */
#define TRY_URANDOM_FIRST

#endif /* LTC_NO_PRNGS */

/* ---> math provider? <--- */
#ifndef LTC_NO_MATH

/* LibTomMath */
/* #define LTM_LTC_DESC */

/* TomsFastMath */
/* #define TFM_LTC_DESC */

#endif /* LTC_NO_MATH */

/* ---> Public Key Crypto <--- */
#ifndef LTC_NO_PK

/* Include RSA support */
#define LTC_MRSA

/* Include Katja (a Rabin variant like RSA) */
/* #define MKAT */ 

/* Digital Signature Algorithm */
#define LTC_MDSA

/* ECC */
#define LTC_MECC

/* use Shamir's trick for point mul (speeds up signature verification) */
/* #define LTC_ECC_SHAMIR */

#if defined(TFM_LTC_DESC) && defined(LTC_MECC)
   #define LTC_MECC_ACCEL
#endif   

/* do we want fixed point ECC */
/* #define LTC_MECC_FP */

/* Timing Resistant? */
/* #define LTC_ECC_TIMING_RESISTANT */

#endif /* LTC_NO_PK */

/* LTC_PKCS #1 (RSA) and #5 (Password Handling) stuff */
#ifndef LTC_NO_PKCS

#define LTC_PKCS_1
#define LTC_PKCS_5

/* Include ASN.1 DER (required by DSA/RSA) */
#define LTC_DER

#endif /* LTC_NO_PKCS */

/* cleanup */

#ifdef LTC_MECC
/* Supported ECC Key Sizes */
#ifndef LTC_NO_CURVES
   #define ECC112
   #define ECC128
   #define ECC160
   #define ECC192
   #define ECC224
   #define ECC256
   #define ECC384
   #define ECC521
#endif
#endif

#if defined(LTC_MECC) || defined(LTC_MRSA) || defined(LTC_MDSA) || defined(MKATJA)
   /* Include the MPI functionality?  (required by the PK algorithms) */
   #define MPI
#endif

#ifdef LTC_MRSA
   #define LTC_PKCS_1
#endif   

#if defined(LTC_DER) && !defined(MPI) 
   #error ASN.1 DER requires MPI functionality
#endif

#if (defined(LTC_MDSA) || defined(LTC_MRSA) || defined(LTC_MECC) || defined(MKATJA)) && !defined(LTC_DER)
   #error PK requires ASN.1 DER functionality, make sure LTC_DER is enabled
#endif

/* THREAD management */
#ifdef LTC_PTHREAD

#include <pthread.h>

#define LTC_MUTEX_GLOBAL(x)   pthread_mutex_t x = PTHREAD_MUTEX_INITIALIZER;
#define LTC_MUTEX_PROTO(x)    extern pthread_mutex_t x;
#define LTC_MUTEX_TYPE(x)     pthread_mutex_t x;
#define LTC_MUTEX_INIT(x)     pthread_mutex_init(x, NULL);
#define LTC_MUTEX_LOCK(x)     pthread_mutex_lock(x);
#define LTC_MUTEX_UNLOCK(x)   pthread_mutex_unlock(x);

#else

/* default no functions */
#define LTC_MUTEX_GLOBAL(x)
#define LTC_MUTEX_PROTO(x)
#define LTC_MUTEX_TYPE(x)
#define LTC_MUTEX_INIT(x)
#define LTC_MUTEX_LOCK(x)
#define LTC_MUTEX_UNLOCK(x)

#endif

/* Debuggers */

/* define this if you use Valgrind, note: it CHANGES the way SOBER-128 and LTC_RC4 work (see the code) */
/* #define LTC_VALGRIND */

#endif



/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_custom.h,v $ */
/* $Revision: 1.74 $ */
/* $Date: 2007/06/20 13:14:31 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_hash.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/* ---- HASH FUNCTIONS ---- */
#ifdef LTC_SHA512
struct sha512_state {
    ulong64  length, state[8];
    unsigned long curlen;
    unsigned char buf[128];
};
#endif

#ifdef LTC_SHA256
struct sha256_state {
    ulong64 length;
    ulong32 state[8], curlen;
    unsigned char buf[64];
};
#endif

#ifdef LTC_SHA1
struct sha1_state {
    ulong64 length;
    ulong32 state[5], curlen;
    unsigned char buf[64];
};
#endif

#ifdef LTC_MD5
struct md5_state {
    ulong64 length;
    ulong32 state[4], curlen;
    unsigned char buf[64];
};
#endif

#ifdef LTC_MD4
struct md4_state {
    ulong64 length;
    ulong32 state[4], curlen;
    unsigned char buf[64];
};
#endif

#ifdef LTC_TIGER
struct tiger_state {
    ulong64 state[3], length;
    unsigned long curlen;
    unsigned char buf[64];
};
#endif

#ifdef LTC_MD2
struct md2_state {
    unsigned char chksum[16], X[48], buf[16];
    unsigned long curlen;
};
#endif

#ifdef LTC_RIPEMD128
struct rmd128_state {
    ulong64 length;
    unsigned char buf[64];
    ulong32 curlen, state[4];
};
#endif

#ifdef LTC_RIPEMD160
struct rmd160_state {
    ulong64 length;
    unsigned char buf[64];
    ulong32 curlen, state[5];
};
#endif

#ifdef LTC_RIPEMD256
struct rmd256_state {
    ulong64 length;
    unsigned char buf[64];
    ulong32 curlen, state[8];
};
#endif

#ifdef LTC_RIPEMD320
struct rmd320_state {
    ulong64 length;
    unsigned char buf[64];
    ulong32 curlen, state[10];
};
#endif

#ifdef LTC_WHIRLPOOL
struct whirlpool_state {
    ulong64 length, state[8];
    unsigned char buf[64];
    ulong32 curlen;
};
#endif

#ifdef LTC_CHC_HASH
struct chc_state {
    ulong64 length;
    unsigned char state[MAXBLOCKSIZE], buf[MAXBLOCKSIZE];
    ulong32 curlen;
};
#endif

#ifdef LTC_SKEIN
///
/// I apologize for #including here, but it works, and will 
/// save you from skew. --  jdcc
///

#include "skein.h"
#include "skein_dropin.h"

#endif

typedef union Hash_state {
    char dummy[1];
#ifdef LTC_CHC_HASH
    struct chc_state chc;
#endif
#ifdef LTC_WHIRLPOOL
    struct whirlpool_state whirlpool;
#endif
#ifdef LTC_SHA512
    struct sha512_state sha512;
#endif
#ifdef LTC_SHA256
    struct sha256_state sha256;
#endif
#ifdef LTC_SHA1
    struct sha1_state   sha1;
#endif
#ifdef LTC_MD5
    struct md5_state    md5;
#endif
#ifdef LTC_MD4
    struct md4_state    md4;
#endif
#ifdef LTC_MD2
    struct md2_state    md2;
#endif
#ifdef LTC_TIGER
    struct tiger_state  tiger;
#endif
#ifdef LTC_RIPEMD128
    struct rmd128_state rmd128;
#endif
#ifdef LTC_RIPEMD160
    struct rmd160_state rmd160;
#endif
#ifdef LTC_RIPEMD256
    struct rmd256_state rmd256;
#endif
#ifdef LTC_RIPEMD320
    struct rmd320_state rmd320;
#endif
#ifdef LTC_SKEIN
	Skein_512_Ctxt_t skein; 
#endif
    void *data;
} hash_state;

/** hash descriptor */
extern  struct ltc_hash_descriptor {
    /** name of hash */
    char *name;
    /** internal ID */
    unsigned char ID;
    /** Size of digest in octets */
    unsigned long hashsize;
    /** Input block size in octets */
    unsigned long blocksize;
    /** ASN.1 OID */
    unsigned long OID[16];
    /** Length of DER encoding */
    unsigned long OIDlen;

    /** Init a hash state
      @param hash   The hash to initialize
      @return CRYPT_OK if successful
    */
    int (*init)(hash_state *hash);
    /** Process a block of data 
      @param hash   The hash state
      @param in     The data to hash
      @param inlen  The length of the data (octets)
      @return CRYPT_OK if successful
    */
    int (*process)(hash_state *hash, const unsigned char *in, unsigned long inlen);
    /** Produce the digest and store it
      @param hash   The hash state
      @param out    [out] The destination of the digest
      @return CRYPT_OK if successful
    */
    int (*done)(hash_state *hash, unsigned char *out);
    /** Self-test
      @return CRYPT_OK if successful, CRYPT_NOP if self-tests have been disabled
    */
    int (*test)(void);

    /* accelerated hmac callback: if you need to-do multiple packets just use the generic hmac_memory and provide a hash callback */
    int  (*hmac_block)(const unsigned char *key, unsigned long  keylen,
                       const unsigned char *in,  unsigned long  inlen, 
                             unsigned char *out, unsigned long *outlen);

} hash_descriptor[];

#ifdef LTC_CHC_HASH
int chc_register(int cipher);
int chc_init(hash_state * md);
int chc_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int chc_done(hash_state * md, unsigned char *hash);
int chc_test(void);
extern const struct ltc_hash_descriptor chc_desc;
#endif

#ifdef LTC_WHIRLPOOL
int whirlpool_init(hash_state * md);
int whirlpool_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int whirlpool_done(hash_state * md, unsigned char *hash);
int whirlpool_test(void);
extern const struct ltc_hash_descriptor whirlpool_desc;
#endif

#ifdef LTC_SHA512
int sha512_init(hash_state * md);
int sha512_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha512_done(hash_state * md, unsigned char *hash);
int sha512_test(void);
extern const struct ltc_hash_descriptor sha512_desc;
#endif

#ifdef LTC_SHA384
#ifndef LTC_SHA512
   #error LTC_SHA512 is required for LTC_SHA384
#endif
int sha384_init(hash_state * md);
#define sha384_process sha512_process
int sha384_done(hash_state * md, unsigned char *hash);
int sha384_test(void);
extern const struct ltc_hash_descriptor sha384_desc;
#endif

#ifdef LTC_SHA256
int sha256_init(hash_state * md);
int sha256_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha256_done(hash_state * md, unsigned char *hash);
int sha256_test(void);
extern const struct ltc_hash_descriptor sha256_desc;

#ifdef LTC_SHA224
#ifndef LTC_SHA256
   #error LTC_SHA256 is required for LTC_SHA224
#endif
int sha224_init(hash_state * md);
#define sha224_process sha256_process
int sha224_done(hash_state * md, unsigned char *hash);
int sha224_test(void);
extern const struct ltc_hash_descriptor sha224_desc;
#endif
#endif

#ifdef LTC_SHA1
int sha1_init(hash_state * md);
int sha1_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int sha1_done(hash_state * md, unsigned char *hash);
int sha1_test(void);
extern const struct ltc_hash_descriptor sha1_desc;
#endif

#ifdef LTC_MD5
int ltc_md5_init(hash_state * md);
int ltc_md5_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int ltc_md5_done(hash_state * md, unsigned char *hash);
int ltc_md5_test(void);
extern const struct ltc_hash_descriptor ltc_md5_desc;
#endif

#ifdef LTC_MD4
int md4_init(hash_state * md);
int md4_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md4_done(hash_state * md, unsigned char *hash);
int md4_test(void);
extern const struct ltc_hash_descriptor md4_desc;
#endif

#ifdef LTC_MD2
int md2_init(hash_state * md);
int md2_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int md2_done(hash_state * md, unsigned char *hash);
int md2_test(void);
extern const struct ltc_hash_descriptor md2_desc;
#endif

#ifdef LTC_TIGER
int tiger_init(hash_state * md);
int tiger_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int tiger_done(hash_state * md, unsigned char *hash);
int tiger_test(void);
extern const struct ltc_hash_descriptor tiger_desc;
#endif

#ifdef LTC_RIPEMD128
int rmd128_init(hash_state * md);
int rmd128_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd128_done(hash_state * md, unsigned char *hash);
int rmd128_test(void);
extern const struct ltc_hash_descriptor rmd128_desc;
#endif

#ifdef LTC_RIPEMD160
int rmd160_init(hash_state * md);
int rmd160_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd160_done(hash_state * md, unsigned char *hash);
int rmd160_test(void);
extern const struct ltc_hash_descriptor rmd160_desc;
#endif

#ifdef LTC_RIPEMD256
int rmd256_init(hash_state * md);
int rmd256_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd256_done(hash_state * md, unsigned char *hash);
int rmd256_test(void);
extern const struct ltc_hash_descriptor rmd256_desc;
#endif

#ifdef LTC_RIPEMD320
int rmd320_init(hash_state * md);
int rmd320_process(hash_state * md, const unsigned char *in, unsigned long inlen);
int rmd320_done(hash_state * md, unsigned char *hash);
int rmd320_test(void);
extern const struct ltc_hash_descriptor rmd320_desc;
#endif


int find_hash(const char *name);
int find_hash_id(unsigned char ID);
int find_hash_oid(const unsigned long *ID, unsigned long IDlen);
int find_hash_any(const char *name, int digestlen);
int register_hash(const struct ltc_hash_descriptor *hash);
int unregister_hash(const struct ltc_hash_descriptor *hash);
int hash_is_valid(int idx);

LTC_MUTEX_PROTO(ltc_hash_mutex)

int hash_memory(int hash, 
                const unsigned char *in,  unsigned long inlen, 
                      unsigned char *out, unsigned long *outlen);
int hash_memory_multi(int hash, unsigned char *out, unsigned long *outlen,
                      const unsigned char *in, unsigned long inlen, ...);
int hash_filehandle(int hash, FILE *in, unsigned char *out, unsigned long *outlen);
int hash_file(int hash, const char *fname, unsigned char *out, unsigned long *outlen);

/* a simple macro for making hash "process" functions */
#define HASH_PROCESS(func_name, compress_name, state_var, block_size)                       \
int func_name (hash_state * md, const unsigned char *in, unsigned long inlen)               \
{                                                                                           \
    unsigned long n;                                                                        \
    int           err;                                                                      \
    LTC_ARGCHK(md != NULL);                                                                 \
    LTC_ARGCHK(in != NULL);                                                                 \
    if (md-> state_var .curlen > sizeof(md-> state_var .buf)) {                             \
       return CRYPT_INVALID_ARG;                                                            \
    }                                                                                       \
    if ((md-> state_var .length + inlen) < md-> state_var .length) {	                    \
      return CRYPT_HASH_OVERFLOW;                                                           \
    }                                                                                       \
    while (inlen > 0) {                                                                     \
        if (md-> state_var .curlen == 0 && inlen >= block_size) {                           \
           if ((err = compress_name (md, (unsigned char *)in)) != CRYPT_OK) {               \
              return err;                                                                   \
           }                                                                                \
           md-> state_var .length += block_size * 8;                                        \
           in             += block_size;                                                    \
           inlen          -= block_size;                                                    \
        } else {                                                                            \
           n = MIN(inlen, (block_size - md-> state_var .curlen));                           \
           memcpy(md-> state_var .buf + md-> state_var.curlen, in, (size_t)n);              \
           md-> state_var .curlen += n;                                                     \
           in             += n;                                                             \
           inlen          -= n;                                                             \
           if (md-> state_var .curlen == block_size) {                                      \
              if ((err = compress_name (md, md-> state_var .buf)) != CRYPT_OK) {            \
                 return err;                                                                \
              }                                                                             \
              md-> state_var .length += 8*block_size;                                       \
              md-> state_var .curlen = 0;                                                   \
           }                                                                                \
       }                                                                                    \
    }                                                                                       \
    return CRYPT_OK;                                                                        \
}

/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_hash.h,v $ */
/* $Revision: 1.22 $ */
/* $Date: 2007/05/12 14:32:35 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_mac.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#ifdef LTC_HMAC
typedef struct Hmac_state {
     hash_state     md;
     int            hash;
     hash_state     hashstate;
     unsigned char  *key;
} hmac_state;

int hmac_init(hmac_state *hmac, int hash, const unsigned char *key, unsigned long keylen);
int hmac_process(hmac_state *hmac, const unsigned char *in, unsigned long inlen);
int hmac_done(hmac_state *hmac, unsigned char *out, unsigned long *outlen);
int hmac_test(void);
int hmac_memory(int hash, 
                const unsigned char *key, unsigned long keylen,
                const unsigned char *in,  unsigned long inlen, 
                      unsigned char *out, unsigned long *outlen);
int hmac_memory_multi(int hash, 
                const unsigned char *key,  unsigned long keylen,
                      unsigned char *out,  unsigned long *outlen,
                const unsigned char *in,   unsigned long inlen, ...);
int hmac_file(int hash, const char *fname, const unsigned char *key,
              unsigned long keylen, 
              unsigned char *dst, unsigned long *dstlen);
#endif

#ifdef LTC_OMAC

typedef struct {
   int             cipher_idx, 
                   buflen,
                   blklen;
   unsigned char   block[MAXBLOCKSIZE],
                   prev[MAXBLOCKSIZE],
                   Lu[2][MAXBLOCKSIZE];
   symmetric_key   key;
} omac_state;

int omac_init(omac_state *omac, int cipher, const unsigned char *key, unsigned long keylen);
int omac_process(omac_state *omac, const unsigned char *in, unsigned long inlen);
int omac_done(omac_state *omac, unsigned char *out, unsigned long *outlen);
int omac_memory(int cipher, 
               const unsigned char *key, unsigned long keylen,
               const unsigned char *in,  unsigned long inlen,
                     unsigned char *out, unsigned long *outlen);
int omac_memory_multi(int cipher, 
                const unsigned char *key, unsigned long keylen,
                      unsigned char *out, unsigned long *outlen,
                const unsigned char *in,  unsigned long inlen, ...);
int omac_file(int cipher, 
              const unsigned char *key, unsigned long keylen,
              const          char *filename, 
                    unsigned char *out, unsigned long *outlen);
int omac_test(void);
#endif /* LTC_OMAC */

#ifdef LTC_PMAC

typedef struct {
   unsigned char     Ls[32][MAXBLOCKSIZE],    /* L shifted by i bits to the left */
                     Li[MAXBLOCKSIZE],        /* value of Li [current value, we calc from previous recall] */
                     Lr[MAXBLOCKSIZE],        /* L * x^-1 */
                     block[MAXBLOCKSIZE],     /* currently accumulated block */
                     checksum[MAXBLOCKSIZE];  /* current checksum */

   symmetric_key     key;                     /* scheduled key for cipher */
   unsigned long     block_index;             /* index # for current block */
   int               cipher_idx,              /* cipher idx */
                     block_len,               /* length of block */
                     buflen;                  /* number of bytes in the buffer */
} pmac_state;

int pmac_init(pmac_state *pmac, int cipher, const unsigned char *key, unsigned long keylen);
int pmac_process(pmac_state *pmac, const unsigned char *in, unsigned long inlen);
int pmac_done(pmac_state *pmac, unsigned char *out, unsigned long *outlen);

int pmac_memory(int cipher, 
               const unsigned char *key, unsigned long keylen,
               const unsigned char *msg, unsigned long msglen,
                     unsigned char *out, unsigned long *outlen);

int pmac_memory_multi(int cipher, 
                const unsigned char *key, unsigned long keylen,
                      unsigned char *out, unsigned long *outlen,
                const unsigned char *in, unsigned long inlen, ...);

int pmac_file(int cipher, 
             const unsigned char *key, unsigned long keylen,
             const          char *filename, 
                   unsigned char *out, unsigned long *outlen);

int pmac_test(void);

/* internal functions */
int pmac_ntz(unsigned long x);
void pmac_shift_xor(pmac_state *pmac);

#endif /* PMAC */

#ifdef LTC_EAX_MODE

#if !(defined(LTC_OMAC) && defined(LTC_CTR_MODE))
   #error LTC_EAX_MODE requires LTC_OMAC and CTR
#endif

typedef struct {
   unsigned char N[MAXBLOCKSIZE];
   symmetric_CTR ctr;
   omac_state    headeromac, ctomac;
} eax_state;

int eax_init(eax_state *eax, int cipher, const unsigned char *key, unsigned long keylen,
             const unsigned char *nonce, unsigned long noncelen,
             const unsigned char *header, unsigned long headerlen);

int eax_encrypt(eax_state *eax, const unsigned char *pt, unsigned char *ct, unsigned long length);
int eax_decrypt(eax_state *eax, const unsigned char *ct, unsigned char *pt, unsigned long length);
int eax_addheader(eax_state *eax, const unsigned char *header, unsigned long length);
int eax_done(eax_state *eax, unsigned char *tag, unsigned long *taglen);

int eax_encrypt_authenticate_memory(int cipher,
    const unsigned char *key,    unsigned long keylen,
    const unsigned char *nonce,  unsigned long noncelen,
    const unsigned char *header, unsigned long headerlen,
    const unsigned char *pt,     unsigned long ptlen,
          unsigned char *ct,
          unsigned char *tag,    unsigned long *taglen);

int eax_decrypt_verify_memory(int cipher,
    const unsigned char *key,    unsigned long keylen,
    const unsigned char *nonce,  unsigned long noncelen,
    const unsigned char *header, unsigned long headerlen,
    const unsigned char *ct,     unsigned long ctlen,
          unsigned char *pt,
          unsigned char *tag,    unsigned long taglen,
          int           *stat);

 int eax_test(void);
#endif /* EAX MODE */

#ifdef LTC_OCB_MODE
typedef struct {
   unsigned char     L[MAXBLOCKSIZE],         /* L value */
                     Ls[32][MAXBLOCKSIZE],    /* L shifted by i bits to the left */
                     Li[MAXBLOCKSIZE],        /* value of Li [current value, we calc from previous recall] */
                     Lr[MAXBLOCKSIZE],        /* L * x^-1 */
                     R[MAXBLOCKSIZE],         /* R value */
                     checksum[MAXBLOCKSIZE];  /* current checksum */

   symmetric_key     key;                     /* scheduled key for cipher */
   unsigned long     block_index;             /* index # for current block */
   int               cipher,                  /* cipher idx */
                     block_len;               /* length of block */
} ocb_state;

int ocb_init(ocb_state *ocb, int cipher, 
             const unsigned char *key, unsigned long keylen, const unsigned char *nonce);

int ocb_encrypt(ocb_state *ocb, const unsigned char *pt, unsigned char *ct);
int ocb_decrypt(ocb_state *ocb, const unsigned char *ct, unsigned char *pt);

int ocb_done_encrypt(ocb_state *ocb, 
                     const unsigned char *pt,  unsigned long ptlen,
                           unsigned char *ct, 
                           unsigned char *tag, unsigned long *taglen);

int ocb_done_decrypt(ocb_state *ocb, 
                     const unsigned char *ct,  unsigned long ctlen,
                           unsigned char *pt, 
                     const unsigned char *tag, unsigned long taglen, int *stat);

int ocb_encrypt_authenticate_memory(int cipher,
    const unsigned char *key,    unsigned long keylen,
    const unsigned char *nonce,  
    const unsigned char *pt,     unsigned long ptlen,
          unsigned char *ct,
          unsigned char *tag,    unsigned long *taglen);

int ocb_decrypt_verify_memory(int cipher,
    const unsigned char *key,    unsigned long keylen,
    const unsigned char *nonce,  
    const unsigned char *ct,     unsigned long ctlen,
          unsigned char *pt,
    const unsigned char *tag,    unsigned long taglen,
          int           *stat);

int ocb_test(void);

/* internal functions */
void ocb_shift_xor(ocb_state *ocb, unsigned char *Z);
int ocb_ntz(unsigned long x);
int s_ocb_done(ocb_state *ocb, const unsigned char *pt, unsigned long ptlen,
               unsigned char *ct, unsigned char *tag, unsigned long *taglen, int mode);

#endif /* LTC_OCB_MODE */

#ifdef LTC_CCM_MODE

#define CCM_ENCRYPT 0
#define CCM_DECRYPT 1

int ccm_memory(int cipher,
    const unsigned char *key,    unsigned long keylen,
    symmetric_key       *uskey,
    const unsigned char *nonce,  unsigned long noncelen,
    const unsigned char *header, unsigned long headerlen,
          unsigned char *pt,     unsigned long ptlen,
          unsigned char *ct,
          unsigned char *tag,    unsigned long *taglen,
                    int  direction);

int ccm_memory_ex(int cipher,
    const unsigned char *key,    unsigned long keylen,
    symmetric_key       *uskey,
    const unsigned char *nonce,  unsigned long noncelen,
    const unsigned char *header, unsigned long headerlen,
          unsigned char *pt,     unsigned long ptlen,
          unsigned char *ct,
          unsigned char *tag,    unsigned long *taglen,
                    int  direction,
    const unsigned char *B0,
    const unsigned char *CTR,
                    int  ctrwidth);

int ccm_test(void);

#endif /* LTC_CCM_MODE */

#if defined(LRW_MODE) || defined(LTC_GCM_MODE)
void gcm_gf_mult(const unsigned char *a, const unsigned char *b, unsigned char *c);
#endif


/* table shared between GCM and LRW */
#if defined(LTC_GCM_TABLES) || defined(LRW_TABLES) || ((defined(LTC_GCM_MODE) || defined(LTC_GCM_MODE)) && defined(LTC_FAST))
extern const unsigned char gcm_shift_table[];
#endif

#ifdef LTC_GCM_MODE

#define GCM_ENCRYPT 0
#define GCM_DECRYPT 1

#define LTC_GCM_MODE_IV    0
#define LTC_GCM_MODE_AAD   1
#define LTC_GCM_MODE_TEXT  2

typedef struct { 
   symmetric_key       K;
   unsigned char       H[16],        /* multiplier */
                       X[16],        /* accumulator */
                       Y[16],        /* counter */
                       Y_0[16],      /* initial counter */
                       buf[16];      /* buffer for stuff */

   int                 cipher,       /* which cipher */
                       ivmode,       /* Which mode is the IV in? */
                       mode,         /* mode the GCM code is in */
                       buflen;       /* length of data in buf */

   ulong64             totlen,       /* 64-bit counter used for IV and AAD */
                       pttotlen;     /* 64-bit counter for the PT */

#ifdef LTC_GCM_TABLES
   unsigned char       PC[16][256][16]  /* 16 tables of 8x128 */
#ifdef LTC_GCM_TABLES_SSE2
__attribute__ ((aligned (16)))
#endif
;
#endif  
} gcm_state;

void gcm_mult_h(gcm_state *gcm, unsigned char *I);

int gcm_init(gcm_state *gcm, int cipher,
             const unsigned char *key, int keylen);

int gcm_reset(gcm_state *gcm);

int gcm_add_iv(gcm_state *gcm, 
               const unsigned char *IV,     unsigned long IVlen);

int gcm_add_aad(gcm_state *gcm,
               const unsigned char *adata,  unsigned long adatalen);

int gcm_process(gcm_state *gcm,
                     unsigned char *pt,     unsigned long ptlen,
                     unsigned char *ct,
                     int direction);

int gcm_done(gcm_state *gcm, 
                     unsigned char *tag,    unsigned long *taglen);

int gcm_memory(      int           cipher,
               const unsigned char *key,    unsigned long keylen,
               const unsigned char *IV,     unsigned long IVlen,
               const unsigned char *adata,  unsigned long adatalen,
                     unsigned char *pt,     unsigned long ptlen,
                     unsigned char *ct, 
                     unsigned char *tag,    unsigned long *taglen,
                               int direction);
int gcm_test(void);

#endif /* LTC_GCM_MODE */

#ifdef LTC_PELICAN

typedef struct pelican_state
{
    symmetric_key K;
    unsigned char state[16];
    int           buflen;
} pelican_state;

int pelican_init(pelican_state *pelmac, const unsigned char *key, unsigned long keylen);
int pelican_process(pelican_state *pelmac, const unsigned char *in, unsigned long inlen);
int pelican_done(pelican_state *pelmac, unsigned char *out);
int pelican_test(void);

int pelican_memory(const unsigned char *key, unsigned long keylen,
                   const unsigned char *in, unsigned long inlen,
                         unsigned char *out);

#endif

#ifdef LTC_XCBC

/* add this to "keylen" to xcbc_init to use a pure three-key XCBC MAC */
#define LTC_XCBC_PURE  0x8000UL

typedef struct {
   unsigned char K[3][MAXBLOCKSIZE],
                 IV[MAXBLOCKSIZE];

   symmetric_key key;

             int cipher,
                 buflen,
                 blocksize;
} xcbc_state;

int xcbc_init(xcbc_state *xcbc, int cipher, const unsigned char *key, unsigned long keylen);
int xcbc_process(xcbc_state *xcbc, const unsigned char *in, unsigned long inlen);
int xcbc_done(xcbc_state *xcbc, unsigned char *out, unsigned long *outlen);
int xcbc_memory(int cipher, 
               const unsigned char *key, unsigned long keylen,
               const unsigned char *in,  unsigned long inlen,
                     unsigned char *out, unsigned long *outlen);
int xcbc_memory_multi(int cipher, 
                const unsigned char *key, unsigned long keylen,
                      unsigned char *out, unsigned long *outlen,
                const unsigned char *in,  unsigned long inlen, ...);
int xcbc_file(int cipher, 
              const unsigned char *key, unsigned long keylen,
              const          char *filename, 
                    unsigned char *out, unsigned long *outlen);
int xcbc_test(void);

#endif

#ifdef LTC_F9_MODE

typedef struct {
   unsigned char akey[MAXBLOCKSIZE],
                 ACC[MAXBLOCKSIZE],
                 IV[MAXBLOCKSIZE];

   symmetric_key key;

             int cipher,
                 buflen,
                 keylen,
                 blocksize;
} f9_state;

int f9_init(f9_state *f9, int cipher, const unsigned char *key, unsigned long keylen);
int f9_process(f9_state *f9, const unsigned char *in, unsigned long inlen);
int f9_done(f9_state *f9, unsigned char *out, unsigned long *outlen);
int f9_memory(int cipher, 
               const unsigned char *key, unsigned long keylen,
               const unsigned char *in,  unsigned long inlen,
                     unsigned char *out, unsigned long *outlen);
int f9_memory_multi(int cipher, 
                const unsigned char *key, unsigned long keylen,
                      unsigned char *out, unsigned long *outlen,
                const unsigned char *in,  unsigned long inlen, ...);
int f9_file(int cipher, 
              const unsigned char *key, unsigned long keylen,
              const          char *filename, 
                    unsigned char *out, unsigned long *outlen);
int f9_test(void);

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_mac.h,v $ */
/* $Revision: 1.24 $ */
/* $Date: 2007/06/20 13:14:31 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_macros.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/* fix for MSVC ...evil! */
#ifdef _MSC_VER
   #define CONST64(n) n ## ui64
   typedef unsigned __int64 ulong64;
#else
   #define CONST64(n) n ## ULL
   typedef unsigned long long ulong64;
#endif

/* this is the "32-bit at least" data type 
 * Re-define it to suit your platform but it must be at least 32-bits 
 */
#if defined(__x86_64__) || (defined(__sparc__) && defined(__arch64__))
   typedef unsigned ulong32;
#else
   typedef unsigned long ulong32;
#endif

/* ---- HELPER MACROS ---- */
#ifdef ENDIAN_NEUTRAL

#define STORE32L(x, y)                                                                     \
     { (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255);   \
       (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }

#define LOAD32L(x, y)                            \
     { x = ((unsigned long)((y)[3] & 255)<<24) | \
           ((unsigned long)((y)[2] & 255)<<16) | \
           ((unsigned long)((y)[1] & 255)<<8)  | \
           ((unsigned long)((y)[0] & 255)); }

#define STORE64L(x, y)                                                                     \
     { (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255);   \
       (y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255);   \
       (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255);   \
       (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }

#define LOAD64L(x, y)                                                       \
     { x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48)| \
           (((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32)| \
           (((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16)| \
           (((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); }

#define STORE32H(x, y)                                                                     \
     { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255);   \
       (y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }

#define LOAD32H(x, y)                            \
     { x = ((unsigned long)((y)[0] & 255)<<24) | \
           ((unsigned long)((y)[1] & 255)<<16) | \
           ((unsigned long)((y)[2] & 255)<<8)  | \
           ((unsigned long)((y)[3] & 255)); }

#define STORE64H(x, y)                                                                     \
   { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255);     \
     (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255);     \
     (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255);     \
     (y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }

#define LOAD64H(x, y)                                                      \
   { x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48) | \
         (((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32) | \
         (((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16) | \
         (((ulong64)((y)[6] & 255))<<8)|(((ulong64)((y)[7] & 255))); }

#endif /* ENDIAN_NEUTRAL */

#ifdef ENDIAN_LITTLE

#if !defined(LTC_NO_BSWAP) && (defined(INTEL_CC) || (defined(__GNUC__) && (defined(__DJGPP__) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__i386__) || defined(__x86_64__))))

#define STORE32H(x, y)           \
asm __volatile__ (               \
   "bswapl %0     \n\t"          \
   "movl   %0,(%1)\n\t"          \
   "bswapl %0     \n\t"          \
      ::"r"(x), "r"(y));

#define LOAD32H(x, y)          \
asm __volatile__ (             \
   "movl (%1),%0\n\t"          \
   "bswapl %0\n\t"             \
   :"=r"(x): "r"(y));

#else

#define STORE32H(x, y)                                                                     \
     { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255);   \
       (y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); }

#define LOAD32H(x, y)                            \
     { x = ((unsigned long)((y)[0] & 255)<<24) | \
           ((unsigned long)((y)[1] & 255)<<16) | \
           ((unsigned long)((y)[2] & 255)<<8)  | \
           ((unsigned long)((y)[3] & 255)); }

#endif


/* x86_64 processor */
#if !defined(LTC_NO_BSWAP) && (defined(__GNUC__) && defined(__x86_64__))

#define STORE64H(x, y)           \
asm __volatile__ (               \
   "bswapq %0     \n\t"          \
   "movq   %0,(%1)\n\t"          \
   "bswapq %0     \n\t"          \
      ::"r"(x), "r"(y));

#define LOAD64H(x, y)          \
asm __volatile__ (             \
   "movq (%1),%0\n\t"          \
   "bswapq %0\n\t"             \
   :"=r"(x): "r"(y));

#else

#define STORE64H(x, y)                                                                     \
   { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255);     \
     (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255);     \
     (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255);     \
     (y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); }

#define LOAD64H(x, y)                                                      \
   { x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48) | \
         (((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32) | \
         (((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16) | \
         (((ulong64)((y)[6] & 255))<<8)|(((ulong64)((y)[7] & 255))); }

#endif

#ifdef ENDIAN_32BITWORD 

#define STORE32L(x, y)        \
     { ulong32  __t = (x); XMEMCPY(y, &__t, 4); }

#define LOAD32L(x, y)         \
     XMEMCPY(&(x), y, 4);

#define STORE64L(x, y)                                                                     \
     { (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255);   \
       (y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255);   \
       (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255);   \
       (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }

#define LOAD64L(x, y)                                                       \
     { x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48)| \
           (((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32)| \
           (((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16)| \
           (((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); }

#else /* 64-bit words then  */

#define STORE32L(x, y)        \
     { ulong32 __t = (x); XMEMCPY(y, &__t, 4); }

#define LOAD32L(x, y)         \
     { XMEMCPY(&(x), y, 4); x &= 0xFFFFFFFF; }

#define STORE64L(x, y)        \
     { ulong64 __t = (x); XMEMCPY(y, &__t, 8); }

#define LOAD64L(x, y)         \
    { XMEMCPY(&(x), y, 8); }

#endif /* ENDIAN_64BITWORD */

#endif /* ENDIAN_LITTLE */

#ifdef ENDIAN_BIG
#define STORE32L(x, y)                                                                     \
     { (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255);   \
       (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }

#define LOAD32L(x, y)                            \
     { x = ((unsigned long)((y)[3] & 255)<<24) | \
           ((unsigned long)((y)[2] & 255)<<16) | \
           ((unsigned long)((y)[1] & 255)<<8)  | \
           ((unsigned long)((y)[0] & 255)); }

#define STORE64L(x, y)                                                                     \
   { (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255);     \
     (y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255);     \
     (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255);     \
     (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); }

#define LOAD64L(x, y)                                                      \
   { x = (((ulong64)((y)[7] & 255))<<56)|(((ulong64)((y)[6] & 255))<<48) | \
         (((ulong64)((y)[5] & 255))<<40)|(((ulong64)((y)[4] & 255))<<32) | \
         (((ulong64)((y)[3] & 255))<<24)|(((ulong64)((y)[2] & 255))<<16) | \
         (((ulong64)((y)[1] & 255))<<8)|(((ulong64)((y)[0] & 255))); }

#ifdef ENDIAN_32BITWORD 

#define STORE32H(x, y)        \
     { ulong32 __t = (x); XMEMCPY(y, &__t, 4); }

#define LOAD32H(x, y)         \
     XMEMCPY(&(x), y, 4);

#define STORE64H(x, y)                                                                     \
     { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255);   \
       (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255);   \
       (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255);   \
       (y)[6] = (unsigned char)(((x)>>8)&255);  (y)[7] = (unsigned char)((x)&255); }

#define LOAD64H(x, y)                                                       \
     { x = (((ulong64)((y)[0] & 255))<<56)|(((ulong64)((y)[1] & 255))<<48)| \
           (((ulong64)((y)[2] & 255))<<40)|(((ulong64)((y)[3] & 255))<<32)| \
           (((ulong64)((y)[4] & 255))<<24)|(((ulong64)((y)[5] & 255))<<16)| \
           (((ulong64)((y)[6] & 255))<<8)| (((ulong64)((y)[7] & 255))); }

#else /* 64-bit words then  */

#define STORE32H(x, y)        \
     { ulong32 __t = (x); XMEMCPY(y, &__t, 4); }

#define LOAD32H(x, y)         \
     { XMEMCPY(&(x), y, 4); x &= 0xFFFFFFFF; }

#define STORE64H(x, y)        \
     { ulong64 __t = (x); XMEMCPY(y, &__t, 8); }

#define LOAD64H(x, y)         \
    { XMEMCPY(&(x), y, 8); }

#endif /* ENDIAN_64BITWORD */
#endif /* ENDIAN_BIG */

#define BSWAP(x)  ( ((x>>24)&0x000000FFUL) | ((x<<24)&0xFF000000UL)  | \
                    ((x>>8)&0x0000FF00UL)  | ((x<<8)&0x00FF0000UL) )


/* 32-bit Rotates */
#if defined(_MSC_VER)

/* instrinsic rotate */
#include <stdlib.h>
#pragma intrinsic(_lrotr,_lrotl)
#define ROR(x,n) _lrotr(x,n)
#define ROL(x,n) _lrotl(x,n)
#define RORc(x,n) _lrotr(x,n)
#define ROLc(x,n) _lrotl(x,n)

#elif !defined(__STRICT_ANSI__) && defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) && !defined(INTEL_CC) && !defined(LTC_NO_ASM)

static inline unsigned ROL(unsigned word, int i)
{
   asm ("roll %%cl,%0"
      :"=r" (word)
      :"0" (word),"c" (i));
   return word;
}

static inline unsigned ROR(unsigned word, int i)
{
   asm ("rorl %%cl,%0"
      :"=r" (word)
      :"0" (word),"c" (i));
   return word;
}

#ifndef LTC_NO_ROLC

static inline unsigned ROLc(unsigned word, const int i)
{
   asm ("roll %2,%0"
      :"=r" (word)
      :"0" (word),"I" (i));
   return word;
}

static inline unsigned RORc(unsigned word, const int i)
{
   asm ("rorl %2,%0"
      :"=r" (word)
      :"0" (word),"I" (i));
   return word;
}

#else

#define ROLc ROL
#define RORc ROR

#endif

#elif !defined(__STRICT_ANSI__) && defined(LTC_PPC32)

static inline unsigned ROL(unsigned word, int i)
{
   asm ("rotlw %0,%0,%2"
      :"=r" (word)
      :"0" (word),"r" (i));
   return word;
}

static inline unsigned ROR(unsigned word, int i)
{
   asm ("rotlw %0,%0,%2"
      :"=r" (word)
      :"0" (word),"r" (32-i));
   return word;
}

#ifndef LTC_NO_ROLC

static inline unsigned ROLc(unsigned word, const int i)
{
   asm ("rotlwi %0,%0,%2"
      :"=r" (word)
      :"0" (word),"I" (i));
   return word;
}

static inline unsigned RORc(unsigned word, const int i)
{
   asm ("rotrwi %0,%0,%2"
      :"=r" (word)
      :"0" (word),"I" (i));
   return word;
}

#else

#define ROLc ROL
#define RORc ROR

#endif


#else

/* rotates the hard way */
#define ROL(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define ROR(x, y) ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define RORc(x, y) ( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | ((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)

#endif


/* 64-bit Rotates */
#if !defined(__STRICT_ANSI__) && defined(__GNUC__) && defined(__x86_64__) && !defined(LTC_NO_ASM)

static inline unsigned long ROL64(unsigned long word, int i)
{
   asm("rolq %%cl,%0"
      :"=r" (word)
      :"0" (word),"c" (i));
   return word;
}

static inline unsigned long ROR64(unsigned long word, int i)
{
   asm("rorq %%cl,%0"
      :"=r" (word)
      :"0" (word),"c" (i));
   return word;
}

#ifndef LTC_NO_ROLC

static inline unsigned long ROL64c(unsigned long word, const int i)
{
   asm("rolq %2,%0"
      :"=r" (word)
      :"0" (word),"J" (i));
   return word;
}

static inline unsigned long ROR64c(unsigned long word, const int i)
{
   asm("rorq %2,%0"
      :"=r" (word)
      :"0" (word),"J" (i));
   return word;
}

#else /* LTC_NO_ROLC */

#define ROL64c ROL64
#define ROR64c ROR64

#endif

#else /* Not x86_64  */

#define ROL64(x, y) \
    ( (((x)<<((ulong64)(y)&63)) | \
      (((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)64-((y)&63)))) & CONST64(0xFFFFFFFFFFFFFFFF))

#define ROR64(x, y) \
    ( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)(y)&CONST64(63))) | \
      ((x)<<((ulong64)(64-((y)&CONST64(63)))))) & CONST64(0xFFFFFFFFFFFFFFFF))

#define ROL64c(x, y) \
    ( (((x)<<((ulong64)(y)&63)) | \
      (((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)64-((y)&63)))) & CONST64(0xFFFFFFFFFFFFFFFF))

#define ROR64c(x, y) \
    ( ((((x)&CONST64(0xFFFFFFFFFFFFFFFF))>>((ulong64)(y)&CONST64(63))) | \
      ((x)<<((ulong64)(64-((y)&CONST64(63)))))) & CONST64(0xFFFFFFFFFFFFFFFF))

#endif

#ifndef MAX
   #define MAX(x, y) ( ((x)>(y))?(x):(y) )
#endif

#ifndef MIN
   #define MIN(x, y) ( ((x)<(y))?(x):(y) )
#endif

/* extract a byte portably */
#ifdef _MSC_VER
   #define byte(x, n) ((unsigned char)((x) >> (8 * (n))))
#else
   #define byte(x, n) (((x) >> (8 * (n))) & 255)
#endif   

/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_macros.h,v $ */
/* $Revision: 1.15 $ */
/* $Date: 2006/11/29 23:43:57 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_math.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/** math functions **/

#define LTC_MP_LT   -1
#define LTC_MP_EQ    0
#define LTC_MP_GT    1

#define LTC_MP_NO    0
#define LTC_MP_YES   1

#ifndef LTC_MECC
   typedef void ecc_point;
#endif

#ifndef LTC_MRSA
   typedef void rsa_key;
#endif

/** math descriptor */
typedef struct {
   /** Name of the math provider */
   char *name;

   /** Bits per digit, amount of bits must fit in an unsigned long */
   int  bits_per_digit;

/* ---- init/deinit functions ---- */

   /** initialize a bignum
     @param   a     The number to initialize
     @return  CRYPT_OK on success
   */
   int (*init)(void **a);
   
   /** init copy 
     @param  dst    The number to initialize and write to
     @param  src    The number to copy from
     @return CRYPT_OK on success
   */
   int (*init_copy)(void **dst, void *src);

   /** deinit 
      @param   a    The number to free
      @return CRYPT_OK on success
   */
   void (*deinit)(void *a);

/* ---- data movement ---- */

   /** negate
      @param   src   The number to negate
      @param   dst   The destination
      @return CRYPT_OK on success
   */
   int (*neg)(void *src, void *dst);
   
   /** copy 
      @param   src   The number to copy from
      @param   dst   The number to write to 
      @return CRYPT_OK on success
   */
   int (*copy)(void *src, void *dst);

/* ---- trivial low level functions ---- */

   /** set small constant 
      @param a    Number to write to
      @param n    Source upto bits_per_digit (actually meant for very small constants) 
      @return CRYPT_OK on succcess
   */
   int (*set_int)(void *a, unsigned long n);

   /** get small constant 
      @param a    Number to read, only fetches upto bits_per_digit from the number
      @return  The lower bits_per_digit of the integer (unsigned)
   */
   unsigned long (*get_int)(void *a);

   /** get digit n 
     @param a  The number to read from
     @param n  The number of the digit to fetch
     @return  The bits_per_digit  sized n'th digit of a
   */
   unsigned long (*get_digit)(void *a, int n);

   /** Get the number of digits that represent the number
     @param a   The number to count
     @return The number of digits used to represent the number
   */
   int (*get_digit_count)(void *a);

   /** compare two integers
     @param a   The left side integer
     @param b   The right side integer
     @return LTC_MP_LT if a < b, LTC_MP_GT if a > b and LTC_MP_EQ otherwise.  (signed comparison)
   */
   int (*compare)(void *a, void *b);

   /** compare against int 
     @param a   The left side integer
     @param b   The right side integer (upto bits_per_digit)
     @return LTC_MP_LT if a < b, LTC_MP_GT if a > b and LTC_MP_EQ otherwise.  (signed comparison)
   */
   int (*compare_d)(void *a, unsigned long n);

   /** Count the number of bits used to represent the integer
     @param a   The integer to count
     @return The number of bits required to represent the integer
   */
   int (*count_bits)(void * a);

   /** Count the number of LSB bits which are zero 
     @param a   The integer to count
     @return The number of contiguous zero LSB bits
   */
   int (*count_lsb_bits)(void *a);

   /** Compute a power of two
     @param a  The integer to store the power in
     @param n  The power of two you want to store (a = 2^n)
     @return CRYPT_OK on success
   */
   int (*twoexpt)(void *a , int n);

/* ---- radix conversions ---- */
   
   /** read ascii string 
     @param a     The integer to store into
     @param str   The string to read
     @param radix The radix the integer has been represented in (2-64)
     @return CRYPT_OK on success
   */
   int (*read_radix)(void *a, const char *str, int radix);

   /** write number to string
     @param a     The integer to store
     @param str   The destination for the string
     @param radix The radix the integer is to be represented in (2-64)
     @return CRYPT_OK on success
   */
   int (*write_radix)(void *a, char *str, int radix);

   /** get size as unsigned char string 
     @param a     The integer to get the size (when stored in array of octets)
     @return The length of the integer
   */
   unsigned long (*unsigned_size)(void *a);

   /** store an integer as an array of octets 
     @param src   The integer to store
     @param dst   The buffer to store the integer in
     @return CRYPT_OK on success
   */
   int (*unsigned_write)(void *src, unsigned char *dst);

   /** read an array of octets and store as integer
     @param dst   The integer to load
     @param src   The array of octets 
     @param len   The number of octets 
     @return CRYPT_OK on success
   */
   int (*unsigned_read)(void *dst, unsigned char *src, unsigned long len);

/* ---- basic math ---- */

   /** add two integers 
     @param a   The first source integer
     @param b   The second source integer
     @param c   The destination of "a + b"
     @return CRYPT_OK on success
   */
   int (*add)(void *a, void *b, void *c);


   /** add two integers 
     @param a   The first source integer
     @param b   The second source integer (single digit of upto bits_per_digit in length)
     @param c   The destination of "a + b"
     @return CRYPT_OK on success
   */
   int (*addi)(void *a, unsigned long b, void *c);

   /** subtract two integers 
     @param a   The first source integer
     @param b   The second source integer
     @param c   The destination of "a - b"
     @return CRYPT_OK on success
   */
   int (*sub)(void *a, void *b, void *c);

   /** subtract two integers 
     @param a   The first source integer
     @param b   The second source integer (single digit of upto bits_per_digit in length)
     @param c   The destination of "a - b"
     @return CRYPT_OK on success
   */
   int (*subi)(void *a, unsigned long b, void *c);

   /** multiply two integers 
     @param a   The first source integer
     @param b   The second source integer (single digit of upto bits_per_digit in length)
     @param c   The destination of "a * b"
     @return CRYPT_OK on success
   */
   int (*mul)(void *a, void *b, void *c);

   /** multiply two integers 
     @param a   The first source integer
     @param b   The second source integer (single digit of upto bits_per_digit in length)
     @param c   The destination of "a * b"
     @return CRYPT_OK on success
   */
   int (*muli)(void *a, unsigned long b, void *c);

   /** Square an integer
     @param a    The integer to square
     @param b    The destination
     @return CRYPT_OK on success
   */
   int (*sqr)(void *a, void *b);

   /** Divide an integer
     @param a    The dividend
     @param b    The divisor
     @param c    The quotient (can be NULL to signify don't care)
     @param d    The remainder (can be NULL to signify don't care)
     @return CRYPT_OK on success
   */
   int (*mpdiv)(void *a, void *b, void *c, void *d);

   /** divide by two 
      @param  a   The integer to divide (shift right)
      @param  b   The destination 
      @return CRYPT_OK on success
   */
   int (*div_2)(void *a, void *b);

   /** Get remainder (small value)
      @param  a    The integer to reduce
      @param  b    The modulus (upto bits_per_digit in length)
      @param  c    The destination for the residue
      @return CRYPT_OK on success
   */
   int (*modi)(void *a, unsigned long b, unsigned long *c);

   /** gcd 
      @param  a     The first integer
      @param  b     The second integer
      @param  c     The destination for (a, b)
      @return CRYPT_OK on success
   */
   int (*gcd)(void *a, void *b, void *c);

   /** lcm 
      @param  a     The first integer
      @param  b     The second integer
      @param  c     The destination for [a, b]
      @return CRYPT_OK on success
   */
   int (*lcm)(void *a, void *b, void *c);

   /** Modular multiplication
      @param  a     The first source
      @param  b     The second source 
      @param  c     The modulus
      @param  d     The destination (a*b mod c)
      @return CRYPT_OK on success
   */
   int (*mulmod)(void *a, void *b, void *c, void *d);

   /** Modular squaring
      @param  a     The first source
      @param  b     The modulus
      @param  c     The destination (a*a mod b)
      @return CRYPT_OK on success
   */
   int (*sqrmod)(void *a, void *b, void *c);

   /** Modular inversion
      @param  a     The value to invert
      @param  b     The modulus 
      @param  c     The destination (1/a mod b)
      @return CRYPT_OK on success
   */
   int (*invmod)(void *, void *, void *);

/* ---- reduction ---- */

   /** setup montgomery
       @param a  The modulus 
       @param b  The destination for the reduction digit 
       @return CRYPT_OK on success
   */
   int (*montgomery_setup)(void *a, void **b);

   /** get normalization value 
       @param a   The destination for the normalization value
       @param b   The modulus
       @return  CRYPT_OK on success
   */
   int (*montgomery_normalization)(void *a, void *b);

   /** reduce a number
       @param a   The number [and dest] to reduce
       @param b   The modulus
       @param c   The value "b" from montgomery_setup()
       @return CRYPT_OK on success
   */
   int (*montgomery_reduce)(void *a, void *b, void *c);

   /** clean up  (frees memory)
       @param a   The value "b" from montgomery_setup()
       @return CRYPT_OK on success
   */      
   void (*montgomery_deinit)(void *a);

/* ---- exponentiation ---- */

   /** Modular exponentiation
       @param a    The base integer
       @param b    The power (can be negative) integer
       @param c    The modulus integer
       @param d    The destination
       @return CRYPT_OK on success
   */
   int (*exptmod)(void *a, void *b, void *c, void *d);

   /** Primality testing
       @param a     The integer to test
       @param b     The destination of the result (FP_YES if prime)
       @return CRYPT_OK on success
   */
   int (*isprime)(void *a, int *b);

/* ----  (optional) ecc point math ---- */

   /** ECC GF(p) point multiplication (from the NIST curves)
       @param k   The integer to multiply the point by
       @param G   The point to multiply
       @param R   The destination for kG  
       @param modulus  The modulus for the field
       @param map Boolean indicated whether to map back to affine or not (can be ignored if you work in affine only)
       @return CRYPT_OK on success
   */
   int (*ecc_ptmul)(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);

   /** ECC GF(p) point addition 
       @param P    The first point
       @param Q    The second point
       @param R    The destination of P + Q
       @param modulus  The modulus
       @param mp   The "b" value from montgomery_setup()
       @return CRYPT_OK on success
   */
   int (*ecc_ptadd)(ecc_point *P, ecc_point *Q, ecc_point *R, void *modulus, void *mp);

   /** ECC GF(p) point double 
       @param P    The first point
       @param R    The destination of 2P
       @param modulus  The modulus
       @param mp   The "b" value from montgomery_setup()
       @return CRYPT_OK on success
   */
   int (*ecc_ptdbl)(ecc_point *P, ecc_point *R, void *modulus, void *mp);

   /** ECC mapping from projective to affine, currently uses (x,y,z) => (x/z^2, y/z^3, 1)
       @param P     The point to map
       @param modulus The modulus
       @param mp    The "b" value from montgomery_setup()
       @return CRYPT_OK on success
       @remark  The mapping can be different but keep in mind a ecc_point only has three 
                integers (x,y,z) so if you use a different mapping you have to make it fit.
   */
   int (*ecc_map)(ecc_point *P, void *modulus, void *mp);

   /** Computes kA*A + kB*B = C using Shamir's Trick
       @param A        First point to multiply
       @param kA       What to multiple A by
       @param B        Second point to multiply
       @param kB       What to multiple B by
       @param C        [out] Destination point (can overlap with A or B
       @param modulus  Modulus for curve 
       @return CRYPT_OK on success
   */ 
   int (*ecc_mul2add)(ecc_point *A, void *kA,
                      ecc_point *B, void *kB,
                      ecc_point *C,
                           void *modulus);

/* ---- (optional) rsa optimized math (for internal CRT) ---- */

   /** RSA Key Generation 
       @param prng     An active PRNG state
       @param wprng    The index of the PRNG desired
       @param size     The size of the modulus (key size) desired (octets)
       @param e        The "e" value (public key).  e==65537 is a good choice
       @param key      [out] Destination of a newly created private key pair
       @return CRYPT_OK if successful, upon error all allocated ram is freed
    */
    int (*rsa_keygen)(prng_state *prng, int wprng, int size, long e, rsa_key *key);
   

   /** RSA exponentiation
      @param in       The octet array representing the base
      @param inlen    The length of the input
      @param out      The destination (to be stored in an octet array format)
      @param outlen   The length of the output buffer and the resulting size (zero padded to the size of the modulus)
      @param which    PK_PUBLIC for public RSA and PK_PRIVATE for private RSA
      @param key      The RSA key to use 
      @return CRYPT_OK on success
   */
   int (*rsa_me)(const unsigned char *in,   unsigned long inlen,
                       unsigned char *out,  unsigned long *outlen, int which,
                       rsa_key *key);
} ltc_math_descriptor;

extern ltc_math_descriptor ltc_mp;

int ltc_init_multi(void **a, ...);
void ltc_deinit_multi(void *a, ...);

#ifdef LTM_DESC
extern const ltc_math_descriptor ltm_desc;
#endif

#ifdef TFM_DESC
extern const ltc_math_descriptor tfm_desc;
#endif

#ifdef GMP_DESC
extern const ltc_math_descriptor gmp_desc;
#endif

#if !defined(DESC_DEF_ONLY) && defined(LTC_SOURCE)

#define MP_DIGIT_BIT                 ltc_mp.bits_per_digit

/* some handy macros */
#define mp_init(a)                   ltc_mp.init(a)
#define mp_init_multi                ltc_init_multi
#define mp_clear(a)                  ltc_mp.deinit(a)
#define mp_clear_multi               ltc_deinit_multi
#define mp_init_copy(a, b)           ltc_mp.init_copy(a, b)

#define mp_neg(a, b)                 ltc_mp.neg(a, b)
#define mp_copy(a, b)                ltc_mp.copy(a, b)

#define mp_set(a, b)                 ltc_mp.set_int(a, b)
#define mp_set_int(a, b)             ltc_mp.set_int(a, b)
#define mp_get_int(a)                ltc_mp.get_int(a)
#define mp_get_digit(a, n)           ltc_mp.get_digit(a, n)
#define mp_get_digit_count(a)        ltc_mp.get_digit_count(a)
#define mp_cmp(a, b)                 ltc_mp.compare(a, b)
#define mp_cmp_d(a, b)               ltc_mp.compare_d(a, b)
#define mp_count_bits(a)             ltc_mp.count_bits(a)
#define mp_cnt_lsb(a)                ltc_mp.count_lsb_bits(a)
#define mp_2expt(a, b)               ltc_mp.twoexpt(a, b)

#define mp_read_radix(a, b, c)       ltc_mp.read_radix(a, b, c)
#define mp_toradix(a, b, c)          ltc_mp.write_radix(a, b, c)
#define mp_unsigned_bin_size(a)      ltc_mp.unsigned_size(a)
#define mp_to_unsigned_bin(a, b)     ltc_mp.unsigned_write(a, b)
#define mp_read_unsigned_bin(a, b, c) ltc_mp.unsigned_read(a, b, c)

#define mp_add(a, b, c)              ltc_mp.add(a, b, c)
#define mp_add_d(a, b, c)            ltc_mp.addi(a, b, c)
#define mp_sub(a, b, c)              ltc_mp.sub(a, b, c)
#define mp_sub_d(a, b, c)            ltc_mp.subi(a, b, c)
#define mp_mul(a, b, c)              ltc_mp.mul(a, b, c)
#define mp_mul_d(a, b, c)            ltc_mp.muli(a, b, c)
#define mp_sqr(a, b)                 ltc_mp.sqr(a, b)
#define mp_div(a, b, c, d)           ltc_mp.mpdiv(a, b, c, d)
#define mp_div_2(a, b)               ltc_mp.div_2(a, b)
#define mp_mod(a, b, c)              ltc_mp.mpdiv(a, b, NULL, c)
#define mp_mod_d(a, b, c)            ltc_mp.modi(a, b, c)
#define mp_gcd(a, b, c)              ltc_mp.gcd(a, b, c)
#define mp_lcm(a, b, c)              ltc_mp.lcm(a, b, c)

#define mp_mulmod(a, b, c, d)        ltc_mp.mulmod(a, b, c, d)
#define mp_sqrmod(a, b, c)           ltc_mp.sqrmod(a, b, c)
#define mp_invmod(a, b, c)           ltc_mp.invmod(a, b, c)

#define mp_montgomery_setup(a, b)    ltc_mp.montgomery_setup(a, b)
#define mp_montgomery_normalization(a, b) ltc_mp.montgomery_normalization(a, b)
#define mp_montgomery_reduce(a, b, c)   ltc_mp.montgomery_reduce(a, b, c)
#define mp_montgomery_free(a)        ltc_mp.montgomery_deinit(a)

#define mp_exptmod(a,b,c,d)          ltc_mp.exptmod(a,b,c,d)
#define mp_prime_is_prime(a, b, c)   ltc_mp.isprime(a, c)

#define mp_iszero(a)                 (mp_cmp_d(a, 0) == LTC_MP_EQ ? LTC_MP_YES : LTC_MP_NO)
#define mp_isodd(a)                  (mp_get_digit_count(a) > 0 ? (mp_get_digit(a, 0) & 1 ? LTC_MP_YES : LTC_MP_NO) : LTC_MP_NO)
#define mp_exch(a, b)                do { void *ABC__tmp = a; a = b; b = ABC__tmp; } while(0);

#define mp_tohex(a, b)               mp_toradix(a, b, 16)

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_math.h,v $ */
/* $Revision: 1.44 $ */
/* $Date: 2007/05/12 14:32:35 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_misc.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* ---- LTC_BASE64 Routines ---- */
#ifdef LTC_BASE64
int base64_encode(const unsigned char *in,  unsigned long len, 
                        unsigned char *out, unsigned long *outlen);

int base64_decode(const unsigned char *in,  unsigned long len, 
                        unsigned char *out, unsigned long *outlen);
#endif

/* ---- MEM routines ---- */
void zeromem(void *dst, size_t len);
void burn_stack(unsigned long len);

const char *error_to_string(int err);

extern const char *crypt_build_settings;

/* ---- HMM ---- */
int crypt_fsa(void *mp, ...);

/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_misc.h,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2007/05/12 14:32:35 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































Deleted Source/libtomcrypt/src/headers/tomcrypt_mode.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/* 
 * Copyright (c) 2004 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include <unistd.h>
#include <stdint.h>
#include "tomcrypt.h"
#include "rc4.h"

typedef union ltcModeContext {
	symmetric_ECB 	ecbContext;
	symmetric_CBC		cbcContext;
	symmetric_CFB		cfbContext;
	symmetric_CTR		ctrContext;
	symmetric_OFB 	ofbContext;
	symmetric_LRW 	lrwContext;
	symmetric_F8 	f8Context;
	symmetric_xts 	xtsContext;
	char rc4ctx[sizeof(RC4_KEY)];
} mode_context;

typedef struct ltc_mode_descriptor {
	/** name of mode */
	char *name;
	/** internal ID */
	unsigned char ID;
	/** default number of rounds */
	uint32_t default_rounds;
	/** size of the context */
	size_t	ctxsize;
	/** Setup the mode
	 @param cipher				The index of the LTC Cipher - must be registered
	 @param IV						The initial vector
	 @param key						The input symmetric key
	 @param keylen				The length of the input key (octets)
	 @param tweak					The input tweak or salt
	 @param tweaklen			The length of the tweak or salt (if variable) (octets)
	 @param options				Mask for any mode options
	 @param num_rounds		The requested number of rounds (0==default)
	 @param ctx						[out] The destination of the mode context
	 @return CRYPT_OK if successful
	 */
	int  (*mode_setup)(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *tweak, int tweaklen, int num_rounds, int options, mode_context *ctx);
	/** Encrypt a block
	 @param pt						The plaintext
	 @param ct						[out] The ciphertext
	 @param len						the length of data (in == out) octets
	 @param ctx						The mode context
	 @return CRYPT_OK if successful
	 */
	int (*mode_encrypt)(const unsigned char *pt, unsigned char *ct, unsigned long len, mode_context *ctx);
	/** Decrypt a block
	 @param ct						The ciphertext
	 @param pt						[out] The plaintext
	 @param len						the length of data (in == out) octets
	 @param ctx						The mode context
	 @return CRYPT_OK if successful
	 */
	int (*mode_decrypt)(const unsigned char *ct, unsigned char *pt, unsigned long len, mode_context *ctx);
	/** Encrypt a block with a tweak (XTS mode currently)
	 @param pt						The plaintext
	 @param ct						[out] The ciphertext
	 @param len						the length of data (in == out) octets
	 @param tweak					The 128--bit encryption tweak (e.g. sector number)
	 @param ctx						The mode context
	 @return CRYPT_OK if successful
	 */
	int (*mode_encrypt_tweaked)(const unsigned char *pt, unsigned long len, unsigned char *ct, const unsigned char *tweak, mode_context *ctx);
	/** Decrypt a block with a tweak (XTS mode currently)
	 @param ct						The ciphertext
	 @param pt						[out] The plaintext
	 @param len						the length of data (in == out) octets
	 @param ctx						The mode context
	 @return CRYPT_OK if successful
	 */
	int (*mode_decrypt_tweaked)(const unsigned char *ct, unsigned long len, unsigned char *pt, const unsigned char *tweak, mode_context *ctx);
	/** Terminate the mode
	 @param ctx						[out] The mode context
	 @return CRYPT_OK if successful
	 */
	int (*mode_done)(mode_context *ctx);
	/** Set an Initial Vector
	 @param IV						The initial vector
	 @param len						The length of the initial vector
	 @param ctx						The mode context
	 @return CRYPT_OK if successful
	 */
	int (*mode_setiv)(const unsigned char *IV, unsigned long len, mode_context *ctx);
	/** Get an Initial Vector
	 @param IV						[out] The initial vector
	 @param len						The length of the initial vector
	 @param ctx						The mode context
	 @return CRYPT_OK if successful
	 */
	int (*mode_getiv)(const unsigned char *IV, unsigned long *len, mode_context *ctx);
	
	
} *mode_descriptor_ptr;

extern mode_descriptor_ptr mode_descriptor[];

int unimp_mode_setup(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
const unsigned char *tweak, int tweaklen, int num_rounds, int options, mode_context *ctx);
int unimp_mode_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, mode_context *ctx);
int unimp_mode_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, mode_context *ctx);
int unimp_mode_encrypt_tweaked(const unsigned char *pt, unsigned long len, unsigned char *ct, const unsigned char *tweak, mode_context *ctx);
int unimp_mode_decrypt_tweaked(const unsigned char *ct, unsigned long len, unsigned char *pt, const unsigned char *tweak, mode_context *ctx);
int unimp_mode_done(mode_context *ctx);
int unimp_mode_setiv(const unsigned char *IV, unsigned long len, mode_context *ctx);
int unimp_mode_getiv(const unsigned char *IV, unsigned long *len, mode_context *ctx);

int rc4_stream_setup(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
const unsigned char *tweak, int tweaklen, int num_rounds, int options, RC4_KEY *ctx);
int rc4_stream_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, mode_context *ctx);
int rc4_stream_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, mode_context *ctx);
int rc4_stream_done(mode_context *ctx);

extern const struct ltc_mode_descriptor	modeUNIMP_desc;
extern const struct ltc_mode_descriptor	modeECB_desc;
extern const struct ltc_mode_descriptor	modeCBC_desc;
extern const struct ltc_mode_descriptor	modeCFB_desc;
extern const struct ltc_mode_descriptor	modeCFB8_desc;
extern const struct ltc_mode_descriptor	modeCTR_desc;
extern const struct ltc_mode_descriptor	modef8_desc;
extern const struct ltc_mode_descriptor	modeLRW_desc;
extern const struct ltc_mode_descriptor	modeOFB_desc;
extern const struct ltc_mode_descriptor	modeXTS_desc;
extern const struct ltc_mode_descriptor	modeRC4_desc;

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_pk.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
/* ---- NUMBER THEORY ---- */

enum {
   PK_PUBLIC=0,
   PK_PRIVATE=1
};

int rand_prime(void *N, long len, prng_state *prng, int wprng);

/* ---- RSA ---- */
#ifdef LTC_MRSA

/* Min and Max RSA key sizes (in bits) */
#define MIN_RSA_SIZE 1024
#define MAX_RSA_SIZE 4096

/** RSA LTC_PKCS style key */
typedef struct Rsa_key {
    /** Type of key, PK_PRIVATE or PK_PUBLIC */
    int type;
    /** The public exponent */
    void *e; 
    /** The private exponent */
    void *d; 
    /** The modulus */
    void *N; 
    /** The p factor of N */
    void *p; 
    /** The q factor of N */
    void *q; 
    /** The 1/q mod p CRT param */
    void *qP; 
    /** The d mod (p - 1) CRT param */
    void *dP; 
    /** The d mod (q - 1) CRT param */
    void *dQ;
} rsa_key;

int rsa_make_key(prng_state *prng1, int wprng1, prng_state *prng2, int wprng2, int size, long e, rsa_key *key);

int rsa_exptmod(const unsigned char *in,   unsigned long inlen,
                      unsigned char *out,  unsigned long *outlen, int which,
                      rsa_key *key);

void rsa_free(rsa_key *key);

/* These use LTC_PKCS #1 v2.0 padding */
#define rsa_encrypt_key(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _prng, _prng_idx, _hash_idx, _key) \
  rsa_encrypt_key_ex(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _prng, _prng_idx, _hash_idx, LTC_PKCS_1_OAEP, _key)

#define rsa_decrypt_key(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _hash_idx, _stat, _key) \
  rsa_decrypt_key_ex(_in, _inlen, _out, _outlen, _lparam, _lparamlen, _hash_idx, LTC_PKCS_1_OAEP, _stat, _key)

#define rsa_sign_hash(_in, _inlen, _out, _outlen, _prng, _prng_idx, _hash_idx, _saltlen, _key) \
  rsa_sign_hash_ex(_in, _inlen, _out, _outlen, LTC_PKCS_1_PSS, _prng, _prng_idx, _hash_idx, _saltlen, _key)

#define rsa_verify_hash(_sig, _siglen, _hash, _hashlen, _hash_idx, _saltlen, _stat, _key) \
  rsa_verify_hash_ex(_sig, _siglen, _hash, _hashlen, LTC_PKCS_1_PSS, _hash_idx, _saltlen, _stat, _key)

/* These can be switched between LTC_PKCS #1 v2.x and LTC_PKCS #1 v1.5 paddings */
int rsa_encrypt_key_ex(const unsigned char *in,     unsigned long inlen,
                             unsigned char *out,    unsigned long *outlen,
                       const unsigned char *lparam, unsigned long lparamlen,
                       prng_state *prng, int prng_idx, int hash_idx, int padding, rsa_key *key);

int rsa_decrypt_key_ex(const unsigned char *in,       unsigned long  inlen,
                             unsigned char *out,      unsigned long *outlen,
                       const unsigned char *lparam,   unsigned long  lparamlen,
                             int            hash_idx, int            padding,
                             int           *stat,     rsa_key       *key);

int rsa_sign_hash_ex(const unsigned char *in,       unsigned long  inlen,
                           unsigned char *out,      unsigned long *outlen,
                           int            padding,
                           prng_state    *prng,     int            prng_idx,
                           int            hash_idx, unsigned long  saltlen,
                           rsa_key *key);

int rsa_verify_hash_ex(const unsigned char *sig,      unsigned long siglen,
                       const unsigned char *hash,     unsigned long hashlen,
                             int            padding,
                             int            hash_idx, unsigned long saltlen,
                             int           *stat,     rsa_key      *key);

/* LTC_PKCS #1 import/export */
int rsa_export(unsigned char *out, unsigned long *outlen, int type, rsa_key *key);
int rsa_import(const unsigned char *in, unsigned long inlen, rsa_key *key);
                        
#endif

/* ---- Katja ---- */
#ifdef MKAT

/* Min and Max KAT key sizes (in bits) */
#define MIN_KAT_SIZE 1024
#define MAX_KAT_SIZE 4096

/** Katja LTC_PKCS style key */
typedef struct KAT_key {
    /** Type of key, PK_PRIVATE or PK_PUBLIC */
    int type;
    /** The private exponent */
    void *d; 
    /** The modulus */
    void *N; 
    /** The p factor of N */
    void *p; 
    /** The q factor of N */
    void *q; 
    /** The 1/q mod p CRT param */
    void *qP; 
    /** The d mod (p - 1) CRT param */
    void *dP; 
    /** The d mod (q - 1) CRT param */
    void *dQ;
    /** The pq param */
    void *pq;
} katja_key;

int katja_make_key(prng_state *prng, int wprng, int size, katja_key *key);

int katja_exptmod(const unsigned char *in,   unsigned long inlen,
                        unsigned char *out,  unsigned long *outlen, int which,
                        katja_key *key);

void katja_free(katja_key *key);

/* These use LTC_PKCS #1 v2.0 padding */
int katja_encrypt_key(const unsigned char *in,     unsigned long inlen,
                            unsigned char *out,    unsigned long *outlen,
                      const unsigned char *lparam, unsigned long lparamlen,
                      prng_state *prng, int prng_idx, int hash_idx, katja_key *key);
                                        
int katja_decrypt_key(const unsigned char *in,       unsigned long inlen,
                            unsigned char *out,      unsigned long *outlen, 
                      const unsigned char *lparam,   unsigned long lparamlen,
                            int            hash_idx, int *stat,
                            katja_key       *key);

/* LTC_PKCS #1 import/export */
int katja_export(unsigned char *out, unsigned long *outlen, int type, katja_key *key);
int katja_import(const unsigned char *in, unsigned long inlen, katja_key *key);
                        
#endif

/* ---- ECC Routines ---- */
#ifdef LTC_MECC

/* size of our temp buffers for exported keys */
#define ECC_BUF_SIZE 256

/* max private key size */
#define ECC_MAXSIZE  66

/** Structure defines a NIST GF(p) curve */
typedef struct {
   /** The size of the curve in octets */
   int size;

   /** name of curve */
   char *name; 

   /** The prime that defines the field the curve is in (encoded in hex) */
   char *prime;

   /** The fields B param (hex) */
   char *B;

   /** The order of the curve (hex) */
   char *order;
  
   /** The x co-ordinate of the base point on the curve (hex) */
   char *Gx;

   /** The y co-ordinate of the base point on the curve (hex) */
   char *Gy;
} ltc_ecc_set_type;

/** A point on a ECC curve, stored in Jacbobian format such that (x,y,z) => (x/z^2, y/z^3, 1) when interpretted as affine */
typedef struct {

  /** Is this the point at infinity? **/

    int infinity;
  
    /** The x co-ordinate */
    void *x;

    /** The y co-ordinate */
    void *y;

    /** The z co-ordinate */
    void *z;
} ecc_point;

/** An ECC key */
typedef struct {
    /** Type of key, PK_PRIVATE or PK_PUBLIC */
    int type;

    /** Index into the ltc_ecc_sets[] for the parameters of this curve; if -1, then this key is using user supplied curve in dp */
    int idx;

	/** pointer to domain parameters; either points to NIST curves (identified by idx >= 0) or user supplied curve */
	const ltc_ecc_set_type *dp;

    /** The public key */
    ecc_point pubkey;

    /** The private key */
    void *k;
} ecc_key;

/** the ECC params provided */
extern const ltc_ecc_set_type ltc_ecc_sets[];

int  ecc_test(void);
void ecc_sizes(int *low, int *high);
int  ecc_get_size(ecc_key *key);

int  ecc_make_key(prng_state *prng, int wprng, int keysize, ecc_key *key);
int  ecc_make_key_ex(prng_state *prng, int wprng, ecc_key *key, const ltc_ecc_set_type *dp);
void ecc_free(ecc_key *key);

int ecc_validate_key(ecc_key *key);

int  ecc_export(unsigned char *out, unsigned long *outlen, int type, ecc_key *key);
int  ecc_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
int  ecc_import_ex(const unsigned char *in, unsigned long inlen, ecc_key *key, const ltc_ecc_set_type *dp);

int ecc_ansi_x963_export(ecc_key *key, unsigned char *out, unsigned long *outlen);
int ecc_ansi_x963_import(const unsigned char *in, unsigned long inlen, ecc_key *key);
int ecc_ansi_x963_import_ex(const unsigned char *in, unsigned long inlen, ecc_key *key, ltc_ecc_set_type *dp);

int  ecc_shared_secret(ecc_key *private_key, ecc_key *public_key, 
                       unsigned char *out, unsigned long *outlen);

int  ecc_encrypt_key(const unsigned char *in,   unsigned long inlen,
                           unsigned char *out,  unsigned long *outlen, 
                           prng_state *prng, int wprng, int hash, 
                           ecc_key *key);

int  ecc_decrypt_key(const unsigned char *in,  unsigned long  inlen,
                           unsigned char *out, unsigned long *outlen, 
                           ecc_key *key);

int  ecc_sign_hash(const unsigned char *in,  unsigned long inlen, 
                         unsigned char *out, unsigned long *outlen, 
                         prng_state *prng, int wprng, ecc_key *key);

int  ecc_verify_hash(const unsigned char *sig,  unsigned long siglen,
                     const unsigned char *hash, unsigned long hashlen, 
                     int *stat, ecc_key *key);

/* low level functions */
ecc_point *ltc_ecc_new_point(void);
void       ltc_ecc_del_point(ecc_point *p);
int        ltc_ecc_is_valid_idx(int n);

/* point ops (mp == montgomery digit) */
#if !defined(LTC_MECC_ACCEL) || defined(LTM_LTC_DESC) || defined(GMP_LTC_DESC)
/* R = 2P */
int ltc_ecc_projective_dbl_point(ecc_point *P, ecc_point *R, void *modulus, void *mp);

/* R = P + Q */
int ltc_ecc_projective_add_point(ecc_point *P, ecc_point *Q, ecc_point *R, void *modulus, void *mp);
#endif

#if defined(LTC_MECC_FP)
/* optimized point multiplication using fixed point cache (HAC algorithm 14.117) */
int ltc_ecc_fp_mulmod(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);

/* functions for saving/loading/freeing/adding to fixed point cache */
int ltc_ecc_fp_save_state(unsigned char **out, unsigned long *outlen);
int ltc_ecc_fp_restore_state(unsigned char *in, unsigned long inlen);
void ltc_ecc_fp_free(void);
int ltc_ecc_fp_add_point(ecc_point *g, void *modulus, int lock);

/* lock/unlock all points currently in fixed point cache */
void ltc_ecc_fp_tablelock(int lock);
#endif

/* R = kG */
int ltc_ecc_mulmod(void *k, ecc_point *G, ecc_point *R, void *modulus, int map);

#ifdef LTC_ECC_SHAMIR
/* kA*A + kB*B = C */
int ltc_ecc_mul2add(ecc_point *A, void *kA,
                    ecc_point *B, void *kB,
                    ecc_point *C,
                         void *modulus);

#ifdef LTC_MECC_FP
/* Shamir's trick with optimized point multiplication using fixed point cache */
int ltc_ecc_fp_mul2add(ecc_point *A, void *kA,
                       ecc_point *B, void *kB,
                       ecc_point *C, void *modulus);
#endif

#endif


/* map P to affine from projective */
int ltc_ecc_map(ecc_point *P, void *modulus, void *mp);

#endif

#ifdef LTC_MDSA

/* Max diff between group and modulus size in bytes */
#define LTC_MDSA_DELTA     512

/* Max DSA group size in bytes (default allows 4k-bit groups) */
#define LTC_MDSA_MAX_GROUP 512

/** DSA key structure */
typedef struct {
   /** The key type, PK_PRIVATE or PK_PUBLIC */
   int type; 

   /** The order of the sub-group used in octets */
   int qord;

   /** The generator  */
   void *g;

   /** The prime used to generate the sub-group */
   void *q;

   /** The large prime that generats the field the contains the sub-group */
   void *p;

   /** The private key */
   void *x;

   /** The public key */
   void *y;
} dsa_key;

int dsa_make_key(prng_state *prng, int wprng, int group_size, int modulus_size, dsa_key *key);
void dsa_free(dsa_key *key);

int dsa_sign_hash_raw(const unsigned char *in,  unsigned long inlen,
                                   void *r,   void *s,
                               prng_state *prng, int wprng, dsa_key *key);

int dsa_sign_hash(const unsigned char *in,  unsigned long inlen,
                        unsigned char *out, unsigned long *outlen,
                        prng_state *prng, int wprng, dsa_key *key);

int dsa_verify_hash_raw(         void *r,          void *s,
                    const unsigned char *hash, unsigned long hashlen, 
                                    int *stat,      dsa_key *key);

int dsa_verify_hash(const unsigned char *sig,  unsigned long siglen,
                    const unsigned char *hash, unsigned long hashlen, 
                          int           *stat, dsa_key       *key);

int dsa_encrypt_key(const unsigned char *in,   unsigned long inlen,
                          unsigned char *out,  unsigned long *outlen, 
                          prng_state *prng, int wprng, int hash, 
                          dsa_key *key);
                      
int dsa_decrypt_key(const unsigned char *in,  unsigned long  inlen,
                          unsigned char *out, unsigned long *outlen, 
                          dsa_key *key);
                          
int dsa_import(const unsigned char *in, unsigned long inlen, dsa_key *key);
int dsa_export(unsigned char *out, unsigned long *outlen, int type, dsa_key *key);
int dsa_verify_key(dsa_key *key, int *stat);

int dsa_shared_secret(void          *private_key, void *base,
                      dsa_key       *public_key,
                      unsigned char *out,         unsigned long *outlen);
#endif

#ifdef LTC_DER
/* DER handling */

enum {
 LTC_ASN1_EOL,
 LTC_ASN1_BOOLEAN,
 LTC_ASN1_INTEGER,
 LTC_ASN1_SHORT_INTEGER,
 LTC_ASN1_BIT_STRING,
 LTC_ASN1_OCTET_STRING,
 LTC_ASN1_NULL,
 LTC_ASN1_OBJECT_IDENTIFIER,
 LTC_ASN1_IA5_STRING,
 LTC_ASN1_PRINTABLE_STRING,
 LTC_ASN1_UTF8_STRING,
 LTC_ASN1_UTCTIME,
 LTC_ASN1_CHOICE,
 LTC_ASN1_SEQUENCE,
 LTC_ASN1_SET,
 LTC_ASN1_SETOF
};

/** A LTC ASN.1 list type */
typedef struct ltc_asn1_list_ {
   /** The LTC ASN.1 enumerated type identifier */
   int           type;
   /** The data to encode or place for decoding */
   void         *data;
   /** The size of the input or resulting output */
   unsigned long size;
   /** The used flag, this is used by the CHOICE ASN.1 type to indicate which choice was made */
   int           used;
   /** prev/next entry in the list */
   struct ltc_asn1_list_ *prev, *next, *child, *parent;
} ltc_asn1_list;

#define LTC_SET_ASN1(list, index, Type, Data, Size)  \
   do {                                              \
      int LTC_MACRO_temp            = (index);       \
      ltc_asn1_list *LTC_MACRO_list = (list);        \
      LTC_MACRO_list[LTC_MACRO_temp].type = (Type);  \
      LTC_MACRO_list[LTC_MACRO_temp].data = (void*)(Data);  \
      LTC_MACRO_list[LTC_MACRO_temp].size = (Size);  \
      LTC_MACRO_list[LTC_MACRO_temp].used = 0;       \
   } while (0);

/* SEQUENCE */
int der_encode_sequence_ex(ltc_asn1_list *list, unsigned long inlen,
                           unsigned char *out,  unsigned long *outlen, int type_of);
                          
#define der_encode_sequence(list, inlen, out, outlen) der_encode_sequence_ex(list, inlen, out, outlen, LTC_ASN1_SEQUENCE)                        

int der_decode_sequence_ex(const unsigned char *in, unsigned long  inlen,
                           ltc_asn1_list *list,     unsigned long  outlen, int ordered);
                              
#define der_decode_sequence(in, inlen, list, outlen) der_decode_sequence_ex(in, inlen, list, outlen, 1)

int der_length_sequence(ltc_asn1_list *list, unsigned long inlen,
                        unsigned long *outlen);

/* SET */
#define der_decode_set(in, inlen, list, outlen) der_decode_sequence_ex(in, inlen, list, outlen, 0)
#define der_length_set der_length_sequence
int der_encode_set(ltc_asn1_list *list, unsigned long inlen,
                   unsigned char *out,  unsigned long *outlen);

int der_encode_setof(ltc_asn1_list *list, unsigned long inlen,
                     unsigned char *out,  unsigned long *outlen);
                        
/* VA list handy helpers with triplets of <type, size, data> */
int der_encode_sequence_multi(unsigned char *out, unsigned long *outlen, ...);
int der_decode_sequence_multi(const unsigned char *in, unsigned long inlen, ...);

/* FLEXI DECODER handle unknown list decoder */
int  der_decode_sequence_flexi(const unsigned char *in, unsigned long *inlen, ltc_asn1_list **out);
void der_free_sequence_flexi(ltc_asn1_list *list);
void der_sequence_free(ltc_asn1_list *in);

/* BOOLEAN */
int der_length_boolean(unsigned long *outlen);
int der_encode_boolean(int in, 
                       unsigned char *out, unsigned long *outlen);
int der_decode_boolean(const unsigned char *in, unsigned long inlen,
                                       int *out);		       
/* INTEGER */
int der_encode_integer(void *num, unsigned char *out, unsigned long *outlen);
int der_decode_integer(const unsigned char *in, unsigned long inlen, void *num);
int der_length_integer(void *num, unsigned long *len);

/* INTEGER -- handy for 0..2^32-1 values */
int der_decode_short_integer(const unsigned char *in, unsigned long inlen, unsigned long *num);
int der_encode_short_integer(unsigned long num, unsigned char *out, unsigned long *outlen);
int der_length_short_integer(unsigned long num, unsigned long *outlen);

/* BIT STRING */
int der_encode_bit_string(const unsigned char *in, unsigned long inlen,
                                unsigned char *out, unsigned long *outlen);
int der_decode_bit_string(const unsigned char *in, unsigned long inlen,
                                unsigned char *out, unsigned long *outlen);
int der_length_bit_string(unsigned long nbits, unsigned long *outlen);

/* OCTET STRING */
int der_encode_octet_string(const unsigned char *in, unsigned long inlen,
                                  unsigned char *out, unsigned long *outlen);
int der_decode_octet_string(const unsigned char *in, unsigned long inlen,
                                  unsigned char *out, unsigned long *outlen);
int der_length_octet_string(unsigned long noctets, unsigned long *outlen);

/* OBJECT IDENTIFIER */
int der_encode_object_identifier(unsigned long *words, unsigned long  nwords,
                                 unsigned char *out,   unsigned long *outlen);
int der_decode_object_identifier(const unsigned char *in,    unsigned long  inlen,
                                       unsigned long *words, unsigned long *outlen);
int der_length_object_identifier(unsigned long *words, unsigned long nwords, unsigned long *outlen);
unsigned long der_object_identifier_bits(unsigned long x);

/* IA5 STRING */
int der_encode_ia5_string(const unsigned char *in, unsigned long inlen,
                                unsigned char *out, unsigned long *outlen);
int der_decode_ia5_string(const unsigned char *in, unsigned long inlen,
                                unsigned char *out, unsigned long *outlen);
int der_length_ia5_string(const unsigned char *octets, unsigned long noctets, unsigned long *outlen);

int der_ia5_char_encode(int c);
int der_ia5_value_decode(int v);

/* Printable STRING */
int der_encode_printable_string(const unsigned char *in, unsigned long inlen,
                                unsigned char *out, unsigned long *outlen);
int der_decode_printable_string(const unsigned char *in, unsigned long inlen,
                                unsigned char *out, unsigned long *outlen);
int der_length_printable_string(const unsigned char *octets, unsigned long noctets, unsigned long *outlen);

int der_printable_char_encode(int c);
int der_printable_value_decode(int v);

/* UTF-8 */
#if (defined(SIZE_MAX) || __STDC_VERSION__ >= 199901L || defined(WCHAR_MAX) || defined(_WCHAR_T) || defined(_WCHAR_T_DEFINED) || defined (__WCHAR_TYPE__)) && !defined(LTC_NO_WCHAR) 
#include <wchar.h>
#else
typedef ulong32 wchar_t;
#endif

int der_encode_utf8_string(const wchar_t *in,  unsigned long inlen,
                           unsigned char *out, unsigned long *outlen);

int der_decode_utf8_string(const unsigned char *in,  unsigned long inlen,
                                       wchar_t *out, unsigned long *outlen);
unsigned long der_utf8_charsize(const wchar_t c);
int der_length_utf8_string(const wchar_t *in, unsigned long noctets, unsigned long *outlen);


/* CHOICE */
int der_decode_choice(const unsigned char *in,   unsigned long *inlen,
                            ltc_asn1_list *list, unsigned long  outlen);

/* UTCTime */
typedef struct {
   unsigned YY, /* year */
            MM, /* month */
            DD, /* day */
            hh, /* hour */
            mm, /* minute */
            ss, /* second */
            off_dir, /* timezone offset direction 0 == +, 1 == - */
            off_hh, /* timezone offset hours */
            off_mm; /* timezone offset minutes */
} ltc_utctime;

int der_encode_utctime(ltc_utctime *utctime, 
                       unsigned char *out,   unsigned long *outlen);

int der_decode_utctime(const unsigned char *in, unsigned long *inlen,
                             ltc_utctime   *out);

int der_length_utctime(ltc_utctime *utctime, unsigned long *outlen);


#endif

/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_pk.h,v $ */
/* $Revision: 1.81 $ */
/* $Date: 2007/05/12 14:32:35 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_pkcs.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* LTC_PKCS Header Info */

/* ===> LTC_PKCS #1 -- RSA Cryptography <=== */
#ifdef LTC_PKCS_1

enum ltc_pkcs_1_v1_5_blocks
{
  LTC_PKCS_1_EMSA   = 1,        /* Block type 1 (LTC_PKCS #1 v1.5 signature padding) */
  LTC_PKCS_1_EME    = 2         /* Block type 2 (LTC_PKCS #1 v1.5 encryption padding) */
};

enum ltc_pkcs_1_paddings
{
  LTC_PKCS_1_V1_5   = 1,        /* LTC_PKCS #1 v1.5 padding (\sa ltc_pkcs_1_v1_5_blocks) */
  LTC_PKCS_1_OAEP   = 2,        /* LTC_PKCS #1 v2.0 encryption padding */
  LTC_PKCS_1_PSS    = 3         /* LTC_PKCS #1 v2.1 signature padding */
};

int pkcs_1_mgf1(      int            hash_idx,
                const unsigned char *seed, unsigned long seedlen,
                      unsigned char *mask, unsigned long masklen);

int pkcs_1_i2osp(void *n, unsigned long modulus_len, unsigned char *out);
int pkcs_1_os2ip(void *n, unsigned char *in, unsigned long inlen);

/* *** v1.5 padding */
int pkcs_1_v1_5_encode(const unsigned char *msg, 
                             unsigned long  msglen,
                             int            block_type,
                             unsigned long  modulus_bitlen,
                                prng_state *prng, 
                                       int  prng_idx,
                             unsigned char *out, 
                             unsigned long *outlen);

int pkcs_1_v1_5_decode(const unsigned char *msg, 
                             unsigned long  msglen,
                                       int  block_type,
                             unsigned long  modulus_bitlen,
                             unsigned char *out, 
                             unsigned long *outlen,
                                       int *is_valid);

/* *** v2.1 padding */
int pkcs_1_oaep_encode(const unsigned char *msg,    unsigned long msglen,
                       const unsigned char *lparam, unsigned long lparamlen,
                             unsigned long modulus_bitlen, prng_state *prng,
                             int           prng_idx,         int  hash_idx,
                             unsigned char *out,    unsigned long *outlen);

int pkcs_1_oaep_decode(const unsigned char *msg,    unsigned long msglen,
                       const unsigned char *lparam, unsigned long lparamlen,
                             unsigned long modulus_bitlen, int hash_idx,
                             unsigned char *out,    unsigned long *outlen,
                             int           *res);

int pkcs_1_pss_encode(const unsigned char *msghash, unsigned long msghashlen,
                            unsigned long saltlen,  prng_state   *prng,     
                            int           prng_idx, int           hash_idx,
                            unsigned long modulus_bitlen,
                            unsigned char *out,     unsigned long *outlen);

int pkcs_1_pss_decode(const unsigned char *msghash, unsigned long msghashlen,
                      const unsigned char *sig,     unsigned long siglen,
                            unsigned long saltlen,  int           hash_idx,
                            unsigned long modulus_bitlen, int    *res);

#endif /* LTC_PKCS_1 */

/* ===> LTC_PKCS #5 -- Password Based Cryptography <=== */
#ifdef LTC_PKCS_5

/* Algorithm #1 (old) */
int pkcs_5_alg1(const unsigned char *password, unsigned long password_len, 
                const unsigned char *salt, 
                int iteration_count,  int hash_idx,
                unsigned char *out,   unsigned long *outlen);

/* Algorithm #2 (new) */
int pkcs_5_alg2(const unsigned char *password, unsigned long password_len, 
                const unsigned char *salt,     unsigned long salt_len,
                int iteration_count,           int hash_idx,
                unsigned char *out,            unsigned long *outlen);

#endif  /* LTC_PKCS_5 */

/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_pkcs.h,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2007/05/12 14:32:35 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































































































































Deleted Source/libtomcrypt/src/headers/tomcrypt_prng.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/* ---- PRNG Stuff ---- */
#ifdef LTC_YARROW
struct yarrow_prng {
    int                   cipher, hash;
    unsigned char         pool[MAXBLOCKSIZE];
    symmetric_CTR         ctr;
    LTC_MUTEX_TYPE(prng_lock)
};
#endif

#ifdef LTC_RC4
struct rc4_prng {
    int x, y;
    unsigned char buf[256];
};
#endif

#ifdef LTC_FORTUNA
struct fortuna_prng {
    hash_state pool[LTC_FORTUNA_POOLS];     /* the  pools */

    symmetric_key skey;

    unsigned char K[32],      /* the current key */
                  IV[16];     /* IV for CTR mode */
    
    unsigned long pool_idx,   /* current pool we will add to */
                  pool0_len,  /* length of 0'th pool */
                  wd;            

    ulong64       reset_cnt;  /* number of times we have reset */
    LTC_MUTEX_TYPE(prng_lock)
};
#endif

#ifdef LTC_SOBER128
struct sober128_prng {
    ulong32      R[17],          /* Working storage for the shift register */
                 initR[17],      /* saved register contents */ 
                 konst,          /* key dependent constant */
                 sbuf;           /* partial word encryption buffer */

    int          nbuf,           /* number of part-word stream bits buffered */
                 flag,           /* first add_entropy call or not? */
                 set;            /* did we call add_entropy to set key? */
    
};
#endif

typedef union Prng_state {
    char dummy[1];
#ifdef LTC_YARROW
    struct yarrow_prng    yarrow;
#endif
#ifdef LTC_RC4
    struct rc4_prng       rc4;
#endif
#ifdef LTC_FORTUNA
    struct fortuna_prng   fortuna;
#endif
#ifdef LTC_SOBER128
    struct sober128_prng  sober128;
#endif
} prng_state;

/** PRNG descriptor */
extern struct ltc_prng_descriptor {
    /** Name of the PRNG */
    char *name;
    /** size in bytes of exported state */
    int  export_size;
    /** Start a PRNG state
        @param prng   [out] The state to initialize
        @return CRYPT_OK if successful
    */
    int (*start)(prng_state *prng);
    /** Add entropy to the PRNG
        @param in         The entropy
        @param inlen      Length of the entropy (octets)\
        @param prng       The PRNG state
        @return CRYPT_OK if successful
    */
    int (*add_entropy)(const unsigned char *in, unsigned long inlen, prng_state *prng);
    /** Ready a PRNG state to read from
        @param prng       The PRNG state to ready
        @return CRYPT_OK if successful
    */
    int (*ready)(prng_state *prng);
    /** Read from the PRNG
        @param out     [out] Where to store the data
        @param outlen  Length of data desired (octets)
        @param prng    The PRNG state to read from
        @return Number of octets read
    */
    unsigned long (*read)(unsigned char *out, unsigned long outlen, prng_state *prng);
    /** Terminate a PRNG state
        @param prng   The PRNG state to terminate
        @return CRYPT_OK if successful
    */
    int (*done)(prng_state *prng);
    /** Export a PRNG state  
        @param out     [out] The destination for the state
        @param outlen  [in/out] The max size and resulting size of the PRNG state
        @param prng    The PRNG to export
        @return CRYPT_OK if successful
    */
    int (*pexport)(unsigned char *out, unsigned long *outlen, prng_state *prng);
    /** Import a PRNG state
        @param in      The data to import
        @param inlen   The length of the data to import (octets)
        @param prng    The PRNG to initialize/import
        @return CRYPT_OK if successful
    */
    int (*pimport)(const unsigned char *in, unsigned long inlen, prng_state *prng);
    /** Self-test the PRNG
        @return CRYPT_OK if successful, CRYPT_NOP if self-testing has been disabled
    */
    int (*test)(void);
} prng_descriptor[];

#ifdef LTC_YARROW
int yarrow_start(prng_state *prng);
int yarrow_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int yarrow_ready(prng_state *prng);
unsigned long yarrow_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int yarrow_done(prng_state *prng);
int  yarrow_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int  yarrow_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int  yarrow_test(void);
extern const struct ltc_prng_descriptor yarrow_desc;
#endif

#ifdef LTC_FORTUNA
int fortuna_start(prng_state *prng);
int fortuna_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int fortuna_ready(prng_state *prng);
unsigned long fortuna_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int fortuna_done(prng_state *prng);
int  fortuna_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int  fortuna_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int  fortuna_test(void);
extern const struct ltc_prng_descriptor fortuna_desc;
#endif

#ifdef LTC_RC4
int rc4_start(prng_state *prng);
int rc4_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int rc4_ready(prng_state *prng);
unsigned long rc4_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int  rc4_done(prng_state *prng);
int  rc4_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int  rc4_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int  rc4_test(void);
extern const struct ltc_prng_descriptor rc4_desc;
#endif

#ifdef LTC_SPRNG
int sprng_start(prng_state *prng);
int sprng_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sprng_ready(prng_state *prng);
unsigned long sprng_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int sprng_done(prng_state *prng);
int  sprng_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int  sprng_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int  sprng_test(void);
extern const struct ltc_prng_descriptor sprng_desc;
#endif

#ifdef LTC_SOBER128
int sober128_start(prng_state *prng);
int sober128_add_entropy(const unsigned char *in, unsigned long inlen, prng_state *prng);
int sober128_ready(prng_state *prng);
unsigned long sober128_read(unsigned char *out, unsigned long outlen, prng_state *prng);
int sober128_done(prng_state *prng);
int  sober128_export(unsigned char *out, unsigned long *outlen, prng_state *prng);
int  sober128_import(const unsigned char *in, unsigned long inlen, prng_state *prng);
int  sober128_test(void);
extern const struct ltc_prng_descriptor sober128_desc;
#endif

int find_prng(const char *name);
int register_prng(const struct ltc_prng_descriptor *prng);
int unregister_prng(const struct ltc_prng_descriptor *prng);
int prng_is_valid(int idx);
LTC_MUTEX_PROTO(ltc_prng_mutex)

/* Slow RNG you **might** be able to use to seed a PRNG with.  Be careful as this
 * might not work on all platforms as planned
 */
unsigned long rng_get_bytes(unsigned char *out, 
                            unsigned long outlen, 
                            void (*callback)(void));

int rng_make_prng(int bits, int wprng, prng_state *prng, void (*callback)(void));


/* $Source: /cvs/libtom/libtomcrypt/src/headers/tomcrypt_prng.h,v $ */
/* $Revision: 1.9 $ */
/* $Date: 2007/05/12 14:32:35 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































































Deleted Source/libtomcrypt/src/misc/base64/base64_decode.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file base64_decode.c
  Compliant base64 code donated by Wayne Scott (wscott@bitmover.com)
*/


#ifdef LTC_BASE64

static const unsigned char map[256] = {
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255,  62, 255, 255, 255,  63,
 52,  53,  54,  55,  56,  57,  58,  59,  60,  61, 255, 255,
255, 254, 255, 255, 255,   0,   1,   2,   3,   4,   5,   6,
  7,   8,   9,  10,  11,  12,  13,  14,  15,  16,  17,  18,
 19,  20,  21,  22,  23,  24,  25, 255, 255, 255, 255, 255,
255,  26,  27,  28,  29,  30,  31,  32,  33,  34,  35,  36,
 37,  38,  39,  40,  41,  42,  43,  44,  45,  46,  47,  48,
 49,  50,  51, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255 };

/**
   base64 decode a block of memory
   @param in       The base64 data to decode
   @param inlen    The length of the base64 data
   @param out      [out] The destination of the binary decoded data
   @param outlen   [in/out] The max size and resulting size of the decoded data
   @return CRYPT_OK if successful
*/
int base64_decode(const unsigned char *in,  unsigned long inlen, 
                        unsigned char *out, unsigned long *outlen)
{
   unsigned long t, x, y, z;
   unsigned char c;
   int           g;

   LTC_ARGCHK(in     != NULL);
   LTC_ARGCHK(out    != NULL);
   LTC_ARGCHK(outlen != NULL);

   g = 3;
   for (x = y = z = t = 0; x < inlen; x++) {
       c = map[in[x]&0xFF];
       if (c == 255) continue;
       /* the final = symbols are read and used to trim the remaining bytes */
       if (c == 254) { 
          c = 0; 
          /* prevent g < 0 which would potentially allow an overflow later */
          if (--g < 0) {
             return CRYPT_INVALID_PACKET;
          }
       } else if (g != 3) {
          /* we only allow = to be at the end */
          return CRYPT_INVALID_PACKET;
       }

       t = (t<<6)|c;

       if (++y == 4) {
          if (z + g > *outlen) { 
             return CRYPT_BUFFER_OVERFLOW; 
          }
          out[z++] = (unsigned char)((t>>16)&255);
          if (g > 1) out[z++] = (unsigned char)((t>>8)&255);
          if (g > 2) out[z++] = (unsigned char)(t&255);
          y = t = 0;
       }
   }
   if (y != 0) {
       return CRYPT_INVALID_PACKET;
   }
   *outlen = z;
   return CRYPT_OK;
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/misc/base64/base64_decode.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2007/05/12 14:32:35 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































Deleted Source/libtomcrypt/src/misc/base64/base64_encode.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file base64_encode.c
  Compliant base64 encoder donated by Wayne Scott (wscott@bitmover.com)
*/


#ifdef LTC_BASE64

static const char *codes = 
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/**
   base64 Encode a buffer (NUL terminated)
   @param in      The input buffer to encode
   @param inlen   The length of the input buffer
   @param out     [out] The destination of the base64 encoded data
   @param outlen  [in/out] The max size and resulting size
   @return CRYPT_OK if successful
*/
int base64_encode(const unsigned char *in,  unsigned long inlen, 
                        unsigned char *out, unsigned long *outlen)
{
   unsigned long i, len2, leven;
   unsigned char *p;

   LTC_ARGCHK(in     != NULL);
   LTC_ARGCHK(out    != NULL);
   LTC_ARGCHK(outlen != NULL);

   /* valid output size ? */
   len2 = 4 * ((inlen + 2) / 3);
   if (*outlen < len2 + 1) {
      *outlen = len2 + 1;
      return CRYPT_BUFFER_OVERFLOW;
   }
   p = out;
   leven = 3*(inlen / 3);
   for (i = 0; i < leven; i += 3) {
       *p++ = codes[(in[0] >> 2) & 0x3F];
       *p++ = codes[(((in[0] & 3) << 4) + (in[1] >> 4)) & 0x3F];
       *p++ = codes[(((in[1] & 0xf) << 2) + (in[2] >> 6)) & 0x3F];
       *p++ = codes[in[2] & 0x3F];
       in += 3;
   }
   /* Pad it if necessary...  */
   if (i < inlen) {
       unsigned a = in[0];
       unsigned b = (i+1 < inlen) ? in[1] : 0;

       *p++ = codes[(a >> 2) & 0x3F];
       *p++ = codes[(((a & 3) << 4) + (b >> 4)) & 0x3F];
       *p++ = (i+1 < inlen) ? codes[(((b & 0xf) << 2)) & 0x3F] : '=';
       *p++ = '=';
   }

   /* append a NULL byte */
   *p = '\0';

   /* return ok */
   *outlen = p - out;
   return CRYPT_OK;
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/misc/base64/base64_encode.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2007/05/12 14:32:35 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































Deleted Source/libtomcrypt/src/misc/burn_stack.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file burn_stack.c
   Burn stack, Tom St Denis
*/

/**
   Burn some stack memory
   @param len amount of stack to burn in bytes
*/
void burn_stack(unsigned long len)
{
   unsigned char buf[32];
   zeromem(buf, sizeof(buf));
   if (len > (unsigned long)sizeof(buf))
      burn_stack(len - sizeof(buf));
}



/* $Source: /cvs/libtom/libtomcrypt/src/misc/burn_stack.c,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































Deleted Source/libtomcrypt/src/misc/crypt/crypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt.c
  Build strings, Tom St Denis
*/  

const char *crypt_build_settings =
   "LibTomCrypt " SCRYPT " (Tom St Denis, tomstdenis@gmail.com)\n"
   "LibTomCrypt is public domain software.\n"
   "Built on " __DATE__ " at " __TIME__ "\n\n\n"
   "Endianess: "
#if defined(ENDIAN_NEUTRAL)
   "neutral\n"
#elif defined(ENDIAN_LITTLE)
   "little"
   #if defined(ENDIAN_32BITWORD)
   " (32-bit words)\n"
   #else
   " (64-bit words)\n"
   #endif
#elif defined(ENDIAN_BIG)
   "big"
   #if defined(ENDIAN_32BITWORD)
   " (32-bit words)\n"
   #else
   " (64-bit words)\n"
   #endif
#endif
   "Clean stack: "
#if defined(LTC_CLEAN_STACK)
   "enabled\n"
#else
   "disabled\n"
#endif
   "Ciphers built-in:\n"
#if defined(LTC_BLOWFISH)
   "   Blowfish\n"
#endif
#if defined(LTC_RC2)
   "   LTC_RC2\n"
#endif
#if defined(LTC_RC5)
   "   LTC_RC5\n"
#endif
#if defined(LTC_RC6)
   "   LTC_RC6\n"
#endif
#if defined(LTC_SAFERP)
   "   Safer+\n"
#endif
#if defined(LTC_SAFER)
   "   Safer\n"
#endif
#if defined(LTC_RIJNDAEL)
   "   Rijndael\n"
#endif
#if defined(LTC_XTEA)
   "   LTC_XTEA\n"
#endif
#if defined(LTC_TWOFISH)
   "   Twofish "
   #if defined(LTC_TWOFISH_SMALL) && defined(LTC_TWOFISH_TABLES) && defined(LTC_TWOFISH_ALL_TABLES)
       "(small, tables, all_tables)\n"
   #elif defined(LTC_TWOFISH_SMALL) && defined(LTC_TWOFISH_TABLES)
       "(small, tables)\n"
   #elif defined(LTC_TWOFISH_SMALL) && defined(LTC_TWOFISH_ALL_TABLES)
       "(small, all_tables)\n"
   #elif defined(LTC_TWOFISH_TABLES) && defined(LTC_TWOFISH_ALL_TABLES)
       "(tables, all_tables)\n"
   #elif defined(LTC_TWOFISH_SMALL)
       "(small)\n"
   #elif defined(LTC_TWOFISH_TABLES)
       "(tables)\n"
   #elif defined(LTC_TWOFISH_ALL_TABLES)
       "(all_tables)\n"
   #else
       "\n"
   #endif
#endif
#if defined(LTC_DES)
   "   LTC_DES\n"
#endif
#if defined(LTC_CAST5)
   "   LTC_CAST5\n"
#endif
#if defined(LTC_NOEKEON)
   "   Noekeon\n"
#endif
#if defined(LTC_SKIPJACK)
   "   Skipjack\n"
#endif
#if defined(LTC_KHAZAD)
   "   Khazad\n"
#endif
#if defined(LTC_ANUBIS)
   "   Anubis "
#endif
#if defined(LTC_ANUBIS_TWEAK)
   " (tweaked)"
#endif
   "\n"
#if defined(LTC_KSEED)
   "   LTC_KSEED\n"
#endif
#if defined(LTC_KASUMI)
   "   KASUMI\n"
#endif
#if defined(LTC_MULTI2)
   "   MULTI2\n"
#endif
#if defined(LTC_CAMELLIA)
   "   Camellia\n"
#endif

    "\nHashes built-in:\n"
#if defined(LTC_SHA512)
   "   LTC_SHA-512\n"
#endif
#if defined(LTC_SHA384)
   "   LTC_SHA-384\n"
#endif
#if defined(LTC_SHA256)
   "   LTC_SHA-256\n"
#endif
#if defined(LTC_SHA224)
   "   LTC_SHA-224\n"
#endif
#if defined(LTC_TIGER)
   "   LTC_TIGER\n"
#endif
#if defined(LTC_SHA1)
   "   LTC_SHA1\n"
#endif
#if defined(LTC_MD5)
   "   LTC_MD5\n"
#endif
#if defined(LTC_MD4)
   "   LTC_MD4\n"
#endif
#if defined(LTC_MD2)
   "   LTC_MD2\n"
#endif
#if defined(LTC_RIPEMD128)
   "   LTC_RIPEMD128\n"
#endif
#if defined(LTC_RIPEMD160)
   "   LTC_RIPEMD160\n"
#endif
#if defined(LTC_RIPEMD256)
   "   LTC_RIPEMD256\n"
#endif
#if defined(LTC_RIPEMD320)
   "   LTC_RIPEMD320\n"
#endif
#if defined(LTC_WHIRLPOOL)
   "   LTC_WHIRLPOOL\n"
#endif
#if defined(LTC_CHC_HASH)
   "   LTC_CHC_HASH \n"
#endif

    "\nBlock Chaining Modes:\n"
#if defined(LTC_CFB_MODE)
    "   CFB\n"
#endif
#if defined(LTC_OFB_MODE)
    "   OFB\n"
#endif
#if defined(LTC_ECB_MODE)
    "   ECB\n"
#endif
#if defined(LTC_CBC_MODE)
    "   CBC\n"
#endif
#if defined(LTC_CTR_MODE)
    "   CTR "
#endif
#if defined(LTC_CTR_OLD)
    " (CTR_OLD) "
#endif
    "\n"
#if defined(LRW_MODE)
    "   LRW_MODE"
#if defined(LRW_TABLES)
    " (LRW_TABLES) "
#endif
    "\n"
#endif
#if defined(LTC_F8_MODE)
    "   F8 MODE\n"
#endif    
#if defined(LTC_XTS_MODE)
    "   LTC_XTS_MODE\n"
#endif

    "\nMACs:\n"
#if defined(LTC_HMAC)
    "   LTC_HMAC\n"
#endif
#if defined(LTC_OMAC)
    "   LTC_OMAC\n"
#endif
#if defined(LTC_PMAC)
    "   PMAC\n"
#endif
#if defined(LTC_PELICAN)
    "   LTC_PELICAN\n"
#endif
#if defined(LTC_XCBC)
    "   XCBC-MAC\n"
#endif
#if defined(LTC_F9_MODE)
    "   F9-MAC\n"
#endif

    "\nENC + AUTH modes:\n"
#if defined(LTC_EAX_MODE)
    "   LTC_EAX_MODE\n"
#endif
#if defined(LTC_OCB_MODE)
    "   LTC_OCB_MODE\n"
#endif
#if defined(LTC_CCM_MODE)
    "   LTC_CCM_MODE\n"
#endif
#if defined(LTC_GCM_MODE)
    "   LTC_GCM_MODE "
#endif
#if defined(LTC_GCM_TABLES)
    " (LTC_GCM_TABLES) "
#endif
   "\n"

    "\nPRNG:\n"
#if defined(LTC_YARROW)
    "   Yarrow\n"
#endif
#if defined(LTC_SPRNG)
    "   LTC_SPRNG\n"
#endif
#if defined(LTC_RC4)
    "   LTC_RC4\n"
#endif
#if defined(LTC_FORTUNA)
    "   Fortuna\n"
#endif
#if defined(LTC_SOBER128)
    "   LTC_SOBER128\n"
#endif

    "\nPK Algs:\n"
#if defined(LTC_MRSA)
    "   RSA \n"
#endif
#if defined(LTC_MECC)
    "   ECC\n"
#endif
#if defined(LTC_MDSA)
    "   DSA\n"
#endif
#if defined(MKAT)
    "   Katja\n"
#endif    

    "\nCompiler:\n"
#if defined(WIN32)
    "   WIN32 platform detected.\n"
#endif
#if defined(__CYGWIN__)
    "   CYGWIN Detected.\n"
#endif
#if defined(__DJGPP__)
    "   DJGPP Detected.\n"
#endif
#if defined(_MSC_VER)
    "   MSVC compiler detected.\n"
#endif
#if defined(__GNUC__)
    "   GCC compiler detected.\n"
#endif
#if defined(INTEL_CC)
    "   Intel C Compiler detected.\n"
#endif
#if defined(__x86_64__)
    "   x86-64 detected.\n"
#endif
#if defined(LTC_PPC32)
    "   LTC_PPC32 defined \n"
#endif    

    "\nVarious others: "
#if defined(LTC_BASE64)
    " LTC_BASE64 "
#endif
#if defined(MPI)
    " MPI "
#endif
#if defined(TRY_UNRANDOM_FIRST)
    " TRY_UNRANDOM_FIRST "
#endif
#if defined(LTC_TEST)
    " LTC_TEST "
#endif
#if defined(LTC_PKCS_1)
    " LTC_PKCS#1 "
#endif
#if defined(LTC_PKCS_5)
    " LTC_PKCS#5 "
#endif
#if defined(LTC_SMALL_CODE)
    " LTC_SMALL_CODE "
#endif
#if defined(LTC_NO_FILE)
    " LTC_NO_FILE "
#endif
#if defined(LTC_DER)
    " LTC_DER "
#endif
#if defined(LTC_FAST)
    " LTC_FAST "
#endif
#if defined(LTC_NO_FAST)
    " LTC_NO_FAST "
#endif
#if defined(LTC_NO_BSWAP)
    " LTC_NO_BSWAP "
#endif
#if defined(LTC_NO_ASM)
    " LTC_NO_ASM "
#endif
#if defined(LTC_NO_TEST)
    " LTC_NO_TEST "
#endif
#if defined(LTC_NO_TABLES)
    " LTC_NO_TABLES "
#endif
#if defined(LTC_PTHREAD)
    " LTC_PTHREAD "
#endif
#if defined(LTM_LTC_DESC)
    " LTM_DESC "
#endif
#if defined(TFM_LTC_DESC)
    " TFM_DESC "
#endif
#if defined(LTC_MECC_ACCEL)
    " LTC_MECC_ACCEL "
#endif
#if defined(GMP_LTC_DESC)
    " GMP_DESC "
#endif
#if defined(LTC_EASY)
    " (easy) "
#endif    
#if defined(LTC_MECC_FP)
   " LTC_MECC_FP "
#endif
#if defined(LTC_ECC_SHAMIR)
   " LTC_ECC_SHAMIR "
#endif
    "\n"
    "\n\n\n"
    ;


/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt.c,v $ */
/* $Revision: 1.37 $ */
/* $Date: 2007/06/20 13:14:31 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































































































































































































































































































































































































































































































































































































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_argchk.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"
#include <signal.h>

/**
  @file crypt_argchk.c
  Perform argument checking, Tom St Denis
*/  

#if (ARGTYPE == 0)
void crypt_argchk(char *v, char *s, int d)
{
 fprintf(stderr, "LTC_ARGCHK '%s' failure on line %d of file %s\n",
         v, d, s);
 (void)raise(SIGABRT);
}
#endif

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_argchk.c,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































Deleted Source/libtomcrypt/src/misc/crypt/crypt_cipher_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_cipher_descriptor.c
  Stores the cipher descriptor table, Tom St Denis
*/

struct ltc_cipher_descriptor cipher_descriptor[TAB_SIZE] = {
{ NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
 };

LTC_MUTEX_GLOBAL(ltc_cipher_mutex)


/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_cipher_descriptor.c,v $ */
/* $Revision: 1.13 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































Deleted Source/libtomcrypt/src/misc/crypt/crypt_cipher_is_valid.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_cipher_is_valid.c
  Determine if cipher is valid, Tom St Denis
*/

/*
   Test if a cipher index is valid
   @param idx   The index of the cipher to search for
   @return CRYPT_OK if valid
*/
int cipher_is_valid(int idx)
{
   LTC_MUTEX_LOCK(&ltc_cipher_mutex);
   if (idx < 0 || idx >= TAB_SIZE || cipher_descriptor[idx].name == NULL) {
      LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
      return CRYPT_INVALID_CIPHER;
   }
   LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
   return CRYPT_OK;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_cipher_is_valid.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_find_cipher.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_find_cipher.c
  Find a cipher in the descriptor tables, Tom St Denis
*/

/**
   Find a registered cipher by name
   @param name   The name of the cipher to look for
   @return >= 0 if found, -1 if not present
*/
int find_cipher(const char *name)
{
   int x;
   LTC_ARGCHK(name != NULL);
   LTC_MUTEX_LOCK(&ltc_cipher_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (cipher_descriptor[x].name != NULL && !XSTRCMP(cipher_descriptor[x].name, name)) {
          LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
          return x;
       }
   }
   LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
   return -1;
}


/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_find_cipher.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_find_cipher_any.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_find_cipher_any.c
  Find a cipher in the descriptor tables, Tom St Denis
*/

/**
   Find a cipher flexibly.  First by name then if not present by block and key size 
   @param name        The name of the cipher desired
   @param blocklen    The minimum length of the block cipher desired (octets)
   @param keylen      The minimum length of the key size desired (octets)
   @return >= 0 if found, -1 if not present
*/
int find_cipher_any(const char *name, int blocklen, int keylen)
{
   int x;

   LTC_ARGCHK(name != NULL);

   x = find_cipher(name);
   if (x != -1) return x;

   LTC_MUTEX_LOCK(&ltc_cipher_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (cipher_descriptor[x].name == NULL) {
          continue;
       }
       if (blocklen <= (int)cipher_descriptor[x].block_length && keylen <= (int)cipher_descriptor[x].max_key_length) {
          LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
          return x;
       }
   }
   LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
   return -1;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_find_cipher_any.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_find_cipher_id.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_find_cipher_id.c
  Find cipher by ID, Tom St Denis
*/

/**
   Find a cipher by ID number
   @param ID    The ID (not same as index) of the cipher to find
   @return >= 0 if found, -1 if not present
*/
int find_cipher_id(unsigned char ID)
{
   int x;
   LTC_MUTEX_LOCK(&ltc_cipher_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (cipher_descriptor[x].ID == ID) {
          x = (cipher_descriptor[x].name == NULL) ? -1 : x;
          LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
          return x;
       }
   }
   LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
   return -1;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_find_cipher_id.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_find_hash.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_find_hash.c
  Find a hash, Tom St Denis
*/

/**
   Find a registered hash by name
   @param name   The name of the hash to look for
   @return >= 0 if found, -1 if not present
*/
int find_hash(const char *name)
{
   int x;
   LTC_ARGCHK(name != NULL);
   LTC_MUTEX_LOCK(&ltc_hash_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (hash_descriptor[x].name != NULL && XSTRCMP(hash_descriptor[x].name, name) == 0) {
          LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
          return x;
       }
   }
   LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
   return -1;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_find_hash.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_find_hash_any.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_find_hash_any.c
  Find a hash, Tom St Denis
*/

/**
   Find a hash flexibly.  First by name then if not present by digest size 
   @param name        The name of the hash desired
   @param digestlen   The minimum length of the digest size (octets)
   @return >= 0 if found, -1 if not present
*/

int find_hash_any(const char *name, int digestlen)
{
   int x, y, z;
   LTC_ARGCHK(name != NULL);

   x = find_hash(name);
   if (x != -1) return x;

   LTC_MUTEX_LOCK(&ltc_hash_mutex);
   y = MAXBLOCKSIZE+1;
   z = -1;
   for (x = 0; x < TAB_SIZE; x++) {
       if (hash_descriptor[x].name == NULL) {
          continue;
       }
       if ((int)hash_descriptor[x].hashsize >= digestlen && (int)hash_descriptor[x].hashsize < y) {
          z = x;
          y = hash_descriptor[x].hashsize;
       }
   }
   LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
   return z;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_find_hash_any.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_find_hash_id.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_find_hash_id.c
  Find hash by ID, Tom St Denis
*/

/**
   Find a hash by ID number
   @param ID    The ID (not same as index) of the hash to find
   @return >= 0 if found, -1 if not present
*/
int find_hash_id(unsigned char ID)
{
   int x;
   LTC_MUTEX_LOCK(&ltc_hash_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
      if (hash_descriptor[x].ID == ID) {
          x = (hash_descriptor[x].name == NULL) ? -1 : x;
          LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
          return x;
      }
   }
   LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
   return -1;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_find_hash_id.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_find_hash_oid.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_find_hash_oid.c
  Find a hash, Tom St Denis
*/

int find_hash_oid(const unsigned long *ID, unsigned long IDlen)
{
   int x;
   LTC_ARGCHK(ID != NULL);
   LTC_MUTEX_LOCK(&ltc_hash_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (hash_descriptor[x].name != NULL && hash_descriptor[x].OIDlen == IDlen && !XMEMCMP(hash_descriptor[x].OID, ID, sizeof(unsigned long) * IDlen)) {
          LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
          return x;
       }
   }
   LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
   return -1;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_find_hash_oid.c,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_find_prng.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_find_prng.c
  Find a PRNG, Tom St Denis
*/

/**
   Find a registered PRNG by name
   @param name   The name of the PRNG to look for
   @return >= 0 if found, -1 if not present
*/
int find_prng(const char *name)
{
   int x;
   LTC_ARGCHK(name != NULL);
   LTC_MUTEX_LOCK(&ltc_prng_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if ((prng_descriptor[x].name != NULL) && XSTRCMP(prng_descriptor[x].name, name) == 0) {
          LTC_MUTEX_UNLOCK(&ltc_prng_mutex);
          return x;
       }
   }
   LTC_MUTEX_UNLOCK(&ltc_prng_mutex);
   return -1;
}


/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_find_prng.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


















































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_fsa.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"
#include <stdarg.h>

/**
  @file crypt_fsa.c
  LibTomCrypt FULL SPEED AHEAD!, Tom St Denis
*/  

/* format is ltc_mp, cipher_desc, [cipher_desc], NULL, hash_desc, [hash_desc], NULL, prng_desc, [prng_desc], NULL */
int crypt_fsa(void *mp, ...)
{
   int      err;
   va_list  args;
   void     *p;

   va_start(args, mp);
   if (mp != NULL) {
      XMEMCPY(&ltc_mp, mp, sizeof(ltc_mp));
   }
   
   while ((p = va_arg(args, void*)) != NULL) {
      if ((err = register_cipher(p)) != CRYPT_OK) {
         va_end(args);
         return err;
      }
   }

   while ((p = va_arg(args, void*)) != NULL) {
      if ((err = register_hash(p)) != CRYPT_OK) {
         va_end(args);
         return err;
      }
   }

   while ((p = va_arg(args, void*)) != NULL) {
      if ((err = register_prng(p)) != CRYPT_OK) {
         va_end(args);
         return err;
      }
   }

   va_end(args);
   return CRYPT_OK;   
}


/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_fsa.c,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_hash_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_hash_descriptor.c
  Stores the hash descriptor table, Tom St Denis  
*/

struct ltc_hash_descriptor hash_descriptor[TAB_SIZE] = {
{ NULL, 0, 0, 0, { 0 }, 0, NULL, NULL, NULL, NULL, NULL }
};

LTC_MUTEX_GLOBAL(ltc_hash_mutex)


/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_hash_descriptor.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































Deleted Source/libtomcrypt/src/misc/crypt/crypt_hash_is_valid.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_hash_is_valid.c
  Determine if hash is valid, Tom St Denis
*/  

/*
   Test if a hash index is valid
   @param idx   The index of the hash to search for
   @return CRYPT_OK if valid
*/
int hash_is_valid(int idx)
{
   LTC_MUTEX_LOCK(&ltc_hash_mutex);
   if (idx < 0 || idx >= TAB_SIZE || hash_descriptor[idx].name == NULL) {
      LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
      return CRYPT_INVALID_HASH;
   }
   LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
   return CRYPT_OK;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_hash_is_valid.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_ltc_mp_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

ltc_math_descriptor ltc_mp;
<
<
<
<
<
<
<
<
<
<
<
<
<


























Deleted Source/libtomcrypt/src/misc/crypt/crypt_mode_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
 *  crypt_mode_descriptor.c
 *  MacTomCrypt
 */
#include "tomcrypt.h"

/*
 
 This is implemented slightly differently from Tom's cipher descriptor table.  All entries are static and the order and ID match.  Not only that, but the 
 modes advertised by CommonCryptor.h match the IDs and hence the array index.  That's currently defined like this:

enum {
	kCCModeECB		= 1,
	kCCModeCBC		= 2,
	kCCModeCFB		= 3,
	kCCModeCTR		= 4,
	kCCModeF8		= 5, // Not included
	kCCModeLRW		= 6, // Not included
	kCCModeOFB		= 7,
	kCCModeXTS		= 8,
	kCCModeRC4		= 9, // RC4 as a streaming cipher is handled internally as a mode.
};
typedef uint32_t CCMode;

*/

mode_descriptor_ptr mode_descriptor[TAB_SIZE] = {
	&modeUNIMP_desc,
	&modeECB_desc,
	&modeCBC_desc,
	&modeCFB_desc,
	&modeCTR_desc,
	&modeUNIMP_desc,
	&modeUNIMP_desc,
	&modeOFB_desc,
	&modeXTS_desc,
	&modeRC4_desc,
	&modeCFB8_desc,
 };
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_prng_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_prng_descriptor.c
  Stores the PRNG descriptors, Tom St Denis
*/  
struct ltc_prng_descriptor prng_descriptor[TAB_SIZE] = {
{ NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
};

LTC_MUTEX_GLOBAL(ltc_prng_mutex)


/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_prng_descriptor.c,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































Deleted Source/libtomcrypt/src/misc/crypt/crypt_prng_is_valid.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_prng_is_valid.c
  Determine if PRNG is valid, Tom St Denis
*/

/*
   Test if a PRNG index is valid
   @param idx   The index of the PRNG to search for
   @return CRYPT_OK if valid
*/
int prng_is_valid(int idx)
{
   LTC_MUTEX_LOCK(&ltc_prng_mutex);
   if (idx < 0 || idx >= TAB_SIZE || prng_descriptor[idx].name == NULL) {
      LTC_MUTEX_UNLOCK(&ltc_prng_mutex);
      return CRYPT_INVALID_PRNG;
   }
   LTC_MUTEX_UNLOCK(&ltc_prng_mutex);
   return CRYPT_OK;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_prng_is_valid.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_register_cipher.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_register_cipher.c
  Register a cipher, Tom St Denis
*/

/**
   Register a cipher with the descriptor table
   @param cipher   The cipher you wish to register
   @return value >= 0 if successfully added (or already present), -1 if unsuccessful
*/
int register_cipher(const struct ltc_cipher_descriptor *cipher)
{
   int x;

   LTC_ARGCHK(cipher != NULL);

   /* is it already registered? */
   LTC_MUTEX_LOCK(&ltc_cipher_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (cipher_descriptor[x].name != NULL && cipher_descriptor[x].ID == cipher->ID) {
          LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
          return x;
       }
   }

   /* find a blank spot */
   for (x = 0; x < TAB_SIZE; x++) {
       if (cipher_descriptor[x].name == NULL) {
          XMEMCPY(&cipher_descriptor[x], cipher, sizeof(struct ltc_cipher_descriptor));
          LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
          return x;
       }
   }

   /* no spot */
   LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
   return -1;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_register_cipher.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_register_hash.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_register_hash.c
  Register a HASH, Tom St Denis
*/

/**
   Register a hash with the descriptor table
   @param hash   The hash you wish to register
   @return value >= 0 if successfully added (or already present), -1 if unsuccessful
*/
int register_hash(const struct ltc_hash_descriptor *hash)
{
   int x;

   LTC_ARGCHK(hash != NULL);

   /* is it already registered? */
   LTC_MUTEX_LOCK(&ltc_hash_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (XMEMCMP(&hash_descriptor[x], hash, sizeof(struct ltc_hash_descriptor)) == 0) {
          LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
          return x;
       }
   }

   /* find a blank spot */
   for (x = 0; x < TAB_SIZE; x++) {
       if (hash_descriptor[x].name == NULL) {
         XMEMCPY(&hash_descriptor[x], hash, sizeof(struct ltc_hash_descriptor));
          LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
          return x;
       }
   }
   /* no spot */
   LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
   return -1;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_register_hash.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_register_prng.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_register_prng.c
  Register a PRNG, Tom St Denis
*/
  
/**
   Register a PRNG with the descriptor table
   @param prng   The PRNG you wish to register
   @return value >= 0 if successfully added (or already present), -1 if unsuccessful
*/
int register_prng(const struct ltc_prng_descriptor *prng)
{
   int x;

   LTC_ARGCHK(prng != NULL);

   /* is it already registered? */
   LTC_MUTEX_LOCK(&ltc_prng_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (XMEMCMP(&prng_descriptor[x], prng, sizeof(struct ltc_prng_descriptor)) == 0) {
          LTC_MUTEX_UNLOCK(&ltc_prng_mutex);
          return x;
       }
   }

   /* find a blank spot */
   for (x = 0; x < TAB_SIZE; x++) {
       if (prng_descriptor[x].name == NULL) {
          XMEMCPY(&prng_descriptor[x], prng, sizeof(struct ltc_prng_descriptor));
          LTC_MUTEX_UNLOCK(&ltc_prng_mutex);
          return x;
       }
   }

   /* no spot */
   LTC_MUTEX_UNLOCK(&ltc_prng_mutex);
   return -1;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_register_prng.c,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_unregister_cipher.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_unregister_cipher.c
  Unregister a cipher, Tom St Denis
*/

/**
  Unregister a cipher from the descriptor table
  @param cipher   The cipher descriptor to remove
  @return CRYPT_OK on success
*/
int unregister_cipher(const struct ltc_cipher_descriptor *cipher)
{
   int x;

   LTC_ARGCHK(cipher != NULL);

   /* is it already registered? */
   LTC_MUTEX_LOCK(&ltc_cipher_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (XMEMCMP(&cipher_descriptor[x], cipher, sizeof(struct ltc_cipher_descriptor)) == 0) {
          cipher_descriptor[x].name = NULL;
          cipher_descriptor[x].ID   = 255;
          LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
          return CRYPT_OK;
       }
   }
   LTC_MUTEX_UNLOCK(&ltc_cipher_mutex);
   return CRYPT_ERROR;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_unregister_cipher.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_unregister_hash.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_unregister_hash.c
  Unregister a hash, Tom St Denis
*/

/**
  Unregister a hash from the descriptor table
  @param hash   The hash descriptor to remove
  @return CRYPT_OK on success
*/
int unregister_hash(const struct ltc_hash_descriptor *hash)
{
   int x;

   LTC_ARGCHK(hash != NULL);

   /* is it already registered? */
   LTC_MUTEX_LOCK(&ltc_hash_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (XMEMCMP(&hash_descriptor[x], hash, sizeof(struct ltc_hash_descriptor)) == 0) {
          hash_descriptor[x].name = NULL;
          LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
          return CRYPT_OK;
       }
   }
   LTC_MUTEX_UNLOCK(&ltc_hash_mutex);
   return CRYPT_ERROR;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_unregister_hash.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































Deleted Source/libtomcrypt/src/misc/crypt/crypt_unregister_prng.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file crypt_unregister_prng.c
  Unregister a PRNG, Tom St Denis
*/

/**
  Unregister a PRNG from the descriptor table
  @param prng   The PRNG descriptor to remove
  @return CRYPT_OK on success
*/
int unregister_prng(const struct ltc_prng_descriptor *prng)
{
   int x;

   LTC_ARGCHK(prng != NULL);
 
   /* is it already registered? */
   LTC_MUTEX_LOCK(&ltc_prng_mutex);
   for (x = 0; x < TAB_SIZE; x++) {
       if (XMEMCMP(&prng_descriptor[x], prng, sizeof(struct ltc_prng_descriptor)) != 0) {
          prng_descriptor[x].name = NULL;
          LTC_MUTEX_UNLOCK(&ltc_prng_mutex);
          return CRYPT_OK;
       }
   }
   LTC_MUTEX_UNLOCK(&ltc_prng_mutex);
   return CRYPT_ERROR;
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/crypt/crypt_unregister_prng.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































Deleted Source/libtomcrypt/src/misc/error_to_string.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */

#include "tomcrypt.h"

/**
  @file error_to_string.c
  Convert error codes to ASCII strings, Tom St Denis
*/

static const char *err_2_str[] =
{
   "CRYPT_OK",
   "CRYPT_ERROR",
   "Non-fatal 'no-operation' requested.",

   "Invalid keysize for block cipher.",
   "Invalid number of rounds for block cipher.",
   "Algorithm failed test vectors.",

   "Buffer overflow.",
   "Invalid input packet.",

   "Invalid number of bits for a PRNG.",
   "Error reading the PRNG.",

   "Invalid cipher specified.",
   "Invalid hash specified.",
   "Invalid PRNG specified.",

   "Out of memory.",

   "Invalid PK key or key type specified for function.",
   "A private PK key is required.",

   "Invalid argument provided.",
   "File Not Found",

   "Invalid PK type.",
   "Invalid PK system.",
   "Duplicate PK key found on keyring.",
   "Key not found in keyring.",
   "Invalid sized parameter.",

   "Invalid size for prime.",

   "Invalid padding.",

   "Hash applied to too many bits.",
};

/**
   Convert an LTC error code to ASCII
   @param err    The error code
   @return A pointer to the ASCII NUL terminated string for the error or "Invalid error code." if the err code was not valid.
*/
const char *error_to_string(int err)
{
   if (err < 0 || err >= (int)(sizeof(err_2_str)/sizeof(err_2_str[0]))) {
      return "Invalid error code.";
   } else {
      return err_2_str[err];
   }   
}


/* $Source: /cvs/libtom/libtomcrypt/src/misc/error_to_string.c,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































































Deleted Source/libtomcrypt/src/misc/pkcs5/pkcs_5_1.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <tomcrypt.h>

/** 
   @file pkcs_5_1.c
   LTC_PKCS #5, Algorithm #1, Tom St Denis
*/
#ifdef LTC_PKCS_5
/**
   Execute LTC_PKCS #5 v1
   @param password         The password (or key)
   @param password_len     The length of the password (octet)
   @param salt             The salt (or nonce) which is 8 octets long
   @param iteration_count  The LTC_PKCS #5 v1 iteration count
   @param hash_idx         The index of the hash desired
   @param out              [out] The destination for this algorithm
   @param outlen           [in/out] The max size and resulting size of the algorithm output
   @return CRYPT_OK if successful
*/
int pkcs_5_alg1(const unsigned char *password, unsigned long password_len, 
                const unsigned char *salt, 
                int iteration_count,  int hash_idx,
                unsigned char *out,   unsigned long *outlen)
{
   int err;
   unsigned long x;
   hash_state    *md;
   unsigned char *buf;

   LTC_ARGCHK(password != NULL);
   LTC_ARGCHK(salt     != NULL);
   LTC_ARGCHK(out      != NULL);
   LTC_ARGCHK(outlen   != NULL);

   /* test hash IDX */
   if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
      return err;
   }

   /* allocate memory */
   md  = XMALLOC(sizeof(hash_state));
   buf = XMALLOC(MAXBLOCKSIZE);
   if (md == NULL || buf == NULL) {
      if (md != NULL) {
         XFREE(md);
      }
      if (buf != NULL) { 
         XFREE(buf);
      }
      return CRYPT_MEM;
   }        

   /* hash initial password + salt */
   if ((err = hash_descriptor[hash_idx].init(md)) != CRYPT_OK) {
       goto LBL_ERR;
   }
   if ((err = hash_descriptor[hash_idx].process(md, password, password_len)) != CRYPT_OK) {
       goto LBL_ERR;
   }
   if ((err = hash_descriptor[hash_idx].process(md, salt, 8)) != CRYPT_OK) {
       goto LBL_ERR;
   }
   if ((err = hash_descriptor[hash_idx].done(md, buf)) != CRYPT_OK) {
       goto LBL_ERR;
   }

   while (--iteration_count) {
      /* code goes here. */
      x = MAXBLOCKSIZE;
      if ((err = hash_memory(hash_idx, buf, hash_descriptor[hash_idx].hashsize, buf, &x)) != CRYPT_OK) {
         goto LBL_ERR;
      }
   }

   /* copy upto outlen bytes */
   for (x = 0; x < hash_descriptor[hash_idx].hashsize && x < *outlen; x++) {
       out[x] = buf[x];
   }
   *outlen = x;
   err = CRYPT_OK;
LBL_ERR:
#ifdef LTC_CLEAN_STACK 
   zeromem(buf, MAXBLOCKSIZE);
   zeromem(md, sizeof(hash_state));
#endif

   XFREE(buf);
   XFREE(md);

   return err;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/misc/pkcs5/pkcs_5_1.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2007/05/12 14:32:35 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































































Deleted Source/libtomcrypt/src/misc/pkcs5/pkcs_5_2.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include <tomcrypt.h>

/** 
   @file pkcs_5_2.c
   LTC_PKCS #5, Algorithm #2, Tom St Denis
*/
#ifdef LTC_PKCS_5

/**
   Execute LTC_PKCS #5 v2
   @param password          The input password (or key)
   @param password_len      The length of the password (octets)
   @param salt              The salt (or nonce)
   @param salt_len          The length of the salt (octets)
   @param iteration_count   # of iterations desired for LTC_PKCS #5 v2 [read specs for more]
   @param hash_idx          The index of the hash desired
   @param out               [out] The destination for this algorithm
   @param outlen            [in/out] The max size and resulting size of the algorithm output
   @return CRYPT_OK if successful
*/
int pkcs_5_alg2(const unsigned char *password, unsigned long password_len, 
                const unsigned char *salt,     unsigned long salt_len,
                int iteration_count,           int hash_idx,
                unsigned char *out,            unsigned long *outlen)
{
   int err, itts;
   ulong32  blkno;
   unsigned long stored, left, x, y;
   unsigned char *buf[2];
   hmac_state    *hmac;

   LTC_ARGCHK(password != NULL);
   LTC_ARGCHK(salt     != NULL);
   LTC_ARGCHK(out      != NULL);
   LTC_ARGCHK(outlen   != NULL);

   /* test hash IDX */
   if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
      return err;
   }

   buf[0] = XMALLOC(MAXBLOCKSIZE * 2);
   hmac   = XMALLOC(sizeof(hmac_state));
   if (hmac == NULL || buf[0] == NULL) {
      if (hmac != NULL) {
         XFREE(hmac);
      }
      if (buf[0] != NULL) {
         XFREE(buf[0]);
      }
      return CRYPT_MEM;
   }
   /* buf[1] points to the second block of MAXBLOCKSIZE bytes */
   buf[1] = buf[0] + MAXBLOCKSIZE;

   left   = *outlen;
   blkno  = 1;
   stored = 0;
   while (left != 0) {
       /* process block number blkno */
       zeromem(buf[0], MAXBLOCKSIZE*2);
       
       /* store current block number and increment for next pass */
       STORE32H(blkno, buf[1]);
       ++blkno;

       /* get PRF(P, S||int(blkno)) */
       if ((err = hmac_init(hmac, hash_idx, password, password_len)) != CRYPT_OK) { 
          goto LBL_ERR;
       }
       if ((err = hmac_process(hmac, salt, salt_len)) != CRYPT_OK) {
          goto LBL_ERR;
       }
       if ((err = hmac_process(hmac, buf[1], 4)) != CRYPT_OK) {
          goto LBL_ERR;
       }
       x = MAXBLOCKSIZE;
       if ((err = hmac_done(hmac, buf[0], &x)) != CRYPT_OK) {
          goto LBL_ERR;
       }

       /* now compute repeated and XOR it in buf[1] */
       XMEMCPY(buf[1], buf[0], x);
       for (itts = 1; itts < iteration_count; ++itts) {
           if ((err = hmac_memory(hash_idx, password, password_len, buf[0], x, buf[0], &x)) != CRYPT_OK) {
              goto LBL_ERR;
           }
           for (y = 0; y < x; y++) {
               buf[1][y] ^= buf[0][y];
           }
       }

       /* now emit upto x bytes of buf[1] to output */
       for (y = 0; y < x && left != 0; ++y) {
           out[stored++] = buf[1][y];
           --left;
       }
   }
   *outlen = stored;

   err = CRYPT_OK;
LBL_ERR:
#ifdef LTC_CLEAN_STACK
   zeromem(buf[0], MAXBLOCKSIZE*2);
   zeromem(hmac, sizeof(hmac_state));
#endif

   XFREE(hmac);
   XFREE(buf[0]);

   return err;
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/misc/pkcs5/pkcs_5_2.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2007/05/12 14:32:35 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































Deleted Source/libtomcrypt/src/misc/zeromem.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file zeromem.c
   Zero a block of memory, Tom St Denis
*/

/**
   Zero a block of memory
   @param out    The destination of the area to zero
   @param outlen The length of the area to zero (octets)
*/
void zeromem(void *out, size_t outlen)
{
   unsigned char *mem = out;
   LTC_ARGCHKVD(out != NULL);
   while (outlen-- > 0) {
      *mem++ = 0;
   }
}

/* $Source: /cvs/libtom/libtomcrypt/src/misc/zeromem.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































Deleted Source/libtomcrypt/src/modes/cbc/cbc_decrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cbc_decrypt.c
   CBC implementation, encrypt block, Tom St Denis
*/


#ifdef LTC_CBC_MODE

/**
  CBC decrypt
  @param ct     Ciphertext
  @param pt     [out] Plaintext
  @param len    The number of bytes to process (must be multiple of block length)
  @param cbc    CBC state
  @return CRYPT_OK if successful
*/
int cbc_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CBC *cbc)
{
   int x, err;
   unsigned char tmp[16];
#ifdef LTC_FAST
   LTC_FAST_TYPE tmpy;
#else
   unsigned char tmpy;
#endif         

   LTC_ARGCHK(pt  != NULL);
   LTC_ARGCHK(ct  != NULL);
   LTC_ARGCHK(cbc != NULL);

   if ((err = cipher_is_valid(cbc->cipher)) != CRYPT_OK) {
       return err;
   }

    /* is blocklen valid? */
   if (cbc->blocklen < 1 || cbc->blocklen > (int)sizeof(cbc->IV)) {
      return CRYPT_INVALID_ARG;
   }    

   if (len % cbc->blocklen) {
      return CRYPT_INVALID_ARG;
   }
#ifdef LTC_FAST
   if (cbc->blocklen % sizeof(LTC_FAST_TYPE)) {   
      return CRYPT_INVALID_ARG;
   }
#endif
   
   if (cipher_descriptor[cbc->cipher].accel_cbc_decrypt != NULL) {
      return cipher_descriptor[cbc->cipher].accel_cbc_decrypt(ct, pt, len / cbc->blocklen, cbc->IV, &cbc->key);
   } else {
      while (len) {
         /* decrypt */
         if ((err = cipher_descriptor[cbc->cipher].ecb_decrypt(ct, tmp, &cbc->key)) != CRYPT_OK) {
            return err;
         }

         /* xor IV against plaintext */
         #if defined(LTC_FAST)
        for (x = 0; x < cbc->blocklen; x += sizeof(LTC_FAST_TYPE)) {
            tmpy = *((LTC_FAST_TYPE*)((unsigned char *)cbc->IV + x)) ^ *((LTC_FAST_TYPE*)((unsigned char *)tmp + x));
       *((LTC_FAST_TYPE*)((unsigned char *)cbc->IV + x)) = *((LTC_FAST_TYPE*)((unsigned char *)ct + x));
       *((LTC_FAST_TYPE*)((unsigned char *)pt + x)) = tmpy;
        }
    #else 
            for (x = 0; x < cbc->blocklen; x++) {
               tmpy       = tmp[x] ^ cbc->IV[x];
               cbc->IV[x] = ct[x];
               pt[x]      = tmpy;
            }
    #endif
       
         ct  += cbc->blocklen;
         pt  += cbc->blocklen;
         len -= cbc->blocklen;
      }
   }
   return CRYPT_OK;
}

int cbc_decrypt_tweaked(const unsigned char *ct, unsigned long len, unsigned char *pt, const unsigned char *tweak, symmetric_CBC *cbc)
{
    (void) cbc_setiv(tweak, cbc->blocklen, cbc);
    return cbc_decrypt(ct, pt, len, cbc);
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cbc/cbc_decrypt.c,v $ */
/* $Revision: 1.16 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































Deleted Source/libtomcrypt/src/modes/cbc/cbc_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
 *  cbc_descriptor.c
 *  MacTomCrypt
 */

#include "tomcrypt.h"
#if defined(LTC_CBC_MODE) && defined(MACTOMCRYPT)

const struct ltc_mode_descriptor modeCBC_desc =
{
	"CBC",
	2,	/* Must match 	kCCModeCBC = 2 */
	1,
	sizeof(symmetric_CBC),
	&cbc_start,
	&cbc_encrypt, 
	&cbc_decrypt, 
	&cbc_encrypt_tweaked, 
	&cbc_decrypt_tweaked, 
	&cbc_done, 
	&cbc_setiv,
	&cbc_getiv,
};
#endif /* LTC_CBC_MODE */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/libtomcrypt/src/modes/cbc/cbc_done.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cbc_done.c
   CBC implementation, finish chain, Tom St Denis
*/

#ifdef LTC_CBC_MODE

/** Terminate the chain
  @param cbc    The CBC chain to terminate
  @return CRYPT_OK on success
*/
int cbc_done(symmetric_CBC *cbc)
{
   int err;
   LTC_ARGCHK(cbc != NULL);

   if ((err = cipher_is_valid(cbc->cipher)) != CRYPT_OK) {
      return err;
   }
   cipher_descriptor[cbc->cipher].done(&cbc->key);
   return CRYPT_OK;
}

   

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cbc/cbc_done.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































Deleted Source/libtomcrypt/src/modes/cbc/cbc_encrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cbc_encrypt.c
   CBC implementation, encrypt block, Tom St Denis
*/


#ifdef LTC_CBC_MODE

/**
  CBC encrypt
  @param pt     Plaintext
  @param ct     [out] Ciphertext
  @param len    The number of bytes to process (must be multiple of block length)
  @param cbc    CBC state
  @return CRYPT_OK if successful
*/
int cbc_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CBC *cbc)
{
   int x, err;

   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(cbc != NULL);

   if ((err = cipher_is_valid(cbc->cipher)) != CRYPT_OK) {
       return err;
   }
   
    /* is blocklen valid? */
   if (cbc->blocklen < 1 || cbc->blocklen > (int)sizeof(cbc->IV)) {
      return CRYPT_INVALID_ARG;
   }    

   if (len % cbc->blocklen) {
      return CRYPT_INVALID_ARG;
   }
#ifdef LTC_FAST
   if (cbc->blocklen % sizeof(LTC_FAST_TYPE)) {   
      return CRYPT_INVALID_ARG;
   }
#endif

   if (cipher_descriptor[cbc->cipher].accel_cbc_encrypt != NULL) {
      return cipher_descriptor[cbc->cipher].accel_cbc_encrypt(pt, ct, len / cbc->blocklen, cbc->IV, &cbc->key);
   } else {
      while (len) {
         /* xor IV against plaintext */
         #if defined(LTC_FAST)
        for (x = 0; x < cbc->blocklen; x += sizeof(LTC_FAST_TYPE)) {
            *((LTC_FAST_TYPE*)((unsigned char *)cbc->IV + x)) ^= *((LTC_FAST_TYPE*)((unsigned char *)pt + x));
        }
    #else 
            for (x = 0; x < cbc->blocklen; x++) {
               cbc->IV[x] ^= pt[x];
            }
    #endif

         /* encrypt */
         if ((err = cipher_descriptor[cbc->cipher].ecb_encrypt(cbc->IV, ct, &cbc->key)) != CRYPT_OK) {
            return err;
         }

        /* store IV [ciphertext] for a future block */
         #if defined(LTC_FAST)
        for (x = 0; x < cbc->blocklen; x += sizeof(LTC_FAST_TYPE)) {
            *((LTC_FAST_TYPE*)((unsigned char *)cbc->IV + x)) = *((LTC_FAST_TYPE*)((unsigned char *)ct + x));
        }
    #else 
             for (x = 0; x < cbc->blocklen; x++) {
                cbc->IV[x] = ct[x];
             }
    #endif
        
        ct  += cbc->blocklen;
        pt  += cbc->blocklen;
        len -= cbc->blocklen;
     }
   }
   return CRYPT_OK;
}

int cbc_encrypt_tweaked(const unsigned char *pt, unsigned long len, unsigned char *ct, const unsigned char *tweak, symmetric_CBC *cbc)
{
    (void) cbc_setiv(tweak, cbc->blocklen, cbc);
    return cbc_encrypt(pt, ct, len, cbc);
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cbc/cbc_encrypt.c,v $ */
/* $Revision: 1.14 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































































































































Deleted Source/libtomcrypt/src/modes/cbc/cbc_getiv.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cbc_getiv.c
   CBC implementation, get IV, Tom St Denis
*/

#ifdef LTC_CBC_MODE

/**
   Get the current initial vector
   @param IV   [out] The destination of the initial vector
   @param len  [in/out]  The max size and resulting size of the initial vector
   @param cbc  The CBC state
   @return CRYPT_OK if successful
*/
int cbc_getiv(unsigned char *IV, unsigned long *len, symmetric_CBC *cbc)
{
   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(len != NULL);
   LTC_ARGCHK(cbc != NULL);
   if ((unsigned long)cbc->blocklen > *len) {
      *len = cbc->blocklen;
      return CRYPT_BUFFER_OVERFLOW;
   }
   XMEMCPY(IV, cbc->IV, cbc->blocklen);
   *len = cbc->blocklen;

   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cbc/cbc_getiv.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/libtomcrypt/src/modes/cbc/cbc_setiv.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cbc_setiv.c
   CBC implementation, set IV, Tom St Denis
*/


#ifdef LTC_CBC_MODE

/**
   Set an initial vector
   @param IV   The initial vector
   @param len  The length of the vector (in octets)
   @param cbc  The CBC state
   @return CRYPT_OK if successful
*/
int cbc_setiv(const unsigned char *IV, unsigned long len, symmetric_CBC *cbc)
{
   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(cbc != NULL);
   if (len != (unsigned long)cbc->blocklen) {
      return CRYPT_INVALID_ARG;
   }
   XMEMCPY(cbc->IV, IV, len);
   return CRYPT_OK;
}

#endif 


/* $Source: /cvs/libtom/libtomcrypt/src/modes/cbc/cbc_setiv.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































Deleted Source/libtomcrypt/src/modes/cbc/cbc_start.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cbc_start.c
   CBC implementation, start chain, Tom St Denis
*/

#ifdef LTC_CBC_MODE

/**
   Initialize a CBC context
   @param cipher      The index of the cipher desired
   @param IV          The initial vector
   @param key         The secret key 
   @param keylen      The length of the secret key (octets)
   @param num_rounds  Number of rounds in the cipher desired (0 for default)
   @param cbc         The CBC state to initialize
   @return CRYPT_OK if successful
*/
#ifdef MACTOMCRYPT
int cbc_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
	const unsigned char *tweak, int tweaklen, int num_rounds, int options, symmetric_CBC *cbc)
#else
int cbc_start(int cipher, const unsigned char *IV, const unsigned char *key, 
              int keylen, int num_rounds, symmetric_CBC *cbc)
#endif
{
   int x, err;
 
   LTC_ARGCHK(IV != NULL);
   LTC_ARGCHK(key != NULL);
   LTC_ARGCHK(cbc != NULL);

   /* bad param? */
   if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
      return err;
   }

   /* setup cipher */
   if ((err = cipher_descriptor[cipher].setup(key, keylen, num_rounds, &cbc->key)) != CRYPT_OK) {
      return err;
   }

   /* copy IV */
   cbc->blocklen = cipher_descriptor[cipher].block_length;
   cbc->cipher   = cipher;
   for (x = 0; x < cbc->blocklen; x++) {
       cbc->IV[x] = IV[x];
   }
   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cbc/cbc_start.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































Deleted Source/libtomcrypt/src/modes/cfb/cfb_decrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file cfb_decrypt.c
  CFB implementation, decrypt data, Tom St Denis
*/

#ifdef LTC_CFB_MODE

/**
   CFB decrypt
   @param ct      Ciphertext
   @param pt      [out] Plaintext
   @param len     Length of ciphertext (octets)
   @param cfb     CFB state
   @return CRYPT_OK if successful
*/
int cfb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CFB *cfb)
{
   int err;

   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(cfb != NULL);

   if ((err = cipher_is_valid(cfb->cipher)) != CRYPT_OK) {
       return err;
   }

   /* is blocklen/padlen valid? */
   if (cfb->blocklen < 0 || cfb->blocklen > (int)sizeof(cfb->IV) ||
       cfb->padlen   < 0 || cfb->padlen   > (int)sizeof(cfb->pad)) {
      return CRYPT_INVALID_ARG;
   }

   while (len-- > 0) {
       if (cfb->padlen == cfb->blocklen) {
          if ((err = cipher_descriptor[cfb->cipher].ecb_encrypt(cfb->pad, cfb->IV, &cfb->key)) != CRYPT_OK) {
             return err;
          }
          cfb->padlen = 0;
       }
       cfb->pad[cfb->padlen] = *ct;
       *pt = *ct ^ cfb->IV[cfb->padlen];
       ++pt; 
       ++ct;
       ++(cfb->padlen);
   }
   return CRYPT_OK;
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_decrypt.c,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































Deleted Source/libtomcrypt/src/modes/cfb/cfb_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
 *  cfb_descriptor.c
 *  MacTomCrypt
 */

#include "tomcrypt.h"
#if defined(LTC_CFB_MODE) && defined(MACTOMCRYPT)

const struct ltc_mode_descriptor modeCFB_desc =
{
	"CFB",
	3,   /* Must match 	kCCModeCFB = 3 */
	1,
	sizeof(symmetric_CFB),
	&cfb_start,
	&cfb_encrypt, 
	&cfb_decrypt, 
	&unimp_mode_encrypt_tweaked, 
	&unimp_mode_decrypt_tweaked, 
	&cfb_done, 
	&cfb_setiv,
	&cfb_getiv,
};
#endif /* LTC_CFB_MODE */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/libtomcrypt/src/modes/cfb/cfb_done.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cfb_done.c
   CFB implementation, finish chain, Tom St Denis
*/

#ifdef LTC_CFB_MODE

/** Terminate the chain
  @param cfb    The CFB chain to terminate
  @return CRYPT_OK on success
*/
int cfb_done(symmetric_CFB *cfb)
{
   int err;
   LTC_ARGCHK(cfb != NULL);

   if ((err = cipher_is_valid(cfb->cipher)) != CRYPT_OK) {
      return err;
   }
   cipher_descriptor[cfb->cipher].done(&cfb->key);
   return CRYPT_OK;
}

   

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_done.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































Deleted Source/libtomcrypt/src/modes/cfb/cfb_encrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file cfb_encrypt.c
  CFB implementation, encrypt data, Tom St Denis
*/

#ifdef LTC_CFB_MODE

/**
  CFB encrypt
  @param pt     Plaintext
  @param ct     [out] Ciphertext
  @param len    Length of plaintext (octets)
  @param cfb    CFB state
  @return CRYPT_OK if successful
*/
int cfb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CFB *cfb)
{
   int err;

   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(cfb != NULL);

   if ((err = cipher_is_valid(cfb->cipher)) != CRYPT_OK) {
       return err;
   }

   /* is blocklen/padlen valid? */
   if (cfb->blocklen < 0 || cfb->blocklen > (int)sizeof(cfb->IV) ||
       cfb->padlen   < 0 || cfb->padlen   > (int)sizeof(cfb->pad)) {
      return CRYPT_INVALID_ARG;
   }

   while (len-- > 0) {
       if (cfb->padlen == cfb->blocklen) {
          if ((err = cipher_descriptor[cfb->cipher].ecb_encrypt(cfb->pad, cfb->IV, &cfb->key)) != CRYPT_OK) {
             return err;
          }
          cfb->padlen = 0;
       }
       cfb->pad[cfb->padlen] = (*ct = *pt ^ cfb->IV[cfb->padlen]);
       ++pt; 
       ++ct;
       ++(cfb->padlen);
   }
   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_encrypt.c,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































Deleted Source/libtomcrypt/src/modes/cfb/cfb_getiv.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cfb_getiv.c
   CFB implementation, get IV, Tom St Denis
*/

#ifdef LTC_CFB_MODE

/**
   Get the current initial vector
   @param IV   [out] The destination of the initial vector
   @param len  [in/out]  The max size and resulting size of the initial vector
   @param cfb  The CFB state
   @return CRYPT_OK if successful
*/
int cfb_getiv(unsigned char *IV, unsigned long *len, symmetric_CFB *cfb)
{
   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(len != NULL);
   LTC_ARGCHK(cfb != NULL);
   if ((unsigned long)cfb->blocklen > *len) {
      *len = cfb->blocklen;
      return CRYPT_BUFFER_OVERFLOW;
   }
   XMEMCPY(IV, cfb->IV, cfb->blocklen);
   *len = cfb->blocklen;

   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_getiv.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/libtomcrypt/src/modes/cfb/cfb_setiv.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file cfb_setiv.c
  CFB implementation, set IV, Tom St Denis
*/  

#ifdef LTC_CFB_MODE

/**
   Set an initial vector
   @param IV   The initial vector
   @param len  The length of the vector (in octets)
   @param cfb  The CFB state
   @return CRYPT_OK if successful
*/
int cfb_setiv(const unsigned char *IV, unsigned long len, symmetric_CFB *cfb)
{
   int err;
   
   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(cfb != NULL);

   if ((err = cipher_is_valid(cfb->cipher)) != CRYPT_OK) {
       return err;
   }
   
   if (len != (unsigned long)cfb->blocklen) {
      return CRYPT_INVALID_ARG;
   }
      
   /* force next block */
   cfb->padlen = 0;
   return cipher_descriptor[cfb->cipher].ecb_encrypt(IV, cfb->IV, &cfb->key);
}

#endif 


/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_setiv.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































Deleted Source/libtomcrypt/src/modes/cfb/cfb_start.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cfb_start.c
   CFB implementation, start chain, Tom St Denis
*/


#ifdef LTC_CFB_MODE

/**
   Initialize a CFB context
   @param cipher      The index of the cipher desired
   @param IV          The initial vector
   @param key         The secret key 
   @param keylen      The length of the secret key (octets)
   @param num_rounds  Number of rounds in the cipher desired (0 for default)
   @param cfb         The CFB state to initialize
   @return CRYPT_OK if successful
*/
#ifdef MACTOMCRYPT
int cfb_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *tweak, int tweaklen,
	int num_rounds, int options, symmetric_CFB *cfb)
#else
int cfb_start(int cipher, const unsigned char *IV, const unsigned char *key, 
              int keylen, int num_rounds, symmetric_CFB *cfb)
#endif
{
   int x, err;

   LTC_ARGCHK(IV != NULL);
   LTC_ARGCHK(key != NULL);
   LTC_ARGCHK(cfb != NULL);

   if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
      return err;
   }
   

   /* copy data */
   cfb->cipher = cipher;
   cfb->blocklen = cipher_descriptor[cipher].block_length;
   for (x = 0; x < cfb->blocklen; x++)
       cfb->IV[x] = IV[x];

   /* init the cipher */
   if ((err = cipher_descriptor[cipher].setup(key, keylen, num_rounds, &cfb->key)) != CRYPT_OK) {
      return err;
   }

   /* encrypt the IV */
   cfb->padlen = 0;
   return cipher_descriptor[cfb->cipher].ecb_encrypt(cfb->IV, cfb->IV, &cfb->key);
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_start.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































Deleted Source/libtomcrypt/src/modes/cfb8/cfb8_decrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file cfb_decrypt.c
  CFB implementation, decrypt data, Tom St Denis
*/

#ifdef LTC_CFB_MODE

/**
   CFB decrypt
   @param ct      Ciphertext
   @param pt      [out] Plaintext
   @param len     Length of ciphertext (octets)
   @param cfb     CFB state
   @return CRYPT_OK if successful
*/
int cfb8_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CFB *cfb)
{
    int err;
    unsigned char *theIV;
    int ivSize;
    
    LTC_ARGCHK(pt != NULL);
    LTC_ARGCHK(ct != NULL);
    LTC_ARGCHK(cfb != NULL);
    
    theIV = (unsigned char *) cfb->IV;
    ivSize = cfb->blocklen;
        
    if ((err = cipher_is_valid(cfb->cipher)) != CRYPT_OK)  return err;
    
    if (cfb->blocklen < 0 || cfb->blocklen > ivSize) return CRYPT_INVALID_ARG;
    
    while (len-- > 0) {
        // XOR the plaintext byte *ct with the leftmost byte of the IV buffer giving *pt
        *pt = cfb->pad[0] ^ *ct;
        // Rotate the IV Buffer left one byte
        memmove(theIV, theIV+1, ivSize-1);
        // copy *ct into the rightmost byte of the IV buffer 
        theIV[ivSize - 1] = *ct;
        // Encrypt the IV buffer
        if ((err = cipher_descriptor[cfb->cipher].ecb_encrypt(cfb->IV, cfb->pad, &cfb->key)) != CRYPT_OK) return err;
        // Bump the pointers
        ++pt; 
        ++ct;
    }
    return CRYPT_OK;
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_decrypt.c,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































Deleted Source/libtomcrypt/src/modes/cfb8/cfb8_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
 *  cfb_descriptor.c
 *  MacTomCrypt
 */

#include "tomcrypt.h"
#if defined(LTC_CFB_MODE) && defined(MACTOMCRYPT)

const struct ltc_mode_descriptor modeCFB8_desc =
{
	"CFB8",
	10,   /* Must match 	kCCModeCFB = 3 */
	1,
	sizeof(symmetric_CFB),
	&cfb8_start,
	&cfb8_encrypt, 
	&cfb8_decrypt, 
	&unimp_mode_encrypt_tweaked, 
	&unimp_mode_decrypt_tweaked, 
	&cfb8_done, 
	&cfb8_setiv,
	&cfb8_getiv,
};
#endif /* LTC_CFB_MODE */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/libtomcrypt/src/modes/cfb8/cfb8_done.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cfb_done.c
   CFB implementation, finish chain, Tom St Denis
*/

#ifdef LTC_CFB_MODE

/** Terminate the chain
  @param cfb    The CFB chain to terminate
  @return CRYPT_OK on success
*/
int cfb8_done(symmetric_CFB *cfb)
{
   int err;
   LTC_ARGCHK(cfb != NULL);

   if ((err = cipher_is_valid(cfb->cipher)) != CRYPT_OK) {
      return err;
   }
   cipher_descriptor[cfb->cipher].done(&cfb->key);
   return CRYPT_OK;
}

   

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_done.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































Deleted Source/libtomcrypt/src/modes/cfb8/cfb8_encrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file cfb_encrypt.c
  CFB implementation, encrypt data, Tom St Denis
*/

#ifdef LTC_CFB_MODE


/**
  CFB8 encrypt
  @param pt     Plaintext
  @param ct     [out] Ciphertext
  @param len    Length of plaintext (octets)
  @param cfb    CFB state
  @return CRYPT_OK if successful
*/

int cfb8_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CFB *cfb)
{
    int err;
    unsigned char *theIV;
    int ivSize;

    LTC_ARGCHK(pt != NULL);
    LTC_ARGCHK(ct != NULL);
    LTC_ARGCHK(cfb != NULL);

    theIV = (unsigned char *) cfb->IV;
    ivSize = cfb->blocklen;

    if ((err = cipher_is_valid(cfb->cipher)) != CRYPT_OK)  return err;

    if (cfb->blocklen < 0 || cfb->blocklen > ivSize) return CRYPT_INVALID_ARG;

    while (len-- > 0) {
        // XOR the plaintext byte *pt with the leftmost byte of the IV buffer giving *ct
        *ct = cfb->pad[0] ^ *pt;
        // Rotate the IV Buffer left one byte
        memmove(theIV, theIV+1, ivSize-1);
        // copy *ct into the rightmost byte of the IV buffer 
        theIV[ivSize - 1] = *ct;
        // Encrypt the IV buffer
        if ((err = cipher_descriptor[cfb->cipher].ecb_encrypt(cfb->IV, cfb->pad, &cfb->key)) != CRYPT_OK) return err;
        // Bump the pointers
        ++pt; 
        ++ct;
    }
    return CRYPT_OK;
}

#endif
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































































Deleted Source/libtomcrypt/src/modes/cfb8/cfb8_getiv.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cfb_getiv.c
   CFB implementation, get IV, Tom St Denis
*/

#ifdef LTC_CFB_MODE

/**
   Get the current initial vector
   @param IV   [out] The destination of the initial vector
   @param len  [in/out]  The max size and resulting size of the initial vector
   @param cfb  The CFB state
   @return CRYPT_OK if successful
*/
int cfb8_getiv(unsigned char *IV, unsigned long *len, symmetric_CFB *cfb)
{
   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(len != NULL);
   LTC_ARGCHK(cfb != NULL);
   if ((unsigned long)cfb->blocklen > *len) {
      *len = cfb->blocklen;
      return CRYPT_BUFFER_OVERFLOW;
   }
   XMEMCPY(IV, cfb->IV, cfb->blocklen);
   *len = cfb->blocklen;

   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_getiv.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/libtomcrypt/src/modes/cfb8/cfb8_setiv.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file cfb_setiv.c
  CFB implementation, set IV, Tom St Denis
*/  

#ifdef LTC_CFB_MODE

/**
   Set an initial vector
   @param IV   The initial vector
   @param len  The length of the vector (in octets)
   @param cfb  The CFB state
   @return CRYPT_OK if successful
*/
int cfb8_setiv(const unsigned char *IV, unsigned long len, symmetric_CFB *cfb)
{
   int err;
   
   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(cfb != NULL);

   if ((err = cipher_is_valid(cfb->cipher)) != CRYPT_OK) {
       return err;
   }
   
   if (len != (unsigned long)cfb->blocklen) {
      return CRYPT_INVALID_ARG;
   }
      
   /* force next block */
   cfb->padlen = 0;
   return cipher_descriptor[cfb->cipher].ecb_encrypt(IV, cfb->pad, &cfb->key);
}

#endif 


/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_setiv.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































Deleted Source/libtomcrypt/src/modes/cfb8/cfb8_start.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file cfb8_start.c
   CFB implementation, start chain, Tom St Denis
*/


#ifdef LTC_CFB_MODE

/**
   Initialize a CFB8 context
   @param cipher      The index of the cipher desired
   @param IV          The initial vector
   @param key         The secret key 
   @param keylen      The length of the secret key (octets)
   @param num_rounds  Number of rounds in the cipher desired (0 for default)
   @param cfb         The CFB state to initialize
   @return CRYPT_OK if successful
*/
#ifdef MACTOMCRYPT
int cfb8_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *tweak, int tweaklen,
	int num_rounds, int options, symmetric_CFB *cfb)
#else
int cfb8_start(int cipher, const unsigned char *IV, const unsigned char *key, 
              int keylen, int num_rounds, symmetric_CFB *cfb)
#endif
{
   int x, err;

   LTC_ARGCHK(IV != NULL);
   LTC_ARGCHK(key != NULL);
   LTC_ARGCHK(cfb != NULL);

   if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
      return err;
   }
   

   /* copy data */
   cfb->cipher = cipher;
   cfb->blocklen = cipher_descriptor[cipher].block_length;
   for (x = 0; x < cfb->blocklen; x++)
       cfb->IV[x] = IV[x];

   /* init the cipher */
   if ((err = cipher_descriptor[cipher].setup(key, keylen, num_rounds, &cfb->key)) != CRYPT_OK) {
      return err;
   }

   /* encrypt the IV */
   return cipher_descriptor[cfb->cipher].ecb_encrypt(cfb->IV, cfb->pad, &cfb->key);
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/cfb/cfb_start.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































Deleted Source/libtomcrypt/src/modes/ctr/ctr_decrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file ctr_decrypt.c
  CTR implementation, decrypt data, Tom St Denis
*/

#ifdef LTC_CTR_MODE

/**
   CTR decrypt
   @param ct      Ciphertext
   @param pt      [out] Plaintext
   @param len     Length of ciphertext (octets)
   @param ctr     CTR state
   @return CRYPT_OK if successful
*/
int ctr_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_CTR *ctr)
{
   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(ctr != NULL);

   return ctr_encrypt(ct, pt, len, ctr);
}

#endif


/* $Source: /cvs/libtom/libtomcrypt/src/modes/ctr/ctr_decrypt.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































Deleted Source/libtomcrypt/src/modes/ctr/ctr_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
 *  ctr_descriptor.c
 *  MacTomCrypt
 */

#include "tomcrypt.h"
#if defined(LTC_CTR_MODE) && defined(MACTOMCRYPT)

const struct ltc_mode_descriptor modeCTR_desc =
{
	"CTR",
	4,			/* Must match 	kCCModeCTR = 4 */
	1,
	sizeof(symmetric_CTR),
	&ctr_start,
	&ctr_encrypt, 
	&ctr_decrypt, 
	&unimp_mode_encrypt_tweaked, 
	&unimp_mode_decrypt_tweaked, 
	&ctr_done, 
	&ctr_setiv,
	&ctr_getiv,
};
#endif /* LTC_CTR_MODE */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/libtomcrypt/src/modes/ctr/ctr_done.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file ctr_done.c
   CTR implementation, finish chain, Tom St Denis
*/

#ifdef LTC_CTR_MODE

/** Terminate the chain
  @param ctr    The CTR chain to terminate
  @return CRYPT_OK on success
*/
int ctr_done(symmetric_CTR *ctr)
{
   int err;
   LTC_ARGCHK(ctr != NULL);

   if ((err = cipher_is_valid(ctr->cipher)) != CRYPT_OK) {
      return err;
   }
   cipher_descriptor[ctr->cipher].done(&ctr->key);
   return CRYPT_OK;
}

   

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ctr/ctr_done.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































Deleted Source/libtomcrypt/src/modes/ctr/ctr_encrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file ctr_encrypt.c
  CTR implementation, encrypt data, Tom St Denis
*/


#ifdef LTC_CTR_MODE

/**
  CTR encrypt
  @param pt     Plaintext
  @param ct     [out] Ciphertext
  @param len    Length of plaintext (octets)
  @param ctr    CTR state
  @return CRYPT_OK if successful
*/
int ctr_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CTR *ctr)
{
   int x, err;

   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(ctr != NULL);

   if ((err = cipher_is_valid(ctr->cipher)) != CRYPT_OK) {
       return err;
   }
   
   /* is blocklen/padlen valid? */
   if (ctr->blocklen < 1 || ctr->blocklen > (int)sizeof(ctr->ctr) ||
       ctr->padlen   < 0 || ctr->padlen   > (int)sizeof(ctr->pad)) {
      return CRYPT_INVALID_ARG;
   }

#ifdef LTC_FAST
   if (ctr->blocklen % sizeof(LTC_FAST_TYPE)) {
      return CRYPT_INVALID_ARG;
   }
#endif
   
   /* handle acceleration only if pad is empty, accelerator is present and length is >= a block size */
   if ((ctr->padlen == ctr->blocklen) && cipher_descriptor[ctr->cipher].accel_ctr_encrypt != NULL && (len >= (unsigned long)ctr->blocklen)) {
      if ((err = cipher_descriptor[ctr->cipher].accel_ctr_encrypt(pt, ct, len/ctr->blocklen, ctr->ctr, ctr->mode, &ctr->key)) != CRYPT_OK) {
         return err;
      }
      len %= ctr->blocklen;
   }

   while (len) {
      /* is the pad empty? */
      if (ctr->padlen == ctr->blocklen) {
         /* increment counter */
         if (ctr->mode == CTR_COUNTER_LITTLE_ENDIAN) {
            /* little-endian */
            for (x = 0; x < ctr->ctrlen; x++) {
               ctr->ctr[x] = (ctr->ctr[x] + (unsigned char)1) & (unsigned char)255;
               if (ctr->ctr[x] != (unsigned char)0) {
                  break;
               }
            }
         } else {
            /* big-endian */
            for (x = ctr->blocklen-1; x >= ctr->ctrlen; x--) {
               ctr->ctr[x] = (ctr->ctr[x] + (unsigned char)1) & (unsigned char)255;
               if (ctr->ctr[x] != (unsigned char)0) {
                  break;
               }
            }
         }

         /* encrypt it */
         if ((err = cipher_descriptor[ctr->cipher].ecb_encrypt(ctr->ctr, ctr->pad, &ctr->key)) != CRYPT_OK) {
            return err;
         }
         ctr->padlen = 0;
      }
#ifdef LTC_FAST
      if (ctr->padlen == 0 && len >= (unsigned long)ctr->blocklen) {
         for (x = 0; x < ctr->blocklen; x += sizeof(LTC_FAST_TYPE)) {
            *((LTC_FAST_TYPE*)((unsigned char *)ct + x)) = *((LTC_FAST_TYPE*)((unsigned char *)pt + x)) ^
                                                           *((LTC_FAST_TYPE*)((unsigned char *)ctr->pad + x));
         }
       pt         += ctr->blocklen;
       ct         += ctr->blocklen;
       len        -= ctr->blocklen;
       ctr->padlen = ctr->blocklen;
       continue;
      }
#endif    
      *ct++ = *pt++ ^ ctr->pad[ctr->padlen++];
      --len;
   }
   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ctr/ctr_encrypt.c,v $ */
/* $Revision: 1.22 $ */
/* $Date: 2007/02/22 20:26:05 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































Deleted Source/libtomcrypt/src/modes/ctr/ctr_getiv.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file ctr_getiv.c
   CTR implementation, get IV, Tom St Denis
*/

#ifdef LTC_CTR_MODE

/**
   Get the current initial vector
   @param IV   [out] The destination of the initial vector
   @param len  [in/out]  The max size and resulting size of the initial vector
   @param ctr  The CTR state
   @return CRYPT_OK if successful
*/
int ctr_getiv(unsigned char *IV, unsigned long *len, symmetric_CTR *ctr)
{
   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(len != NULL);
   LTC_ARGCHK(ctr != NULL);
   if ((unsigned long)ctr->blocklen > *len) {
      *len = ctr->blocklen;
      return CRYPT_BUFFER_OVERFLOW;
   }
   XMEMCPY(IV, ctr->ctr, ctr->blocklen);
   *len = ctr->blocklen;

   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ctr/ctr_getiv.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/libtomcrypt/src/modes/ctr/ctr_setiv.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file ctr_setiv.c
  CTR implementation, set IV, Tom St Denis
*/
  
#ifdef LTC_CTR_MODE

/**
   Set an initial vector
   @param IV   The initial vector
   @param len  The length of the vector (in octets)
   @param ctr  The CTR state
   @return CRYPT_OK if successful
*/
int ctr_setiv(const unsigned char *IV, unsigned long len, symmetric_CTR *ctr)
{
   int err;
   
   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(ctr != NULL);

   /* bad param? */
   if ((err = cipher_is_valid(ctr->cipher)) != CRYPT_OK) {
      return err;
   }
   
   if (len != (unsigned long)ctr->blocklen) {
      return CRYPT_INVALID_ARG;
   }

   /* set IV */
   XMEMCPY(ctr->ctr, IV, len);
   
   /* force next block */
   ctr->padlen = 0;
   return cipher_descriptor[ctr->cipher].ecb_encrypt(IV, ctr->pad, &ctr->key);
}

#endif 


/* $Source: /cvs/libtom/libtomcrypt/src/modes/ctr/ctr_setiv.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































Deleted Source/libtomcrypt/src/modes/ctr/ctr_start.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file ctr_start.c
   CTR implementation, start chain, Tom St Denis
*/


#ifdef LTC_CTR_MODE

/**
   Initialize a CTR context
   @param cipher      The index of the cipher desired
   @param IV          The initial vector
   @param key         The secret key 
   @param keylen      The length of the secret key (octets)
   @param num_rounds  Number of rounds in the cipher desired (0 for default)
   @param ctr_mode    The counter mode (CTR_COUNTER_LITTLE_ENDIAN or CTR_COUNTER_BIG_ENDIAN)
   @param ctr         The CTR state to initialize
   @return CRYPT_OK if successful
*/
#ifdef MACTOMCRYPT
int ctr_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *tweak, int tweaklen,
	int num_rounds, int ctr_mode, symmetric_CTR *ctr)
#else
int ctr_start(int   cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
	int  num_rounds, int ctr_mode, symmetric_CTR *ctr)
#endif
{
   int x, err;

   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(key != NULL);
   LTC_ARGCHK(ctr != NULL);

   /* bad param? */
   if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
      return err;
   }

   /* ctrlen == counter width */
   ctr->ctrlen   = (ctr_mode & 255) ? (ctr_mode & 255) : cipher_descriptor[cipher].block_length;
   if (ctr->ctrlen > cipher_descriptor[cipher].block_length) {
      return CRYPT_INVALID_ARG;
   }

   if ((ctr_mode & 0x1000) == CTR_COUNTER_BIG_ENDIAN) {
      ctr->ctrlen = cipher_descriptor[cipher].block_length - ctr->ctrlen;
   }

   /* setup cipher */
   if ((err = cipher_descriptor[cipher].setup(key, keylen, num_rounds, &ctr->key)) != CRYPT_OK) {
      return err;
   }

   /* copy ctr */
   ctr->blocklen = cipher_descriptor[cipher].block_length;
   ctr->cipher   = cipher;
   ctr->padlen   = 0;
   ctr->mode     = ctr_mode & 0x1000;
   for (x = 0; x < ctr->blocklen; x++) {
       ctr->ctr[x] = IV[x];
   }

   if (ctr_mode & LTC_CTR_RFC3686) {
      /* increment the IV as per RFC 3686 */
      if (ctr->mode == CTR_COUNTER_LITTLE_ENDIAN) {
         /* little-endian */
         for (x = 0; x < ctr->ctrlen; x++) {
             ctr->ctr[x] = (ctr->ctr[x] + (unsigned char)1) & (unsigned char)255;
             if (ctr->ctr[x] != (unsigned char)0) {
                break;
             }
         }
      } else {
         /* big-endian */
         for (x = ctr->blocklen-1; x >= ctr->ctrlen; x--) {
             ctr->ctr[x] = (ctr->ctr[x] + (unsigned char)1) & (unsigned char)255;
             if (ctr->ctr[x] != (unsigned char)0) {
                break;
             }
         }
      }
   }

   return cipher_descriptor[ctr->cipher].ecb_encrypt(ctr->ctr, ctr->pad, &ctr->key); 
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ctr/ctr_start.c,v $ */
/* $Revision: 1.15 $ */
/* $Date: 2007/02/23 14:18:37 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































Deleted Source/libtomcrypt/src/modes/ctr/ctr_test.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file ctr_test.c
  CTR implementation, Tests again RFC 3686, Tom St Denis
*/

#ifdef LTC_CTR_MODE

int ctr_test(void)
{
#ifdef LTC_NO_TEST
   return CRYPT_NOP;
#else
   static const struct {
      int keylen, msglen;
      unsigned char key[32], IV[16], pt[64], ct[64];
   } tests[] = {
/* 128-bit key, 16-byte pt */
{
   16, 16,
   {0xAE,0x68,0x52,0xF8,0x12,0x10,0x67,0xCC,0x4B,0xF7,0xA5,0x76,0x55,0x77,0xF3,0x9E },
   {0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
   {0x53,0x69,0x6E,0x67,0x6C,0x65,0x20,0x62,0x6C,0x6F,0x63,0x6B,0x20,0x6D,0x73,0x67 },
   {0xE4,0x09,0x5D,0x4F,0xB7,0xA7,0xB3,0x79,0x2D,0x61,0x75,0xA3,0x26,0x13,0x11,0xB8 },
},

/* 128-bit key, 36-byte pt */
{
   16, 36,
   {0x76,0x91,0xBE,0x03,0x5E,0x50,0x20,0xA8,0xAC,0x6E,0x61,0x85,0x29,0xF9,0xA0,0xDC },
   {0x00,0xE0,0x01,0x7B,0x27,0x77,0x7F,0x3F,0x4A,0x17,0x86,0xF0,0x00,0x00,0x00,0x00 },
   {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,
    0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,
    0x20,0x21,0x22,0x23},
   {0xC1,0xCF,0x48,0xA8,0x9F,0x2F,0xFD,0xD9,0xCF,0x46,0x52,0xE9,0xEF,0xDB,0x72,0xD7,
    0x45,0x40,0xA4,0x2B,0xDE,0x6D,0x78,0x36,0xD5,0x9A,0x5C,0xEA,0xAE,0xF3,0x10,0x53,
    0x25,0xB2,0x07,0x2F },
},
};
  int idx, err, x;
  unsigned char buf[64];
  symmetric_CTR ctr;

  /* AES can be under rijndael or aes... try to find it */ 
  if ((idx = find_cipher("aes")) == -1) {
     if ((idx = find_cipher("rijndael")) == -1) {
        return CRYPT_NOP;
     }
  }

  for (x = 0; x < (int)(sizeof(tests)/sizeof(tests[0])); x++) {
#ifdef MACTOMCRYPT
     if ((err = ctr_start(idx, tests[x].IV, tests[x].key, tests[x].keylen, 
			NULL, 0, 0, CTR_COUNTER_BIG_ENDIAN|LTC_CTR_RFC3686, &ctr)) != CRYPT_OK) {
#else
     if ((err = ctr_start(idx, tests[x].IV, tests[x].key, tests[x].keylen, 0, CTR_COUNTER_BIG_ENDIAN|LTC_CTR_RFC3686, &ctr)) != CRYPT_OK) {
#endif
        return err;
     }
     if ((err = ctr_encrypt(tests[x].pt, buf, tests[x].msglen, &ctr)) != CRYPT_OK) {
        return err;
     }
     ctr_done(&ctr);
     if (XMEMCMP(buf, tests[x].ct, tests[x].msglen)) {
        return CRYPT_FAIL_TESTVECTOR;
     }
  }
  return CRYPT_OK;
#endif
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ctr/ctr_test.c,v $ */
/* $Revision: 1.4 $ */
/* $Date: 2006/12/28 01:27:24 $ */



<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































Deleted Source/libtomcrypt/src/modes/ecb/ecb_decrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file ecb_decrypt.c
  ECB implementation, decrypt a block, Tom St Denis
*/

#ifdef LTC_ECB_MODE

/**
  ECB decrypt
  @param ct     Ciphertext
  @param pt     [out] Plaintext
  @param len    The number of octets to process (must be multiple of the cipher block size)
  @param ecb    ECB state
  @return CRYPT_OK if successful
*/
int ecb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_ECB *ecb)
{
   int err;
   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(ecb != NULL);
   if ((err = cipher_is_valid(ecb->cipher)) != CRYPT_OK) {
       return err;
   }
   if (len % cipher_descriptor[ecb->cipher].block_length) {
      return CRYPT_INVALID_ARG;
   }

   /* check for accel */
   if (cipher_descriptor[ecb->cipher].accel_ecb_decrypt != NULL) {
      return cipher_descriptor[ecb->cipher].accel_ecb_decrypt(ct, pt, len / cipher_descriptor[ecb->cipher].block_length, &ecb->key);
   } else {
      while (len) {
         if ((err = cipher_descriptor[ecb->cipher].ecb_decrypt(ct, pt, &ecb->key)) != CRYPT_OK) {
            return err;
         }
         pt  += cipher_descriptor[ecb->cipher].block_length;
         ct  += cipher_descriptor[ecb->cipher].block_length;
         len -= cipher_descriptor[ecb->cipher].block_length;
      }
   }
   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ecb/ecb_decrypt.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































Deleted Source/libtomcrypt/src/modes/ecb/ecb_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
 *  ecb_descriptor.c
 *  MacTomCrypt
 */

#include "tomcrypt.h"
#if defined(LTC_ECB_MODE) && defined(MACTOMCRYPT)

const struct ltc_mode_descriptor modeECB_desc =
{
	"ECB",
	1, /* Must match 	kCCModeECB = 1 */
	1,
	sizeof(symmetric_ECB),
	&ecb_start,
	&ecb_encrypt, 
	&ecb_decrypt, 
	&unimp_mode_encrypt_tweaked, 
	&unimp_mode_decrypt_tweaked, 
	&ecb_done, 
	&unimp_mode_setiv,
	&unimp_mode_getiv,
};
#endif /* LTC_ECB_MODE */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/libtomcrypt/src/modes/ecb/ecb_done.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file ecb_done.c
   ECB implementation, finish chain, Tom St Denis
*/

#ifdef LTC_ECB_MODE

/** Terminate the chain
  @param ecb    The ECB chain to terminate
  @return CRYPT_OK on success
*/
int ecb_done(symmetric_ECB *ecb)
{
   int err;
   LTC_ARGCHK(ecb != NULL);

   if ((err = cipher_is_valid(ecb->cipher)) != CRYPT_OK) {
      return err;
   }
   cipher_descriptor[ecb->cipher].done(&ecb->key);
   return CRYPT_OK;
}

   

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ecb/ecb_done.c,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































Deleted Source/libtomcrypt/src/modes/ecb/ecb_encrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file ecb_encrypt.c
  ECB implementation, encrypt a block, Tom St Denis
*/

#ifdef LTC_ECB_MODE

/**
  ECB encrypt
  @param pt     Plaintext
  @param ct     [out] Ciphertext
  @param len    The number of octets to process (must be multiple of the cipher block size)
  @param ecb    ECB state
  @return CRYPT_OK if successful
*/
int ecb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_ECB *ecb)
{
   int err;
   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(ecb != NULL);
   if ((err = cipher_is_valid(ecb->cipher)) != CRYPT_OK) {
       return err;
   }
   if (len % cipher_descriptor[ecb->cipher].block_length) {
      return CRYPT_INVALID_ARG;
   }

   /* check for accel */
   if (cipher_descriptor[ecb->cipher].accel_ecb_encrypt != NULL) {
      return cipher_descriptor[ecb->cipher].accel_ecb_encrypt(pt, ct, len / cipher_descriptor[ecb->cipher].block_length, &ecb->key);
   } else {
      while (len) {
         if ((err = cipher_descriptor[ecb->cipher].ecb_encrypt(pt, ct, &ecb->key)) != CRYPT_OK) {
            return err;
         }
         pt  += cipher_descriptor[ecb->cipher].block_length;
         ct  += cipher_descriptor[ecb->cipher].block_length;
         len -= cipher_descriptor[ecb->cipher].block_length;
      }
   }
   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ecb/ecb_encrypt.c,v $ */
/* $Revision: 1.10 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































Deleted Source/libtomcrypt/src/modes/ecb/ecb_start.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file ecb_start.c
   ECB implementation, start chain, Tom St Denis
*/


#ifdef LTC_ECB_MODE

/**
   Initialize a ECB context
   @param cipher      The index of the cipher desired
   @param key         The secret key 
   @param keylen      The length of the secret key (octets)
   @param num_rounds  Number of rounds in the cipher desired (0 for default)
   @param ecb         The ECB state to initialize
   @return CRYPT_OK if successful
*/
#ifdef MACTOMCRYPT
int ecb_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, const unsigned char *tweak, int tweaklen,
	int num_rounds, int options, symmetric_ECB *ecb)
#else
int ecb_start(int cipher, const unsigned char *key, int keylen, int num_rounds, symmetric_ECB *ecb)
#endif
{
   int err;
   LTC_ARGCHK(key != NULL);
   LTC_ARGCHK(ecb != NULL);

   if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
      return err;
   }
   ecb->cipher = cipher;
   ecb->blocklen = cipher_descriptor[cipher].block_length;
   return cipher_descriptor[cipher].setup(key, keylen, num_rounds, &ecb->key);
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ecb/ecb_start.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































Deleted Source/libtomcrypt/src/modes/ofb/ofb_decrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file ofb_decrypt.c
  OFB implementation, decrypt data, Tom St Denis
*/

#ifdef LTC_OFB_MODE

/**
   OFB decrypt
   @param ct      Ciphertext
   @param pt      [out] Plaintext
   @param len     Length of ciphertext (octets)
   @param ofb     OFB state
   @return CRYPT_OK if successful
*/
int ofb_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, symmetric_OFB *ofb)
{
   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(ofb != NULL);
   return ofb_encrypt(ct, pt, len, ofb);
}


#endif

 

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ofb/ofb_decrypt.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































Deleted Source/libtomcrypt/src/modes/ofb/ofb_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/*
 *  ofb_descriptor.c
 *  MacTomCrypt
 */

#include "tomcrypt.h"
#if defined(LTC_OFB_MODE) && defined(MACTOMCRYPT)

const struct ltc_mode_descriptor modeOFB_desc =
{
	"OFB",
	7,				/* Must match 	kCCModeOFB = 7 */
	1,
	sizeof(symmetric_OFB),
	&ofb_start,
	&ofb_encrypt, 
	&ofb_decrypt, 
	&unimp_mode_encrypt_tweaked, 
	&unimp_mode_decrypt_tweaked, 
	&ofb_done, 
	&ofb_setiv,
	&ofb_getiv,
};
#endif /* LTC_OFB_MODE */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






























































































Deleted Source/libtomcrypt/src/modes/ofb/ofb_done.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file ofb_done.c
   OFB implementation, finish chain, Tom St Denis
*/

#ifdef LTC_OFB_MODE

/** Terminate the chain
  @param ofb    The OFB chain to terminate
  @return CRYPT_OK on success
*/
int ofb_done(symmetric_OFB *ofb)
{
   int err;
   LTC_ARGCHK(ofb != NULL);

   if ((err = cipher_is_valid(ofb->cipher)) != CRYPT_OK) {
      return err;
   }
   cipher_descriptor[ofb->cipher].done(&ofb->key);
   return CRYPT_OK;
}

   

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ofb/ofb_done.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































Deleted Source/libtomcrypt/src/modes/ofb/ofb_encrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
  @file ofb_encrypt.c
  OFB implementation, encrypt data, Tom St Denis
*/

#ifdef LTC_OFB_MODE

/**
  OFB encrypt
  @param pt     Plaintext
  @param ct     [out] Ciphertext
  @param len    Length of plaintext (octets)
  @param ofb    OFB state
  @return CRYPT_OK if successful
*/
int ofb_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_OFB *ofb)
{
   int err;
   LTC_ARGCHK(pt != NULL);
   LTC_ARGCHK(ct != NULL);
   LTC_ARGCHK(ofb != NULL);
   if ((err = cipher_is_valid(ofb->cipher)) != CRYPT_OK) {
       return err;
   }
   
   /* is blocklen/padlen valid? */
   if (ofb->blocklen < 0 || ofb->blocklen > (int)sizeof(ofb->IV) ||
       ofb->padlen   < 0 || ofb->padlen   > (int)sizeof(ofb->IV)) {
      return CRYPT_INVALID_ARG;
   }
   
   while (len-- > 0) {
       if (ofb->padlen == ofb->blocklen) {
          if ((err = cipher_descriptor[ofb->cipher].ecb_encrypt(ofb->IV, ofb->IV, &ofb->key)) != CRYPT_OK) {
             return err;
          }
          ofb->padlen = 0;
       }
       *ct++ = *pt++ ^ ofb->IV[(ofb->padlen)++];
   }
   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ofb/ofb_encrypt.c,v $ */
/* $Revision: 1.8 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
























































































































Deleted Source/libtomcrypt/src/modes/ofb/ofb_getiv.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file ofb_getiv.c
   OFB implementation, get IV, Tom St Denis
*/

#ifdef LTC_OFB_MODE

/**
   Get the current initial vector
   @param IV   [out] The destination of the initial vector
   @param len  [in/out]  The max size and resulting size of the initial vector
   @param ofb  The OFB state
   @return CRYPT_OK if successful
*/
int ofb_getiv(unsigned char *IV, unsigned long *len, symmetric_OFB *ofb)
{
   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(len != NULL);
   LTC_ARGCHK(ofb != NULL);
   if ((unsigned long)ofb->blocklen > *len) {
      *len = ofb->blocklen;
      return CRYPT_BUFFER_OVERFLOW;
   }
   XMEMCPY(IV, ofb->IV, ofb->blocklen);
   *len = ofb->blocklen;

   return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ofb/ofb_getiv.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




























































































Deleted Source/libtomcrypt/src/modes/ofb/ofb_setiv.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file ofb_setiv.c
   OFB implementation, set IV, Tom St Denis
*/

#ifdef LTC_OFB_MODE

/**
   Set an initial vector
   @param IV   The initial vector
   @param len  The length of the vector (in octets)
   @param ofb  The OFB state
   @return CRYPT_OK if successful
*/
int ofb_setiv(const unsigned char *IV, unsigned long len, symmetric_OFB *ofb)
{
   int err;

   LTC_ARGCHK(IV  != NULL);
   LTC_ARGCHK(ofb != NULL);

   if ((err = cipher_is_valid(ofb->cipher)) != CRYPT_OK) {
       return err;
   }

   if (len != (unsigned long)ofb->blocklen) {
      return CRYPT_INVALID_ARG;
   }

   /* force next block */
   ofb->padlen = 0;
   return cipher_descriptor[ofb->cipher].ecb_encrypt(IV, ofb->IV, &ofb->key);
}

#endif 


/* $Source: /cvs/libtom/libtomcrypt/src/modes/ofb/ofb_setiv.c,v $ */
/* $Revision: 1.7 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































Deleted Source/libtomcrypt/src/modes/ofb/ofb_start.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/**
   @file ofb_start.c
   OFB implementation, start chain, Tom St Denis
*/


#ifdef LTC_OFB_MODE

/**
   Initialize a OFB context
   @param cipher      The index of the cipher desired
   @param IV          The initial vector
   @param key         The secret key 
   @param keylen      The length of the secret key (octets)
   @param num_rounds  Number of rounds in the cipher desired (0 for default)
   @param ofb         The OFB state to initialize
   @return CRYPT_OK if successful
*/
#ifdef MACTOMCRYPT
int ofb_start(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
	const unsigned char *tweak, int tweaklen, int num_rounds, int options, symmetric_OFB *ofb)
#else
int ofb_start(int cipher, const unsigned char *IV, const unsigned char *key, 
              int keylen, int num_rounds, symmetric_OFB *ofb)
#endif
{
   int x, err;

   LTC_ARGCHK(IV != NULL);
   LTC_ARGCHK(key != NULL);
   LTC_ARGCHK(ofb != NULL);

   if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
      return err;
   }

   /* copy details */
   ofb->cipher = cipher;
   ofb->blocklen = cipher_descriptor[cipher].block_length;
   for (x = 0; x < ofb->blocklen; x++) {
       ofb->IV[x] = IV[x];
   }

   /* init the cipher */
   ofb->padlen = ofb->blocklen;
   return cipher_descriptor[cipher].setup(key, keylen, num_rounds, &ofb->key);
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/ofb/ofb_start.c,v $ */
/* $Revision: 1.6 $ */
/* $Date: 2006/12/28 01:27:24 $ */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































Deleted Source/libtomcrypt/src/modes/rc4_stream.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* 
 * Copyright (c) 2004 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include "tomcrypt.h"
#include "ccdebug.h"
// Wrench RC4 into a common interface.

const struct ltc_mode_descriptor modeRC4_desc =
{
	"RC4",
	10,
	1,
	sizeof(RC4_KEY),
	&rc4_stream_setup,
	&rc4_stream_encrypt, 
	&rc4_stream_decrypt, 
	&unimp_mode_encrypt_tweaked, 
	&unimp_mode_decrypt_tweaked, 
	&rc4_stream_done, 
	&unimp_mode_setiv,
	&unimp_mode_getiv,
};


int rc4_stream_setup(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
const unsigned char *tweak, int tweaklen, int num_rounds, int options, RC4_KEY *ctx) {
	CC_RC4_set_key(ctx, keylen, key);
	return CRYPT_OK; 
}

int rc4_stream_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, mode_context *ctx) {
	ccdebug(ASL_LEVEL_ERR, " RC4 Processing %d bytes\n"	, len);
	CC_RC4(ctx, len, pt, ct);
	return CRYPT_OK; 
}

int rc4_stream_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, mode_context *ctx) {
	ccdebug(ASL_LEVEL_ERR, " RC4 Processing %d bytes\n"	, len);
	CC_RC4(ctx, len, ct, pt);
	return CRYPT_OK; 
}

int rc4_stream_done(mode_context *ctx) { 
	memset(ctx, 0, sizeof(RC4_KEY));
	return CRYPT_OK; 
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































Deleted Source/libtomcrypt/src/modes/unimplemented.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* 
 * Copyright (c) 2004 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include "tomcrypt.h"

// Filler routines for unimplemented mode methods.

const struct ltc_mode_descriptor modeUNIMP_desc =
{
	NULL,
	0,
	0,
	0,
	unimp_mode_setup,
	unimp_mode_encrypt, 
	unimp_mode_decrypt, 
	unimp_mode_encrypt_tweaked, 
	unimp_mode_decrypt_tweaked, 
	unimp_mode_done, 
	unimp_mode_setiv,
	unimp_mode_getiv,
};


int unimp_mode_setup(int cipher, const unsigned char *IV, const unsigned char *key, int keylen, 
const unsigned char *tweak, int tweaklen, int num_rounds, int options, mode_context *ctx) { return CRYPT_UNIMPLEMENTED; }

int unimp_mode_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, mode_context *ctx) { return CRYPT_UNIMPLEMENTED; }

int unimp_mode_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, mode_context *ctx) { return CRYPT_UNIMPLEMENTED; }

int unimp_mode_encrypt_tweaked(const unsigned char *pt, unsigned long len, unsigned char *ct, const unsigned char *tweak, mode_context *ctx) { return CRYPT_UNIMPLEMENTED; }

int unimp_mode_decrypt_tweaked(const unsigned char *ct, unsigned long len, unsigned char *pt, const unsigned char *tweak, mode_context *ctx) { return CRYPT_UNIMPLEMENTED; }

int unimp_mode_done(mode_context *ctx) { return CRYPT_UNIMPLEMENTED; }

int unimp_mode_setiv(const unsigned char *IV, unsigned long len, mode_context *ctx) { return CRYPT_UNIMPLEMENTED; }

int unimp_mode_getiv(const unsigned char *IV, unsigned long *len, mode_context *ctx) { return CRYPT_UNIMPLEMENTED; }

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


























































































































Deleted Source/libtomcrypt/src/modes/xts/xts_decrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/** 
 Source donated by Elliptic Semiconductor Inc (www.ellipticsemi.com) to the LibTom Projects
 */

#ifdef LTC_XTS_MODE

static int tweak_uncrypt(const unsigned char *C, unsigned char *P, unsigned char *T, symmetric_xts *xts)
{
    unsigned long x;
    int err;
    
    /* tweak encrypt block i */
#ifdef LTC_FAST
    for (x = 0; x < 16; x += sizeof(LTC_FAST_TYPE)) {
        *((LTC_FAST_TYPE*)&P[x]) = *((LTC_FAST_TYPE*)&C[x]) ^ *((LTC_FAST_TYPE*)&T[x]);
    }
#else
    for (x = 0; x < 16; x++) {
        P[x] = C[x] ^ T[x];
    }
#endif
    
    err = cipher_descriptor[xts->cipher].ecb_decrypt(P, P, &xts->key1);  
    
#ifdef LTC_FAST
    for (x = 0; x < 16; x += sizeof(LTC_FAST_TYPE)) {
        *((LTC_FAST_TYPE*)&P[x]) ^=  *((LTC_FAST_TYPE*)&T[x]);
    }
#else
    for (x = 0; x < 16; x++) {
        P[x] = P[x] ^ T[x];
    }
#endif
    
    /* LFSR the tweak */
    xts_mult_x(T);
    
    return err;
}   

/** XTS Decryption
 @param ct     [in] Ciphertext
 @param ptlen  Length of plaintext (and ciphertext)
 @param pt     [out]  Plaintext
 @param tweak  [in] The 128--bit encryption tweak (e.g. sector number)
 @param xts    The XTS structure
 Returns CRYPT_OK upon success
 */int xts_decrypt(
                   const unsigned char *ct, unsigned long ptlen,
                   unsigned char *pt,
                   const unsigned char *tweak,
                   symmetric_xts *xts)
{
    unsigned char PP[16], CC[16], T[16];
    unsigned long i, m, mo, lim;
    int           err;
    
    /* check inputs */
    LTC_ARGCHK(pt    != NULL);
    LTC_ARGCHK(ct    != NULL);
    LTC_ARGCHK(tweak != NULL);
    LTC_ARGCHK(xts   != NULL);
    
    /* check if valid */
    if ((err = cipher_is_valid(xts->cipher)) != CRYPT_OK) {
        return err;
    }
    
    // if the cipher has an accelerated logical block decryptor, call it.
    if(cipher_descriptor[xts->cipher].accel_xts_decrypt) return cipher_descriptor[xts->cipher].accel_xts_decrypt(ct, ptlen, pt, tweak, xts);
    
    /* get number of blocks */
    m  = ptlen >> 4;
    mo = ptlen & 15;
    
    /* must have at least one full block */
    if (m == 0) {
        return CRYPT_INVALID_ARG;
    }
    
    /* encrypt the tweak */
    if ((err = cipher_descriptor[xts->cipher].ecb_encrypt(tweak, T, &xts->key2)) != CRYPT_OK) {
        return err;
    }
    
    /* for i = 0 to m-2 do */
    if (mo == 0) {
        lim = m;
    } else {
        lim = m - 1;
    }
    
    for (i = 0; i < lim; i++) {
        err = tweak_uncrypt(ct, pt, T, xts);
        ct += 16;
        pt += 16;
    }
    
    /* if ptlen not divide 16 then */
    if (mo > 0) {
        XMEMCPY(CC, T, 16);
        xts_mult_x(CC);
        
        /* PP = tweak decrypt block m-1 */
        if ((err = tweak_uncrypt(ct, PP, CC, xts)) != CRYPT_OK) {
            return err;
        }
        
        /* Pm = first ptlen % 16 bytes of PP */
        for (i = 0; i < mo; i++) {
            CC[i]    = ct[16+i];
            pt[16+i] = PP[i];
        }
        for (; i < 16; i++) {
            CC[i] = PP[i];
        }
        
        /* Pm-1 = Tweak uncrypt CC */
        if ((err = tweak_uncrypt(CC, pt, T, xts)) != CRYPT_OK) {
            return err;
        }
    }
    
    return CRYPT_OK;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/xts/xts_decrypt.c,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2007/05/12 14:05:56 $ */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































Deleted Source/libtomcrypt/src/modes/xts/xts_descriptor.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* 
 * Copyright (c) 2006 Apple Computer, Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
 
/*
 *  xts_descriptor.c
 *  MacTomCrypt
 */

#include "tomcrypt.h"
#if defined(LTC_XTS_MODE) && defined(MACTOMCRYPT)

const struct ltc_mode_descriptor modeXTS_desc =
{
	"XTS",
	8,			/* Must match 	kCCModeXTS = 8 */
	1,
	sizeof(symmetric_xts),
	&xts_start,
	&unimp_mode_encrypt, 
	&unimp_mode_decrypt, 
	&xts_encrypt, 
	&xts_decrypt, 
	&xts_done, 
	&unimp_mode_setiv,
	&unimp_mode_getiv,
};

#endif /* LTC_XTS_MODE */
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































Deleted Source/libtomcrypt/src/modes/xts/xts_done.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/** 
  Source donated by Elliptic Semiconductor Inc (www.ellipticsemi.com) to the LibTom Projects
*/

#ifdef LTC_XTS_MODE

/** Terminate XTS state 
   @param XTS    The state to terminate
*/
void xts_done(symmetric_xts *xts)
{
   LTC_ARGCHKVD(xts != NULL);
   cipher_descriptor[xts->cipher].done(&xts->key1);
   cipher_descriptor[xts->cipher].done(&xts->key2);
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/xts/xts_done.c,v $ */
/* $Revision: 1.4 $ */
/* $Date: 2007/03/10 23:59:09 $ */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































Deleted Source/libtomcrypt/src/modes/xts/xts_encrypt.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/** 
 Source donated by Elliptic Semiconductor Inc (www.ellipticsemi.com) to the LibTom Projects
 */

#ifdef LTC_XTS_MODE

static int tweak_crypt(const unsigned char *P, unsigned char *C, unsigned char *T, symmetric_xts *xts)
{
    unsigned long x;
    int err;
    
    /* tweak encrypt block i */
#ifdef LTC_FAST
    for (x = 0; x < 16; x += sizeof(LTC_FAST_TYPE)) {
        *((LTC_FAST_TYPE*)&C[x]) = *((LTC_FAST_TYPE*)&P[x]) ^ *((LTC_FAST_TYPE*)&T[x]);
    }
#else
    for (x = 0; x < 16; x++) {
        C[x] = P[x] ^ T[x];
    }
#endif
    
    if ((err = cipher_descriptor[xts->cipher].ecb_encrypt(C, C, &xts->key1)) != CRYPT_OK) {
        return err;
    }
    
#ifdef LTC_FAST
    for (x = 0; x < 16; x += sizeof(LTC_FAST_TYPE)) {
        *((LTC_FAST_TYPE*)&C[x]) ^= *((LTC_FAST_TYPE*)&T[x]);
    }
#else
    for (x = 0; x < 16; x++) {
        C[x] = C[x] ^ T[x];
    }
#endif
    
    /* LFSR the tweak */
    xts_mult_x(T);
    
    return CRYPT_OK;
}   

/** XTS Encryption
 @param pt     [in]  Plaintext
 @param ptlen  Length of plaintext (and ciphertext)
 @param ct     [out] Ciphertext
 @param tweak  [in] The 128--bit encryption tweak (e.g. sector number)
 @param xts    The XTS structure
 Returns CRYPT_OK upon success
 */
int xts_encrypt(
                const unsigned char *pt, unsigned long ptlen,
                unsigned char *ct,
                const unsigned char *tweak,
                symmetric_xts *xts)
{
    unsigned char PP[16], CC[16], T[16];
    unsigned long i, m, mo, lim;
    int           err;
    
    /* check inputs */
    LTC_ARGCHK(pt    != NULL);
    LTC_ARGCHK(ct    != NULL);
    LTC_ARGCHK(tweak != NULL);
    LTC_ARGCHK(xts   != NULL);
    
    /* check if valid */
    if ((err = cipher_is_valid(xts->cipher)) != CRYPT_OK) {
        return err;
    }
    
    // if the cipher has an accelerated logical block encryptor, call it.
    if(cipher_descriptor[xts->cipher].accel_xts_encrypt) return cipher_descriptor[xts->cipher].accel_xts_encrypt(pt, ptlen, ct, tweak, xts);
    
    /* get number of blocks */
    m  = ptlen >> 4;
    mo = ptlen & 15;
    
    /* must have at least one full block */
    if (m == 0) {
        return CRYPT_INVALID_ARG;
    }
    
    /* encrypt the tweak */
    if ((err = cipher_descriptor[xts->cipher].ecb_encrypt(tweak, T, &xts->key2)) != CRYPT_OK) {
        return err;
    }
    
    /* for i = 0 to m-2 do */
    if (mo == 0) {
        lim = m;
    } else {
        lim = m - 1;
    }
    
    for (i = 0; i < lim; i++) {
        err = tweak_crypt(pt, ct, T, xts);
        ct += 16;
        pt += 16;
    }
    
    /* if ptlen not divide 16 then */
    if (mo > 0) {
        /* CC = tweak encrypt block m-1 */
        if ((err = tweak_crypt(pt, CC, T, xts)) != CRYPT_OK) {
            return err;
        }
        
        /* Cm = first ptlen % 16 bytes of CC */
        for (i = 0; i < mo; i++) {
            PP[i] = pt[16+i];
            ct[16+i] = CC[i];
        }
        
        for (; i < 16; i++) {
            PP[i] = CC[i];
        }
        
        /* Cm-1 = Tweak encrypt PP */
        if ((err = tweak_crypt(PP, ct, T, xts)) != CRYPT_OK) {
            return err;
        }
    }
    
    return err;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/xts/xts_encrypt.c,v $ */
/* $Revision: 1.5 $ */
/* $Date: 2007/05/12 14:05:56 $ */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































Deleted Source/libtomcrypt/src/modes/xts/xts_init.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/** 
  Source donated by Elliptic Semiconductor Inc (www.ellipticsemi.com) to the LibTom Projects
*/

#ifdef LTC_XTS_MODE


/** Start XTS mode
   @param cipher      The index of the cipher to use
   @param key1        The encrypt key
   @param key2        The tweak encrypt key
   @param keylen      The length of the keys (each) in octets
   @param num_rounds  The number of rounds for the cipher (0 == default)
   @param xts         [out] XTS structure
   Returns CRYPT_OK upon success.
*/
#ifdef MACTOMCRYPT
int xts_start(int cipher, const unsigned char *IV, const unsigned char *key1, int keylen, const unsigned char *key2, int tweaklen,
	int num_rounds, int options, symmetric_xts *xts)
#else
int xts_start(int cipher, const unsigned char *key1, const unsigned char *key2, unsigned long keylen, int num_rounds, symmetric_xts *xts)
#endif


{
   int err;

   /* check inputs */
   LTC_ARGCHK(key1  != NULL);
   LTC_ARGCHK(key2  != NULL);
   LTC_ARGCHK(xts   != NULL);

   /* check if valid */
   if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
      return err;
   }

   if (cipher_descriptor[cipher].block_length != 16) {
      return CRYPT_INVALID_ARG;
   }

   /* schedule the two ciphers */
   if ((err = cipher_descriptor[cipher].setup(key1, keylen, num_rounds, &xts->key1)) != CRYPT_OK) {
      return err;
   }
   if ((err = cipher_descriptor[cipher].setup(key2, keylen, num_rounds, &xts->key2)) != CRYPT_OK) {
      return err;
   }
   xts->cipher = cipher;

   return err;
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/xts/xts_init.c,v $ */
/* $Revision: 1.4 $ */
/* $Date: 2007/03/10 23:59:09 $ */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































Deleted Source/libtomcrypt/src/modes/xts/xts_mult_x.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

/** 
  Source donated by Elliptic Semiconductor Inc (www.ellipticsemi.com) to the LibTom Projects
*/

#ifdef LTC_XTS_MODE

/** multiply by x 
  @param I      The value to multiply by x (LFSR shift)
*/
void xts_mult_x(unsigned char *I)
{
  int x;
  unsigned char t, tt;

  for (x = t = 0; x < 16; x++) {
     tt   = I[x] >> 7;
     I[x] = ((I[x] << 1) | t) & 0xFF;
     t    = tt;
  }
  if (tt) {
     I[0] ^= 0x87;
  } 
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/xts/xts_mult_x.c,v $ */
/* $Revision: 1.4 $ */
/* $Date: 2007/03/10 23:59:09 $ */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































Deleted Source/libtomcrypt/src/modes/xts/xts_test.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
 *
 * LibTomCrypt is a library that provides various cryptographic
 * algorithms in a highly modular and flexible manner.
 *
 * The library is free for all purposes without any express
 * guarantee it works.
 *
 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
 */
#include "tomcrypt.h"

#ifdef LTC_XTS_MODE

/** 
  Source donated by Elliptic Semiconductor Inc (www.ellipticsemi.com) to the LibTom Projects
  Returns CRYPT_OK upon success.
*/
int xts_test(void)
{
#ifdef LTC_NO_TEST
   return CRYPT_NOP;
#else
   static const struct {
      int keylen;
      unsigned char key1[32];
      unsigned char key2[32];
      ulong64 seqnum;
      unsigned long PTLEN;
      unsigned char PTX[512], CTX[512];
   } tests[] = {

/* #1 32 byte key, 32 byte PTX */
{
   32,
   { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
   { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
   0,
   32,
   { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },
   { 0x91,0x7c,0xf6,0x9e,0xbd,0x68,0xb2,0xec,0x9b,0x9f,0xe9,0xa3,0xea,0xdd,0xa6,0x92,0xcd,0x43,0xd2,0xf5,0x95,0x98,0xed,0x85,0x8c,0x02,0xc2,0x65,0x2f,0xbf,0x92,0x2e },
},

/* #2, 32 byte key, 32 byte PTX */
{
   32,
   { 0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11 },
   { 0x22,0x22,0x22,0x22,0x22,0x22,0x22,0x22,0x22,0x22,0x22,0x22,0x22,0x22,0x22,0x22 },
   CONST64(0x3333333333),
   32,
   { 0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44 },
   { 0xc4,0x54,0x18,0x5e,0x6a,0x16,0x93,0x6e,0x39,0x33,0x40,0x38,0xac,0xef,0x83,0x8b,0xfb,0x18,0x6f,0xff,0x74,0x80,0xad,0xc4,0x28,0x93,0x82,0xec,0xd6,0xd3,0x94,0xf0 },
},

/* #5 from xts.7, 32 byte key, 32 byte PTX */
{
   32,
   { 0xff,0xfe,0xfd,0xfc,0xfb,0xfa,0xf9,0xf8,0xf7,0xf6,0xf5,0xf4,0xf3,0xf2,0xf1,0xf0 },
   { 0xbf,0xbe,0xbd,0xbc,0xbb,0xba,0xb9,0xb8,0xb7,0xb6,0xb5,0xb4,0xb3,0xb2,0xb1,0xb0 },
   CONST64(0x123456789a),
   32,
   { 0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44,0x44 },
   { 0xb0,0x1f,0x86,0xf8,0xed,0xc1,0x86,0x37,0x06,0xfa,0x8a,0x42,0x53,0xe3,0x4f,0x28,0xaf,0x31,0x9d,0xe3,0x83,0x34,0x87,0x0f,0x4d,0xd1,0xf9,0x4c,0xbe,0x98,0x32,0xf1 },
},

/* #4, 32 byte key, 512 byte PTX  */
{
   32,
   { 0x27,0x18,0x28,0x18,0x28,0x45,0x90,0x45,0x23,0x53,0x60,0x28,0x74,0x71,0x35,0x26 },
   { 0x31,0x41,0x59,0x26,0x53,0x58,0x97,0x93,0x23,0x84,0x62,0x64,0x33,0x83,0x27,0x95 },
   0,
   512,
   {
0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,
0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f,
0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,
0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f,
0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f,
0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf,0xb0,0xb1,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0xbe,0xbf,
0xc0,0xc1,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xcb,0xcc,0xcd,0xce,0xcf,0xd0,0xd1,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xdb,0xdc,0xdd,0xde,0xdf,
0xe0,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xeb,0xec,0xed,0xee,0xef,0xf0,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa,0xfb,0xfc,0xfd,0xfe,0xff,
0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,
0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f,
0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,
0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f,
0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f,
0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf,0xb0,0xb1,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0xbe,0xbf,
0xc0,0xc1,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xcb,0xcc,0xcd,0xce,0xcf,0xd0,0xd1,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xdb,0xdc,0xdd,0xde,0xdf,
0xe0,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xeb,0xec,0xed,0xee,0xef,0xf0,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa,0xfb,0xfc,0xfd,0xfe,0xff,
   },
   {
0x27,0xa7,0x47,0x9b,0xef,0xa1,0xd4,0x76,0x48,0x9f,0x30,0x8c,0xd4,0xcf,0xa6,0xe2,0xa9,0x6e,0x4b,0xbe,0x32,0x08,0xff,0x25,0x28,0x7d,0xd3,0x81,0x96,0x16,0xe8,0x9c,
0xc7,0x8c,0xf7,0xf5,0xe5,0x43,0x44,0x5f,0x83,0x33,0xd8,0xfa,0x7f,0x56,0x00,0x00,0x05,0x27,0x9f,0xa5,0xd8,0xb5,0xe4,0xad,0x40,0xe7,0x36,0xdd,0xb4,0xd3,0x54,0x12,
0x32,0x80,0x63,0xfd,0x2a,0xab,0x53,0xe5,0xea,0x1e,0x0a,0x9f,0x33,0x25,0x00,0xa5,0xdf,0x94,0x87,0xd0,0x7a,0x5c,0x92,0xcc,0x51,0x2c,0x88,0x66,0xc7,0xe8,0x60,0xce,
0x93,0xfd,0xf1,0x66,0xa2,0x49,0x12,0xb4,0x22,0x97,0x61,0x46,0xae,0x20,0xce,0x84,0x6b,0xb7,0xdc,0x9b,0xa9,0x4a,0x76,0x7a,0xae,0xf2,0x0c,0x0d,0x61,0xad,0x02,0x65,
0x5e,0xa9,0x2d,0xc4,0xc4,0xe4,0x1a,0x89,0x52,0xc6,0x51,0xd3,0x31,0x74,0xbe,0x51,0xa1,0x0c,0x42,0x11,0x10,0xe6,0xd8,0x15,0x88,0xed,0xe8,0x21,0x03,0xa2,0x52,0xd8,
0xa7,0x50,0xe8,0x76,0x8d,0xef,0xff,0xed,0x91,0x22,0x81,0x0a,0xae,0xb9,0x9f,0x91,0x72,0xaf,0x82,0xb6,0x04,0xdc,0x4b,0x8e,0x51,0xbc,0xb0,0x82,0x35,0xa6,0xf4,0x34,
0x13,0x32,0xe4,0xca,0x60,0x48,0x2a,0x4b,0xa1,0xa0,0x3b,0x3e,0x65,0x00,0x8f,0xc5,0xda,0x76,0xb7,0x0b,0xf1,0x69,0x0d,0xb4,0xea,0xe2,0x9c,0x5f,0x1b,0xad,0xd0,0x3c,
0x5c,0xcf,0x2a,0x55,0xd7,0x05,0xdd,0xcd,0x86,0xd4,0x49,0x51,0x1c,0xeb,0x7e,0xc3,0x0b,0xf1,0x2b,0x1f,0xa3,0x5b,0x91,0x3f,0x9f,0x74,0x7a,0x8a,0xfd,0x1b,0x13,0x0e,
0x94,0xbf,0xf9,0x4e,0xff,0xd0,0x1a,0x91,0x73,0x5c,0xa1,0x72,0x6a,0xcd,0x0b,0x19,0x7c,0x4e,0x5b,0x03,0x39,0x36,0x97,0xe1,0x26,0x82,0x6f,0xb6,0xbb,0xde,0x8e,0xcc,
0x1e,0x08,0x29,0x85,0x16,0xe2,0xc9,0xed,0x03,0xff,0x3c,0x1b,0x78,0x60,0xf6,0xde,0x76,0xd4,0xce,0xcd,0x94,0xc8,0x11,0x98,0x55,0xef,0x52,0x97,0xca,0x67,0xe9,0xf3,
0xe7,0xff,0x72,0xb1,0xe9,0x97,0x85,0xca,0x0a,0x7e,0x77,0x20,0xc5,0xb3,0x6d,0xc6,0xd7,0x2c,0xac,0x95,0x74,0xc8,0xcb,0xbc,0x2f,0x80,0x1e,0x23,0xe5,0x6f,0xd3,0x44,
0xb0,0x7f,0x22,0x15,0x4b,0xeb,0xa0,0xf0,0x8c,0xe8,0x89,0x1e,0x64,0x3e,0xd9,0x95,0xc9,0x4d,0x9a,0x69,0xc9,0xf1,0xb5,0xf4,0x99,0x02,0x7a,0x78,0x57,0x2a,0xee,0xbd,
0x74,0xd2,0x0c,0xc3,0x98,0x81,0xc2,0x13,0xee,0x77,0x0b,0x10,0x10,0xe4,0xbe,0xa7,0x18,0x84,0x69,0x77,0xae,0x11,0x9f,0x7a,0x02,0x3a,0xb5,0x8c,0xca,0x0a,0xd7,0x52,
0xaf,0xe6,0x56,0xbb,0x3c,0x17,0x25,0x6a,0x9f,0x6e,0x9b,0xf1,0x9f,0xdd,0x5a,0x38,0xfc,0x82,0xbb,0xe8,0x72,0xc5,0x53,0x9e,0xdb,0x60,0x9e,0xf4,0xf7,0x9c,0x20,0x3e,
0xbb,0x14,0x0f,0x2e,0x58,0x3c,0xb2,0xad,0x15,0xb4,0xaa,0x5b,0x65,0x50,0x16,0xa8,0x44,0x92,0x77,0xdb,0xd4,0x77,0xef,0x2c,0x8d,0x6c,0x01,0x7d,0xb7,0x38,0xb1,0x8d,
0xeb,0x4a,0x42,0x7d,0x19,0x23,0xce,0x3f,0xf2,0x62,0x73,0x57,0x79,0xa4,0x18,0xf2,0x0a,0x28,0x2d,0xf9,0x20,0x14,0x7b,0xea,0xbe,0x42,0x1e,0xe5,0x31,0x9d,0x05,0x68,
   }
},

/* #7, 32 byte key, 17 byte PTX */
{
   32,
   { 0xff,0xfe,0xfd,0xfc,0xfb,0xfa,0xf9,0xf8,0xf7,0xf6,0xf5,0xf4,0xf3,0xf2,0xf1,0xf0 },
   { 0xbf,0xbe,0xbd,0xbc,0xbb,0xba,0xb9,0xb8,0xb7,0xb6,0xb5,0xb4,0xb3,0xb2,0xb1,0xb0 },
   CONST64(0x123456789a),
   17,
   { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10 },
   { 0x6c,0x16,0x25,0xdb,0x46,0x71,0x52,0x2d,0x3d,0x75,0x99,0x60,0x1d,0xe7,0xca,0x09,0xed },
},

/* #15, 32 byte key, 25 byte PTX */
{
   32,
   { 0xff,0xfe,0xfd,0xfc,0xfb,0xfa,0xf9,0xf8,0xf7,0xf6,0xf5,0xf4,0xf3,0xf2,0xf1,0xf0 },
   { 0xbf,0xbe,0xbd,0xbc,0xbb,0xba,0xb9,0xb8,0xb7,0xb6,0xb5,0xb4,0xb3,0xb2,0xb1,0xb0 },
   CONST64(0x123456789a),
   25,
   { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18 },
   { 0x8f,0x4d,0xcb,0xad,0x55,0x55,0x8d,0x7b,0x4e,0x01,0xd9,0x37,0x9c,0xd4,0xea,0x22,0xed,0xbf,0x9d,0xac,0xe4,0x5d,0x6f,0x6a,0x73 },
},

/* #21, 32 byte key, 31 byte PTX */
{
   32,
   { 0xff,0xfe,0xfd,0xfc,0xfb,0xfa,0xf9,0xf8,0xf7,0xf6,0xf5,0xf4,0xf3,0xf2,0xf1,0xf0 },
   { 0xbf,0xbe,0xbd,0xbc,0xbb,0xba,0xb9,0xb8,0xb7,0xb6,0xb5,0xb4,0xb3,0xb2,0xb1,0xb0 },
   CONST64(0x123456789a),
   31,
   { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e },
   { 0xd0,0x5b,0xc0,0x90,0xa8,0xe0,0x4f,0x1b,0x3d,0x3e,0xcd,0xd5,0xba,0xec,0x0f,0xd4,0xed,0xbf,0x9d,0xac,0xe4,0x5d,0x6f,0x6a,0x73,0x06,0xe6,0x4b,0xe5,0xdd,0x82 },
},

};
   unsigned char OUT[512], T[16];
   ulong64       seq;
   symmetric_xts xts;
   int           i, err, idx;

   /* AES can be under rijndael or aes... try to find it */ 
   if ((idx = find_cipher("aes")) == -1) {
      if ((idx = find_cipher("rijndael")) == -1) {
         return CRYPT_NOP;
      }
   }

   for (i = 0; i < (int)(sizeof(tests)/sizeof(tests[0])); i++) {
#ifdef MACTOMCRYPT
       err = xts_start(idx, NULL, tests[i].key1, tests[i].keylen/2, tests[i].key2, 0, 0, 0, &xts);
#else
       err = xts_start(idx, tests[i].key1, tests[i].key2, tests[i].keylen/2, 0, &xts);
#endif
       if (err != CRYPT_OK) {
          return err;
       }
 
       seq = tests[i].seqnum;
       STORE64L(seq,T);
       XMEMSET(T+8, 0, 8);

       err = xts_encrypt(tests[i].PTX, tests[i].PTLEN, OUT, T, &xts);
       if (err != CRYPT_OK) {
          xts_done(&xts);
          return err;
       }

       if (XMEMCMP(OUT, tests[i].CTX, tests[i].PTLEN)) {
          xts_done(&xts);
          return CRYPT_FAIL_TESTVECTOR;
       }

       err = xts_decrypt(tests[i].CTX, tests[i].PTLEN, OUT, T, &xts);
       if (err != CRYPT_OK) {
          xts_done(&xts);
          return err;
       }

       if (XMEMCMP(OUT, tests[i].PTX, tests[i].PTLEN)) {
          xts_done(&xts);
          return CRYPT_FAIL_TESTVECTOR;
       }
       xts_done(&xts);
   }
   return CRYPT_OK;
#endif
}

#endif

/* $Source: /cvs/libtom/libtomcrypt/src/modes/xts/xts_test.c,v $ */
/* $Revision: 1.4 $ */
/* $Date: 2007/03/10 23:59:09 $ */

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






















































































































































































































































































































































































































Deleted Source/libtomcrypt/src/padding/ansix923/ansi923pad.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */




/*
 *  ansi923pad.c
 *  MacTomCrypt
 *
 *		ANSI.923 padding mode functions.
 */


#include "ansi923pad.h"

#define MAXBLOCKSIZE_ANSI923 128

int
ansi923_pad(char *buff, size_t blocksize, size_t startpoint) {
	char padbyte;
	int  i;

	if((buff == NULL) || (blocksize > MAXBLOCKSIZE_ANSI923) || (startpoint > blocksize)) return -1;
	padbyte = blocksize - startpoint;
	if(padbyte == 0) padbyte = blocksize;

	for(i = 0; i < padbyte; i++) buff[startpoint + i] = 0;
	buff[startpoint + padbyte - 1] = padbyte;
	return padbyte;
}


int
ansi923_len(size_t blocksize) {
    if(blocksize > MAXBLOCKSIZE_ANSI923) return -1;
    return blocksize * 2;
}

int
ansi923_unpadlen(char *buff, size_t blocksize) {
    if(blocksize > MAXBLOCKSIZE_ANSI923) return -1;
	 if(buff == NULL) return -1;
    return blocksize - *(buff + blocksize - 1);
}


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































































Deleted Source/libtomcrypt/src/padding/ansix923/ansi923pad.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include <stdint.h>
#include <stddef.h>

/*
 *  ansi923.h
 *  MacTomCrypt
 *
 *		ANSI.923 padding mode functions.
 */

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Fill out the padding for a buffer.  The blocksize and starting points are used to determine how much needs
 * to be padded.  If startpoint is blocksize+1 then a full new buffer is added.  Blocksize cannot be greater
 * than 256.
 */
 
int
ansi923_pad(char *buff, size_t blocksize, size_t startpoint);

/*
 * Given the last buffer containing the pad, how many bytes is the original text?
 * returns -1 on error.
 */
 
int
ansi923_unpadlen(char *buff, size_t blocksize);

/*
 * Maximum space needed for padding.  For ANSI.923 this is blocksize*2
 */
 
int
ansi923_len(size_t blocksize);

#ifdef __cplusplus
}
#endif

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































Deleted Source/libtomcrypt/src/padding/iso10126/iso10126pad.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */




/*
 *  iso10126pad.c
 *  MacTomCrypt
 *
 * iso10126 padding mode functions.
 */


#include "iso10126pad.h"

#define MAXBLOCKSIZE_ISO10126 128

int
iso10126_pad(char *buff, size_t blocksize, size_t startpoint) {
	char padbyte;
	int  i;

	if((buff == NULL) || (blocksize > MAXBLOCKSIZE_ISO10126) || (startpoint > blocksize)) return -1;
	padbyte = blocksize - startpoint;
	if(padbyte != 0) {
		for(i = 0; i < padbyte; i++) buff[startpoint + i] = 0 /* ZZZ Random source needed */;
	}
	return padbyte;
}


int
iso10126_len(size_t blocksize) {
    if(blocksize > MAXBLOCKSIZE_ISO10126) return -1;
    return blocksize;
}

int
iso10126_unpadlen(char *buff, size_t blocksize) {
    if(blocksize > MAXBLOCKSIZE_ISO10126) return -1;
		if(buff == NULL) return -1;
    return blocksize;
}


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































Deleted Source/libtomcrypt/src/padding/iso10126/iso10126pad.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include <stdint.h>
#include <stddef.h>

/*
 *  iso10126pad.h
 *  MacTomCrypt
 *
 * iso10126 padding mode functions.
 */

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Fill out the padding for a buffer.  The blocksize and starting points are used to determine how much needs
 * to be padded.  If startpoint is blocksize+1 then a full new buffer is added.  Blocksize cannot be greater
 * than 256.
 */
 
int
iso10126_pad(char *buff, size_t blocksize, size_t startpoint);

/*
 * Given the last buffer containing the pad, how many bytes is the original text?
 * returns -1 on error.
 */
 
int
iso10126_unpadlen(char *buff, size_t blocksize);

/*
 * Maximum space needed for padding.  For iso10126 this is blocksize*2
 */
 
int
iso10126_len(size_t blocksize);

#ifdef __cplusplus
}
#endif

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































Deleted Source/libtomcrypt/src/padding/nopadding/nopad.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */




/*
 *  nopad.c
 *  MacTomCrypt
 *
 *	No padding mode functions.
 */


#include "nopad.h"

int
no_pad(char *buff, size_t blocksize, size_t startpoint) {
	return 0;
}


int
no_len(size_t blocksize) {
	return 0;
}

int
no_unpadlen(char *buff, size_t blocksize) {
	return blocksize;
}


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































Deleted Source/libtomcrypt/src/padding/nopadding/nopad.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include <stdint.h>
#include <stddef.h>

/*
 *  nopad.h
 *  MacTomCrypt
 *
 *  No padding mode functions.
 */

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Fill out the padding for a buffer.  The blocksize and starting points are used to determine how much needs
 * to be padded.  If startpoint is blocksize+1 then a full new buffer is added.  Blocksize cannot be greater
 * than 256.
 */
 
int
no_pad(char *buff, size_t blocksize, size_t startpoint);

/*
 * Given the last buffer containing the pad, how many bytes is the original text?
 * returns -1 on error.
 */
 
int
no_unpadlen(char *buff, size_t blocksize);

/*
 * Maximum space needed for padding.  For PKCS7 this is blocksize*2
 */
 
int
no_len(size_t blocksize);

#ifdef __cplusplus
}
#endif

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































Deleted Source/libtomcrypt/src/padding/pkcs7/pkcs7pad.c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */




/*
 *  pkcs7pad.c
 *  MacTomCrypt
 *
 * PKCS7 padding mode functions.
 */


#include "pkcs7pad.h"

#define MAXBLOCKSIZE_PKCS7 128

int
pkcs7_pad(char *buff, size_t blocksize, size_t startpoint) {
	char padbyte;
	int  i;

	if((buff == NULL) || (blocksize > MAXBLOCKSIZE_PKCS7) || (startpoint > blocksize)) return -1;
	padbyte = blocksize - startpoint;
	if(padbyte == 0) padbyte = blocksize;

	for(i = 0; i < padbyte; i++) buff[startpoint + i] = padbyte;
	return padbyte;
}


int
pkcs7_len(size_t blocksize) {
    if(blocksize > MAXBLOCKSIZE_PKCS7) return -1;
    return blocksize * 2;
}

int
pkcs7_unpadlen(char *buff, size_t blocksize) {
    if(blocksize > MAXBLOCKSIZE_PKCS7) return -1;
	 if(buff == NULL) return -1;
    return blocksize - buff[blocksize - 1];
}


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































Deleted Source/libtomcrypt/src/padding/pkcs7/pkcs7pad.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

#include <stdint.h>
#include <stddef.h>

/*
 *  pkcs7pad.h
 *  MacTomCrypt
 *
 * PKCS7 padding mode functions.
 */

#ifdef __cplusplus
extern "C" {
#endif

/*
 * Fill out the padding for a buffer.  The blocksize and starting points are used to determine how much needs
 * to be padded.  If startpoint is blocksize+1 then a full new buffer is added.  Blocksize cannot be greater
 * than 256.
 */
 
int
pkcs7_pad(char *buff, size_t blocksize, size_t startpoint);

/*
 * Given the last buffer containing the pad, how many bytes is the original text?
 * returns -1 on error.
 */
 
int
pkcs7_unpadlen(char *buff, size_t blocksize);

/*
 * Maximum space needed for padding.  For PKCS7 this is blocksize*2
 */
 
int
pkcs7_len(size_t blocksize);

#ifdef __cplusplus
}
#endif

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































Deleted UnitTestSource/CCMemoryHandler.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//
//  CCMemoryHandler.h
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import <Cocoa/Cocoa.h>

class CCMemoryHandler
{
protected:
	NSMutableArray*	_memoryList;
	
private:
	// disallow heap based instances of this class
	void* operator new (size_t size)
	{
		return ::operator new(size);
	}
	
public:
	CCMemoryHandler() :
	_memoryList(nil)
	{
		_memoryList	= [NSMutableArray new];
	}
	
	virtual ~CCMemoryHandler()
	{
		[_memoryList release];
		_memoryList = nil;
	}
	
	void* malloc(size_t size);	
};

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































Deleted UnitTestSource/CCMemoryHandler.mm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//
//  CCMemoryHandler.mm
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import "CCMemoryHandler.h"

@interface CCMemoryAllocation : NSObject
{
	void*		_allocation;
}

@property (readonly) void* allocation;

- (id)initWithMemSize:(size_t)size;

@end

@implementation CCMemoryAllocation

@synthesize  allocation = _allocation;

- (id)initWithMemSize:(size_t)size
{
	_allocation = NULL;
	if ((self = [super init]))
	{
		_allocation = malloc(size);
		memset(_allocation, 0, size);
	}
	return self;
}

- (void)dealloc
{
	if (_allocation != NULL)
	{
		free(_allocation);
		_allocation = NULL;
	}
	[super dealloc];
}

@end

void* CCMemoryHandler::malloc(size_t size)
{
	CCMemoryAllocation* allocObj = [[CCMemoryAllocation alloc] initWithMemSize:size];
	void* result = allocObj.allocation;
	[_memoryList addObject:allocObj];
	return result;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































Deleted UnitTestSource/CommonCryptoUnitTests-Info.plist.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleDevelopmentRegion</key>
	<string>English</string>
	<key>CFBundleExecutable</key>
	<string>${EXECUTABLE_NAME}</string>
	<key>CFBundleIdentifier</key>
	<string>com.yourcompany.${PRODUCT_NAME:rfc1034identifier}</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundlePackageType</key>
	<string>BNDL</string>
	<key>CFBundleShortVersionString</key>
	<string>1.0</string>
	<key>CFBundleSignature</key>
	<string>????</string>
	<key>CFBundleVersion</key>
	<string>1</string>
</dict>
</plist>
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































Deleted UnitTestSource/CommonCryptoUnitTests.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//
//  CommonCryptoUnitTests.h
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#import <SenTestingKit/SenTestingKit.h>
#import "TestToolProtocol.h"


@interface CommonCryptoUnitTests : SenTestCase  <TestToolProtocol>
{
	// No member variables
}

// This allows an object that is NOT subclassed from SenTestCase to issue 
// an assert
- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr;

@end
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































Deleted UnitTestSource/CommonCryptoUnitTests.mm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
//
//  CommonCryptoUnitTests.mm
//  CommonCrypto
//
//  Created by Jim Murphy on 1/11/10.
//  Copyright 2010 Apple Inc. All rights reserved.
//

#import "CommonCryptoUnitTests.h"
#import "DigestTest.h"
#include "CommonDigest.h"
#include "CommonCryptor.h"
#include "CommonHMAC.h"
#include "RandomNumberService.h"
#import "EncryptionTest.h"
#import "HMACTest.h"
#import "PBKDFTest.h"
#import "SymmetricWrapTest.h"
#import "CommonRandomSPI.h"


// - (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr;
/* --------------------------------------------------------------------------
	class: 			CommonCryptoUnitTests
	description: 	Implementation of the unit tests for the CommonCrypto
					library	
   -------------------------------------------------------------------------- */
@implementation CommonCryptoUnitTests

/* --------------------------------------------------------------------------
	method: 		-(void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr
	decription: 	Provide a way for class that is NOT subclassed from 
					SenTestCase have an assert
   -------------------------------------------------------------------------- */
-(void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr	
{
	STAssertTrue(result, errorStr);
}

/* --------------------------------------------------------------------------
	method: 		- (void)testDigests
	decription: 	Test all of the digest algorithms in the CommonCrypto
					library
   -------------------------------------------------------------------------- */
- (void)testDigests	
{
	NSAutoreleasePool *pool = [NSAutoreleasePool new];	
	
	NSLog(@"%@", @"In the testDigest method");
	
	NSArray* digestTests = [CCDigestTestObject setupDigestTests:self];
	
	for (CCDigestTestObject* testObject in digestTests)
	{
		NSLog(@"Running test for %@", testObject.digestName);
		[testObject runTest];
	}
	
	[pool drain];
}

/* --------------------------------------------------------------------------
	method: 		- (void)testEncryption
	decription: 	Test all of the encryption algorithms in the CommonCrypto
					library
   -------------------------------------------------------------------------- */
- (void)testEncryption	
{
	
	NSAutoreleasePool *pool = [NSAutoreleasePool new];	
	
	NSLog(@"%@", @"In the testEncryption method");
	NSArray* encryptionTests = [CCEncryptionTest setupEncryptionTests:self];
								
	for (CCEncryptionTest* aTest in encryptionTests)
	{
		NSLog(@"Running test for %@", aTest.algName);
		[aTest runTest];
	}
	
		
	[pool drain];
	
}

/* --------------------------------------------------------------------------
	method: 		- (void)testHMAC
	decription: 	Test all of the HMAC algorithms in the CommonCrypto library
   -------------------------------------------------------------------------- */
- (void)testHMAC
{
	NSAutoreleasePool *pool = [NSAutoreleasePool new];	
	
	NSLog(@"%@", @"In the testHMAC method");
	NSArray* hmacTests = [CCHMACTestObject setupHMACTests:self];
	
	for (CCHMACTestObject* aTest in hmacTests)
	{
		NSLog(@"Running test for %@", aTest.nameHMAC);
		[aTest runTest];
	}
	
	
	[pool drain];
}

/* --------------------------------------------------------------------------
 method: 		- (void)testPBKDF
 decription: 	Test all of the PBKDF algorithms in the CommonCrypto library
 -------------------------------------------------------------------------- */
- (void)testPBKDF
{
	NSAutoreleasePool *pool = [NSAutoreleasePool new];	
	
	NSLog(@"%@", @"In the testPBKDF method");
	printf("Starting\n");
	NSArray* pbkdfTests = [CCDerviationTestObject setupPBKDFTests:self];
	
	for (CCDerviationTestObject* aTest in pbkdfTests)
	{
		NSLog(@"Running test for %@", aTest.namePBKDF);
		[aTest runTest];
	}
	
	
	[pool drain];
}


/* --------------------------------------------------------------------------
 method: 		- (void)testSymmetricWrap
 decription: 	Test all of the SymmetricWrap algorithms in the CommonCrypto library
 -------------------------------------------------------------------------- */
- (void)testSymmetricWrap
{
	NSAutoreleasePool *pool = [NSAutoreleasePool new];	
	
	NSLog(@"%@", @"In the testSymmetricWrap method");
	NSArray* SymmetricWrapTests = [CCSymmetricalWrapTest setupSymmWrapTests:self];
	
	for (CCSymmetricalWrapTest* aTest in SymmetricWrapTests)
	{
		NSLog(@"%@", @"About to call the unit test");
		[aTest runTest];
	}
	
	[pool drain];
}

/* --------------------------------------------------------------------------
 method: 		- (void)testRandomCopyBytes
 decription: 	Test the main PRNG for non-repeatability
 -------------------------------------------------------------------------- */
- (void)testRandomCopyBytes
{
	NSAutoreleasePool *pool = [NSAutoreleasePool new];	
    uint8_t bytes[1024];
    uint8_t previous[1024];
    int i;
    
	NSLog(@"%@", @"In the testRandomCopyBytes method");
    bzero(previous, 1024);
    for(i=0; i<1024; i++) {
        int retval =  CCRandomCopyBytes(kCCRandomDefault, bytes, 1024);
        if(retval) {
            NSLog(@"%@", @"Failed call to CCRandomCopyBytes");
        }
        
        if(memcmp(previous, bytes, 1024) == 0) {
            NSLog(@"%@", @"Failed - random bytes match (1024 bytes)");
        }
        
        memcpy(previous, bytes, 1024);
    }

	
	[pool drain];
}


@end


<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































































































































Deleted UnitTestSource/DigestTest.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//
//  DigestTest.h
//  CommonCrypto
//
//  Created by Jim Murphy on 1/12/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#include "CommonDigest.h"
#include "CommonDigestSPI.h"
#import "TestToolProtocol.h"

/* ==========================================================================
	Type defined by this file
   ========================================================================== */

// Block definition for initializing a staged digest 
typedef int (^initBlock)(void *ctx);

// Block definition for updating a staged digest
typedef int (^updateBlock)(void *ctx, const void *data, CC_LONG len);

// Block definition for finalizing a staged digest
typedef int (^finalBlock)(unsigned char *md, void *ctx);

// Block definition for a 'one shot' digest
typedef unsigned char* (^oneShotBlock)(const void *data, CC_LONG len, unsigned char *md);

/* ==========================================================================
	Defines used by this file
   ========================================================================== */

#define MIN_DATA_SIZE	1
#define MAX_DATA_SIZE	10000			/* bytes */
#define MAX_DIGEST_SIZE		64
#define MAX_CONTEXT_SIZE	CC_DIGEST_SIZE


/* --------------------------------------------------------------------------
	Class: 			CCDigestTestObject
	Description: 	This class provides for testing a digest type
   -------------------------------------------------------------------------- */

@interface CCDigestTestObject : NSObject
{
	NSString*		_digestName;				// The name of the digest type
	size_t			_digestSize;				// The size of the digest
	initBlock		_initBlock;					// Block that initialize a staged digest
	updateBlock		_updateBlock;				// Block that updates a staged digest
	finalBlock		_finalBlock;				// Block that finalizes a staged digest
	oneShotBlock	_oneShotBlock;				// Block that does a 'one shot' digest
	NSData*			_stagedResult;				// Result of the staged digest
	NSData*			_oneShotResult;				// Result of the 'one shot' digest
	NSData*			_digestData;				// Data to be digested
	unsigned char	_context[MAX_CONTEXT_SIZE];	// Working digest buffer
	id<TestToolProtocol>
					_testObject;				// The owning test object NOT retained	
	BOOL			_testPassed;
}

@property (readonly) NSString* digestName;
@property (readonly) size_t digestSize;
@property (readonly) NSData* stagedResult;
@property (readonly) NSData* oneShotResult;
@property (readonly) NSData* digestData;
@property (readwrite, assign) id<TestToolProtocol> testObject;
@property (readonly) BOOL testPassed;


+ (NSArray *)setupDigestTests:(id<TestToolProtocol>)testObject;


- (id)initWithDigestName:(NSString *)name withDigestSize:(size_t)size 
	withInitBlock:(initBlock)initDigest
	withUpdateBlock:(updateBlock)updateDigest
	withFinalBlock:(finalBlock)completeDigest
	withOneShotBlock:(oneShotBlock)oneShotDigest;

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr;

- (void)runTest;

@end
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































































Deleted UnitTestSource/DigestTest.mm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//
//  DigestTest.mm
//  CommonCrypto
//
//  Created by Jim Murphy on 1/12/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import "DigestTest.h"
#import "RandomNumberService.h"
#include "CommonDigest.h"
#include "CommonDigestSPI.h"
#include <stdio.h>


@implementation CCDigestTestObject

@synthesize digestName = _digestName;
@synthesize digestSize = _digestSize;
@synthesize stagedResult = _stagedResult;
@synthesize oneShotResult = _oneShotResult;
@synthesize digestData = _digestData;
@synthesize testObject = _testObject;
@synthesize testPassed = _testPassed;


/* --------------------------------------------------------------------------
	method: 		setupDigestTests
	returns: 		NSArray *												
	decription: 	This method allows for creating digest specific tests for
					all of the digest supported by the CommonCrypto library.
					It creates an instance of the CCDigestTestObject for
					each digest to be tested and places that object into
					an NSArray.
   -------------------------------------------------------------------------- */
+ (NSArray *)setupDigestTests:(id<TestToolProtocol>)testObject;
{
	initBlock anInitBlock;
	updateBlock anUpdateBlock;
	finalBlock aFinalBlock;
	oneShotBlock anOneShotBlock;
	
	NSMutableArray* result = [NSMutableArray array]; // autoreleased
	
	// --------------------- MD2 Digest ----------------------
	anInitBlock = ^(void *ctx)
	{
		return CC_MD2_Init((CC_MD2_CTX *)ctx);
	};
	
	anUpdateBlock = ^(void *ctx, const void *data, CC_LONG len)
	{
		return CC_MD2_Update((CC_MD2_CTX *)ctx, data, len);
	};
	
	aFinalBlock = ^(unsigned char *md, void *ctx)
	{
		return CC_MD2_Final(md, (CC_MD2_CTX *)ctx);
	};
	
	anOneShotBlock = ^(const void *data, CC_LONG len, unsigned char *md)
	{
		return CC_MD2(data, len, md);
	};
	
	CCDigestTestObject* md2DigestTest = [[[CCDigestTestObject alloc] 
		initWithDigestName:@"MD2" 
		withDigestSize:CC_MD2_DIGEST_LENGTH 
		withInitBlock:anInitBlock
		withUpdateBlock:anUpdateBlock
		withFinalBlock:aFinalBlock
		withOneShotBlock:anOneShotBlock] autorelease];
		
	md2DigestTest.testObject = testObject;
		
	[result addObject:md2DigestTest];
	
	// --------------------- MD4 Digest ----------------------
	anInitBlock = ^(void *ctx)
	{
		return CC_MD4_Init((CC_MD4_CTX *)ctx);
	};
	
	anUpdateBlock = ^(void *ctx, const void *data, CC_LONG len)
	{
		return CC_MD4_Update((CC_MD4_CTX *)ctx, data, len);
	};
	
	aFinalBlock = ^(unsigned char *md, void *ctx)
	{
		return CC_MD4_Final(md, (CC_MD4_CTX *)ctx);
	};
	
	anOneShotBlock = ^(const void *data, CC_LONG len, unsigned char *md)
	{
		return CC_MD4(data, len, md);
	};
	
	CCDigestTestObject* md4DigestTest = [[[CCDigestTestObject alloc] initWithDigestName:@"MD4" 
		withDigestSize:CC_MD4_DIGEST_LENGTH 
		withInitBlock:anInitBlock
		withUpdateBlock:anUpdateBlock
		withFinalBlock:aFinalBlock
		withOneShotBlock:anOneShotBlock] autorelease];
		
	md4DigestTest.testObject = testObject;
		
	[result addObject:md4DigestTest];
	
	// --------------------- MD5 Digest ----------------------
	
	anInitBlock = ^(void *ctx)
	{
		return CC_MD5_Init((CC_MD5_CTX *)ctx);
	};
	
	anUpdateBlock = ^(void *ctx, const void *data, CC_LONG len)
	{
		return CC_MD5_Update((CC_MD5_CTX *)ctx, data, len);
	};
	
	aFinalBlock = ^(unsigned char *md, void *ctx)
	{
		return CC_MD5_Final(md, (CC_MD5_CTX *)ctx);
	};
	
	anOneShotBlock = ^(const void *data, CC_LONG len, unsigned char *md)
	{
		return CC_MD5(data, len, md);
	};
	
	CCDigestTestObject* md5DigestTest = [[[CCDigestTestObject alloc] initWithDigestName:@"MD5" 
		withDigestSize:CC_MD5_DIGEST_LENGTH 
		withInitBlock:anInitBlock
		withUpdateBlock:anUpdateBlock
		withFinalBlock:aFinalBlock
		withOneShotBlock:anOneShotBlock] autorelease];
		
	md5DigestTest.testObject = testObject;
		
	[result addObject:md5DigestTest];
	
	// --------------------- SHA1 Digest ----------------------
		
	anInitBlock = ^(void *ctx)
	{
		return CC_SHA1_Init((CC_SHA1_CTX *)ctx);
	};
	
	anUpdateBlock = ^(void *ctx, const void *data, CC_LONG len)
	{
		return CC_SHA1_Update((CC_SHA1_CTX *)ctx, data, len);
	};
	
	aFinalBlock = ^(unsigned char *md, void *ctx)
	{
		return CC_SHA1_Final(md, (CC_SHA1_CTX *)ctx);
	};
	
	anOneShotBlock = ^(const void *data, CC_LONG len, unsigned char *md)
	{
		return CC_SHA1(data, len, md);
	};
	
	CCDigestTestObject* sha1DigestTest = [[[CCDigestTestObject alloc] initWithDigestName:@"SHA1" 
		withDigestSize:CC_SHA1_DIGEST_LENGTH 
		withInitBlock:anInitBlock
		withUpdateBlock:anUpdateBlock
		withFinalBlock:aFinalBlock
		withOneShotBlock:anOneShotBlock] autorelease];
		
	sha1DigestTest.testObject = testObject;
		
	[result addObject:sha1DigestTest];
	
	// --------------------- SHA224 Digest ----------------------
	
	anInitBlock = ^(void *ctx)
	{
		return CC_SHA224_Init((CC_SHA256_CTX *)ctx);
	};
	
	anUpdateBlock = ^(void *ctx, const void *data, CC_LONG len)
	{
		return CC_SHA224_Update((CC_SHA256_CTX *)ctx, data, len);
	};
	
	aFinalBlock = ^(unsigned char *md, void *ctx)
	{
		return CC_SHA224_Final(md, (CC_SHA256_CTX *)ctx);
	};
	
	anOneShotBlock = ^(const void *data, CC_LONG len, unsigned char *md)
	{
		return CC_SHA224(data, len, md);
	};
	
	CCDigestTestObject* sha224DigestTest = [[[CCDigestTestObject alloc] initWithDigestName:@"SHA224" 
		withDigestSize:CC_SHA224_DIGEST_LENGTH 
		withInitBlock:anInitBlock
		withUpdateBlock:anUpdateBlock
		withFinalBlock:aFinalBlock
		withOneShotBlock:anOneShotBlock] autorelease];
		
	sha224DigestTest.testObject = testObject;
		
	[result addObject:sha224DigestTest];
	
	// --------------------- SHA256 Digest ----------------------
	
	anInitBlock = ^(void *ctx)
	{
		return CC_SHA256_Init((CC_SHA256_CTX *)ctx);
	};
	
	anUpdateBlock = ^(void *ctx, const void *data, CC_LONG len)
	{
		return CC_SHA256_Update((CC_SHA256_CTX *)ctx, data, len);
	};
	
	aFinalBlock = ^(unsigned char *md, void *ctx)
	{
		return CC_SHA256_Final(md, (CC_SHA256_CTX *)ctx);
	};
	
	anOneShotBlock = ^(const void *data, CC_LONG len, unsigned char *md)
	{
		return CC_SHA256(data, len, md);
	};
	
	CCDigestTestObject* sha256DigestTest = [[[CCDigestTestObject alloc] initWithDigestName:@"SHA256" 
		withDigestSize:CC_SHA256_DIGEST_LENGTH 
		withInitBlock:anInitBlock
		withUpdateBlock:anUpdateBlock
		withFinalBlock:aFinalBlock
		withOneShotBlock:anOneShotBlock] autorelease];
		
	sha224DigestTest.testObject = testObject;
		
	[result addObject:sha256DigestTest];
	
	// --------------------- SHA384 Digest ----------------------
	
	anInitBlock = ^(void *ctx)
	{
		return CC_SHA384_Init((CC_SHA512_CTX *)ctx);
	};
	
	anUpdateBlock = ^(void *ctx, const void *data, CC_LONG len)
	{
		return CC_SHA384_Update((CC_SHA512_CTX *)ctx, data, len);
	};
	
	aFinalBlock = ^(unsigned char *md, void *ctx)
	{
		return CC_SHA384_Final(md, (CC_SHA512_CTX *)ctx);
	};
	
	anOneShotBlock = ^(const void *data, CC_LONG len, unsigned char *md)
	{
		return CC_SHA384(data, len, md);
	};
	
	CCDigestTestObject* sha384DigestTest = [[[CCDigestTestObject alloc] initWithDigestName:@"SHA384" 
		withDigestSize:CC_SHA384_DIGEST_LENGTH 
		withInitBlock:anInitBlock
		withUpdateBlock:anUpdateBlock
		withFinalBlock:aFinalBlock
		withOneShotBlock:anOneShotBlock] autorelease];
		
	sha384DigestTest.testObject = testObject;
		
	[result addObject:sha384DigestTest];
	
	// --------------------- SHA512 Digest ----------------------
	
	anInitBlock = ^(void *ctx)
	{
		return CC_SHA512_Init((CC_SHA512_CTX *)ctx);
	};
	
	anUpdateBlock = ^(void *ctx, const void *data, CC_LONG len)
	{
		return CC_SHA512_Update((CC_SHA512_CTX *)ctx, data, len);
	};
	
	aFinalBlock = ^(unsigned char *md, void *ctx)
	{
		return CC_SHA512_Final(md, (CC_SHA512_CTX *)ctx);
	};
	
	anOneShotBlock = ^(const void *data, CC_LONG len, unsigned char *md)
	{
		return CC_SHA512(data, len, md);
	};
	
	CCDigestTestObject* sha512DigestTest = [[[CCDigestTestObject alloc] initWithDigestName:@"SHA512" 
		withDigestSize:CC_SHA512_DIGEST_LENGTH 
		withInitBlock:anInitBlock
		withUpdateBlock:anUpdateBlock
		withFinalBlock:aFinalBlock
		withOneShotBlock:anOneShotBlock] autorelease];
		
	sha512DigestTest.testObject = testObject;
		
	[result addObject:sha512DigestTest];
	
	// --------------------- Skein512 Digest ----------------------

		
	anInitBlock = ^(void *ctx)
	{
		return CCDigestInit(kCCDigestSkein512, (CCDigestCtx *)ctx);
	};
	
	anUpdateBlock = ^(void *ctx, const void *data, CC_LONG len)
	{
		return CCDigestUpdate((CCDigestCtx *)ctx, (const uint8_t *) data, len);
	};
	
	aFinalBlock = ^(unsigned char *md, void *ctx)
	{
		return CCDigestFinal((CCDigestCtx *)ctx, md);
	};
	
	anOneShotBlock = ^(const void *data, CC_LONG len, unsigned char *md)
	{
		return (unsigned char *) CCDigest(kCCDigestSkein512, (const uint8_t *)data, len, (uint8_t *)md);
	};
	
	CCDigestTestObject* skein512DigestTest = [[[CCDigestTestObject alloc] initWithDigestName:@"Skein512 (CommonHash)" 
																			withDigestSize:CC_SHA512_DIGEST_LENGTH 
																			 withInitBlock:anInitBlock
																		   withUpdateBlock:anUpdateBlock
																			withFinalBlock:aFinalBlock
																		  withOneShotBlock:anOneShotBlock] autorelease];
	
	skein512DigestTest.testObject = testObject;
	
	[result addObject:skein512DigestTest];
	

	
	return result;
}


/* --------------------------------------------------------------------------
	method: 		initWithDigestName:withDigestSize:withInitBlock:withUpdateBlock:withFinalBlock:withOneShotBlock:
	returns: 		new CCDigestTestObject object
	parameters:
					name:
						Then name of the digest type i.e. SHA1
					size:
						The size in bytes of the digest for the specified type
					initDigest:
						A block to initialize a staged digest
					updateDigest:
						A block to update a staged digest
					completeDigest:
						A block to finalize a staged digest
					oneShotDigest:
						A block to do a 'one shot' digest
						
												
	decription: 	Initalize a new Digest testing object
   -------------------------------------------------------------------------- */
- (id)initWithDigestName:(NSString *)name withDigestSize:(size_t)size 
	withInitBlock:(initBlock)initDigest
	withUpdateBlock:(updateBlock)updateDigest
	withFinalBlock:(finalBlock)completeDigest
	withOneShotBlock:(oneShotBlock)oneShotDigest
{
	if ((self = [super init]))
	{
		_testPassed = YES;
		[self doAssertTest:(NULL != name) errorString:@"CCDigestTestObject.init received a nil Name"];
		[self doAssertTest:(size > 0) errorString:@"CCDigestTestObject.init got a 0 buffer size"];
		[self doAssertTest:(0 != initDigest) errorString:@"CCDigestTestObject.init received a NULL InitBlock"];
		[self doAssertTest:(0 != updateDigest) errorString:@"CCDigestTestObject.init received a NULL UpdateBlock"];
		[self doAssertTest:(0 != completeDigest) errorString:@"CCDigestTestObject.init received a NULL CompleteDigestBlock"];
		[self doAssertTest:(0 != oneShotDigest) errorString:@"CCDigestTestObject.init received a NULL OneShotBlock"];
		
		_digestName = [name copy];
		_digestSize = size;
		_initBlock = [initDigest copy];
		_updateBlock = [updateDigest copy];
		_finalBlock = [completeDigest copy];
		_oneShotBlock = [oneShotDigest copy];
		
		// Create the data that will be digested by this test.
		CCRandomNumberService* randNumService = [CCRandomNumberService defaultRandomNumberService];
		unsigned int randomDataLength = [randNumService generateRandomNumberInRange:MIN_DATA_SIZE toMax:MAX_DATA_SIZE];
		_digestData = [[randNumService generateRandomDataOfSize:randomDataLength] retain];
		memset(_context, 0, MAX_CONTEXT_SIZE);
	}
	return self;
}

/* --------------------------------------------------------------------------
	method: 		dealloc
	returns: 		void												
	decription: 	Alway put away your toys when you are done playing with
					them.
   -------------------------------------------------------------------------- */
- (void)dealloc
{
	[_digestName release];
	[_stagedResult release];
	[_oneShotResult release];
	[_digestData release];
	[_initBlock release];
	[_updateBlock release];
	[_finalBlock release];
	[_oneShotBlock release];
	[super dealloc];
}

/* --------------------------------------------------------------------------
	method: 		doStaged
	returns: 		void												
	decription: 	Do the staged digest creation for this test placing the
					result into the _stagedResult member
   -------------------------------------------------------------------------- */
- (void)doStaged
{
	
	unsigned int thisMove;
	memset(_context, 0, MAX_CONTEXT_SIZE);
	
	_initBlock(_context);
	
	unsigned int dataLength = [self.digestData length];
	const unsigned char* raw_bytes = (const unsigned char*)[self.digestData bytes];
	
	unsigned char	mdBuffer[MAX_DIGEST_SIZE];
	memset(mdBuffer, 0, MAX_DIGEST_SIZE);
		
	
	CCRandomNumberService* randNumService = [CCRandomNumberService defaultRandomNumberService];
		
	while (dataLength)
	{
		thisMove = [randNumService generateRandomNumberInRange:1 toMax:dataLength];
		_updateBlock(_context, raw_bytes, thisMove);
		
		raw_bytes += thisMove;
		
		dataLength -= thisMove;
	}
	
	(void)_finalBlock(mdBuffer, _context);
	[_stagedResult release];
	_stagedResult = [[NSData alloc] initWithBytes:mdBuffer length:_digestSize];
	
}

/* --------------------------------------------------------------------------
	method: 		doOneShot
	returns: 		void												
	decription: 	Do the 'one shot' digest creation for this test placing the
					result into the _oneShotResult member
   -------------------------------------------------------------------------- */
- (void)doOneShot
{
	unsigned char mdBuffer[MAX_DIGEST_SIZE];
	memset(mdBuffer, 0, MAX_DIGEST_SIZE);
	_oneShotBlock([self.digestData bytes], [self.digestData length], (unsigned char *)mdBuffer);
	[_oneShotResult release];
	_oneShotResult = [[NSData alloc] initWithBytes:mdBuffer length:_digestSize];
	
}

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr
{
	if (nil != self.testObject)
	{
		[self.testObject doAssertTest:result errorString:errorStr];
		return;
	}
	
	if (_testPassed)
	{
		_testPassed = result;
	}
}


/* --------------------------------------------------------------------------
	method: 		runTest
	returns: 		void												
	decription: 	Do the testing of the digest by creating both a staged 
					and one shot digest from the same data and ensuring 
					that the two digests match
   -------------------------------------------------------------------------- */
- (void)runTest
{
	[self doOneShot];
	[self doStaged];
	
	BOOL testResult = [self.stagedResult isEqualToData:self.oneShotResult];
	
	[self doAssertTest:testResult errorString:[
		NSString stringWithFormat:@"Staged Result is not equal to the one shot result for digest type %@", self.digestName]];
	
	if (nil == _testObject)
	{
		printf("DigestTest: %s\n", (self.testPassed) ? "Passed" : "Failed");
	}
}

@end

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted UnitTestSource/EncryptionTest.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//
//  EncryptionTest.h
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#import "TestToolProtocol.h"
#include "CommonCryptor.h"



@interface CCEncryptionTest : NSObject <TestToolProtocol>
{
	CCAlgorithm						_encrAlg;
	uint32							_blockSize;
	uint32							_minKeySizeInBytes;
	uint32							_maxKeySizeInBytes;
	size_t							_ctxSize;
	NSString*						_algName;
	id<TestToolProtocol>			_testObject; // The owning test object NOT retained	
	BOOL							_testPassed;
}

@property (readonly) CCAlgorithm encrAlg;
@property (readonly) uint32 blockSize;
@property (readonly) uint32 minKeySizeInBytes;
@property (readonly) uint32 maxKeySizeInBytes;
@property (readonly) size_t ctxSize;
@property (readonly) NSString* algName;
@property (readonly) id<TestToolProtocol> testObject;
@property (readonly) BOOL testPassed;


+ (NSArray *)setupEncryptionTests:(id<TestToolProtocol>)testObject;

- (id)initWithEncryptionName:(NSString *)name 
		withEncryptionAlgo:(CCAlgorithm)encrAlg
		withBlockSize:(uint32)blockSize 
		withMinKeySizeInBytes:(uint32)minKeySizeInBytes
		withMaxKeySizeInBytes:(uint32)maxKeySizeInBytes
		withContextSize:(size_t)ctxSize
		withUnitTest:(id<TestToolProtocol>)testObject;

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr;

- (void)runTest;

@end
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






































































































Deleted UnitTestSource/EncryptionTest.mm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
//
//  EncryptionTest.mm
//  CommonCrypto
//
//  Created by Jim Murphy on 1/13/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import "EncryptionTest.h"

/* Copyright 2006 Apple Computer, Inc.
 *
 * ccSymTest.c - test CommonCrypto symmetric encrypt/decrypt.
 */
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "CommonCryptor.h"
#include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacErrors.h>
#include "RandomNumberService.h"

int DoTesting(CCEncryptionTest* unitTest);

/*
 * Defaults.
 */
#define LOOPS_DEF		500
#define MIN_DATA_SIZE	8
#define MAX_DATA_SIZE	10000						/* bytes */
#define MAX_KEY_SIZE	kCCKeySizeMaxRC4			/* bytes */
#define MAX_BLOCK_SIZE	kCCBlockSizeAES128			/* bytes */
#define LOOP_NOTIFY		250

/*
 * Enumerate algs our own way to allow iteration.
 */
typedef enum {
	ALG_AES_128 = 1,	/* 128 bit block, 128 bit key */
	ALG_AES_192,		/* 128 bit block, 192 bit key */
	ALG_AES_256,		/* 128 bit block, 256 bit key */
	ALG_DES,
	ALG_3DES,
	ALG_CAST,
	ALG_RC4,
	/* these aren't in CommonCrypto (yet?) */
	ALG_RC2,
	ALG_RC5,
	ALG_BFISH,
	ALG_ASC,
	ALG_NULL					/* normally not used */
} SymAlg;
#define ALG_FIRST			ALG_AES_128
#define ALG_LAST			ALG_RC4


@implementation CCEncryptionTest

@synthesize encrAlg = _encrAlg;
@synthesize blockSize = _blockSize;
@synthesize minKeySizeInBytes = _minKeySizeInBytes;
@synthesize maxKeySizeInBytes = _maxKeySizeInBytes;
@synthesize ctxSize = _ctxSize;
@synthesize algName = _algName;
@synthesize testObject = _testObject;
@synthesize testPassed = _testPassed;


+ (NSArray *)setupEncryptionTests:(id<TestToolProtocol>)testObject
{
	NSMutableArray* result = [NSMutableArray array];
	
	// ============================= DES ==========================
	
	CCEncryptionTest* desTest = [[[CCEncryptionTest alloc]
		initWithEncryptionName:@"DES"
		withEncryptionAlgo:kCCAlgorithmDES
		withBlockSize:kCCBlockSizeDES 
		withMinKeySizeInBytes:kCCKeySizeDES
		withMaxKeySizeInBytes:kCCKeySizeDES
		withContextSize:kCCContextSizeDES
		withUnitTest:testObject
		] autorelease];
		
	[result addObject:desTest];
	
	// ============================= 3DES =========================
	
	CCEncryptionTest* des3Test = [[[CCEncryptionTest alloc]
		initWithEncryptionName:@"3DES"
		withEncryptionAlgo:kCCAlgorithm3DES 
		withBlockSize:kCCBlockSize3DES 
		withMinKeySizeInBytes:kCCKeySize3DES
		withMaxKeySizeInBytes:kCCKeySize3DES
		withContextSize:kCCContextSize3DES
		withUnitTest:testObject
		] autorelease];
		
	[result addObject:des3Test];
	
	// ============================ AES128 =========================
	
	CCEncryptionTest* aes128Test = [[[CCEncryptionTest alloc]
		initWithEncryptionName:@"AES128"
		withEncryptionAlgo:kCCAlgorithmAES128 
		withBlockSize:kCCBlockSizeAES128 
		withMinKeySizeInBytes:kCCKeySizeAES128
		withMaxKeySizeInBytes:kCCKeySizeAES128
		withContextSize:kCCContextSizeAES128
		withUnitTest:testObject
		] autorelease];
		
	[result addObject:aes128Test];
	
	// ============================ AES192 =========================
	
	CCEncryptionTest* aes192Test = [[[CCEncryptionTest alloc]
		initWithEncryptionName:@"AES192"
		withEncryptionAlgo:kCCAlgorithmAES128 
		withBlockSize:kCCBlockSizeAES128 
		withMinKeySizeInBytes:kCCKeySizeAES192
		withMaxKeySizeInBytes:kCCKeySizeAES192
		withContextSize:kCCContextSizeAES128
		withUnitTest:testObject
		] autorelease];
		
	[result addObject:aes192Test];
	
	// ============================ AES256 =========================
	
	CCEncryptionTest* aes256Test = [[[CCEncryptionTest alloc]
		initWithEncryptionName:@"AES256"
		withEncryptionAlgo:kCCAlgorithmAES128 
		withBlockSize:kCCBlockSizeAES128 
		withMinKeySizeInBytes:kCCKeySizeAES256
		withMaxKeySizeInBytes:kCCKeySizeAES256
		withContextSize:kCCContextSizeAES128
		withUnitTest:testObject
		] autorelease];
		
	[result addObject:aes256Test];
	
	// ============================= CAST ==========================
	
	CCEncryptionTest* castTest = [[[CCEncryptionTest alloc]
		initWithEncryptionName:@"CAST"
		withEncryptionAlgo:kCCAlgorithmCAST 
		withBlockSize:kCCBlockSizeCAST 
		withMinKeySizeInBytes:kCCKeySizeMinCAST
		withMaxKeySizeInBytes:kCCKeySizeMaxCAST
		withContextSize:kCCContextSizeCAST
		withUnitTest:testObject
		] autorelease];
		
	[result addObject:castTest];
	
	// ============================== RC4 ==========================
	
	CCEncryptionTest* rc4Test = [[[CCEncryptionTest alloc]
		initWithEncryptionName:@"RC4"
		withEncryptionAlgo:kCCAlgorithmRC4 
		withBlockSize:0 
		withMinKeySizeInBytes:kCCKeySizeMinRC4
		withMaxKeySizeInBytes:kCCKeySizeMaxRC4
		withContextSize:kCCContextSizeRC4
		withUnitTest:testObject
		] autorelease];
		
	[result addObject:rc4Test];
	
	return result;
}

- (id)initWithEncryptionName:(NSString *)name 
		withEncryptionAlgo:(CCAlgorithm)encrAlg
		withBlockSize:(uint32)blockSize 
		withMinKeySizeInBytes:(uint32)minKeySizeInBytes
		withMaxKeySizeInBytes:(uint32)maxKeySizeInBytes
		withContextSize:(size_t)ctxSize
		withUnitTest:(id<TestToolProtocol>)testObject
{
	if ((self = [super init]))
	{
		_encrAlg = encrAlg;
		_blockSize = blockSize;
		_minKeySizeInBytes = minKeySizeInBytes;
		_maxKeySizeInBytes = maxKeySizeInBytes;
		_ctxSize = ctxSize;
		_algName = [name copy];
		_testObject = [testObject retain];
		_testPassed = YES;
	}
	return self;
}

- (void)dealloc
{
	[_algName release];
	[_testObject release];
	[super dealloc];
}

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr
{
	if (nil != self.testObject)
	{
		[self.testObject doAssertTest:result errorString:errorStr];
		return;
	}
	
	if (_testPassed)
	{
		_testPassed = result;
	}
}



- (void)runTest
{
	int iResult = DoTesting(self);
	[self doAssertTest:(iResult == 0)  errorString:[NSString stringWithFormat:@"%@ test failed", _algName]];
	
	if (nil == _testObject)
	{
		printf("EncryptionTest: %s\n", (self.testPassed) ? "Passed" : "Failed");
	}
}

@end


static void appGetRandomBytes(void* dest, uint32 numBytes)
{
	NSAutoreleasePool *pool = [NSAutoreleasePool new];
	NSData* tempResult = [[CCRandomNumberService defaultRandomNumberService] generateRandomDataOfSize:numBytes];
	memcpy(dest, [tempResult bytes], numBytes);
	[pool drain];
}


static void printCCError(NSString* str, CCCryptorStatus crtn, id<TestToolProtocol> unitTest)
{
	NSString* errStr;
	
	switch(crtn) 
	{
		case kCCSuccess: errStr = @"kCCSuccess"; break;
		case kCCParamError: errStr = @"kCCParamError"; break;
		case kCCBufferTooSmall: errStr = @"kCCBufferTooSmall"; break;
		case kCCMemoryFailure: errStr = @"kCCMemoryFailure"; break;
		case kCCAlignmentError: errStr = @"kCCAlignmentError"; break;
		case kCCDecodeError: errStr = @"kCCDecodeError"; break;
		case kCCUnimplemented: errStr = @"kCCUnimplemented"; break;
		default:
			errStr = [NSString stringWithFormat:@"Unknown(%ld)", (long)crtn];
			break;
	}
	NSString* outputStr = nil;
	if (NULL != str)
	{
		outputStr = [NSString stringWithFormat:@"%@ %@", str, errStr];
	}
	else
	{
		outputStr = errStr;
	}
	
	[unitTest doAssertTest:NO errorString:outputStr];
}

/* max context size */
#define CC_MAX_CTX_SIZE	kCCContextSizeRC4

/* 
 * We write a marker at end of expected output and at end of caller-allocated 
 * CCCryptorRef, and check at the end to make sure they weren't written 
 */
#define MARKER_LENGTH	8
#define MARKER_BYTE		0x7e

/* 
 * Test harness for CCCryptor with lots of options. 
 */
CCCryptorStatus doCCCrypt(
	bool forEncrypt,
	CCAlgorithm encrAlg,			
	bool doCbc,
	bool doPadding,
	const void *keyBytes, size_t keyLen,
	const void *iv,
	bool randUpdates,
	bool inPlace,								/* !doPadding only */
	size_t ctxSize,								/* if nonzero, we allocate ctx */
	bool askOutSize,
	const uint8_t *inText, size_t inTextLen,
	uint8_t **outText, size_t *outTextLen, /* both returned, WE malloc */
	id<TestToolProtocol> unitTest)		
{
	CCCryptorRef	cryptor = NULL;
	CCCryptorStatus crtn;
	CCOperation		op = forEncrypt ? kCCEncrypt : kCCDecrypt;
	CCOptions		options = 0;
	uint8_t			*outBuf = NULL;			/* mallocd output buffer */
	uint8_t			*outp;					/* running ptr into outBuf */
	const uint8		*inp;					/* running ptr into inText */
	size_t			outLen;					/* bytes remaining in outBuf */
	size_t			toMove;					/* bytes remaining in inText */
	size_t			thisMoveOut;			/* output from CCCryptUpdate()/CCCryptFinal() */
	size_t			outBytes;				/* total bytes actually produced in outBuf */
	char			ctx[CC_MAX_CTX_SIZE];	/* for CCCryptorCreateFromData() */
	uint8_t			*textMarker = NULL;		/* 8 bytes of marker here after expected end of 
											 * output */
	char			*ctxMarker = NULL;		/* ditto for caller-provided context */
	unsigned		dex;
	size_t			askedOutSize;			/* from the lib */
	size_t			thisOutLen;				/* dataOutAvailable we use */
	
	
	if(!doCbc) 
	{
		options |= kCCOptionECBMode;
	}
	
	if(doPadding) 
	{
		options |= kCCOptionPKCS7Padding;
	}
	
	/* just hack this one */
	outLen = inTextLen;
	if(forEncrypt) 
	{
		outLen += MAX_BLOCK_SIZE;
	}
	
	outBuf = (uint8_t *)malloc(outLen + MARKER_LENGTH);
	
	/* library should not touch this memory */
	textMarker = outBuf + outLen;
	memset(textMarker, MARKER_BYTE, MARKER_LENGTH);
	
	/* subsequent errors to errOut: */

	if(inPlace) 
	{
		memmove(outBuf, inText, inTextLen);
		inp = outBuf;
	}
	else 
	{
		inp = inText;
	}

	if(!randUpdates) 
	{
		/* one shot */
		if(askOutSize) 
		{
			crtn = CCCrypt(op, encrAlg, options,
				keyBytes, keyLen, iv,
				inp, inTextLen,
				outBuf, 0, &askedOutSize);
			if(crtn != kCCBufferTooSmall) 
			{
				NSString* errStr = [NSString stringWithFormat:@"CCCrypt: ***Did not get kCCBufferTooSmall as expected\n  alg %d inTextLen %lu cbc %d padding %d keyLen %lu",
					(int)encrAlg, (unsigned long)inTextLen, (int)doCbc, (int)doPadding,
					(unsigned long)keyLen];
					
				printCCError(errStr, crtn, unitTest);
				crtn = -1;
				goto errOut;
			}
			outLen = askedOutSize;
		}
		crtn = CCCrypt(op, encrAlg, options,
			keyBytes, keyLen, iv,
			inp, inTextLen,
			outBuf, outLen, &outLen);
		if(crtn) 
		{
			printCCError(@"CCCrypt", crtn, unitTest);
			goto errOut;
		}
        
        [unitTest doAssertTest:(outLen != 0) errorString:@"output length should be non-zero for encryption operation"];
		*outText = outBuf;
		*outTextLen = outLen;
		goto errOut;
	}
	
	/* random multi updates */
	if(ctxSize) {
		size_t ctxSizeCreated;
		
		if(askOutSize) 
		{
			crtn = CCCryptorCreateFromData(op, encrAlg, options,
				keyBytes, keyLen, iv,
				ctx, 0 /* ctxSize */,
				&cryptor, &askedOutSize);
			if(crtn != kCCBufferTooSmall) 
			{
				printCCError(@"CCCryptorCreateFromData: ***Did not get kCCBufferTooSmall as expected", crtn, unitTest);
				crtn = -1;
				goto errOut;
			}
			ctxSize = askedOutSize;
		}
		crtn = CCCryptorCreateFromData(op, encrAlg, options,
			keyBytes, keyLen, iv,
			ctx, ctxSize, &cryptor, &ctxSizeCreated);
		if(crtn) 
		{
			printCCError(@"CCCryptorCreateFromData", crtn, unitTest);
			return crtn;
		}
		ctxMarker = ctx + ctxSizeCreated;
		memset(ctxMarker, MARKER_BYTE, MARKER_LENGTH);
	}
	else 
	{
		crtn = CCCryptorCreate(op, encrAlg, options,
			keyBytes, keyLen, iv,
			&cryptor);
		if(crtn) 
		{
			printCCError(@"CCCryptorCreate", crtn, unitTest);
			return crtn;
		}
	}
	
	toMove = inTextLen;		/* total to go */
	outp = outBuf;
	outBytes = 0;			/* bytes actually produced in outBuf */
	
	while(toMove) 
	{
		uint32 thisMoveIn;			/* input to CCryptUpdate() */
		
		thisMoveIn = [[CCRandomNumberService defaultRandomNumberService] 
			generateRandomNumberInRange:1 toMax:toMove];
		if(askOutSize) 
		{
			thisOutLen = CCCryptorGetOutputLength(cryptor, thisMoveIn, false);
		}
		else 
		{
			thisOutLen = outLen;
		}
		crtn = CCCryptorUpdate(cryptor, inp, thisMoveIn,
			outp, thisOutLen, &thisMoveOut);
		if(crtn) 
		{
			printCCError(@"CCCryptorUpdate", crtn, unitTest);
			goto errOut;
		}
		inp			+= thisMoveIn;
		toMove		-= thisMoveIn;
		outp		+= thisMoveOut;
		outLen   	-= thisMoveOut;
		outBytes	+= thisMoveOut;
	}
	
	if(doPadding) 
	{
		/* Final is not needed if padding is disabled */
		if(askOutSize) 
		{
			thisOutLen = CCCryptorGetOutputLength(cryptor, 0, true);
		}
		else 
		{
			thisOutLen = outLen;
		}
		crtn = CCCryptorFinal(cryptor, outp, thisOutLen, &thisMoveOut);
	}
	else 
	{
		thisMoveOut = 0;
		crtn = kCCSuccess;
	}
	
	if(crtn) 
	{
		printCCError(@"CCCryptorFinal", crtn, unitTest);
		goto errOut;
	}
	
	outBytes += thisMoveOut;
	*outText = outBuf;
	*outTextLen = outBytes;
	crtn = kCCSuccess;

	for(dex=0; dex<MARKER_LENGTH; dex++) 
	{
		if(textMarker[dex] != MARKER_BYTE) 
		{
			[unitTest doAssertTest:NO errorString:[NSString stringWithFormat:@"***lib scribbled on our textMarker memory (op=%s)!\n",
				forEncrypt ? "encrypt" : "decrypt"]];
			crtn = (CCCryptorStatus)-1;
		}
	}
	if(ctxSize) 
	{
		for(dex=0; dex<MARKER_LENGTH; dex++) 
		{
			if(ctxMarker[dex] != MARKER_BYTE) 
			{
				[unitTest doAssertTest:NO errorString:[NSString stringWithFormat:@"***lib scribbled on our ctxMarker memory (op=%s)!\n",
					forEncrypt ? "encrypt" : "decrypt"]];
				crtn = (CCCryptorStatus)-1;
			}
		}
	}
	
errOut:
	if(crtn) 
	{
		if(outBuf) 
		{
			free(outBuf);
		}
	}
	if(cryptor) 
	{
		CCCryptorRelease(cryptor);
	}
	return crtn;
}

static int doTest(const uint8_t *ptext,
	size_t ptextLen,
	CCAlgorithm encrAlg,			
	bool doCbc,
	bool doPadding,
	bool nullIV,			/* if CBC, use NULL IV */
	uint32 keySizeInBytes,
	bool stagedEncr,
	bool stagedDecr,
	bool inPlace,	
	size_t ctxSize,		
	bool askOutSize,
	bool quiet,
	id<TestToolProtocol> unitTest)
{
	uint8_t			keyBytes[MAX_KEY_SIZE];
	uint8_t			iv[MAX_BLOCK_SIZE];
	uint8_t			*ivPtrEncrypt;
	uint8_t			*ivPtrDecrypt;
	uint8_t			*ctext = NULL;		/* mallocd by doCCCrypt */
	size_t			ctextLen = 0;
	uint8_t			*rptext = NULL;		/* mallocd by doCCCrypt */
	size_t			rptextLen;
	CCCryptorStatus	crtn;
	int				rtn = 0;
	
	/* random key */
	appGetRandomBytes(keyBytes, keySizeInBytes);
	
	/* random IV if needed */
	if(doCbc) 
	{
		if(nullIV) 
		{
			memset(iv, 0, MAX_BLOCK_SIZE);
			
			/* flip a coin, give one side NULL, the other size zeroes */
			
			if ([[CCRandomNumberService defaultRandomNumberService] 
						generateRandomNumberInRange:1 toMax:2] == 1)
			{
				ivPtrEncrypt = NULL;
				ivPtrDecrypt = iv;
			}
			else 
			{
				ivPtrEncrypt = iv;
				ivPtrDecrypt = NULL;
			}
		}
		else 
		{
			appGetRandomBytes(iv, MAX_BLOCK_SIZE);
			ivPtrEncrypt = iv;
			ivPtrDecrypt = iv;
		}
	}	
	else 
	{
		ivPtrEncrypt = NULL;
		ivPtrDecrypt = NULL;
	}

	crtn = doCCCrypt(true, encrAlg, doCbc, doPadding,
		keyBytes, keySizeInBytes, ivPtrEncrypt,
		stagedEncr, inPlace, ctxSize, askOutSize,
		ptext, ptextLen,
		&ctext, &ctextLen, unitTest);
	if(crtn) 
	{
		rtn = 1;
		goto abort;
	}
		
	crtn = doCCCrypt(false, encrAlg, doCbc, doPadding,
		keyBytes, keySizeInBytes, ivPtrDecrypt,
		stagedDecr, inPlace, ctxSize, askOutSize,
		ctext, ctextLen,
		&rptext, &rptextLen, unitTest);
	if(crtn) 
	{
		rtn = 1;
		goto abort;
	}
	
	/* compare ptext, rptext */
	if(ptextLen != rptextLen) 
	{
		NSString* errStr = [NSString stringWithFormat:@"Ptext length mismatch: expect %lu, got %lu\n", ptextLen, rptextLen];
		[unitTest doAssertTest:NO errorString:errStr];
		rtn = 1;
		goto abort;
		
	}
	
	if(memcmp(ptext, rptext, ptextLen)) 
	{
		[unitTest doAssertTest:NO errorString:@"***data miscompare"];
		rtn = 1;
	}
	
abort:
	if(ctext) 
	{
		free(ctext);
	}
	if(rptext) 
	{
		free(rptext);
	}
	return rtn;
}

bool isBitSet(unsigned bit, unsigned word) 
{
	if(bit > 31) 
	{
		NSLog(@"We don't have that many bits");
		exit(1);
	}
	unsigned mask = 1 << bit;
	return (word & mask) ? true : false;
}

int DoTesting(CCEncryptionTest* unitTest)
{
	unsigned			loop;
	uint8				*ptext;
	size_t				ptextLen;
	bool				stagedEncr;
	bool				stagedDecr;
	bool				doPadding;
	bool				doCbc;
	bool				nullIV;
	const char			*algStr;
	CCAlgorithm			encrAlg;	
	uint32				minKeySizeInBytes;
	uint32				maxKeySizeInBytes;
	uint32				keySizeInBytes;
	int					rtn = 0;
	uint32				blockSize;		// for noPadding case
	size_t				ctxSize;		// always set per alg
	size_t				ctxSizeUsed;	// passed to doTest
	bool				askOutSize;		// inquire output size each op
	
	/*
	 * User-spec'd params
	 */
	bool		keySizeSpec = false;		// false: use rand key size
	unsigned	loops = LOOPS_DEF;
	size_t		minPtextSize = MIN_DATA_SIZE;
	size_t		maxPtextSize = MAX_DATA_SIZE;
	bool		quiet = false;
	bool		paddingSpec = false;		// true: user calls doPadding, const
	bool		cbcSpec = false;			// ditto for doCbc
	bool		stagedSpec = false;			// ditto for stagedEncr and stagedDecr
	bool		inPlace = false;			// en/decrypt in place for ECB
	bool		allocCtxSpec = false;		// use allocCtx
	bool		allocCtx = false;			// allocate context ourself
	

	ptext = (uint8 *)malloc(maxPtextSize);
	if(ptext == NULL) 
	{
		[unitTest doAssertTest:NO errorString:@"Insufficient heap space"];
		exit(1);
	}
	/* ptext length set in test loop */
	
	/* Set up the values for this test from the object */	
	encrAlg = unitTest.encrAlg;
	blockSize = unitTest.blockSize;
	minKeySizeInBytes = unitTest.minKeySizeInBytes;
	maxKeySizeInBytes = unitTest.maxKeySizeInBytes;
	ctxSize = unitTest.ctxSize;
	algStr = [unitTest.algName UTF8String];		
		
	for(loop=1; ; loop++) 
	{
		ptextLen = [[CCRandomNumberService defaultRandomNumberService] 
			generateRandomNumberInRange:minPtextSize toMax:maxPtextSize];
		appGetRandomBytes(ptext, ptextLen);
		
		/* per-loop settings */
		if(!keySizeSpec) 
		{
			if(minKeySizeInBytes == maxKeySizeInBytes) 
			{
				keySizeInBytes = minKeySizeInBytes;
			}
			else 
			{
				keySizeInBytes = [[CCRandomNumberService defaultRandomNumberService] 
					generateRandomNumberInRange:minKeySizeInBytes toMax:maxKeySizeInBytes];
			}
		}
		if(blockSize == 0) 
		{
			/* stream cipher */
			doCbc = false;
			doPadding = false;
		}
		else 
		{
			if(!cbcSpec) 
			{
				doCbc = isBitSet(0, loop);
			}
			if(!paddingSpec) 
			{
				doPadding = isBitSet(1, loop);
			}
		}
		if(!doPadding && (blockSize != 0)) 
		{
			/* align plaintext */
			ptextLen = (ptextLen / blockSize) * blockSize;
			if(ptextLen == 0) 
			{
				ptextLen = blockSize;
			}
		}
		if(!stagedSpec) 
		{
			stagedEncr = isBitSet(2, loop);
			stagedDecr = isBitSet(3, loop);
		}
		if(doCbc) 
		{
			nullIV = isBitSet(4, loop);
		}
		else 
		{
			nullIV = false;
		}
		inPlace = isBitSet(5, loop);
		if(allocCtxSpec) 
		{
			ctxSizeUsed = allocCtx ? ctxSize : 0;
		}
		else if(isBitSet(6, loop)) 
		{
			ctxSizeUsed = ctxSize;
		}
		else 
		{
			ctxSizeUsed = 0;
		}
		askOutSize = isBitSet(7, loop);
		
		
		if(doTest(ptext, ptextLen,
				encrAlg, doCbc, doPadding, nullIV,
				keySizeInBytes,
				stagedEncr,	stagedDecr, inPlace, ctxSizeUsed, askOutSize,
				quiet, unitTest)) 
		{
			rtn = 1;
			break;
		}
		
		if(loops && (loop == loops)) 
		{
			break;
		}
		
		if(rtn) 
		{
			break;
		}
		
	}	/* for algs */
	
	free(ptext);
	return rtn;
}
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Deleted UnitTestSource/HMACTest.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
//  HMACTest.h
//  CommonCrypto
//
//  Created by Jim Murphy on 1/14/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#include "CommonHMAC.h"
#import "TestToolProtocol.h"

/* --------------------------------------------------------------------------
	Class: 			CCHMACTestObject
	Description: 	This class provides for testing a HMAC type
   -------------------------------------------------------------------------- */

@interface CCHMACTestObject : NSObject
{
	NSString*		_nameHMAC;				    // The name of the HMAC type
	CCHmacAlgorithm	_algoHMAC;					// The HMAC algorithm
	NSData*			_keyMaterial;				// The key for the HMAC
	NSData*			_stagedResult;				// Result of the staged HMAC
	NSData*			_oneShotResult;				// Result of the 'one shot' HMAC
	NSData*			_dataHMAC;				    // Data to be HMACed
	unsigned int	_digestBufferSize;			// The size of the output buffer
	void*			_digestBuffer;				// The output buffer for the digest
	CCHmacContext	_context;				    // Working HMAC buffer
	id<TestToolProtocol>
					_testObject;				// The owning test object NOT retained	
	BOOL			_testPassed;
}

@property (readonly) NSString* nameHMAC;
@property (readonly) CCHmacAlgorithm algoHMAC;
@property (readonly) NSData* keyMaterial;
@property (readonly) NSData* stagedResult;
@property (readonly) NSData* oneShotResult;
@property (readonly) NSData* dataHMAC;
@property (readonly) void* digestBuffer;
@property (readonly) id<TestToolProtocol> testObject;
@property (readonly) BOOL testPassed;


+ (NSArray *)setupHMACTests:(id<TestToolProtocol>)testObject;

- (id)initWithHMACName:(NSString *)name 
 	withCCHmacAlgorithm:(CCHmacAlgorithm)algo
	withDigestSize:(unsigned int)digestSize
	withTestObject:(id<TestToolProtocol>)testObject;

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr;
	
- (void)runTest;

@end
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
















































































































Deleted UnitTestSource/HMACTest.mm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
//
//  HMACTest.mm
//  CommonCrypto
//
//  Created by Jim Murphy on 1/14/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import "HMACTest.h"
#import "RandomNumberService.h"
#import "CommonHMAC.h"
#include <stdio.h>

// completely arbitrary
#define kMIN_KEY_LENGTH 0
#define kMAX_KEY_LENGTH 512

#define kMIN_DATA_LENGTH 16
#define kMAC_DATA_LENGTH 0x8000

@implementation CCHMACTestObject

@synthesize nameHMAC = _nameHMAC;
@synthesize algoHMAC = _algoHMAC;
@synthesize keyMaterial = _keyMaterial;
@synthesize stagedResult = _stagedResult;
@synthesize oneShotResult = _oneShotResult;
@synthesize dataHMAC = _dataHMAC;
@synthesize testObject = _testObject;
@synthesize digestBuffer = _digestBuffer;
@synthesize testPassed = _testPassed;


/* --------------------------------------------------------------------------
	method: 		setupHMACTests
	returns: 		NSArray *												
	decription: 	This method allows for creating digest specific tests for
					all of the digest supported by the CommonCrypto library.
					It creates an instance of the CCDigestTestObject for
					each digest to be tested and places that object into
					an NSArray.
   -------------------------------------------------------------------------- */
+ (NSArray *)setupHMACTests:(id<TestToolProtocol>)testObject;
{
	
	NSMutableArray* result = [NSMutableArray array]; // autoreleased
	
	// ======================= SHA1 HMAC ==========================
	
	CCHMACTestObject* sha1HMACTest = [[[CCHMACTestObject alloc] initWithHMACName:@"Sha1HMAC" 
 		withCCHmacAlgorithm:kCCHmacAlgSHA1 withDigestSize:CC_SHA1_DIGEST_LENGTH 
		withTestObject:testObject] autorelease];

	[result addObject:sha1HMACTest];
	
	// ======================= MD5 HMAC ==========================
	
	CCHMACTestObject* md5HMACTest = [[[CCHMACTestObject alloc] initWithHMACName:@"md5HMAC" 
 		withCCHmacAlgorithm:kCCHmacAlgMD5 withDigestSize:CC_MD5_DIGEST_LENGTH 
		withTestObject:testObject] autorelease];

	[result addObject:md5HMACTest];
	
	// ====================== SHA256 HMAC =========================
	
	CCHMACTestObject* sha256HMACTest = [[[CCHMACTestObject alloc] initWithHMACName:@"Sha256HMAC" 
 		withCCHmacAlgorithm:kCCHmacAlgSHA256 withDigestSize:CC_SHA256_DIGEST_LENGTH
		withTestObject:testObject] autorelease];

	[result addObject:sha256HMACTest];
	
	// ====================== SHA384 HMAC =========================
	
	CCHMACTestObject* sha384HMACTest = [[[CCHMACTestObject alloc] initWithHMACName:@"Sha384HMAC" 
 		withCCHmacAlgorithm:kCCHmacAlgSHA384 withDigestSize:CC_SHA384_DIGEST_LENGTH
		withTestObject:testObject] autorelease];

	[result addObject:sha384HMACTest];
	
	// ====================== SHA512 HMAC =========================
	
	CCHMACTestObject* sha512HMACTest = [[[CCHMACTestObject alloc] initWithHMACName:@"Sha512HMAC" 
 		withCCHmacAlgorithm:kCCHmacAlgSHA512 withDigestSize:CC_SHA512_DIGEST_LENGTH
		withTestObject:testObject] autorelease];

	[result addObject:sha512HMACTest];
	
	// ====================== SHA224 HMAC =========================
	
	CCHMACTestObject* sha224HMACTest = [[[CCHMACTestObject alloc] initWithHMACName:@"Sha224HMAC" 
 		withCCHmacAlgorithm:kCCHmacAlgSHA224 withDigestSize:CC_SHA224_DIGEST_LENGTH
		withTestObject:testObject] autorelease];

	[result addObject:sha224HMACTest];

	
	return result;
}


- (id)initWithHMACName:(NSString *)name 
 	withCCHmacAlgorithm:(CCHmacAlgorithm)algo
	withDigestSize:(unsigned int)digestSize
	withTestObject:(id<TestToolProtocol>)testObject
	
{	
	if ((self = [super init]))
	{
		_testPassed = YES;

		_nameHMAC = [name copy];
		_algoHMAC = algo;
		
		CCRandomNumberService* randService = [CCRandomNumberService defaultRandomNumberService];
		
		unsigned int bufferSize = [randService generateRandomNumberInRange:kMIN_KEY_LENGTH toMax:kMAX_KEY_LENGTH];
		_keyMaterial = [[randService generateRandomDataOfSize:bufferSize] copy];
		
		_stagedResult = nil;
		_oneShotResult = nil;
		
		bufferSize = [randService generateRandomNumberInRange:kMIN_DATA_LENGTH toMax:kMAC_DATA_LENGTH];
		_dataHMAC = [[randService generateRandomDataOfSize:bufferSize] copy];
		
		_digestBufferSize = digestSize;
		_digestBuffer = malloc(_digestBufferSize);
		
		_testObject = [testObject retain];
	}
	return self;
	
}


/* --------------------------------------------------------------------------
	method: 		dealloc
	returns: 		void												
	decription: 	Alway put away your toys when you are done playing with
					them.
   -------------------------------------------------------------------------- */
- (void)dealloc
{
	[_keyMaterial release];
	[_stagedResult release];
	[_oneShotResult release];
	[_dataHMAC release];
	[_testObject release];
	if (NULL != _digestBuffer)
	{
		free(_digestBuffer);
		_digestBuffer = NULL;
	}
	[super dealloc];
}

- (CCHmacContext *)context
{
	return &_context;
}

- (void)clearContext
{
	memset(&_context, 0, sizeof(_context));
	memset(_digestBuffer, 0, _digestBufferSize);
}

/* --------------------------------------------------------------------------
	method: 		doStaged
	returns: 		void												
	decription: 	Do the staged digest creation for this test placing the
					result into the _stagedResult member
   -------------------------------------------------------------------------- */
- (void)doStaged
{
	[self clearContext];
	
	CCHmacInit([self context], self.algoHMAC, [self.keyMaterial bytes], 
		[self.keyMaterial length]);
		
	unsigned int dataLength = [self.dataHMAC length];
	unsigned int thisMove;
	
	const unsigned char* raw_bytes = (const unsigned char*)[self.dataHMAC bytes];
	
	CCRandomNumberService* randNumService = [CCRandomNumberService defaultRandomNumberService];
		
	while (dataLength)
	{
		thisMove = [randNumService generateRandomNumberInRange:1 toMax:dataLength];
		
		CCHmacUpdate([self context], raw_bytes, thisMove);
		
		raw_bytes += thisMove;
		
		dataLength -= thisMove;
	}
	
	CCHmacFinal([self context], _digestBuffer);
	[_stagedResult release];
	_stagedResult = [[NSData alloc] initWithBytes:_digestBuffer length:_digestBufferSize];
}


/* --------------------------------------------------------------------------
	method: 		doOneShot
	returns: 		void												
	decription: 	Do the 'one shot' digest creation for this test placing the
					result into the _oneShotResult member
   -------------------------------------------------------------------------- */
- (void)doOneShot
{
	[self clearContext];
	CCHmac(self.algoHMAC, [self.keyMaterial bytes], [self.keyMaterial length], 
		[self.dataHMAC bytes], [self.dataHMAC length], _digestBuffer);

	[_oneShotResult release];
	_oneShotResult = [[NSData alloc] initWithBytes:_digestBuffer length:_digestBufferSize];
	
}

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr
{
	if (nil != self.testObject)
	{
		[self.testObject doAssertTest:result errorString:errorStr];
		return;
	}
	
	if (_testPassed)
	{
		_testPassed = result;
	}
}


/* --------------------------------------------------------------------------
	method: 		runTest
	returns: 		void												
	decription: 	Do the testing of the digest by creating both a staged 
					and one shot digest from the same data and ensuring 
					that the two digests match
   -------------------------------------------------------------------------- */
- (void)runTest
{
	[self doOneShot];
	[self doStaged];
	
	BOOL testResult = [self.stagedResult isEqualToData:self.oneShotResult];
	
	[self doAssertTest:testResult errorString:[
		NSString stringWithFormat:@"Staged Result is not equal to the one shot result for digest type %@", self.nameHMAC]];
	
	if (nil == _testObject)
	{
		printf("HMACTest: %s\n", (self.testPassed) ? "Passed" : "Failed");
	}
	
}

@end

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































































































































































































































































Deleted UnitTestSource/PBKDFTest.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//
//  PBKDFTest.h
//  CommonCrypto
//
//  Created by Richard Murphy on 2/3/10.
//  Copyright 2010 McKenzie-Murphy. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#include "CommonKeyDerivation.h"
#import "TestToolProtocol.h"

/* --------------------------------------------------------------------------
 Class: 			CCDerviationTestObject
 Description: 	This class provides for testing a PBKDF type
 -------------------------------------------------------------------------- */

@interface CCDerviationTestObject : NSObject <TestToolProtocol>
{
	NSString*		_namePBKDF;				    // The name of the PBKDF type
	CCPBKDFAlgorithm	_algoPBKDF;				// The PBKDF algorithm
	NSData*			_password;					// The password for the PBKDF
	NSData*			_salt;						// The salt for the PBKDF
	CCPseudoRandomAlgorithm _prf;				// The PRF to use with the PBKDF
	uint			_rounds;					// The number of rounds for the PBKDF
	uint8_t			_derivedKey[1024];			// Max buffer for derived key from function under test
	NSData*			_derivedResult;				// Result of the staged PBKDF
	NSData*			_expectedResult;			// The expected result
	id<TestToolProtocol> _testObject;			// The owning test object NOT retained	
	BOOL					_testPassed;

}

@property (readonly) NSString* namePBKDF;
@property (readonly) CCPBKDFAlgorithm algoPBKDF;
@property (readonly) NSData* password;
@property (readonly) NSData* salt;
@property (readonly) CCPseudoRandomAlgorithm prf;
@property (readonly) uint rounds;
@property (readonly) NSData* derivedResult;
@property (readonly) NSData* expectedResult;
@property (readonly) id<TestToolProtocol> testObject;
@property (readonly) BOOL testPassed;


+ (NSArray *)setupPBKDFTests:(id<TestToolProtocol>)testObject;

- (id)initWithPBKDFName:(NSString *)name 
		withCCPBKDFAlgorithm:(CCPBKDFAlgorithm) algo
		withPassword:(NSData *) password
		withSalt:(NSData *) salt
		withCCPseudoRandomAlgorithm:(CCPseudoRandomAlgorithm) prf
		withRounds:(uint)rounds
		withExpectedResult:(NSData *)expectedResult
		withTestObject:(id<TestToolProtocol>)testObject;

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr;

- (void)runTest;


struct test_vector {
	u_int rounds;
	const char *pass;
	const char *salt;
	const char expected[32];
};
@end
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<








































































































































Deleted UnitTestSource/PBKDFTest.mm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//
//  PBKDFTest.mm
//  CommonCrypto
//
//  Created by Richard Murphy on 2/3/10.
//  Copyright 2010 McKenzie-Murphy. All rights reserved.
//

#import "PBKDFTest.h"
#include <stdio.h>


@implementation CCDerviationTestObject

@synthesize namePBKDF = _namePBKDF;
@synthesize algoPBKDF = _algoPBKDF;
@synthesize password = _password;
@synthesize salt = _salt;
@synthesize prf = _prf;
@synthesize rounds = _rounds;
@synthesize derivedResult = _derivedResult;
@synthesize expectedResult = _expectedResult;
@synthesize testObject = _testObject;
@synthesize testPassed = _testPassed;


/* --------------------------------------------------------------------------
 method: 		setupPBKDFTests
 returns: 		NSArray *												
 decription: 	This method allows for creating digest specific tests for
				all of the digest supported by the CommonCrypto library.
				It creates an instance of the CCDigestTestObject for
				each digest to be tested and places that object into
				an NSArray.
 -------------------------------------------------------------------------- */
+ (NSArray *)setupPBKDFTests:(id<TestToolProtocol>)testObject;
{
	
	NSMutableArray* result = [NSMutableArray array]; // autoreleased
	
	/*
	 * Test vectors from RFC 3962
	 */
	
	struct test_vector test_vectors[] = {
		{ 
			1, "password", "ATHENA.MIT.EDUraeburn", { 
				0xcd, 0xed, 0xb5, 0x28, 0x1b, 0xb2, 0xf8, 0x01, 0x56, 0x5a, 0x11, 0x22, 0xb2, 0x56, 0x35, 0x15,
				0x0a, 0xd1, 0xf7, 0xa0, 0x4b, 0xb9, 0xf3, 0xa3, 0x33, 0xec, 0xc0, 0xe2, 0xe1, 0xf7, 0x08, 0x37 },
		}, {
			2, "password", "ATHENA.MIT.EDUraeburn", { 
				0x01, 0xdb, 0xee, 0x7f, 0x4a, 0x9e, 0x24, 0x3e,  0x98, 0x8b, 0x62, 0xc7, 0x3c, 0xda, 0x93, 0x5d,
				0xa0, 0x53, 0x78, 0xb9, 0x32, 0x44, 0xec, 0x8f, 0x48, 0xa9, 0x9e, 0x61, 0xad, 0x79, 0x9d, 0x86 },
		}, {
			1200, "password", "ATHENA.MIT.EDUraeburn", { 
				0x5c, 0x08, 0xeb, 0x61, 0xfd, 0xf7, 0x1e, 0x4e, 0x4e, 0xc3, 0xcf, 0x6b, 0xa1, 0xf5, 0x51, 0x2b,
				0xa7, 0xe5, 0x2d, 0xdb, 0xc5, 0xe5, 0x14, 0x2f, 0x70, 0x8a, 0x31, 0xe2, 0xe6, 0x2b, 0x1e, 0x13 },
		}, {
			5, "password", "\0224VxxV4\022", /* 0x1234567878563412 */ { 
				0xd1, 0xda, 0xa7, 0x86, 0x15, 0xf2, 0x87, 0xe6, 0xa1, 0xc8, 0xb1, 0x20, 0xd7, 0x06, 0x2a, 0x49,
				0x3f, 0x98, 0xd2, 0x03, 0xe6, 0xbe, 0x49, 0xa6, 0xad, 0xf4, 0xfa, 0x57, 0x4b, 0x6e, 0x64, 0xee },
		}, { 1200, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase equals block size", {
				0x13, 0x9c, 0x30, 0xc0, 0x96, 0x6b, 0xc3, 0x2b, 0xa5, 0x5f, 0xdb, 0xf2, 0x12, 0x53, 0x0a, 0xc9,
				0xc5, 0xec, 0x59, 0xf1, 0xa4, 0x52, 0xf5, 0xcc, 0x9a, 0xd9, 0x40, 0xfe, 0xa0, 0x59, 0x8e, 0xd1 },
		}, { 1200, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "pass phrase exceeds block size", {
				0x9c, 0xca, 0xd6, 0xd4, 0x68, 0x77, 0x0c, 0xd5, 0x1b, 0x10, 0xe6, 0xa6, 0x87, 0x21, 0xbe, 0x61,
				0x1a, 0x8b, 0x4d, 0x28, 0x26, 0x01, 0xdb, 0x3b, 0x36, 0xbe, 0x92, 0x46, 0x91, 0x5e, 0xc8, 0x2a },
		}, { 50, "\360\235\204\236", /* g-clef (0xf09d849e) */ "EXAMPLE.COMpianist", {
				0x6b, 0x9c, 0xf2, 0x6d, 0x45, 0x45, 0x5a, 0x43, 0xa5, 0xb8, 0xbb, 0x27, 0x6a, 0x40, 0x3b, 0x39,
				0xe7, 0xfe, 0x37, 0xa0, 0xc4, 0x1e, 0x02, 0xc2, 0x81, 0xff, 0x30, 0x69, 0xe1, 0xe9, 0x4f, 0x52 },
		}, { 1, "password", "salt", { 
				0x0c, 0x60, 0xc8, 0x0f, 0x96, 0x1f, 0x0e, 0x71, 0xf3, 0xa9, 0xb5, 0x24, 0xaf, 0x60, 0x12, 0x06, 
                0x2f, 0xe0, 0x37, 0xa6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
		}
	};
	int nvecs = (sizeof(test_vectors) / sizeof(*test_vectors));
	int i;

	for(i=0; i< nvecs-1; i++) {
		CCDerviationTestObject* pbkdfHMACSha1Test = [[[CCDerviationTestObject alloc] 
		   initWithPBKDFName:@"pbkdfHMACSha1Test1" 
		   withCCPBKDFAlgorithm: kCCPBKDF2
		   withPassword: [[NSData alloc] initWithBytes:test_vectors[i].pass length:strlen(test_vectors[i].pass)]
		   withSalt: [[NSData alloc] initWithBytes:test_vectors[i].salt length:strlen(test_vectors[i].salt)]
		   withCCPseudoRandomAlgorithm: kCCPRFHmacAlgSHA1
		   withRounds:(uint)test_vectors[i].rounds
		   withExpectedResult:[[NSData alloc] initWithBytes:test_vectors[i].expected length:32]
		   withTestObject:testObject] autorelease];
		[result addObject:pbkdfHMACSha1Test];
	}
    
    CCDerviationTestObject* pbkdfHMACSha1Test = [[[CCDerviationTestObject alloc] 
                                                  initWithPBKDFName:@"pbkdfHMACSha1Test1" 
                                                  withCCPBKDFAlgorithm: kCCPBKDF2
                                                  withPassword: [[NSData alloc] initWithBytes:test_vectors[i].pass length:strlen(test_vectors[i].pass)]
                                                  withSalt: [[NSData alloc] initWithBytes:test_vectors[i].salt length:strlen(test_vectors[i].salt)]
                                                  withCCPseudoRandomAlgorithm: kCCPRFHmacAlgSHA1
                                                  withRounds:(uint)test_vectors[i].rounds
                                                  withExpectedResult:[[NSData alloc] initWithBytes:test_vectors[i].expected length:20]
                                                  withTestObject:testObject] autorelease];
    [result addObject:pbkdfHMACSha1Test];
    
	
	return result;
}


- (id)initWithPBKDFName:(NSString *)namePBKDF 
   withCCPBKDFAlgorithm:(CCPBKDFAlgorithm) algoPBKDF
		   withPassword:(NSData *) password
			   withSalt:(NSData *) salt
withCCPseudoRandomAlgorithm:(CCPseudoRandomAlgorithm) prf
			 withRounds:(uint)rounds
	 withExpectedResult:(NSData *)expectedResult
		 withTestObject:(id<TestToolProtocol>)testObject;

{	
	if ((self = [super init]))
	{
		_namePBKDF = [namePBKDF copy];
		_algoPBKDF = algoPBKDF;
		_password = [password copy];
		_salt = [salt copy];
		_prf = prf;
		_rounds = rounds;
		_expectedResult = [expectedResult copy];
		_testObject = testObject; 
		_testPassed = YES;
	}
	return self;
	
}


/* --------------------------------------------------------------------------
 method: 		dealloc
 returns: 		void												
 decription: 	Alway put away your toys when you are done playing with
				them.
 -------------------------------------------------------------------------- */
- (void)dealloc
{
	[_namePBKDF release];
	[_password release];
	[_salt release];
	[_expectedResult release];
	[_derivedResult release];
	//[_testObject release];
	[super dealloc];
}

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr
{
	if (nil != self.testObject)
	{
		[self.testObject doAssertTest:result errorString:errorStr];
		return;
	}
	
	if (_testPassed)
	{
		_testPassed = result;
	}
}

/* --------------------------------------------------------------------------
 method: 		doTest
 returns: 		void												
 decription: 	Do the 'one shot' digest creation for this test placing the
				result into the _oneShotResult member
 -------------------------------------------------------------------------- */
- (void)doVectorTest
{
	// [self clearContext];
	(void) CCKeyDerivationPBKDF(self.algoPBKDF, (const char *)[self.password bytes], [self.password length], 
						 (const uint8_t *)[self.salt bytes], [self.salt length], 
						 _prf, _rounds,
						 _derivedKey, [self.expectedResult length]);
	
	//[_derivedResult release];
	_derivedResult = [[NSData alloc] initWithBytes:_derivedKey length:[self.expectedResult length]];
	
}

/* --------------------------------------------------------------------------
 method: 		runTest
 returns: 		void												
 decription: 	Do the testing of the digest by creating both a staged 
				and one shot digest from the same data and ensuring 
				that the two digests match
 -------------------------------------------------------------------------- */
- (void)runTest
{
	[self doVectorTest];
	
	BOOL testResult = [self.expectedResult isEqualToData:self.derivedResult];
	
	[self doAssertTest:testResult errorString:[
			NSString stringWithFormat:@"Expected Result is not equal to the derived result in %@", self.namePBKDF]];
	
	if (nil == _testObject)
	{
		printf("PBKDFTest: %s\n", (self.testPassed) ? "Passed" : "Failed");
	}
}

@end

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































































































































































































































































































































































































































Deleted UnitTestSource/RandomNumberService.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//
//  RandomNumberService.h
//  CommonCrypto
//
//  Created by Jim Murphy on 1/12/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import <Cocoa/Cocoa.h>


/* --------------------------------------------------------------------------
	Class: 			CCRandomNumberService
	Description: 	This class provides random number services for testing
	Note: 			This should be in another shared file so that other unit 
					test code could use this service.  For now it can remain 
					here for illustration
   -------------------------------------------------------------------------- */
@interface CCRandomNumberService : NSObject 
{
	NSFileHandle*	_devRandomFileHandle;	// file handle for reading from /dev/random
}

// Get the "default" Random number service
+ (CCRandomNumberService *)defaultRandomNumberService;

// Release the default Random number service.  NOTE: This is really 
// an unsafe method.  This should ONLY be called once.
+ (void)relaseDefaultRandomNumberService;

// generate a random integer within a set range
- (unsigned int)generateRandomNumberInRange:(unsigned int)min 
									  toMax:(unsigned int)max;

// generate a random set of bytes of an arbitrary length
- (NSData *)generateRandomDataOfSize:(size_t)length;

@end
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































Deleted UnitTestSource/RandomNumberService.mm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
//
//  RandomNumberService.mm
//  CommonCrypto
//
//  Created by Jim Murphy on 1/12/10.
//  Copyright 2010 Apple. All rights reserved.
//

#import "RandomNumberService.h"


// The one singleton representation of the RandomNumberService
static CCRandomNumberService*	gDefaultRandomNumberService = nil;

@implementation CCRandomNumberService

/* --------------------------------------------------------------------------
	method: 		[class] defaultRandomNumberService
	returns: 		CCRandomNumberService*
	decription: 	This class method ensures a singleton instance for getting
					random data for testing
   -------------------------------------------------------------------------- */
+ (CCRandomNumberService *) defaultRandomNumberService
{
	if (nil == gDefaultRandomNumberService)
	{
		gDefaultRandomNumberService = [CCRandomNumberService new];
	}
	
	return gDefaultRandomNumberService;
}

/* --------------------------------------------------------------------------
	method: 		[class] relaseDefaultRandomNumberService
	returns: 		void
	decription: 	Releases the singleton object
   -------------------------------------------------------------------------- */
+ (void)relaseDefaultRandomNumberService
{
	[gDefaultRandomNumberService release];
	gDefaultRandomNumberService = nil;
}

/* --------------------------------------------------------------------------
	method: 		init
	returns: 		id
	decription: 	Initialize a new instance of the CCRandomNumberService 
					object.  It ensure a singleton object for this service
   -------------------------------------------------------------------------- */
- (id)init
{
	if (nil != gDefaultRandomNumberService)
	{
		// This needs to be a singleton 
		// The correct thing here would be to 
		// complain but for now 'do the right thing'
		[self release];
		self = gDefaultRandomNumberService;
	}
	else
	{
		// This is the normal path
		if ((self = [super init]))
		{
			_devRandomFileHandle = [[NSFileHandle fileHandleForReadingAtPath:@"/dev/random"] retain];
		}
	}
	return self;
}

/* --------------------------------------------------------------------------
	method: 		dealloc
	returns: 		void
	decription: 	Alway put away your toys when you are done playing with
					them.
   -------------------------------------------------------------------------- */
- (void)dealloc
{
	[_devRandomFileHandle closeFile];
	[_devRandomFileHandle release];
	[super dealloc];
}

/* --------------------------------------------------------------------------
	method: 		generateRandomNumberInRange:toMax:
	returns: 		unsigned int within the specified range
	parameters:
					min:
						The minimum value to be returned
						
					max:
						The maximum value to be returned
						
	decription: 	Returns a pesudo random number within a range.
   -------------------------------------------------------------------------- */
- (unsigned int)generateRandomNumberInRange:(unsigned int)min toMax:(unsigned int)max
{
	unsigned int result = 0L;
	if (min == max)
	{
		result = min;
	}
	else
	{
		NSAutoreleasePool *pool = [NSAutoreleasePool new];
		NSData* randomData = [_devRandomFileHandle readDataOfLength:sizeof(result)];
		unsigned int temp_i = *((unsigned int *) [randomData bytes]);
		result = (min + (temp_i % (max - min + 1)));
		[pool drain]; 
	}
	return result;
}

/* --------------------------------------------------------------------------
	method: 		generateRandomDataOfSize:toMax:
	returns: 		autorelased NSData of  pesudo random data of the specified
					size
	parameters:
					length:
						The size in bytes of the data to be created
												
	decription: 	Returns a NSData of random data
   -------------------------------------------------------------------------- */
- (NSData *)generateRandomDataOfSize:(size_t)length
{
	NSData* randomData = [_devRandomFileHandle readDataOfLength:length];
	return randomData;
}

@end
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




































































































































































































































































Deleted UnitTestSource/SymmetricWrapTest.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//
//  SymmetricWrapTest.h
//  CommonCrypto
//
//  Created by Richard Murphy on 2/3/10.
//  Copyright 2010 McKenzie-Murphy. All rights reserved.
//

#import <Cocoa/Cocoa.h>
#import "CommonSymmetricKeywrap.h"
#import "TestToolProtocol.h"


@interface CCSymmetricalWrapTest : NSObject <TestToolProtocol>
{
	id<TestToolProtocol>	_testObject;			// The owning test object NOT retained	
	BOOL					_testPassed;
	
}

@property (readonly) id<TestToolProtocol> testObject;
@property (readonly) BOOL testPassed;

+ (NSArray *)setupSymmWrapTests:(id<TestToolProtocol>)testObject;

- (id)initWithTestObject:(id<TestToolProtocol>)testObject;

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr;

- (void)runTest;

@end

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<


































































Deleted UnitTestSource/SymmetricWrapTest.mm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
//
//  SymmetricWrapTest.mm
//  CommonCrypto
//
//  Created by Richard Murphy on 2/3/10.
//  Copyright 2010 McKenzie-Murphy. All rights reserved.
//

#import "SymmetricWrapTest.h"
#include <stdio.h>


@implementation CCSymmetricalWrapTest

@synthesize testObject = _testObject;
@synthesize testPassed = _testPassed;

+ (NSArray *)setupSymmWrapTests:(id<TestToolProtocol>)testObject
{
	
	NSMutableArray* result = [NSMutableArray array]; // autoreleased
	
	CCSymmetricalWrapTest* wrapTest = [[[CCSymmetricalWrapTest alloc] initWithTestObject:testObject] autorelease];
	[result addObject:wrapTest];
	return result;
}

- (id)initWithTestObject:(id<TestToolProtocol>)testObject
{
	
	if ((self = [super init]))
	{
		_testPassed = YES;
		_testObject = testObject;
		
	}
	return self;
}

- (void)dealloc
{
	[super dealloc];
	
}

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr
{
	if (nil != self.testObject)
	{
		[self.testObject doAssertTest:result errorString:errorStr];
		return;
	}
	
	if (_testPassed)
	{
		_testPassed = result;
	}
}
	

- (void)runTest
{	
	
	uint8_t kek[] = {
		0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 
		0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
	};
	
	uint8_t key[] = {
		0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
		0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF
	};
	
	uint8_t wrapped_key[] = {
		0x1F, 0xA6, 0x8B, 0x0A, 0x81, 0x12, 0xB4, 0x47, 
		0xAE, 0xF3, 0x4B, 0xD8, 0xFB, 0x5A, 0x7B, 0x82, 
		0x9D, 0x3E, 0x86, 0x23, 0x71, 0xD2, 0xCF, 0xE5
	};
	
	uint8_t wrapped[(128+64)/8];
	size_t wrapped_size = sizeof(wrapped);
	uint8_t unwrapped[128/8];
	size_t unwrapped_size = sizeof(unwrapped);
	
	BOOL self_test = NO; // guilty until proven
	
	//rfc3394_wrap(kek, sizeof(kek), rfc3394_iv, key, sizeof(key), wrapped, &wrapped_size);
	const uint8_t *iv =  CCrfc3394_iv;
	const size_t ivLen = CCrfc3394_ivLen;
	
	CCSymmetricKeyWrap(kCCWRAPAES, iv , ivLen, kek, sizeof(kek), key, sizeof(key), wrapped, &wrapped_size);
					   
	self_test = (0 == memcmp(wrapped, wrapped_key, wrapped_size));
	[self doAssertTest:self_test errorString:@"Wrapped key does not match"];
								   
	//rfc3394_unwrap(kek, sizeof(kek), rfc3394_iv, wrapped, wrapped_size, unwrapped, &unwrapped_size);
	CCSymmetricKeyUnwrap(kCCWRAPAES, iv, ivLen, kek, sizeof(kek), wrapped, wrapped_size, unwrapped, &unwrapped_size);
	self_test = (0 == memcmp(unwrapped, key, sizeof(key)));
	[self doAssertTest:self_test errorString:@"Unwrapped key does not match"];
	
	if (nil == _testObject)
	{
		printf("SymmetricalWrapTestest: %s\n", (self.testPassed) ? "Passed" : "Failed");
	}
																  
	/*
	 #if !KERNEL || AES256_KEK
	 {
	 uint8_t kek[] = {
	 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
	 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
	 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
	 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
	 };
	 uint8_t key[] = {
	 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
	 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
	 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
	 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
	 };
	 uint8_t wrapped_key[] = {
	 0x28, 0xC9, 0xF4, 0x04, 0xC4, 0xB8, 0x10, 0xF4,
	 0xCB, 0xCC, 0xB3, 0x5C, 0xFB, 0x87, 0xF8, 0x26,
	 0x3F, 0x57, 0x86, 0xE2, 0xD8, 0x0E, 0xD3, 0x26,
	 0xCB, 0xC7, 0xF0, 0xE7, 0x1A, 0x99, 0xF4, 0x3B,
	 0xFB, 0x98, 0x8B, 0x9B, 0x7A, 0x02, 0xDD, 0x21
	 };
	 uint8_t wrapped[(256+64)/8];
	 size_t wrapped_size = sizeof(wrapped);
	 uint8_t unwrapped[256/8];
	 size_t unwrapped_size = sizeof(unwrapped);
	 bool self_test;
	 
	 rfc3394_wrap(kek, sizeof(kek), rfc3394_iv, key, sizeof(key), wrapped, &wrapped_size);
	 self_test = (0 == memcmp(wrapped, wrapped_key, wrapped_size));
	 require(self_test, out);
	 printf("\nSELF-TEST %s\n\n", self_test ? "OK" : "FAIL");
	 rfc3394_unwrap(kek, sizeof(kek), rfc3394_iv, wrapped, wrapped_size, unwrapped, &unwrapped_size);
	 self_test = (0 == memcmp(unwrapped, key, sizeof(key)));
	 require(self_test, out);
	 printf("\nSELF-TEST %s\n\n", self_test ? "OK" : "FAIL");
	 }
	 #endif
	 */
	
								   
}

@end

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<












































































































































































































































































































Deleted UnitTestSource/TestToolProtocol.h.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//
//  TestToolProtocol.h
//  CommonCrypto
//
//  Created by James Murphy on 10/28/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import <Cocoa/Cocoa.h>


@protocol TestToolProtocol <NSObject>

- (void)doAssertTest:(BOOL)result errorString:(NSString *)errorStr;

@end
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
































Deleted UnitTestSource/main.mm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
 *  main.mm
 *  CommonCrypto
 *
 *  Created by James Murphy on 10/28/10.
 *  Copyright 2010 __MyCompanyName__. All rights reserved.
 *
 */

#import <Foundation/Foundation.h>
#import "CommonCryptoUnitTests.h"
#import "DigestTest.h"
#import "CommonDigest.h"
#import "CommonCryptor.h"
#import "CommonHMAC.h"
#import "RandomNumberService.h"
#import "EncryptionTest.h"
#import "HMACTest.h"
#import "PBKDFTest.h"
#import "SymmetricWrapTest.h"
#import "CommonRandomSPI.h"

int main (int argc, const char * argv[]) 
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
	NSArray* digestTests = [CCDigestTestObject setupDigestTests:nil];
	
	for (CCDigestTestObject* testObject in digestTests)
	{
		[testObject runTest];
	}
	
	NSArray* encryptionTests = [CCEncryptionTest setupEncryptionTests:nil];
	
	for (CCEncryptionTest* aTest in encryptionTests)
	{
		[aTest runTest];
	}
	
	NSArray* hmacTests = [CCHMACTestObject setupHMACTests:nil];
	
	for (CCHMACTestObject* aTest in hmacTests)
	{
		[aTest runTest];
	}
	
	NSArray* pbkdfTests = [CCDerviationTestObject setupPBKDFTests:nil];
	
	for (CCDerviationTestObject* aTest in pbkdfTests)
	{
		[aTest runTest];
	}
	
	NSArray* SymmetricWrapTests = [CCSymmetricalWrapTest setupSymmWrapTests:nil];
	
	for (CCSymmetricalWrapTest* aTest in SymmetricWrapTests)
	{
		[aTest runTest];
	}
	
	uint8_t bytes[1024];
    uint8_t previous[1024];
    int i;
    
    bzero(previous, 1024);
    for(i = 0; i < 1024; i++) 
	{
        int retval =  CCRandomCopyBytes(kCCRandomDefault, bytes, 1024);
        if(retval) 
		{
            printf("CCRandomCopyBytes: Failed");
        }
        
        if(memcmp(previous, bytes, 1024) == 0) 
		{
            printf("CCRandomCopyBytes: Failed");
        }
        
        memcpy(previous, bytes, 1024);
    }
	
	[pool drain];
	return 0;
}
	
	
	
	

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















































































































































































Deleted doc/CCCalibratePBKDF.3cc.

1
.so man3/CCCommonKeyDerivation.3cc
<


Deleted doc/CCCommonKeyDerivation.3cc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
.Dd January 21, 2011
.Dt CCCommonKeyDerivation.3cc
.Os
.Sh NAME
.Nm CCKeyDerivationPBKDF ,
.Nm CCCalibratePBKDF
.Nd Common Key Derivation Interfaces
.Sh LIBRARY
These functions are found in libSystem.
.Sh SYNOPSIS
.In CommonCrypto/CommonKeyDerivation.h
.Ft int
.Fn CCKeyDerivationPBKDF "CCPBKDFAlgorithm algorithm" "const char *password" \
"size_t passwordLen" "const uint8_t *salt""size_t saltLen" "CCPseudoRandomAlgorithm prf" \
"uint rounds" "uint8_t *derivedKey""size_t derivedKeyLen"
.Ft uint
.Fn CCCalibratePBKDF "CCPBKDFAlgorithm algorithm" "size_t passwordLen" "size_t saltLen" \
"CCPseudoRandomAlgorithm prf" "size_t derivedKeyLen" "uint32_t msec" 
.Sh DESCRIPTION
.Ss Function  
.Nm CCKeyDerivationPBKDF
.Ss Abstract  
Derive a key from a text password/passphrase
.Ss Parameters
.Bl -tag
.It algorithm       
Currently only PBKDF2 is available via kCCPBKDF2
.It password              
The text password used as input to the derivation function.  The actual octets present in \
this string will be used with no additional processing.  It's extremely important that the \
same encoding and normalization be used each time this routine is called if the same key \
is  expected to be derived.
.It passwordLen           
The length of the text password in bytes.
.It salt             
The salt byte values used as input to the derivation function.
.It saltLen          
The length of the salt in bytes.
.It prf          
The Pseudo Random Algorithm to use for the derivation iterations.
.It rounds       
The number of rounds of the Pseudo Random Algorithm to use.
.It derivedKey      
The resulting derived key produced by the function.  The space for this must be provided \
by the caller.
.It derivedKeyLen   
The length of the derived key in bytes.
.El
.Pp 
.Ss Discussion 
The following values are used to designate the PRF:
.br
.sp 
\fB * kCCPRFHmacAlgSHA1
.br
 * kCCPRFHmacAlgSHA224
.br
 * kCCPRFHmacAlgSHA256
.br
 * kCCPRFHmacAlgSHA384
.br
 * kCCPRFHmacAlgSHA512\fR
.br
.Pp
.Ss Result    
.Er kCCParamError 
- can result from bad values for the password, salt, and unwrapped key pointers as \
well as a bad value for the prf function.
.Ss Function  
.Nm CCCalibratePBKDF
.Ss Abstract  
Determine the number of PRF rounds to use for a specific delay on the current platform.
.Ss Parameters
.Bl -tag
.It algorithm       
Currently only PBKDF2 is available via kCCPBKDF2
.It passwordLen              
The length of the text password in bytes.
.It saltLen           
The length of the salt in bytes.
.It prf          
The Pseudo Random Algorithm to use for the derivation iterations.
.It derivedKeyLen      
The expected length of the derived key in bytes.
.It msec   
The targetted duration we want to achieve for a key derivation with these parameters.
.El
.Pp 
.Ss Result    
The number of iterations to use for the desired processing time.
.Sh EXAMPLE	
.nf
int main (int argc, const char * argv[]) {
	uint rounds;
	size_t	passwordLen = 10, saltLen = 10;
	char *password = "ThePasswrd";
	uint8_t salt[10] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
	CCPseudoRandomAlgorithm prf = kCCPRFHmacAlgSHA256;
	size_t derivedKeyLen = 16;
	uint8_t derivedKey[16];
	uint32_t msec = 10;
	int retval;
.sp
	rounds = CCCalibratePBKDF(kCCPBKDF2, strlen(password), saltLen, prf, derivedKeyLen, msec);
.sp
	retval =  CCKeyDerivationPBKDF(kCCPBKDF2, password, strlen(password), salt, saltLen,
                       prf, rounds, derivedKey, derivedKeyLen);
 	/* At this point the key is produced in "derivedKey" for "derivedKeyLen" bytes and could
	   be used as the key for AES encryption.
.sp
	   The "Salt" must be remembered somehow by the calling program as well as the rounds value 
	   and prf that was used.  These values, along with the original password will result in the
	   same 16 byte key being produced each time.
	*/
    	return 0;
}
.fi
.Sh HISTORY
These functions are available in OS X 10.7 and IOS 5.0 and later.
.Sh SEE ALSO
.Xr CCCryptor 3cc ,
.Xr CCHmac 3cc ,
.Xr CC_MD5 3cc ,
.Xr CC_SHA 3cc ,
.Xr CC_crypto 3cc ,
.Xr CCDigest 3cc
.Sh STANDARDS
.Bl -tag
.It AES:
Federal Information Processing Standard \s-1FIPS\s0 \s-1PUB\s0 197 (Advanced Encryption Standard),
.It DES:
Federal Information Processing Standard \s-1FIPS\s0 \s-1PUB\s0 46\-3 (Data Encryption Standard)
.It 3DES:
NIST Special Publication\s-1PUB\s0 800\-67 (Recommendation for the Triple Data Encryption Algorithm (TDEA) Block Cipher)
.El
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<














































































































































































































































































Deleted doc/CCKeyDerivationPBKDF.3cc.

1
.so man3/CCCommonKeyDerivation.3cc
<


Deleted doc/CCSymmetricKeyUnwrap.3cc.

1
.so man3/CCSymmetricKeyWrap.3cc
<


Deleted doc/CCSymmetricKeyWrap.3cc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
.Dd January 20, 2011
.Dt CCSymmetricKeyWrap 3cc
.Os
.Sh NAME
.Nm CCSymmetricKeyWrap ,
.Nm CCSymmetricKeyUnwrap ,
.Nm CCSymmetricWrappedSize ,
.Nm CCSymmetricUnwrappedSize
.Nd Common Symmetric Keywrap Algorithm Interfaces
.Sh LIBRARY
These functions are found in libSystem.
.Sh SYNOPSIS
.In CommonCrypto/CommonSymmetricKeywrap.h
.Ft int
.Fn CCSymmetricKeyWrap "CCWrappingAlgorithm algorithm" "const uint8_t *iv" "const size_t ivLen" \
"const uint8_t *kek" "size_t kekLen" "const uint8_t *rawKey" "size_t rawKeyLen" \
"uint8_t  *wrappedKey" "size_t *wrappedKeyLen"
.Ft int
.Fn CCSymmetricKeyUnwrap "CCWrappingAlgorithm algorithm" "const uint8_t *iv" \
"const size_t ivLen" "const uint8_t *kek" "size_t kekLen" "const uint8_t  *wrappedKey" \
"size_t wrappedKeyLen" "uint8_t  *rawKey" "size_t *rawKeyLen"
.Ft size_t
.Fn CCSymmetricWrappedSize "CCWrappingAlgorithm algorithm" "size_t rawKeyLen"
.Ft size_t
.Fn CCSymmetricUnwrappedSize "CCWrappingAlgorithm algorithm" "size_t wrappedKeyLen"
.Sh DESCRIPTION
.Ss Function  
.Nm CCSymmetricKeyWrap
.Ss Abstract  
Wrap a symmetric key with a Key Encryption Key (KEK).  
.Ss Parameters
.Bl -tag
.It algorithm       
Currently only AES Keywrapping (rfc3394) is available via kCCWRAPAES
.It iv              
The initialization value to be used.  CCrfc3394_iv is available as a constant for \
the standard IV to use.
.It ivLen           
The length of the initialization value to be used.  CCrfc3394_ivLen is available as \
a constant for the standard IV to use.
.It kek             
The Key Encryption Key to be used to wrap the raw key.
.It kekLen          
The length of the KEK in bytes.
.It rawKey          
The raw key bytes to be wrapped.
.It rawKeyLen       
The length of the key in bytes.
.It wrappedKey      
The resulting wrapped key produced by the function.  The space for this must be \
provided by the caller.
.It wrappedKeyLen   
The length of the wrapped key in bytes.
.El
.Pp 
.Ss Discussion 
The algorithm chosen is determined by the algorithm parameter and the size of the \
key being wrapped (ie aes128 for 128 bit keys).
.Pp
.Ss Result    
.Er kCCBufferTooSmall 
- indicates insufficent space in the wrappedKey buffer. 
.Pp
.Er kCCParamError 
- can result from bad values for the kek, rawKey, and wrappedKey key pointers.
.Ss Function  
.Nm CCSymmetricKeyUnwrap
.Ss Abstract  
Unwrap a symmetric key with a Key Encryption Key (KEK).  
.Ss Parameters
.Bl -tag
.It algorithm       
Currently only AES Keywrapping (rfc3394) is available via kCCWRAPAES
.It iv              
The initialization value to be used.  CCrfc3394_iv is available as a constant for the \
standard IV to use.
.It ivLen           
The length of the initialization value to be used.  CCrfc3394_ivLen is available as a \
constant for the standard IV to use.
.It kekLen          
The length of the KEK in bytes.
.It wrappedKey      
The wrapped key bytes.
.It wrappedKeyLen   
The length of the wrapped key in bytes.
.It rawKey          
The resulting raw key bytes. The space for this must be provided by the caller.
.It rawKeyLen       
The length of the raw key in bytes.
.El
.Pp 
.Ss Discussion 
The algorithm chosen is determined by the algorithm parameter and the size of the key \
being wrapped (ie aes128 for 128 bit keys).
.Ss Result    
.Er kCCBufferTooSmall 
- indicates insufficent space in the rawKey buffer. 
.Pp
.Er kCCParamError 
- can result from bad values for the kek, rawKey, and wrappedKey key pointers.
.Pp
.br
.Ss Function  
.Nm CCSymmetricWrappedSize
.Ss Abstract  
Determine the buffer size required to hold a key wrapped with 
.Fn CCAESKeyWrap .  
.Ss Parameters
.Bl -tag
.It algorithm       
Currently only AES Keywrapping (rfc3394) is available via kCCWRAPAES
.It rawKeyLen       
The length of the key in bytes.
.El
.Ss Result    
The length of the resulting wrapped key.
.br
.Ss Function  
.Nm CCSymmetricUnwrappedSize
.Ss abstract  
Determine the buffer size required to hold a key unwrapped with 
.Fn CCAESKeyUnwrap . 
.Ss Parameters
.Bl -tag
.It algorithm       
Currently only AES Keywrapping (rfc3394) is available via kCCWRAPAES
.It wrappedKeyLen   
The length of the wrapped key in bytes.
.El
.Ss Result    
The length of the resulting raw key.
.Sh HISTORY
These functions are available in OS X 10.7 and IOS 5.0 and later.
.Sh SEE ALSO
.Xr CCCryptor 3cc ,
.Xr CCHmac 3cc ,
.Xr CC_MD5 3cc ,
.Xr CC_SHA 3cc ,
.Xr CC_crypto 3cc ,
.Xr CCDigest 3cc
.Sh STANDARDS
.Bl -tag
.It AES:
Federal Information Processing Standard \s-1FIPS\s0 \s-1PUB\s0 197 (Advanced Encryption Standard),
.It DES:
Federal Information Processing Standard \s-1FIPS\s0 \s-1PUB\s0 46\-3 (Data Encryption Standard)
.It 3DES:
NIST Special Publication\s-1PUB\s0 800\-67 (Recommendation for the Triple Data Encryption Algorithm (TDEA) Block Cipher)
.El
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










































































































































































































































































































Deleted doc/CCSymmetricUnwrappedSize.3cc.

1
.so man3/CCSymmetricKeyWrap.3cc
<


Deleted doc/CCSymmetricWrappedSize.3cc.

1
.so man3/CCSymmetricKeyWrap.3cc
<


Changes to doc/CommonCrypto.plist.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
	<dict>
		<key>OpenSourceLicense</key>
		<string>openssl</string>
		<key>OpenSourceImportDate</key>
		<string>2004-04-07</string>
		<key>OpenSourceLicenseFile</key>
		<string>CommonCrypto.txt</string>
		<key>OpenSourceModifications</key>
		<string>Extensive customization for OS X</string>
		<key>OpenSourceProject</key>
		<string>openssl</string>
		<key>OpenSourceURL</key>
		<string>http://www.openssl.org/source/openssl-0.9.6.tar.gz</string>
		<key>OpenSourceVersion</key>
		<string>openssl-0.9.6</string>
		<key>OpenSourceWebsiteURL</key>
		<string>http://www.openssl.org/</string>
	</dict>
	<dict>
		<key>OpenSourceImportDate</key>
		<string>2004-04-07</string>
		<key>OpenSourceLicense</key>
		<string>other</string>
		<key>OpenSourceLicenseFile</key>
		<string>CommonCrypto.txt</string>
		<key>OpenSourceModifications</key>
		<string>Customization for OS X</string>
		<key>OpenSourceProject</key>
		<string>Gladman AES</string>
		<key>OpenSourceURL</key>
		<string>http://gladman.plushost.co.uk/oldsite/AES/aes-src-29-04-09.zip</string>
		<key>OpenSourceVersion</key>
		<string>aes-src-26-08-05</string>
		<key>OpenSourceWebsiteURL</key>
		<string>http://www.gladman.me.uk/</string>
	</dict>
	<dict>
		<key>OpenSourceImportDate</key>
		<string>2005-09-02</string>
		<key>OpenSourceLicense</key>
		<string>other</string>
		<key>OpenSourceLicenseFile</key>
		<string>CommonCrypto.txt</string>
		<key>OpenSourceModifications</key>
		<string>Customization for OS X</string>
		<key>OpenSourceProject</key>
		<string>Gladman SHA2</string>
		<key>OpenSourceURL</key>
		<string>http://gladman.plushost.co.uk/oldsite/cryptography_technology/sha/sha2-07-01-07.zip</string>
		<key>OpenSourceVersion</key>
		<string>sha-26-08-05</string>
		<key>OpenSourceWebsiteURL</key>
		<string>http://www.gladman.me.uk/</string>
	</dict>
	<dict>
		<key>OpenSourceImportDate</key>
		<string>2010-01-04</string>
		<key>OpenSourceLicense</key>
		<string>other</string>
		<key>OpenSourceLicenseFile</key>
		<string>CommonCrypto.txt</string>
		<key>OpenSourceModifications</key>
		<string>Branched for OS X</string>
		<key>OpenSourceProject</key>
		<string>libTomCrypt</string>
		<key>OpenSourceURL</key>
		<string>http://libtom.org/files/crypt-1.17.zip</string>
		<key>OpenSourceVersion</key>
		<string>1.17</string>
		<key>OpenSourceWebsiteURL</key>
		<string>http://libtom.org/</string>
	</dict>
</array>
</plist>

|




|
<
<

















|







|



|





|







|



<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|



1
2
3
4
5
6
7


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54


















55
56
57
58
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
	<dict>
		<key>OpenSourceLicense</key>
		<string>Eric Young</string>


		<key>OpenSourceLicenseFile</key>
		<string>CommonCrypto.txt</string>
		<key>OpenSourceModifications</key>
		<string>Extensive customization for OS X</string>
		<key>OpenSourceProject</key>
		<string>openssl</string>
		<key>OpenSourceURL</key>
		<string>http://www.openssl.org/source/openssl-0.9.6.tar.gz</string>
		<key>OpenSourceVersion</key>
		<string>openssl-0.9.6</string>
		<key>OpenSourceWebsiteURL</key>
		<string>http://www.openssl.org/</string>
	</dict>
	<dict>
		<key>OpenSourceImportDate</key>
		<string>2004-04-07</string>
		<key>OpenSourceLicense</key>
		<string>Brian Gladman</string>
		<key>OpenSourceLicenseFile</key>
		<string>CommonCrypto.txt</string>
		<key>OpenSourceModifications</key>
		<string>Customization for OS X</string>
		<key>OpenSourceProject</key>
		<string>Gladman AES</string>
		<key>OpenSourceURL</key>
		<string>http://fp.gladman.plus.com/AES/aesfull.zip</string>
		<key>OpenSourceVersion</key>
		<string>aes-src-26-08-05</string>
		<key>OpenSourceWebsiteURL</key>
		<string>http://fp.gladman.plus.com/AES/index.htm</string>
	</dict>
	<dict>
		<key>OpenSourceImportDate</key>
		<string>2005-09-02</string>
		<key>OpenSourceLicense</key>
		<string>Brian Gladman</string>
		<key>OpenSourceLicenseFile</key>
		<string>CommonCrypto.txt</string>
		<key>OpenSourceModifications</key>
		<string>Customization for OS X</string>
		<key>OpenSourceProject</key>
		<string>Gladman SHA2</string>
		<key>OpenSourceURL</key>
		<string>http://fp.gladman.plus.com/cryptography_technology/sha/sha-26-08-05.zip</string>
		<key>OpenSourceVersion</key>
		<string>sha-26-08-05</string>
		<key>OpenSourceWebsiteURL</key>


















		<string>http://fp.gladman.plus.com/cryptography_technology/sha/index.htm</string>
	</dict>
</array>
</plist>

Changes to doc/CommonCrypto.txt.

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.

---------------------------------------------------------------------------
License for libTomCrypt
---------------------------------------------------------------------------
libTomCrypt is a library that provides various cryptographic
algorithms in a highly modular and flexible manner.

The library is free for all purposes without any express
guarantee it works.

Tom St Denis, tomstdenis@gmail.com, http://libtom.org









<
<
<
<
<
<
<
<
<
<
<
<
<
114
115
116
117
118
119
120













 in which case the provisions of the GPL apply INSTEAD OF those given above.

 DISCLAIMER

 This software is provided 'as is' with no explicit or implied warranties
 in respect of its properties, including, but not limited to, correctness
 and/or fitness for purpose.













Added xcodescripts/convert-launchd-plists-to-binary.sh.













>
>
>
>
>
>
1
2
3
4
5
6
/bin/sh
set -e
mkdir -p "$DSTROOT"/System/Library/LaunchDaemons
for plist in "$SRCROOT"/cc_fips_test/*.plist; do
	plutil -convert binary1 "$plist" -o "$DSTROOT"/System/Library/LaunchDaemons/$(basename "$plist")
done