summaryrefslogtreecommitdiffstats
path: root/src/tpm12/tpm_storage.c
blob: c3cd1acc6438f946724099880330d42b1786dd4a (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
/********************************************************************************/
/*										*/
/*				Storage Functions				*/
/*			     Written by Ken Goldman				*/
/*		       IBM Thomas J. Watson Research Center			*/
/*	      $Id: tpm_storage.c 4442 2011-02-14 20:20:01Z 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 <stdlib.h>
#include <string.h>

#include "tpm_auth.h"
#include "tpm_cryptoh.h"
#include "tpm_crypto.h"
#include "tpm_debug.h"
#include "tpm_digest.h"
#include "tpm_error.h"
#include "tpm_io.h"
#include "tpm_key.h"
#include "tpm_memory.h"
#include "tpm_nonce.h"
#include "tpm_pcr.h"
#include "tpm_process.h"
#include "tpm_secret.h"
#include "tpm_structures.h"
#include "tpm_ver.h"

#include "tpm_storage.h"

/* local function prototypes */

static TPM_RESULT TPM_SealCryptCommon(BYTE **o1,
				      TPM_ADIP_ENC_SCHEME adipEncScheme,
				      TPM_SIZED_BUFFER *inData,
				      TPM_AUTH_SESSION_DATA *auth_session_data,
				      TPM_NONCE nonceOdd);

static TPM_RESULT TPM_LoadKeyCommon(TPM_KEY_HANDLE	*inKeyHandle,
				    TPM_BOOL		*key_added,
				    TPM_SECRET		**hmacKey,
				    TPM_AUTH_SESSION_DATA	**auth_session_data,
				    tpm_state_t		*tpm_state,
				    TPM_TAG		tag,
				    TPM_COMMAND_CODE	ordinal,
				    TPM_KEY_HANDLE	parentHandle,
				    TPM_KEY		*inKey,
				    TPM_DIGEST		inParamDigest,
				    TPM_AUTHHANDLE	authHandle,
				    TPM_NONCE		nonceOdd,
				    TPM_BOOL		continueAuthSession,
				    TPM_AUTHDATA	parentAuth);

/*
  TPM_BOUND_DATA
*/

/* TPM_BoundData_Init()

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

void TPM_BoundData_Init(TPM_BOUND_DATA *tpm_bound_data)
{
    printf(" TPM_BoundData_Init:\n");
    TPM_StructVer_Init(&(tpm_bound_data->ver));
    tpm_bound_data->payload = TPM_PT_BIND;
    tpm_bound_data->payloadDataSize = 0;
    tpm_bound_data->payloadData = NULL;
    return;
}

/* TPM_BoundData_Load()

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

TPM_RESULT TPM_BoundData_Load(TPM_BOUND_DATA *tpm_bound_data,
			      unsigned char **stream,
			      uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_BoundData_Load:\n");
    if (rc == 0) {
	rc = TPM_StructVer_Load(&(tpm_bound_data->ver), stream, stream_size);
    }
    /* check ver immediately to ease debugging */
    if (rc == 0) {
	rc = TPM_StructVer_CheckVer(&(tpm_bound_data->ver));
    }
    if (rc == 0) {
	rc = TPM_Load8(&(tpm_bound_data->payload), stream, stream_size);
    }
    if ((rc == 0) && (*stream_size > 0)){
	/* There is no payloadData size in the serialized data.	 Assume it consumes the rest of the
	   stream */
	tpm_bound_data->payloadDataSize = *stream_size;
	rc = TPM_Malloc(&(tpm_bound_data->payloadData), tpm_bound_data->payloadDataSize);
    }
    if ((rc == 0) && (*stream_size > 0)){
	memcpy(tpm_bound_data->payloadData, *stream, tpm_bound_data->payloadDataSize);
	*stream += tpm_bound_data->payloadDataSize;
	*stream_size -= tpm_bound_data->payloadDataSize;
    }
    return rc;
}

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

   This structure serialization assumes that the payloadDataSize member indicates the size of
   payloadData.
*/

TPM_RESULT TPM_BoundData_Store(TPM_STORE_BUFFER *sbuffer,
			       const TPM_BOUND_DATA *tpm_bound_data)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_BoundData_Store:\n");
    if (rc == 0) {
	rc = TPM_StructVer_Store(sbuffer, &(tpm_bound_data->ver));
    }
    if (rc == 0) {
	rc = TPM_Sbuffer_Append(sbuffer, &(tpm_bound_data->payload), sizeof(TPM_PAYLOAD_TYPE));
    }
    if (rc == 0) {
	rc = TPM_Sbuffer_Append(sbuffer, tpm_bound_data->payloadData,
				tpm_bound_data->payloadDataSize);
    }
    return rc;
}
#endif

/* TPM_BoundData_Delete()

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

void TPM_BoundData_Delete(TPM_BOUND_DATA *tpm_bound_data)
{
    printf(" TPM_BoundData_Delete:\n");
    if (tpm_bound_data != NULL) {
	free(tpm_bound_data->payloadData);
	TPM_BoundData_Init(tpm_bound_data);
    }
    return;
}

/*
  TPM_SEALED_DATA
*/

/* TPM_SealedData_Init()

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

void TPM_SealedData_Init(TPM_SEALED_DATA *tpm_sealed_data)
{
    printf(" TPM_SealedData_Init:\n");
    tpm_sealed_data->payload = TPM_PT_SEAL;
    TPM_Secret_Init(tpm_sealed_data->authData);
    TPM_Secret_Init(tpm_sealed_data->tpmProof);
    TPM_Digest_Init(tpm_sealed_data->storedDigest);
    TPM_SizedBuffer_Init(&(tpm_sealed_data->data));
    return;
}

/* TPM_SealedData_Load()

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

TPM_RESULT TPM_SealedData_Load(TPM_SEALED_DATA *tpm_sealed_data,
			       unsigned char **stream,
			       uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_SealedData_Load:\n");
    /* load payload */
    if (rc == 0) {
	rc = TPM_Load8(&(tpm_sealed_data->payload), stream, stream_size);
    }
    /* load authData */
    if (rc == 0) {
	rc = TPM_Secret_Load(tpm_sealed_data->authData, stream, stream_size);
    }
    /* load tpmProof */
    if (rc == 0) {
	rc = TPM_Secret_Load(tpm_sealed_data->tpmProof, stream, stream_size);
    }
    /* load storedDigest */
    if (rc == 0) {
	rc = TPM_Digest_Load(tpm_sealed_data->storedDigest, stream, stream_size);
    }
    /* load dataSize and data  */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Load(&(tpm_sealed_data->data), stream, stream_size);
    }
    return rc;
}

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

TPM_RESULT TPM_SealedData_Store(TPM_STORE_BUFFER *sbuffer,
				const TPM_SEALED_DATA *tpm_sealed_data)
{
    TPM_RESULT		rc = 0;
    printf(" TPM_SealedData_Store:\n");
    /* store payload */
    if (rc == 0) {
	rc = TPM_Sbuffer_Append(sbuffer, &(tpm_sealed_data->payload), sizeof(TPM_PAYLOAD_TYPE));
    }
    /* store authData */
    if (rc == 0) {
	rc = TPM_Secret_Store(sbuffer, tpm_sealed_data->authData);
    }
    /* store tpmProof */
    if (rc == 0) {
	rc = TPM_Secret_Store(sbuffer, tpm_sealed_data->tpmProof);
    }
    /* store storedDigest */
    if (rc == 0) {
	rc = TPM_Digest_Store(sbuffer, tpm_sealed_data->storedDigest);
    }
    /* store dataSize and data	*/
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_sealed_data->data));
    }
    return rc;
}

/* TPM_SealedData_Delete()

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

void TPM_SealedData_Delete(TPM_SEALED_DATA *tpm_sealed_data)
{
    printf(" TPM_SealedData_Delete:\n");
    if (tpm_sealed_data != NULL) {
	TPM_SizedBuffer_Delete(&(tpm_sealed_data->data));
	TPM_SealedData_Init(tpm_sealed_data);
    }
    return;
}

/* TPM_SealedData_GenerateEncData() generates an enc_data structure by serializing the
   TPM_SEALED_DATA structure and encrypting the result using the public key.
*/

TPM_RESULT TPM_SealedData_GenerateEncData(TPM_SIZED_BUFFER *enc_data,
					  const TPM_SEALED_DATA *tpm_sealed_data,
					  TPM_KEY *tpm_key)
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	sbuffer;		/* TPM_SEALED_DATA serialization */

    printf(" TPM_SealedData_GenerateEncData\n");
    TPM_Sbuffer_Init(&sbuffer);			/* freed @1 */
    /* serialize the TPM_SEALED_DATA */
    if (rc == 0) {
	rc = TPM_SealedData_Store(&sbuffer, tpm_sealed_data);
    }
    /* encrypt the TPM_SEALED_DATA serialization buffer with the public key, and place
       the result in the encData members */
    if (rc == 0) {
	rc = TPM_RSAPublicEncryptSbuffer_Key(enc_data, &sbuffer, tpm_key);
    }
    TPM_Sbuffer_Delete(&sbuffer);	/* @1 */
    return rc;
}

/* TPM_SealedData_DecryptEncData() decrypts the enc_data using the private key.	 The
   result is deserialized and stored in the TPM_SEALED_DATA structure.

*/

TPM_RESULT TPM_SealedData_DecryptEncData(TPM_SEALED_DATA *tpm_sealed_data,	/* result */
					 TPM_SIZED_BUFFER *enc_data,	/* encrypted input */
					 TPM_KEY *tpm_key)		/* key for decrypting */
{
    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_SealedData_DecryptEncData:\n");
    /* allocate space for the decrypted data */
    if (rc == 0) {
	rc = TPM_RSAPrivateDecryptMalloc(&decryptData,		/* decrypted data */
					 &decryptDataLength,	/* actual size of decrypted data */
					 enc_data->buffer,	/* encrypted data */
					 enc_data->size,	/* encrypted data size */
					 tpm_key);
    }
    /* load the TPM_SEALED_DATA structure from the decrypted data stream */
    if (rc == 0) {
	/* use temporary variables, because TPM_SealedData_Load() moves the stream */
	stream = decryptData;
	stream_size = decryptDataLength;
	rc = TPM_SealedData_Load(tpm_sealed_data, &stream, &stream_size);
    }
    free(decryptData);		/* @1 */
    return rc;
}


/*
  TPM_STORED_DATA
*/

/* TPM_StoredData_Init()

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

void TPM_StoredData_Init(TPM_STORED_DATA *tpm_stored_data,
			 unsigned int version)
{
    printf(" TPM_StoredData_Init: v%u\n", version);
    if (version == 1) {
	TPM_StructVer_Init(&(tpm_stored_data->ver));
    }
    else {
	((TPM_STORED_DATA12 *)tpm_stored_data)->tag = TPM_TAG_STORED_DATA12;
	((TPM_STORED_DATA12 *)tpm_stored_data)->et = 0x0000;
    }
    TPM_SizedBuffer_Init(&(tpm_stored_data->sealInfo));
    TPM_SizedBuffer_Init(&(tpm_stored_data->encData));
    tpm_stored_data->tpm_seal_info = NULL;
    return;
}

/* TPM_StoredData_Load()

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

   This function handles both TPM_STORED_DATA and TPM_STORED_DATA12 and returns the 'version'.
*/

TPM_RESULT TPM_StoredData_Load(TPM_STORED_DATA *tpm_stored_data,
			       unsigned int *version,
			       unsigned char **stream,
			       uint32_t *stream_size)
{
    TPM_RESULT		rc = 0;

    /* Peek at the first byte to guess the version number.  The data is verified later.
       TPM_STORED_DATA is 01,01,00,00 TPM_STORED_DATA12 is 00,16,00,00 */
    if ((rc == 0) && (*stream_size > 0)) {
	if (**stream == 0x01) {
	    *version = 1;
	}
	else {
	    *version = 2;
	}
	printf(" TPM_StoredData_Load: v%u\n", *version);
    }	 
    /* 1.1 load ver */
    if ((rc == 0) && (*version == 1)) {
	rc = TPM_StructVer_Load(&(tpm_stored_data->ver), stream, stream_size);
    }
    /* 1.2 load tag */
    if ((rc == 0) && (*version != 1)) {
	rc = TPM_Load16(&(((TPM_STORED_DATA12 *)tpm_stored_data)->tag), stream, stream_size);
    }
    /* 1.2 load et */
    if ((rc == 0) && (*version != 1)) {
	rc = TPM_Load16(&(((TPM_STORED_DATA12 *)tpm_stored_data)->et), stream, stream_size);
    }
    /* check the TPM_STORED_DATA structure version */
    if ((rc == 0) && (*version == 1)) {
	rc = TPM_StructVer_CheckVer(&(tpm_stored_data->ver));
    }
    /* check the TPM_STORED_DATA12 structure tag */
    if ((rc == 0) && (*version != 1)) {
	rc = TPM_StoredData_CheckTag((TPM_STORED_DATA12 *)tpm_stored_data);
    }
    /* load sealInfoSize and sealInfo */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Load(&(tpm_stored_data->sealInfo), stream, stream_size);
    }
    /* load the TPM_PCR_INFO or TPM_PCR_INFO_LONG cache */
    if (rc == 0) {
	if (*version == 1) {
	    rc = TPM_PCRInfo_CreateFromBuffer(&(tpm_stored_data->tpm_seal_info),
					      &(tpm_stored_data->sealInfo));
	}
	else {
	    rc = TPM_PCRInfoLong_CreateFromBuffer
		 (&(((TPM_STORED_DATA12 *)tpm_stored_data)->tpm_seal_info_long),
		  &(tpm_stored_data->sealInfo));
	}
    }
    /* load encDataSize and encData */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Load(&(tpm_stored_data->encData), stream, stream_size);
    }
    return rc;
}

/* TPM_StoredData_StoreClearData() serializes a TPM_STORED_DATA structure, excluding encData,
   appending results to 'sbuffer'.

   Before serializing, it serializes tpm_seal_info to sealInfoSize and sealInfo.

   This function handles both TPM_STORED_DATA and TPM_STORED_DATA12.
   
   serialize the structure to a stream contained in 'sbuffer'
   returns 0 or error codes
*/

TPM_RESULT TPM_StoredData_StoreClearData(TPM_STORE_BUFFER *sbuffer,
					 TPM_STORED_DATA *tpm_stored_data,
					 unsigned int version)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_StoredData_StoreClearData: v%u\n", version);
    /* 1.1 store ver */
    if ((rc == 0) && (version == 1)) {
	rc = TPM_StructVer_Store(sbuffer, &(tpm_stored_data->ver));
    }
    /* 1.2 store tag */
    if ((rc == 0) && (version != 1)) {
	rc = TPM_Sbuffer_Append16(sbuffer, ((TPM_STORED_DATA12 *)tpm_stored_data)->tag);
    }
    /* 1.2 store et */
    if ((rc == 0) && (version != 1)) {
	rc = TPM_Sbuffer_Append16(sbuffer, ((TPM_STORED_DATA12 *)tpm_stored_data)->et);
    }
    /* store sealInfoSize and sealInfo */
    if (rc == 0) {
	/* copy cache to sealInfoSize and sealInfo */
	if (version == 1) {
	    rc = TPM_SizedBuffer_SetStructure(&(tpm_stored_data->sealInfo),
					      tpm_stored_data->tpm_seal_info,
					      (TPM_STORE_FUNCTION_T)TPM_PCRInfo_Store);
	}
	else {
	    rc = TPM_SizedBuffer_SetStructure(&(tpm_stored_data->sealInfo),
					      tpm_stored_data->tpm_seal_info,
					      (TPM_STORE_FUNCTION_T)TPM_PCRInfoLong_Store);
	}
    }
    /* copy sealInfoSize and sealInfo to sbuffer */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_stored_data->sealInfo));
    }
    return rc;
}

/* TPM_StoredData_Store()
   
   Before serializing, it serializes tpm_seal_info to sealInfoSize and sealInfo.

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

TPM_RESULT TPM_StoredData_Store(TPM_STORE_BUFFER *sbuffer,
				TPM_STORED_DATA *tpm_stored_data,
				unsigned int version)
{
    TPM_RESULT		rc = 0;

    printf(" TPM_StoredData_Store: v%u\n", version);
    if (rc == 0) {
	rc = TPM_StoredData_StoreClearData(sbuffer, tpm_stored_data, version);
    }
    /* store encDataSize and encData */
    if (rc == 0) {
	rc = TPM_SizedBuffer_Store(sbuffer, &(tpm_stored_data->encData));
    }
    return rc;
}

/* TPM_StoredData_Delete()

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

void TPM_StoredData_Delete(TPM_STORED_DATA *tpm_stored_data,
			   unsigned int version)
{
    printf(" TPM_StoredData_Delete: v%u\n", version);
    if (tpm_stored_data != NULL) {
	TPM_SizedBuffer_Delete(&(tpm_stored_data->sealInfo));
	TPM_SizedBuffer_Delete(&(tpm_stored_data->encData));
	if (version == 1) {
	    TPM_PCRInfo_Delete(tpm_stored_data->tpm_seal_info);
	    free(tpm_stored_data->tpm_seal_info);
	}
	else {
	    TPM_PCRInfoLong_Delete((TPM_PCR_INFO_LONG *)tpm_stored_data->tpm_seal_info);
	    free(tpm_stored_data->tpm_seal_info);
	}
	TPM_StoredData_Init(tpm_stored_data, version);
    }
    return;
}

/* TPM_StoredData_CheckTag() verifies the tag and et members of a TPM_STORED_DATA12 structure

 */

TPM_RESULT TPM_StoredData_CheckTag(TPM_STORED_DATA12 *tpm_stored_data12)
{
    TPM_RESULT	rc = 0;

    printf(" TPM_StoredData_CheckTag:\n");
    if (rc == 0) {
	if (tpm_stored_data12->tag != TPM_TAG_STORED_DATA12) {
	    printf("TPM_StoredData_CheckTag: Error, tag expected %04x found %04hx\n",
		   TPM_TAG_STORED_DATA12, tpm_stored_data12->tag);
	    rc = TPM_BAD_VERSION;
	}
    }
    return rc;
}

/* TPM_StoredData_GenerateDigest() generates a TPM_DIGEST over the TPM_STORED_DATA structure
   excluding the encDataSize and encData members.
*/

TPM_RESULT TPM_StoredData_GenerateDigest(TPM_DIGEST tpm_digest,
					 TPM_STORED_DATA *tpm_stored_data,
					 unsigned int version)
{
    TPM_RESULT		rc = 0;
    TPM_STORE_BUFFER	sbuffer;	/* TPM_STORED_DATA serialization */
    
    printf(" TPM_StoredData_GenerateDigest:\n");
    TPM_Sbuffer_Init(&sbuffer);			/* freed @1 */
    /* serialize the TPM_STORED_DATA excluding the encData fields */
    if (rc == 0) {
	rc = TPM_StoredData_StoreClearData(&sbuffer, tpm_stored_data, version);
    }
    if (rc == 0) {
	rc = TPM_SHA1Sbuffer(tpm_digest, &sbuffer);
    }
    TPM_Sbuffer_Delete(&sbuffer);	/* @1 */
    return rc;
}

/*
  Processing Functions
*/

/* TPM_SealCryptCommon() rev 98

   Handles the encrypt/decrypt actions common to TPM_Sealx and TPM_Unseal

   'encrypt TRUE for encryption, FALSE for decryption

   The output o1 must be freed by the caller.
*/

static TPM_RESULT TPM_SealCryptCommon(BYTE **o1,	/* freed by caller */
				      TPM_ADIP_ENC_SCHEME adipEncScheme,
				      TPM_SIZED_BUFFER *inData,
				      TPM_AUTH_SESSION_DATA *auth_session_data,
				      TPM_NONCE nonceOdd)
{
    TPM_RESULT		rc = 0;
    BYTE		*x1;			/* XOR string, MGF1 output */
    TPM_DIGEST		ctr;			/* symmetric key algorithm CTR */

    printf(" TPM_SealCryptCommon:\n");
    x1 = NULL;					/* freed @1 */

    /* allocate for the output o1 */
    if (rc == TPM_SUCCESS) {
	rc = TPM_Malloc(o1, inData->size);	/* freed by caller */
    }
    if (rc == TPM_SUCCESS) {
	TPM_PrintFourLimit("  TPM_SealCryptCommon: input data", inData->buffer, inData->size);
    }
    switch (adipEncScheme) {
      case TPM_ET_XOR:
	printf("  TPM_SealCryptCommon: TPM_ET_XOR\n");
	if (rc == TPM_SUCCESS) {
	    /* i. Use MGF1 to create string X1 of length sealedDataSize. The inputs to MGF1 are;
	       authLastnonceEven, nonceOdd, "XOR", and authHandle -> sharedSecret. The four
	       concatenated values form the Z value that is the seed for MFG1. */
	    rc = TPM_MGF1_GenerateArray(&x1,		/* MGF1 array */
					inData->size,	/* MGF1 array length */
					
					TPM_NONCE_SIZE +
					TPM_NONCE_SIZE +
					sizeof("XOR") -1 +
					TPM_DIGEST_SIZE, /* seed length */
					
					TPM_NONCE_SIZE, auth_session_data->nonceEven,
					TPM_NONCE_SIZE, nonceOdd,
					sizeof("XOR") -1, "XOR",
					TPM_DIGEST_SIZE, auth_session_data->sharedSecret,
					0, NULL);
	}
	/* ii. Create o1 by XOR of d1 -> data and X1 */
	if (rc == TPM_SUCCESS) {
	    TPM_PrintFour("  TPM_SealCryptCommon: XOR key", x1);
	    TPM_XOR(*o1, inData->buffer, x1, inData->size);
	}
	break;
      case TPM_ET_AES128_CTR:
	printf("  TPM_SealCryptCommon: TPM_ET_AES128_CTR\n");
	/* i. Create o1 by encrypting d1 -> data using the algorithm indicated by inData ->
	   et */
	/* ii. Key is from authHandle -> sharedSecret */
	/* iii. IV is SHA-1 of (authLastNonceEven || nonceOdd) */
	if (rc == TPM_SUCCESS) {
	    rc = TPM_SHA1(ctr,
			  TPM_NONCE_SIZE, auth_session_data->nonceEven,
			  TPM_NONCE_SIZE, nonceOdd,
			  0, NULL);
	}
	if (rc == TPM_SUCCESS) {
	    TPM_PrintFour("  TPM_SealCryptCommon: AES key", auth_session_data->sharedSecret);
	    TPM_PrintFour("  TPM_SealCryptCommon: CTR", ctr);
	    rc = TPM_SymmetricKeyData_CtrCrypt(*o1,				/* output data */
					       inData->buffer,			/* input data */
					       inData->size,			/* data size */
					       auth_session_data->sharedSecret, /* key */
					       TPM_SECRET_SIZE,			/* key size */
					       ctr,				/* CTR */
					       TPM_DIGEST_SIZE);		/* CTR size */
	}
	break;
      default:
	printf("TPM_SealCryptCommon: Error, unsupported adipEncScheme %02x\n", adipEncScheme);
	rc = TPM_INAPPROPRIATE_ENC;
	break;
    }
    if (rc == 0) {
	TPM_PrintFour("  TPM_SealCryptCommon: output data", *o1);
	
    }
    free(x1);				/* @1 */
    return rc;
}

/* 10.1 TPM_Seal rev 110

   The SEAL operation allows software to explicitly state the future "trusted" configuration that
   the platform must be in for the secret to be revealed. The SEAL operation also implicitly
   includes the relevant platform configuration (PCR-values) when the SEAL operation was
   performed. The SEAL operation uses the tpmProof value to BIND the blob to an individual TPM.

   TPM_Seal is used to encrypt private objects that can only be decrypted using TPM_Unseal.
*/

TPM_RESULT TPM_Process_Seal(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_KEY_HANDLE	keyHandle;	/* Handle of a loaded key that can perform seal
					   operations. */
    TPM_ENCAUTH		encAuth;	/* The encrypted authorization data for the sealed data. */
    TPM_SIZED_BUFFER	pcrInfo;	/* The PCR selection information. The caller MAY use
					   TPM_PCR_INFO_LONG. */
    TPM_SIZED_BUFFER	inData;		/* The data to be sealed to the platform and any specified
					   PCRs */
    TPM_AUTHHANDLE	authHandle;	/* The authorization handle used for keyHandle
					   authorization. Must be an OS_AP session for this
					   command. */
    TPM_NONCE		nonceOdd;	/* Nonce generated by system associated with authHandle */
    TPM_BOOL		continueAuthSession = TRUE;	/* Ignored */
    TPM_AUTHDATA	pubAuth;	/* The authorization digest for inputs and keyHandle. HMAC
					   key: key.usageAuth. */

    /* 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_SECRET			*hmacKey;
    TPM_KEY			*key = NULL;		/* the key specified by keyHandle */
    TPM_SECRET			*keyUsageAuth;
    TPM_BOOL			parentPCRStatus;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    unsigned int		v1PcrVersion = 1;		/* pcrInfo version */
    TPM_STORED_DATA12		*s1_12;
    TPM_PCR_INFO		tpm_pcr_info;		/* deserialized pcrInfo v1 */
    TPM_PCR_INFO_LONG		tpm_pcr_info_long;	/* deserialized pcrInfo v2 */
    unsigned char		*stream;
    uint32_t			stream_size;
    TPM_DIGEST			a1Auth;
    TPM_SEALED_DATA		s2SealedData;
    
    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_STORED_DATA	s1StoredData;	/* Encrypted, integrity-protected data object that is the
					   result of the TPM_Seal operation. Returned as
					   SealedData */
    
    printf("TPM_Process_Seal: Ordinal Entry\n");
    TPM_SizedBuffer_Init(&pcrInfo);			/* freed @1 */
    TPM_SizedBuffer_Init(&inData);			/* freed @2 */
    TPM_StoredData_Init(&s1StoredData, v1PcrVersion);	/* freed @3, default is v1 */
    TPM_PCRInfo_Init(&tpm_pcr_info);			/* freed @4 */
    TPM_PCRInfoLong_Init(&tpm_pcr_info_long);		/* freed @5 */
    TPM_SealedData_Init(&s2SealedData);			/* freed @6 */
    s1_12 = (TPM_STORED_DATA12 *)&s1StoredData;		/* to avoid casts */
    /*
      get inputs
    */
    /* get keyHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&keyHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get encAuth parameter */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_Seal: keyHandle %08x\n", keyHandle);
	returnCode = TPM_Authdata_Load(encAuth, &command, &paramSize);
    }
    /* get pcrInfo parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&pcrInfo, &command, &paramSize);
    }	
    /* get inData parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&inData, &command, &paramSize);
    }	
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_Seal: Sealing %u bytes\n", inData.size);
    }	
    /* 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,
					pubAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_Seal: 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
    */
    /* get the key corresponding to the keyHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&key, &parentPCRStatus, tpm_state, keyHandle,
						 FALSE,		/* not r/o, using to encrypt */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* get keyHandle -> usageAuth */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_GetUsageAuth(&keyUsageAuth, key);
    }	 
    /* get the session data */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_OSAP,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      key,
					      NULL,			/* OIAP */
					      key->tpm_store_asymkey->pubDataDigest);	/* OSAP */
    }
    /* 1. Validate the authorization to use the key pointed to by keyHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					pubAuth);		/* Authorization digest for input */
    }
    /* 2. If the inDataSize is 0 the TPM returns TPM_BAD_PARAMETER */
    if (returnCode == TPM_SUCCESS) {
	if (inData.size == 0) {
	    printf("TPM_Process_Seal: Error, inDataSize is 0\n");
	    returnCode = TPM_BAD_PARAMETER;
	}
    }
    /* 3. If the keyUsage field of the key indicated by keyHandle does not have the value
       TPM_KEY_STORAGE, the TPM must return the error code TPM_INVALID_KEYUSAGE. */
    if (returnCode == TPM_SUCCESS) {
	if (key->keyUsage != TPM_KEY_STORAGE) {
	    printf("TPM_Process_Seal: Error, key keyUsage %04hx must be TPM_KEY_STORAGE\n",
		   key->keyUsage);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 4. If the keyHandle points to a migratable key then the TPM MUST return the error code
       TPM_INVALID_KEY_USAGE. */
    if (returnCode == TPM_SUCCESS) {
	if (key->keyFlags & TPM_MIGRATABLE) {
	    printf("TPM_Process_Seal: Error, key keyFlags %08x indicates migratable\n",
		   key->keyFlags);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 5. Determine the version of pcrInfo */
    if (returnCode == TPM_SUCCESS) {
	/* a. If pcrInfoSize is 0 */
	if (pcrInfo.size == 0) {
	    v1PcrVersion = 1;			/* i. set V1 to 1  */
	}
	else {				/* b. Else */
	    /* i. Point X1 as TPM_PCR_INFO_LONG structure to pcrInfo  */
	    /* ii. If X1 -> tag is TPM_TAG_PCR_INFO_LONG  */
	    if (htons(*(uint16_t *)(pcrInfo.buffer)) == TPM_TAG_PCR_INFO_LONG) {
		v1PcrVersion = 2;			/* (1) Set V1 to 2  */
	    }
	    else {			/* iii. Else */
		v1PcrVersion = 1;			/* (1) Set V1 to 1 */
	    }
	}
	/* 6. If V1 is 1 then */
	/* a. Create S1 a TPM_STORED_DATA structure  */
	/* 7. else  */
	/* a. Create S1 a TPM_STORED_DATA12 structure  */
	/* b. Set S1 -> et to 0 */
	/* 8. Set S1 -> encDataSize to 0 */
	/* 9. Set S1 -> encData to all zeros */
	printf("TPM_Process_Seal: V%u\n", v1PcrVersion);
	TPM_StoredData_Init(&s1StoredData, v1PcrVersion);
	/* 10. Set S1 -> sealInfoSize to pcrInfoSize */
	/* NOTE This step is unnecessary.  If pcrInfoSize is 0, sealInfoSize is already initialized
	   to 0.  If pcrInfoSize is non-zero, sealInfoSize is the result of serialization of the
	   tpm_seal_info member, which is either a TPM_PCR_INFO or a TPM_PCR_INFO_LONG */
    }
    /* 11. If pcrInfoSize is not 0 then */
    if ((returnCode == TPM_SUCCESS) && (pcrInfo.size != 0)) {
	printf("TPM_Process_Seal: Creating PCR digest\n");
	/* assign the stream, so pcrInfo is not altered */
	stream = pcrInfo.buffer;
	stream_size = pcrInfo.size;
	/* a. if V1 is 1 then */
	if (v1PcrVersion == 1) {
	    /* i. Validate pcrInfo as a valid TPM_PCR_INFO structure, return TPM_BADINDEX on
	       error */
	    if (returnCode == TPM_SUCCESS) {
		returnCode = TPM_PCRInfo_Load(&tpm_pcr_info, &stream, &stream_size);
		if (returnCode != 0) {
		    returnCode = TPM_BADINDEX;
		}
	    }
	    /* build the TPM_STORED_DATA S1 structure */
	    if (returnCode == TPM_SUCCESS) {
		/* ii. Set S1 -> sealInfo -> pcrSelection to pcrInfo -> pcrSelection */
		returnCode = TPM_PCRInfo_CreateFromBuffer(&(s1StoredData.tpm_seal_info), &pcrInfo);
	    }
	    /* iii. Create h1 the composite hash of the PCR selected by pcrInfo -> pcrSelection */
	    /* iv. Set S1 -> sealInfo -> digestAtCreation to h1 */
	    /* NOTE hash directly to destination.  */
	    if (returnCode == TPM_SUCCESS) {
		returnCode =
		    TPM_PCRSelection_GenerateDigest(s1StoredData.tpm_seal_info->digestAtCreation,
						    &(tpm_pcr_info.pcrSelection),
						    tpm_state->tpm_stclear_data.PCRS);
	    }
	    /* v. Set S1 -> sealInfo -> digestAtRelease to pcrInfo -> digestAtRelease */
	    /* NOTE digestAtRelease copied during TPM_PCRInfo_CreateFromBuffer() */
	}
	/* b. else (v1 is 2) */
	else {
	    /* i. Validate pcrInfo as a valid TPM_PCR_INFO_LONG structure, return TPM_BADINDEX
	       on error */
	    if (returnCode == TPM_SUCCESS) {
		returnCode = TPM_PCRInfoLong_Load(&tpm_pcr_info_long, &stream, &stream_size);
		if (returnCode != 0) {
		    returnCode = TPM_BADINDEX;
		}
	    }
	    /* build the TPM_STORED_DATA S1 structure */
	    if (returnCode == TPM_SUCCESS) {
		/* ii. Set S1 -> sealInfo -> creationPCRSelection to pcrInfo -> creationPCRSelection
		   */
		/* iii. Set S1 -> sealInfo -> releasePCRSelection to pcrInfo -> releasePCRSelection
		   */
		/* iv. Set S1 -> sealInfo -> digestAtRelease to pcrInfo -> digestAtRelease */
		/* v. Set S1 -> sealInfo -> localityAtRelease to pcrInfo -> localityAtRelease */
		/* NOTE copied during TPM_PCRInfoLong_CreateFromBuffer() */
		returnCode = TPM_PCRInfoLong_CreateFromBuffer(&(s1_12->tpm_seal_info_long),
							      &pcrInfo);
	    }
	    if (returnCode == TPM_SUCCESS) {
		/* vi. Create h2 the composite hash of the PCR selected by pcrInfo ->
		   creationPCRSelection */
		/* vii. Set S1 -> sealInfo -> digestAtCreation to h2 */
		/* NOTE hash directly to destination. */
		returnCode =
		    TPM_PCRSelection_GenerateDigest(s1_12->tpm_seal_info_long->digestAtCreation,
						    &(tpm_pcr_info_long.creationPCRSelection),
						    tpm_state->tpm_stclear_data.PCRS);
	    }
	    /* viii. Set S1 -> sealInfo -> localityAtCreation to TPM_STANY_FLAGS ->
	       localityModifier */
	    if (returnCode == TPM_SUCCESS) {
		returnCode = TPM_Locality_Set(&(s1_12->tpm_seal_info_long->localityAtCreation),
					      tpm_state->tpm_stany_flags.localityModifier);
	    }
	}
    }
    /* 12. Create a1 by decrypting encAuth according to the ADIP indicated by authHandle. */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessionData_Decrypt(a1Auth,
						 NULL,
						 encAuth,
						 auth_session_data,
						 NULL,
						 NULL,
						 FALSE);	/* even and odd */
    }
    /* 13. The TPM provides NO validation of a1. Well-known values (like all zeros) are valid and
       possible. */
    /* 14. Create S2 a TPM_SEALED_DATA structure */
    if (returnCode == TPM_SUCCESS) {
	/* a. Set S2 -> payload to TPM_PT_SEAL */
	/* NOTE: Done at TPM_SealedData_Init() */
	/* b. Set S2 -> tpmProof to TPM_PERMANENT_DATA -> tpmProof */
	TPM_Secret_Copy(s2SealedData.tpmProof, tpm_state->tpm_permanent_data.tpmProof);
	/* c. Create h3 the SHA-1 of S1 */
	/* d. Set S2 -> storedDigest to h3 */
	returnCode = TPM_StoredData_GenerateDigest(s2SealedData.storedDigest,
						   &s1StoredData, v1PcrVersion);
    }
    if (returnCode == TPM_SUCCESS) {
	/* e. Set S2 -> authData to a1 */
	TPM_Secret_Copy(s2SealedData.authData, a1Auth);
	/* f. Set S2 -> dataSize to inDataSize */
	/* g. Set S2 -> data to inData */
	returnCode = TPM_SizedBuffer_Copy(&(s2SealedData.data), &inData);
    }
    /* 15. Validate that the size of S2 can be encrypted by the key pointed to by keyHandle, return
       TPM_BAD_DATASIZE on error */
    /* 16. Create s3 the encryption of S2 using the key pointed to by keyHandle */
    /* 17. Set continueAuthSession to FALSE */
    if (returnCode == TPM_SUCCESS) {
	continueAuthSession = FALSE;
    }
    /* 18. Set S1 -> encDataSize to the size of s3 */
    /* 19. Set S1 -> encData to s3 */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SealedData_GenerateEncData(&(s1StoredData.encData), &s2SealedData, key);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_Seal: 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;
	    /* 20. Return S1 as sealedData */
	    returnCode = TPM_StoredData_Store(response, &s1StoredData, v1PcrVersion);
	    /* 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) {
	    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, or continueAuthSession is FALSE, 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_SizedBuffer_Delete(&pcrInfo);			/* @1 */
    TPM_SizedBuffer_Delete(&inData);			/* @2 */
    TPM_StoredData_Delete(&s1StoredData, v1PcrVersion);	/* @3 */
    TPM_PCRInfo_Delete(&tpm_pcr_info);			/* @4 */
    TPM_PCRInfoLong_Delete(&tpm_pcr_info_long); 	/* @5 */
    TPM_SealedData_Delete(&s2SealedData);		/* @6 */
    return rcf;
}

/* 10.7 TPM_Sealx rev 110
     
   The TPM_Sealx command works exactly like the TPM_Seal command with the additional requirement of
   encryption for the inData parameter. This command also places in the sealed blob the information
   that the TPM_Unseal also requires encryption.

   TPM_Sealx requires the use of 1.2 data structures. The actions are the same as TPM_Seal without
   the checks for 1.1 data structure usage.
*/

TPM_RESULT TPM_Process_Sealx(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_KEY_HANDLE	keyHandle;	/* Handle of a loaded key that can perform seal
					   operations. */
    TPM_ENCAUTH		encAuth;	/* The encrypted authorization data for the sealed data */
    TPM_SIZED_BUFFER	pcrInfo;	/* If 0 there are no PCR registers in use.  pcrInfo MUST use
					   TPM_PCR_INFO_LONG */
    TPM_SIZED_BUFFER	inData;		/* The data to be sealed to the platform and any specified
					   PCRs */

    TPM_AUTHHANDLE	authHandle;	/* The authorization session handle used for keyHandle
					   authorization.  Must be an OSAP session for this command.
					   */
    TPM_NONCE		nonceOdd;	/* Nonce generated by system associated with authHandle */
    TPM_BOOL		continueAuthSession = TRUE;	/* Ignored */
    TPM_AUTHDATA	pubAuth;	/* The authorization digest for inputs and keyHandle. HMAC
					   key: key.usageAuth. */

    /* 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_SECRET			*hmacKey;
    TPM_KEY			*key = NULL;			/* the key specified by keyHandle */
    TPM_SECRET			*keyUsageAuth;
    TPM_BOOL			parentPCRStatus;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */

    /* output parameters */
    uint32_t			outParamStart;	/* starting point of outParam's */
    uint32_t			outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST			outParamDigest;
    TPM_STORED_DATA12		s1StoredData;	/* Encrypted, integrity-protected data object that
						   is the result of the TPM_Seal operation. Returned
						   as SealedData */
    TPM_STORED_DATA		*s1_11;		/* 1.1 version to avoid casts */
    TPM_SEALED_DATA		s2SealedData;
    TPM_DIGEST			a1Auth;
    BYTE			*o1DecryptedData;
    
    printf("TPM_Process_Sealx: Ordinal Entry\n");
    s1_11 = (TPM_STORED_DATA *)&s1StoredData;	/* 1.1 version to avoid casts */
    TPM_SizedBuffer_Init(&pcrInfo);		/* freed @1 */
    TPM_SizedBuffer_Init(&inData);		/* freed @2 */
    TPM_StoredData_Init(s1_11, 2);		/* freed @3 */
    TPM_SealedData_Init(&s2SealedData); 	/* freed @4 */
    o1DecryptedData = NULL;			/* freed @5 */
    /*
      get inputs
    */
    /*	get keyHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&keyHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get encAuth parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Load(encAuth, &command, &paramSize);
    }
    /* get pcrInfo parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&pcrInfo, &command, &paramSize);
    }	
    /* get inData parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_SizedBuffer_Load(&inData, &command, &paramSize);
    }	
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_Sealx: Sealing %u bytes\n", inData.size);
	TPM_PrintFourLimit("TPM_Process_Sealx: Sealing data", inData.buffer, inData.size);
    }	
    /* 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,
					pubAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_Sealx: 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
    */
    /* get the key corresponding to the keyHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&key, &parentPCRStatus, tpm_state, keyHandle,
						 FALSE,		/* not r/o, using to encrypt */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* get keyHandle -> usageAuth */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_GetUsageAuth(&keyUsageAuth, key);
    }	 
    /* get the session data */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_OSAP,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      key,
					      NULL,			/* OIAP */
					      key->tpm_store_asymkey->pubDataDigest);	/* OSAP */
    }
    /* 1. Validate the authorization to use the key pointed to by keyHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					pubAuth);		/* Authorization digest for input */
    }
    /* 2. If the inDataSize is 0 the TPM returns TPM_BAD_PARAMETER */
    if (returnCode == TPM_SUCCESS) {
	if (inData.size == 0) {
	    printf("TPM_Process_Sealx: Error, inDataSize is 0\n");
	    returnCode = TPM_BAD_PARAMETER;
	}
    }
    /* 3. If the keyUsage field of the key indicated by keyHandle does not have the value
       TPM_KEY_STORAGE, the TPM must return the error code TPM_INVALID_KEYUSAGE. */
    if (returnCode == TPM_SUCCESS) {
	if (key->keyUsage != TPM_KEY_STORAGE) {
	    printf("TPM_Process_Sealx: Error, key keyUsage %04hx must be TPM_KEY_STORAGE\n",
		   key->keyUsage);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 4. If the keyHandle points to a migratable key then the TPM MUST return the error code
       TPM_INVALID_KEY_USAGE. */
    if (returnCode == TPM_SUCCESS) {
	if (key->keyFlags & TPM_MIGRATABLE) {
	    printf("TPM_Process_Sealx: Error, key keyFlags %08x indicates migratable\n",
		   key->keyFlags);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 5. Create S1 a TPM_STORED_DATA12 structure */
    /* 6. Set S1 -> encDataSize to 0 */
    /* 7. Set S1 -> encData to all zeros */
    /* NOTE: Done by TPM_StoredData_Init() */
    /* 8. Set S1 -> sealInfoSize to pcrInfoSize */
    /* NOTE This step is unnecessary.  If pcrInfoSize is 0, sealInfoSize is already initialized
       to 0.  If pcrInfoSize is non-zero, sealInfoSize is the result of serialization of the
       tpm_seal_info member, which is a TPM_PCR_INFO_LONG */
    /* 9. If pcrInfoSize is not 0 then */
    if ((returnCode == TPM_SUCCESS) && (pcrInfo.size != 0)) {
	printf("TPM_Process_Sealx: Setting sealInfo to pcrInfo\n");
	/* initializing the s -> TPM_PCR_INFO_LONG cache to the contents of pcrInfo */
	/* a. Validate pcrInfo as a valid TPM_PCR_INFO_LONG structure, return TPM_BADINDEX on
	   error */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_PCRInfoLong_CreateFromBuffer(&(s1StoredData.tpm_seal_info_long),
							  &pcrInfo);
	    if (returnCode != TPM_SUCCESS) {
		returnCode = TPM_BADINDEX;
	    }
	}
	/* b. Set S1 -> sealInfo -> creationPCRSelection to pcrInfo -> creationPCRSelection */
	/* c. Set S1 -> sealInfo -> releasePCRSelection to pcrInfo -> releasePCRSelection */
	/* d. Set S1 -> sealInfo -> digestAtRelease to pcrInfo -> digestAtRelease */
	/* e. Set S1 -> sealInfo -> localityAtRelease to pcrInfo -> localityAtRelease  */
	/* NOTE copied during TPM_PCRInfoLong_CreateFromBuffer() */
	/* f. Create h2 the composite hash of the PCR selected by pcrInfo -> creationPCRSelection */
	/* g. Set S1 -> sealInfo -> digestAtCreation to h2 */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_PCRSelection_GenerateDigest
			 (s1StoredData.tpm_seal_info_long->digestAtCreation,
			  &(s1StoredData.tpm_seal_info_long->creationPCRSelection),
			  tpm_state->tpm_stclear_data.PCRS);
	}
	/* h. Set S1 -> sealInfo -> localityAtCreation to TPM_STANY_DATA -> localityModifier */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_Locality_Set(&(s1StoredData.tpm_seal_info_long->localityAtCreation),
					  tpm_state->tpm_stany_flags.localityModifier);
	}
    }
    /* 10. Create S2 a TPM_SEALED_DATA structure */
    /* NOTE: Done at TPM_SealedData_Init() */
    /* 11.Create a1 by decrypting encAuth according to the ADIP indicated by authHandle. */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_Sealx: Decrypting encAuth\n");
	returnCode = TPM_AuthSessionData_Decrypt(a1Auth,	/* a1 even */
						 NULL,		/* a1 odd (2nd encAuth) */
						 encAuth,	/* encAuthEven */
						 auth_session_data,
						 NULL,		/* nonceOdd */
						 NULL,		/* encAuthOdd */
						 FALSE);	/* even and odd */
    }
    if (returnCode == TPM_SUCCESS) {
	TPM_PrintFour("TPM_Process_Sealx: Decrypted Auth", a1Auth);
	/* a. If authHandle indicates XOR encryption for the AuthData secrets */
	if (auth_session_data->adipEncScheme == TPM_ET_XOR) {
	    /* i. Set S1 -> et to TPM_ET_XOR || TPM_ET_KEY */
	    /* (1) TPM_ET_KEY is added because TPM_Unseal uses zero as a special value indicating no
	       encryption. */
	    s1StoredData.et = TPM_ET_XOR | TPM_ET_KEY;
	}
	/* b. Else */
	else {
	    /* i. Set S1 -> et to algorithm indicated by authHandle */
	    s1StoredData.et = auth_session_data->adipEncScheme << 8;
	}
    }
    /* 12. The TPM provides NO validation of a1. Well-known values (like all zeros) are valid and
       possible. */
    /* 13. If authHandle indicates XOR encryption */
    /* a. Use MGF1 to create string X2 of length inDataSize. The inputs to MGF1 are;
       authLastNonceEven, nonceOdd, "XOR", and authHandle -> sharedSecret. The four concatenated
       values form the Z value that is the seed for MFG1. */
    /* b. Create o1 by XOR of inData and x2 */
    /* 14. Else */
    /* a. Create o1 by decrypting inData using the algorithm indicated by authHandle */
    /* b. Key is from authHandle -> sharedSecret */
    /* c. CTR is SHA-1 of (authLastNonceEven || nonceOdd) */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_Sealx: decrypting inData\n");
	returnCode = TPM_SealCryptCommon(&o1DecryptedData,		/* freed by caller */
					 auth_session_data->adipEncScheme,
					 &inData,
					 auth_session_data,
					 nonceOdd);

   }
    /* 15. Create S2 a TPM_SEALED_DATA structure */
    if (returnCode == TPM_SUCCESS) {
	/* a. Set S2 -> payload to TPM_PT_SEAL */
	/* NOTE: Done at TPM_SealedData_Init() */
	/* b. Set S2 -> tpmProof to TPM_PERMANENT_DATA -> tpmProof */
	TPM_Secret_Copy(s2SealedData.tpmProof, tpm_state->tpm_permanent_data.tpmProof);
	/* c. Create h3 the SHA-1 of S1 */
	/* d. Set S2 -> storedDigest to h3 */
	returnCode = TPM_StoredData_GenerateDigest(s2SealedData.storedDigest, s1_11, 2);
    }
    /* e. Set S2 -> authData to a1 */
    if (returnCode == TPM_SUCCESS) {
	TPM_Secret_Copy(s2SealedData.authData, a1Auth);
	/* f. Set S2 -> dataSize to inDataSize */
	/* g. Set S2 -> data to o1 */
	returnCode = TPM_SizedBuffer_Set(&(s2SealedData.data), inData.size, o1DecryptedData);
    }
    /* 16. Validate that the size of S2 can be encrypted by the key pointed to by keyHandle, return
       */
    /* TPM_BAD_DATASIZE on error */
    /* 17. Create s3 the encryption of S2 using the key pointed to by keyHandle */
    /* 18. Set continueAuthSession to FALSE */
    if (returnCode == TPM_SUCCESS) {
	continueAuthSession = FALSE;
    }
    /* 19. Set S1 -> encDataSize to the size of s3 */
    /* 20. Set S1 -> encData to s3 */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_Sealx: Encrypting sealed data\n");
	returnCode = TPM_SealedData_GenerateEncData(&(s1StoredData.encData), &s2SealedData, key);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_Sealx: 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;
	    /* 21. Return S1 as sealedData */
	    returnCode = TPM_StoredData_Store(response, s1_11, 2);
	    /* 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) {
	    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, or continueAuthSession is FALSE, 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_SizedBuffer_Delete(&pcrInfo);		/* @1 */
    TPM_SizedBuffer_Delete(&inData);		/* @2 */
    TPM_StoredData_Delete(s1_11, 2);		/* @3 */
    TPM_SealedData_Delete(&s2SealedData);	/* @4 */
    free(o1DecryptedData);			/* @5 */
    return rcf;
}

/* 10.2 TPM_Unseal rev 110

   The TPM_Unseal operation will reveal TPM_Sealed data only if it was encrypted on this platform
   and the current configuration (as defined by the named PCR contents) is the one named as
   qualified to decrypt it.  Internally, TPM_Unseal accepts a data blob generated by a TPM_Seal
   operation. TPM_Unseal decrypts the structure internally, checks the integrity of the resulting
   data, and checks that the PCR named has the value named during TPM_Seal.  Additionally, the
   caller must supply appropriate authorization data for blob and for the key that was used to seal
   that data.
   
   If the integrity, platform configuration and authorization checks succeed, the sealed data is
   returned to the caller; otherwise, an error is generated.
*/

TPM_RESULT TPM_Process_Unseal(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_KEY_HANDLE	parentHandle;	/* Handle of a loaded key that can unseal the data. */
    TPM_STORED_DATA	inData;		/* The encrypted data generated by TPM_Seal. */
    TPM_AUTHHANDLE	authHandle;	/* The authorization handle used for parentHandle. */
    TPM_NONCE		nonceOdd;	/* Nonce generated by system associated with authHandle */
    TPM_BOOL	continueAuthSession = TRUE;	/* The continue use flag for the authorization
						   handle */
    TPM_AUTHDATA	parentAuth;	/* The authorization digest for inputs and
					   parentHandle. HMAC key: parentKey.usageAuth. */
    TPM_AUTHHANDLE	dataAuthHandle; /* The authorization handle used to authorize inData. */
    TPM_NONCE		datanonceOdd;	/* Nonce generated by system associated with
					   entityAuthHandle */
    TPM_BOOL	continueDataSession = TRUE;	/* Continue usage flag for dataAuthHandle. */
    TPM_AUTHDATA	dataAuth;	/* The authorization digest for the encrypted entity. HMAC
					   key: entity.usageAuth.  */

    /* 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_BOOL			dataAuthHandleValid = FALSE;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    TPM_AUTH_SESSION_DATA	*data_auth_session_data = NULL; /* session data for dataAuthHandle
								   */
    TPM_SECRET			*hmacKey;
    TPM_SECRET			*dataHmacKey;
    unsigned int		v1StoredDataVersion = 1;	/* version of TPM_STORED_DATA
								   inData */
    TPM_KEY			*parentKey;
    TPM_BOOL			parentPCRStatus;
    TPM_SECRET			*parentUsageAuth;
    TPM_SEALED_DATA		d1SealedData;
    TPM_DIGEST			h1StoredDataDigest;
    TPM_STORED_DATA12		*s2StoredData;
    BYTE			*o1Encrypted;			/* For ADIP encryption */
    TPM_ADIP_ENC_SCHEME		adipEncScheme;	 

    /* output parameters */
    uint32_t			outParamStart;	/* starting point of outParam's */
    uint32_t			outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST			outParamDigest;
    uint32_t			secretSize = 0; /* Decrypted data that had been sealed */
    BYTE			*secret = NULL;

    printf("TPM_Process_Unseal: Ordinal Entry\n");
    TPM_StoredData_Init(&inData, v1StoredDataVersion);	/* freed @1, default is v1 */
    TPM_SealedData_Init(&d1SealedData); 		/* freed @2 */
    o1Encrypted = NULL;					/* freed @3 */
    s2StoredData = (TPM_STORED_DATA12 *)&inData;	/* inData when it's a TPM_STORED_DATA12
							   structure */
    /*
      get inputs
    */
    /* get parentHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&parentHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get inData parameter */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_Unseal: parentHandle %08x\n", parentHandle);
	returnCode = TPM_StoredData_Load(&inData, &v1StoredDataVersion, &command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_Unseal: inData is v%u\n", v1StoredDataVersion);
    }
    /* 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_CheckRequestTag21(tag);
    }
    /* get the optional 'below the line' authorization parameters */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					parentAuth,
					&command, &paramSize);
    }
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	printf("TPM_Process_Unseal: authHandle %08x\n", authHandle);
    }
    /* get the 'below the line' authorization parameters */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthParams_Get(&dataAuthHandle,
					&dataAuthHandleValid,
					datanonceOdd,
					&continueDataSession,
					dataAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_Unseal: dataAuthHandle %08x\n", dataAuthHandle); 
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_Unseal: 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;
	dataAuthHandleValid = FALSE;
    }
    /*
      Processing
    */
    /* Verify that parentHandle points to a valid key.	Get the TPM_KEY associated with parentHandle
     */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&parentKey, &parentPCRStatus,
						 tpm_state, parentHandle,
						 FALSE,		/* not r/o, using to decrypt */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* get parentHandle -> usageAuth */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	returnCode = TPM_Key_GetUsageAuth(&parentUsageAuth, parentKey);
    }	 
    /* get the first session data */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      parentKey,
					      parentUsageAuth,			/* OIAP */
					      parentKey->tpm_store_asymkey->pubDataDigest); /*OSAP*/
    }
    /* 1. The TPM MUST validate that parentAuth authorizes the use of the key in parentHandle, on
       error return TPM_AUTHFAIL */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					parentAuth);		/* Authorization digest for input */
    }
    /* if there are no parent auth parameters */
    if ((returnCode == TPM_SUCCESS) && (tag != TPM_TAG_RQU_AUTH2_COMMAND)) {
	if (parentKey->authDataUsage != TPM_AUTH_NEVER) {
	    printf("TPM_Process_Unseal: Error, parent key authorization required\n");
	    returnCode = TPM_AUTHFAIL;
	}
    }
    /* 2. If the keyUsage field of the key indicated by parentHandle does not have the value
       TPM_KEY_STORAGE, the TPM MUST return the error code TPM_INVALID_KEYUSAGE. */
    if (returnCode == TPM_SUCCESS) {
	if (parentKey->keyUsage != TPM_KEY_STORAGE) {
	    printf("TPM_Process_Unseal: Error, key keyUsage %04hx must be TPM_KEY_STORAGE\n",
		   parentKey->keyUsage);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 3. The TPM MUST check that the TPM_KEY_FLAGS -> Migratable flag has the value FALSE in the
       key indicated by parentKeyHandle. If not, the TPM MUST return the error code
       TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	if (parentKey->keyFlags & TPM_MIGRATABLE) {
	    printf("TPM_Process_Unseal: Error, key keyFlags %08x indicates migratable\n",
		   parentKey->keyFlags);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 4. Determine the version of inData */
    /* a. If inData -> tag = TPM_TAG_STORED_DATA12 */
    /* i. Set V1 to 2 */
    /* ii. Map S2 a TPM_STORED_DATA12 structure to inData */
    /* b. Else If inData -> ver = 1.1 */
    /* i. Set V1 to 1 */
    /* ii. Map S2 a TPM_STORED_DATA structure to inData */
    /* c. Else */
    /* i. Return TPM_BAD_VERSION */
    /* NOTE: Done during TPM_StoredData_Load() */
    /* The extra indent of error checking is required because the next steps all return
       TPM_NOTSEALED_BLOB on error */
    if (returnCode == TPM_SUCCESS) {
	/* 5. Create d1 by decrypting S2 -> encData using the key pointed to by parentHandle */
	printf("TPM_Process_Unseal: Decrypting encData\n");
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_SealedData_DecryptEncData(&d1SealedData,	/* TPM_SEALED_DATA */
						       &(inData.encData),
						       parentKey);	
	}
	/* 6. Validate d1 */
	/* a. d1 MUST be a TPM_SEALED_DATA structure */
	/* NOTE Done during TPM_SealedData_DecryptEncData() */
	/* b. d1 -> tpmProof MUST match TPM_PERMANENT_DATA -> tpmProof */
	if (returnCode == TPM_SUCCESS) {
	    printf("TPM_Process_Unseal: Sealed data size %u\n", d1SealedData.data.size);
	    TPM_PrintFour("TPM_Process_Unseal: Sealed data", d1SealedData.data.buffer);
	    printf("TPM_Process_Unseal: Checking tpmProof\n");
	    returnCode = TPM_Secret_Compare(d1SealedData.tpmProof,
					    tpm_state->tpm_permanent_data.tpmProof);
	}
	if (returnCode == TPM_SUCCESS) {
	    /* c. Set S2 -> encDataSize to 0 */
	    /* d. Set S2 -> encData to all zeros */
	    /* NOTE: This would be done at cleanup */
	    TPM_SizedBuffer_Delete(&(inData.encData));
	    /* e. Create h1 the SHA-1 of S2 */
	    returnCode = TPM_StoredData_GenerateDigest(h1StoredDataDigest,
						       &inData, v1StoredDataVersion);
	}
	/* f. d1 -> storedDigest MUST match h1 */
	if (returnCode == TPM_SUCCESS) {
	    printf("TPM_Process_Unseal: Checking storedDigest\n");
	    returnCode = TPM_Digest_Compare(d1SealedData.storedDigest, h1StoredDataDigest);
	}
	/* g. d1 -> payload MUST be TPM_PT_SEAL */
	if (returnCode == TPM_SUCCESS) {
	    if (d1SealedData.payload != TPM_PT_SEAL) {
		printf("TPM_Process_Unseal: Error, payload %02x not TPM_PT_SEAL\n",
		       d1SealedData.payload);
		returnCode = TPM_NOTSEALED_BLOB;
	    }
	}
	/* h. Any failure MUST return TPM_NOTSEALED_BLOB */
	if (returnCode != TPM_SUCCESS) {
	    returnCode = TPM_NOTSEALED_BLOB;
	}
    }
    /* 7. If S2 -> sealInfo is not 0 then */
    /* NOTE: Done by _CheckDigest() */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_Unseal: Checking PCR digest\n");
	/* a. If V1 is 1 then */
	if (v1StoredDataVersion == 1) {
	    /* i. Validate that S2 -> pcrInfo is a valid TPM_PCR_INFO structure */
	    /* NOTE: Done during TPM_StoredData_Load() */
	    /* ii. Create h2 the composite hash of the PCR selected by S2 -> pcrInfo -> pcrSelection
	     */
	    /* c. Compare h2 with S2 -> pcrInfo -> digestAtRelease, on mismatch return
	       TPM_WRONGPCRVALUE */
	    returnCode = TPM_PCRInfo_CheckDigest(inData.tpm_seal_info,
						 tpm_state->tpm_stclear_data.PCRS); /* PCR array */
	}
	/* b. If V1 is 2 then */
	else {
	    /* i. Validate that S2 -> pcrInfo is a valid TPM_PCR_INFO_LONG structure */
	    /* NOTE: Done during TPM_StoredData_Load() */
	    /* ii. Create h2 the composite hash of the PCR selected by S2 -> pcrInfo ->
	       releasePCRSelection */
	    /* iii. Check that S2 -> pcrInfo -> localityAtRelease for TPM_STANY_DATA ->
	       localityModifier is TRUE */
	    /* (1) For example if TPM_STANY_DATA -> localityModifier was 2 then S2 -> pcrInfo ->
	       localityAtRelease -> TPM_LOC_TWO would have to be TRUE */
	    /* c. Compare h2 with S2 -> pcrInfo -> digestAtRelease, on mismatch return
	       TPM_WRONGPCRVALUE */
	    returnCode =
		TPM_PCRInfoLong_CheckDigest(s2StoredData->tpm_seal_info_long,
					    tpm_state->tpm_stclear_data.PCRS,	/* PCR array */
					    tpm_state->tpm_stany_flags.localityModifier);
	}
    }
    /* 8. The TPM MUST validate authorization to use d1 by checking that the HMAC calculation
       using d1 -> authData as the shared secret matches the dataAuth. Return TPM_AUTHFAIL on
       mismatch. */
    /* get the second session data */
    /* NOTE: While OSAP isn't specifically excluded, there is currently no way to set up an OSAP
       session using TPM_SEALED_DATA as the entity */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&data_auth_session_data,
					      &dataHmacKey,
					      tpm_state,
					      dataAuthHandle,
					      TPM_PID_OIAP,	/* currently require OIAP */
					      0,		/* OSAP entity type */
					      ordinal,
					      NULL,
					      &(d1SealedData.authData), /* OIAP */
					      NULL);			/* OSAP */
    }
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Auth2data_Check(tpm_state,
					 *dataHmacKey,		/* HMAC key */
					 inParamDigest,
					 data_auth_session_data, /* authorization session */
					 datanonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					 continueDataSession,
					 dataAuth);		/* Authorization digest for input */
    }
    if (returnCode == TPM_SUCCESS) {
	/* 9. If V1 is 2 and S2 -> et specifies encryption (i.e. is not all zeros) then */
	if ((v1StoredDataVersion == 2) && (s2StoredData->et != 0x0000)) {
	    /* a. If tag is not TPM_TAG_RQU_AUTH2_COMMAND, return TPM_AUTHFAIL */
	    if (returnCode == TPM_SUCCESS) {
		if (tag != TPM_TAG_RQU_AUTH2_COMMAND) {
		    printf("TPM_Process_Unseal: Error, sealed with encryption but auth-1\n");
		    returnCode = TPM_AUTHFAIL;
		}
	    }
	    /* b. Verify that the authHandle session type is TPM_PID_OSAP or TPM_PID_DSAP, return
	       TPM_BAD_MODE on error. */
	    if (returnCode == TPM_SUCCESS) {
		if ((auth_session_data->protocolID != TPM_PID_OSAP) &&
		    (auth_session_data->protocolID != TPM_PID_DSAP)) {
		    printf("TPM_Process_Unseal: Error, sealed with encryption but OIAP\n");
		    returnCode = TPM_BAD_MODE;
		}
	    }	    
	    /* c. If MSB of S2 -> et is TPM_ET_XOR */
	    /* i. Use MGF1 to create string X1 of length sealedDataSize. The inputs to MGF1 are;
	       authLastnonceEven, nonceOdd, "XOR", and authHandle -> sharedSecret. The four
	       concatenated values form the Z value that is the seed for MFG1. */
	    /* d. Else */
	    /* i. Create o1 by encrypting d1 -> data using the algorithm indicated by inData ->
	       et */
	    /* ii. Key is from authHandle -> sharedSecret */
	    /* iii. IV is SHA-1 of (authLastNonceEven || nonceOdd) */
	    if (returnCode == TPM_SUCCESS) {
		/* entity type MSB is ADIP encScheme */
		adipEncScheme = (s2StoredData->et >> 8) & 0x00ff;
		printf("TPM_Process_Unseal: Encrypting the output, encScheme %02x\n",
		       adipEncScheme);
		returnCode = TPM_SealCryptCommon(&o1Encrypted,
						 adipEncScheme,
						 &(d1SealedData.data),
						 auth_session_data,
						 nonceOdd);
		secretSize = d1SealedData.data.size;
		secret = o1Encrypted;
	    }
	    /* e. Set continueAuthSession to FALSE */
	    continueAuthSession = FALSE;
	}
	/* 10. else */
	else {
	    printf("TPM_Process_Unseal: No output encryption\n");
	    /* a. Set o1 to d1 -> data */
	    secretSize = d1SealedData.data.size;
	    secret = d1SealedData.data.buffer;
	}
    }
    /* 11. Set the return secret as o1 */
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_Unseal: 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;
	    /* return secretSize */
	    returnCode = TPM_Sbuffer_Append32(response, secretSize);
	}
	if (returnCode == TPM_SUCCESS) {
	    /* return secret */
	    returnCode = TPM_Sbuffer_Append(response, secret, secretSize);
	    /* 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) && (tag == TPM_TAG_RQU_AUTH2_COMMAND)) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* HMAC key */
					    auth_session_data,
					    outParamDigest,
					    nonceOdd,
					    continueAuthSession);
	}
	/* calculate and set the below the line parameters */
	if (returnCode == TPM_SUCCESS) {
	    returnCode = TPM_AuthParams_Set(response,
					    *dataHmacKey,	/* HMAC key */
					    data_auth_session_data,
					    outParamDigest,
					    datanonceOdd,
					    continueDataSession);
	}
	/* 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, or continueAuthSession is FALSE, 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);
    }
    if (((rcf != 0) ||
	 ((returnCode != TPM_SUCCESS) && (returnCode != TPM_DEFEND_LOCK_RUNNING)) ||
	 !continueDataSession) &&
	dataAuthHandleValid) {
	TPM_AuthSessions_TerminateHandle(tpm_state->tpm_stclear_data.authSessions, dataAuthHandle);
    }
    /*
      cleanup
    */
    TPM_StoredData_Delete(&inData, v1StoredDataVersion);	/* @1 */
    TPM_SealedData_Delete(&d1SealedData);			/* @2 */
    free(o1Encrypted);						/* @3 */
    return rcf;
}
	    
/* 10.3 TPM_UnBind rev 87

   TPM_UnBind takes the data blob that is the result of a Tspi_Data_Bind command and decrypts it
   for export to the User. The caller must authorize the use of the key that will decrypt the
   incoming blob.

   UnBind operates on a block-by-block basis, and has no notion of any relation between one block
   and another.

   UnBind SHALL operate on a single block only. 
*/

TPM_RESULT TPM_Process_UnBind(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_KEY_HANDLE	keyHandle;	/* The keyHandle identifier of a loaded key that can perform
					   UnBind operations. */
    TPM_SIZED_BUFFER	inData;		/* Encrypted blob to be decrypted */
    TPM_AUTHHANDLE	authHandle;	/* The handle used for keyHandle 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	privAuth;	/* The authorization digest that authorizes the inputs and
					   use of keyHandle. HMAC key: key.usageAuth. */

    /* 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_SECRET			*hmacKey;
    TPM_KEY			*key = NULL;			/* the key specified by keyHandle */
    TPM_SECRET			*keyUsageAuth;
    TPM_RSA_KEY_PARMS		*tpm_rsa_key_parms;		/* for key */
    TPM_BOOL			parentPCRStatus;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    uint32_t			decrypt_data_size;		/* resulting decrypted data size */
    BYTE			*decrypt_data = NULL;		/* The resulting decrypted data. */
    unsigned char		*stream;
    uint32_t			stream_size;
    TPM_BOUND_DATA		tpm_bound_data;

    /* output parameters */
    uint32_t		outParamStart;		/* starting point of outParam's */
    uint32_t		outParamEnd;		/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    size_t		outDataSize = 0;	/* The length of the returned decrypted data */
    BYTE		*outData = NULL;	/* The resulting decrypted data. */
    
    printf("TPM_Process_UnBind: Ordinal Entry\n");
    TPM_SizedBuffer_Init(&inData);		/* freed @1 */
    TPM_BoundData_Init(&tpm_bound_data);	/* freed @3 */
    /*
      get inputs
    */
    /*	get keyHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&keyHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get areaToSignSize and areaToSign parameters */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_UnBind: keyHandle %08x\n", keyHandle);
	returnCode = TPM_SizedBuffer_Load(&inData, &command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_UnBind: UnBinding %u bytes\n", inData.size);
    }
    /* 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_CheckRequestTag10(tag);
    }
    /* get the optional 'below the line' authorization parameters */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					privAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_UnBind: 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. If the inDataSize is 0 the TPM returns TPM_BAD_PARAMETER */
    if (returnCode == TPM_SUCCESS) {
	if (inData.size == 0) {
	    printf("TPM_Process_UnBind: Error, inDataSize is 0\n");
	    returnCode = TPM_BAD_PARAMETER;
	}
    }
    /* get the key corresponding to the keyHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&key, &parentPCRStatus, tpm_state, keyHandle,
						 FALSE,		/* not read-only */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_COMMAND)){
	if (key->authDataUsage != TPM_AUTH_NEVER) {
	    printf("TPM_Process_UnBind: Error, authorization required\n");
	    returnCode = TPM_AUTHFAIL;
	}
    }
    /* get keyHandle -> usageAuth */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_Key_GetUsageAuth(&keyUsageAuth, key);
    }	 
    /* get the session data */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      key,
					      keyUsageAuth,		/* OIAP */
					      key->tpm_store_asymkey->pubDataDigest); /* OSAP */
    }
    /* 2. Validate the authorization to use the key pointed to by keyHandle */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					privAuth);		/* Authorization digest for input */
    }
    /* 3. If the keyUsage field of the key referenced by keyHandle does not have the value
       TPM_KEY_BIND or TPM_KEY_LEGACY, the TPM must return the error code TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	if ((key->keyUsage != TPM_KEY_BIND) && (key->keyUsage != TPM_KEY_LEGACY)) {
	    printf("TPM_Process_UnBind: Error, invalid keyUsage %04hx\n", (key->keyUsage));
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }
    /* Get the TPM_RSA_KEY_PARMS associated with key */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyParms_GetRSAKeyParms(&tpm_rsa_key_parms, &(key->algorithmParms));
    }	     
    /* 4. Decrypt the inData using the key pointed to by keyHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode =
	    TPM_RSAPrivateDecryptMalloc(&decrypt_data,		/* decrypted data, freed @2 */
					&decrypt_data_size,	/* actual size of decrypted data
								   data */
					inData.buffer,
					inData.size,
					key);
    }
    if (returnCode == TPM_SUCCESS) {
	/* 5. if (keyHandle -> encScheme does not equal TPM_ES_RSAESOAEP_SHA1_MGF1) and (keyHandle
	   -> keyUsage equals TPM_KEY_LEGACY), */
	if ((key->algorithmParms.encScheme != TPM_ES_RSAESOAEP_SHA1_MGF1) &&
	    (key->keyUsage == TPM_KEY_LEGACY)) {
	    printf("TPM_Process_UnBind: Legacy key\n");
	    /* a. The payload does not have TPM specific markers to validate, so no consistency
	       check can be performed. */
	    /* b. Set the output parameter outData to the value of the decrypted value of
	       inData. (Padding associated with the encryption wrapping of inData SHALL NOT be
	       returned.) */
	    outData = decrypt_data;
	    /* c. Set the output parameter outDataSize to the size of outData, as deduced from the
	       decryption process. */
	    outDataSize = decrypt_data_size;
	}
	/* 6. else */
	else {
	    printf("TPM_Process_UnBind: Payload is TPM_BOUND_DATA structure\n");
	    /* a. Interpret the decrypted data under the assumption that it is a TPM_BOUND_DATA
	       structure, and validate that the payload type is TPM_PT_BIND */
	    if (returnCode == TPM_SUCCESS) {
		stream = decrypt_data;
		stream_size = decrypt_data_size;
		returnCode = TPM_BoundData_Load(&tpm_bound_data,
						&stream,
						&stream_size);
	    }
	    if (returnCode == TPM_SUCCESS) {
		if (tpm_bound_data.payload != TPM_PT_BIND) {
		    printf("TPM_Process_UnBind: Error, "
			   "TPM_BOUND_DATA->payload %02x not TPM_PT_BIND\n",
			   tpm_bound_data.payload);
		    returnCode = TPM_INVALID_STRUCTURE;
		}
	    }
	    /* b. Set the output parameter outData to the value of TPM_BOUND_DATA ->
	       payloadData. (Other parameters of TPM_BOUND_DATA SHALL NOT be returned. Padding
	       associated with the encryption wrapping of inData SHALL NOT be returned.) */
	    if (returnCode == TPM_SUCCESS) {
		outData = tpm_bound_data.payloadData;
		/* c. Set the output parameter outDataSize to the size of outData, as deduced from
		   the decryption process and the interpretation of TPM_BOUND_DATA. */
		outDataSize = tpm_bound_data.payloadDataSize;
	    }
	}
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_UnBind: 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;
	    /* 10. Return the computed outData */
	    /* append outDataSize */
	    returnCode = TPM_Sbuffer_Append32(response, outDataSize);
	}
	if (returnCode == TPM_SUCCESS) {
	    /* append outData */
	    returnCode = TPM_Sbuffer_Append(response, outData, outDataSize);
	    /* 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) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* 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, or continueAuthSession is FALSE, 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_SizedBuffer_Delete(&inData);		/* @1 */
    free(decrypt_data);				/* @2 */
    TPM_BoundData_Delete(&tpm_bound_data);	/* @3 */
    return rcf;
}

/* 10.4 TPM_CreateWrapKey rev 114

   The TPM_CreateWrapKey command both generates and creates a secure storage bundle for asymmetric
   keys.

   The newly created key can be locked to a specific PCR value by specifying a set of PCR registers.
*/

TPM_RESULT TPM_Process_CreateWrapKey(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_KEY_HANDLE	parentHandle;	/* Handle of a loaded key that can perform key wrapping. */
    TPM_ENCAUTH		dataUsageAuth;	/* Encrypted usage authorization data for the key. */
    TPM_ENCAUTH		dataMigrationAuth;	/* Encrypted migration authorization data for the
						   key.*/
    TPM_KEY		keyInfo;	/* Information about key to be created, pubkey.keyLength and
					   keyInfo.encData elements are 0. MAY be TPM_KEY12 */
    TPM_AUTHHANDLE	authHandle;	/* The authorization handle used for parent key
					   authorization. Must be an OSAP session.  */
    TPM_NONCE	nonceOdd;		/* Nonce generated by system associated with authHandle */
    TPM_BOOL	continueAuthSession = TRUE;	/* Ignored */
    TPM_AUTHDATA pubAuth;		/* The authorization digest that authorizes the use of the
					   public key in parentHandle. HMAC key:
					   parentKey.usageAuth. */

    /* 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 = NULL;	/* session data for authHandle */
    TPM_SECRET			*hmacKey;
    TPM_KEY			*parentKey = NULL;	/* the key specified by parentHandle */
    TPM_BOOL			parentPCRStatus;
    TPM_RSA_KEY_PARMS		*keyInfoRSAParms = NULL;	/* substructure of keyInfo */
    TPM_SECRET			du1UsageAuth;
    TPM_SECRET			dm1MigrationAuth;
    TPM_STORE_ASYMKEY		*wrappedStoreAsymkey;		/* substructure of wrappedKey */
    TPM_PCR_INFO		wrappedPCRInfo;
    int				ver;				/* TPM_KEY or TPM_KEY12 */

    /* output parameters */
    TPM_KEY		wrappedKey;	/* The TPM_KEY structure which includes the public and
					   encrypted private key. MAY be TPM_KEY12 */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    
    printf("TPM_Process_CreateWrapKey: Ordinal Entry\n");
    TPM_Key_Init(&keyInfo);
    TPM_Key_Init(&wrappedKey);
    TPM_PCRInfo_Init(&wrappedPCRInfo);
    /*
      get inputs
    */
    /* get parentHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&parentHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* get dataUsageAuth parameter */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CreateWrapKey: parentHandle %08x\n", parentHandle);
	returnCode = TPM_Authdata_Load(dataUsageAuth, &command, &paramSize);
    }
    /* get dataMigrationAuth parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Authdata_Load(dataMigrationAuth, &command, &paramSize);
    }
    /* get keyInfo parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_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_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,
					pubAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_CreateWrapKey: 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
    */
    /* get the key corresponding to the parentHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_KeyHandleEntries_GetKey(&parentKey, &parentPCRStatus, tpm_state,
						 parentHandle,
						 FALSE, /* not r/o, using to encrypt w/public key */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* get the session data */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_OSAP,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      parentKey,
					      NULL,			/* OIAP */
					      parentKey->tpm_store_asymkey->pubDataDigest); /*OSAP*/
    }
    /* 1. Validate the authorization to use the key pointed to by parentHandle. Return TPM_AUTHFAIL
       on any error. */
    /* 2. Validate the session type for parentHandle is OSAP. */
    if (returnCode == TPM_SUCCESS) {
	TPM_PrintFour("TPM_Process_CreateWrapKey: sharedSecret", auth_session_data->sharedSecret);
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle
								*/
					continueAuthSession,
					pubAuth);	/* Authorization digest for input */
    }
    /* 3. If the TPM is not designed to create a key of the type requested in keyInfo, return the
       error code TPM_BAD_KEY_PROPERTY */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CreateWrapKey: Checking key properties\n");
	returnCode = TPM_Key_CheckProperties(&ver, &keyInfo, 0,
					     tpm_state->tpm_permanent_flags.FIPS);
    }	     
    /* Get the TPM_RSA_KEY_PARMS associated with keyInfo */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CreateWrapKey: key parameters v = %d\n", ver);
	returnCode = TPM_KeyParms_GetRSAKeyParms(&keyInfoRSAParms, &(keyInfo.algorithmParms));
    }	     
    /* 4. Verify that parentHandle->keyUsage equals TPM_KEY_STORAGE */
    if (returnCode == TPM_SUCCESS) {
	if (parentKey->keyUsage != TPM_KEY_STORAGE) {
	    printf("TPM_Process_CreateWrapKey: Error, parent keyUsage not TPM_KEY_STORAGE\n");
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }	 
    /* 5. If parentHandle -> keyFlags -> migratable is TRUE and keyInfo -> keyFlags -> migratable is
       FALSE then return TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	if ((parentKey->keyFlags & TPM_MIGRATABLE) && !(keyInfo.keyFlags & TPM_MIGRATABLE)) {
	    printf("TPM_Process_CreateWrapKey: Error, parent not migratable\n");
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }	 
    /* 6. Validate key parameters */
    /* a. keyInfo -> keyUsage MUST NOT be TPM_KEY_IDENTITY or TPM_KEY_AUTHCHANGE. If it is, return
       TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	if ((keyInfo.keyUsage == TPM_KEY_IDENTITY) ||
	    (keyInfo.keyUsage == TPM_KEY_AUTHCHANGE)) {
	    printf("TPM_Process_CreateWrapKey: Error, Invalid key usage %04x\n",
		   keyInfo.keyUsage);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }	 
    /* b. If keyInfo -> keyFlags -> migrateAuthority is TRUE then return TPM_INVALID_KEYUSAGE */
    if (returnCode == TPM_SUCCESS) {
	if (keyInfo.keyFlags & TPM_MIGRATEAUTHORITY) {
	    printf("TPM_Process_CreateWrapKey: Error, Invalid key flags %08x\n",
		   keyInfo.keyFlags);
	    returnCode = TPM_INVALID_KEYUSAGE;
	}
    }	 
    /* 7.  If TPM_PERMANENT_FLAGS -> FIPS is TRUE then
       a.  If keyInfo -> keySize is less than 1024 return TPM_NOTFIPS
       b.  If keyInfo -> authDataUsage specifies TPM_AUTH_NEVER return TPM_NOTFIPS
       c.  If keyInfo -> keyUsage specifies TPM_KEY_LEGACY return TPM_NOTFIPS
       NOTE Done in step 3 TPM_Key_CheckProperties()
    */
    /* 8. If keyInfo -> keyUsage equals TPM_KEY_STORAGE	 or TPM_KEY_MIGRATE
       i. algorithmID MUST be TPM_ALG_RSA
       ii. encScheme MUST be TPM_ES_RSAESOAEP_SHA1_MGF1
       iii. sigScheme MUST be TPM_SS_NONE
       iv. key size MUST be 2048
       v. exponentSize MUST be 0
       NOTE Done in step 3 TPM_Key_CheckProperties()
    */
    /* 9. Determine the version of key
       a.If keyInfo -> ver is 1.1
       i. Set V1 to 1
       ii. Map wrappedKey to a TPM_KEY structure
       iii. Validate all remaining TPM_KEY structures
       b. Else if keyInfo -> tag is TPM_TAG_KEY12
       i. Set V1 to 2
       ii. Map wrappedKey to a TPM_KEY12 structure
       iii. Validate all remaining TPM_KEY12 structures
       NOTE Check done by TPM_Key_CheckProperties()
       NOTE Map done by TPM_Key_GenerateRSA()
    */
    /* 10..Create DU1 by decrypting dataUsageAuth according to the ADIP indicated by authHandle */
    /* 11. Create DM1 by decrypting dataMigrationAuth according to the ADIP indicated by
	   authHandle */
    if (returnCode == TPM_SUCCESS) {
	TPM_AuthSessionData_Decrypt(du1UsageAuth, 
				    dm1MigrationAuth,
				    dataUsageAuth,	/* even encAuth */
				    auth_session_data,
				    nonceOdd,
				    dataMigrationAuth,	/* odd encAuth */
				    TRUE);
    }
    /* 12. Set continueAuthSession to FALSE */
    if (returnCode == TPM_SUCCESS) {
	continueAuthSession = FALSE;
    }
    /* 13. Generate asymmetric key according to algorithm information in keyInfo */
    /* 14. Fill in the wrappedKey structure with information from the newly generated key. */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_CreateWrapKey: Generating key\n");
	returnCode = TPM_Key_GenerateRSA(&wrappedKey,
					 tpm_state,
					 parentKey,
					 tpm_state->tpm_stclear_data.PCRS,	/* PCR array */
					 ver,
					 keyInfo.keyUsage,
					 keyInfo.keyFlags,
					 keyInfo.authDataUsage,		/* TPM_AUTH_DATA_USAGE */
					 &(keyInfo.algorithmParms),	/* TPM_KEY_PARMS */
					 keyInfo.tpm_pcr_info,		/* TPM_PCR_INFO */
					 keyInfo.tpm_pcr_info_long);	/* TPM_PCR_INFO_LONG */
    }	 
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_GetStoreAsymkey(&wrappedStoreAsymkey,
					     &wrappedKey);
    }	 
    if (returnCode == TPM_SUCCESS) {
	/* a. Set wrappedKey -> encData -> usageAuth to DU1 */
	TPM_Secret_Copy(wrappedStoreAsymkey->usageAuth, du1UsageAuth);
	/* b. If the KeyFlags -> migratable bit is set to 1, the wrappedKey -> encData ->
	   migrationAuth SHALL contain the decrypted value from dataMigrationAuth. */
	if (wrappedKey.keyFlags & TPM_MIGRATABLE) {
	    TPM_Secret_Copy(wrappedStoreAsymkey->migrationAuth, dm1MigrationAuth);
	}
	/* c. If the KeyFlags -> migratable bit is set to 0, the wrappedKey -> encData ->
	   migrationAuth SHALL be set to the value tpmProof */
	else {
	    TPM_Secret_Copy(wrappedStoreAsymkey->migrationAuth,
			    tpm_state->tpm_permanent_data.tpmProof);
	}
	printf("TPM_Process_CreateWrapKey: wrappedKey.PCRInfoSize %d\n", wrappedKey.pcrInfo.size);
    }	 
    /* 15. If keyInfo->PCRInfoSize is non-zero. */
    /* a. If V1 is 1 */
    /* i. Set wrappedKey -> pcrInfo to a TPM_PCR_INFO structure using the pcrSelection to
       indicate the PCR's in use */
    /* b. Else */
    /* i. Set wrappedKey -> pcrInfo to a TPM_PCR_INFO_LONG structure */
    /* c. Set wrappedKey -> pcrInfo to keyInfo -> pcrInfo */
    /* d. Set wrappedKey -> digestAtCreation to the TPM_COMPOSITE_HASH indicated by
       creationPCRSelection */
    /* e. If V1 is 2 set wrappedKey -> localityAtCreation to TPM_STANY_DATA -> locality */
    /* NOTE Done by TPM_Key_GenerateRSA() */
    /* 16. Encrypt the private portions of the wrappedKey structure using the key in parentHandle */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_GenerateEncData(&wrappedKey, parentKey);
    }	 
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_CreateWrapKey: 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;
	    /* 17. Return the newly generated key in the wrappedKey parameter */
	    returnCode = TPM_Key_Store(response, &wrappedKey);
	    /* 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) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* 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, or continueAuthSession is FALSE, 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_Key_Delete(&keyInfo);			/* @1 */
    TPM_Key_Delete(&wrappedKey);		/* @2 */
    TPM_PCRInfo_Delete(&wrappedPCRInfo);	/* @3 */
    return rcf;
}

/* 27.8 TPM_LoadKey rev 114

   Version 1.2 deprecates LoadKey due to the HMAC of the new keyhandle on return. The wrapping makes
   use of the handle difficult in an environment where the TSS, or other management entity, is
   changing the TPM handle to a virtual handle.
   
   Software using loadKey on a 1.2 TPM can have a collision with the returned handle as the 1.2 TPM
   uses random values in the lower three bytes of the handle. All new software must use LoadKey2 to
   allow management software the ability to manage the key handle.
   
   Before the TPM can use a key to either wrap, unwrap, bind, unbind, seal, unseal, sign or perform
   any other action, it needs to be present in the TPM.	 The TPM_LoadKey function loads the key into
   the TPM for further use.
*/

TPM_RESULT TPM_Process_LoadKey(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_KEY_HANDLE	parentHandle;	/* TPM handle of parent key. */
    TPM_KEY		*inKey;		/* Incoming key structure, both encrypted private and clear
					   public portions.  MAY be TPM_KEY12 */
    TPM_AUTHHANDLE	authHandle;	/* The authorization handle used for parentHandle
					   authorization. */
    TPM_NONCE		nonceOdd;	/* Nonce generated by system associated with authHandle */
    TPM_BOOL	continueAuthSession = FALSE;	/* The continue use flag for the authorization
						   handle */
    TPM_AUTHDATA	parentAuth;	/* The authorization digest for inputs and
					   parentHandle. HMAC key: parentKey.usageAuth. */
    /* 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_SECRET			*hmacKey;
    TPM_BOOL			key_added = FALSE;	/* key has been added to handle list */
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    
    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_KEY_HANDLE	inKeyHandle;	/* Internal TPM handle where decrypted key was loaded. */

    printf("TPM_Process_LoadKey: Ordinal Entry\n");
    inKey = NULL;			/* freed @1 */
    /*
      get inputs
    */
    /*	get parentHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&parentHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* Allocate space for inKey.  The key cannot be a local variable, since it persists in key
       storage after the command completes. */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_LoadKey: parentHandle %08x\n", parentHandle);
	returnCode = TPM_Malloc((unsigned char **)&inKey, sizeof(TPM_KEY));	/* freed @1 */
    }
    /* get inKey parameter */
    if (returnCode == TPM_SUCCESS) {
	TPM_Key_Init(inKey);					/* freed @2 */
	returnCode = TPM_Key_Load(inKey, &command, &paramSize); /* freed @2 */
    }
    if (returnCode == TPM_SUCCESS) {
	TPM_PrintFour("TPM_Process_LoadKey: inKey n", inKey->pubKey.buffer);
    }
    /* 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_CheckRequestTag10(tag);
    }
    /* get the optional 'below the line' authorization parameters */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					parentAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_LoadKey: 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
    */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_LoadKeyCommon(&inKeyHandle,	/* output */
				       &key_added,	/* output */
				       &hmacKey,	/* output */
				       &auth_session_data, /* output */
				       tpm_state,
				       tag,
				       ordinal,
				       parentHandle,
				       inKey,
				       inParamDigest,
				       authHandle,	/*uninitialized*/
				       nonceOdd,
				       continueAuthSession,
				       parentAuth);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_LoadKey: 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;
	    /* return the key handle */
	    returnCode = TPM_Sbuffer_Append32(response, inKeyHandle);
	    /* 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) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* 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, or continueAuthSession is FALSE, 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
    */
    /* if there was a failure, delete inKey */
    if ((rcf != 0) || (returnCode != TPM_SUCCESS)) {
	TPM_Key_Delete(inKey);	/* @2 */
	free(inKey);		/* @1 */
	if (key_added) {
	    /* if there was a failure and inKey was stored in the handle list, free the handle.
	       Ignore errors, since only one error code can be returned. */
	    TPM_KeyHandleEntries_DeleteHandle(tpm_state->tpm_key_handle_entries, inKeyHandle);
	}	
    }
    return rcf;
}
	    
/* 10.5 TPM_LoadKey2 rev 107

   Before the TPM can use a key to either wrap, unwrap, unbind, seal, unseal, sign or perform any
   other action, it needs to be present in the TPM.  The TPM_LoadKey2 function loads the key into
   the TPM for further use.

   The TPM assigns the key handle. The TPM always locates a loaded key by use of the handle. The
   assumption is that the handle may change due to key management operations. It is the
   responsibility of upper level software to maintain the mapping between handle and any label used
   by external software.

   This command has the responsibility of enforcing restrictions on the use of keys. For example,
   when attempting to load a STORAGE key it will be checked for the restrictions on a storage key
   (2048 size etc.).

   The load command must maintain a record of whether any previous key in the key hierarchy was
   bound to a PCR using parentPCRStatus.
   
   The flag parentPCRStatus enables the possibility of checking that a platform passed through some
   particular state or states before finishing in the current state. A grandparent key could be
   linked to state-1, a parent key could linked to state-2, and a child key could be linked to
   state-3, for example. The use of the child key then indicates that the platform passed through
   states 1 and 2 and is currently in state 3, in this example.	 TPM_Startup with stType ==
   TPM_ST_CLEAR indicates that the platform has been reset, so the platform has not passed through
   the previous states. Hence keys with parentPCRStatus==TRUE must be unloaded if TPM_Startup is
   issued with stType == TPM_ST_CLEAR.
   
   If a TPM_KEY structure has been decrypted AND the integrity test using "pubDataDigest" has passed
   AND the key is non-migratory, the key must have been created by the TPM. So there is every reason
   to believe that the key poses no security threat to the TPM. While there is no known attack from
   a rogue migratory key, there is a desire to verify that a loaded migratory key is a real key,
   arising from a general sense of unease about execution of arbitrary data as a key. Ideally a
   consistency check would consist of an encrypt/decrypt cycle, but this may be expensive. For RSA
   keys, it is therefore suggested that the consistency test consists of dividing the supposed RSA
   product by the supposed RSA prime, and checking that there is no remainder.
*/

TPM_RESULT TPM_Process_LoadKey2(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_KEY_HANDLE	parentHandle;	/* TPM handle of parent key. */
    TPM_KEY		*inKey;		/* Incoming key structure, both encrypted private and clear
					   public portions.  MAY be TPM_KEY12 */
    TPM_AUTHHANDLE	authHandle;	/* The authorization handle used for parentHandle
					   authorization. */
    TPM_NONCE		nonceOdd;	/* Nonce generated by system associated with authHandle */
    TPM_BOOL	continueAuthSession = FALSE;	/* The continue use flag for the authorization
						   handle */
    TPM_AUTHDATA	parentAuth;	/* The authorization digest for inputs and
					   parentHandle. HMAC key: parentKey.usageAuth. */
    /* 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_SECRET			*hmacKey;
    TPM_BOOL			key_added = FALSE;	/* key has been added to handle list */
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    
    /* output parameters */
    uint32_t		outParamStart;	/* starting point of outParam's */
    uint32_t		outParamEnd;	/* ending point of outParam's */
    TPM_DIGEST		outParamDigest;
    TPM_KEY_HANDLE	inKeyHandle;	/* Internal TPM handle where decrypted key was loaded. */

    printf("TPM_Process_LoadKey2: Ordinal Entry\n");
    inKey = NULL;			/* freed @1 */
    /*
      get inputs
    */
    /*	get parentHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&parentHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    /* Allocate space for inKey.  The key cannot be a local variable, since it persists in key
       storage after the command completes. */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_LoadKey2: parentHandle %08x\n", parentHandle);
	returnCode = TPM_Malloc((unsigned char **)&inKey, sizeof(TPM_KEY));	/* freed @1 */
    }
    /* get inKey parameter */
    if (returnCode == TPM_SUCCESS) {
	TPM_Key_Init(inKey);					/* freed @2 */
	returnCode = TPM_Key_Load(inKey, &command, &paramSize); /* freed @2 */
    }
    if (returnCode == TPM_SUCCESS) {
	TPM_PrintFour("TPM_Process_LoadKey2: inKey n", inKey->pubKey.buffer);
    }
    /* 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_CheckRequestTag10(tag);
    }
    /* get the optional 'below the line' authorization parameters */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					parentAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_LoadKey2: 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
    */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_LoadKeyCommon(&inKeyHandle,		/* output */
				       &key_added,		/* output */
				       &hmacKey,		/* output */
				       &auth_session_data,	/* output */
				       tpm_state,
				       tag,
				       ordinal,
				       parentHandle,
				       inKey,
				       inParamDigest,
				       authHandle,		/* uninitialized */
				       nonceOdd,
				       continueAuthSession,
				       parentAuth);
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_LoadKey2: 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;
	    /* In TPM_LoadKey2, the inKeyHandle is not part of the output HMAC */
	    /* return the key handle */
	    returnCode = TPM_Sbuffer_Append32(response, inKeyHandle);
	}
	/* 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) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	    returnCode = TPM_AuthParams_Set(response,
					    *hmacKey,		/* 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, or continueAuthSession is FALSE, 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
    */
    /* if there was a failure, delete inKey */
    if ((rcf != 0) || (returnCode != TPM_SUCCESS)) {
	TPM_Key_Delete(inKey);	/* @2 */
	free(inKey);		/* @1 */
	if (key_added) {
	    /* if there was a failure and inKey was stored in the handle list, free the handle.
	       Ignore errors, since only one error code can be returned. */
	    TPM_KeyHandleEntries_DeleteHandle(tpm_state->tpm_key_handle_entries, inKeyHandle);
	}	
    }
    return rcf;
}

/* TPM_LoadKeyCommon rev 114

   Code common to TPM_LoadKey and TPM_LoadKey2.	 They differ only in whether the key handle is
   included in the response HMAC calculation.
*/

static TPM_RESULT TPM_LoadKeyCommon(TPM_KEY_HANDLE	*inKeyHandle,	/* output */
				    TPM_BOOL		*key_added,	/* output */
				    TPM_SECRET		**hmacKey,	/* output */
				    TPM_AUTH_SESSION_DATA	**auth_session_data, /* output */
				    tpm_state_t		*tpm_state,
				    TPM_TAG		tag,
				    TPM_COMMAND_CODE	ordinal,
				    TPM_KEY_HANDLE	parentHandle,
				    TPM_KEY		*inKey,
				    TPM_DIGEST		inParamDigest,
				    TPM_AUTHHANDLE	authHandle,
				    TPM_NONCE		nonceOdd,
				    TPM_BOOL		continueAuthSession,
				    TPM_AUTHDATA	parentAuth)
{
    TPM_RESULT			rc = 0;
    TPM_KEY			*parentKey;		/* the key specified by parentHandle */
    TPM_SECRET			*parentUsageAuth;
    TPM_BOOL			parentPCRStatus;
    TPM_BOOL			parentPCRUsage;
    int				ver;

    printf("TPM_LoadKeyCommon:\n");
    *key_added = FALSE; /* key has been added to handle list */
    /* Verify that parentHandle points to a valid key.	Get the TPM_KEY associated with parentHandle
     */
    if (rc == TPM_SUCCESS) {
	rc = TPM_KeyHandleEntries_GetKey(&parentKey, &parentPCRStatus,
					 tpm_state, parentHandle,
					 FALSE,		/* not r/o, using to decrypt */
					 FALSE,		/* do not ignore PCRs */
					 FALSE);	/* cannot use EK */
    }
    /* check TPM_AUTH_DATA_USAGE authDataUsage */
    if ((rc == TPM_SUCCESS) && (tag == TPM_TAG_RQU_COMMAND)) {
	if (parentKey->authDataUsage != TPM_AUTH_NEVER) {
	    printf("TPM_LoadKeyCommon: Error, authorization required\n");
	    rc = TPM_AUTHFAIL;
	}
    }
    /* get parentHandle -> usageAuth */
    if ((rc == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	rc = TPM_Key_GetUsageAuth(&parentUsageAuth, parentKey);
    }	 
    /* get the session data */
    if ((rc == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	rc = TPM_AuthSessions_GetData(auth_session_data,
				      hmacKey,
				      tpm_state,
				      authHandle,
				      TPM_PID_NONE,
				      TPM_ET_KEYHANDLE,
				      ordinal,
				      parentKey,
				      parentUsageAuth,			/* OIAP */
				      parentKey->tpm_store_asymkey->pubDataDigest);	/* OSAP */
    }
    /* 1. Validate the command and the parameters using parentAuth and parentHandle -> usageAuth */
    if ((rc == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	rc = TPM_Authdata_Check(tpm_state,
				**hmacKey,		/* HMAC key */
				inParamDigest,
				*auth_session_data,	/* authorization session */
				nonceOdd,		/* Nonce generated by system
							   associated with authHandle */
				continueAuthSession,
				parentAuth);		/* Authorization digest for input */
    }
    /* 2. If parentHandle -> keyUsage is NOT TPM_KEY_STORAGE return TPM_INVALID_KEYUSAGE */
    if (rc == TPM_SUCCESS) {
	if (parentKey->keyUsage != TPM_KEY_STORAGE) {
	    printf("TPM_LoadKeyCommon: Error, "
		   "parentHandle -> keyUsage should be TPM_KEY_STORAGE, is %04x\n",
		   parentKey->keyUsage);
	    rc = TPM_INVALID_KEYUSAGE;
	}
    }
    /* 3. If the TPM is not designed to operate on a key of the type specified by inKey, return the
       error code TPM_BAD_KEY_PROPERTY.	 */
    if (rc == TPM_SUCCESS) {
	rc = TPM_Key_CheckProperties(&ver, inKey, 0, tpm_state->tpm_permanent_flags.FIPS);
	printf("TPM_LoadKeyCommon: key parameters v = %d\n", ver);
    }
    /* 4. The TPM MUST handle both TPM_KEY and TPM_KEY12 structures.
       This step is done at TPM_Key_Load()
    */
    /* 5. Decrypt the inKey -> privkey to obtain TPM_STORE_ASYMKEY structure using the key in
       parentHandle.
    */
    if (rc == TPM_SUCCESS) {
	rc = TPM_Key_DecryptEncData(inKey, parentKey);
    }
    /* 6. Validate the integrity of inKey and decrypted TPM_STORE_ASYMKEY
       a. Reproduce inKey -> TPM_STORE_ASYMKEY -> pubDataDigest using the fields of inKey, and check
       that the reproduced value is the same as pubDataDigest
    */
    if (rc == TPM_SUCCESS) {
	rc = TPM_Key_CheckPubDataDigest(inKey);
    }
    /* 7. Validate the consistency of the key and it's key usage. */
    /* a. If inKey -> keyFlags -> migratable is TRUE, the TPM SHALL verify consistency of the public
       and private components of the asymmetric key pair. If inKey -> keyFlags -> migratable is
       FALSE, the TPM MAY verify consistency of the public and private components of the asymmetric
       key pair. The consistency of an RSA key pair MAY be verified by dividing the supposed (P*Q)
       product by a supposed prime and checking that there is no remainder.

       This step is done at TPM_Key_Load()
    */
    /* b.  If inKey -> keyUsage is TPM_KEY_IDENTITY, verify that inKey->keyFlags->migratable is
       FALSE. If it is not, return TPM_INVALID_KEYUSAGE
    */
    if (rc == TPM_SUCCESS) {
	if ((inKey->keyUsage == TPM_KEY_IDENTITY) &&
	    (inKey->keyFlags & TPM_MIGRATABLE)) {
	    printf("TPM_LoadKeyCommon: Error, identity key is migratable\n");
	    rc = TPM_INVALID_KEYUSAGE;
	}
    }
    /* c.  If inKey -> keyUsage is TPM_KEY_AUTHCHANGE, return TPM_INVALID_KEYUSAGE */
    if (rc == TPM_SUCCESS) {
	if (inKey->keyUsage == TPM_KEY_AUTHCHANGE) {
	    printf("TPM_LoadKeyCommon: Error, keyUsage is TPM_KEY_AUTHCHANGE\n");
	    rc = TPM_INVALID_KEYUSAGE;
	}
    }
    /* d.  If inKey -> keyFlags -> migratable equals 0 then verify that TPM_STORE_ASYMKEY ->
       migrationAuth equals TPM_PERMANENT_DATA -> tpmProof */
    if (rc == TPM_SUCCESS) {
	if (!(inKey->keyFlags & TPM_MIGRATABLE)) {
	    rc = TPM_Secret_Compare(tpm_state->tpm_permanent_data.tpmProof,
				   inKey->tpm_store_asymkey->migrationAuth);
	    if (rc != 0) {
		printf("TPM_LoadKeyCommon: Error, tpmProof mismatch\n");
		rc = TPM_INVALID_KEYUSAGE;
	    }
	}
    }
    /*	 e.   Validate the mix of encryption and signature schemes
	 f.   If TPM_PERMANENT_FLAGS -> FIPS is TRUE then
	 i.   If keyInfo -> keySize is less than 1024 return TPM_NOTFIPS
	 ii.  If keyInfo -> authDataUsage specifies TPM_AUTH_NEVER return
	 TPM_NOTFIPS
	 iii.  If  keyInfo  ->	keyUsage specifies TPM_KEY_LEGACY  return
	 TPM_NOTFIPS
	 g.   If inKey -> keyUsage is TPM_KEY_STORAGE or TPM_KEY_MIGRATE
	 i.   algorithmID MUST be TPM_ALG_RSA
	 ii.  Key size MUST be 2048
	 iii. exponentSize MUST be 0
	 iv. sigScheme MUST be TPM_SS_NONE
	 h.   If inKey -> keyUsage is TPM_KEY_IDENTITY
	 i.   algorithmID MUST be TPM_ALG_RSA
	 ii.  Key size MUST be 2048
	 iv. exponentSize MUST be 0
	 iii. encScheme MUST be TPM_ES_NONE
	 NOTE Done in step 3.  
    */
    if (rc == TPM_SUCCESS) {
	/* i. If the decrypted inKey -> pcrInfo is NULL, */
	/* i. The TPM MUST set the internal indicator to indicate that the key is not using any PCR
	   registers. */
	/* j.  Else */
	/* i. The TPM MUST store pcrInfo in a manner that allows the TPM to calculate a composite
	   hash whenever the key will be in use */
	/* ii. The TPM MUST handle both version 1.1 TPM_PCR_INFO and 1.2 TPM_PCR_INFO_LONG
	   structures according to the type of TPM_KEY structure */
	/* (1) The TPM MUST validate the TPM_PCR_INFO or TPM_PCR_INFO_LONG structures for legal
	       values.	However, the digestAtRelease and localityAtRelease are not validated for
	       authorization until use time.*/
	/* NOTE TPM_Key_Load() loads the TPM_PCR_INFO or TPM_PCR_INFO_LONG cache */
    }
    /* 8.  Perform any processing necessary to make TPM_STORE_ASYMKEY key available for
       operations. */
    /* NOTE Done at TPM_Key_Load() */
    /* 9. Load key and key information into internal memory of the TPM. If insufficient memory
       exists return error TPM_NOSPACE. */
    /* 10. Assign inKeyHandle according to internal TPM rules. */
    /* 11. Set InKeyHandle -> parentPCRStatus to parentHandle -> parentPCRStatus. */
    if (rc == TPM_SUCCESS) {
	*inKeyHandle = 0;	/* no preferred value */
	rc = TPM_KeyHandleEntries_AddKeyEntry(inKeyHandle,			/* output */
					      tpm_state->tpm_key_handle_entries, /* input */
					      inKey,				/* input */
					      parentPCRStatus,
					      0);			/* keyControl */
    }
    if (rc == TPM_SUCCESS) {
	printf(" TPM_LoadKeyCommon: Loaded key handle %08x\n", *inKeyHandle);
	/* remember that the handle has been added to handle list, so it can be deleted on error */
	*key_added = TRUE;
	
    }
    /* 12. If parentHandle indicates it is using PCR registers then set inKeyHandle ->
       parentPCRStatus to TRUE. */
    if (rc == TPM_SUCCESS) {
	rc = TPM_Key_GetPCRUsage(&parentPCRUsage, parentKey, 0);
    }
    if (rc == TPM_SUCCESS) {
	if (parentPCRUsage) {
	    rc = TPM_KeyHandleEntries_SetParentPCRStatus(tpm_state->tpm_key_handle_entries,
							 *inKeyHandle, TRUE);
	}
    }	
    return rc;
}

/* 10.6 TPM_GetPubKey rev 102

   The owner of a key may wish to obtain the public key value from a loaded key. This information
   may have privacy concerns so the command must have authorization from the key owner.
*/

TPM_RESULT TPM_Process_GetPubKey(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_KEY_HANDLE	keyHandle;	/* TPM handle of key. */
    TPM_AUTHHANDLE	authHandle;	/* The authorization handle used for keyHandle
					   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	keyAuth;	/* Authorization HMAC key: key.usageAuth. */
    
    /* 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_SECRET			*hmacKey;
    TPM_KEY			*key = NULL;		/* the key specified by keyHandle */
    TPM_BOOL			parentPCRStatus;
    TPM_AUTH_SESSION_DATA	*auth_session_data = NULL;	/* session data for authHandle */
    TPM_SECRET			*keyUsageAuth;
    TPM_STORE_BUFFER		pubkeyStream;

    /* output parameters */
    uint32_t			outParamStart;		/* starting point of outParam's */
    uint32_t			outParamEnd;		/* ending point of outParam's */
    TPM_DIGEST			outParamDigest;
    const unsigned char		*pubkeyStreamBuffer;	/* output */
    uint32_t			pubkeyStreamLength;

    printf("TPM_Process_GetPubKey: Ordinal Entry\n");
    TPM_Sbuffer_Init(&pubkeyStream);		/* freed @1 */
    /*
      get inputs
    */
    /* get keyHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Load32(&keyHandle, &command, &paramSize);
    }
    /* save the starting point of inParam's for authorization and auditing */
    inParamStart = command;
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_GetPubKey: 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_CheckRequestTag10(tag);
    }
    /* get the optional 'below the line' authorization parameters */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_AuthParams_Get(&authHandle,
					&authHandleValid,
					nonceOdd,
					&continueAuthSession,
					keyAuth,
					&command, &paramSize);
    }
    if (returnCode == TPM_SUCCESS) {
	if (paramSize != 0) {
	    printf("TPM_Process_GetPubKey: 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
    */
    /* get the key corresponding to the keyHandle parameter */
    if (returnCode == TPM_SUCCESS) {
	printf("TPM_Process_GetPubKey: Key handle %08x\n", keyHandle);
	returnCode = TPM_KeyHandleEntries_GetKey(&key, &parentPCRStatus, tpm_state, keyHandle,
						 TRUE,		/* read-only */
						 FALSE,		/* do not ignore PCRs */
						 FALSE);	/* cannot use EK */
    }
    /* 1. If tag = TPM_TAG_RQU_AUTH1_COMMAND then */
    /* get keyHandle -> usageAuth */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_Key_GetUsageAuth(&keyUsageAuth, key);
    }	 
    /* get the session data */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_AuthSessions_GetData(&auth_session_data,
					      &hmacKey,
					      tpm_state,
					      authHandle,
					      TPM_PID_NONE,
					      TPM_ET_KEYHANDLE,
					      ordinal,
					      key,
					      keyUsageAuth,		/* OIAP */
					      key->tpm_store_asymkey->pubDataDigest);	/* OSAP */
    }


    /* a. Validate the command parameters using keyHandle -> usageAuth, on error return
       TPM_AUTHFAIL */
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	returnCode = TPM_Authdata_Check(tpm_state,
					*hmacKey,		/* HMAC key */
					inParamDigest,
					auth_session_data,	/* authorization session */
					nonceOdd,		/* Nonce generated by system
								   associated with authHandle */
					continueAuthSession,
					keyAuth);		/* Authorization digest for input */
    }
    /* 2. Else	*/
    if ((returnCode == TPM_SUCCESS) && (tag == TPM_TAG_RQU_COMMAND)){
	/* a. Verify that keyHandle -> authDataUsage is TPM_NO_READ_PUBKEY_AUTH or TPM_AUTH_NEVER,
	   on error return TPM_AUTHFAIL */
#ifdef TPM_V12
	if ((key->authDataUsage != TPM_NO_READ_PUBKEY_AUTH) &&
	    (key->authDataUsage != TPM_AUTH_NEVER)) {
	    printf("TPM_Process_GetPubKey: Error, authorization required\n");
	    returnCode = TPM_AUTHFAIL;
	}
#else	/* TPM 1.1 does not have TPM_NO_READ_PUBKEY_AUTH */
	if (key->authDataUsage != TPM_AUTH_NEVER) {
	    printf("TPM_Process_GetPubKey: Error, authorization required\n");
	    returnCode = TPM_AUTHFAIL;
	}
#endif
    }
#ifdef TPM_V12	/* TPM 1.1 does not have readSRKPub  */
    if (returnCode == TPM_SUCCESS) {
	/* 3. If keyHandle == TPM_KH_SRK then  */
	if ((keyHandle == TPM_KH_SRK) &&
	    /* a. If TPM_PERMANENT_FLAGS -> readSRKPub is FALSE then return TPM_INVALID_KEYHANDLE */
	    !tpm_state->tpm_permanent_flags.readSRKPub) {
	    printf("TPM_Process_GetPubKey: "
		   "Error, keyHandle is TPM_KH_SRK and readSRKPub is FALSE\n");
	    returnCode = TPM_INVALID_KEYHANDLE;
	}
    }
#endif
    /* 4. If keyHandle -> pcrInfoSize is not 0 */
    /* a. If keyHandle -> keyFlags has pcrIgnoredOnRead set to FALSE */
    /* i. Create a digestAtRelease according to the specified PCR registers and compare
       to keyHandle -> digestAtRelease and if a mismatch return TPM_WRONGPCRVAL */
    /* ii. If specified validate any locality requests */
    /* NOTE: Done at TPM_KeyHandleEntries_GetKey() */
    /* 5. Create a TPM_PUBKEY structure and return */
    if (returnCode == TPM_SUCCESS) {
	returnCode = TPM_Key_StorePubkey(&pubkeyStream,		/* output */
					 &pubkeyStreamBuffer,	/* output */
					 &pubkeyStreamLength,	/* output */
					 key);			/* input */
    }
    /*
      response
    */
    /* standard response: tag, (dummy) paramSize, returnCode.  Failure is fatal. */
    if (rcf == 0) {
	printf("TPM_Process_GetPubKey: 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;
	    /* TPM_PUBKEY structure  */
	    returnCode = TPM_Sbuffer_Append(response, pubkeyStreamBuffer, pubkeyStreamLength);
	    /* 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) && (tag == TPM_TAG_RQU_AUTH1_COMMAND)) {
	    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, or continueAuthSession is FALSE, 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(&pubkeyStream);		/* @1 */
    return rcf;
}