libssh2-sys 0.1.39

Native bindings to the libssh2 library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
/*
 * Copyright (C) 2015 Patrick Monnerat, D+H <patrick.monnerat@dh.com>
 * 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 name of the copyright holder nor the names
 *   of any other 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 OWNER 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 "libssh2_priv.h"

#ifdef LIBSSH2_OS400QC3 /* compile only if we build with OS/400 QC3 library */

#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif

#include <stdio.h>
#include <stdarg.h>
#include <alloca.h>
#include <sys/uio.h>

#include <arpa/inet.h>


#ifdef OS400_DEBUG
/* In debug mode, all system library errors cause an exception. */
#define set_EC_length(ec, length)   ((ec).Bytes_Provided =                  \
                                     (ec).Bytes_Available = 0)
#else
#define set_EC_length(ec, length)   ((ec).Bytes_Provided = (length))
#endif


/* Ensure va_list operations are not on an array. */
typedef struct {
    va_list     list;
}       valiststr;


typedef int (*loadkeyproc)(LIBSSH2_SESSION *session,
                           const unsigned char *data, unsigned int datalen,
                           const unsigned char *passphrase, void *loadkeydata);

/* Public key extraction data. */
typedef struct {
    const char *            method;
    const unsigned char *   data;
    unsigned int            length;
}       loadpubkeydata;


/* Support for ASN.1 elements. */

typedef struct {
    char *          header;         /* Pointer to header byte. */
    char *          beg;            /* Pointer to element data. */
    char *          end;            /* Pointer to 1st byte after element. */
    unsigned char   class;          /* ASN.1 element class. */
    unsigned char   tag;            /* ASN.1 element tag. */
    unsigned char   constructed;    /* Element is constructed. */
}       asn1Element;

#define ASN1_INTEGER        2
#define ASN1_BIT_STRING     3
#define ASN1_OCTET_STRING   4
#define ASN1_NULL           5
#define ASN1_OBJ_ID         6
#define ASN1_SEQ            16

#define ASN1_CONSTRUCTED    0x20

/* rsaEncryption OID: 1.2.840.113549.1.1.1 */
static unsigned char    OID_rsaEncryption[] =
                            {9, 40 + 2, 0x86, 0x48, 0x86, 0xF7, 0x0D, 1, 1, 1};
static int  sshrsapubkey(LIBSSH2_SESSION *session, char **sshpubkey,
                         asn1Element *params, asn1Element *key,
                         const char *method);

#if LIBSSH2_DSA != 0
/* dsaEncryption OID: 1.2.840.10040.4.1 */
static unsigned char    OID_dsaEncryption[] =
                            {7, 40 + 2, 0x86, 0x48, 0xCE, 0x38, 4, 1};
static int  sshdsapubkey(LIBSSH2_SESSION *session, char **sshpubkey,
                         asn1Element *params, asn1Element *key,
                         const char *method);
#endif


/* PKCS#5 support. */

typedef struct pkcs5params  pkcs5params;
struct pkcs5params {
    int         cipher;         /* Encryption cipher. */
    int         blocksize;      /* Cipher block size. */
    char        mode;           /* Block encryption mode. */
    char        padopt;         /* Pad option. */
    char        padchar;        /* Pad character. */
    int         (*kdf)(LIBSSH2_SESSION *session, char **dk,
                       const unsigned char * passphrase, pkcs5params *pkcs5);
    int         hash;           /* KDF hash algorithm. */
    size_t      hashlen;        /* KDF hash digest length. */
    char *      salt;           /* Salt. */
    size_t      saltlen;        /* Salt length. */
    char *      iv;             /* Initialization vector. */
    size_t      ivlen;          /* Initialization vector length. */
    int         itercount;      /* KDF iteration count. */
    int         dklen;          /* Derived key length (#bytes). */
    int         effkeysize;     /* RC2 effective key size (#bits) or 0. */
};

typedef struct pkcs5algo    pkcs5algo;
struct pkcs5algo {
    const unsigned char *   oid;
    int         (*parse)(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
                         pkcs5algo *algo, asn1Element *param);
    int         cipher;         /* Encryption cipher. */
    size_t      blocksize;      /* Cipher block size. */
    char        mode;           /* Block encryption mode. */
    char        padopt;         /* Pad option. */
    char        padchar;        /* Pad character. */
    size_t      keylen;         /* Key length (#bytes). */
    int         hash;           /* Hash algorithm. */
    size_t      hashlen;        /* Hash digest length. */
    size_t      saltlen;        /* Salt length. */
    size_t      ivlen;          /* Initialisation vector length. */
    int         effkeysize;     /* RC2 effective key size (#bits) or 0. */
};

/* id-PBES2 OID: 1.2.840.113549.1.5.13 */
static const unsigned char  OID_id_PBES2[] = {
    9, 40 + 2, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0D
};
static int  parse_pbes2(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
                        pkcs5algo *algo, asn1Element *param);
static const pkcs5algo  PBES2 = {
    OID_id_PBES2,   parse_pbes2,    0,  0,  '\0',   '\0',   '\0',   0,
    0,  0,  0,  0,  0
};

/* id-PBKDF2 OID: 1.2.840.113549.1.5.12 */
static const unsigned char  OID_id_PBKDF2[] = {
    9, 40 + 2, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0C
};
static int  parse_pbkdf2(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
                         pkcs5algo *algo, asn1Element *param);
static const pkcs5algo  PBKDF2 = {
    OID_id_PBKDF2,  parse_pbkdf2,   0,  0,  '\0',   '\0',   '\0',
    SHA_DIGEST_LENGTH,  Qc3_SHA1,   SHA_DIGEST_LENGTH,  8,  8,  0
};

/* id-hmacWithSHA1 OID: 1.2.840.113549.2.7 */
static const unsigned char  OID_id_hmacWithSHA1[] = {
    8, 40 + 2, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x07
};
static int  parse_hmacWithSHA1(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
                               pkcs5algo *algo, asn1Element *param);
static const pkcs5algo  hmacWithSHA1 = {
    OID_id_hmacWithSHA1,    parse_hmacWithSHA1, 0,  0,  '\0',   '\0',   '\0',
    SHA_DIGEST_LENGTH,  Qc3_SHA1,   SHA_DIGEST_LENGTH,  8,  8,  0
};

/* desCBC OID: 1.3.14.3.2.7 */
static const unsigned char  OID_desCBC[] = {5, 40 + 3, 0x0E, 0x03, 0x02, 0x07};
static int  parse_iv(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
                     pkcs5algo *algo, asn1Element *param);
static const pkcs5algo  desCBC = {
    OID_desCBC, parse_iv,   Qc3_DES,    8,  Qc3_CBC,    Qc3_Pad_Counter,
   '\0',   8,   0,  0,  8,  8,  0
};

/* des-EDE3-CBC OID: 1.2.840.113549.3.7 */
static const unsigned char  OID_des_EDE3_CBC[] = {
    8, 40 + 2, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x03, 0x07
};
static const pkcs5algo  des_EDE3_CBC = {
    OID_des_EDE3_CBC,   parse_iv,   Qc3_TDES,   8,  Qc3_CBC, Qc3_Pad_Counter,
    '\0',   24, 0,  0,  8,  8,  0
};
 
/* rc2CBC OID: 1.2.840.113549.3.2 */
static const unsigned char  OID_rc2CBC[] = {
    8, 40 + 2, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x03, 0x02
};
static int  parse_rc2(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
                      pkcs5algo *algo, asn1Element *param);
static const pkcs5algo  rc2CBC = {
    OID_rc2CBC, parse_rc2,  Qc3_RC2,    8,  Qc3_CBC,    Qc3_Pad_Counter,
    '\0',   0,  0,  0,  8,  0,  32
};

/* pbeWithMD5AndDES-CBC OID: 1.2.840.113549.1.5.3 */
static const unsigned char  OID_pbeWithMD5AndDES_CBC[] = {
    9, 40 + 2, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x03
};
static int  parse_pbes1(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
                        pkcs5algo *algo, asn1Element *param);
static const pkcs5algo  pbeWithMD5AndDES_CBC = {
    OID_pbeWithMD5AndDES_CBC,   parse_pbes1,    Qc3_DES,    8,  Qc3_CBC,
    Qc3_Pad_Counter,    '\0',   8,  Qc3_MD5,    MD5_DIGEST_LENGTH,  8,  0,  0
};

/* pbeWithMD5AndRC2-CBC OID: 1.2.840.113549.1.5.6 */
static const unsigned char  OID_pbeWithMD5AndRC2_CBC[] = {
    9, 40 + 2, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x06
};
static const pkcs5algo  pbeWithMD5AndRC2_CBC = {
    OID_pbeWithMD5AndRC2_CBC,   parse_pbes1,    Qc3_RC2,    8,  Qc3_CBC,
    Qc3_Pad_Counter,    '\0',   0,  Qc3_MD5,    MD5_DIGEST_LENGTH,  8,  0,  64
};

/* pbeWithSHA1AndDES-CBC OID: 1.2.840.113549.1.5.10 */
static const unsigned char  OID_pbeWithSHA1AndDES_CBC[] = {
    9, 40 + 2, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0A
};
static const pkcs5algo  pbeWithSHA1AndDES_CBC = {
    OID_pbeWithSHA1AndDES_CBC,   parse_pbes1,    Qc3_DES,    8,  Qc3_CBC,
    Qc3_Pad_Counter,    '\0',   8,  Qc3_SHA1,   SHA_DIGEST_LENGTH,  8,  0, 0
};

/* pbeWithSHA1AndRC2-CBC OID: 1.2.840.113549.1.5.11 */
static const unsigned char  OID_pbeWithSHA1AndRC2_CBC[] = {
    9, 40 + 2, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05, 0x0B
};
static const pkcs5algo  pbeWithSHA1AndRC2_CBC = {
    OID_pbeWithSHA1AndRC2_CBC,   parse_pbes1,    Qc3_RC2,    8,  Qc3_CBC,
    Qc3_Pad_Counter,    '\0',   0,  Qc3_SHA1,   SHA_DIGEST_LENGTH,  8,  0,  64
};

/* rc5-CBC-PAD OID: 1.2.840.113549.3.9: RC5 not implemented in Qc3. */
/* pbeWithMD2AndDES-CBC OID: 1.2.840.113549.1.5.1: MD2 not implemented. */
/* pbeWithMD2AndRC2-CBC OID: 1.2.840.113549.1.5.4: MD2 not implemented. */

static const pkcs5algo *    pbestable[] = {
    &pbeWithMD5AndDES_CBC,
    &pbeWithMD5AndRC2_CBC,
    &pbeWithSHA1AndDES_CBC,
    &pbeWithSHA1AndRC2_CBC,
    &PBES2,
    NULL
};

static const pkcs5algo *    pbkdf2table[] = {
    &PBKDF2,
    NULL
};

static const pkcs5algo *    pbes2enctable[] = {
    &desCBC,
    &des_EDE3_CBC,
    &rc2CBC,
    NULL
};

static const pkcs5algo *    kdf2prftable[] = {
    &hmacWithSHA1,
    NULL
};


/* Public key extraction support. */
static struct {
    unsigned char * oid;
    int             (*sshpubkey)(LIBSSH2_SESSION *session, char **pubkey,
                                 asn1Element *params, asn1Element *key,
                                 const char *method);
    const char *    method;
}       pka[] = {
#if LIBSSH2_RSA != 0
    {   OID_rsaEncryption,  sshrsapubkey,   "ssh-rsa"   },
#endif
#if LIBSSH2_DSA != 0
    {   OID_dsaEncryption,  sshdsapubkey,   "ssh-dss"   },
#endif
    {   NULL,               NULL,           NULL        }
};

/* Define ASCII strings. */
static const char   beginencprivkeyhdr[] =
                                    "-----BEGIN ENCRYPTED PRIVATE KEY-----";
static const char   endencprivkeyhdr[] = "-----END ENCRYPTED PRIVATE KEY-----";
static const char   beginprivkeyhdr[] = "-----BEGIN PRIVATE KEY-----";
static const char   endprivkeyhdr[] = "-----END PRIVATE KEY-----";
static const char   beginrsaprivkeyhdr[] = "-----BEGIN RSA PRIVATE KEY-----";
static const char   endrsaprivkeyhdr[] = "-----END RSA PRIVATE KEY-----";
static const char   fopenrmode[] = "r";
static const char   fopenrbmode[] = "rb";


/* The rest of character literals in this module are in EBCDIC. */
#pragma convert(37)

#include <qusec.h>
#include <qc3prng.h>
#include <qc3dtaen.h>
#include <qc3dtade.h>
#include <qc3ctx.h>
#include <qc3hash.h>
#include <qc3hmac.h>
#include <qc3pbext.h>
#include <qc3sigvr.h>
#include <qc3sigcl.h>
#include <qc3pbext.h>

static Qc3_Format_KEYD0100_T    nulltoken = {""};

static int      zero = 0;
static int      rsaprivate[] = { Qc3_RSA_Private };
static char     anycsp[] = { Qc3_Any_CSP };
static char     binstring[] = { Qc3_Bin_String };
static char     berstring[] = { Qc3_BER_String };
static char     qc3clear[] = { Qc3_Clear };

static const Qus_EC_t ecnull = {0};     /* Error causes an exception. */

static asn1Element  lastbytebitcount = {
    (char *) &zero, NULL, (char *) &zero + 1
};


/*******************************************************************
 *
 * OS/400 QC3 crypto-library backend: ASN.1 support.
 *
 *******************************************************************/

static char *
getASN1Element(asn1Element *elem, char *beg, char *end)
{
    unsigned char b;
    unsigned long len;
    asn1Element lelem;

    /* Get a single ASN.1 element into `elem', parse ASN.1 string at `beg'
     * ending at `end'.
     * Returns a pointer in source string after the parsed element, or NULL
     * if an error occurs.
     */

    if (beg >= end || !*beg)
        return NULL;

    /* Process header byte. */
    elem->header = beg;
    b = (unsigned char) *beg++;
    elem->constructed = (b & 0x20) != 0;
    elem->class = (b >> 6) & 3;
    b &= 0x1F;
    if (b == 0x1F)
        return NULL;            /* Long tag values not supported here. */
    elem->tag = b;

    /* Process length. */
    if (beg >= end)
        return NULL;
    b = (unsigned char) *beg++;
    if (!(b & 0x80))
        len = b;
    else if (!(b &= 0x7F)) {
        /* Unspecified length. Since we have all the data, we can determine the
         * effective length by skipping element until an end element is
         * found.
         */
        if (!elem->constructed)
            return NULL;
        elem->beg = beg;
        while (beg < end && *beg) {
            beg = getASN1Element(&lelem, beg, end);
        if (!beg)
            return NULL;
        }
        if (beg >= end)
            return NULL;
        elem->end = beg;
        return beg + 1;
    } else if (beg + b > end)
        return NULL;                        /* Does not fit in source. */
    else {
        /* Get long length. */
        len = 0;
        do {
            if (len & 0xFF000000L)
                return NULL;    /* Lengths > 32 bits are not supported. */
            len = (len << 8) | (unsigned char) *beg++;
        } while (--b);
    }
    if ((unsigned long) (end - beg) < len)
        return NULL;            /* Element data does not fit in source. */
    elem->beg = beg;
    elem->end = beg + len;
    return elem->end;
}

static asn1Element *
asn1_new(unsigned int type, unsigned int length)
{
    asn1Element *e;
    unsigned int hdrl = 2;
    unsigned int i;
    unsigned char *buf;

    e = (asn1Element *) malloc(sizeof *e);

    if (e) {
        if (length >= 0x80)
            for (i = length; i; i >>= 8)
                hdrl++;

        buf = (unsigned char *) malloc(hdrl + length);

        if (buf) {
            e->header = buf;
            e->beg = buf + hdrl;
            e->end = e->beg + length;
            e->class = (type >> 6) & 0x03;
            e->tag = type & 0x1F;
            e->constructed = (type >> 5) & 0x01;
            e->header[0] = type;

            if (length < 0x80)
                e->header[1] = length;
            else {
                e->header[1] = (hdrl - 2) | 0x80;
                do {
                    e->header[--hdrl] = length;
                    length >>= 8;
                } while (length);
            }
        } else {
            free((char *) e);
            e = NULL;
        }
    }

    return e;
}

static asn1Element *
asn1_new_from_bytes(const unsigned char *data, unsigned int length)
{
    asn1Element *e;
    asn1Element te;

    getASN1Element(&te,
                   (unsigned char *) data, (unsigned char *) data + length);
    e = asn1_new(te.tag, te.end - te.beg);

    if (e)
        memcpy(e->header, data, e->end - e->header);

    return e;
}

static void
asn1delete(asn1Element *e)
{
    if (e) {
        if (e->header)
            free((char *) e->header);
        free((char *) e);
    }
}

static asn1Element *
asn1uint(_libssh2_bn *bn)
{
    asn1Element *e;
    int bits;
    int length;
    unsigned char * p;

    if (!bn)
        return NULL;

    bits = _libssh2_bn_bits(bn);
    length = (bits + 8) >> 3;
    e = asn1_new(ASN1_INTEGER, length);

    if (e) {
        p = e->beg;
        if (!(bits & 0x07))
            *p++ = 0;
        _libssh2_bn_to_bin(bn, p);
    }

    return e;
}

static asn1Element *
asn1containerv(unsigned int type, valiststr args)
{
    valiststr va;
    asn1Element *e;
    asn1Element *p;
    unsigned char *bp;
    unsigned int length = 0;

    memcpy((char *) &va, (char *) &args, sizeof args);
    while ((p = va_arg(va.list, asn1Element *)))
        length += p->end - p->header;
    va_end(va.list);
    e = asn1_new(type, length);
    if (e) {
        bp = e->beg;
        while ((p = va_arg(args.list, asn1Element *))) {
            memcpy(bp, p->header, p->end - p->header);
            bp += p->end - p->header;
        }
    }
    return e;
}

/* VARARGS1 */
static asn1Element *
asn1container(unsigned int type, ...)
{
    valiststr va;
    asn1Element *e;

    va_start(va.list, type);
    e = asn1containerv(type, va);
    va_end(va.list);
    return e;
}

static asn1Element *
asn1bytes(unsigned int type, const unsigned char *bytes, unsigned int length)
{
    asn1Element *e;

    e = asn1_new(type, length);
    if (e && length)
        memcpy(e->beg, bytes, length);
    return e;
}

static asn1Element *
rsapublickey(_libssh2_bn *e, _libssh2_bn *m)
{
    asn1Element *publicexponent;
    asn1Element *modulus;
    asn1Element *rsapubkey;

    /* Build a PKCS#1 RSAPublicKey. */

    modulus = asn1uint(m);
    publicexponent = asn1uint(e);
    rsapubkey = asn1container(ASN1_SEQ | ASN1_CONSTRUCTED,
                              modulus, publicexponent, NULL);
    asn1delete(modulus);
    asn1delete(publicexponent);

    if (!modulus || !publicexponent) {
        asn1delete(rsapubkey);
        rsapubkey = NULL;
    }

    return rsapubkey;
}

static asn1Element *
rsaprivatekey(_libssh2_bn *e, _libssh2_bn *m, _libssh2_bn *d,
              _libssh2_bn *p, _libssh2_bn *q,
              _libssh2_bn *exp1, _libssh2_bn *exp2, _libssh2_bn *coeff)
{
    asn1Element *version;
    asn1Element *modulus;
    asn1Element *publicexponent;
    asn1Element *privateexponent;
    asn1Element *prime1;
    asn1Element *prime2;
    asn1Element *exponent1;
    asn1Element *exponent2;
    asn1Element *coefficient;
    asn1Element *rsaprivkey;

    /* Build a PKCS#1 RSAPrivateKey. */
    version = asn1bytes(ASN1_INTEGER, "\0", 1);
    modulus = asn1uint(m);
    publicexponent = asn1uint(e);
    privateexponent = asn1uint(d);
    prime1 = asn1uint(p);
    prime2 = asn1uint(q);
    exponent1 = asn1uint(exp1);
    exponent2 = asn1uint(exp2);
    coefficient = asn1uint(coeff);
    rsaprivkey = asn1container(ASN1_SEQ | ASN1_CONSTRUCTED, version, modulus,
                               publicexponent, privateexponent, prime1, prime2,
                               exponent1, exponent2, coefficient, NULL);
    asn1delete(version);
    asn1delete(modulus);
    asn1delete(publicexponent);
    asn1delete(privateexponent);
    asn1delete(prime1);
    asn1delete(prime2);
    asn1delete(exponent1);
    asn1delete(exponent2);
    asn1delete(coefficient);

    if (!version || !modulus || !publicexponent || !privateexponent ||
        !prime1 || !prime2 || !exponent1 || !exponent2 || !coefficient) {
        asn1delete(rsaprivkey);
        rsaprivkey = NULL;
    }

    return rsaprivkey;
}

static asn1Element *
subjectpublickeyinfo(asn1Element *pubkey, const unsigned char *algo,
                     asn1Element *parameters)
{
    asn1Element *subjpubkey;
    asn1Element *algorithm;
    asn1Element *algorithmid;
    asn1Element *subjpubkeyinfo;
    unsigned int algosize = *algo++;

    algorithm = asn1bytes(ASN1_OBJ_ID, algo, algosize);
    algorithmid = asn1container(ASN1_SEQ | ASN1_CONSTRUCTED,
                                algorithm, parameters, NULL);
    subjpubkey = asn1container(ASN1_BIT_STRING, &lastbytebitcount,
                               pubkey, NULL);
    subjpubkeyinfo = asn1container(ASN1_SEQ | ASN1_CONSTRUCTED,
                                   algorithmid, subjpubkey, NULL);
    asn1delete(algorithm);
    asn1delete(algorithmid);
    asn1delete(subjpubkey);
    if (!algorithm || !algorithmid || !subjpubkey) {
        asn1delete(subjpubkeyinfo);
        subjpubkeyinfo = NULL;
    }
    return subjpubkeyinfo;
}

static asn1Element *
rsasubjectpublickeyinfo(asn1Element *pubkey)
{
    asn1Element *parameters;
    asn1Element *subjpubkeyinfo;

    parameters = asn1bytes(ASN1_NULL, NULL, 0);
    subjpubkeyinfo = subjectpublickeyinfo(pubkey,
                                          OID_rsaEncryption, parameters);
    asn1delete(parameters);
    if (!parameters) {
        asn1delete(subjpubkeyinfo);
        subjpubkeyinfo = NULL;
    }
    return subjpubkeyinfo;
}

static asn1Element *
privatekeyinfo(asn1Element *privkey, const unsigned char *algo,
               asn1Element *parameters)
{
    asn1Element *version;
    asn1Element *privatekey;
    asn1Element *algorithm;
    asn1Element *privatekeyalgorithm;
    asn1Element *privkeyinfo;
    unsigned int algosize = *algo++;

    /* Build a PKCS#8 PrivateKeyInfo. */
    version = asn1bytes(ASN1_INTEGER, "\0", 1);
    algorithm = asn1bytes(ASN1_OBJ_ID, algo, algosize);
    privatekeyalgorithm = asn1container(ASN1_SEQ | ASN1_CONSTRUCTED,
                                        algorithm, parameters, NULL);
    privatekey = asn1container(ASN1_OCTET_STRING, privkey, NULL);
    privkeyinfo = asn1container(ASN1_SEQ | ASN1_CONSTRUCTED, version,
                                privatekeyalgorithm, privatekey, NULL);
    asn1delete(version);
    asn1delete(algorithm);
    asn1delete(privatekeyalgorithm);
    if (!version || !algorithm || !privatekeyalgorithm) {
        asn1delete(privkeyinfo);
        privkeyinfo = NULL;
    }
    return privkeyinfo;
}

static asn1Element *
rsaprivatekeyinfo(asn1Element *privkey)
{
    asn1Element *parameters;
    asn1Element *privkeyinfo;

    parameters = asn1bytes(ASN1_NULL, NULL, 0);
    privkeyinfo = privatekeyinfo(privkey, OID_rsaEncryption, parameters);
    asn1delete(parameters);
    if (!parameters) {
        asn1delete(privkeyinfo);
        privkeyinfo = NULL;
    }
    return privkeyinfo;
}

/*******************************************************************
 *
 * OS/400 QC3 crypto-library backend: big numbers support.
 *
 *******************************************************************/


_libssh2_bn *
_libssh2_bn_init(void)
{
    _libssh2_bn *bignum;

    bignum = (_libssh2_bn *) malloc(sizeof *bignum);
    if (bignum) {
        bignum->bignum = NULL;
        bignum->length = 0;
    }

    return bignum;
}

void
_libssh2_bn_free(_libssh2_bn *bn)
{
    if (bn) {
        if (bn->bignum) {
#ifdef LIBSSH2_CLEAR_MEMORY
            if (bn->length)
                memset((char *) bn->bignum, 0, bn->length);
#endif
            free(bn->bignum);
        }

        free((char *) bn);
    }
}

static int
_libssh2_bn_resize(_libssh2_bn *bn, size_t newlen)
{
    unsigned char *bignum;

    if (!bn)
        return -1;
    if (newlen == bn->length)
        return 0;

    if (!bn->bignum)
        bignum = (unsigned char *) malloc(newlen);
    else {
#ifdef LIBSSH2_CLEAR_MEMORY
        if (newlen < bn->length)
            memset((char *) bn->bignum + newlen, 0, bn->length - newlen);
#endif
        if (!newlen) {
            free((char *) bn->bignum);
            bn->bignum = NULL;
            bn->length = 0;
            return 0;
        }
        bignum = (unsigned char *) realloc((char *) bn->bignum, newlen);
    }

    if (!bignum)
        return -1;

    if (newlen > bn->length)
        memset((char *) bignum + bn->length, 0, newlen - bn->length);

    bn->bignum = bignum;
    bn->length = newlen;
    return 0;
}

unsigned long
_libssh2_bn_bits(_libssh2_bn *bn)
{
    unsigned int i;
    unsigned char b;

    if (bn && bn->bignum) {
        for (i = bn->length; i--;)
            if ((b = bn->bignum[i])) {
                i *= 8;
                do {
                    i++;
                } while (b >>= 1);
                return i;
            }
    }

    return 0;
}

int
_libssh2_bn_from_bin(_libssh2_bn *bn, int len, const unsigned char *val)
{
    int i;

    if (!bn || (len && !val))
        return -1;

    for (; len && !*val; len--)
        val++;

    if (_libssh2_bn_resize(bn, len))
        return -1;

    for (i = len; i--;)
        bn->bignum[i] = *val++;

    return 0;
}

int
_libssh2_bn_set_word(_libssh2_bn *bn, unsigned long val)
{
    val = htonl(val);
    return _libssh2_bn_from_bin(bn, sizeof val, (unsigned char *) &val);
}

int
_libssh2_bn_to_bin(_libssh2_bn *bn, unsigned char *val)
{
    int i;

    if (!bn || !val)
        return -1;

    for (i = bn->length; i--;)
        *val++ = bn->bignum[i];

    return 0;
}

static int
_libssh2_bn_from_bn(_libssh2_bn *to, _libssh2_bn *from)
{
    int i;

    if (!to || !from)
        return -1;

    if (_libssh2_bn_resize(to, from->length))
        return -1;

    for (i = to->length; i--;)
        to->bignum[i] = from->bignum[i];

    return 0;
}

void
_libssh2_random(unsigned char *buf, int len)
{
    Qc3GenPRNs(buf, len,
        Qc3PRN_TYPE_NORMAL, Qc3PRN_NO_PARITY, (char *) &ecnull);
}

int
_libssh2_bn_rand(_libssh2_bn *bn, int bits, int top, int bottom)
{
    int len;
    int i;

    if (!bn || bits <= 0)
        return -1;
    len = (bits + 7) >> 3;
    if (_libssh2_bn_resize(bn, len))
        return -1;
    _libssh2_random(bn->bignum, len);
    i = ((bits - 1) & 07) + 1;
    bn->bignum[len - 1] &= (1 << i) - 1;
    switch (top) {
    case 1:
        if (bits > 1)
            if (i > 1)
                bn->bignum[len - 1] |= 1 << (i - 2);
            else
                bn->bignum[len - 2] |= 0x80;
        /* Fall into. */
    case 0:
        bn->bignum[len - 1] |= 1 << (i - 1);
        break;
    }
    if (bottom)
        *bn->bignum |= 0x01;
    return 0;
}

static int
_libssh2_bn_lshift(_libssh2_bn *bn)
{
    int i;
    int c = 0;

    if (!bn)
        return -1;

    if (_libssh2_bn_resize(bn, (_libssh2_bn_bits(bn) + 8) >> 3))
        return -1;

    for (i = 0; i < bn->length; i++) {
        if (bn->bignum[i] & 0x80)
            c |= 0x02;
        bn->bignum[i] = (bn->bignum[i] << 1) | (c & 0x01);
        c >>= 1;
    }

    return 0;
}

static int
_libssh2_bn_rshift(_libssh2_bn *bn)
{
    int i;
    int c = 0;

    if (!bn)
        return -1;

    for (i = bn->length; i--;) {
        if (bn->bignum[i] & 0x01)
            c |= 0x100;
        bn->bignum[i] = (bn->bignum[i] >> 1) | (c & 0x80);
        c >>= 1;
    }

    if (_libssh2_bn_resize(bn, (_libssh2_bn_bits(bn) + 7) >> 3))
        return -1;

    return 0;
}

static void
_libssh2_bn_swap(_libssh2_bn *bn1, _libssh2_bn *bn2)
{
    _libssh2_bn t = *bn1;

    *bn1 = *bn2;
    *bn2 = t;
}

static int
_libssh2_bn_subtract(_libssh2_bn *d, _libssh2_bn *bn1, _libssh2_bn *bn2)
{
    int c = 0;
    int i;

    if (bn1->length < bn2->length)
        return -1;

    if (_libssh2_bn_resize(d, bn1->length))
        return -1;

    for (i = 0; i < bn2->length; i++) {
        c += (int) bn1->bignum[i] - (int) bn2->bignum[i];
        d->bignum[i] = c;
        c = c < 0? -1: 0;
    }

    for (; c && i < bn1->length; i++) {
        c += (int) bn1->bignum[i];
        d->bignum[i] = c;
        c = c < 0? -1: 0;
    }

    if (_libssh2_bn_resize(d, (_libssh2_bn_bits(d) + 7) >> 3))
        return -1;

    return c;
}

int
_libssh2_os400qc3_bn_mod_exp(_libssh2_bn *r, _libssh2_bn *a, _libssh2_bn *p,
                             _libssh2_bn *m)
{
    _libssh2_bn *mp;
    _libssh2_bn *rp;
    asn1Element *rsapubkey;
    asn1Element *subjpubkeyinfo;
    unsigned char *av;
    unsigned char *rv;
    char *keydbuf;
    Qc3_Format_ALGD0400_T algd;
    Qc3_Format_KEYD0200_T *keyd;
    Qus_EC_t errcode;
    int sc;
    int outlen;
    int ret = -1;

    /* There is no support for this function in the Qc3 crypto-library.
       Since a RSA encryption performs this function, we can emulate it
       by creating an RSA public key in ASN.1 SubjectPublicKeyInfo format
       from p (exponent) and m (modulus) and encrypt a with this key. The
       encryption output is the function result.
       Problem: the Qc3EncryptData procedure only succeeds if the data bit
       count is less than the modulus bit count. To satisfy this condition,
       we multiply the modulus by a power of two and adjust the result
       accordingly. */

    if (!r || !a || !p)
        return ret;
 
    mp = _libssh2_bn_init();
    if (!mp)
        return ret;
    if (_libssh2_bn_from_bn(mp, m)) {
        _libssh2_bn_free(mp);
        return ret;
    }
    for (sc = 0; _libssh2_bn_bits(mp) <= 8 * a->length; sc++)
        if (_libssh2_bn_lshift(mp)) {
            _libssh2_bn_free(mp);
            return ret;
        }

    rsapubkey = rsapublickey(p, mp);
    subjpubkeyinfo = rsasubjectpublickeyinfo(rsapubkey);
    asn1delete(rsapubkey);

    if (!rsapubkey || !subjpubkeyinfo) {
        asn1delete(rsapubkey);
        asn1delete(subjpubkeyinfo);
        _libssh2_bn_free(mp);
        return ret;
    }

    av = (unsigned char *) alloca(a->length);
    rv = (unsigned char *) alloca(mp->length);
    keydbuf = alloca(sizeof *keyd +
                     subjpubkeyinfo->end - subjpubkeyinfo->header);

    if (av && rv && keydbuf) {
        _libssh2_bn_to_bin(a, av);
        algd.Public_Key_Alg = Qc3_RSA;
        algd.PKA_Block_Format = Qc3_Zero_Pad;
        memset(algd.Reserved, 0, sizeof algd.Reserved);
        algd.Signing_Hash_Alg = 0;
        keyd = (Qc3_Format_KEYD0200_T *) keydbuf;
        keyd->Key_Type = Qc3_RSA_Public;
        keyd->Key_String_Len = subjpubkeyinfo->end - subjpubkeyinfo->header;
        keyd->Key_Format = Qc3_BER_String;
        memset(keyd->Reserved, 0, sizeof keyd->Reserved);
        memcpy(keydbuf + sizeof *keyd, subjpubkeyinfo->header,
               keyd->Key_String_Len);
        set_EC_length(errcode, sizeof errcode);
        Qc3EncryptData(av, (int *) &a->length, Qc3_Data, (char *) &algd,
                       Qc3_Alg_Public_Key, keydbuf, Qc3_Key_Parms, anycsp,
                       NULL, rv, (int *) &mp->length, &outlen, &errcode);
        if (!errcode.Bytes_Available) {
            _libssh2_bn_from_bin(r, outlen, rv);
            if (!sc)
                ret = 0;
            else {
                rp = _libssh2_bn_init();
                if (rp) {
                    do {
                        _libssh2_bn_rshift(mp);
                        if (!_libssh2_bn_subtract(rp, r, mp))
                            _libssh2_bn_swap(r, rp);
                    } while (--sc);
                    _libssh2_bn_free(rp);
                    ret = 0;
                }
            }
        }
    }
    asn1delete(subjpubkeyinfo);
    _libssh2_bn_free(mp);
    return ret;
}


/*******************************************************************
 *
 * OS/400 QC3 crypto-library backend: crypto context support.
 *
 *******************************************************************/

static _libssh2_os400qc3_crypto_ctx *
libssh2_init_crypto_ctx(_libssh2_os400qc3_crypto_ctx *ctx)
{
    if (!ctx)
        ctx = (_libssh2_os400qc3_crypto_ctx *) malloc(sizeof *ctx);

    if (ctx) {
        memset((char *) ctx, 0, sizeof *ctx);
        ctx->hash.Final_Op_Flag = Qc3_Continue;
    }

    return ctx;
}

static int
null_token(const char *token)
{
    return !memcmp(token, nulltoken.Key_Context_Token,
                   sizeof nulltoken.Key_Context_Token);
}

void
_libssh2_os400qc3_crypto_dtor(_libssh2_os400qc3_crypto_ctx *x)
{
    if (!x)
        return;
    if (!null_token(x->hash.Alg_Context_Token)) {
        Qc3DestroyAlgorithmContext(x->hash.Alg_Context_Token, (char *) &ecnull);
        memset(x->hash.Alg_Context_Token, 0, sizeof x->hash.Alg_Context_Token);
    }
    if (!null_token(x->key.Key_Context_Token)) {
        Qc3DestroyKeyContext(x->key.Key_Context_Token, (char *) &ecnull);
        memset(x->key.Key_Context_Token, 0, sizeof x->key.Key_Context_Token);
    }
    if (x->kek) {
        _libssh2_os400qc3_crypto_dtor(x->kek);
        free((char *) x->kek);
        x->kek = NULL;
    }
}

/*******************************************************************
 *
 * OS/400 QC3 crypto-library backend: hash algorithms support.
 *
 *******************************************************************/

int
libssh2_os400qc3_hash_init(Qc3_Format_ALGD0100_T *x, unsigned int algorithm)
{
    Qc3_Format_ALGD0500_T algd;
    Qus_EC_t errcode;

    if (!x)
        return 0;

    memset((char *) x, 0, sizeof *x);
    x->Final_Op_Flag = Qc3_Continue;
    algd.Hash_Alg = algorithm;
    set_EC_length(errcode, sizeof errcode);
    Qc3CreateAlgorithmContext((char *) &algd, Qc3_Alg_Hash,
                              x->Alg_Context_Token, &errcode);
    return errcode.Bytes_Available? 0: 1;
}

void
libssh2_os400qc3_hash_update(Qc3_Format_ALGD0100_T *ctx,
                             unsigned char *data, int len)
{
    char dummy[64];

    ctx->Final_Op_Flag = Qc3_Continue;
    Qc3CalculateHash((char *) data, &len, Qc3_Data, (char *) ctx,
                     Qc3_Alg_Token, anycsp, NULL, dummy, (char *) &ecnull);
}

void
libssh2_os400qc3_hash_final(Qc3_Format_ALGD0100_T *ctx, unsigned char *out)
{
    char data;

    ctx->Final_Op_Flag = Qc3_Final;
    Qc3CalculateHash(&data, &zero, Qc3_Data, (char *) ctx, Qc3_Alg_Token,
                     anycsp, NULL, (char *) out, (char *) &ecnull);
    Qc3DestroyAlgorithmContext(ctx->Alg_Context_Token, (char *) &ecnull);
    memset(ctx->Alg_Context_Token, 0, sizeof ctx->Alg_Context_Token);
}

int
libssh2_os400qc3_hash(const unsigned char *message, unsigned long len,
                      unsigned char *out, unsigned int algo)
{
    Qc3_Format_ALGD0100_T ctx;

    if (!libssh2_os400qc3_hash_init(&ctx, algo))
        return 1;

    libssh2_os400qc3_hash_update(&ctx, (unsigned char *) message, len);
    libssh2_os400qc3_hash_final(&ctx, out);
    return 0;
}

void
libssh2_os400qc3_hmac_init(_libssh2_os400qc3_crypto_ctx *ctx,
                           int algo, size_t minkeylen, void *key, int keylen)
{
    if (keylen < minkeylen) {
        char *lkey = alloca(minkeylen);

        /* Pad key with zeroes if too short. */
        if (!lkey)
            return;
        memcpy(lkey, (char *) key, keylen);
        memset(lkey + keylen, 0, minkeylen - keylen);
        key = (void *) lkey;
        keylen = minkeylen;
    }
    libssh2_os400qc3_hash_init(&ctx->hash, algo);
    Qc3CreateKeyContext((char *) key, &keylen, binstring, &algo, qc3clear,
                        NULL, NULL, ctx->key.Key_Context_Token,
                        (char *) &ecnull);
}

void
libssh2_os400qc3_hmac_update(_libssh2_os400qc3_crypto_ctx *ctx,
                             unsigned char *data, int len)
{
    char dummy[64];

    ctx->hash.Final_Op_Flag = Qc3_Continue;
    Qc3CalculateHMAC((char *) data, &len, Qc3_Data, (char *) &ctx->hash,
                     Qc3_Alg_Token, ctx->key.Key_Context_Token, Qc3_Key_Token,
                     anycsp, NULL, dummy, (char *) &ecnull);
}

void
libssh2_os400qc3_hmac_final(_libssh2_os400qc3_crypto_ctx *ctx,
                            unsigned char *out)
{
    char data;

    ctx->hash.Final_Op_Flag = Qc3_Final;
    Qc3CalculateHMAC((char *) data, &zero, Qc3_Data, (char *) &ctx->hash,
                     Qc3_Alg_Token, ctx->key.Key_Context_Token, Qc3_Key_Token,
                     anycsp, NULL, (char *) out, (char *) &ecnull);
}


/*******************************************************************
 *
 * OS/400 QC3 crypto-library backend: cipher algorithms support.
 *
 *******************************************************************/

int
_libssh2_cipher_init(_libssh2_cipher_ctx *h, _libssh2_cipher_type(algo),
                     unsigned char *iv, unsigned char *secret, int encrypt)
{
    Qc3_Format_ALGD0200_T algd;
    Qus_EC_t errcode;

    (void) encrypt;

    if (!h)
        return -1;

    libssh2_init_crypto_ctx(h);
    algd.Block_Cipher_Alg = algo.algo;
    algd.Block_Length = algo.size;
    algd.Mode = algo.mode;
    algd.Pad_Option = Qc3_No_Pad;
    algd.Pad_Character = 0;
    algd.Reserved = 0;
    algd.MAC_Length = 0;
    algd.Effective_Key_Size = 0;
    memset(algd.Init_Vector, 0 , sizeof algd.Init_Vector);
    if (algo.mode != Qc3_ECB && algo.size)
        memcpy(algd.Init_Vector, iv, algo.size);
    set_EC_length(errcode, sizeof errcode);
    Qc3CreateAlgorithmContext((char *) &algd, algo.fmt,
                              h->hash.Alg_Context_Token, &errcode);
    if (errcode.Bytes_Available)
        return -1;
    Qc3CreateKeyContext((char *) secret, &algo.keylen, binstring,
                        &algo.algo, qc3clear, NULL, NULL,
                        h->key.Key_Context_Token, (char *) &errcode);
    if (errcode.Bytes_Available) {
        _libssh2_os400qc3_crypto_dtor(h);
        return -1;
    }

    return 0;
}

int
_libssh2_cipher_crypt(_libssh2_cipher_ctx *ctx,
                      _libssh2_cipher_type(algo),
                      int encrypt, unsigned char *block, size_t blocksize)
{
    Qus_EC_t errcode;
    int outlen;
    int blksize = blocksize;

    (void) algo;

    set_EC_length(errcode, sizeof errcode);
    if (encrypt)
        Qc3EncryptData((char *) block, &blksize, Qc3_Data,
                       ctx->hash.Alg_Context_Token, Qc3_Alg_Token,
                       ctx->key.Key_Context_Token, Qc3_Key_Token, anycsp, NULL,
                       (char *) block, &blksize, &outlen, (char *) &errcode);
    else
        Qc3DecryptData((char *) block, &blksize,
                       ctx->hash.Alg_Context_Token, Qc3_Alg_Token,
                       ctx->key.Key_Context_Token, Qc3_Key_Token, anycsp, NULL,
                       (char *) block, &blksize, &outlen, (char *) &errcode);

    return errcode.Bytes_Available? -1: 0;
}


/*******************************************************************
 *
 * OS/400 QC3 crypto-library backend: RSA support.
 *
 *******************************************************************/

int
_libssh2_rsa_new(libssh2_rsa_ctx **rsa,
                 const unsigned char *edata, unsigned long elen,
                 const unsigned char *ndata, unsigned long nlen,
                 const unsigned char *ddata, unsigned long dlen,
                 const unsigned char *pdata, unsigned long plen,
                 const unsigned char *qdata, unsigned long qlen,
                 const unsigned char *e1data, unsigned long e1len,
                 const unsigned char *e2data, unsigned long e2len,
                 const unsigned char *coeffdata, unsigned long coefflen)
{
    libssh2_rsa_ctx *ctx;
    _libssh2_bn *e = _libssh2_bn_init_from_bin();
    _libssh2_bn *n = _libssh2_bn_init_from_bin();
    _libssh2_bn *d = NULL;
    _libssh2_bn *p = NULL;
    _libssh2_bn *q = NULL;
    _libssh2_bn *e1 = NULL;
    _libssh2_bn *e2 = NULL;
    _libssh2_bn *coeff = NULL;
    asn1Element *key = NULL;
    asn1Element *structkey = NULL;
    Qc3_Format_ALGD0400_T algd;
    Qus_EC_t errcode;
    int keytype;
    int ret = 0;
    int i;

    ctx = libssh2_init_crypto_ctx(NULL);
    if (!ctx)
        ret = -1;
    if (!ret) {
        _libssh2_bn_from_bin(e, elen, edata);
        _libssh2_bn_from_bin(n, nlen, ndata);
        if (!e || !n)
            ret = -1;
    }
    if (!ret && ddata) {
        /* Private key. */
        d = _libssh2_bn_init_from_bin();
        _libssh2_bn_from_bin(d, dlen, ddata);
        p = _libssh2_bn_init_from_bin();
        _libssh2_bn_from_bin(p, plen, pdata);
        q = _libssh2_bn_init_from_bin();
        _libssh2_bn_from_bin(q, qlen, qdata);
        e1 = _libssh2_bn_init_from_bin();
        _libssh2_bn_from_bin(e1, e1len, e1data);
        e2 = _libssh2_bn_init_from_bin();
        _libssh2_bn_from_bin(e2, e2len, e2data);
        coeff = _libssh2_bn_init_from_bin();
        _libssh2_bn_from_bin(coeff, coefflen, coeffdata);
        if (!d || !p || !q ||!e1 || !e2 || !coeff)
            ret = -1;

        if (!ret) {
            /* Build a PKCS#8 private key. */
            key = rsaprivatekey(e, n, d, p, q, e1, e2, coeff);
            structkey = rsaprivatekeyinfo(key);
        }
        keytype = Qc3_RSA_Private;
    } else if (!ret) {
        key = rsapublickey(e, n);
        structkey = rsasubjectpublickeyinfo(key);
        keytype = Qc3_RSA_Public;
    }
    if (!key || !structkey)
        ret = -1;

    set_EC_length(errcode, sizeof errcode);

    if (!ret) {
        /* Create the algorithm context. */
        algd.Public_Key_Alg = Qc3_RSA;
        algd.PKA_Block_Format = Qc3_PKCS1_01;
        memset(algd.Reserved, 0, sizeof algd.Reserved);
        algd.Signing_Hash_Alg = Qc3_SHA1;
        Qc3CreateAlgorithmContext((char *) &algd, Qc3_Alg_Public_Key,
                                  ctx->hash.Alg_Context_Token, &errcode);
        if (errcode.Bytes_Available)
            ret = -1;
        ctx->hash.Final_Op_Flag = Qc3_Continue;
    }

    /* Create the key context. */
    if (!ret) {
        i = structkey->end - structkey->header;
        Qc3CreateKeyContext(structkey->header, &i, berstring, &keytype,
                            qc3clear, NULL, NULL, ctx->key.Key_Context_Token,
                            (char *) &errcode);
        if (errcode.Bytes_Available)
            ret = -1;
    }

    _libssh2_bn_free(e);
    _libssh2_bn_free(n);
    _libssh2_bn_free(d);
    _libssh2_bn_free(p);
    _libssh2_bn_free(q);
    _libssh2_bn_free(e1);
    _libssh2_bn_free(e2);
    _libssh2_bn_free(coeff);
    asn1delete(key);
    asn1delete(structkey);
    if (ret && ctx) {
        _libssh2_rsa_free(ctx);
        ctx = NULL;
    }
    *rsa = ctx;
    return ret;
}


/*******************************************************************
 *
 * OS/400 QC3 crypto-library backend: PKCS#5 supplement.
 *
 *******************************************************************/

static int
oidcmp(const asn1Element *e, const unsigned char *oid)
{
    int i = e->end - e->beg - *oid++;

    if (*e->header != ASN1_OBJ_ID)
        return -2;
    if (!i)
        i = memcmp(e->beg, oid, oid[-1]);
    return i;
}

static int
asn1getword(asn1Element *e, unsigned long *v)
{
    unsigned long a;
    const unsigned char *cp;

    if (*e->header != ASN1_INTEGER)
        return -1;
    for (cp = e->beg; cp < e->end && !*cp; cp++)
        ;
    if (e->end - cp > sizeof a)
        return -1;
    for (a = 0; cp < e->end; cp++)
        a = (a << 8) | *cp;
    *v = a;
    return 0;
}

static int
pbkdf1(LIBSSH2_SESSION *session, char **dk, const unsigned char * passphrase,
       pkcs5params *pkcs5)
{
    int i;
    Qc3_Format_ALGD0100_T hctx;
    int len = pkcs5->saltlen;
    char *data = (char *) pkcs5->salt;

    *dk = NULL;
    if (pkcs5->dklen > pkcs5->hashlen)
        return -1;

    /* Allocate the derived key buffer. */
    if (!(*dk = LIBSSH2_ALLOC(session, pkcs5->hashlen)))
        return -1;

    /* Initial hash. */
    libssh2_os400qc3_hash_init(&hctx, pkcs5->hash);
    libssh2_os400qc3_hash_update(&hctx, (unsigned char *) passphrase,
                                 strlen(passphrase));
    hctx.Final_Op_Flag = Qc3_Final;
    Qc3CalculateHash((char *) pkcs5->salt, &len, Qc3_Data, (char *) &hctx,
                     Qc3_Alg_Token, anycsp, NULL, *dk, (char *) &ecnull);

    /* Iterate. */
    len = pkcs5->hashlen;
    for (i = 1; i < pkcs5->itercount; i++)
        Qc3CalculateHash((char *) *dk, &len, Qc3_Data, (char *) &hctx,
                         Qc3_Alg_Token, anycsp, NULL, *dk, (char *) &ecnull);

    /* Special stuff for PBES1: split derived key into 8-byte key and 8-byte
       initialization vector. */
    pkcs5->dklen = 8;
    pkcs5->ivlen = 8;
    pkcs5->iv = *dk + 8;

    /* Clean-up and exit. */
    Qc3DestroyAlgorithmContext(hctx.Alg_Context_Token, (char *) &ecnull);
    return 0;
}

static int
pbkdf2(LIBSSH2_SESSION *session, char **dk, const unsigned char * passphrase,
       pkcs5params *pkcs5)
{
    size_t i;
    size_t k;
    int j;
    int l;
    uint32_t ni;
    unsigned long long t;
    char *mac;
    char *buf;
    _libssh2_os400qc3_crypto_ctx hctx;

    *dk = NULL;
    t = ((unsigned long long) pkcs5->dklen + pkcs5->hashlen - 1) /
        pkcs5->hashlen;
    if (t > 0xFFFFFFFF)
        return -1;
    mac = alloca(pkcs5->hashlen);
    if (!mac)
        return -1;

    /* Allocate the derived key buffer. */
    l = t;
    if (!(buf = LIBSSH2_ALLOC(session, l * pkcs5->hashlen)))
        return -1;
    *dk = buf;

    /* Create an HMAC context for our computations. */
    libssh2_os400qc3_hmac_init(&hctx, pkcs5->hash, pkcs5->hashlen,
                               (void *) passphrase, strlen(passphrase));

    /* Process each hLen-size blocks. */
    for (i = 1; i <= l; i++) {
        ni = htonl(i);
        libssh2_os400qc3_hmac_update(&hctx, pkcs5->salt, pkcs5->saltlen);
        libssh2_os400qc3_hmac_update(&hctx, (char *) &ni, sizeof ni);
        libssh2_os400qc3_hmac_final(&hctx, mac);
        memcpy(buf, mac, pkcs5->hashlen);
        for (j = 1; j < pkcs5->itercount; j++) {
            libssh2_os400qc3_hmac_update(&hctx, mac, pkcs5->hashlen);
            libssh2_os400qc3_hmac_final(&hctx, mac);
            for (k = 0; k < pkcs5->hashlen; k++)
                buf[k] ^= mac[k];
        }
        buf += pkcs5->hashlen;
    }

    /* Computation done. Release HMAC context. */
    _libssh2_os400qc3_crypto_dtor(&hctx);
    return 0;
}

static int
parse_pkcs5_algorithm(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
                      asn1Element *algid, pkcs5algo **algotable)
{
    asn1Element oid;
    asn1Element param;
    char *cp;

    cp = getASN1Element(&oid, algid->beg, algid->end);
    if (!cp || *oid.header != ASN1_OBJ_ID)
        return -1;
    param.header = NULL;
    if (cp < algid->end)
        cp = getASN1Element(&param, cp, algid->end);
    if (cp != algid->end)
        return -1;
    for (; *algotable; algotable++)
        if (!oidcmp(&oid, (*algotable)->oid))
            return (*(*algotable)->parse)(session, pkcs5, *algotable,
                                          param.header? &param: NULL);
    return -1;
}

static int
parse_pbes2(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
            pkcs5algo *algo, asn1Element *param)
{
    asn1Element keyDerivationFunc;
    asn1Element encryptionScheme;
    char *cp;

    if (!param || *param->header != (ASN1_SEQ | ASN1_CONSTRUCTED))
        return -1;
    cp = getASN1Element(&keyDerivationFunc, param->beg, param->end);
    if (!cp || *keyDerivationFunc.header != (ASN1_SEQ | ASN1_CONSTRUCTED))
        return -1;
    if (getASN1Element(&encryptionScheme, cp, param->end) != param->end ||
        *encryptionScheme.header != (ASN1_SEQ | ASN1_CONSTRUCTED))
        return -1;
    if (parse_pkcs5_algorithm(session, pkcs5, &encryptionScheme, pbes2enctable))
        return -1;
    if (parse_pkcs5_algorithm(session, pkcs5, &keyDerivationFunc, pbkdf2table))
        return -1;
    return 0;
}

static int
parse_pbkdf2(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
             pkcs5algo *algo, asn1Element *param)
{
    asn1Element salt;
    asn1Element iterationCount;
    asn1Element keyLength;
    asn1Element prf;
    unsigned long itercount;
    char *cp;

    if (!param || *param->header != (ASN1_SEQ | ASN1_CONSTRUCTED))
        return -1;
    cp = getASN1Element(&salt, param->beg, param->end);
    /* otherSource not supported. */
    if (!cp || *salt.header != ASN1_OCTET_STRING)
        return -1;
    cp = getASN1Element(&iterationCount, cp, param->end);
    if (!cp || *iterationCount.header != ASN1_INTEGER)
        return -1;
    keyLength.header = prf.header = NULL;
    if (cp < param->end) {
        cp = getASN1Element(&prf, cp, param->end);
        if (!cp)
            return -1;
        if (*prf.header == ASN1_INTEGER) {
            keyLength = prf;
            prf.header = NULL;
            if (cp < param->end)
                cp = getASN1Element(&prf, cp, param->end);
        }
        if (cp != param->end)
            return -1;
    }
    pkcs5->hash = algo->hash;
    pkcs5->hashlen = algo->hashlen;
    if (prf.header) {
        if (*prf.header != (ASN1_SEQ | ASN1_CONSTRUCTED))
            return -1;
        if (parse_pkcs5_algorithm(session, pkcs5, &prf, kdf2prftable))
            return -1;
    }
    pkcs5->saltlen = salt.end - salt.beg;
    pkcs5->salt = salt.beg;
    if (asn1getword(&iterationCount, &itercount) ||
        !itercount || itercount > 100000)
        return -1;
    pkcs5->itercount = itercount;
    pkcs5->kdf = pbkdf2;
    return 0;
}

static int
parse_hmacWithSHA1(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
                   pkcs5algo *algo, asn1Element *param)
{
    if (!param || *param->header != ASN1_NULL)
        return -1;
    pkcs5->hash = algo->hash;
    pkcs5->hashlen = algo->hashlen;
    return 0;
}

static int
parse_iv(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
         pkcs5algo *algo, asn1Element *param)
{
    if (!param || *param->header != ASN1_OCTET_STRING ||
        param->end - param->beg != algo->ivlen)
        return -1;
    pkcs5->cipher = algo->cipher;
    pkcs5->blocksize = algo->blocksize;
    pkcs5->mode = algo->mode;
    pkcs5->padopt = algo->padopt;
    pkcs5->padchar = algo->padchar;
    pkcs5->dklen = algo->keylen;
    pkcs5->ivlen = algo->ivlen;
    pkcs5->iv = param->beg;
    return 0;
}

static int
parse_rc2(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
          pkcs5algo *algo, asn1Element *param)
{
    asn1Element iv;
    unsigned long effkeysize;
    char *cp;

    if (!param || *param->header != (ASN1_SEQ | ASN1_CONSTRUCTED))
        return -1;
    cp = getASN1Element(&iv, param->beg, param->end);
    if (!cp)
        return -1;
    effkeysize = algo->effkeysize;
    if (*iv.header == ASN1_INTEGER) {
        if (asn1getword(&iv, &effkeysize) || effkeysize > 1024)
            return -1;

        cp = getASN1Element(&iv, cp, param->end);
        if (effkeysize < 256)
            switch (effkeysize) {
            case 160:
                effkeysize = 40;
            case 120:
                effkeysize = 64;
            case 58:
                effkeysize = 128;
                break;
            default:
                return -1;
            }
    }
    if (effkeysize > 1024 || cp != param->end ||
        *iv.header != ASN1_OCTET_STRING || iv.end - iv.beg != algo->ivlen)
        return -1;
    pkcs5->cipher = algo->cipher;
    pkcs5->blocksize = algo->blocksize;
    pkcs5->mode = algo->mode;
    pkcs5->padopt = algo->padopt;
    pkcs5->padchar = algo->padchar;
    pkcs5->ivlen = algo->ivlen;
    pkcs5->iv = iv.beg;
    pkcs5->effkeysize = effkeysize;
    pkcs5->dklen = (effkeysize + 8 - 1) / 8;
    return 0;
}

static int
parse_pbes1(LIBSSH2_SESSION *session, pkcs5params *pkcs5,
            pkcs5algo *algo, asn1Element *param)
{
    asn1Element salt;
    asn1Element iterationCount;
    unsigned long itercount;
    char *cp;

    if (!param || *param->header != (ASN1_SEQ | ASN1_CONSTRUCTED))
        return -1;

    cp = getASN1Element(&salt, param->beg, param->end);
    if (!cp || *salt.header != ASN1_OCTET_STRING ||
        salt.end - salt.beg != algo->saltlen)
        return -1;
    if (getASN1Element(&iterationCount, cp, param->end) != param->end ||
        *iterationCount.header != ASN1_INTEGER)
        return -1;
    if (asn1getword(&iterationCount, &itercount) ||
        !itercount || itercount > 100000)
        return -1;
    pkcs5->cipher = algo->cipher;
    pkcs5->blocksize = algo->blocksize;
    pkcs5->mode = algo->mode;
    pkcs5->padopt = algo->padopt;
    pkcs5->padchar = algo->padchar;
    pkcs5->hash = algo->hash;
    pkcs5->hashlen = algo->hashlen;
    pkcs5->dklen = 16;
    pkcs5->saltlen = algo->saltlen;
    pkcs5->effkeysize = algo->effkeysize;
    pkcs5->salt = salt.beg;
    pkcs5->kdf = pbkdf1;
    pkcs5->itercount = itercount;
    return 0;
}

static int
pkcs8kek(LIBSSH2_SESSION *session, _libssh2_os400qc3_crypto_ctx **ctx,
         const unsigned char *data, unsigned int datalen,
         const unsigned char *passphrase, asn1Element *privkeyinfo)
{
    asn1Element encprivkeyinfo;
    asn1Element pkcs5alg;
    pkcs5params pkcs5;
    size_t pplen;
    char *cp;
    unsigned long t;
    int i;
    char *dk = NULL;
    Qc3_Format_ALGD0200_T algd;
    Qus_EC_t errcode;

    /* Determine if the PKCS#8 data is encrypted and, if so, set-up a
       key encryption key and algorithm in context.
       Return 1 if encrypted, 0, if not, -1 if error. */

    *ctx = NULL;
    privkeyinfo->beg = (char *) data;
    privkeyinfo->end = privkeyinfo->beg + datalen;

    /* If no passphrase is given, it cannot be an encrypted key. */
    if (!passphrase || !*passphrase)
        return 0;

    /* Parse PKCS#8 data, checking if ASN.1 format is PrivateKeyInfo or
       EncryptedPrivateKeyInfo. */
    if (getASN1Element(&encprivkeyinfo, privkeyinfo->beg, privkeyinfo->end) !=
        (char *) data + datalen ||
        *encprivkeyinfo.header != (ASN1_SEQ | ASN1_CONSTRUCTED))
        return -1;
    cp = getASN1Element(&pkcs5alg, encprivkeyinfo.beg, encprivkeyinfo.end);
    if (!cp)
        return -1;

    switch (*pkcs5alg.header) {
    case ASN1_INTEGER:                          /* Version. */
        return 0;       /* This is a PrivateKeyInfo --> not encrypted. */
    case ASN1_SEQ | ASN1_CONSTRUCTED:           /* AlgorithIdentifier. */
        break;          /* This is an EncryptedPrivateKeyInfo --> encrypted. */
    default:
        return -1;      /* Unrecognized: error. */
    }

    /* Get the encrypted key data. */
    if (getASN1Element(privkeyinfo, cp, encprivkeyinfo.end) !=
        encprivkeyinfo.end || *privkeyinfo->header != ASN1_OCTET_STRING)
        return -1;

    /* PKCS#5: parse the PBES AlgorithmIdentifier and recursively get all
       encryption parameters. */
    memset((char *) &pkcs5, 0, sizeof pkcs5);
    if (parse_pkcs5_algorithm(session, &pkcs5, &pkcs5alg, pbestable))
        return -1;

    /* Compute the derived key. */
    if ((*pkcs5.kdf)(session, &dk, passphrase, &pkcs5))
        return -1;

    /* Prepare the algorithm descriptor. */
    memset((char *) &algd, 0, sizeof algd);
    algd.Block_Cipher_Alg = pkcs5.cipher;
    algd.Block_Length = pkcs5.blocksize;
    algd.Mode = pkcs5.mode;
    algd.Pad_Option = pkcs5.padopt;
    algd.Pad_Character = pkcs5.padchar;
    algd.Effective_Key_Size = pkcs5.effkeysize;
    memcpy(algd.Init_Vector, pkcs5.iv, pkcs5.ivlen);

    /* Create the key and algorithm context tokens. */
    *ctx = libssh2_init_crypto_ctx(NULL);
    if (!*ctx) {
        LIBSSH2_FREE(session, dk);
        return -1;
    }
    libssh2_init_crypto_ctx(*ctx);
    set_EC_length(errcode, sizeof errcode);
    Qc3CreateKeyContext(dk, &pkcs5.dklen, binstring, &algd.Block_Cipher_Alg,
                        qc3clear, NULL, NULL, (*ctx)->key.Key_Context_Token,
                        (char *) &errcode);
    LIBSSH2_FREE(session, dk);
    if (errcode.Bytes_Available) {
        free((char *) *ctx);
        *ctx = NULL;
        return -1;
    }

    Qc3CreateAlgorithmContext((char *) &algd, Qc3_Alg_Block_Cipher,
                              (*ctx)->hash.Alg_Context_Token, &errcode);
    if (errcode.Bytes_Available) {
        Qc3DestroyKeyContext((*ctx)->key.Key_Context_Token, (char *) &ecnull);
        free((char *) *ctx);
        *ctx = NULL;
        return -1;
    }
    return 1;       /* Tell it's encrypted. */
}

static int
rsapkcs8privkey(LIBSSH2_SESSION *session,
                const unsigned char *data, unsigned int datalen,
                const unsigned char *passphrase, void *loadkeydata)
{
    libssh2_rsa_ctx *ctx = (libssh2_rsa_ctx *) loadkeydata;
    char keyform = Qc3_Clear;
    char *kek = NULL;
    char *kea = NULL;
    _libssh2_os400qc3_crypto_ctx *kekctx;
    asn1Element pki;
    int pkilen;
    Qus_EC_t errcode;

    switch (pkcs8kek(session, &kekctx, data, datalen, passphrase, &pki)) {
    case 1:
        keyform = Qc3_Encrypted;
        kek = kekctx->key.Key_Context_Token;
        kea = kekctx->hash.Alg_Context_Token;
    case 0:
        break;
    default:
        return -1;
    }

    set_EC_length(errcode, sizeof errcode);
    pkilen = pki.end - pki.beg;
    Qc3CreateKeyContext((unsigned char *) pki.beg, &pkilen, berstring,
                        rsaprivate, &keyform, kek, kea,
                        ctx->key.Key_Context_Token, (char *) &errcode);
    if (errcode.Bytes_Available) {
        if (kekctx)
            _libssh2_os400qc3_crypto_dtor(kekctx);
        return -1;
    }
    ctx->kek = kekctx;
    return 0;
}

static char *
storewithlength(char *p, const char *data, int length)
{
    _libssh2_htonu32(p, length);
    if (length)
        memcpy(p + 4, data, length);
    return p + 4 + length;
}

static int
sshrsapubkey(LIBSSH2_SESSION *session, char **sshpubkey,
             asn1Element *params, asn1Element *key, const char *method)
{
    int methlen = strlen(method);
    asn1Element keyseq;
    asn1Element m;
    asn1Element e;
    int len;
    char *cp;

    if (getASN1Element(&keyseq, key->beg + 1, key->end) != key->end ||
        *keyseq.header != (ASN1_SEQ | ASN1_CONSTRUCTED))
        return -1;
    if (!getASN1Element(&m, keyseq.beg, keyseq.end) ||
        *m.header != ASN1_INTEGER)
        return -1;
    if (getASN1Element(&e, m.end, keyseq.end) != keyseq.end ||
        *e.header != ASN1_INTEGER)
        return -1;
    len = 4 + methlen + 4 + (e.end - e.beg) + 4 + (m.end - m.beg);
    cp = LIBSSH2_ALLOC(session, len);
    if (!cp)
        return -1;
    *sshpubkey = cp;
    cp = storewithlength(cp, method, methlen);
    cp = storewithlength(cp, e.beg, e.end - e.beg);
    cp = storewithlength(cp, m.beg, m.end - m.beg);
    return len;
}

static int
rsapkcs8pubkey(LIBSSH2_SESSION *session,
               const unsigned char *data, unsigned int datalen,
               const unsigned char *passphrase, void *loadkeydata)
{
    loadpubkeydata *p = (loadpubkeydata *) loadkeydata;
    char *buf;
    int len;
    char *cp;
    int i;
    char keyform = Qc3_Clear;
    char *kek = NULL;
    char *kea = NULL;
    _libssh2_os400qc3_crypto_ctx *kekctx;
    asn1Element subjpubkeyinfo;
    asn1Element algorithmid;
    asn1Element algorithm;
    asn1Element subjpubkey;
    asn1Element parameters;
    asn1Element pki;
    int pkilen;
    Qus_EC_t errcode;

    if (!(buf = alloca(datalen)))
        return -1;

    switch (pkcs8kek(session, &kekctx, data, datalen, passphrase, &pki)) {
    case 1:
        keyform = Qc3_Encrypted;
        kek = kekctx->key.Key_Context_Token;
        kea = kekctx->hash.Alg_Context_Token;
    case 0:
        break;
    default:
        return -1;
    }

    set_EC_length(errcode, sizeof errcode);
    pkilen = pki.end - pki.beg;
    Qc3ExtractPublicKey(pki.beg, &pkilen, berstring, &keyform,
                        kek, kea, buf, (int *) &datalen, &len, &errcode);
    _libssh2_os400qc3_crypto_dtor(kekctx);
    if (errcode.Bytes_Available)
        return -1;
    /* Get the algorithm OID and key data from SubjectPublicKeyInfo. */
    if (getASN1Element(&subjpubkeyinfo, buf, buf + len) != buf + len ||
        *subjpubkeyinfo.header != (ASN1_SEQ | ASN1_CONSTRUCTED))
        return -1;
    cp = getASN1Element(&algorithmid, subjpubkeyinfo.beg, subjpubkeyinfo.end);
    if (!cp || *algorithmid.header != (ASN1_SEQ | ASN1_CONSTRUCTED))
        return -1;
    if (!getASN1Element(&algorithm, algorithmid.beg, algorithmid.end) ||
        *algorithm.header != ASN1_OBJ_ID)
        return -1;
    if (getASN1Element(&subjpubkey, cp, subjpubkeyinfo.end) !=
        subjpubkeyinfo.end || *subjpubkey.header != ASN1_BIT_STRING)
        return -1;
    /* Check for supported algorithm. */
    for (i = 0; pka[i].oid; i++)
        if (!oidcmp(&algorithm, pka[i].oid)) {
            len = (*pka[i].sshpubkey)(session, &p->data, &algorithmid,
                                      &subjpubkey, pka[i].method);
            if (len < 0)
                return -1;
            p->length = len;
            p->method = pka[i].method;
            return 0;
        }
    return -1;                              /* Algorithm not supported. */
}

static int
pkcs1topkcs8(LIBSSH2_SESSION *session,
             const unsigned char **data8, unsigned int *datalen8,
             const unsigned char *data1, unsigned int datalen1)
{
    asn1Element *prvk;
    asn1Element *pkcs8;
    unsigned char *data;

    *data8 = NULL;
    *datalen8 = 0;
    if (datalen1 < 2)
        return -1;
    prvk = asn1_new_from_bytes(data1, datalen1);
    if (!prvk)
        return -1;
    pkcs8 = rsaprivatekeyinfo(prvk);
    asn1delete(prvk);
    if (!prvk) {
        asn1delete(pkcs8);
        pkcs8 = NULL;
    }
    if (!pkcs8)
        return -1;
    data = (unsigned char *) LIBSSH2_ALLOC(session, pkcs8->end - pkcs8->header);
    if (!data) {
        asn1delete(pkcs8);
        return -1;
    }
    *data8 = data;
    *datalen8 = pkcs8->end - pkcs8->header;
    memcpy((char *) data, (char *) pkcs8->header, *datalen8);
    asn1delete(pkcs8);
    return 0;
}

static int
rsapkcs1privkey(LIBSSH2_SESSION *session,
                const unsigned char *data, unsigned int datalen,
                const unsigned char *passphrase, void *loadkeydata)
{
    const unsigned char *data8;
    unsigned int datalen8;
    int ret;

    if (pkcs1topkcs8(session, &data8, &datalen8, data, datalen))
        return -1;
    ret = rsapkcs8privkey(session, data8, datalen8, passphrase, loadkeydata);
    LIBSSH2_FREE(session, (char *) data8);
    return ret;
}

static int
rsapkcs1pubkey(LIBSSH2_SESSION *session,
               const unsigned char *data, unsigned int datalen,
               const unsigned char *passphrase, void *loadkeydata)
{
    const unsigned char *data8;
    unsigned int datalen8;
    int ret;

    if (pkcs1topkcs8(session, &data8, &datalen8, data, datalen))
        return -1;
    ret = rsapkcs8pubkey(session, data8, datalen8, passphrase, loadkeydata);
    LIBSSH2_FREE(session, (char *) data8);
    return ret;
}

static int
try_pem_load(LIBSSH2_SESSION *session, FILE *fp,
             const unsigned char *passphrase,
             const char *header, const char *trailer,
             loadkeyproc proc, void *loadkeydata)
{
    unsigned char *data = NULL;
    unsigned int datalen = 0;
    int c;
    int ret;

    fseek(fp, 0L, SEEK_SET);
    for (;;) {
        ret = _libssh2_pem_parse(session, header, trailer,
                                 fp, &data, &datalen);

        if (!ret) {
            ret = (*proc)(session, data, datalen, passphrase, loadkeydata);
            if (!ret)
                return 0;
        }

        if (data) {
            LIBSSH2_FREE(session, data);
            data = NULL;
        }
        c = getc(fp);

        if (c == EOF)
            break;

        ungetc(c, fp);
    }

    return -1;
}

static int
load_rsa_private_file(LIBSSH2_SESSION *session, const char *filename,
                      unsigned const char *passphrase,
                      loadkeyproc proc1, loadkeyproc proc8, void *loadkeydata)
{
    FILE *fp = fopen(filename, fopenrmode);
    unsigned char *data = NULL;
    size_t datalen = 0;
    int ret;
    long filesize;

    if (!fp)
        return -1;

    /* Try with "ENCRYPTED PRIVATE KEY" PEM armor.
       --> PKCS#8 EncryptedPrivateKeyInfo */
    ret = try_pem_load(session, fp, passphrase, beginencprivkeyhdr,
                       endencprivkeyhdr, proc8, loadkeydata);

    /* Try with "PRIVATE KEY" PEM armor.
       --> PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo */
    if (ret)
        ret = try_pem_load(session, fp, passphrase, beginprivkeyhdr,
                           endprivkeyhdr, proc8, loadkeydata);

    /* Try with "RSA PRIVATE KEY" PEM armor.
       --> PKCS#1 RSAPrivateKey */
    if (ret)
        ret = try_pem_load(session, fp, passphrase, beginrsaprivkeyhdr,
                           endrsaprivkeyhdr, proc1, loadkeydata);
    fclose(fp);

    if (ret) {
        /* Try DER encoding. */
        fp = fopen(filename, fopenrbmode);
        fseek(fp, 0L, SEEK_END);
        filesize = ftell(fp);

        if (filesize <= 32768) {        /* Limit to a reasonable size. */
            datalen = filesize;
            data = (unsigned char *) alloca(datalen);
            if (data) {
                fseek(fp, 0L, SEEK_SET);
                fread(data, datalen, 1, fp);

                /* Try as PKCS#8 DER data.
                   --> PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo */
                ret = (*proc8)(session, data, datalen, passphrase,
                               loadkeydata);

                /* Try as PKCS#1 DER data.
                   --> PKCS#1 RSAPrivateKey */
                if (ret)
                    ret = (*proc1)(session, data, datalen, passphrase,
                                   loadkeydata);
            }
        }
        fclose(fp);
    }

    return ret;
}

int
_libssh2_rsa_new_private(libssh2_rsa_ctx **rsa, LIBSSH2_SESSION *session,
                         const char *filename, unsigned const char *passphrase)
{
    libssh2_rsa_ctx *ctx = libssh2_init_crypto_ctx(NULL);
    int ret;
    Qc3_Format_ALGD0400_T algd;
    Qus_EC_t errcode;

    if (!ctx)
        return -1;
    ret = load_rsa_private_file(session, filename, passphrase,
                                rsapkcs1privkey, rsapkcs8privkey, (void *) ctx);
    if (!ret) {
        /* Create the algorithm context. */
        algd.Public_Key_Alg = Qc3_RSA;
        algd.PKA_Block_Format = Qc3_PKCS1_01;
        memset(algd.Reserved, 0, sizeof algd.Reserved);
        algd.Signing_Hash_Alg = Qc3_SHA1;
        set_EC_length(errcode, sizeof errcode);
        Qc3CreateAlgorithmContext((char *) &algd, Qc3_Alg_Public_Key,
                                  ctx->hash.Alg_Context_Token, &errcode);
        if (errcode.Bytes_Available)
            ret = -1;
    }
    if (ret) {
        _libssh2_os400qc3_crypto_dtor(ctx);
        ctx = NULL;
    }
    *rsa = ctx;
    return ret;
}

int
_libssh2_pub_priv_keyfile(LIBSSH2_SESSION *session,
                          unsigned char **method, size_t *method_len,
                          unsigned char **pubkeydata, size_t *pubkeydata_len,
                          const char *privatekey, const char *passphrase)

{
    loadpubkeydata p;
    int ret;

    *method = NULL;
    *method_len = 0;
    *pubkeydata = NULL;
    *pubkeydata_len = 0;

    ret = load_rsa_private_file(session, privatekey, passphrase,
                                rsapkcs1pubkey, rsapkcs8pubkey, (void *) &p);
    if (!ret) {
        *method_len = strlen(p.method);
        if ((*method = LIBSSH2_ALLOC(session, *method_len)))
            memcpy((char *) *method, p.method, *method_len);
        else
            ret = -1;
    }

    if (ret) {
        if (*method)
            LIBSSH2_FREE(session, *method);
        if (p.data)
            LIBSSH2_FREE(session, (void *) p.data);
        *method = NULL;
        *method_len = 0;
    } else {
        *pubkeydata = (unsigned char *) p.data;
        *pubkeydata_len = p.length;
    }

    return ret;
}

int
_libssh2_rsa_new_private_frommemory(libssh2_rsa_ctx **rsa,
                                    LIBSSH2_SESSION *session,
                                    const char *filedata,
                                    size_t filedata_len,
                                    unsigned const char *passphrase)
{
    libssh2_rsa_ctx *ctx = libssh2_init_crypto_ctx(NULL);
    unsigned char *data = NULL;
    unsigned int datalen = 0;
    int ret;
    Qc3_Format_ALGD0400_T algd;
    Qus_EC_t errcode;

    if (!ctx)
        return -1;

    /* Try with "ENCRYPTED PRIVATE KEY" PEM armor.
       --> PKCS#8 EncryptedPrivateKeyInfo */
    ret = _libssh2_pem_parse_memory(session,
                                    beginencprivkeyhdr, endencprivkeyhdr,
                                    filedata, filedata_len, &data, &datalen);

    /* Try with "PRIVATE KEY" PEM armor.
       --> PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo */
    if (ret)
        ret = _libssh2_pem_parse_memory(session,
                                        beginprivkeyhdr, endprivkeyhdr,
                                        filedata, filedata_len,
                                        &data, &datalen);

    if (!ret) {
        /* Process PKCS#8. */
        ret = rsapkcs8privkey(session,
                              data, datalen, passphrase, (void *) &ctx);
    } else {
        /* Try with "RSA PRIVATE KEY" PEM armor.
           --> PKCS#1 RSAPrivateKey */
        ret = _libssh2_pem_parse_memory(session,
                                        beginrsaprivkeyhdr, endrsaprivkeyhdr,
                                        filedata, filedata_len,
                                        &data, &datalen);
        if (!ret)
            ret = rsapkcs1privkey(session,
                                  data, datalen, passphrase, (void *) &ctx);
    }

    if (ret) {
        /* Try as PKCS#8 DER data.
           --> PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo */
        ret = rsapkcs8privkey(session, filedata, filedata_len,
                              passphrase, (void *) &ctx);

        /* Try as PKCS#1 DER data.
           --> PKCS#1 RSAPrivateKey */
        if (ret)
            ret = rsapkcs1privkey(session, filedata, filedata_len,
                                  passphrase, (void *) &ctx);
    }

    if (data)
        LIBSSH2_FREE(session, data);

    if (!ret) {
        /* Create the algorithm context. */
        algd.Public_Key_Alg = Qc3_RSA;
        algd.PKA_Block_Format = Qc3_PKCS1_01;
        memset(algd.Reserved, 0, sizeof algd.Reserved);
        algd.Signing_Hash_Alg = Qc3_SHA1;
        set_EC_length(errcode, sizeof errcode);
        Qc3CreateAlgorithmContext((char *) &algd, Qc3_Alg_Public_Key,
                                  ctx->hash.Alg_Context_Token, &errcode);
        if (errcode.Bytes_Available)
            ret = -1;
    }

    if (ret) {
        _libssh2_os400qc3_crypto_dtor(ctx);
        ctx = NULL;
    }

    *rsa = ctx;
    return ret;
}

int
_libssh2_pub_priv_keyfilememory(LIBSSH2_SESSION *session,
                                unsigned char **method, size_t *method_len,
                                unsigned char **pubkeydata,
                                size_t *pubkeydata_len,
                                const char *privatekeydata,
                                size_t privatekeydata_len,
                                const char *passphrase)
{
    loadpubkeydata p;
    unsigned char *data = NULL;
    unsigned int datalen = 0;
    const char *meth;
    int ret;

    *method = NULL;
    *method_len = 0;
    *pubkeydata = NULL;
    *pubkeydata_len = 0;

    /* Try with "ENCRYPTED PRIVATE KEY" PEM armor.
       --> PKCS#8 EncryptedPrivateKeyInfo */
    ret = _libssh2_pem_parse_memory(session,
                                    beginencprivkeyhdr, endencprivkeyhdr,
                                    privatekeydata, privatekeydata_len,
                                    &data, &datalen);

    /* Try with "PRIVATE KEY" PEM armor.
       --> PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo */
    if (ret)
        ret = _libssh2_pem_parse_memory(session,
                                        beginprivkeyhdr, endprivkeyhdr,
                                        privatekeydata, privatekeydata_len,
                                        &data, &datalen);

    if (!ret) {
        /* Process PKCS#8. */
        ret = rsapkcs8pubkey(session,
                             data, datalen, passphrase, (void *) &p);
    } else {
        /* Try with "RSA PRIVATE KEY" PEM armor.
           --> PKCS#1 RSAPrivateKey */
        ret = _libssh2_pem_parse_memory(session,
                                        beginrsaprivkeyhdr, endrsaprivkeyhdr,
                                        privatekeydata, privatekeydata_len,
                                        &data, &datalen);
        if (!ret)
            ret = rsapkcs1pubkey(session,
                                 data, datalen, passphrase, (void *) &p);
    }

    if (ret) {
        /* Try as PKCS#8 DER data.
           --> PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo */
        ret = rsapkcs8pubkey(session, privatekeydata, privatekeydata_len,
                             passphrase, (void *) &p);

        /* Try as PKCS#1 DER data.
           --> PKCS#1 RSAPrivateKey */
        if (ret)
            ret = rsapkcs1pubkey(session, privatekeydata, privatekeydata_len,
                                 passphrase, (void *) &p);
    }

    if (data)
        LIBSSH2_FREE(session, data);

    if (!ret) {
        *method_len = strlen(p.method);
        if ((*method = LIBSSH2_ALLOC(session, *method_len)))
            memcpy((char *) *method, p.method, *method_len);
        else
            ret = -1;
    }
    if (ret) {
        if (*method)
            LIBSSH2_FREE(session, *method);
        if (p.data)
            LIBSSH2_FREE(session, (void *) p.data);
        *method = NULL;
        *method_len = 0;
    } else {
        *pubkeydata = (unsigned char *) p.data;
        *pubkeydata_len = p.length;
    }

    return ret;
}

int
_libssh2_rsa_sha1_verify(libssh2_rsa_ctx *rsa,
                         const unsigned char *sig, unsigned long sig_len,
                         const unsigned char *m, unsigned long m_len)
{
    Qus_EC_t errcode;
    int slen = sig_len;
    int mlen = m_len;

    set_EC_length(errcode, sizeof errcode);
    Qc3VerifySignature((char *) sig, &slen, (char *) m, &mlen, Qc3_Data,
                       rsa->hash.Alg_Context_Token, Qc3_Alg_Token,
                       rsa->key.Key_Context_Token, Qc3_Key_Token, anycsp,
                       NULL, (char *) &errcode);
    return errcode.Bytes_Available? -1: 0;
}

int
_libssh2_os400qc3_rsa_sha1_signv(LIBSSH2_SESSION *session,
                                 unsigned char **signature,
                                 size_t *signature_len,
                                 int veccount,
                                 const struct iovec vector[],
                                 libssh2_rsa_ctx *ctx)
{
    Qus_EC_t errcode;
    int siglen;
    unsigned char *sig;
    char sigbuf[8192];
    int sigbufsize = sizeof sigbuf;

    ctx->hash.Final_Op_Flag = Qc3_Final;
    set_EC_length(errcode, sizeof errcode);
    Qc3CalculateSignature((char *) vector, &veccount, Qc3_Array,
                          (char *) &ctx->hash, Qc3_Alg_Token,
                          (char *) &ctx->key, Qc3_Key_Token,
                          anycsp, NULL, sigbuf, &sigbufsize, &siglen,
                          (char *) &errcode);
    ctx->hash.Final_Op_Flag = Qc3_Continue;
    if (errcode.Bytes_Available)
        return -1;
    sig = LIBSSH2_ALLOC(session, siglen);
    if (!sig)
        return -1;
    memcpy((char *) sig, sigbuf, siglen);
    *signature = sig;
    *signature_len = siglen;
    return 0;
}

void
_libssh2_init_aes_ctr(void)
{
}

#endif /* LIBSSH2_OS400QC3 */

/* vim: set expandtab ts=4 sw=4: */