summaryrefslogtreecommitdiffstats
path: root/src/tpm12/tpm_key.c
blob: 6fce49542262456c4a42dbe50bb9b5156eef9132 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
/********************************************************************************/
/*										*/
/*				Key Handler					*/
/*			     Written by Ken Goldman				*/
/*		       IBM Thomas J. Watson Research Center			*/
/*	      $Id: tpm_key.c 4655 2011-12-21 21:03:15Z kgoldman $		*/
/*										*/
/* (c) Copyright IBM Corporation 2006, 2010.					*/
/*										*/
/* All rights reserved.								*/
/* 										*/
/* Redistribution and use in source and binary forms, with or without		*/
/* modification, are permitted provided that the following conditions are	*/
/* met:										*/
/* 										*/
/* Redistributions of source code must retain the above copyright notice,	*/
/* this list of conditions and the following disclaimer.			*/
/* 										*/
/* 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.		*/
/* 										*/
/* Neither the names of the IBM Corporation nor the names of its		*/
/* contributors may be used to endorse or promote products derived from		*/
/* this software without specific prior written permission.			*/
/* 										*/
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS		*/
/* "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 COPYRIGHT		*/
/* HOLDER 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.		*/
/********************************************************************************/

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

#include "tpm_auth.h"
#include "tpm_commands.h"
#include "tpm_crypto.h"
#include "tpm_cryptoh.h"
#include "tpm_debug.h"
#include "tpm_digest.h"
#include "tpm_error.h"
#include "tpm_init.h"
#include "tpm_io.h"
#include "tpm_load.h"
#include "tpm_memory.h"
#include "tpm_nonce.h"
#include "tpm_nvfile.h"
#include "tpm_nvram.h"
#include "tpm_owner.h"
#include "tpm_pcr.h"
#include "tpm_sizedbuffer.h"
#include "tpm_store.h"
#include "tpm_structures.h"
#include "tpm_startup.h"
#include "tpm_permanent.h"
#include "tpm_process.h"
#include "tpm_ver.h"

#include "tpm_key.h"

/* The default RSA exponent */
unsigned char tpm_default_rsa_exponent[] = {0x01, 0x00, 0x01};

/* local prototypes */

static TPM_RESULT TPM_Key_CheckTag(TPM_KEY12 *tpm_key12);

/*
  TPM_KEY, TPM_KEY12

  These functions generally handle either a TPM_KEY or TPM_KEY12.  Where structure members differ,
  the function checks the version or tag and adapts the processing to the structure type.  This
  handling is opaque to the caller.
*/


/* TPM_Key_Init initializes a key structure.  The default is TPM_KEY.  Typically, a TPM_Key_Set() or
   TPM_Key_Load() will adjust to TPM_KEY or TPM_KEY12 */

void TPM_Key_Init(TPM_KEY *tpm_key)
{
    printf(" TPM_Key_Init:\n");
    TPM_StructVer_Init(&(tpm_key->ver));
    tpm_key->keyUsage = TPM_KEY_UNINITIALIZED;
    tpm_key->keyFlags = 0;
    tpm_key->authDataUsage = 0;
    TPM_KeyParms_Init(&(tpm_key->algorithmParms));
    TPM_SizedBuffer_Init(&(tpm_key->pcrInfo));
    TPM_SizedBuffer_Init(&(tpm_key->pubKey));
    TPM_SizedBuffer_Init(&(tpm_key->encData));
    tpm_key->tpm_pcr_info = NULL;
    tpm_key->tpm_pcr_info_long = NULL;
    tpm_key->tpm_store_asymkey = NULL;
    tpm_key->tpm_migrate_asymkey = NULL;
    return;
}

/* TPM_Key_InitTag12() alters the tag and fill from TPM_KEY to TPM_KEY12 */

void TPM_Key_InitTag12(TPM_KEY *tpm_key)
{
    printf(" TPM_Key_InitTag12:\n");
    ((TPM_KEY12 *)tpm_key)->tag = TPM_TAG_KEY12;
    ((TPM_KEY12 *)tpm_key)->fill = 0x0000;
    return;
}

/* TPM_Key_Set() sets a TPM_KEY structure to the specified values.

   The tpm_pcr_info digestAtCreation is calculated.

   It serializes the tpm_pcr_info or tpm_pcr_info_long cache to pcrInfo.  One or the other may be
   specified, but not both.  The tag/version is set correctly.

   If the parent_key is NULL, encData is set to the clear text serialization of the
   tpm_store_asymkey member.

   If parent_key is not NULL, encData is not set yet, since further processing may be done before
   encryption.

   Must call TPM_Key_Delete() to free
 */

TPM_RESULT TPM_Key_Set(TPM_KEY *tpm_key,		/* output created key */
		       tpm_state_t *tpm_state,
		       TPM_KEY *parent_key,		/* NULL for root keys */
		       TPM_DIGEST *tpm_pcrs,		/* points to the TPM PCR array */
		       int ver,				/* TPM_KEY or TPM_KEY12 */
		       TPM_KEY_USAGE keyUsage,				/* input */
		       TPM_KEY_FLAGS keyFlags,				/* input */
		       TPM_AUTH_DATA_USAGE authDataUsage,		/* input */
		       TPM_KEY_PARMS *tpm_key_parms,			/* input */
		       TPM_PCR_INFO *tpm_pcr_info,			/* must copy */
		       TPM_PCR_INFO_LONG *tpm_pcr_info_long,		/* must copy */
		       uint32_t keyLength,		/* public key length in bytes */
		       BYTE* publicKey,			/* public key byte array */
		       TPM_STORE_ASYMKEY *tpm_store_asymkey,	 /* cache TPM_STORE_ASYMKEY */
		       TPM_MIGRATE_ASYMKEY *tpm_migrate_asymkey) /* cache TPM_MIGRATE_ASYMKEY */
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	sbuffer;
     
    printf(" TPM_Key_Set:\n");
    TPM_Sbuffer_Init(&sbuffer);
    /* version must be TPM_KEY or TPM_KEY12 */
    if (rc == 0) {
	if ((ver != 1) && (ver != 2)) {
	    printf("TPM_Key_Set: Error (fatal), "
		   "TPM_KEY version %d is not 1 or 2\n", ver);
	    rc = TPM_FAIL;	/* should never occur */
	}
    }
    /* either tpm_pcr_info != NULL for TPM_KEY or tpm_pcr_info_long != NULL for TPM_KEY12, but not
       both */
    if (rc == 0) {
	if ((ver == 1) && (tpm_pcr_info_long != NULL)) {
	    printf("TPM_Key_Set: Error (fatal), "
		   "TPM_KEY and TPM_PCR_INFO_LONG both specified\n");
	    rc = TPM_FAIL;	/* should never occur */
	}
    }
    if (rc == 0) {
	if ((ver == 2) && (tpm_pcr_info != NULL)) {
	    printf("TPM_Key_Set: Error (fatal), "
		   "TPM_KEY12 and TPM_PCR_INFO both specified\n");
	    rc = TPM_FAIL;	/* should never occur */
	}
    }
    if (rc == 0) {
	TPM_Key_Init(tpm_key);
	if (ver == 2) {
	    TPM_Key_InitTag12(tpm_key);		/* change tag to TPM_KEY12 */
	}
	tpm_key->keyUsage = keyUsage;
	tpm_key->keyFlags = keyFlags;
	tpm_key->authDataUsage = authDataUsage;
	rc = TPM_KeyParms_Copy(&(tpm_key->algorithmParms),	/* freed by caller */
			       tpm_key_parms);
    }
    /* The pcrInfo serialization is deferred, since PCR data is be altered after the initial
       'set'. */
    if (rc == 0) {
	/* generate the TPM_PCR_INFO member cache, directly copying from the tpm_pcr_info */
	if (tpm_pcr_info != NULL) {	/* TPM_KEY */
	    rc = TPM_PCRInfo_CreateFromInfo(&(tpm_key->tpm_pcr_info), tpm_pcr_info);
	}
	/* generate the TPM_PCR_INFO_LONG member cache, directly copying from the
	   tpm_pcr_info_long */
	else if (tpm_pcr_info_long != NULL) {	/* TPM_KEY12 */
	    rc = TPM_PCRInfoLong_CreateFromInfoLong(&(tpm_key->tpm_pcr_info_long),
						    tpm_pcr_info_long);
	}
    }
    if (rc == 0) {
	/* if there are PCR's specified, set the digestAtCreation */
	if (tpm_pcr_info != NULL) {
	    rc = TPM_PCRInfo_SetDigestAtCreation(tpm_key->tpm_pcr_info, tpm_pcrs);
	}
	/* if there are PCR's specified, set the localityAtCreation, digestAtCreation */
	else if (tpm_pcr_info_long != NULL) {	/* TPM_KEY12 */
	    if (rc == 0) {
		rc = TPM_Locality_Set(&(tpm_key->tpm_pcr_info_long->localityAtCreation),
					 tpm_state->tpm_stany_flags.localityModifier);
	    }
	    if (rc == 0) {
		rc = TPM_PCRInfoLong_SetDigestAtCreation(tpm_key->tpm_pcr_info_long, tpm_pcrs);
	    }
	}
    }
    /* set TPM_SIZED_BUFFER pubKey */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Set(&(tpm_key->pubKey),
				 keyLength,	/* in bytes */
				 publicKey);
    }
    if (rc == 0) {
	if (tpm_store_asymkey == NULL) {
	    printf("TPM_Key_Set: Error (fatal), No TPM_STORE_ASYMKEY supplied\n");
	    rc = TPM_FAIL;	/* should never occur */
	}
    }
    /* sanity check, currently no need to set TPM_MIGRATE_ASYMKEY */
    if (rc == 0) {
	if (tpm_migrate_asymkey != NULL) {
	    printf("TPM_Key_Set: Error (fatal), TPM_MIGRATE_ASYMKEY supplied\n");
	    rc = TPM_FAIL;	/* should never occur */
	}
    }
    if (rc == 0) {
	/* root key, no parent, just serialize the TPM_STORE_ASYMKEY structure */
	if (parent_key == NULL) {
	    if (rc == 0) {
		rc = TPM_StoreAsymkey_Store(&sbuffer, FALSE, tpm_store_asymkey); /* freed @1 */
	    }
	    if (rc == 0) {
		rc = TPM_SizedBuffer_SetFromStore(&(tpm_key->encData), &sbuffer);
	    }
	}
    }
    if (rc == 0) {
	tpm_key->tpm_store_asymkey = tpm_store_asymkey;		/* cache TPM_STORE_ASYMKEY */
	tpm_key->tpm_migrate_asymkey = tpm_migrate_asymkey;	/* cache TPM_MIGRATE_ASYMKEY */
    }
    /* Generate the TPM_STORE_ASYMKEY -> pubDataDigest.	 Serializes pcrInfo as a side effect. */
    if (rc == 0) {
	rc = TPM_Key_GeneratePubDataDigest(tpm_key);
    }
    TPM_Sbuffer_Delete(&sbuffer);	/* @1 */
    return rc;
}

/* TPM_Key_Copy() copies the source TPM_KEY to the destination.

   The destination should be initialized before the call.
*/

TPM_RESULT TPM_Key_Copy(TPM_KEY *tpm_key_dest,
			TPM_KEY *tpm_key_src,
			TPM_BOOL copyEncData)
{
    TPM_RESULT	rc = 0;

    if (rc == 0) {
	TPM_StructVer_Copy(&(tpm_key_dest->ver), &(tpm_key_src->ver));	/* works for TPM_KEY12
									   also */
	tpm_key_dest->keyUsage	= tpm_key_src->keyUsage;
	tpm_key_dest->keyFlags	= tpm_key_src->keyFlags;
	tpm_key_dest->authDataUsage = tpm_key_src->authDataUsage;
	rc = TPM_KeyParms_Copy(&(tpm_key_dest->algorithmParms), &(tpm_key_src->algorithmParms));
    }
    if (rc == 0) {
	rc = TPM_SizedBuffer_Copy(&(tpm_key_dest->pcrInfo), &(tpm_key_src->pcrInfo));
    }
    /* copy TPM_PCR_INFO cache */
    if (rc == 0) {
	if (tpm_key_src->tpm_pcr_info != NULL) {		/* TPM_KEY */
	    rc = TPM_PCRInfo_CreateFromInfo(&(tpm_key_dest->tpm_pcr_info),
					    tpm_key_src->tpm_pcr_info);
	}
	else if (tpm_key_src->tpm_pcr_info_long != NULL) {	/* TPM_KEY12 */
	    rc = TPM_PCRInfoLong_CreateFromInfoLong(&(tpm_key_dest->tpm_pcr_info_long),
						    tpm_key_src->tpm_pcr_info_long);
	}
    }
    /* copy pubKey */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Copy(&(tpm_key_dest->pubKey), &(tpm_key_src->pubKey));
    }
    /* copy encData */
    if (rc == 0) {
	if (copyEncData) {
	    rc = TPM_SizedBuffer_Copy(&(tpm_key_dest->encData), &(tpm_key_src->encData));
	}
    }
    return rc;
}

/* TPM_Key_Load()

   deserialize the structure from a 'stream'
   'stream_size' is checked for sufficient data
   returns 0 or error codes

   The TPM_PCR_INFO or TPM_PCR_INFO_LONG cache is set from the deserialized pcrInfo stream.

   After use, call TPM_Key_Delete() to free memory
*/


TPM_RESULT TPM_Key_Load(TPM_KEY *tpm_key,	/* result */
			unsigned char **stream, /* pointer to next parameter */
			uint32_t *stream_size)	/* stream size left */
{
    TPM_RESULT		rc = 0;
    
    printf(" TPM_Key_Load:\n");
    /* load public data, and create PCR cache */
    if (rc == 0) {
	rc = TPM_Key_LoadPubData(tpm_key, FALSE, stream, stream_size);
    }
    /* load encDataSize and encData */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Load(&(tpm_key->encData), stream, stream_size);
    }
    return rc;
}

/* TPM_Key_LoadClear() load a serialized key where the TPM_STORE_ASYMKEY structure is serialized in
   clear text.

   The TPM_PCR_INFO or TPM_PCR_INFO_LONG cache is set from the deserialized pcrInfo stream.

   This function is used to load internal keys (e.g. EK, SRK, owner evict keys) or keys saved as
   part of a save state.
*/

TPM_RESULT TPM_Key_LoadClear(TPM_KEY *tpm_key,		/* result */
			     TPM_BOOL isEK,		/* key being loaded is EK */
			     unsigned char **stream,	/* pointer to next parameter */
			     uint32_t *stream_size)	/* stream size left */
{
    TPM_RESULT		rc = 0;
    uint32_t		storeAsymkeySize;
    
    printf(" TPM_Key_LoadClear:\n");
    /* load public data */
    if (rc == 0) {
	rc = TPM_Key_LoadPubData(tpm_key, isEK, stream, stream_size);
    }
    /* load TPM_STORE_ASYMKEY size */
    if (rc == 0) {
	rc = TPM_Load32(&storeAsymkeySize, stream, stream_size);
    }
    /* The size might be 0 for an uninitialized internal key.  That case is not an error. */
    if ((rc == 0) && (storeAsymkeySize > 0)) {
	rc = TPM_Key_LoadStoreAsymKey(tpm_key, isEK, stream, stream_size);
    }			     
    return rc;
}

/* TPM_Key_LoadPubData() deserializes a TPM_KEY or TPM_KEY12 structure, excluding encData, to
   'tpm_key'.

   The TPM_PCR_INFO or TPM_PCR_INFO_LONG cache is set from the deserialized pcrInfo stream.
   If the pcrInfo stream is empty, the caches remain NULL.

   deserialize the structure from a 'stream'
   'stream_size' is checked for sufficient data
   returns 0 or error codes

   After use, call TPM_Key_Delete() to free memory
*/

TPM_RESULT TPM_Key_LoadPubData(TPM_KEY *tpm_key,	/* result */
			       TPM_BOOL isEK,		/* key being loaded is EK */
			       unsigned char **stream,	/* pointer to next parameter */
			       uint32_t *stream_size)	/* stream size left */
{
    TPM_RESULT		rc = 0;
   
    printf(" TPM_Key_LoadPubData:\n");
    /* peek at the first byte */
    if (rc == 0) {
	/* TPM_KEY[0] is major (non zero) */
	if ((*stream)[0] != 0) {
	    /* load ver */
	    if (rc == 0) {
		rc = TPM_StructVer_Load(&(tpm_key->ver), stream, stream_size);
	    }
	    /* check ver immediately to ease debugging */
	    if (rc == 0) {
		rc = TPM_StructVer_CheckVer(&(tpm_key->ver));
	    }
	}
	else {
	    /* TPM_KEY12 is tag (zero) */
	    /* load tag */
	    if (rc == 0) {
		rc = TPM_Load16(&(((TPM_KEY12 *)tpm_key)->tag), stream, stream_size);
	    }
	    /* load fill */
	    if (rc == 0) {
		rc = TPM_Load16(&(((TPM_KEY12 *)tpm_key)->fill), stream, stream_size);
	    }
	    if (rc == 0) {
		rc = TPM_Key_CheckTag((TPM_KEY12 *)tpm_key);
	    }
	}
    }
    /* load keyUsage */
    if (rc == 0) {
	rc = TPM_Load16(&(tpm_key->keyUsage), stream, stream_size);
    }
    /* load keyFlags */
    if (rc == 0) {
	rc = TPM_KeyFlags_Load(&(tpm_key->keyFlags), stream, stream_size);
    }
    /* load authDataUsage */
    if (rc == 0) {
	rc = TPM_Load8(&(tpm_key->authDataUsage), stream, stream_size);
    }
    /* load algorithmParms */
    if (rc == 0) {
	rc = TPM_KeyParms_Load(&(tpm_key->algorithmParms), stream, stream_size);
    }
    /* load PCRInfo */
    if ((rc == 0) && !isEK) {
	rc = TPM_SizedBuffer_Load(&(tpm_key->pcrInfo), stream, stream_size);
    }
    /* set TPM_PCR_INFO tpm_pcr_info cache from PCRInfo stream.	 If the stream is empty, a NULL is
       returned.
    */
    if ((rc == 0) && !isEK) {
	if (((TPM_KEY12 *)tpm_key)->tag != TPM_TAG_KEY12) {	/* TPM_KEY */
	    rc = TPM_PCRInfo_CreateFromBuffer(&(tpm_key->tpm_pcr_info),
					      &(tpm_key->pcrInfo));
	}
	else {							/* TPM_KEY12 */
	    rc = TPM_PCRInfoLong_CreateFromBuffer(&(tpm_key->tpm_pcr_info_long),
						  &(tpm_key->pcrInfo));
	}
    }
    /* load pubKey */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Load(&(tpm_key->pubKey), stream, stream_size);
    }
    return rc;
}

/* TPM_Key_StorePubData() serializes a TPM_KEY or TPM_KEY12 structure, excluding encData, appending
   results to 'sbuffer'.

   As a side effect, it serializes the tpm_pcr_info cache to pcrInfo.
*/

TPM_RESULT TPM_Key_StorePubData(TPM_STORE_BUFFER *sbuffer,
				TPM_BOOL isEK,
				TPM_KEY *tpm_key)
{
    TPM_RESULT	rc = 0;

    printf(" TPM_Key_StorePubData:\n");
    
    if (rc == 0) {
	/* store ver */
	if (((TPM_KEY12 *)tpm_key)->tag != TPM_TAG_KEY12) {	/* TPM_KEY */
	    rc = TPM_StructVer_Store(sbuffer, &(tpm_key->ver));
	}
	else {							/* TPM_KEY12 */
	    /* store tag */
	    if (rc == 0) {
		rc = TPM_Sbuffer_Append16(sbuffer, TPM_TAG_KEY12);
	    }
	    /* store fill */
	    if (rc == 0) {
		rc = TPM_Sbuffer_Append16(sbuffer, 0x0000);
	    }
	}
    }
    /* store keyUsage */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append16(sbuffer, tpm_key->keyUsage); 
    }
    /* store keyFlags */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append32(sbuffer, tpm_key->keyFlags); 
    }
    /* store authDataUsage */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append(sbuffer, &(tpm_key->authDataUsage), sizeof(TPM_AUTH_DATA_USAGE)); 
    }
    /* store algorithmParms */
    if (rc == 0) {
	rc = TPM_KeyParms_Store(sbuffer, &(tpm_key->algorithmParms)); 
    }
    /* store pcrInfo */
    if ((rc == 0) && !isEK) {
	/* copy cache to pcrInfo */
	if (((TPM_KEY12 *)tpm_key)->tag != TPM_TAG_KEY12) {	/* TPM_KEY */
	    rc = TPM_SizedBuffer_SetStructure(&(tpm_key->pcrInfo),
					      tpm_key->tpm_pcr_info,
					      (TPM_STORE_FUNCTION_T)TPM_PCRInfo_Store);
	}
	else {							/* TPM_KEY12 */
	    rc = TPM_SizedBuffer_SetStructure(&(tpm_key->pcrInfo),
					      tpm_key->tpm_pcr_info_long,
					      (TPM_STORE_FUNCTION_T)TPM_PCRInfoLong_Store);
	}
    }
    /* copy pcrInfo to sbuffer */
    if ((rc == 0) && !isEK) {
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_key->pcrInfo));
    }
    /* store pubKey */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_key->pubKey)); 
    }
    return rc;
}

/* TPM_Key_Store() serializes a TPM_KEY structure, appending results to 'sbuffer'

   As a side effect, it serializes the tpm_pcr_info cache to pcrInfo.
*/

TPM_RESULT TPM_Key_Store(TPM_STORE_BUFFER *sbuffer,
			 TPM_KEY *tpm_key)
{
    TPM_RESULT	rc = 0;

    printf(" TPM_Key_Store:\n");
    /* store the pubData */
    if (rc == 0) {
	rc = TPM_Key_StorePubData(sbuffer, FALSE, tpm_key); 
    }
    /* store encDataSize and encData */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_key->encData)); 
    }
    return rc;
}

/* TPM_Key_StoreClear() serializes a TPM_KEY structure, appending results to 'sbuffer'

   TPM_Key_StoreClear() serializes the tpm_store_asymkey member as cleartext.  It is used for keys
   such as the SRK, which never leave the TPM.	It is also used for saving state, where the entire
   blob is encrypted.

   As a side effect, it serializes the tpm_pcr_info cache to pcrInfo.
*/

TPM_RESULT TPM_Key_StoreClear(TPM_STORE_BUFFER *sbuffer,
			      TPM_BOOL isEK,		/* key being stored is EK */
			      TPM_KEY *tpm_key)
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	asymSbuffer;
    const unsigned char *asymBuffer;
    uint32_t		asymLength;
    
    printf(" TPM_Key_StoreClear:\n");
    TPM_Sbuffer_Init(&asymSbuffer);			/* freed @1 */
    /* store the pubData */
    if (rc == 0) {
	rc = TPM_Key_StorePubData(sbuffer, isEK, tpm_key); 
    }
    /* store TPM_STORE_ASYMKEY cache as cleartext */
    if (rc == 0) {
	/* if the TPM_STORE_ASYMKEY cache exists */
	if (tpm_key->tpm_store_asymkey != NULL) {
	    /* , serialize it */
	    if (rc == 0) {
		rc = TPM_StoreAsymkey_Store(&asymSbuffer, isEK, tpm_key->tpm_store_asymkey);
	    }
	    /* get the result */
	    TPM_Sbuffer_Get(&asymSbuffer, &asymBuffer, &asymLength);
	    /* store the result as a sized buffer */
	    if (rc == 0) {
		rc = TPM_Sbuffer_Append32(sbuffer, asymLength);
	    }
	    if (rc == 0) {
		rc = TPM_Sbuffer_Append(sbuffer, asymBuffer, asymLength);
	    }
	}
	/* If there is no TPM_STORE_ASYMKEY cache, mark it empty.  This can occur for an internal
	   key that has not been created yet.  */
	else {
	    rc = TPM_Sbuffer_Append32(sbuffer, 0);
	}
    }
    TPM_Sbuffer_Delete(&asymSbuffer);			/* @1 */
    return rc;
}

/* TPM_KEY_StorePubkey() gets (as a stream) the TPM_PUBKEY derived from a TPM_KEY

   There is no need to actually assemble the structure, since only the serialization of its two
   members are needed.
   
   The stream is returned as a TPM_STORE_BUFFER (that must be initialized and deleted by the
   caller), and it's components (buffer and size).
*/

TPM_RESULT TPM_Key_StorePubkey(TPM_STORE_BUFFER *pubkeyStream,			/* output */
			       const unsigned char **pubkeyStreamBuffer,	/* output */
			       uint32_t *pubkeyStreamLength,			/* output */
			       TPM_KEY *tpm_key)				/* input */
{
    TPM_RESULT	rc = 0;

    printf(" TPM_Key_StorePubkey:\n");
    /* the first part is a TPM_KEY_PARMS */
    if (rc == 0) {
	rc = TPM_KeyParms_Store(pubkeyStream, &(tpm_key->algorithmParms));
    }
    /* the second part is the TPM_SIZED_BUFFER pubKey */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(pubkeyStream, &(tpm_key->pubKey));
    }
    /* retrieve the resulting pubkey stream */
    if (rc == 0) {
	TPM_Sbuffer_Get(pubkeyStream, 
			pubkeyStreamBuffer,
			pubkeyStreamLength);
    }
    return rc;
}

/* TPM_Key_Delete() 

   No-OP if the parameter is NULL, else:
   frees memory allocated for the object
   sets pointers to NULL
   calls TPM_Key_Init to set members back to default values
   The TPM_KEY itself is not freed

   The key is not freed because it might be a local variable rather than a malloc'ed pointer.
*/   

void TPM_Key_Delete(TPM_KEY *tpm_key)
{
    if (tpm_key != NULL) {
	printf(" TPM_Key_Delete:\n");
	TPM_KeyParms_Delete(&(tpm_key->algorithmParms));
	/* pcrInfo */
	TPM_SizedBuffer_Delete(&(tpm_key->pcrInfo));
	/* pcr caches */
	TPM_PCRInfo_Delete(tpm_key->tpm_pcr_info);
	free(tpm_key->tpm_pcr_info);
	TPM_PCRInfoLong_Delete(tpm_key->tpm_pcr_info_long);
	free(tpm_key->tpm_pcr_info_long);

	TPM_SizedBuffer_Delete(&(tpm_key->pubKey));
	TPM_SizedBuffer_Delete(&(tpm_key->encData));
	TPM_StoreAsymkey_Delete(tpm_key->tpm_store_asymkey);
	free(tpm_key->tpm_store_asymkey);
	TPM_MigrateAsymkey_Delete(tpm_key->tpm_migrate_asymkey);
	free(tpm_key->tpm_migrate_asymkey);
	TPM_Key_Init(tpm_key);
    }
    return;
}

/* TPM_Key_CheckStruct() verifies that the 'tpm_key' has either a TPM_KEY -> ver of a TPM_KEY12 tag
   and fill
*/

TPM_RESULT TPM_Key_CheckStruct(int *ver, TPM_KEY *tpm_key)
{
    TPM_RESULT	rc = 0;

    /* The key can be either a TPM_KEY or TPM_KEY12 */
    if (*(unsigned char *)tpm_key == 0x01) {
	*ver = 1;
	rc = TPM_StructVer_CheckVer(&(tpm_key->ver));	/* check for TPM_KEY */
	if (rc == 0) {					/* if found TPM_KEY */
	    printf(" TPM_Key_CheckStruct: TPM_KEY version %u.%u\n",
		   tpm_key->ver.major, tpm_key->ver.minor);
	}
    }
    else {						/* else check for TPM_KEY12 */
	*ver = 2;
	rc = TPM_Key_CheckTag((TPM_KEY12 *)tpm_key);
	if (rc == 0) {
	    printf(" TPM_Key_CheckStruct: TPM_KEY12\n");
	}
	else {	/* not TPM_KEY or TPM_KEY12 */
	    printf("TPM_Key_CheckStruct: Error checking structure, bytes 0:3 %02x %02x %02x %02x\n",
		   tpm_key->ver.major, tpm_key->ver.minor,
		   tpm_key->ver.revMajor, tpm_key->ver.revMinor);
	    rc = TPM_BAD_KEY_PROPERTY;
	}
    }
    return rc;
}

/* TPM_Key_CheckTag() checks that the TPM_KEY12 tag is correct
 */

static TPM_RESULT TPM_Key_CheckTag(TPM_KEY12 *tpm_key12)
{
    TPM_RESULT	rc = 0;

    if (rc == 0) {
	if (tpm_key12->tag != TPM_TAG_KEY12) {
	    printf("TPM_Key_CheckTag: Error, TPM_KEY12 tag %04x should be TPM_TAG_KEY12\n",
		   tpm_key12->tag);
	    rc = TPM_BAD_KEY_PROPERTY;
	}
    }
    if (rc == 0) {
	if (tpm_key12->fill != 0x0000) {
	    printf("TPM_Key_CheckTag: Error, TPM_KEY12 fill %04x should be 0x0000\n",
		   tpm_key12->fill);
	    rc = TPM_BAD_KEY_PROPERTY;
	}
    }
    return rc;
}

/* TPM_Key_CheckProperties() checks that the TPM can generate a key of the type requested in
   'tpm_key'.

   if keyLength is non-zero, checks that the tpm_key specifies the correct key length.  If keyLength
   is 0, any tpm_key key length is accepted.

   Returns TPM_BAD_KEY_PROPERTY on error.
 */

TPM_RESULT TPM_Key_CheckProperties(int *ver,
				   TPM_KEY *tpm_key,
				   uint32_t keyLength,	/* in bits */
				   TPM_BOOL FIPS)
{
    TPM_RESULT	rc = 0;

    printf(" TPM_Key_CheckProperties:\n");
    /* check the version */
    if (rc == 0) {
	rc = TPM_Key_CheckStruct(ver, tpm_key);
    }
    /* if FIPS */
    if ((rc == 0) && FIPS) {
	/* b.  If keyInfo -> authDataUsage specifies TPM_AUTH_NEVER return TPM_NOTFIPS */
	if (tpm_key->authDataUsage == TPM_AUTH_NEVER) {
	    printf("TPM_Key_CheckProperties: Error, FIPS authDataUsage TPM_AUTH_NEVER\n");
	    rc = TPM_NOTFIPS;
	}
    }
    /* most of the work is done by TPM_KeyParms_CheckProperties() */
    if (rc == 0) {
	printf("  TPM_Key_CheckProperties: authDataUsage %02x\n", tpm_key->authDataUsage);
	rc = TPM_KeyParms_CheckProperties(&(tpm_key->algorithmParms),
					  tpm_key->keyUsage,
					  keyLength,	/* in bits */
					  FIPS);
    }
    return rc;
}

/* TPM_Key_LoadStoreAsymKey() deserializes a stream to a TPM_STORE_ASYMKEY structure and stores it
   in the TPM_KEY cache.

   Call this function when a key is loaded, either from the host (stream is decrypted encData) or
   from permanent data or saved state (stream was clear text).
*/

TPM_RESULT TPM_Key_LoadStoreAsymKey(TPM_KEY *tpm_key,
				    TPM_BOOL isEK,
				    unsigned char **stream,	/* decrypted encData (clear text) */
				    uint32_t *stream_size)
{
    TPM_RESULT	rc = 0;
    
    /* This function should never be called when the TPM_STORE_ASYMKEY structure has already been
       loaded.	This indicates an internal error. */
    printf(" TPM_Key_LoadStoreAsymKey:\n");
    if (rc == 0) {
	if (tpm_key->tpm_store_asymkey != NULL) {
	    printf("TPM_Key_LoadStoreAsymKey: Error (fatal), TPM_STORE_ASYMKEY already loaded\n");
	    rc = TPM_FAIL;	/* should never occur */
	}
    }
    /* If the stream size is 0, there is an internal error. */
    if (rc == 0) {
	if (*stream_size == 0) {
	    printf("TPM_Key_LoadStoreAsymKey: Error (fatal), stream size is 0\n");
	    rc = TPM_FAIL;	/* should never occur */
	}
    }
    /* allocate memory for the structure */
    if (rc == 0) {
	rc = TPM_Malloc((unsigned char **)&(tpm_key->tpm_store_asymkey),
			sizeof(TPM_STORE_ASYMKEY));
    }
    if (rc == 0) {
	TPM_StoreAsymkey_Init(tpm_key->tpm_store_asymkey);
	rc = TPM_StoreAsymkey_Load(tpm_key->tpm_store_asymkey, isEK,
				   stream, stream_size,
				   &(tpm_key->algorithmParms), &(tpm_key->pubKey));
	TPM_PrintFour("  TPM_Key_LoadStoreAsymKey: usageAuth",
		      tpm_key->tpm_store_asymkey->usageAuth);
    }
    return rc;
}

/* TPM_Key_GetStoreAsymkey() gets the TPM_STORE_ASYMKEY from a TPM_KEY cache.
 */

TPM_RESULT TPM_Key_GetStoreAsymkey(TPM_STORE_ASYMKEY **tpm_store_asymkey,
				   TPM_KEY *tpm_key)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_Key_GetStoreAsymkey:\n");
    if (rc == 0) {
	/* return the cached structure */
	*tpm_store_asymkey = tpm_key->tpm_store_asymkey;
	if (tpm_key->tpm_store_asymkey == NULL) {
	    printf("TPM_Key_GetStoreAsymkey: Error (fatal), no cache\n");
	    rc = TPM_FAIL;	/* indicate no cache */
	}
    }
    return rc; 
}

/* TPM_Key_GetMigrateAsymkey() gets the TPM_MIGRATE_ASYMKEY from a TPM_KEY cache.
 */

TPM_RESULT TPM_Key_GetMigrateAsymkey(TPM_MIGRATE_ASYMKEY **tpm_migrate_asymkey,
				     TPM_KEY *tpm_key)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_Key_GetMigrateAsymkey:\n");
    if (rc == 0) {
	/* return the cached structure */
	*tpm_migrate_asymkey = tpm_key->tpm_migrate_asymkey;
	if (tpm_key->tpm_migrate_asymkey == NULL) {
	    printf("TPM_Key_GetMigrateAsymkey: Error (fatal), no cache\n");
	    rc = TPM_FAIL;	/* indicate no cache */
	}
    }
    return rc; 
}

/* TPM_Key_GetUsageAuth() gets the usageAuth from the TPM_STORE_ASYMKEY or TPM_MIGRATE_ASYMKEY
   contained in a TPM_KEY
*/

TPM_RESULT TPM_Key_GetUsageAuth(TPM_SECRET **usageAuth,
				TPM_KEY *tpm_key)
{
    TPM_RESULT	rc = 0;
    TPM_STORE_ASYMKEY *tpm_store_asymkey;
    TPM_MIGRATE_ASYMKEY *tpm_migrate_asymkey;
    
    printf(" TPM_Key_GetUsageAuth:\n");
    /* check that the TPM_KEY_USAGE indicates a valid key */ 
    if (rc == 0) {
	if ((tpm_key == NULL) ||
	    (tpm_key->keyUsage == TPM_KEY_UNINITIALIZED)) {
	    printf("TPM_Key_GetUsageAuth: Error, key not initialized\n");
	    rc = TPM_INVALID_KEYUSAGE;
	}
    }
    /* get the TPM_STORE_ASYMKEY object */
    if (rc == 0) {
	rc = TPM_Key_GetStoreAsymkey(&tpm_store_asymkey, tpm_key);

	/* found a TPM_STORE_ASYMKEY */
	if (rc == 0) {
	    *usageAuth = &(tpm_store_asymkey->usageAuth);
	}
	/* get the TPM_MIGRATE_ASYMKEY object */
	else {
	    rc = TPM_Key_GetMigrateAsymkey(&tpm_migrate_asymkey, tpm_key);
	    /* found a TPM_MIGRATE_ASYMKEY */
	    if (rc == 0) {
		*usageAuth = &(tpm_migrate_asymkey->usageAuth);
	    }
	}
    }
    if (rc != 0) {
	printf("TPM_Key_GetUsageAuth: Error (fatal), "
	       "could not get TPM_STORE_ASYMKEY or TPM_MIGRATE_ASYMKEY\n");
	rc = TPM_FAIL;	/* should never occur */
    }
    /* get the usageAuth element */
    if (rc == 0) {
	TPM_PrintFour("  TPM_Key_GetUsageAuth: Auth", **usageAuth);
    }
    return rc;
}

/* TPM_Key_GetPublicKey() gets the public key from the TPM_STORE_PUBKEY contained in a TPM_KEY
 */

TPM_RESULT TPM_Key_GetPublicKey(uint32_t	*nbytes,
				unsigned char	**narr,
				TPM_KEY		*tpm_key)
{
    TPM_RESULT	rc = 0;
    
    printf(" TPM_Key_GetPublicKey:\n");
    if (rc == 0) {
	*nbytes = tpm_key->pubKey.size;
	*narr = tpm_key->pubKey.buffer;
    }
    return rc;
}

/* TPM_Key_GetPrimeFactorP() gets the prime factor p from the TPM_STORE_ASYMKEY contained in a
   TPM_KEY
*/

TPM_RESULT TPM_Key_GetPrimeFactorP(uint32_t 		*pbytes,
				   unsigned char	**parr,
				   TPM_KEY		*tpm_key)
{
    TPM_RESULT	rc = 0;
    TPM_STORE_ASYMKEY	*tpm_store_asymkey;
    
    printf(" TPM_Key_GetPrimeFactorP:\n");
    if (rc == 0) {
	rc = TPM_Key_GetStoreAsymkey(&tpm_store_asymkey, tpm_key);
    }
    if (rc == 0) {
	*pbytes = tpm_store_asymkey->privKey.p_key.size;
	*parr = tpm_store_asymkey->privKey.p_key.buffer;
    }
    return rc;
}

/* TPM_Key_GetPrivateKey() gets the private key from the TPM_STORE_ASYMKEY contained in a TPM_KEY
 */

TPM_RESULT TPM_Key_GetPrivateKey(uint32_t	*dbytes,
				 unsigned char	**darr,
				 TPM_KEY	*tpm_key)
{
    TPM_RESULT	rc = 0;
    TPM_STORE_ASYMKEY	*tpm_store_asymkey;
    
    printf(" TPM_Key_GetPrivateKey:\n");
    if (rc == 0) {
	rc = TPM_Key_GetStoreAsymkey(&tpm_store_asymkey, tpm_key);
    }
    if (rc == 0) {
	*dbytes = tpm_store_asymkey->privKey.d_key.size;
	*darr = tpm_store_asymkey->privKey.d_key.buffer;
    }
    return rc;
}

/* TPM_Key_GetExponent() gets the exponent key from the TPM_RSA_KEY_PARMS contained in a TPM_KEY
 */

TPM_RESULT TPM_Key_GetExponent(uint32_t		*ebytes,
			       unsigned char	**earr,
			       TPM_KEY		*tpm_key)
{
    TPM_RESULT		rc = 0;
    
    printf(" TPM_Key_GetExponent:\n");
    if (rc == 0) {
	rc = TPM_KeyParms_GetExponent(ebytes, earr, &(tpm_key->algorithmParms));
    }
    return rc;
}

/* TPM_Key_GetPCRUsage() returns 'pcrUsage' TRUE if any bit is set in the pcrSelect bit mask.

   'start_pcr' indicates the starting byte index into pcrSelect[]
*/

TPM_RESULT TPM_Key_GetPCRUsage(TPM_BOOL *pcrUsage,
			       TPM_KEY *tpm_key,
			       size_t start_index)
{
    TPM_RESULT	rc = 0;
    
    printf(" TPM_Key_GetPCRUsage: Start %lu\n", (unsigned long)start_index);
    if (((TPM_KEY12 *)tpm_key)->tag != TPM_TAG_KEY12) { /* TPM_KEY */
	rc = TPM_PCRInfo_GetPCRUsage(pcrUsage, tpm_key->tpm_pcr_info, start_index);
    }
    else {						/* TPM_KEY12 */
	rc = TPM_PCRInfoLong_GetPCRUsage(pcrUsage, tpm_key->tpm_pcr_info_long, start_index);
    }
    return rc;
}

/* TPM_Key_GetLocalityAtRelease() the localityAtRelease for a TPM_PCR_INFO_LONG.
   For a TPM_PCR_INFO is returns TPM_LOC_ALL (all localities).
*/

TPM_RESULT TPM_Key_GetLocalityAtRelease(TPM_LOCALITY_SELECTION *localityAtRelease,
					TPM_KEY *tpm_key)
{
    TPM_RESULT	rc = 0;
    
    printf(" TPM_Key_GetLocalityAtRelease:\n");
    if (((TPM_KEY12 *)tpm_key)->tag != TPM_TAG_KEY12) { /* TPM_KEY */
	/* locality not used for TPM_PCR_INFO */
	*localityAtRelease = TPM_LOC_ALL;
    }
    /* TPM_KEY12 */
    else if (tpm_key->tpm_pcr_info_long == NULL) {
	/* locality not used if TPM_PCR_INFO_LONG was not specified */
	*localityAtRelease = TPM_LOC_ALL;
    }
    else {
	*localityAtRelease = tpm_key->tpm_pcr_info_long->localityAtRelease;
    }
    return rc;
}

/* TPM_Key_GenerateRSA() generates a TPM_KEY using TPM_KEY_PARMS.  The tag/version is set correctly.

   The TPM_STORE_ASYMKEY member cache is set.  pcrInfo is set as a serialized tpm_pcr_info or
   tpm_pcr_info_long.

   For exported keys, encData is not set yet.  It later becomes the encryption of TPM_STORE_ASYMKEY.

   For internal 'root' keys (endorsement key, srk), encData is stored as clear text.

   It returns the TPM_KEY object.

   Call tree:
	local - sets tpm_store_asymkey->privkey
	TPM_Key_Set - sets keyUsage, keyFlags, authDataUsage, algorithmParms
			tpm_pcr_info cache, digestAtCreation, pubKey,
	    TPM_Key_GeneratePubDataDigest - pubDataDigest
		TPM_Key_Store
		    TPM_Key_StorePubData - serializes tpm_pcr_info cache
*/

TPM_RESULT TPM_Key_GenerateRSA(TPM_KEY *tpm_key,		/* output created key */
			       tpm_state_t *tpm_state,
			       TPM_KEY *parent_key,		/* NULL for root keys */
			       TPM_DIGEST *tpm_pcrs,		/* PCR array from state */
			       int ver,				/* TPM_KEY or TPM_KEY12 */
			       TPM_KEY_USAGE keyUsage,			/* input */
			       TPM_KEY_FLAGS keyFlags,			/* input */
			       TPM_AUTH_DATA_USAGE authDataUsage,	/* input */
			       TPM_KEY_PARMS *tpm_key_parms,		/* input */
			       TPM_PCR_INFO *tpm_pcr_info,		/* input */
			       TPM_PCR_INFO_LONG *tpm_pcr_info_long)	/* input */
{
    TPM_RESULT		rc = 0;
    TPM_RSA_KEY_PARMS	*tpm_rsa_key_parms;
    unsigned char	*earr;		/* public exponent */
    uint32_t		ebytes;

	/* generated RSA key */
    unsigned char	*n = NULL;	/* public key */
    unsigned char	*p = NULL;	/* prime factor */
    unsigned char	*q = NULL;	/* prime factor */
    unsigned char	*d = NULL;	/* private key */
    
    printf(" TPM_Key_GenerateRSA:\n");
    /* extract the TPM_RSA_KEY_PARMS from TPM_KEY_PARMS */
    if (rc == 0) {
	rc = TPM_KeyParms_GetRSAKeyParms(&tpm_rsa_key_parms, tpm_key_parms);
    }
    /* get the public exponent, with conversion */
    if (rc == 0) {
	rc = TPM_RSAKeyParms_GetExponent(&ebytes, &earr, tpm_rsa_key_parms);
    }
    /* allocate storage for TPM_STORE_ASYMKEY.	The structure is not freed.  It is cached in the
       TPM_KEY->TPM_STORE_ASYMKEY member and freed when they are deleted. */
    if (rc == 0) {
	rc = TPM_Malloc((unsigned char **)&(tpm_key->tpm_store_asymkey),
			sizeof(TPM_STORE_ASYMKEY));
    }
    if (rc == 0) {
	TPM_StoreAsymkey_Init(tpm_key->tpm_store_asymkey);
    }
    /* generate the key pair */
    if (rc == 0) {
	rc = TPM_RSAGenerateKeyPair(&n,		/* public key (modulus) freed @3 */
				    &p,		/* private prime factor freed @4 */
				    &q,		/* private prime factor freed @5 */
				    &d,		/* private key (private exponent) freed @6 */
				    tpm_rsa_key_parms->keyLength,	/* key size in bits */
				    earr,	/* public exponent */
				    ebytes);
    }
    /* construct the TPM_STORE_ASYMKEY member */
    if (rc == 0) {
	TPM_PrintFour(" TPM_Key_GenerateRSA: Public key n", n);
	TPM_PrintAll(" TPM_Key_GenerateRSA: Exponent", earr, ebytes);
	TPM_PrintFour(" TPM_Key_GenerateRSA: Private prime p", p);
	TPM_PrintFour(" TPM_Key_GenerateRSA: Private prime q", q);
	TPM_PrintFour(" TPM_Key_GenerateRSA: Private key d", d);
	/* add the private primes and key to the TPM_STORE_ASYMKEY object */
	rc = TPM_SizedBuffer_Set(&(tpm_key->tpm_store_asymkey->privKey.d_key),
				 tpm_rsa_key_parms->keyLength/CHAR_BIT,
				 d);
    }
    if (rc == 0) {
	rc = TPM_SizedBuffer_Set(&(tpm_key->tpm_store_asymkey->privKey.p_key),
				 tpm_rsa_key_parms->keyLength/(CHAR_BIT * 2),
				 p);
    }
    if (rc == 0) {
	rc = TPM_SizedBuffer_Set(&(tpm_key->tpm_store_asymkey->privKey.q_key),
				 tpm_rsa_key_parms->keyLength/(CHAR_BIT * 2),
				 q);
    }
    if (rc == 0) {
	rc = TPM_Key_Set(tpm_key,
			 tpm_state,
			 parent_key,
			 tpm_pcrs,
			 ver,					/* TPM_KEY or TPM_KEY12 */
			 keyUsage,				/* TPM_KEY_USAGE */
			 keyFlags,				/* TPM_KEY_FLAGS */
			 authDataUsage,				/* TPM_AUTH_DATA_USAGE */
			 tpm_key_parms,				/* TPM_KEY_PARMS */
			 tpm_pcr_info,				/* TPM_PCR_INFO */
			 tpm_pcr_info_long,			/* TPM_PCR_INFO_LONG */
			 tpm_rsa_key_parms->keyLength/CHAR_BIT, /* TPM_STORE_PUBKEY.keyLength */
			 n,				/* TPM_STORE_PUBKEY.key (public key) */
			 /* FIXME redundant */
			 tpm_key->tpm_store_asymkey,	/* cache the TPM_STORE_ASYMKEY structure */
			 NULL);				/* TPM_MIGRATE_ASYMKEY */
    }
    free(n);					/* @3 */
    free(p);					/* @4 */
    free(q);					/* @5 */
    free(d);					/* @6 */
    return rc;
}

/* TPM_Key_GeneratePubkeyDigest() serializes a TPM_PUBKEY derived from the TPM_KEY and calculates
   its digest.
*/

TPM_RESULT TPM_Key_GeneratePubkeyDigest(TPM_DIGEST tpm_digest,
					TPM_KEY *tpm_key)
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	pubkeyStream;		/* from tpm_key */
    const unsigned char *pubkeyStreamBuffer;	
    uint32_t		pubkeyStreamLength;

    printf(" TPM_Key_GeneratePubkeyDigest:\n");
    TPM_Sbuffer_Init(&pubkeyStream);		/* freed @1 */
    /* serialize a TPM_PUBKEY derived from the TPM_KEY */
    if (rc == 0) {
	rc = TPM_Key_StorePubkey(&pubkeyStream,		/* output */
				 &pubkeyStreamBuffer,	/* output */
				 &pubkeyStreamLength,	/* output */
				 tpm_key);		/* input */
    }
    if (rc == 0) {
	rc = TPM_SHA1(tpm_digest,
		      pubkeyStreamLength, pubkeyStreamBuffer,
		      0, NULL);
    }	
    TPM_Sbuffer_Delete(&pubkeyStream);		/* @1 */
    return rc;

}

/* TPM_Key_ComparePubkey() serializes and hashes the TPM_PUBKEY derived from a TPM_KEY and a
   TPM_PUBKEY and compares the results
*/

TPM_RESULT TPM_Key_ComparePubkey(TPM_KEY *tpm_key,
				 TPM_PUBKEY *tpm_pubkey)
{
    TPM_RESULT		rc = 0;
    TPM_DIGEST		key_digest;
    TPM_DIGEST		pubkey_digest;
    
    if (rc == 0) {
	rc = TPM_Key_GeneratePubkeyDigest(key_digest, tpm_key);
    }
    if (rc == 0) {
	rc = TPM_SHA1_GenerateStructure(pubkey_digest, tpm_pubkey,
					(TPM_STORE_FUNCTION_T)TPM_Pubkey_Store);
    }
    if (rc == 0) {
	rc = TPM_Digest_Compare(key_digest, pubkey_digest);
    }	 
    return rc;
}

/* TPM_Key_GeneratePubDataDigest() generates and stores a TPM_STORE_ASYMKEY -> pubDataDigest

   As a side effect, it serializes the tpm_pcr_info cache to pcrInfo.
*/

TPM_RESULT TPM_Key_GeneratePubDataDigest(TPM_KEY *tpm_key)
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	sbuffer;	/* TPM_KEY serialization */
    TPM_STORE_ASYMKEY	*tpm_store_asymkey;
    
    printf(" TPM_Key_GeneratePubDataDigest:\n");
    TPM_Sbuffer_Init(&sbuffer);			/* freed @1 */
    /* serialize the TPM_KEY excluding the encData fields */
    if (rc == 0) {
	rc = TPM_Key_StorePubData(&sbuffer, FALSE, tpm_key);
    }
    /* get the TPM_STORE_ASYMKEY structure */
    if (rc == 0) {
	rc = TPM_Key_GetStoreAsymkey(&tpm_store_asymkey, tpm_key);
    }
    /* hash the serialized buffer to tpm_digest */
    if (rc == 0) {
	rc = TPM_SHA1Sbuffer(tpm_store_asymkey->pubDataDigest, &sbuffer);
    }
    TPM_Sbuffer_Delete(&sbuffer);	/* @1 */
    return rc;
}

/* TPM_Key_CheckPubDataDigest() generates a TPM_STORE_ASYMKEY -> pubDataDigest and compares it to
   the stored value.

   Returns:  Error id
 */

TPM_RESULT TPM_Key_CheckPubDataDigest(TPM_KEY *tpm_key)
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	sbuffer;	/* TPM_KEY serialization */
    TPM_STORE_ASYMKEY	*tpm_store_asymkey;
    TPM_DIGEST		tpm_digest;	/* calculated pubDataDigest */
    
    printf(" TPM_Key_CheckPubDataDigest:\n");
    TPM_Sbuffer_Init(&sbuffer);			/* freed @1 */
    /* serialize the TPM_KEY excluding the encData fields */
    if (rc == 0) {
	rc = TPM_Key_StorePubData(&sbuffer, FALSE, tpm_key);
    }
    /* get the TPM_STORE_ASYMKEY structure */
    if (rc == 0) {
	rc = TPM_Key_GetStoreAsymkey(&tpm_store_asymkey, tpm_key);
    }
    if (rc == 0) {
	rc = TPM_SHA1Sbuffer(tpm_digest, &sbuffer);
    }
    if (rc == 0) {
	rc = TPM_Digest_Compare(tpm_store_asymkey->pubDataDigest, tpm_digest);
    }
    TPM_Sbuffer_Delete(&sbuffer);	/* @1 */
    return rc;
}

/* TPM_Key_GenerateEncData() generates an TPM_KEY -> encData structure member by serializing the
   cached TPM_KEY -> TPM_STORE_ASYMKEY member and encrypting the result using the parent_key public
   key.
*/

TPM_RESULT TPM_Key_GenerateEncData(TPM_KEY *tpm_key,
				   TPM_KEY *parent_key)
{
    TPM_RESULT		rc = 0;
    TPM_STORE_ASYMKEY	*tpm_store_asymkey;

    printf(" TPM_Key_GenerateEncData;\n");
    /* get the TPM_STORE_ASYMKEY structure */
    if (rc == 0) {
	rc = TPM_Key_GetStoreAsymkey(&tpm_store_asymkey, tpm_key);
    }
    if (rc == 0) {
	rc = TPM_StoreAsymkey_GenerateEncData(&(tpm_key->encData),
					      tpm_store_asymkey,
					      parent_key);
    }
    return rc;
}


/* TPM_Key_DecryptEncData() decrypts the TPM_KEY -> encData using the parent private key.  The
   result is deserialized and stored in the TPM_KEY -> TPM_STORE_ASYMKEY cache.

*/

TPM_RESULT TPM_Key_DecryptEncData(TPM_KEY *tpm_key,	/* result */
				  TPM_KEY *parent_key)	/* parent for decrypting encData */
{
    TPM_RESULT		rc = 0;
    unsigned char	*decryptData = NULL;	/* freed @1 */
    uint32_t		decryptDataLength = 0;	/* actual valid data */
    unsigned char	*stream;
    uint32_t		stream_size;

    printf(" TPM_Key_DecryptEncData\n");
    /* allocate space for the decrypted data */
    if (rc == 0) {
	rc = TPM_RSAPrivateDecryptMalloc(&decryptData,			/* decrypted data */
					 &decryptDataLength,		/* actual size of decrypted
									   data */
					 tpm_key->encData.buffer,	/* encrypted data */
					 tpm_key->encData.size,		/* encrypted data size */
					 parent_key);
    }
    /* load the TPM_STORE_ASYMKEY cache from the 'encData' member stream */
    if (rc == 0) {
	stream = decryptData;
	stream_size = decryptDataLength;
	rc = TPM_Key_LoadStoreAsymKey(tpm_key, FALSE, &stream, &stream_size);
    }
    free(decryptData);		/* @1 */
    return rc;
}

/* TPM_Key_GeneratePCRDigest() generates a digest based on the current PCR state and the PCR's
   specified with the key.

   The key can be either TPM_KEY or TPM_KEY12.

   This function assumes that TPM_Key_GetPCRUsage() has determined that PCR's are in use, so
   a NULL PCR cache will return an error here.

   See Part 1 25.1 
*/

TPM_RESULT TPM_Key_CheckPCRDigest(TPM_KEY *tpm_key,
				  tpm_state_t *tpm_state)
{
    TPM_RESULT		rc = 0;
    
    printf(" TPM_Key_GeneratePCRDigest:\n");
    if (((TPM_KEY12 *)tpm_key)->tag != TPM_TAG_KEY12) { /* TPM_KEY */
	/* i. Calculate H1 a TPM_COMPOSITE_HASH of the PCR selected by LK -> pcrInfo ->
	   releasePCRSelection */
	/* ii. Compare H1 to LK -> pcrInfo -> digestAtRelease on mismatch return TPM_WRONGPCRVAL */
	if (rc == 0) {
	    rc = TPM_PCRInfo_CheckDigest(tpm_key->tpm_pcr_info,
					 tpm_state->tpm_stclear_data.PCRS);	/* array of PCR's */
	}
    }
    else {					/* TPM_KEY12 */
	/* i. Calculate H1 a TPM_COMPOSITE_HASH of the PCR selected by LK -> pcrInfo ->
	   releasePCRSelection */
	/* ii. Compare H1 to LK -> pcrInfo -> digestAtRelease on mismatch return TPM_WRONGPCRVAL */
	if (rc == 0) {
	    rc = TPM_PCRInfoLong_CheckDigest(tpm_key->tpm_pcr_info_long,
					     tpm_state->tpm_stclear_data.PCRS,	/* array of PCR's */
					     tpm_state->tpm_stany_flags.localityModifier);
	}
    }
    /* 4. Allow use of the key */
    if (rc != 0) {
	printf("TPM_Key_CheckPCRDigest: Error, wrong digestAtRelease value\n");
	rc = TPM_WRONGPCRVAL;
    }
    return rc;
}

/* TPM_Key_CheckRestrictDelegate() checks the restrictDelegate data against the TPM_KEY properties.
   It determines how the TPM responds to delegated requests to use a certified migration key.

   Called from TPM_AuthSessions_GetData() if it's a DSAP session using a key entity..

   TPM_PERMANENT_DATA -> restrictDelegate is used as follows:

   1. If the session type is TPM_PID_DSAP and TPM_KEY -> keyFlags -> migrateAuthority is TRUE
   a. If
     TPM_KEY_USAGE is TPM_KEY_SIGNING and restrictDelegate -> TPM_CMK_DELEGATE_SIGNING is TRUE, or
     TPM_KEY_USAGE is TPM_KEY_STORAGE and restrictDelegate -> TPM_CMK_DELEGATE_STORAGE is TRUE, or
     TPM_KEY_USAGE is TPM_KEY_BIND and restrictDelegate -> TPM_CMK_DELEGATE_BIND is TRUE, or
     TPM_KEY_USAGE is TPM_KEY_LEGACY and restrictDelegate -> TPM_CMK_DELEGATE_LEGACY is TRUE, or
     TPM_KEY_USAGE is TPM_KEY_MIGRATE and restrictDelegate -> TPM_CMK_DELEGATE_MIGRATE is TRUE
   then the key can be used.
   b. Else return TPM_INVALID_KEYUSAGE.

*/

TPM_RESULT TPM_Key_CheckRestrictDelegate(TPM_KEY *tpm_key,
					 TPM_CMK_DELEGATE restrictDelegate)
{
    TPM_RESULT	rc = 0;
    
    printf("TPM_Key_CheckRestrictDelegate:\n");
    if (rc == 0) {
	if (tpm_key == NULL) {
	    printf("TPM_Key_CheckRestrictDelegate: Error (fatal), key NULL\n");
	    rc = TPM_FAIL;	/* internal error, should never occur */
	}
    }
    /* if it's a certified migration key */
    if (rc == 0) {
	if (tpm_key->keyFlags & TPM_MIGRATEAUTHORITY) {
	    if (!(
		  ((restrictDelegate & TPM_CMK_DELEGATE_SIGNING) &&
		   (tpm_key->keyUsage == TPM_KEY_SIGNING)) ||

		  ((restrictDelegate & TPM_CMK_DELEGATE_STORAGE) &&
		   (tpm_key->keyUsage == TPM_KEY_STORAGE)) ||

		  ((restrictDelegate & TPM_CMK_DELEGATE_BIND) &&
		   (tpm_key->keyUsage == TPM_KEY_BIND)) ||

		  ((restrictDelegate & TPM_CMK_DELEGATE_LEGACY) &&
		   (tpm_key->keyUsage == TPM_KEY_LEGACY)) ||

		  ((restrictDelegate & TPM_CMK_DELEGATE_MIGRATE) &&
		   (tpm_key->keyUsage == TPM_KEY_MIGRATE))
		  )) {
		printf("TPM_Key_CheckRestrictDelegate: Error, "
		       "invalid keyUsage %04hx restrictDelegate %08x\n",
		       tpm_key->keyUsage, restrictDelegate);
		rc = TPM_INVALID_KEYUSAGE;
	    }
	}
    }
    return rc;
}

/*
  TPM_KEY_FLAGS
*/

/* TPM_KeyFlags_Load() deserializes a TPM_KEY_FLAGS value and checks for a legal value.
 */

TPM_RESULT TPM_KeyFlags_Load(TPM_KEY_FLAGS *tpm_key_flags,	/* result */
			     unsigned char **stream,		/* pointer to next parameter */
			     uint32_t *stream_size)		/* stream size left */
{
    TPM_RESULT		rc = 0;

    /* load keyFlags */
    if (rc == 0) {
	rc = TPM_Load32(tpm_key_flags, stream, stream_size);
    }
    /* check TPM_KEY_FLAGS validity, look for extra bits set */
    if (rc == 0) {
	if (*tpm_key_flags & ~TPM_KEY_FLAGS_MASK) {
	    printf("TPM_KeyFlags_Load: Error, illegal keyFlags value %08x\n",
		   *tpm_key_flags);
	    rc = TPM_BAD_KEY_PROPERTY;
	}
    }
    return rc;
}

/*
  TPM_KEY_PARMS
*/

void TPM_KeyParms_Init(TPM_KEY_PARMS *tpm_key_parms)
{
    printf(" TPM_KeyParms_Init:\n");
    tpm_key_parms->algorithmID = 0;
    tpm_key_parms->encScheme = TPM_ES_NONE;
    tpm_key_parms->sigScheme = TPM_SS_NONE;
    TPM_SizedBuffer_Init(&(tpm_key_parms->parms));
    tpm_key_parms->tpm_rsa_key_parms = NULL;
    return;
}

#if 0
/* TPM_KeyParms_SetRSA() is a 'Set' version specific to RSA keys */

TPM_RESULT TPM_KeyParms_SetRSA(TPM_KEY_PARMS *tpm_key_parms,
			       TPM_ALGORITHM_ID algorithmID,
			       TPM_ENC_SCHEME encScheme,
			       TPM_SIG_SCHEME sigScheme,
			       uint32_t keyLength,	/* in bits */
			       TPM_SIZED_BUFFER *exponent)
{
    TPM_RESULT	rc = 0;

    printf(" TPM_KeyParms_SetRSA:\n");
    /* copy the TPM_KEY_PARMS members */
    if (rc == 0) {
	tpm_key_parms->algorithmID = algorithmID;
	tpm_key_parms->encScheme = encScheme;
	tpm_key_parms->sigScheme = sigScheme;
	/* construct the TPM_RSA_KEY_PARMS cache member object */
	rc = TPM_RSAKeyParms_New(&tpm_key_parms->tpm_rsa_key_parms);
    }
    if (rc == 0) {
	/* copy the TPM_RSA_KEY_PARMS members */
	tpm_key_parms->tpm_rsa_key_parms->keyLength = keyLength;
	tpm_key_parms->tpm_rsa_key_parms->numPrimes = 2;
	rc = TPM_SizedBuffer_Copy(&(tpm_key_parms->tpm_rsa_key_parms->exponent), exponent);
    }
    /* serialize the TPM_RSA_KEY_PARMS object back to TPM_KEY_PARMS */
    if (rc == 0) {
	rc = TPM_SizedBuffer_SetStructure(&(tpm_key_parms->parms),
					  tpm_key_parms->tpm_rsa_key_parms,
					  (TPM_STORE_FUNCTION_T)TPM_RSAKeyParms_Store);
    }
    return rc;
}
#endif


/* TPM_KeyParms_Copy() copies the source to the destination.

   If the algorithmID is TPM_ALG_RSA, the tpm_rsa_key_parms cache is allocated and copied.

   Must be freed by TPM_KeyParms_Delete() after use
*/

TPM_RESULT TPM_KeyParms_Copy(TPM_KEY_PARMS *tpm_key_parms_dest,
			     TPM_KEY_PARMS *tpm_key_parms_src)
{
    TPM_RESULT rc = 0;
    
    printf(" TPM_KeyParms_Copy:\n");
    if (rc == 0) {
	tpm_key_parms_dest->algorithmID = tpm_key_parms_src->algorithmID;
	tpm_key_parms_dest->encScheme	= tpm_key_parms_src->encScheme;
	tpm_key_parms_dest->sigScheme	= tpm_key_parms_src->sigScheme;
	rc = TPM_SizedBuffer_Copy(&(tpm_key_parms_dest->parms),
				  &(tpm_key_parms_src->parms));
    }
    /* if there is a destination TPM_RSA_KEY_PARMS cache */
    if ((rc == 0) && (tpm_key_parms_dest->algorithmID == TPM_ALG_RSA)) {
	/* construct the TPM_RSA_KEY_PARMS cache member object */
	if (rc == 0) {
	    rc = TPM_RSAKeyParms_New(&(tpm_key_parms_dest->tpm_rsa_key_parms));
	}
	/* copy the TPM_RSA_KEY_PARMS member */
	if (rc == 0) {
	    rc = TPM_RSAKeyParms_Copy(tpm_key_parms_dest->tpm_rsa_key_parms,
				      tpm_key_parms_src->tpm_rsa_key_parms);
	}
    }
    return rc;
}

/* TPM_KeyParms_Load deserializes a stream to a TPM_KEY_PARMS structure.

   Must be freed by TPM_KeyParms_Delete() after use
*/

TPM_RESULT TPM_KeyParms_Load(TPM_KEY_PARMS *tpm_key_parms,	/* result */
			     unsigned char **stream,		/* pointer to next parameter */
			     uint32_t *stream_size)		/* stream size left */
{
    TPM_RESULT		rc = 0;
    unsigned char	*parms_stream;
    uint32_t		parms_stream_size;
    
    printf(" TPM_KeyParms_Load:\n");
    /* load algorithmID */
    if (rc == 0) {
	rc = TPM_Load32(&(tpm_key_parms->algorithmID), stream, stream_size);
    }
    /* load encScheme */
    if (rc == 0) {
	rc = TPM_Load16(&(tpm_key_parms->encScheme), stream, stream_size);
    }
    /* load sigScheme */
    if (rc == 0) {
	rc = TPM_Load16(&(tpm_key_parms->sigScheme), stream, stream_size);
    }
    /* load parmSize and parms */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Load(&(tpm_key_parms->parms), stream, stream_size);
    }
    if (rc == 0) {
	switch (tpm_key_parms->algorithmID) {
	    /* Allow load of uninitialized structures */
	  case 0:
	    break;

	  case TPM_ALG_RSA:
	    /* load the TPM_RSA_KEY_PARMS cache if the algorithmID indicates an RSA key */
	    if (rc == 0) {
		rc = TPM_RSAKeyParms_New(&(tpm_key_parms->tpm_rsa_key_parms));
	    }
	    /* deserialize the parms stream, but don't move the pointer */
	    if (rc == 0) {
		parms_stream = tpm_key_parms->parms.buffer;
		parms_stream_size = tpm_key_parms->parms.size;
		rc = TPM_RSAKeyParms_Load(tpm_key_parms->tpm_rsa_key_parms,
					  &parms_stream, &parms_stream_size);
	    }
	    break;

	    /* NOTE Only handles TPM_RSA_KEY_PARMS, could handle TPM_SYMMETRIC_KEY_PARMS */
	  case TPM_ALG_AES128:
	  case TPM_ALG_AES192:
	  case TPM_ALG_AES256:
	  default:
	    printf("TPM_KeyParms_Load: Cannot handle algorithmID %08x\n",
		   tpm_key_parms->algorithmID);
	    rc = TPM_BAD_KEY_PROPERTY;
	    break;
	}
    }
    return rc;
}

TPM_RESULT TPM_KeyParms_GetExponent(uint32_t		*ebytes,
				    unsigned char	**earr,
				    TPM_KEY_PARMS	*tpm_key_parms)
{
    TPM_RESULT		rc = 0;
    TPM_RSA_KEY_PARMS	*tpm_rsa_key_parms;
    
    printf(" TPM_KeyParms_GetExponent:\n");
    if (rc == 0) {
	rc = TPM_KeyParms_GetRSAKeyParms(&tpm_rsa_key_parms, tpm_key_parms);
    }
    if (rc == 0) {
	rc = TPM_RSAKeyParms_GetExponent(ebytes, earr, tpm_rsa_key_parms);
    }
    return rc;
}
     

/* TPM_KeyParms_Store serializes a TPM_KEY_PARMS structure, appending results to 'sbuffer'
*/

TPM_RESULT TPM_KeyParms_Store(TPM_STORE_BUFFER *sbuffer,
			      TPM_KEY_PARMS *tpm_key_parms)
{
    TPM_RESULT	rc = 0;

    printf(" TPM_KeyParms_Store:\n");
    /* store algorithmID */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append32(sbuffer, tpm_key_parms->algorithmID); 
    }
    /* store encScheme */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append16(sbuffer, tpm_key_parms->encScheme); 
    }
    /* store sigScheme */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append16(sbuffer, tpm_key_parms->sigScheme); 
    }
    /* copy cache to parms */
    if (rc == 0) {
	switch (tpm_key_parms->algorithmID) {
	    /* Allow store of uninitialized structures */
	  case 0:
	    break;
	  case TPM_ALG_RSA:
	    rc = TPM_SizedBuffer_SetStructure(&(tpm_key_parms->parms),
					      tpm_key_parms->tpm_rsa_key_parms,
					      (TPM_STORE_FUNCTION_T)TPM_RSAKeyParms_Store);
	    break;
	    /* NOTE Only handles TPM_RSA_KEY_PARMS, could handle TPM_SYMMETRIC_KEY_PARMS */
	  case TPM_ALG_AES128:
	  case TPM_ALG_AES192:
	  case TPM_ALG_AES256:
	  default:
	    printf("TPM_KeyParms_Store: Cannot handle algorithmID %08x\n",
		   tpm_key_parms->algorithmID);
	    rc = TPM_BAD_KEY_PROPERTY;
	    break;
	}
    }
    /* store parms */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_key_parms->parms));
    }
    return rc;
}

/* TPM_KeyParms_Delete frees any member allocated memory */
    
void TPM_KeyParms_Delete(TPM_KEY_PARMS *tpm_key_parms)
{
    printf(" TPM_KeyParms_Delete:\n");
    if (tpm_key_parms != NULL) {
	TPM_SizedBuffer_Delete(&(tpm_key_parms->parms));
	TPM_RSAKeyParms_Delete(tpm_key_parms->tpm_rsa_key_parms);
	free(tpm_key_parms->tpm_rsa_key_parms);
	TPM_KeyParms_Init(tpm_key_parms);
    }
    return;
}

/* TPM_KeyParms_GetRSAKeyParms() gets the TPM_RSA_KEY_PARMS from a TPM_KEY_PARMS cache.

   Returns an error if the cache is NULL, since the cache should always be set when the
   TPM_KEY_PARMS indicates an RSA key.
*/

TPM_RESULT TPM_KeyParms_GetRSAKeyParms(TPM_RSA_KEY_PARMS **tpm_rsa_key_parms,
				       TPM_KEY_PARMS *tpm_key_parms)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_KeyParms_GetRSAKeyParms:\n");
    /* algorithmID must be RSA */
    if (rc == 0) {
	if (tpm_key_parms->algorithmID != TPM_ALG_RSA) {
	    printf("TPM_KeyParms_GetRSAKeyParms: Error, incorrect algorithmID %08x\n",
		   tpm_key_parms->algorithmID);
	    rc = TPM_BAD_KEY_PROPERTY;
	}
    }
    /* if the TPM_RSA_KEY_PARMS structure has not been cached, deserialize it */
    if (rc == 0) {
	if (tpm_key_parms->tpm_rsa_key_parms == NULL) {
	    printf("TPM_KeyParms_GetRSAKeyParms: Error (fatal), cache is NULL\n");
	    /* This should never occur.	 The cache is loaded when the TPM_KEY_PARMS is loaded. */
	    rc = TPM_FAIL;
	}
    }
    /* return the cached structure */
    if (rc == 0) {
	*tpm_rsa_key_parms = tpm_key_parms->tpm_rsa_key_parms;
    }
    return rc; 
}

/* TPM_KeyParms_CheckProperties() checks that the TPM can generate a key of the type requested in
   'tpm_key_parms'

   if' keyLength' is non-zero, checks that the tpm_key specifies the correct key length.  If
   keyLength is 0, any tpm_key key length is accepted.
*/

TPM_RESULT TPM_KeyParms_CheckProperties(TPM_KEY_PARMS *tpm_key_parms,
					TPM_KEY_USAGE tpm_key_usage,
					uint32_t keyLength,	/* in bits */
					TPM_BOOL FIPS)
{
    TPM_RESULT	rc = 0;
    TPM_RSA_KEY_PARMS *tpm_rsa_key_parms = NULL;/* used if algorithmID indicates RSA */

    printf("  TPM_KeyParms_CheckProperties: keyUsage %04hx\n", tpm_key_usage);
    printf("  TPM_KeyParms_CheckProperties: sigScheme %04hx\n", tpm_key_parms->sigScheme);
    printf("  TPM_KeyParms_CheckProperties: encScheme %04hx\n", tpm_key_parms->encScheme);
    if (rc == 0) {
	/* the code currently only supports RSA */
	if (tpm_key_parms->algorithmID != TPM_ALG_RSA) {
	    printf("TPM_KeyParms_CheckProperties: Error, algorithmID not TPM_ALG_RSA\n");
	    rc = TPM_BAD_KEY_PROPERTY;
	}
    }
    /* get the TPM_RSA_KEY_PARMS structure from the TPM_KEY_PARMS structure */
    /* NOTE: for now only support RSA keys */
    if (rc == 0) {
	rc = TPM_KeyParms_GetRSAKeyParms(&tpm_rsa_key_parms, tpm_key_parms);
    }
    /* check key length if specified as input parameter */
    if ((rc == 0) && (keyLength != 0)) {
	if (tpm_rsa_key_parms->keyLength != keyLength) {	/* in bits */
	    printf("TPM_KeyParms_CheckProperties: Error, Bad keyLength should be %u, was %u\n",
		   keyLength, tpm_rsa_key_parms->keyLength);
	    rc = TPM_BAD_KEY_PROPERTY;
	}
    }
    if (rc == 0) {
	if (tpm_rsa_key_parms->keyLength > TPM_RSA_KEY_LENGTH_MAX) {	/* in bits */
	    printf("TPM_KeyParms_CheckProperties: Error, Bad keyLength max %u, was %u\n",
		   TPM_RSA_KEY_LENGTH_MAX, tpm_rsa_key_parms->keyLength);
	    rc = TPM_BAD_KEY_PROPERTY;
	}
	
    }
    /* kgold - Support only 2 primes */
    if (rc == 0) {
	if (tpm_rsa_key_parms->numPrimes != 2) {
	    printf("TPM_KeyParms_CheckProperties: Error, numPrimes %u should be 2\n",
		   tpm_rsa_key_parms->numPrimes);
	    rc = TPM_BAD_KEY_PROPERTY;
	}
    }
    /* if FIPS */
    if ((rc == 0) && FIPS) {
	/* a.  If keyInfo -> keySize is less than 1024 return TPM_NOTFIPS */
	if (tpm_rsa_key_parms->keyLength < 1024) {
	    printf("TPM_KeyParms_CheckProperties: Error, Invalid FIPS key length %u\n",
		   tpm_rsa_key_parms->keyLength);
	    rc = TPM_NOTFIPS;
	}
	/* c.  If keyInfo -> keyUsage specifies TPM_KEY_LEGACY return TPM_NOTFIPS */
	else if (tpm_key_usage == TPM_KEY_LEGACY) {
	    printf("TPM_KeyParms_CheckProperties: Error, FIPS authDataUsage TPM_AUTH_NEVER\n");
	    rc = TPM_NOTFIPS;
	}
    }
    /* From Part 2 5.7.1 Mandatory Key Usage Schemes  and TPM_CreateWrapKey, TPM_LoadKey */
    if (rc == 0) {
	switch (tpm_key_usage) {
	  case TPM_KEY_UNINITIALIZED:
	    printf("TPM_KeyParms_CheckProperties: Error, keyUsage TPM_KEY_UNINITIALIZED\n");
	    rc = TPM_BAD_KEY_PROPERTY;
	    break;
	  case TPM_KEY_SIGNING:
	    if (tpm_key_parms->encScheme != TPM_ES_NONE) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Signing encScheme %04hx is not TPM_ES_NONE\n",
		       tpm_key_parms->encScheme);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
#ifdef TPM_V12
	    else if ((tpm_key_parms->sigScheme != TPM_SS_RSASSAPKCS1v15_SHA1) &&
		     (tpm_key_parms->sigScheme != TPM_SS_RSASSAPKCS1v15_DER) &&
		     (tpm_key_parms->sigScheme != TPM_SS_RSASSAPKCS1v15_INFO)) {
#else	/* TPM 1.1 */
	    else if (tpm_key_parms->sigScheme != TPM_SS_RSASSAPKCS1v15_SHA1) {

#endif	
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Signing sigScheme %04hx is not DER, SHA1, INFO\n",
		       tpm_key_parms->sigScheme);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    break;
	  case TPM_KEY_STORAGE:
	    if (tpm_key_parms->encScheme != TPM_ES_RSAESOAEP_SHA1_MGF1) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Storage encScheme %04hx is not TPM_ES_RSAESOAEP_SHA1_MGF1\n",
		       tpm_key_parms->encScheme);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else if (tpm_key_parms->sigScheme != TPM_SS_NONE) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Storage sigScheme %04hx is not TPM_SS_NONE\n",
		       tpm_key_parms->sigScheme);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else if (tpm_key_parms->algorithmID != TPM_ALG_RSA) { /*constant condition*/
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Storage algorithmID %08x is not TPM_ALG_RSA\n",
		       tpm_key_parms->algorithmID);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    /* interoperable TPM only supports 2048 */
	    else if (tpm_rsa_key_parms->keyLength < 2048) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Storage keyLength %d is less than 2048\n",
		       tpm_rsa_key_parms->keyLength);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else {
		rc = TPM_KeyParams_CheckDefaultExponent(&(tpm_rsa_key_parms->exponent));
	    }
	    break;
	  case TPM_KEY_IDENTITY:
	    if (tpm_key_parms->encScheme != TPM_ES_NONE) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Identity encScheme %04hx is not TPM_ES_NONE\n",
		       tpm_key_parms->encScheme);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else if (tpm_key_parms->sigScheme != TPM_SS_RSASSAPKCS1v15_SHA1) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Identity sigScheme %04hx is not %04x\n",
		       tpm_key_parms->sigScheme, TPM_SS_RSASSAPKCS1v15_SHA1);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else if (tpm_key_parms->algorithmID != TPM_ALG_RSA) { /*constant condition*/
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Identity algorithmID %08x is not TPM_ALG_RSA\n",
		       tpm_key_parms->algorithmID);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    /* interoperable TPM only supports 2048 */
	    else if (tpm_rsa_key_parms->keyLength < 2048) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Identity keyLength %d is less than 2048\n",
		       tpm_rsa_key_parms->keyLength);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else {
		rc = TPM_KeyParams_CheckDefaultExponent(&(tpm_rsa_key_parms->exponent));
	    }
	    break;
	  case TPM_KEY_AUTHCHANGE:
	    if (tpm_key_parms->encScheme != TPM_ES_RSAESOAEP_SHA1_MGF1) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Authchange encScheme %04hx is not TPM_ES_RSAESOAEP_SHA1_MGF1\n",
		       tpm_key_parms->encScheme);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else if (tpm_key_parms->sigScheme != TPM_SS_NONE) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Authchange sigScheme %04hx is not TPM_SS_NONE\n",
		       tpm_key_parms->sigScheme);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else if (tpm_rsa_key_parms->keyLength < 512) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Authchange keyLength %d is less than 512\n",
		       tpm_rsa_key_parms->keyLength);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    break;
	  case TPM_KEY_BIND:
	    if ((tpm_key_parms->encScheme != TPM_ES_RSAESOAEP_SHA1_MGF1) &&
		(tpm_key_parms->encScheme != TPM_ES_RSAESPKCSv15)) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Bind encScheme %04hx is not %04x or %04x\n",
		       tpm_key_parms->encScheme,
		       TPM_ES_RSAESOAEP_SHA1_MGF1, TPM_ES_RSAESPKCSv15);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else if (tpm_key_parms->sigScheme != TPM_SS_NONE) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Bind sigScheme %04hx is not TPM_SS_NONE\n",
		       tpm_key_parms->sigScheme);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    break;
	  case TPM_KEY_LEGACY:
	    if ((tpm_key_parms->encScheme != TPM_ES_RSAESOAEP_SHA1_MGF1) &&
		(tpm_key_parms->encScheme != TPM_ES_RSAESPKCSv15)) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Legacy encScheme %04hx is not %04x or %04x\n",
		       tpm_key_parms->encScheme,
		       TPM_ES_RSAESOAEP_SHA1_MGF1, TPM_ES_RSAESPKCSv15);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else if ((tpm_key_parms->sigScheme != TPM_SS_RSASSAPKCS1v15_SHA1) &&
		     (tpm_key_parms->sigScheme != TPM_SS_RSASSAPKCS1v15_DER)) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Legacy sigScheme %04hx is not %04x or %04x\n",
		       tpm_key_parms->sigScheme,
		       TPM_SS_RSASSAPKCS1v15_SHA1, TPM_SS_RSASSAPKCS1v15_DER);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    break;
	  case TPM_KEY_MIGRATE:
	    if (tpm_key_parms->encScheme != TPM_ES_RSAESOAEP_SHA1_MGF1) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Migrate encScheme %04hx is not TPM_ES_RSAESOAEP_SHA1_MGF1\n",
		       tpm_key_parms->encScheme);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else if (tpm_key_parms->sigScheme != TPM_SS_NONE) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Migrate sigScheme %04hx is not TPM_SS_NONE\n",
		       tpm_key_parms->sigScheme);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else if (tpm_key_parms->algorithmID != TPM_ALG_RSA) { /*constant condition*/
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Migrate algorithmID %08x is not TPM_ALG_RSA\n",
		       tpm_key_parms->algorithmID);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    /* interoperable TPM only supports 2048 */
	    else if (tpm_rsa_key_parms->keyLength < 2048) {
		printf("TPM_KeyParms_CheckProperties: Error, "
		       "Migrate keyLength %d is less than 2048\n",
		       tpm_rsa_key_parms->keyLength);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	    else {
		rc = TPM_KeyParams_CheckDefaultExponent(&(tpm_rsa_key_parms->exponent));
	    }
	    break;
	  default:
	    printf("TPM_KeyParms_CheckProperties: Error, Unknown keyUsage %04hx\n", tpm_key_usage);
	    rc = TPM_BAD_KEY_PROPERTY;
	    break;
	}
    }
    return rc; 
}

TPM_RESULT TPM_KeyParams_CheckDefaultExponent(TPM_SIZED_BUFFER *exponent)
{
    TPM_RESULT	rc = 0;
    uint32_t	i;
    
    if ((rc == 0) && (exponent->size != 0)) {	 /* 0 is the default */
	printf("  TPM_KeyParams_CheckDefaultExponent: exponent size %u\n", exponent->size);
	if (rc == 0) {
	    if (exponent->size < 3) {		 
		printf("TPM_KeyParams_CheckDefaultExponent: Error, exponent size is %u\n",
		       exponent->size);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	}
	if (rc == 0) {
	    for (i = 3 ; i < exponent->size ; i++) {
		if (exponent->buffer[i] != 0) {
		    printf("TPM_KeyParams_CheckDefaultExponent: Error, exponent[%u] is %02x\n",
			   i, exponent->buffer[i]);
		    rc = TPM_BAD_KEY_PROPERTY;
		}
	    }
	}
	if (rc == 0) {
	    if ((exponent->buffer[0] != tpm_default_rsa_exponent[0]) ||
		(exponent->buffer[1] != tpm_default_rsa_exponent[1]) ||
		(exponent->buffer[2] != tpm_default_rsa_exponent[2])) {
		printf("TPM_KeyParams_CheckDefaultExponent: Error, exponent is %02x %02x %02x\n",
		       exponent->buffer[2], exponent->buffer[1], exponent->buffer[0]);
		rc = TPM_BAD_KEY_PROPERTY;
	    }
	}
    }
    return rc; 
}

/*
  TPM_STORE_ASYMKEY
*/

void TPM_StoreAsymkey_Init(TPM_STORE_ASYMKEY *tpm_store_asymkey)
{
    printf(" TPM_StoreAsymkey_Init:\n");
    tpm_store_asymkey->payload = TPM_PT_ASYM;
    TPM_Secret_Init(tpm_store_asymkey->usageAuth);
    TPM_Secret_Init(tpm_store_asymkey->migrationAuth);
    TPM_Digest_Init(tpm_store_asymkey->pubDataDigest);
    TPM_StorePrivkey_Init(&(tpm_store_asymkey->privKey));
    return;
}

/* TPM_StoreAsymkey_Load() deserializes the TPM_STORE_ASYMKEY structure.

   The serialized structure contains the private factor p.  Normally, 'tpm_key_parms' and
   tpm_store_pubkey are not NULL and the private key d is derived from p and the public key n and
   exponent e.

   In some cases, a TPM_STORE_ASYMKEY is being manipulated without the rest of the TPM_KEY
   structure.  When 'tpm_key' is NULL, p is left intact, and the resulting structure cannot be used
   as a private key.
*/

TPM_RESULT TPM_StoreAsymkey_Load(TPM_STORE_ASYMKEY *tpm_store_asymkey,
				 TPM_BOOL isEK,
				 unsigned char **stream,	
				 uint32_t *stream_size,
				 TPM_KEY_PARMS *tpm_key_parms,
				 TPM_SIZED_BUFFER *pubKey)
{
    TPM_RESULT	rc = 0;

    printf(" TPM_StoreAsymkey_Load:\n");
    /* load payload */
    if ((rc == 0) && !isEK) {
	rc = TPM_Load8(&(tpm_store_asymkey->payload), stream, stream_size);
    }
    /* check payload value to ease debugging */
    if ((rc == 0) && !isEK) {
	if (
	    /* normal key */
	    (tpm_store_asymkey->payload != TPM_PT_ASYM) &&
	    /* TPM_CMK_CreateKey payload */
	    (tpm_store_asymkey->payload != TPM_PT_MIGRATE_RESTRICTED) &&
	    /* TPM_CMK_ConvertMigration payload */
	    (tpm_store_asymkey->payload != TPM_PT_MIGRATE_EXTERNAL)
	    ) {
	    printf("TPM_StoreAsymkey_Load: Error, invalid payload %02x\n",
		   tpm_store_asymkey->payload);
	    rc = TPM_INVALID_STRUCTURE;
	}
    }
    /* load usageAuth */
    if ((rc == 0) && !isEK) {
	rc = TPM_Secret_Load(tpm_store_asymkey->usageAuth, stream, stream_size);
    }
    /* load migrationAuth */
    if ((rc == 0) && !isEK) {
	rc = TPM_Secret_Load(tpm_store_asymkey->migrationAuth, stream, stream_size);
    }
    /* load pubDataDigest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_store_asymkey->pubDataDigest, stream, stream_size);
    }
    /* load privKey - actually prime factor p */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Load((&(tpm_store_asymkey->privKey.p_key)),
				  stream, stream_size);
    }
    /* convert prime factor p to the private key */
    if ((rc == 0) && (tpm_key_parms != NULL) && (pubKey != NULL)) {
	rc = TPM_StorePrivkey_Convert(tpm_store_asymkey,
				      tpm_key_parms, pubKey);
    }
    return rc;
}

#if 0
static TPM_RESULT TPM_StoreAsymkey_LoadTest(TPM_KEY *tpm_key)
{
    TPM_RESULT	rc = 0;
    int		irc;

    /* actual */
    unsigned char	*narr;
    unsigned char	*earr;
    unsigned char	*parr;		
    unsigned char	*qarr;
    unsigned char	*darr;

    uint32_t		nbytes;
    uint32_t		ebytes;
    uint32_t		pbytes;
    uint32_t		qbytes;
    uint32_t		dbytes;

    /* computed */
    unsigned char	*q1arr = NULL;
    unsigned char	*d1arr = NULL;

    uint32_t		q1bytes;
    uint32_t		d1bytes;

    printf(" TPM_StoreAsymkey_LoadTest:\n");
    /* actual data */
    if (rc == 0) {
	narr = tpm_key->pubKey.key;
	darr = tpm_key->tpm_store_asymkey->privKey.d_key;
	parr = tpm_key->tpm_store_asymkey->privKey.p_key;
	qarr = tpm_key->tpm_store_asymkey->privKey.q_key;

	nbytes = tpm_key->pubKey.keyLength;
	dbytes = tpm_key->tpm_store_asymkey->privKey.d_keyLength;
	pbytes = tpm_key->tpm_store_asymkey->privKey.p_keyLength;
	qbytes = tpm_key->tpm_store_asymkey->privKey.q_keyLength;
	
	rc = TPM_Key_GetPublicKey(&nbytes, &narr, tpm_key);
    }
    if (rc == 0) {
	rc = TPM_Key_GetExponent(&ebytes, &earr, tpm_key);
    }
    if (rc == 0) {
	rc = TPM_Key_GetPrimeFactorP(&pbytes, &parr, tpm_key);
    }
    /* computed data */
    if (rc == 0) {
	rc = TPM_RSAGetPrivateKey(&q1bytes, &q1arr,	/* freed @1 */
				  &d1bytes, &d1arr,	/* freed @2 */
				  nbytes, narr,
				  ebytes, earr,
				  pbytes, parr);
    }
    /* compare q */
    if (rc == 0) {
	if (qbytes != q1bytes) {
	    printf("TPM_StoreAsymkey_LoadTest: Error (fatal), qbytes %u q1bytes %u\n",
		   qbytes, q1bytes);
	    rc = TPM_FAIL;
	}
    }
    if (rc == 0) {
	irc = memcmp(qarr, q1arr, qbytes);
	if (irc != 0) {
	    printf("TPM_StoreAsymkey_LoadTest: Error (fatal), qarr mismatch\n");
	    rc = TPM_FAIL;
	}
    }
    /* compare d */
    if (rc == 0) {
	if (dbytes != d1bytes) {
	    printf("TPM_StoreAsymkey_LoadTest: Error (fatal), dbytes %u d1bytes %u\n",
		   dbytes, d1bytes);
	    rc = TPM_FAIL;
	}
    }
    if (rc == 0) {
	irc = memcmp(darr, d1arr, dbytes);
	if (irc != 0) {
	    printf("TPM_StoreAsymkey_LoadTest: Error (fatal), darr mismatch\n");
	    rc = TPM_FAIL;
	}
    }
    free(q1arr);	/* @1 */
    free(d1arr);	/* @2 */
    return rc;
}
#endif

TPM_RESULT TPM_StoreAsymkey_Store(TPM_STORE_BUFFER *sbuffer,
				  TPM_BOOL isEK,
				  const TPM_STORE_ASYMKEY *tpm_store_asymkey)
{
    TPM_RESULT	rc = 0;

    printf(" TPM_StoreAsymkey_Store:\n");
    /* store payload */
    if ((rc == 0) && !isEK) {
	rc = TPM_Sbuffer_Append(sbuffer, &(tpm_store_asymkey->payload), sizeof(TPM_PAYLOAD_TYPE));
    }
    /* store usageAuth */
    if ((rc == 0) && !isEK) {
	rc = TPM_Secret_Store(sbuffer, tpm_store_asymkey->usageAuth);
    }
    /* store migrationAuth */
    if ((rc == 0) && !isEK) {
	rc = TPM_Secret_Store(sbuffer, tpm_store_asymkey->migrationAuth);
    }
    /* store pubDataDigest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_store_asymkey->pubDataDigest);
    }
    /* store privKey */
    if (rc == 0) {
	rc = TPM_StorePrivkey_Store(sbuffer, &(tpm_store_asymkey->privKey));
    }
    return rc;
}

void TPM_StoreAsymkey_Delete(TPM_STORE_ASYMKEY *tpm_store_asymkey)
{
    printf(" TPM_StoreAsymkey_Delete:\n");
    if (tpm_store_asymkey != NULL) {
	TPM_Secret_Delete(tpm_store_asymkey->usageAuth);
	TPM_Secret_Delete(tpm_store_asymkey->migrationAuth);
	TPM_StorePrivkey_Delete(&(tpm_store_asymkey->privKey));
	TPM_StoreAsymkey_Init(tpm_store_asymkey);
    }
    return;
}

TPM_RESULT TPM_StoreAsymkey_GenerateEncData(TPM_SIZED_BUFFER *encData,
					    TPM_STORE_ASYMKEY *tpm_store_asymkey,
					    TPM_KEY *parent_key)
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	sbuffer;		/* TPM_STORE_ASYMKEY serialization */

    printf(" TPM_StoreAsymkey_GenerateEncData;\n");
    TPM_Sbuffer_Init(&sbuffer);			/* freed @1 */
    /* serialize the TPM_STORE_ASYMKEY member */
    if (rc == 0) {
	rc = TPM_StoreAsymkey_Store(&sbuffer, FALSE, tpm_store_asymkey);
    }
    if (rc == 0) {
	rc = TPM_RSAPublicEncryptSbuffer_Key(encData, &sbuffer, parent_key);
    }
    TPM_Sbuffer_Delete(&sbuffer);	/* @1 */
    return rc;
}

/* TPM_StoreAsymkey_GetPrimeFactorP() gets the prime factor p from the TPM_STORE_ASYMKEY
*/

TPM_RESULT TPM_StoreAsymkey_GetPrimeFactorP(uint32_t 		*pbytes,
					    unsigned char	**parr,
					    TPM_STORE_ASYMKEY	*tpm_store_asymkey)
{
    TPM_RESULT	rc = 0;
    
    printf(" TPM_StoreAsymkey_GetPrimeFactorP:\n");
    if (rc == 0) {
	*pbytes = tpm_store_asymkey->privKey.p_key.size;
	*parr = tpm_store_asymkey->privKey.p_key.buffer;
	TPM_PrintFour("  TPM_StoreAsymkey_GetPrimeFactorP:", *parr);
    }
    return rc;
}

/* TPM_StoreAsymkey_GetO1Size() calculates the destination o1 size for a TPM_STORE_ASYMKEY

   Used for creating a migration blob, TPM_STORE_ASYMKEY -> TPM_MIGRATE_ASYMKEY.
 */

void TPM_StoreAsymkey_GetO1Size(uint32_t		*o1_size,
				TPM_STORE_ASYMKEY	*tpm_store_asymkey)
{
    *o1_size = tpm_store_asymkey->privKey.p_key.size +	/* private key */
	       sizeof(uint32_t) -		/* private key length */
	       TPM_DIGEST_SIZE +		/* - k1 -> k2 TPM_MIGRATE_ASYMKEY -> partPrivKey */
	       sizeof(uint32_t) +		/* TPM_MIGRATE_ASYMKEY -> partPrivKeyLen */
	       sizeof(TPM_PAYLOAD_TYPE) +	/* TPM_MIGRATE_ASYMKEY -> payload */
	       TPM_SECRET_SIZE +		/* TPM_MIGRATE_ASYMKEY -> usageAuth */
	       TPM_DIGEST_SIZE +		/* TPM_MIGRATE_ASYMKEY -> pubDataDigest */
	       TPM_DIGEST_SIZE +		/* OAEP pHash */
	       TPM_DIGEST_SIZE +		/* OAEP seed */
	       1;				/* OAEP 0x01 byte */
    printf(" TPM_StoreAsymkey_GetO1Size: key size %u o1 size %u\n",
	   tpm_store_asymkey->privKey.p_key.size, *o1_size);
}

/* TPM_StoreAsymkey_CheckO1Size() verifies the destination o1_size against the source k1k2 array
   length

   This is a currently just a sanity check on the TPM_StoreAsymkey_GetO1Size() function.
*/

TPM_RESULT TPM_StoreAsymkey_CheckO1Size(uint32_t o1_size,
					uint32_t k1k2_length)
{
    TPM_RESULT rc = 0;
    
    /* sanity check the TPM_MIGRATE_ASYMKEY size against the requested o1 size */
    /* K1 K2 are the length and value of the private key, 4 + 128 bytes for a 2048-bit key */
    if (o1_size <
	(k1k2_length - TPM_DIGEST_SIZE + /* k1 k2, the first 20 bytes are used as the OAEP seed */
	 sizeof(TPM_PAYLOAD_TYPE) +	/* TPM_MIGRATE_ASYMKEY -> payload */
	 TPM_SECRET_SIZE +		/* TPM_MIGRATE_ASYMKEY -> usageAuth */
	 TPM_DIGEST_SIZE +		/* TPM_MIGRATE_ASYMKEY -> pubDataDigest */
	 sizeof(uint32_t) +		/* TPM_MIGRATE_ASYMKEY -> partPrivKeyLen */
	 TPM_DIGEST_SIZE +		/* OAEP pHash */
	 TPM_DIGEST_SIZE +				/* OAEP seed */
	 1)) {				/* OAEP 0x01 byte */
	printf("  TPM_StoreAsymkey_CheckO1Size: Error (fatal) k1k2_length %d too large for o1 %u\n",
	       k1k2_length, o1_size);
	rc = TPM_FAIL;
    }
    return rc;
}

/* TPM_StoreAsymkey_StoreO1() creates an OAEP encoded TPM_MIGRATE_ASYMKEY from a
   TPM_STORE_ASYMKEY.

   It does the common steps of constructing the TPM_MIGRATE_ASYMKEY, serializing it, and OAEP
   padding.
*/

TPM_RESULT TPM_StoreAsymkey_StoreO1(BYTE		*o1,
				    uint32_t		o1_size,
				    TPM_STORE_ASYMKEY	*tpm_store_asymkey,
				    TPM_DIGEST		pHash,
				    TPM_PAYLOAD_TYPE	payload_type,
				    TPM_SECRET		usageAuth)
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	k1k2_sbuffer;	/* serialization of TPM_STORE_ASYMKEY -> privKey -> key */
    const unsigned char *k1k2;		/* serialization results */
    uint32_t		k1k2_length;
    TPM_MIGRATE_ASYMKEY tpm_migrate_asymkey;
    TPM_STORE_BUFFER	tpm_migrate_asymkey_sbuffer;	/* serialized tpm_migrate_asymkey */
    const unsigned char *tpm_migrate_asymkey_buffer;	
    uint32_t		tpm_migrate_asymkey_length;
    
    printf(" TPM_StoreAsymkey_StoreO1:\n");
    TPM_Sbuffer_Init(&k1k2_sbuffer);			/* freed @1 */
    TPM_MigrateAsymkey_Init(&tpm_migrate_asymkey);	/* freed @2 */
    TPM_Sbuffer_Init(&tpm_migrate_asymkey_sbuffer);	/* freed @3 */

    /* NOTE Comments from TPM_CreateMigrationBlob rev 81 */
    /* a. Build two byte arrays, K1 and K2: */
    /* i. K1 = TPM_STORE_ASYMKEY.privKey[0..19] (TPM_STORE_ASYMKEY.privKey.keyLength + 16 bytes of
       TPM_STORE_ASYMKEY.privKey.key), sizeof(K1) = 20 */
    /* ii. K2 = TPM_STORE_ASYMKEY.privKey[20..131] (position 16-127 of
       TPM_STORE_ASYMKEY. privKey.key), sizeof(K2) = 112 */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(&k1k2_sbuffer, &(tpm_store_asymkey->privKey.p_key));
    }
    if (rc == 0) {
	TPM_Sbuffer_Get(&k1k2_sbuffer, &k1k2, &k1k2_length);
	/* sanity check the TPM_STORE_ASYMKEY -> privKey -> key size against the requested o1
	   size */
	rc = TPM_StoreAsymkey_CheckO1Size(o1_size, k1k2_length);
    }
    /* b. Build M1 a TPM_MIGRATE_ASYMKEY structure */
    /* i. TPM_MIGRATE_ASYMKEY.payload = TPM_PT_MIGRATE */
    /* ii. TPM_MIGRATE_ASYMKEY.usageAuth = TPM_STORE_ASYMKEY.usageAuth */
    /* iii. TPM_MIGRATE_ASYMKEY.pubDataDigest = TPM_STORE_ASYMKEY. pubDataDigest */
    /* iv. TPM_MIGRATE_ASYMKEY.partPrivKeyLen = 112 - 127. */
    /* v. TPM_MIGRATE_ASYMKEY.partPrivKey = K2 */
    if (rc == 0) {
	tpm_migrate_asymkey.payload = payload_type;
	TPM_Secret_Copy(tpm_migrate_asymkey.usageAuth, usageAuth);
	TPM_Digest_Copy(tpm_migrate_asymkey.pubDataDigest, tpm_store_asymkey->pubDataDigest);
	TPM_PrintFour("  TPM_StoreAsymkey_StoreO1: k1 -", k1k2);
	TPM_PrintFour("  TPM_StoreAsymkey_StoreO1: k2 -", k1k2 + TPM_DIGEST_SIZE);
	rc = TPM_SizedBuffer_Set(&(tpm_migrate_asymkey.partPrivKey),
				 k1k2_length - TPM_DIGEST_SIZE,	/* k2 length 112 for 2048 bit key */
				 k1k2 + TPM_DIGEST_SIZE);	/* k2 */
    }
    /* c. Create o1 (which SHALL be 198 bytes for a 2048 bit RSA key) by performing the OAEP
       encoding of m using OAEP parameters of */
    /* i. m = M1 the TPM_MIGRATE_ASYMKEY structure */
    /* ii. pHash = d1->migrationAuth */
    /* iii. seed = s1 = K1 */
    if (rc == 0) {
	/* serialize TPM_MIGRATE_ASYMKEY m */
	rc = TPM_MigrateAsymkey_Store(&tpm_migrate_asymkey_sbuffer, &tpm_migrate_asymkey);
    }
    if (rc == 0) {
	/* get the serialization result */
	TPM_Sbuffer_Get(&tpm_migrate_asymkey_sbuffer,
			&tpm_migrate_asymkey_buffer, &tpm_migrate_asymkey_length);
	TPM_PrintFour("  TPM_StoreAsymkey_StoreO1: pHash -", pHash);
	rc = TPM_RSA_padding_add_PKCS1_OAEP(o1,				/* output */
					    o1_size,
					    tpm_migrate_asymkey_buffer, /* message */
					    tpm_migrate_asymkey_length,
					    pHash, 
					    k1k2);			/* k1, seed */
	TPM_PrintFour("  TPM_StoreAsymkey_StoreO1: o1 -", o1);
    }
    TPM_Sbuffer_Delete(&k1k2_sbuffer);			/* @1 */
    TPM_MigrateAsymkey_Delete(&tpm_migrate_asymkey);	/* @2 */
    TPM_Sbuffer_Delete(&tpm_migrate_asymkey_sbuffer);	/* @3 */
    return rc;
}

/* TPM_StoreAsymkey_LoadO1() extracts TPM_STORE_ASYMKEY from the OAEP encoded TPM_MIGRATE_ASYMKEY.

   It does the common steps OAEP depadding, deserializing the TPM_MIGRATE_ASYMKEY, and
   reconstructing the TPM_STORE_ASYMKEY.

   It sets these, which may or may not be correct at a higher level
   
   TPM_STORE_ASYMKEY -> payload	      = TPM_MIGRATE_ASYMKEY -> payload
   TPM_STORE_ASYMKEY -> usageAuth     = TPM_MIGRATE_ASYMKEY -> usageAuth
   TPM_STORE_ASYMKEY -> migrationAuth = pHash
   TPM_STORE_ASYMKEY -> pubDataDigest = TPM_MIGRATE_ASYMKEY -> pubDataDigest
   TPM_STORE_ASYMKEY -> privKey	      = seed + TPM_MIGRATE_ASYMKEY -> partPrivKey
*/

TPM_RESULT TPM_StoreAsymkey_LoadO1(TPM_STORE_ASYMKEY	*tpm_store_asymkey,	/* output */
				   BYTE			*o1,			/* input */
				   uint32_t		o1_size)		/* input */
{
    TPM_RESULT			rc = 0;
    BYTE			*tpm_migrate_asymkey_buffer;
    uint32_t			tpm_migrate_asymkey_length;
    TPM_DIGEST			seed;
    TPM_DIGEST			pHash;
    unsigned char		*stream;	/* for deserializing structures */
    uint32_t			stream_size;
    TPM_MIGRATE_ASYMKEY		tpm_migrate_asymkey;
    TPM_STORE_BUFFER		k1k2_sbuffer;
    const unsigned char		*k1k2_buffer;
    uint32_t			k1k2_length;
    
    printf(" TPM_StoreAsymkey_LoadO1:\n");
    TPM_MigrateAsymkey_Init(&tpm_migrate_asymkey);	/* freed @1 */
    TPM_Sbuffer_Init(&k1k2_sbuffer);			/* freed @2 */
    tpm_migrate_asymkey_buffer = NULL;			/* freed @3 */
    /* allocate memory for TPM_MIGRATE_ASYMKEY after removing OAEP pad from o1 */
    if (rc == 0) {
	rc = TPM_Malloc(&tpm_migrate_asymkey_buffer, o1_size);
    }
    if (rc == 0) {
	TPM_PrintFour("  TPM_StoreAsymkey_LoadO1: o1 -", o1);
	/* 5. Create m1, seed and pHash by OAEP decoding o1 */
	printf("  TPM_StoreAsymkey_LoadO1: Depadding\n");
	rc = TPM_RSA_padding_check_PKCS1_OAEP(tpm_migrate_asymkey_buffer,	/* out: to */
					      &tpm_migrate_asymkey_length,	/* out: to length */
					      o1_size,				/* to size */
					      o1, o1_size,		/* from, from length  */
					      pHash,
					      seed);	
	TPM_PrintFour("  TPM_StoreAsymkey_LoadO1: tpm_migrate_asymkey_buffer -",
		      tpm_migrate_asymkey_buffer);
	printf("  TPM_StoreAsymkey_LoadO1: tpm_migrate_asymkey_length %u\n",
	       tpm_migrate_asymkey_length);
	TPM_PrintFour("  TPM_StoreAsymkey_LoadO1: - pHash", pHash);
	TPM_PrintFour("  TPM_StoreAsymkey_LoadO1: - seed", seed);
    }
    /* deserialize the buffer back to a TPM_MIGRATE_ASYMKEY */
    if (rc == 0) {
	stream = tpm_migrate_asymkey_buffer;
	stream_size = tpm_migrate_asymkey_length;
	rc = TPM_MigrateAsymkey_Load(&tpm_migrate_asymkey, &stream, &stream_size);
	printf("  TPM_StoreAsymkey_LoadO1: partPrivKey length %u\n",
	       tpm_migrate_asymkey.partPrivKey.size);
	TPM_PrintFourLimit("  TPM_StoreAsymkey_LoadO1: partPrivKey -",
		      tpm_migrate_asymkey.partPrivKey.buffer,
		      tpm_migrate_asymkey.partPrivKey.size);
    }
    /* create k1k2 by combining seed (k1) and TPM_MIGRATE_ASYMKEY.partPrivKey (k2) field */
    if (rc == 0) {
	rc = TPM_Digest_Store(&k1k2_sbuffer, seed);
    }
    if (rc == 0) {
	rc = TPM_Sbuffer_Append(&k1k2_sbuffer,
				tpm_migrate_asymkey.partPrivKey.buffer,
				tpm_migrate_asymkey.partPrivKey.size);
    }
    /* assemble the TPM_STORE_ASYMKEY structure */
    if (rc == 0) {
	tpm_store_asymkey->payload = tpm_migrate_asymkey.payload;
	TPM_Digest_Copy(tpm_store_asymkey->usageAuth, tpm_migrate_asymkey.usageAuth);
	TPM_Digest_Copy(tpm_store_asymkey->migrationAuth, pHash);
	TPM_Digest_Copy(tpm_store_asymkey->pubDataDigest, tpm_migrate_asymkey.pubDataDigest);
	TPM_Sbuffer_Get(&k1k2_sbuffer, &k1k2_buffer, &k1k2_length);
	printf("  TPM_StoreAsymkey_LoadO1: k1k2 length %u\n", k1k2_length);
	TPM_PrintFourLimit("  TPM_StoreAsymkey_LoadO1: k1k2", k1k2_buffer, k1k2_length);
	rc = TPM_SizedBuffer_Load(&(tpm_store_asymkey->privKey.p_key),
				  (unsigned char **)&k1k2_buffer, &k1k2_length);
    }
    TPM_MigrateAsymkey_Delete(&tpm_migrate_asymkey);	/* @1 */
    TPM_Sbuffer_Delete(&k1k2_sbuffer);			/* @2 */
    free(tpm_migrate_asymkey_buffer);			/* @3 */
    return rc;
}


/*
  TPM_MIGRATE_ASYMKEY
*/

/* TPM_MigrateAsymkey_Init()

   sets members to default values
   sets all pointers to NULL and sizes to 0
   always succeeds - no return code
*/

void TPM_MigrateAsymkey_Init(TPM_MIGRATE_ASYMKEY *tpm_migrate_asymkey)
{
    printf(" TPM_MigrateAsymkey_Init:\n");
    tpm_migrate_asymkey->payload = TPM_PT_MIGRATE;
    TPM_Secret_Init(tpm_migrate_asymkey->usageAuth);
    TPM_Digest_Init(tpm_migrate_asymkey->pubDataDigest);
    TPM_SizedBuffer_Init(&(tpm_migrate_asymkey->partPrivKey));
    return;
}

/* TPM_MigrateAsymkey_Load()

   deserialize the structure from a 'stream'
   'stream_size' is checked for sufficient data
   returns 0 or error codes
   
   Before use, call TPM_MigrateAsymkey_Init()
   After use, call TPM_MigrateAsymkey_Delete() to free memory
*/

TPM_RESULT TPM_MigrateAsymkey_Load(TPM_MIGRATE_ASYMKEY *tpm_migrate_asymkey,
				   unsigned char **stream,
				   uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_MigrateAsymkey_Load:\n");
    /* load payload */
    if (rc == 0) {
	rc = TPM_Load8(&(tpm_migrate_asymkey->payload), stream, stream_size);
    }
    /* check payload value to ease debugging */
    if (rc == 0) {
	if ((tpm_migrate_asymkey->payload != TPM_PT_MIGRATE) &&
	    (tpm_migrate_asymkey->payload != TPM_PT_MAINT) &&
	    (tpm_migrate_asymkey->payload != TPM_PT_CMK_MIGRATE)) {
	    printf("TPM_MigrateAsymkey_Load: Error illegal payload %02x\n",
		   tpm_migrate_asymkey->payload);
	    rc = TPM_INVALID_STRUCTURE;
	}
    }
    /* load usageAuth */
    if (rc == 0) {
	rc = TPM_Secret_Load(tpm_migrate_asymkey->usageAuth, stream, stream_size);
    }
    /* load pubDataDigest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_migrate_asymkey->pubDataDigest, stream, stream_size);
    }
    /* load partPrivKey */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Load(&(tpm_migrate_asymkey->partPrivKey), stream, stream_size);
    }
    return rc;
}

/* TPM_MigrateAsymkey_Store()
   
   serialize the structure to a stream contained in 'sbuffer'
   returns 0 or error codes
*/

TPM_RESULT TPM_MigrateAsymkey_Store(TPM_STORE_BUFFER *sbuffer,
				    const TPM_MIGRATE_ASYMKEY *tpm_migrate_asymkey)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_MigrateAsymkey_Store:\n");
    /* store payload */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append(sbuffer, &(tpm_migrate_asymkey->payload), sizeof(TPM_PAYLOAD_TYPE));
    }
    /* store usageAuth */
    if (rc == 0) {
	rc = TPM_Secret_Store(sbuffer, tpm_migrate_asymkey->usageAuth);
    }
    /* store pubDataDigest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_migrate_asymkey->pubDataDigest);
    }
    /* store partPrivKey */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_migrate_asymkey->partPrivKey));
    }
    return rc;
}

/* TPM_MigrateAsymkey_Delete()

   No-OP if the parameter is NULL, else:
   frees memory allocated for the object
   sets pointers to NULL
   calls TPM_MigrateAsymkey_Init to set members back to default values
   The object itself is not freed
*/   

void TPM_MigrateAsymkey_Delete(TPM_MIGRATE_ASYMKEY *tpm_migrate_asymkey)
{
    printf(" TPM_MigrateAsymkey_Delete:\n");
    if (tpm_migrate_asymkey != NULL) {
	TPM_Secret_Delete(tpm_migrate_asymkey->usageAuth);
	TPM_SizedBuffer_Zero(&(tpm_migrate_asymkey->partPrivKey));
	TPM_SizedBuffer_Delete(&(tpm_migrate_asymkey->partPrivKey));
	TPM_MigrateAsymkey_Init(tpm_migrate_asymkey);
    }
    return;
}

/*
  TPM_STORE_PRIVKEY
*/

void TPM_StorePrivkey_Init(TPM_STORE_PRIVKEY *tpm_store_privkey)
{
    printf(" TPM_StorePrivkey_Init:\n");
    TPM_SizedBuffer_Init(&(tpm_store_privkey->d_key));
    TPM_SizedBuffer_Init(&(tpm_store_privkey->p_key));
    TPM_SizedBuffer_Init(&(tpm_store_privkey->q_key));
    return;
}

/* TPM_StorePrivkey_Convert() sets the prime factor q and private key d based on the prime factor p
   and the public key and exponent.
*/

TPM_RESULT TPM_StorePrivkey_Convert(TPM_STORE_ASYMKEY *tpm_store_asymkey,	/* I/O result */
				    TPM_KEY_PARMS *tpm_key_parms,	/* to get exponent */
				    TPM_SIZED_BUFFER *pubKey)		/* to get public key */
{
    TPM_RESULT	rc = 0;
    /* computed data */
    unsigned char	*narr;
    unsigned char	*earr;
    unsigned char	*parr;		
    unsigned char	*qarr = NULL;
    unsigned char	*darr = NULL;
    uint32_t		nbytes;
    uint32_t		ebytes;
    uint32_t		pbytes;
    uint32_t		qbytes;
    uint32_t		dbytes;

    
    printf(" TPM_StorePrivkey_Convert:\n");
    if (rc == 0) {
	TPM_PrintFour("  TPM_StorePrivkey_Convert: p",	tpm_store_asymkey->privKey.p_key.buffer);
	nbytes = pubKey->size;
	narr = pubKey->buffer;
	rc = TPM_KeyParms_GetExponent(&ebytes, &earr, tpm_key_parms);
    }
    if (rc == 0) {
	rc = TPM_StoreAsymkey_GetPrimeFactorP(&pbytes, &parr, tpm_store_asymkey);
    }
    if (rc == 0) {
	rc = TPM_RSAGetPrivateKey(&qbytes, &qarr,	/* freed @1 */
				  &dbytes, &darr,	/* freed @2 */
				  nbytes, narr,
				  ebytes, earr,
				  pbytes, parr);
    }
    if (rc == 0) {
	TPM_PrintFour("  TPM_StorePrivkey_Convert: q", qarr);
	TPM_PrintFour("  TPM_StorePrivkey_Convert: d", darr);
	rc = TPM_SizedBuffer_Set((&(tpm_store_asymkey->privKey.q_key)), qbytes, qarr);
    }
    if (rc == 0) {
	rc = TPM_SizedBuffer_Set((&(tpm_store_asymkey->privKey.d_key)), dbytes, darr);
    }
    free(qarr); /* @1 */
    free(darr); /* @2 */
    return rc;
}

/* TPM_StorePrivkey_Store serializes a TPM_STORE_PRIVKEY structure, appending results to 'sbuffer'

   Only the prime factor p is stored.  The other prime factor q and the private key d are
   recalculated after a load.
 */

TPM_RESULT TPM_StorePrivkey_Store(TPM_STORE_BUFFER *sbuffer,
				  const TPM_STORE_PRIVKEY *tpm_store_privkey)
{
    TPM_RESULT	rc = 0;

    printf(" TPM_StorePrivkey_Store:\n");
    if (rc == 0) {
	TPM_PrintFour("  TPM_StorePrivkey_Store: p",  tpm_store_privkey->p_key.buffer);
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_store_privkey->p_key));
    }
    return rc;
}

void TPM_StorePrivkey_Delete(TPM_STORE_PRIVKEY *tpm_store_privkey)
{
    printf(" TPM_StorePrivkey_Delete:\n");
    if (tpm_store_privkey != NULL) {
	TPM_SizedBuffer_Zero(&(tpm_store_privkey->d_key));
	TPM_SizedBuffer_Zero(&(tpm_store_privkey->p_key));
	TPM_SizedBuffer_Zero(&(tpm_store_privkey->q_key));
	
	TPM_SizedBuffer_Delete(&(tpm_store_privkey->d_key));
	TPM_SizedBuffer_Delete(&(tpm_store_privkey->p_key));
	TPM_SizedBuffer_Delete(&(tpm_store_privkey->q_key));
	TPM_StorePrivkey_Init(tpm_store_privkey);
    }
    return;
}

/*
  TPM_PUBKEY
*/

void TPM_Pubkey_Init(TPM_PUBKEY *tpm_pubkey)
{
    printf(" TPM_Pubkey_Init:\n");
    TPM_KeyParms_Init(&(tpm_pubkey->algorithmParms));
    TPM_SizedBuffer_Init(&(tpm_pubkey->pubKey));
    return;
}

TPM_RESULT TPM_Pubkey_Load(TPM_PUBKEY *tpm_pubkey,	/* result */
			   unsigned char **stream,	/* pointer to next parameter */
			   uint32_t *stream_size)		/* stream size left */
{
    TPM_RESULT	rc = 0;

    printf(" TPM_Pubkey_Load:\n");
    /* load algorithmParms */
    if (rc == 0) {
	rc = TPM_KeyParms_Load(&(tpm_pubkey->algorithmParms), stream, stream_size);
    }
    /* load pubKey */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Load(&(tpm_pubkey->pubKey), stream, stream_size);
    }
    return rc;
}

/* TPM_Pubkey_Store serializes a TPM_PUBKEY structure, appending results to 'sbuffer'
*/

TPM_RESULT TPM_Pubkey_Store(TPM_STORE_BUFFER *sbuffer,
			    TPM_PUBKEY *tpm_pubkey)
{
    TPM_RESULT	rc = 0;

    printf(" TPM_Pubkey_Store:\n");
    if (rc == 0) {
	rc = TPM_KeyParms_Store(sbuffer, &(tpm_pubkey->algorithmParms));
    }
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_pubkey->pubKey));
    }
    return rc;
}

void TPM_Pubkey_Delete(TPM_PUBKEY *tpm_pubkey)
{
    printf(" TPM_Pubkey_Delete:\n");
    if (tpm_pubkey != NULL) {
	TPM_KeyParms_Delete(&(tpm_pubkey->algorithmParms));
	TPM_SizedBuffer_Delete(&(tpm_pubkey->pubKey));
	TPM_Pubkey_Init(tpm_pubkey);
    }
    return;
}

TPM_RESULT TPM_Pubkey_Set(TPM_PUBKEY *tpm_pubkey,
			  TPM_KEY *tpm_key)
{
    TPM_RESULT	rc = 0;
    
    printf(" TPM_Pubkey_Set:\n");
    if (rc == 0) {
	/* add TPM_KEY_PARMS algorithmParms */
	rc = TPM_KeyParms_Copy(&(tpm_pubkey->algorithmParms),
			       &(tpm_key->algorithmParms));
    }
    if (rc == 0) {
	/* add TPM_SIZED_BUFFER pubKey */
	rc = TPM_SizedBuffer_Copy(&(tpm_pubkey->pubKey),
				  &(tpm_key->pubKey));
    }				
    return rc;
}

TPM_RESULT TPM_Pubkey_Copy(TPM_PUBKEY *dest_tpm_pubkey,
			   TPM_PUBKEY *src_tpm_pubkey)
{
    TPM_RESULT	rc = 0;
    
    printf(" TPM_Pubkey_Copy:\n");
    /* copy TPM_KEY_PARMS algorithmParms */
    if (rc == 0) {
	rc = TPM_KeyParms_Copy(&(dest_tpm_pubkey->algorithmParms),
			       &(src_tpm_pubkey->algorithmParms));
    }
    /* copy TPM_SIZED_BUFFER pubKey */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Copy(&(dest_tpm_pubkey->pubKey),
				  &(src_tpm_pubkey->pubKey));
    }				
    return rc;
   
}

/* TPM_Pubkey_GetExponent() gets the exponent key from the TPM_RSA_KEY_PARMS contained in a
   TPM_PUBKEY
*/

TPM_RESULT TPM_Pubkey_GetExponent(uint32_t	*ebytes,
				  unsigned char **earr,
				  TPM_PUBKEY	*tpm_pubkey)
{
    TPM_RESULT		rc = 0;
    
    printf(" TPM_Pubkey_GetExponent:\n");
    if (rc == 0) {
	rc = TPM_KeyParms_GetExponent(ebytes, earr, &(tpm_pubkey->algorithmParms));
    }
    return rc;
}

/* TPM_Pubkey_GetPublicKey() gets the public key from the TPM_PUBKEY
 */

TPM_RESULT TPM_Pubkey_GetPublicKey(uint32_t		*nbytes,
				   unsigned char	**narr,
				   TPM_PUBKEY		*tpm_pubkey)
{
    TPM_RESULT	rc = 0;
    
    printf(" TPM_Pubkey_GetPublicKey:\n");
    if (rc == 0) {
	*nbytes = tpm_pubkey->pubKey.size;
	*narr = tpm_pubkey->pubKey.buffer;
    }
    return rc;
}

/*
  TPM_RSA_KEY_PARMS
*/
  

/* Allocates and loads a TPM_RSA_KEY_PARMS structure

   Must be delete'd and freed by the caller.
*/

void TPM_RSAKeyParms_Init(TPM_RSA_KEY_PARMS *tpm_rsa_key_parms)
{
    printf(" TPM_RSAKeyParms_Init:\n");
    tpm_rsa_key_parms->keyLength = 0;
    tpm_rsa_key_parms->numPrimes = 0;
    TPM_SizedBuffer_Init(&(tpm_rsa_key_parms->exponent));
    return;
}

/* TPM_RSAKeyParms_Load() sets members from stream, and shifts the stream past the bytes consumed.

   Must call TPM_RSAKeyParms_Delete() to free
*/

TPM_RESULT TPM_RSAKeyParms_Load(TPM_RSA_KEY_PARMS *tpm_rsa_key_parms,	/* result */
				unsigned char **stream,		/* pointer to next parameter */ 
				uint32_t *stream_size)		/* stream size left */
{
    TPM_RESULT	rc = 0;

    printf(" TPM_RSAKeyParms_Load:\n");
    /* load keyLength */
    if (rc == 0) {
	rc = TPM_Load32(&(tpm_rsa_key_parms->keyLength), stream, stream_size);
    }
    /* load numPrimes */
    if (rc == 0) {
	rc = TPM_Load32(&(tpm_rsa_key_parms->numPrimes), stream, stream_size);
    }
    /* load exponent */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Load(&(tpm_rsa_key_parms->exponent), stream, stream_size); 
    }
    return rc;
}

/* TPM_RSAKeyParms_Store serializes a TPM_RSA_KEY_PARMS structure, appending results to 'sbuffer'
*/

TPM_RESULT TPM_RSAKeyParms_Store(TPM_STORE_BUFFER *sbuffer,
				 const TPM_RSA_KEY_PARMS *tpm_rsa_key_parms)
{
    TPM_RESULT	rc = 0;
    
    printf(" TPM_RSAKeyParms_Store:\n");
    /* store keyLength */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append32(sbuffer, tpm_rsa_key_parms->keyLength); 
    }
    /* store numPrimes */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append32(sbuffer, tpm_rsa_key_parms->numPrimes); 
    }
    /* store exponent */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_rsa_key_parms->exponent)); 
    }
    return rc;
}

/* TPM_RSAKeyParms_Delete frees any member allocated memory

   If 'tpm_rsa_key_parms' is NULL, this is a no-op.
 */

void TPM_RSAKeyParms_Delete(TPM_RSA_KEY_PARMS *tpm_rsa_key_parms)
{
    printf(" TPM_RSAKeyParms_Delete:\n");
    if (tpm_rsa_key_parms != NULL) {
	TPM_SizedBuffer_Delete(&(tpm_rsa_key_parms->exponent));
	TPM_RSAKeyParms_Init(tpm_rsa_key_parms);
    }
    return;
}

/* TPM_RSAKeyParms_Copy() does a copy of the source to the destination.

   The destination must be initialized first.
*/

TPM_RESULT TPM_RSAKeyParms_Copy(TPM_RSA_KEY_PARMS *tpm_rsa_key_parms_dest,
				TPM_RSA_KEY_PARMS *tpm_rsa_key_parms_src)
{
    TPM_RESULT rc = 0;
    
    printf(" TPM_RSAKeyParms_Copy:\n");
    if (rc == 0) {
	tpm_rsa_key_parms_dest->keyLength = tpm_rsa_key_parms_src->keyLength;
	tpm_rsa_key_parms_dest->numPrimes = tpm_rsa_key_parms_src->numPrimes;
	rc = TPM_SizedBuffer_Copy(&(tpm_rsa_key_parms_dest->exponent),
				  &(tpm_rsa_key_parms_src->exponent));
    }
    return rc;
}

/* TPM_RSAKeyParms_New() allocates memory for a TPM_RSA_KEY_PARMS and initializes the structure */

TPM_RESULT TPM_RSAKeyParms_New(TPM_RSA_KEY_PARMS **tpm_rsa_key_parms)
{
    TPM_RESULT rc = 0;

    printf(" TPM_RSAKeyParms_New:\n");
    if (rc == 0) {
	rc = TPM_Malloc((unsigned char **)tpm_rsa_key_parms, sizeof(TPM_RSA_KEY_PARMS));
    }	 
    if (rc == 0) {
	TPM_RSAKeyParms_Init(*tpm_rsa_key_parms);
    }	 
    return rc;
}

/* TPM_RSAKeyParms_GetExponent() gets the exponent array and size from tpm_rsa_key_parms.

   If the structure exponent.size is zero, the default RSA exponent is returned.
*/

TPM_RESULT TPM_RSAKeyParms_GetExponent(uint32_t		*ebytes,
				       unsigned char	**earr,
				       TPM_RSA_KEY_PARMS *tpm_rsa_key_parms)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_RSAKeyParms_GetExponent:\n");
    if (tpm_rsa_key_parms->exponent.size != 0) {
	*ebytes = tpm_rsa_key_parms->exponent.size;
	*earr = tpm_rsa_key_parms->exponent.buffer;
    }
    else {
	*ebytes = 3;
	*earr = tpm_default_rsa_exponent;
    }
    return rc;
}

/*
  A Key Handle Entry
*/

/* TPM_KeyHandleEntry_Init() removes an entry from the list.  It DOES NOT delete the
   TPM_KEY object. */

void TPM_KeyHandleEntry_Init(TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entry)
{
    tpm_key_handle_entry->handle = 0;
    tpm_key_handle_entry->key = NULL;
    tpm_key_handle_entry->parentPCRStatus = TRUE;
    tpm_key_handle_entry->keyControl = 0;
    return;
}

/* TPM_KeyHandleEntry_Load()

   deserialize the structure from a 'stream'
   'stream_size' is checked for sufficient data
   returns 0 or error codes
   
   Before use, call TPM_KeyHandleEntry_Init()
   After use, call TPM_KeyHandleEntry_Delete() to free memory
*/

TPM_RESULT TPM_KeyHandleEntry_Load(TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entry,
				   unsigned char **stream,
				   uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_KeyHandleEntry_Load:\n");
    /* load handle */
    if (rc == 0) {
	rc = TPM_Load32(&(tpm_key_handle_entry->handle), stream, stream_size); 
    }
    /* malloc space for the key member */
    if (rc == 0) {
	rc = TPM_Malloc((unsigned char **)&(tpm_key_handle_entry->key), sizeof(TPM_KEY));
    }
    /* load key */
    if (rc == 0) {
	TPM_Key_Init(tpm_key_handle_entry->key);
	rc = TPM_Key_LoadClear(tpm_key_handle_entry->key,
			       FALSE,			/* not EK */
			       stream, stream_size);
    }
    /* load parentPCRStatus */
    if (rc == 0) {
	rc = TPM_LoadBool(&(tpm_key_handle_entry->parentPCRStatus), stream, stream_size); 
    }
    /* load keyControl */
    if (rc == 0) {
	rc = TPM_Load32(&(tpm_key_handle_entry->keyControl), stream, stream_size); 
    }
    return rc;
}

/* TPM_KeyHandleEntry_Store()
   
   serialize the structure to a stream contained in 'sbuffer'
   returns 0 or error codes
*/

TPM_RESULT TPM_KeyHandleEntry_Store(TPM_STORE_BUFFER *sbuffer,
				    const TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entry)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_KeyHandleEntry_Store:\n");
    /* store handle */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append32(sbuffer, tpm_key_handle_entry->handle); 
    }
    /* store key with private data appended in clear text */
    if (rc == 0) {
	rc = TPM_Key_StoreClear(sbuffer,
				FALSE,		/* not EK */
				tpm_key_handle_entry->key);
    }
    /* store parentPCRStatus */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append(sbuffer,
				&(tpm_key_handle_entry->parentPCRStatus), sizeof(TPM_BOOL)); 
    }
    /* store keyControl */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append32(sbuffer, tpm_key_handle_entry->keyControl); 
    }
    return rc;
}

/* TPM_KeyHandleEntry_Delete() deletes an entry from the list, deletes the TPM_KEY object, and
   free's the TPM_KEY.
*/

void TPM_KeyHandleEntry_Delete(TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entry)
{
    if (tpm_key_handle_entry != NULL) {
	if (tpm_key_handle_entry->handle != 0) {
	    printf(" TPM_KeyHandleEntry_Delete: Deleting %08x\n", tpm_key_handle_entry->handle);
	    TPM_Key_Delete(tpm_key_handle_entry->key);
	    free(tpm_key_handle_entry->key);
	}
	TPM_KeyHandleEntry_Init(tpm_key_handle_entry);
    }
    return;
}

/* TPM_KeyHandleEntry_FlushSpecific() flushes a key handle according to the rules of
   TPM_FlushSpecific()
*/

TPM_RESULT TPM_KeyHandleEntry_FlushSpecific(tpm_state_t *tpm_state,
					    TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entry)
{
    TPM_RESULT		rc = 0;
    TPM_AUTHHANDLE	authHandle = 0;		/* dummy parameter */
    TPM_BOOL		continueAuthSession;	/* dummy parameter */
    
    printf(" TPM_KeyHandleEntry_FlushSpecific:\n");
    if (rc == 0) {
	/* Internal error, should never happen */
	if (tpm_key_handle_entry->key == NULL) {
	    printf("TPM_KeyHandleEntry_FlushSpecific: Error (fatal), key is NULL\n");
	    rc = TPM_FAIL;
	}
    }
    /* terminate OSAP and DSAP sessions associated with the key */
    if (rc == 0) {
	/* The dummy parameters are not used.  The session, if any, associated with this function
	   is handled elsewhere. */
	TPM_AuthSessions_TerminateEntity(&continueAuthSession,
					 authHandle,
					 tpm_state->tpm_stclear_data.authSessions,
					 TPM_ET_KEYHANDLE,		/* TPM_ENTITY_TYPE */
					 &(tpm_key_handle_entry->key->
					   tpm_store_asymkey->pubDataDigest)); /* entityDigest */
	printf(" TPM_KeyHandleEntry_FlushSpecific: Flushing key handle %08x\n",
	       tpm_key_handle_entry->handle);
	/* free the TPM_KEY resources, free the key itself, and remove entry from the key handle
	   entries list */
	TPM_KeyHandleEntry_Delete(tpm_key_handle_entry);
    }
    return rc;
}

/*
  Key Handle Entries
*/

/* TPM_KeyHandleEntries_Init() initializes the fixed TPM_KEY_HANDLE_ENTRY array.  All entries are
   emptied.  The keys are not deleted.
*/

void TPM_KeyHandleEntries_Init(TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries)
{
    size_t i;
    
    printf(" TPM_KeyHandleEntries_Init:\n");
    for (i = 0 ; i < TPM_KEY_HANDLES ; i++) {
	TPM_KeyHandleEntry_Init(&(tpm_key_handle_entries[i]));
    }
    return;
}

/* TPM_KeyHandleEntries_Delete() deletes and freed all TPM_KEY's stored in entries, and the entry

*/

void TPM_KeyHandleEntries_Delete(TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries)
{
    size_t i;
    
    printf(" TPM_KeyHandleEntries_Delete:\n");
    for (i = 0 ; i < TPM_KEY_HANDLES ; i++) {
	TPM_KeyHandleEntry_Delete(&(tpm_key_handle_entries[i]));
    }
    return;
}

/* TPM_KeyHandleEntries_Load() loads the key handle entries from a stream created by
   TPM_KeyHandleEntries_Store()

   The two functions must be kept in sync.
*/

TPM_RESULT TPM_KeyHandleEntries_Load(tpm_state_t *tpm_state,
				     unsigned char **stream,
				     uint32_t *stream_size)
{
    TPM_RESULT			rc = 0;
    uint32_t			keyCount = 0;			/* keys to be saved */
    size_t			i;
    TPM_KEY_HANDLE_ENTRY	tpm_key_handle_entry;

    /* check format tag */
    /* In the future, if multiple formats are supported, this check will be replaced by a 'switch'
       on the tag */
    if (rc == 0) {
	rc = TPM_CheckTag(TPM_TAG_KEY_HANDLE_ENTRIES_V1, stream, stream_size);
    }
    /* get the count of keys in the stream */
    if (rc == 0) {
	rc = TPM_Load32(&keyCount, stream, stream_size);
	printf("  TPM_KeyHandleEntries_Load: %u keys to be loaded\n", keyCount);
    }
    /* sanity check that keyCount not greater than key slots */
    if (rc == 0) {
	if (keyCount > TPM_KEY_HANDLES) {
	    printf("TPM_KeyHandleEntries_Load: Error (fatal)"
		   " key handles in stream %u greater than %d\n",
		   keyCount, TPM_KEY_HANDLES);
	    rc = TPM_FAIL;
	}
    }    
    /* for each key handle entry */
    for (i = 0 ; (rc == 0) && (i < keyCount) ; i++) {
	/* deserialize the key handle entry and its key member */
	if (rc == 0) {
	    TPM_KeyHandleEntry_Init(&tpm_key_handle_entry);	/* freed @2 on error */
	    rc = TPM_KeyHandleEntry_Load(&tpm_key_handle_entry, stream, stream_size);
	}
	if (rc == 0) {
	    printf("  TPM_KeyHandleEntries_Load: Loading key handle %08x\n",
		   tpm_key_handle_entry.handle);
	    /* Add the entry to the list.  Keep the handle.  If the suggested value could not be
	       accepted, this is a "should never happen" fatal error.  It means that the save key
	       handle was saved twice.	*/
	    rc = TPM_KeyHandleEntries_AddEntry(&(tpm_key_handle_entry.handle), 	/* suggested */
					       TRUE,				/* keep handle */
					       tpm_state->tpm_key_handle_entries,
					       &tpm_key_handle_entry);
	}
	/* if there was an error copying the entry to the array, the entry must be delete'd to
	   prevent a memory leak, since a key has been loaded to the entry */
	if (rc != 0) {
	    TPM_KeyHandleEntry_Delete(&tpm_key_handle_entry);	/* @2 on error */
	}	
    }
    return rc;
}

/* TPM_KeyHandleEntries_Store() stores the key handle entries to a stream that can be restored
   through TPM_KeyHandleEntries_Load().

   The two functions must be kept in sync.
*/

TPM_RESULT TPM_KeyHandleEntries_Store(TPM_STORE_BUFFER *sbuffer,
				      tpm_state_t *tpm_state)
{
    TPM_RESULT			rc = 0;
    size_t			start;		/* iterator though key handle entries */
    size_t			current;	/* iterator though key handle entries */
    uint32_t			keyCount;	/* keys to be saved */
    TPM_BOOL 			save;		/* should key be saved */
    TPM_KEY_HANDLE_ENTRY	*tpm_key_handle_entry;
    
    if (rc == 0) {
	rc = TPM_Sbuffer_Append16(sbuffer, TPM_TAG_KEY_HANDLE_ENTRIES_V1);
    }
    /* first count up the keys */
    if (rc == 0) {
	start = 0;
	keyCount = 0;
	printf("  TPM_KeyHandleEntries_Store: Counting keys to be stored\n");
    }
    while ((rc == 0) &&
	   /* returns TPM_RETRY when at the end of the table, terminates loop */
	   (TPM_KeyHandleEntries_GetNextEntry(&tpm_key_handle_entry,
					      &current,
					      tpm_state->tpm_key_handle_entries,
					      start)) == 0) {
	TPM_SaveState_IsSaveKey(&save, tpm_key_handle_entry);
	if (save) {
	    keyCount++;
	}
	start = current + 1;
    }
    /* store the number of entries to save */
    if (rc == 0) {
	printf("  TPM_KeyHandleEntries_Store: %u keys to be stored\n", keyCount);
	rc = TPM_Sbuffer_Append32(sbuffer, keyCount);
    }
    /* for each key handle entry */
    if (rc == 0) {
	printf("  TPM_KeyHandleEntries_Store: Storing keys\n");
	start = 0;
    }
    while ((rc == 0) &&
	   /* returns TPM_RETRY when at the end of the table, terminates loop */
	   (TPM_KeyHandleEntries_GetNextEntry(&tpm_key_handle_entry,
					      &current,
					      tpm_state->tpm_key_handle_entries,
					      start)) == 0) {
	TPM_SaveState_IsSaveKey(&save, tpm_key_handle_entry);
	if (save) {
	    /* store the key handle entry and its associated key */
	    rc = TPM_KeyHandleEntry_Store(sbuffer, tpm_key_handle_entry);
	}
	start = current + 1;
    }
    return rc;
}



/* TPM_KeyHandleEntries_StoreHandles() stores only the two members which are part of the
   specification.

   - the number of loaded keys
   - a list of key handles

   A TPM_KEY_HANDLE_LIST structure that enumerates all key handles loaded on the TPM. The list only
   contains the number of handles that an external manager can operate with and does not include the
   EK or SRK.  This is command is available for backwards compatibility. It is the same as
   TPM_CAP_HANDLE with a resource type of keys.
*/

TPM_RESULT TPM_KeyHandleEntries_StoreHandles(TPM_STORE_BUFFER *sbuffer,
					     const TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries)
{
    TPM_RESULT	rc = 0;
    uint16_t	i, loadedCount;
    
    printf(" TPM_KeyHandleEntries_StoreHandles:\n");
    if (rc == 0) {
	loadedCount = 0;
	/* count the number of loaded handles */
	for (i = 0 ; i < TPM_KEY_HANDLES ; i++) {
	    if (tpm_key_handle_entries[i].key != NULL) {
		loadedCount++;
	    }
	}
	/* store 'loaded' handle count */
	rc = TPM_Sbuffer_Append16(sbuffer, loadedCount); 
    }
    for (i = 0 ; (rc == 0) && (i < TPM_KEY_HANDLES) ; i++) {
	if (tpm_key_handle_entries[i].key != NULL) {	/* if the index is loaded */
	    rc = TPM_Sbuffer_Append32(sbuffer, tpm_key_handle_entries[i].handle); /* store it */
	}
    }
    return rc;
}

/* TPM_KeyHandleEntries_DeleteHandle() removes a handle from the list.

   The TPM_KEY object must be _Delete'd and possibly free'd separately, because it might not be in
   the table.
*/

TPM_RESULT TPM_KeyHandleEntries_DeleteHandle(TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries,
					     TPM_KEY_HANDLE tpm_key_handle)
{
    TPM_RESULT	rc = 0;
    TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entry;
    
    printf(" TPM_KeyHandleEntries_DeleteHandle: %08x\n", tpm_key_handle);
    /* search for the handle */
    if (rc == 0) {
	rc = TPM_KeyHandleEntries_GetEntry(&tpm_key_handle_entry,
					   tpm_key_handle_entries,
					   tpm_key_handle);
	if (rc != 0) {
	    printf("TPM_KeyHandleEntries_DeleteHandle: Error, key handle %08x not found\n",
		   tpm_key_handle);
	}
    }
    /* delete the entry */
    if (rc == 0) {
	TPM_KeyHandleEntry_Init(tpm_key_handle_entry);
    }
    return rc;
}

/* TPM_KeyHandleEntries_IsSpace() returns 'isSpace' TRUE if an entry is available, FALSE if not.

   If TRUE, 'index' holds the first free position.
*/

void TPM_KeyHandleEntries_IsSpace(TPM_BOOL *isSpace,
				  uint32_t *index,
				  const TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries)
{
    printf(" TPM_KeyHandleEntries_IsSpace:\n");
    for (*index = 0, *isSpace = FALSE ; *index < TPM_KEY_HANDLES ; (*index)++) {
	if (tpm_key_handle_entries[*index].key == NULL) {	/* if the index is empty */
	    printf("  TPM_KeyHandleEntries_IsSpace: Found space at %u\n", *index);
	    *isSpace = TRUE;
	    break;
	}
    }
    return;
}

/* TPM_KeyHandleEntries_GetSpace() returns the number of unused key handle entries.

*/

void TPM_KeyHandleEntries_GetSpace(uint32_t *space,
				   const TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries)
{
    uint32_t i;

    printf(" TPM_KeyHandleEntries_GetSpace:\n");
    for (*space = 0 , i = 0 ; i < TPM_KEY_HANDLES ; i++) {
	if (tpm_key_handle_entries[i].key == NULL) {	/* if the index is empty */
	    (*space)++;
	}	    
    }
    return;
}

/* TPM_KeyHandleEntries_IsEvictSpace() returns 'isSpace' TRUE if there are at least 'minSpace'
   entries that do not have the ownerEvict bit set, FALSE if not.
*/

void TPM_KeyHandleEntries_IsEvictSpace(TPM_BOOL *isSpace,
				       const TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries,
				       uint32_t minSpace)
{
    uint32_t evictSpace;
    uint32_t i;

    for (i = 0,	 evictSpace = 0 ; i < TPM_KEY_HANDLES ; i++) {
	if (tpm_key_handle_entries[i].key == NULL) {	/* if the index is empty */
	    evictSpace++;
	}
	else {							/* is index is used */
	    if (!(tpm_key_handle_entries[i].keyControl & TPM_KEY_CONTROL_OWNER_EVICT)) {
		evictSpace++;	/* space that can be evicted */
	    }
	}
    }
    printf(" TPM_KeyHandleEntries_IsEvictSpace: evictable space, minimum %u free %u\n",
	   minSpace, evictSpace);
    if (evictSpace >= minSpace) {
	*isSpace = TRUE;
    }
    else {
	*isSpace = FALSE;
    }
    return;
}

/* TPM_KeyHandleEntries_AddKeyEntry() adds a TPM_KEY object to the list.

   If *tpm_key_handle == 0, a value is assigned.  If *tpm_key_handle != 0,
   that value is used if it it not currently in use.

   The handle is returned in tpm_key_handle.
*/

TPM_RESULT TPM_KeyHandleEntries_AddKeyEntry(TPM_KEY_HANDLE *tpm_key_handle,		/* i/o */
					    TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries, /* in */
					    TPM_KEY *tpm_key,
					    TPM_BOOL parentPCRStatus,
					    TPM_KEY_CONTROL keyControl)
{
    TPM_RESULT			rc = 0;
    TPM_KEY_HANDLE_ENTRY	tpm_key_handle_entry;

    printf(" TPM_KeyHandleEntries_AddKeyEntry:\n");
    tpm_key_handle_entry.key = tpm_key;
    tpm_key_handle_entry.parentPCRStatus = parentPCRStatus;
    tpm_key_handle_entry.keyControl = keyControl;
    rc = TPM_KeyHandleEntries_AddEntry(tpm_key_handle,
				       FALSE,			/* don't have to keep handle */
				       tpm_key_handle_entries,
				       &tpm_key_handle_entry);
    return rc;
}

/* TPM_KeyHandleEntries_AddEntry() adds (copies) the TPM_KEY_HANDLE_ENTRY object to the list.

   If *tpm_key_handle == 0:
	a value is assigned.

   If *tpm_key_handle != 0:

	If keepHandle is TRUE, the handle must be used.	 An error is returned if the handle is
	already in use.

	If keepHandle is FALSE, if the handle is already in use, a new value is assigned.

   The handle is returned in tpm_key_handle.
*/

TPM_RESULT TPM_KeyHandleEntries_AddEntry(TPM_KEY_HANDLE *tpm_key_handle,		/* i/o */
					 TPM_BOOL keepHandle,				/* input */
					 TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries,	/* input */
					 TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entry)	/* input */
					 
{
    TPM_RESULT			rc = 0;
    uint32_t			index;
    TPM_BOOL			isSpace;
    
    printf(" TPM_KeyHandleEntries_AddEntry: handle %08x, keepHandle %u\n",
	   *tpm_key_handle, keepHandle);
    /* check for valid TPM_KEY */
    if (rc == 0) {
	if (tpm_key_handle_entry->key == NULL) {	/* should never occur */
	    printf("TPM_KeyHandleEntries_AddEntry: Error (fatal), NULL TPM_KEY\n");
	    rc = TPM_FAIL;
	}
    }
    /* is there an empty entry, get the location index */
    if (rc == 0) {
	TPM_KeyHandleEntries_IsSpace(&isSpace, &index, tpm_key_handle_entries);
	if (!isSpace) {
	    printf("TPM_KeyHandleEntries_AddEntry: Error, key handle entries full\n");
	    rc = TPM_NOSPACE;
	}
    }
    if (rc == 0) {
	rc = TPM_Handle_GenerateHandle(tpm_key_handle,			/* I/O */
				       tpm_key_handle_entries,		/* handle array */
				       keepHandle,
				       TRUE,				/* isKeyHandle */
				       (TPM_GETENTRY_FUNCTION_T)TPM_KeyHandleEntries_GetEntry);
    }
    if (rc == 0) {
	tpm_key_handle_entries[index].handle = *tpm_key_handle;
	tpm_key_handle_entries[index].key = tpm_key_handle_entry->key;
	tpm_key_handle_entries[index].keyControl = tpm_key_handle_entry->keyControl;
	tpm_key_handle_entries[index].parentPCRStatus = tpm_key_handle_entry->parentPCRStatus;
	printf("  TPM_KeyHandleEntries_AddEntry: Index %u key handle %08x key pointer %p\n",
	       index, tpm_key_handle_entries[index].handle, tpm_key_handle_entries[index].key);
    }
    return rc;
}

/* TPM_KeyHandleEntries_GetEntry() searches all entries for the entry matching the handle, and
   returns that entry */

TPM_RESULT TPM_KeyHandleEntries_GetEntry(TPM_KEY_HANDLE_ENTRY **tpm_key_handle_entry,
					 TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries,
					 TPM_KEY_HANDLE tpm_key_handle)
{
    TPM_RESULT	rc = 0;
    size_t	i;
    TPM_BOOL	found;

    printf(" TPM_KeyHandleEntries_GetEntry: Get entry for handle %08x\n", tpm_key_handle);
    for (i = 0, found = FALSE ; (i < TPM_KEY_HANDLES) && !found ; i++) {
	/* first test for matching handle.  Then check for non-NULL to insure that entry is valid */
	if ((tpm_key_handle_entries[i].handle == tpm_key_handle) &&
	    tpm_key_handle_entries[i].key != NULL) {	/* found */
	    found = TRUE;
	    *tpm_key_handle_entry = &(tpm_key_handle_entries[i]);
	}
    }
    if (!found) {
	printf("  TPM_KeyHandleEntries_GetEntry: key handle %08x not found\n", tpm_key_handle);
	rc = TPM_INVALID_KEYHANDLE;
    }
    else {
	printf("  TPM_KeyHandleEntries_GetEntry: key handle %08x found\n", tpm_key_handle);
    }
    return rc;
}

/* TPM_KeyHandleEntries_GetNextEntry() gets the next valid TPM_KEY_HANDLE_ENTRY at or after the
   'start' index.

   The current position is returned in 'current'.  For iteration, the next 'start' should be
   'current' + 1.

   Returns

   0 on success.
   Returns TPM_RETRY when no more valid entries are found.
 */

TPM_RESULT TPM_KeyHandleEntries_GetNextEntry(TPM_KEY_HANDLE_ENTRY **tpm_key_handle_entry,
					     size_t *current,
					     TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries,
					     size_t start)
{
    TPM_RESULT	rc = TPM_RETRY;

    printf(" TPM_KeyHandleEntries_GetNextEntry: Start %lu\n", (unsigned long)start);
    for (*current = start ; *current < TPM_KEY_HANDLES ; (*current)++) {
	if (tpm_key_handle_entries[*current].key != NULL) {
	    *tpm_key_handle_entry = &(tpm_key_handle_entries[*current]);
	    rc = 0;	/* found an entry */
	    break;
	}
    }
    return rc;
}

/* TPM_KeyHandleEntries_GetKey() gets the TPM_KEY associated with the handle.

   If the key has PCR usage (size is non-zero and one or more mask bits are set), PCR's have been
   specified.  It computes a PCR digest based on the TPM PCR's and verifies it against the key
   digestAtRelease.
   
   Exceptions: readOnly is TRUE when the caller is indicating that only the public key is being read
   (e.g. TPM_GetPubKey).  In this case, if keyFlags TPM_PCRIGNOREDONREAD is also TRUE, the PCR
   digest and locality must not be checked.

   If ignorePCRs is TRUE, the PCR digest is also ignored.  A typical case is during OSAP and DSAP
   session setup.
 */

TPM_RESULT TPM_KeyHandleEntries_GetKey(TPM_KEY **tpm_key,
				       TPM_BOOL *parentPCRStatus,
				       tpm_state_t *tpm_state,
				       TPM_KEY_HANDLE tpm_key_handle,
				       TPM_BOOL readOnly,
				       TPM_BOOL ignorePCRs,
				       TPM_BOOL allowEK)
{
    TPM_RESULT		rc = 0;
    TPM_BOOL		found = FALSE;	/* found a special handle key */
    TPM_BOOL		validatePcrs = TRUE;
    TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entry;

    printf(" TPM_KeyHandleEntries_GetKey: For handle %08x\n", tpm_key_handle);
    /* If it's one of the special handles, return the TPM_KEY */
    if (rc == 0) {
	switch (tpm_key_handle) {
	  case TPM_KH_SRK:	/* The handle points to the SRK */
	    if (tpm_state->tpm_permanent_data.ownerInstalled) {
		*tpm_key = &(tpm_state->tpm_permanent_data.srk);
		*parentPCRStatus = FALSE;	/* storage root key (SRK) has no parent */
		found = TRUE;
	    }
	    else {
		printf(" TPM_KeyHandleEntries_GetKey: Error, SRK handle with no owner\n");
		rc = TPM_KEYNOTFOUND;
	    }
	    break;
	  case TPM_KH_EK:	/* The handle points to the PUBEK, only usable with
				   TPM_OwnerReadInternalPub */
	    if (rc == 0) {
		if (!allowEK) {
		    printf(" TPM_KeyHandleEntries_GetKey: Error, EK handle not allowed\n");
		    rc = TPM_KEYNOTFOUND;
		}
	    }
	    if (rc == 0) {
		if (tpm_state->tpm_permanent_data.endorsementKey.keyUsage ==
		    TPM_KEY_UNINITIALIZED) {
		    printf(" TPM_KeyHandleEntries_GetKey: Error, EK handle but no EK\n");
		    rc = TPM_KEYNOTFOUND;
		}
	    }
	    if (rc == 0) {
		*tpm_key = &(tpm_state->tpm_permanent_data.endorsementKey);
		*parentPCRStatus = FALSE;	/* endorsement key (EK) has no parent */
		found = TRUE;
	    }
	    break;
	  case TPM_KH_OWNER:	/* handle points to the TPM Owner */
	  case TPM_KH_REVOKE:	/* handle points to the RevokeTrust value */
	  case TPM_KH_TRANSPORT: /* handle points to the EstablishTransport static authorization */
	  case TPM_KH_OPERATOR: /* handle points to the Operator auth */
	  case TPM_KH_ADMIN:	/* handle points to the delegation administration auth */
	    printf("TPM_KeyHandleEntries_GetKey: Error, Unsupported key handle %08x\n",
		   tpm_key_handle);
	    rc = TPM_INVALID_RESOURCE;
	    break;
	  default:
	    /* continue searching */
	    break;
	}
    }
    /* If not one of the special key handles, search for the handle in the list */
    if ((rc == 0) && !found) {
	rc = TPM_KeyHandleEntries_GetEntry(&tpm_key_handle_entry,
					   tpm_state->tpm_key_handle_entries,
					   tpm_key_handle);
	if (rc != 0) {
	    printf("TPM_KeyHandleEntries_GetKey: Error, key handle %08x not found\n",
		   tpm_key_handle);
	}
    }
    /* Part 1 25.1 Validate Key for use 
       2. Set LK to the loaded key that is being used */
    /* NOTE:  For special handle keys, this was already done.  Just do here for keys in table */
    if ((rc == 0) && !found) {
	*tpm_key = tpm_key_handle_entry->key;
	*parentPCRStatus = tpm_key_handle_entry->parentPCRStatus;
    }
    /* 3. If LK -> pcrInfoSize is not 0 - if the key specifies PCR's */
    /* NOTE Done by TPM_Key_CheckPCRDigest() */
    /* a. If LK -> pcrInfo -> releasePCRSelection identifies the use of one or more PCR */
    if (rc == 0) {
#ifdef TPM_V12
	validatePcrs = !ignorePCRs &&
		       !(readOnly && ((*tpm_key)->keyFlags & TPM_PCRIGNOREDONREAD));
#else
	validatePcrs = !ignorePCRs && !readOnly;
#endif
    }
    if ((rc == 0) && validatePcrs) {
	if (rc == 0) {
	    rc = TPM_Key_CheckPCRDigest(*tpm_key, tpm_state);
	}
    }
    return rc;
}

/* TPM_KeyHandleEntries_SetParentPCRStatus() updates the parentPCRStatus member of the
   TPM_KEY_HANDLE_ENTRY */

TPM_RESULT TPM_KeyHandleEntries_SetParentPCRStatus(TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries,
						   TPM_KEY_HANDLE tpm_key_handle,
						   TPM_BOOL parentPCRStatus)
{
    TPM_RESULT	rc = 0;
    TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entry;

    printf(" TPM_KeyHandleEntries_SetParentPCRStatus: Handle %08x\n", tpm_key_handle);
    /* get the entry for the handle from the table */
    if (rc == 0) {
	rc = TPM_KeyHandleEntries_GetEntry(&tpm_key_handle_entry,
					   tpm_key_handle_entries,
					   tpm_key_handle);
	if (rc != 0) {
	    printf("TPM_KeyHandleEntries_SetParentPCRStatus: Error, key handle %08x not found\n",
		   tpm_key_handle);
	}
    }
    if (rc == 0) {
	tpm_key_handle_entry->parentPCRStatus = parentPCRStatus;
    }
    return rc;
}

/* TPM_KeyHandleEntries_OwnerEvictLoad() loads all owner evict keys from the stream into the key
   handle entries table.
*/

TPM_RESULT TPM_KeyHandleEntries_OwnerEvictLoad(TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries,
					       unsigned char **stream,
					       uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;
    uint16_t 		keyCount;
    uint16_t		i;		/* the uint16_t corresponds to the standard getcap */
    TPM_KEY_HANDLE_ENTRY tpm_key_handle_entry;	/* each entry as read from the stream */
    TPM_TAG		ownerEvictVersion;

    printf(" TPM_KeyHandleEntries_OwnerEvictLoad:\n");
    /* get the owner evict version number */
    if (rc == 0) {
	rc = TPM_Load16(&ownerEvictVersion, stream, stream_size); 
    }
    if (rc == 0) {
	if (ownerEvictVersion != TPM_TAG_NVSTATE_OE_V1) {
	    printf("TPM_KeyHandleEntries_OwnerEvictLoad: "
		   "Error (fatal) unsupported version tag %04x\n",
		   ownerEvictVersion);
	    rc = TPM_FAIL;
	}
    }
    /* get the count of owner evict keys in the stream */
    if (rc == 0) {
	rc = TPM_Load16(&keyCount, stream, stream_size); 
    }
    /* sanity check that keyCount not greater than key slots */
    if (rc == 0) {
	if (keyCount > TPM_OWNER_EVICT_KEY_HANDLES) {
	    printf("TPM_KeyHandleEntries_OwnerEvictLoad: Error (fatal)"
		   " key handles in stream %u greater than %d\n",
		   keyCount, TPM_OWNER_EVICT_KEY_HANDLES);
	    rc = TPM_FAIL;
	}
    }    
    if (rc == 0) {
	printf("  TPM_KeyHandleEntries_OwnerEvictLoad: Count %hu\n", keyCount);
    }
    for (i = 0 ; (rc == 0) && (i < keyCount) ; i++) {
	/* Must init each time through.  This just resets the structure members.  It does not free
	   the key that is in the structure after the first time through.  That key has been added
	   (copied) to the key handle entries array. */
	printf("  TPM_KeyHandleEntries_OwnerEvictLoad: Loading key %hu\n", i);
	TPM_KeyHandleEntry_Init(&tpm_key_handle_entry);	/* freed @2 on error */
	if (rc == 0) {
	    rc = TPM_KeyHandleEntry_Load(&tpm_key_handle_entry, stream, stream_size);
	}
	/* add the entry to the list */
	if (rc == 0) {
	    rc = TPM_KeyHandleEntries_AddEntry(&(tpm_key_handle_entry.handle),	/* suggested */
					       TRUE,				/* keep handle */
					       tpm_key_handle_entries,
					       &tpm_key_handle_entry);
	}
	/* if there was an error copying the entry to the array, the entry must be delete'd to
	   prevent a memory leak, since a key has been loaded to the entry */
	if (rc != 0) {
	    TPM_KeyHandleEntry_Delete(&tpm_key_handle_entry);	/* @2 on error */
	}	
    }
    return rc;
}
    
/* TPM_KeyHandleEntries_OwnerEvictStore() stores all owner evict keys from the key handle entries
   table to the stream.

   It is used to serialize to NVRAM.
*/

TPM_RESULT TPM_KeyHandleEntries_OwnerEvictStore(TPM_STORE_BUFFER *sbuffer,
						const TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries)
{
    TPM_RESULT	rc = 0;
    uint16_t 	count;
    uint16_t	i;		/* the uint16_t corresponds to the standard getcap */

    printf(" TPM_KeyHandleEntries_OwnerEvictStore:\n");
    /* append the owner evict version number to the stream */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append16(sbuffer, TPM_TAG_NVSTATE_OE_V1); 
    }
    /* count the number of owner evict keys */
    if (rc == 0) {
	rc = TPM_KeyHandleEntries_OwnerEvictGetCount(&count, tpm_key_handle_entries);
    }
    /* append the count to the stream */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append16(sbuffer, count); 
    }
    for (i = 0 ; (rc == 0) && (i < TPM_KEY_HANDLES) ; i++) {
	/* if the slot is occupied */
	if (tpm_key_handle_entries[i].key != NULL) {
	    /* if the key is owner evict */
	    if ((tpm_key_handle_entries[i].keyControl & TPM_KEY_CONTROL_OWNER_EVICT)) {
		/* store it */
		rc = TPM_KeyHandleEntry_Store(sbuffer, &(tpm_key_handle_entries[i]));
	    }
	}
    }
    return rc;
}

/* TPM_KeyHandleEntries_OwnerEvictGetCount returns the number of owner evict key entries
 */

TPM_RESULT
TPM_KeyHandleEntries_OwnerEvictGetCount(uint16_t *count,
					const TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries)
{
    TPM_RESULT	rc = 0;
    uint16_t	i;		/* the uint16_t corresponds to the standard getcap */

    printf(" TPM_KeyHandleEntries_OwnerEvictGetCount:\n");
    /* count the number of loaded owner evict handles */
    if (rc == 0) {
	for (i = 0 , *count = 0 ; i < TPM_KEY_HANDLES ; i++) {
	    /* if the slot is occupied */
	    if (tpm_key_handle_entries[i].key != NULL) {
		/* if the key is owner evict */
		if ((tpm_key_handle_entries[i].keyControl & TPM_KEY_CONTROL_OWNER_EVICT)) {
		    (*count)++;		/* count it */
		}
	    }
	}
	printf("  TPM_KeyHandleEntries_OwnerEvictGetCount: Count %hu\n", *count);
    }
    /* sanity check */
    if (rc == 0) {
	if (*count > TPM_OWNER_EVICT_KEY_HANDLES) {
	    printf("TPM_KeyHandleEntries_OwnerEvictGetCount: Error (fatal), "
		   "count greater that max %u\n", TPM_OWNER_EVICT_KEY_HANDLES);
	    rc = TPM_FAIL;	/* should never occur */
	}
    }
    return rc;
}

/* TPM_KeyHandleEntries_OwnerEvictDelete() flushes owner evict keys.  It does NOT write to NV.

*/

void TPM_KeyHandleEntries_OwnerEvictDelete(TPM_KEY_HANDLE_ENTRY *tpm_key_handle_entries)
{
    uint16_t	i;		/* the uint16_t corresponds to the standard getcap */

    for (i = 0 ; i < TPM_KEY_HANDLES ; i++) {
	/* if the slot is occupied */
	if (tpm_key_handle_entries[i].key != NULL) {
	    /* if the key is owner evict */
	    if ((tpm_key_handle_entries[i].keyControl & TPM_KEY_CONTROL_OWNER_EVICT)) {
		TPM_KeyHandleEntry_Delete(&(tpm_key_handle_entries[i]));
	    }
	}
    }
    return;
}

/*
  Processing Functions
*/

/* 14.4 TPM_ReadPubek rev 99

   Return the endorsement key public portion. This value should have controls placed upon access as
   it is a privacy sensitive value

   The readPubek flag is set to FALSE by TPM_TakeOwnership and set to TRUE by TPM_OwnerClear, thus
   mirroring if a TPM Owner is present.
*/

TPM_RESULT TPM_Process_ReadPubek(tpm_state_t *tpm_state,
				 TPM_STORE_BUFFER *response,
				 TPM_TAG tag,
				 uint32_t paramSize,		/* of remaining parameters*/
				 TPM_COMMAND_CODE ordinal,
				 unsigned char *command,
				 TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_NONCE		antiReplay;

    /* processing */
    const unsigned char *pubEndorsementKeyStreamBuffer;
    uint32_t		pubEndorsementKeyStreamLength;

    /* processing parameters */
    unsigned char *		inParamStart;			/* starting point of inParam's */
    unsigned char *		inParamEnd;			/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */

    /* output parameters */
    uint32_t		outParamStart;			/* starting point of outParam's */
    uint32_t		outParamEnd;			/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_STORE_BUFFER	pubEndorsementKeyStream;
    TPM_DIGEST		checksum;
    
    printf("TPM_Process_ReadPubek: Ordinal Entry\n");
    TPM_Sbuffer_Init(&pubEndorsementKeyStream);		/* freed @1 */
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get antiReplay parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Nonce_Load(antiReplay, &command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	TPM_PrintFour(" TPM_Process_ReadPubek: antiReplay", antiReplay);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALLOW_NO_OWNER);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag0(tag);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_ReadPubek: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /*
      Processing
    */
    /* 1. If TPM_PERMANENT_FLAGS -> readPubek is FALSE return TPM_DISABLED_CMD. */
    if (returnCode == TPM_SUCCESS) {
	printf(" TPM_Process_ReadPubek: readPubek %02x\n",
	       tpm_state->tpm_permanent_flags.readPubek);
	if (!tpm_state->tpm_permanent_flags.readPubek) {
	    printf("TPM_Process_ReadPubek: Error, readPubek is FALSE\n");
	    returnCode = TPM_DISABLED_CMD;
	}
    }
    /* 2. If no EK is present the TPM MUST return TPM_NO_ENDORSEMENT */
    if (returnCode == TPM_SUCCESS) {
	if (tpm_state->tpm_permanent_data.endorsementKey.keyUsage == TPM_KEY_UNINITIALIZED) {
	    printf("TPM_Process_ReadPubek: Error, no EK is present\n");
	    returnCode = TPM_NO_ENDORSEMENT;
	}
    }
    /* 3. Create checksum by performing SHA-1 on the concatenation of (pubEndorsementKey ||
	  antiReplay). */
    if (returnCode == TPM_SUCCESS) {
	/* serialize the TPM_PUBKEY components of the EK */
	returnCode =
	    TPM_Key_StorePubkey(&pubEndorsementKeyStream,			/* output */
				&pubEndorsementKeyStreamBuffer,			/* output */
				&pubEndorsementKeyStreamLength,			/* output */
				&(tpm_state->tpm_permanent_data.endorsementKey));	/* input */
    }
    if (returnCode == TPM_SUCCESS) {
	printf(" TPM_Process_ReadPubek: pubEndorsementKey length %u\n",
	       pubEndorsementKeyStreamLength);
	/* create the checksum */
	returnCode = TPM_SHA1(checksum,
#if 0		/* The old Atmel chip and the LTC test code assume this, but it is incorrect */
			      tpm_state->tpm_permanent_data.endorsementKey.pubKey.keyLength,
			      tpm_state->tpm_permanent_data.endorsementKey.pubKey.key,
#else		/* this meets the TPM 1.2 standard */
			      pubEndorsementKeyStreamLength, pubEndorsementKeyStreamBuffer, 
#endif
			      sizeof(TPM_NONCE), antiReplay,
			      0, NULL);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_ReadPubek: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	/* 4. Export the PUBEK and checksum. */
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* append pubEndorsementKey */
	    returnCode = TPM_Sbuffer_Append(response,
					    pubEndorsementKeyStreamBuffer,
					    pubEndorsementKeyStreamLength);
	}
	/* append checksum */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_Digest_Store(response, checksum);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /*
      cleanup
    */
    TPM_Sbuffer_Delete(&pubEndorsementKeyStream);	/* @1 */
    return rcf;
}

/* 14.2 TPM_CreateRevocableEK rev 98

   This command creates the TPM endorsement key. It returns a failure code if an endorsement key
   already exists. The TPM vendor may have a separate mechanism to create the EK and "squirt" the
   value into the TPM.
*/

TPM_RESULT TPM_Process_CreateRevocableEK(tpm_state_t *tpm_state,
					 TPM_STORE_BUFFER *response,
					 TPM_TAG tag,
					 uint32_t paramSize,
					 TPM_COMMAND_CODE ordinal,
					 unsigned char *command,
					 TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_NONCE		antiReplay;	/* Arbitrary data */
    TPM_KEY_PARMS	keyInfo;	/* Information about key to be created, this includes all
					   algorithm parameters */
    TPM_BOOL		generateReset = FALSE;	/* If TRUE use TPM RNG to generate EKreset. If FALSE
						   use the passed value inputEKreset */
    TPM_NONCE		inputEKreset;	/* The authorization value to be used with TPM_RevokeTrust
					   if generateReset==FALSE, else the parameter is present
					   but unused */

    /* processing parameters */
    unsigned char *		inParamStart;		/* starting point of inParam's */
    unsigned char *		inParamEnd;		/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus = FALSE;	/* audit the ordinal */
    TPM_BOOL			transportEncrypt = FALSE; 	/* wrapped in encrypted transport
								   session */
    TPM_KEY			*endorsementKey;	/* EK object from permanent store */
    TPM_BOOL			writeAllNV1 = FALSE;	/* flags to write back NV */
    TPM_BOOL			writeAllNV2 = FALSE;	/* flags to write back NV */

    /* output parameters */
    uint32_t		outParamStart;		/* starting point of outParam's */
    uint32_t		outParamEnd;		/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_PUBKEY		pubEndorsementKey;	/* The public endorsement key */
    TPM_DIGEST		checksum;		/* Hash of pubEndorsementKey and antiReplay */

    printf("TPM_Process_CreateRevocableEK: Ordinal Entry\n");
    /* get pointers */
    endorsementKey = &(tpm_state->tpm_permanent_data.endorsementKey);
    /* so that Delete's are safe */
    TPM_KeyParms_Init(&keyInfo);		/* freed @1 */
    TPM_Pubkey_Init(&pubEndorsementKey);	/* freed @2 */
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get antiReplay parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Nonce_Load(antiReplay, &command, &paramSize);
    }
    /* get keyInfo parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyParms_Load(&keyInfo, &command, &paramSize); /* freed @1 */
    }	    
    /* get generateReset parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode  = TPM_LoadBool(&generateReset, &command, &paramSize);
    }
    /* get inputEKreset parameter */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CreateRevocableEK: generateReset %02x\n", generateReset);
	/* an email clarification says that this parameter is still present (but ignored) if
	   generateReset is TRUE */
	returnCode = TPM_Nonce_Load(inputEKreset, &command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	TPM_PrintFour("TPM_Process_CreateRevocableEK: inputEKreset", inputEKreset);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALLOW_NO_OWNER);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag0(tag);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_CreateRevocableEK: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /*
      Processing
    */
    /* 1. If an EK already exists, return TPM_DISABLED_CMD */
    /* 2. Perform the actions of TPM_CreateEndorsementKeyPair, if any errors return with error */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CreateEndorsementKeyPair_Common(endorsementKey,
							 &pubEndorsementKey,
							 checksum,
							 &writeAllNV1,
							 tpm_state,
							 &keyInfo,
							 antiReplay);
    }
    if (returnCode == TPM_SUCCESS) {
	/* 3. Set TPM_PERMANENT_FLAGS -> enableRevokeEK to TRUE */
	TPM_SetCapability_Flag(&writeAllNV1,					/* altered */
			       &(tpm_state->tpm_permanent_flags.enableRevokeEK),	/* flag */
			       TRUE);							/* value */
	/* a. If generateReset is TRUE then */
	if (generateReset) {
	    /* i. Set TPM_PERMANENT_DATA -> EKreset to the next value from the TPM RNG */
	    returnCode = TPM_Nonce_Generate(tpm_state->tpm_permanent_data.EKReset);
	}
	/* b. Else  */
	else {
	    /* i. Set TPM_PERMANENT_DATA -> EKreset to inputEkreset  */
	    TPM_Nonce_Copy(tpm_state->tpm_permanent_data.EKReset, inputEKreset);
	}
    }
    /* save the permanent data and flags structure sto NVRAM */
    returnCode = TPM_PermanentAll_NVStore(tpm_state,
					  (TPM_BOOL)(writeAllNV1 || writeAllNV2),
					  returnCode);
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_CreateRevocableEK: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* 4. Return PUBEK, checksum and Ekreset */
	    /* append pubEndorsementKey. */
	    returnCode = TPM_Pubkey_Store(response, &pubEndorsementKey);
	}
	/* append checksum */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_Digest_Store(response, checksum);
	}
	/* append outputEKreset */
	/* 5. The outputEKreset authorization is sent in the clear. There is no uniqueness on the
	   TPM available to actually perform encryption or use an encrypted channel. The assumption
	   is that this operation is occurring in a controlled environment and sending the value in
	   the clear is acceptable.
	*/
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_Nonce_Store(response, tpm_state->tpm_permanent_data.EKReset);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /*
      cleanup
    */
    TPM_KeyParms_Delete(&keyInfo);		/* @1 */
    TPM_Pubkey_Delete(&pubEndorsementKey);	/* @2 */
    return rcf;
}

/* 14.1 TPM_CreateEndorsementKeyPair rev 104

   This command creates the TPM endorsement key. It returns a failure code if an endorsement key
   already exists.
*/

TPM_RESULT TPM_Process_CreateEndorsementKeyPair(tpm_state_t *tpm_state,
						TPM_STORE_BUFFER *response,
						TPM_TAG tag,
						uint32_t paramSize,	/* of remaining parameters*/
						TPM_COMMAND_CODE ordinal,
						unsigned char *command,
						TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_NONCE		antiReplay;	/* Arbitrary data */
    TPM_KEY_PARMS	keyInfo;	/* Information about key to be created, this includes all
					   algorithm parameters */

    /* processing parameters */
    unsigned char *	inParamStart;		/* starting point of inParam's */
    unsigned char *	inParamEnd;		/* ending point of inParam's */
    TPM_DIGEST		inParamDigest;
    TPM_BOOL		auditStatus = FALSE;		/* audit the ordinal */
    TPM_BOOL		transportEncrypt = FALSE;	/* wrapped in encrypted transport session */
    TPM_KEY		*endorsementKey = FALSE;	/* EK object from permanent store */
    TPM_BOOL		writeAllNV1 = FALSE;	/* flags to write back data */
    TPM_BOOL		writeAllNV2 = FALSE;	/* flags to write back flags */

    /* output parameters */
    uint32_t		outParamStart;		/* starting point of outParam's */
    uint32_t		outParamEnd;		/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_PUBKEY		pubEndorsementKey;	/* The public endorsement key */
    TPM_DIGEST		checksum;		/* Hash of pubEndorsementKey and antiReplay */
    
    printf("TPM_Process_CreateEndorsementKeyPair: Ordinal Entry\n");
    /* get pointers */
    endorsementKey = &(tpm_state->tpm_permanent_data.endorsementKey);
    /* so that Delete's are safe */
    TPM_KeyParms_Init(&keyInfo);		/* freed @1 */
    TPM_Pubkey_Init(&pubEndorsementKey);	/* freed @2 */
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get antiReplay parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Nonce_Load(antiReplay, &command, &paramSize);
    }
    /* get keyInfo parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyParms_Load(&keyInfo, &command, &paramSize); /* freed @1 */
    }	    
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALLOW_NO_OWNER);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag0(tag);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_CreateEndorsementKeyPair: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /*
      Processing
    */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CreateEndorsementKeyPair_Common(endorsementKey,
							 &pubEndorsementKey,
							 checksum,
							 &writeAllNV1,
							 tpm_state,
							 &keyInfo,
							 antiReplay);
    }
    /* 10. Set TPM_PERMANENT_FLAGS -> enableRevokeEK to FALSE */
    if (returnCode == TPM_SUCCESS) {
	TPM_SetCapability_Flag(&writeAllNV2,					/* altered */
			       &(tpm_state->tpm_permanent_flags.enableRevokeEK),	/* flag */
			       FALSE);						/* value */
    }
    /* save the permanent data and flags structures to NVRAM */
    returnCode = TPM_PermanentAll_NVStore(tpm_state,
					  (TPM_BOOL)(writeAllNV1 || writeAllNV2),
					  returnCode);
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_CreateEndorsementKeyPair: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	/* append pubEndorsementKey.  */
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    returnCode = TPM_Pubkey_Store(response, &pubEndorsementKey);
	}
	/* append checksum */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_Digest_Store(response, checksum);
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /*
      cleanup
    */
    TPM_KeyParms_Delete(&keyInfo);		/* @1 */
    TPM_Pubkey_Delete(&pubEndorsementKey);	/* @2 */
    return rcf;
}

/* TPM_CreateEndorsementKeyPair_Common rev 104

   Actions common to TPM_CreateEndorsementKeyPair and TPM_CreateRevocableEK

   'endorsementKey' points to TPM_PERMANENT_DATA -> endorsementKey
*/

TPM_RESULT TPM_CreateEndorsementKeyPair_Common(TPM_KEY *endorsementKey,		/* output */
					       TPM_PUBKEY *pubEndorsementKey,	/* output */
					       TPM_DIGEST checksum,		/* output */
					       TPM_BOOL *writePermanentData,	/* output */
					       tpm_state_t *tpm_state,		/* input */
					       TPM_KEY_PARMS *keyInfo,		/* input */
					       TPM_NONCE antiReplay)		/* input */
{
    TPM_RESULT		returnCode = TPM_SUCCESS;
    TPM_RSA_KEY_PARMS	*tpm_rsa_key_parms;		/* from keyInfo */
    TPM_STORE_BUFFER	pubEndorsementKeySerial;	/* serialization for checksum calculation */
    const unsigned char *pubEndorsementKeyBuffer;
    uint32_t		pubEndorsementKeyLength;

    printf("TPM_CreateEndorsementKeyPair_Common:\n");
    TPM_Sbuffer_Init(&pubEndorsementKeySerial);		/* freed @1 */
    /* 1. If an EK already exists, return TPM_DISABLED_CMD */
    if (returnCode == TPM_SUCCESS) {
	if (endorsementKey->keyUsage != TPM_KEY_UNINITIALIZED) {
	    printf("TPM_CreateEndorsementKeyPair_Common: Error, key already initialized\n");
	    returnCode = TPM_DISABLED_CMD;
	}
    }
    /* 2. Validate the keyInfo parameters for the key description */
    if (returnCode == TPM_SUCCESS) {
	/*
	  RSA
	*/
	/* a. If the algorithm type is RSA the key length MUST be a minimum of
	   2048. For interoperability the key length SHOULD be 2048 */
	if (keyInfo->algorithmID == TPM_ALG_RSA) {
	    if (returnCode == TPM_SUCCESS) {
		/* get the keyInfo TPM_RSA_KEY_PARMS structure */
		returnCode = TPM_KeyParms_GetRSAKeyParms(&tpm_rsa_key_parms,
							 keyInfo);
	    }
	    if (returnCode == TPM_SUCCESS) {
		if (tpm_rsa_key_parms->keyLength != TPM_KEY_RSA_NUMBITS) {	/* in bits */
		    printf("TPM_CreateEndorsementKeyPair_Common: Error, "
			   "Bad keyLength should be %u, was %u\n",
			   TPM_KEY_RSA_NUMBITS, tpm_rsa_key_parms->keyLength);
		    returnCode = TPM_BAD_KEY_PROPERTY;
		}
	    }
	    /* kgold - Support only 2 primes */
	    if (returnCode == TPM_SUCCESS) {
		if (tpm_rsa_key_parms->numPrimes != 2) {
		    printf("TPM_CreateEndorsementKeyPair_Common: Error, "
			   "Bad numPrimes should be 2, was %u\n",
			   tpm_rsa_key_parms->numPrimes);
		    returnCode = TPM_BAD_KEY_PROPERTY;
		}
	    }
	}
	/*
	  not RSA
	*/
	/* b. If the algorithm type is other than RSA the strength provided by
	   the key MUST be comparable to RSA 2048 */
	else {
	    if (returnCode == TPM_SUCCESS) {
		printf("TPM_CreateEndorsementKeyPair_Common: Error, "
		       "algorithmID %08x not supported\n",
		       keyInfo->algorithmID);
		returnCode = TPM_BAD_KEY_PROPERTY;
	    }
	}
    }
    /* c. The other parameters of keyInfo (encScheme, sigScheme, etc.) are ignored.
     */
    /* 3. Create a key pair called the "endorsement key pair" using a TPM-protected capability. The
       type and size of key are that indicated by keyInfo.  Set encScheme to
       TPM_ES_RSAESOAEP_SHA1_MGF1.

       Save the endorsement key in permanent structure.	 Save the endorsement private key 'd' in the
       TPM_KEY structure as encData */
    /* Certain HW TPMs do not ignore the encScheme parameter, and expect it to be
       TPM_ES_RSAESOAEP_SHA1_MGF1.  Test the value here to detect an application program that will
       fail with that TPM. */

    if (returnCode == TPM_SUCCESS) {
	if (keyInfo->encScheme != TPM_ES_RSAESOAEP_SHA1_MGF1) {
	    returnCode = TPM_BAD_KEY_PROPERTY;
	    printf("TPM_CreateEndorsementKeyPair_Common: Error, "
		   "encScheme %08x must be TPM_ES_RSAESOAEP_SHA1_MGF1\n",
		   keyInfo->encScheme);
	}
    }
    if (returnCode == TPM_SUCCESS) {
	keyInfo->sigScheme = TPM_ES_NONE;
	returnCode = TPM_Key_GenerateRSA(endorsementKey,
					 tpm_state,
					 NULL,			/* parent key, indicate root key */
					 tpm_state->tpm_stclear_data.PCRS,	/* PCR array */
					 1,			/* TPM_KEY */
					 TPM_KEY_STORAGE,	/* keyUsage */
					 0,			/* keyFlags */
					 TPM_AUTH_ALWAYS,	/* authDataUsage */
					 keyInfo,
					 NULL,			/* no PCR's */
					 NULL);			/* no PCR's */
	*writePermanentData = TRUE;
    }
    /* Assemble the TPM_PUBKEY pubEndorsementKey for the response */
    if (returnCode == TPM_SUCCESS) {
	/* add TPM_KEY_PARMS algorithmParms */
	returnCode = TPM_KeyParms_Copy(&(pubEndorsementKey->algorithmParms),
				       keyInfo);
    }
    if (returnCode == TPM_SUCCESS) {
	/* add TPM_SIZED_BUFFER pubKey */
	returnCode = TPM_SizedBuffer_Set(&(pubEndorsementKey->pubKey),
					 endorsementKey->pubKey.size,
					 endorsementKey->pubKey.buffer);
    }				
    /* 4. Create checksum by performing SHA-1 on the concatenation of (PUBEK
       || antiReplay) */
    if (returnCode == TPM_SUCCESS) {
	/* serialize the pubEndorsementKey */
	returnCode = TPM_Pubkey_Store(&pubEndorsementKeySerial,
				      pubEndorsementKey);
    }
    if (returnCode == TPM_SUCCESS) {
	TPM_Sbuffer_Get(&pubEndorsementKeySerial,
			&pubEndorsementKeyBuffer, &pubEndorsementKeyLength);
	/* create the checksum */
	returnCode = TPM_SHA1(checksum,
			      pubEndorsementKeyLength, pubEndorsementKeyBuffer,
			      sizeof(TPM_NONCE), antiReplay,
			      0, NULL);
    }
    /* 5. Store the PRIVEK */
    /* NOTE Created in TPM_PERMANENT_DATA, call should save to NVRAM */
    /* 6. Create TPM_PERMANENT_DATA -> tpmDAASeed from the TPM RNG */
    /* 7. Create TPM_PERMANENT_DATA -> daaProof from the TPM RNG */
    /* 8. Create TPM_PERMANENT_DATA -> daaBlobKey from the TPM RNG */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_PermanentData_InitDaa(&(tpm_state->tpm_permanent_data));
    }
    /* 9. Set TPM_PERMANENT_FLAGS -> CEKPUsed to TRUE */
    if (returnCode == TPM_SUCCESS) {
	tpm_state->tpm_permanent_flags.CEKPUsed = TRUE;
    }
    /*
      cleanup
    */
    TPM_Sbuffer_Delete(&pubEndorsementKeySerial);	/* @1 */
    return returnCode;
}

/* 14.3 TPM_RevokeTrust rev 98

  This command clears the EK and sets the TPM back to a pure default state. The generation of the
  AuthData value occurs during the generation of the EK. It is the responsibility of the EK
  generator to properly protect and disseminate the RevokeTrust AuthData.
*/

TPM_RESULT TPM_Process_RevokeTrust(tpm_state_t *tpm_state,
				   TPM_STORE_BUFFER *response,
				   TPM_TAG tag,
				   uint32_t paramSize,		/* of remaining parameters*/
				   TPM_COMMAND_CODE ordinal,
				   unsigned char *command,
				   TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_NONCE EKReset;			/* The value that will be matched to EK Reset */

    /* processing parameters */
    unsigned char *		inParamStart;			/* starting point of inParam's */
    unsigned char *		inParamEnd;			/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus = FALSE;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt = FALSE;	/* wrapped in encrypted transport
								   session */
    TPM_BOOL			writeAllNV1 = FALSE;	/* flags to write back data */
    TPM_BOOL			writeAllNV2 = FALSE;	/* flags to write back flags */
    TPM_BOOL			writeAllNV3 = FALSE;	/* flags to write back flags */
    TPM_BOOL			physicalPresence;

    /* output parameters */
    uint32_t		outParamStart;		/* starting point of outParam's */
    uint32_t		outParamEnd;		/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;

    printf("TPM_Process_RevokeTrust: Ordinal Entry\n");
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get EKReset parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Nonce_Load(EKReset, &command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	TPM_PrintFour(" TPM_Process_RevokeTrust: EKReset", EKReset);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALLOW_NO_OWNER);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag0(tag);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_RevokeTrust: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /*
      Processing
    */
    /* 1. The TPM MUST validate that TPM_PERMANENT_FLAGS -> enableRevokeEK is TRUE, return
       TPM_PERMANENTEK on error */
    if (returnCode == TPM_SUCCESS) {
	if (!tpm_state->tpm_permanent_flags.enableRevokeEK) {
	    printf("TPM_Process_RevokeTrust: Error, enableRevokeEK is FALSE\n");
	    returnCode = TPM_PERMANENTEK;
	}  
    }
    /* 2. The TPM MUST validate that the EKReset matches TPM_PERMANENT_DATA -> EKReset, return
       TPM_AUTHFAIL on error. */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Nonce_Compare(tpm_state->tpm_permanent_data.EKReset, EKReset);
	if (returnCode != 0) {
	    printf("TPM_Process_RevokeTrust: Error, EKReset mismatch\n");
	    returnCode = TPM_AUTHFAIL;
	}
    }
    /* 3. Ensure that physical presence is being asserted */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Global_GetPhysicalPresence(&physicalPresence, tpm_state);
    }
    if (returnCode == TPM_SUCCESS) {
	if (!physicalPresence) {
	    printf("TPM_Process_RevokeTrust: Error, physicalPresence is FALSE\n");
	    returnCode = TPM_BAD_PRESENCE;
	}
    }
    /* 4. Perform the actions of TPM_OwnerClear (excepting the command authentication) */
    /* a. NV items with the pubInfo -> nvIndex D value set MUST be deleted. This changes the
       TPM_OwnerClear handling of the same NV areas */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_OwnerClearCommon(tpm_state,
					  TRUE);	/* delete all NVRAM */
	writeAllNV1 = TRUE;
    }
    if (returnCode == TPM_SUCCESS) {
	/* b. Set TPM_PERMANENT_FLAGS -> nvLocked to FALSE */
	TPM_SetCapability_Flag(&writeAllNV2,				/* altered (dummy) */
			       &(tpm_state->tpm_permanent_flags.nvLocked),	/* flag */
			       FALSE);						/* value */
	/* 5. Invalidate TPM_PERMANENT_DATA -> tpmDAASeed */
	/* 6. Invalidate TPM_PERMANENT_DATA -> daaProof */
	/* 7. Invalidate TPM_PERMANENT_DATA -> daaBlobKey */
	returnCode = TPM_PermanentData_InitDaa(&(tpm_state->tpm_permanent_data));
    }
    if (returnCode == TPM_SUCCESS) {
	/* 8. Invalidate the EK and any internal state associated with the EK */
	printf("TPM_Process_RevokeTrust: Deleting endorsement key\n");
	TPM_Key_Delete(&(tpm_state->tpm_permanent_data.endorsementKey));
	TPM_SetCapability_Flag(&writeAllNV3,				/* altered  (dummy) */
			       &(tpm_state->tpm_permanent_flags.CEKPUsed),	/* flag */
			       FALSE);						/* value */
    }
    /* Store the permanent data and flags back to NVRAM */
    returnCode = TPM_PermanentAll_NVStore(tpm_state,
					  writeAllNV1,
					  returnCode);
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_RevokeTrust: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /*
      cleanup
    */
    return rcf;
}

/* 27.7 TPM_DisablePubekRead rev 94

   The TPM Owner may wish to prevent any entity from reading the PUBEK. This command sets the
   non-volatile flag so that the TPM_ReadPubek command always returns TPM_DISABLED_CMD.

   This commands has in essence been deprecated as TPM_TakeOwnership now sets the value to false.
   The commands remains at this time for backward compatibility.
*/

TPM_RESULT TPM_Process_DisablePubekRead(tpm_state_t *tpm_state,
					TPM_STORE_BUFFER *response,
					TPM_TAG tag,
					uint32_t paramSize,		/* of remaining parameters*/
					TPM_COMMAND_CODE ordinal,
					unsigned char *command,
					TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_AUTHHANDLE	authHandle;	/* The authorization handle used for owner authorization. */
    TPM_NONCE		nonceOdd;	/* Nonce generated by system associated with authHandle */
    TPM_BOOL	continueAuthSession = TRUE;	/* The continue use flag for the authorization
						   handle */
    TPM_AUTHDATA	ownerAuth;	/* The authorization digest for inputs and owner
					   authorization. HMAC key: ownerAuth. */

    /* processing */
    unsigned char *	inParamStart;		/* starting point of inParam's */
    unsigned char *	inParamEnd;		/* ending point of inParam's */
    TPM_DIGEST		inParamDigest;
    TPM_BOOL		auditStatus;		/* audit the ordinal */
    TPM_BOOL		transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL		authHandleValid = FALSE;
    TPM_AUTH_SESSION_DATA *auth_session_data;		/* session data for authHandle */
    TPM_SECRET		*hmacKey;
    TPM_BOOL		writeAllNV = FALSE;	/* flag to write back NV */

    /* output parameters */
    uint32_t		outParamStart;		/* starting point of outParam's */
    uint32_t		outParamEnd;		/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;

    printf("TPM_Process_DisablePubekRead: Ordinal Entry\n");
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag1(tag);
    }
    /* get the 'below the line' authorization parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					ownerAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_DisablePubekRead: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* Verify that the TPM Owner authorizes the command and all of the input, on error return
       TPM_AUTHFAIL. */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_OWNER,
					      ordinal,
					      NULL,
					      &(tpm_state->tpm_permanent_data.ownerAuth), /* OIAP */
					      tpm_state->tpm_permanent_data.ownerAuth);	  /* OSAP */
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* owner HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					ownerAuth);		/* Authorization digest for input */
    }
    /* 1. This capability sets the TPM_PERMANENT_FLAGS -> readPubek flag to FALSE. */
    if (returnCode == TPM_SUCCESS) {
	TPM_SetCapability_Flag(&writeAllNV,					/* altered */
			       &(tpm_state->tpm_permanent_flags.readPubek),	/* flag */
			       FALSE);						/* value */
	printf("TPM_Process_DisablePubekRead: readPubek now %02x\n",
	       tpm_state->tpm_permanent_flags.readPubek);
	/* save the permanent flags structure to NVRAM */
	returnCode = TPM_PermanentAll_NVStore(tpm_state,
					      writeAllNV,
					      returnCode);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_DisablePubekRead: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    /* no outParam's, set authorization response data */
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,	/* owner HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, terminate the session. */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, authHandle);
    }
    return rcf;
}

/* 27.6 TPM_OwnerReadPubek rev 94

   Return the endorsement key public portion. This is authorized by the TPM Owner.
*/

TPM_RESULT TPM_Process_OwnerReadPubek(tpm_state_t *tpm_state,
				      TPM_STORE_BUFFER *response,
				      TPM_TAG tag,
				      uint32_t paramSize,		/* of remaining parameters*/
				      TPM_COMMAND_CODE ordinal,
				      unsigned char *command,
				      TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_AUTHHANDLE	authHandle;	/* The authorization handle used for owner authorization. */
    TPM_NONCE		nonceOdd;	/* Nonce generated by system associated with authHandle */
    TPM_BOOL	continueAuthSession = TRUE;	/* The continue use flag for the authorization
						   handle */
    TPM_AUTHDATA	ownerAuth;	/* The authorization digest for inputs and owner
					   authorization. HMAC key: ownerAuth. */
  
    /* processing parameters */
    unsigned char *	inParamStart;		/* starting point of inParam's */
    unsigned char *	inParamEnd;		/* ending point of inParam's */
    TPM_DIGEST		inParamDigest;
    TPM_BOOL		auditStatus;		/* audit the ordinal */
    TPM_BOOL		transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL		authHandleValid = FALSE;
    TPM_AUTH_SESSION_DATA *auth_session_data;	/* session data for authHandle */
    TPM_SECRET		*hmacKey;
    const unsigned char *pubEndorsementKeyStreamBuffer;
    uint32_t		pubEndorsementKeyStreamLength;

    /* output parameters */
    uint32_t		outParamStart;			/* starting point of outParam's */
    uint32_t		outParamEnd;			/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_STORE_BUFFER	pubEndorsementKeyStream;	/* The public endorsement key */

    printf("TPM_Process_OwnerReadPubek: Ordinal Entry\n");
    TPM_Sbuffer_Init(&pubEndorsementKeyStream); /* freed @1 */
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag1(tag);
    }
    /* get the 'below the line' authorization parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					ownerAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_OwnerReadPubek: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* 1. Validate the TPM Owner authorization to execute this command */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_OWNER,
					      ordinal,
					      NULL,
					      &(tpm_state->tpm_permanent_data.ownerAuth), /* OIAP */
					      tpm_state->tpm_permanent_data.ownerAuth);	  /* OSAP */
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* owner HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					ownerAuth);		/* Authorization digest for input */
    }
    /* serialize the TPM_PUBKEY components of the EK */
    if (returnCode == TPM_SUCCESS) {
	returnCode =
	    TPM_Key_StorePubkey(&pubEndorsementKeyStream,		/* output */
				&pubEndorsementKeyStreamBuffer,		/* output */
				&pubEndorsementKeyStreamLength,		/* output */
				&(tpm_state->tpm_permanent_data.endorsementKey));	/* input */
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_OwnerReadPubek: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* 2. Export the PUBEK */
	    if (returnCode == TPM_SUCCESS) {
		returnCode = TPM_Sbuffer_Append(response,
						pubEndorsementKeyStreamBuffer,
						pubEndorsementKeyStreamLength);
	    }
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    /* no outParam's, set authorization response data */
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* owner HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, terminate the session.  */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, authHandle);
    }
    /*
      cleanup
    */
    TPM_Sbuffer_Delete(&pubEndorsementKeyStream);	/* @1 */
    return rcf;
}

/* 27.1.1 TPM_EvictKey rev 87

   The key commands are deprecated as the new way to handle keys is to use the standard context
   commands.  So TPM_EvictKey is now handled by TPM_FlushSpecific, TPM_TerminateHandle by
   TPM_FlushSpecific.

   The TPM will invalidate the key stored in the specified handle and return the space to the
   available internal pool for subsequent query by TPM_GetCapability and usage by TPM_LoadKey. If
   the specified key handle does not correspond to a valid key, an error will be returned.
*/

TPM_RESULT TPM_Process_EvictKey(tpm_state_t *tpm_state,
				TPM_STORE_BUFFER *response,
				TPM_TAG tag,
				uint32_t paramSize,		/* of remaining parameters*/
				TPM_COMMAND_CODE ordinal,
				unsigned char *command,
				TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_KEY_HANDLE		evictHandle;	/* The handle of the key to be evicted. */

    /* processing parameters */
    unsigned char *		inParamStart;		/* starting point of inParam's */
    unsigned char *		inParamEnd;		/* ending point of inParam's */
    TPM_DIGEST			inParamDigest;
    TPM_BOOL			auditStatus;		/* audit the ordinal */
    TPM_BOOL			transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_KEY_HANDLE_ENTRY	*tpm_key_handle_entry;	/* table entry for the evictHandle */

    /* output parameters */
    uint32_t		outParamStart;		/* starting point of outParam's */
    uint32_t		outParamEnd;		/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;

    printf("TPM_Process_EvictKey: Ordinal Entry\n");
    /*
      get inputs
    */
    /* get evictHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&evictHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag0(tag);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_EvictKey: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /*
      Processing
    */
    /* New 1.2 functionality
       The command must check the status of the ownerEvict flag for the key and if the flag is TRUE
       return TPM_KEY_CONTROL_OWNER
    */
    /* evict the key stored in the specified handle */
    /* get the TPM_KEY_HANDLE_ENTRY */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_EvictKey: Evicting handle %08x\n", evictHandle);
	returnCode = TPM_KeyHandleEntries_GetEntry(&tpm_key_handle_entry,
						   tpm_state->tpm_key_handle_entries,
						   evictHandle);
	if (returnCode != TPM_SUCCESS) {
	    printf("TPM_Process_EvictKey: Error, key handle %08x not found\n",
		   evictHandle);
	}
    }
    /* If tpm_key_handle_entry -> ownerEvict is TRUE return TPM_KEY_OWNER_CONTROL */
    if (returnCode == TPM_SUCCESS) {
	if (tpm_key_handle_entry->keyControl & TPM_KEY_CONTROL_OWNER_EVICT) {
	    printf("TPM_Process_EvictKey: Error, keyHandle specifies owner evict\n");
	    returnCode = TPM_KEY_OWNER_CONTROL;
	}
    }
    /* delete the entry, delete the key structure, and free the key */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntry_FlushSpecific(tpm_state, tpm_key_handle_entry);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_EvictKey: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    return rcf;
}

/* 14.5 TPM_OwnerReadInternalPub rev 87

   A TPM Owner authorized command that returns the public portion of the EK or SRK.

   The keyHandle parameter is included in the incoming session authorization to prevent 
   alteration of the value, causing a different key to be read.	 Unlike most key handles, which 
   can be mapped by higher layer software, this key handle has only two fixed values.

*/

TPM_RESULT TPM_Process_OwnerReadInternalPub(tpm_state_t *tpm_state,
					    TPM_STORE_BUFFER *response,
					    TPM_TAG tag,
					    uint32_t paramSize,	     /* of remaining parameters */
					    TPM_COMMAND_CODE ordinal,
					    unsigned char *command,
					    TPM_TRANSPORT_INTERNAL *transportInternal)
{
    TPM_RESULT	rcf = 0;			/* fatal error precluding response */
    TPM_RESULT	returnCode = TPM_SUCCESS;	/* command return code */

    /* input parameters */
    TPM_KEY_HANDLE keyHandle;	/* Handle for either PUBEK or SRK */
    TPM_AUTHHANDLE authHandle;	/* The authorization session handle used for owner
				   authentication. */
    TPM_NONCE nonceOdd;		/* Nonce generated by system associated with authHandle */
    TPM_BOOL continueAuthSession = TRUE;	/* The continue use flag for the authorization
						   session handle */
    TPM_AUTHDATA ownerAuth;	/* The authorization session digest for inputs and owner
				   authentication.  HMAC key: ownerAuth. */

    /* processing parameters */
    unsigned char *	inParamStart;		/* starting point of inParam's */
    unsigned char *	inParamEnd;		/* ending point of inParam's */
    TPM_DIGEST		inParamDigest;
    TPM_BOOL		auditStatus;		/* audit the ordinal */
    TPM_BOOL		transportEncrypt;	/* wrapped in encrypted transport session */
    TPM_BOOL		authHandleValid = FALSE;
    TPM_AUTH_SESSION_DATA *auth_session_data;	/* session data for authHandle */
    TPM_SECRET		*hmacKey;
    TPM_KEY		*readKey = NULL;	/* key to be read back */
    const unsigned char *stream;
    uint32_t		stream_size;

    /* output parameters */
    uint32_t		outParamStart;		/* starting point of outParam's */
    uint32_t		outParamEnd;		/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;

    printf("TPM_Process_OwnerReadInternalPub: Ordinal Entry\n");
    /*
      get inputs
    */
    /* save the starting point of inParam's for authorization and auditing */
    /* NOTE: This is a special case, where the keyHandle is part of the HMAC calculation to
       avoid a man-in-the-middle privacy attack that replaces the SRK handle with the EK
       handle. */
    inParamStart = command;
    /*	get keyHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&keyHandle, &command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_OwnerReadInternalPub: keyHandle %08x\n", keyHandle);
    }
    /* save the ending point of inParam's for authorization and auditing */
    inParamEnd = command;
    /* digest the input parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_GetInParamDigest(inParamDigest,	/* output */
					  &auditStatus,		/* output */
					  &transportEncrypt,	/* output */
					  tpm_state,
					  tag,
					  ordinal,
					  inParamStart,
					  inParamEnd,
					  transportInternal);
    }
    /* check state */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckState(tpm_state, tag, TPM_CHECK_ALL);
    }
    /* check tag */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_CheckRequestTag1(tag);
    }
    /* get the 'below the line' authorization parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					ownerAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_OwnerReadInternalPub: Error, command has %u extra bytes\n",
		   paramSize);
	    returnCode = TPM_BAD_PARAM_SIZE;
	}
    }
    /* do not terminate sessions if the command did not parse correctly */
    if (returnCode != TPM_SUCCESS) {
	authHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* 1. Validate the parameters and TPM Owner AuthData for this command */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_OWNER,
					      ordinal,
					      NULL,
					      &(tpm_state->tpm_permanent_data.ownerAuth), /* OIAP */
					      tpm_state->tpm_permanent_data.ownerAuth);	  /* OSAP */
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* owner HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					ownerAuth);		/* Authorization digest for input */
    }
    if (returnCode == TPM_SUCCESS) {
	/* 2. If keyHandle is TPM_KH_EK */
	if (keyHandle == TPM_KH_EK) {
	    /* a. Set publicPortion to PUBEK */
	    printf("TPM_Process_OwnerReadInternalPub: Reading EK\n");
	    readKey = &(tpm_state->tpm_permanent_data.endorsementKey);
	}
	/* 3. Else If keyHandle is TPM_KH_SRK */
	else if (keyHandle == TPM_KH_SRK) {
	    /* a. Set publicPortion to the TPM_PUBKEY of the SRK */
	    printf("TPM_Process_OwnerReadInternalPub: Reading SRK\n");
	    readKey = &(tpm_state->tpm_permanent_data.srk);
	}
	/* 4. Else return TPM_BAD_PARAMETER */
	else {
	    printf("TPM_Process_OwnerReadInternalPub: Error, invalid keyHandle %08x\n",
		   keyHandle);
	    returnCode = TPM_BAD_PARAMETER;
	}
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_OwnerReadInternalPub: Ordinal returnCode %08x %u\n",
	       returnCode, returnCode);
	rcf = TPM_Sbuffer_StoreInitialResponse(response, tag, returnCode);
    }
    /* success response, append the rest of the parameters.  */
    if (rcf == 0) {
	if (returnCode == TPM_SUCCESS) {
	    /* checkpoint the beginning of the outParam's */
	    outParamStart = response->buffer_current - response->buffer;
	    /* 5. Export the public key of the referenced key */
	    if (returnCode == TPM_SUCCESS) {
		returnCode = TPM_Key_StorePubkey(response, &stream, &stream_size, readKey);
	    }
	    /* checkpoint the end of the outParam's */
	    outParamEnd = response->buffer_current - response->buffer;
	}
	/* digest the above the line output parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_GetOutParamDigest(outParamDigest,	/* output */
					       auditStatus,	/* input audit status */
					       transportEncrypt,
					       tag,			
					       returnCode,
					       ordinal,		/* command ordinal */
					       response->buffer + outParamStart,	/* start */
					       outParamEnd - outParamStart);	/* length */
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    /* no outParam's, set authorization response data */
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* owner HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* audit if required */
	if ((returnCode == TPM_SUCCESS) && auditStatus) {
	    returnCode = TPM_ProcessAudit(tpm_state,
					  transportEncrypt,
					  inParamDigest,
					  outParamDigest,
					  ordinal);
	}
	/* adjust the initial response */
	rcf = TPM_Sbuffer_StoreFinalResponse(response, returnCode, tpm_state);
    }
    /* if there was an error, terminate the session. */
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueAuthSession) &&
	authHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, authHandle);
    }
    /*
      cleanup
    */
    return rcf;
}