summaryrefslogtreecommitdiffstats
path: root/src/certtool-common.c
blob: fae3a489d48febfa573bf78b4341af167597235c (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
/*
 * Copyright (C) 2003-2016 Free Software Foundation, Inc.
 * Copyright (C) 2015-2017 Red Hat, Inc.
 *
 * This file is part of GnuTLS.
 *
 * GnuTLS is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GnuTLS is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see
 * <https://www.gnu.org/licenses/>.
 */

#include <config.h>

#include <gnutls/gnutls.h>
#include <gnutls/x509.h>
#include <gnutls/openpgp.h>
#include <gnutls/pkcs12.h>
#include <gnutls/pkcs11.h>
#include <gnutls/abstract.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <common.h>
#include "certtool-common.h"
#include "certtool-options.h"
#include "certtool-cfg.h"
#include "common.h"
#include <minmax.h>

/* Gnulib portability files. */
#include <read-file.h>

unsigned char *lbuffer = NULL;
unsigned long lbuffer_size = 0;

static unsigned long file_size(FILE *fp)
{
	unsigned long size;
	long cur = ftell(fp);

	if (cur == -1)
		return 0;

	if (fseek(fp, 0, SEEK_END) == -1)
		return 0;

	size = ftell(fp);
	if (fseek(fp, cur, SEEK_SET) == -1) {
		fprintf(stderr, "Error reading file size\n");
		app_exit(1);
	}
	return size;
}

void fix_lbuffer(unsigned long size)
{
	if (lbuffer_size == 0 || lbuffer == NULL) {
		if (size == 0)
			lbuffer_size = 64*1024;
		else
			lbuffer_size = MAX(64*1024,size+1);
		lbuffer = malloc(lbuffer_size);
	} else if (size > lbuffer_size) {
		lbuffer_size = MAX(64*1024,size+1);
		lbuffer = realloc(lbuffer, lbuffer_size);
	}

	if (lbuffer == NULL) {
		fprintf(stderr, "memory error");
		app_exit(1);
	}
}

FILE *safe_open_rw(const char *file, int privkey_op)
{
	mode_t omask = 0;
	FILE *fh;

	if (privkey_op != 0) {
		omask = umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
	}

	fh = fopen(file, "wb");

	if (privkey_op != 0) {
		umask(omask);
	}

	return fh;
}

gnutls_datum_t *load_secret_key(int mand, common_info_st * info)
{
	static char raw_key[64];
	size_t raw_key_size = sizeof(raw_key);
	static gnutls_datum_t key;
	gnutls_datum_t hex_key;
	int ret;

	if (info->verbose)
		fprintf(stderr, "Loading secret key...\n");

	if (info->secret_key == NULL) {
		if (mand) {
			fprintf(stderr, "missing --secret-key\n");
			app_exit(1);
		} else
			return NULL;
	}

	hex_key.data = (void *) info->secret_key;
	hex_key.size = strlen(info->secret_key);

	ret = gnutls_hex_decode(&hex_key, raw_key, &raw_key_size);
	if (ret < 0) {
		fprintf(stderr, "hex_decode: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}

	key.data = (void *) raw_key;
	key.size = raw_key_size;

	return &key;
}

const char *get_password(common_info_st * cinfo, unsigned int *flags,
			 int confirm)
{
	const char *p;

	if (cinfo->null_password) {
		if (flags)
			*flags |= GNUTLS_PKCS_NULL_PASSWORD;
		return NULL;
	} else if (cinfo->password) {
		p = cinfo->password;
	} else {
		if (confirm)
			p = get_confirmed_pass(true);
		else
			p = get_pass();
	}

	if ((p == NULL || p[0] == 0) && flags && !cinfo->empty_password)
		*flags |= GNUTLS_PKCS_PLAIN;

	return p;
}

static gnutls_privkey_t _load_privkey(gnutls_datum_t * dat,
				      common_info_st * info)
{
	int ret;
	gnutls_privkey_t key;
	unsigned int flags = 0;
	const char *pass;

	ret = gnutls_privkey_init(&key);
	if (ret < 0) {
		fprintf(stderr, "privkey_init: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}

	ret =
	    gnutls_privkey_import_x509_raw(key, dat, info->incert_format,
					   NULL, 0);
	if (ret == GNUTLS_E_DECRYPTION_FAILED) {
		pass = get_password(info, &flags, 0);
		ret =
		    gnutls_privkey_import_x509_raw(key, dat,
						   info->incert_format,
						   pass, flags);
	}

	if (ret == GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR) {
		fprintf(stderr,
			"import error: could not find a valid PEM header; "
			"check if your key is PKCS #12 encoded\n");
		app_exit(1);
	}

	if (ret < 0) {
		fprintf(stderr, "error loading file at --load-privkey: %s: %s\n",
			info->privkey, gnutls_strerror(ret));
		app_exit(1);
	}

	return key;
}

static gnutls_privkey_t _load_url_privkey(const char *url)
{
	int ret;
	gnutls_privkey_t key;

	ret = gnutls_privkey_init(&key);
	if (ret < 0) {
		fprintf(stderr, "privkey_init: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}

	ret = gnutls_privkey_import_url(key, url, 0);
	if (ret < 0) {
		fprintf(stderr, "error importing key at %s: %s\n",
			url, gnutls_strerror(ret));
		app_exit(1);
	}

	return key;
}

static gnutls_pubkey_t _load_url_pubkey(const char *url)
{
	int ret;
	gnutls_pubkey_t pubkey;
	unsigned int obj_flags = 0;

	ret = gnutls_pubkey_init(&pubkey);
	if (ret < 0) {
		fprintf(stderr, "Error in %s:%d: %s\n", __func__, __LINE__,
			gnutls_strerror(ret));
		app_exit(1);
	}

	ret = gnutls_pubkey_import_url(pubkey, url, obj_flags);
	if (ret < 0) {
		fprintf(stderr, "Error in %s:%d: %s: %s\n", __func__,
			__LINE__, gnutls_strerror(ret), url);
		app_exit(1);
	}

	return pubkey;
}

/* Load the private key.
 * @mand should be non zero if it is required to read a private key.
 */
gnutls_privkey_t load_private_key(int mand, common_info_st * info)
{
	gnutls_privkey_t key;
	gnutls_datum_t dat;
	size_t size;

	if (!info->privkey && !mand)
		return NULL;

	if (info->privkey == NULL) {
		fprintf(stderr, "missing --load-privkey\n");
		app_exit(1);
	}

	if (gnutls_url_is_supported(info->privkey) != 0)
		return _load_url_privkey(info->privkey);

	dat.data = (void *) read_file(info->privkey, RF_BINARY, &size);
	dat.size = size;

	if (!dat.data) {
		fprintf(stderr, "error reading file at --load-privkey: %s\n",
			info->privkey);
		app_exit(1);
	}

	key = _load_privkey(&dat, info);

	free(dat.data);

	return key;
}

/* Load the private key.
 * @mand should be non zero if it is required to read a private key.
 */
gnutls_x509_privkey_t
load_x509_private_key(int mand, common_info_st * info)
{
	gnutls_x509_privkey_t key;
	int ret;
	gnutls_datum_t dat;
	size_t size;
	unsigned int flags = 0;
	const char *pass;

	if (!info->privkey && !mand)
		return NULL;

	if (info->privkey == NULL) {
		fprintf(stderr, "missing --load-privkey\n");
		app_exit(1);
	}

	ret = gnutls_x509_privkey_init(&key);
	if (ret < 0) {
		fprintf(stderr, "privkey_init: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}

	dat.data = (void *) read_file(info->privkey, RF_BINARY, &size);
	dat.size = size;

	if (!dat.data) {
		fprintf(stderr, "error reading file at --load-privkey: %s\n",
			info->privkey);
		app_exit(1);
	}

	if (info->pkcs8) {
		pass = get_password(info, &flags, 0);
		ret =
		    gnutls_x509_privkey_import_pkcs8(key, &dat,
						     info->incert_format,
						     pass, flags);
	} else {
		ret =
		    gnutls_x509_privkey_import2(key, &dat,
						info->incert_format, NULL,
						0);
		if (ret == GNUTLS_E_DECRYPTION_FAILED) {
			pass = get_password(info, &flags, 0);
			ret =
			    gnutls_x509_privkey_import2(key, &dat,
							info->
							incert_format,
							pass, flags);
		}
	}

	free(dat.data);

	if (ret == GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR) {
		fprintf(stderr,
			"import error: could not find a valid PEM header; "
			"check if your key is PEM encoded\n");
		app_exit(1);
	}

	if (ret < 0) {
		fprintf(stderr, "error importing private key: %s: %s\n",
			info->privkey, gnutls_strerror(ret));
		app_exit(1);
	}

	return key;
}


/* Loads the certificate
 * If mand is non zero then a certificate is mandatory. Otherwise
 * null will be returned if the certificate loading fails.
 */
gnutls_x509_crt_t load_cert(int mand, common_info_st * info)
{
	gnutls_x509_crt_t *crt;
	gnutls_x509_crt_t ret_crt;
	size_t size, i;

	crt = load_cert_list(mand, &size, info);
	if (crt) {
		ret_crt = crt[0];
		for (i=1;i<size;i++)
			gnutls_x509_crt_deinit(crt[i]);
		gnutls_free(crt);
		return ret_crt;
	}

	return NULL;
}

/* Loads a certificate list
 */
gnutls_x509_crt_t *load_cert_list(int mand, size_t * crt_size,
				  common_info_st * info)
{
	FILE *fp;
	static gnutls_x509_crt_t *crt;
	int ret;
	gnutls_datum_t dat;
	unsigned size;
	unsigned int crt_max;
	unsigned flags = 0;

	*crt_size = 0;
	if (info->verbose)
		fprintf(stderr, "Loading certificate list...\n");

	if (info->cert == NULL) {
		if (mand) {
			fprintf(stderr, "missing --load-certificate\n");
			app_exit(1);
		} else
			return NULL;
	}

	fp = fopen(info->cert, "r");
	if (fp == NULL) {
		fprintf(stderr, "Could not open %s\n", info->cert);
		app_exit(1);
	}

	fix_lbuffer(file_size(fp));

	size = fread(lbuffer, 1, lbuffer_size - 1, fp);
	lbuffer[size] = 0;

	fclose(fp);

	dat.data = (void *) lbuffer;
	dat.size = size;

	if (info->sort_chain)
		flags |= GNUTLS_X509_CRT_LIST_SORT;

	ret = gnutls_x509_crt_list_import2(&crt, &crt_max, &dat, GNUTLS_X509_FMT_PEM, flags);
	if (ret < 0) {
		fprintf(stderr, "Error loading certificates: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}

	*crt_size = crt_max;

	if (info->verbose)
		fprintf(stderr, "Loaded %d certificates.\n",
			(int) crt_max);

	return crt;
}

/* Loads a CRL list
 */
gnutls_x509_crl_t *load_crl_list(int mand, size_t * crl_size,
				  common_info_st * info)
{
	FILE *fp;
	static gnutls_x509_crl_t *crl;
	unsigned int crl_max;
	int ret;
	gnutls_datum_t dat;
	size_t size;

	*crl_size = 0;
	if (info->verbose)
		fprintf(stderr, "Loading CRL list...\n");

	if (info->crl == NULL) {
		if (mand) {
			fprintf(stderr, "missing --load-crl\n");
			app_exit(1);
		} else
			return NULL;
	}

	fp = fopen(info->crl, "r");
	if (fp == NULL) {
		fprintf(stderr, "Could not open %s\n", info->crl);
		app_exit(1);
	}

	fix_lbuffer(file_size(fp));

	size = fread(lbuffer, 1, lbuffer_size - 1, fp);
	lbuffer[size] = 0;

	fclose(fp);

	dat.data = (void *) lbuffer;
	dat.size = size;

	ret = gnutls_x509_crl_list_import2(&crl, &crl_max, &dat, GNUTLS_X509_FMT_PEM, 0);
	if (ret == GNUTLS_E_BASE64_DECODING_ERROR) {
		ret = gnutls_x509_crl_list_import2(&crl, &crl_max, &dat, GNUTLS_X509_FMT_DER, 0);
	}
	if (ret < 0) {
		fprintf(stderr, "Error loading CRLs: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}

	*crl_size = crl_max;

	if (info->verbose)
		fprintf(stderr, "Loaded %d CRLs.\n",
			(int) *crl_size);

	return crl;
}

/* Load the Certificate Request.
 */
gnutls_x509_crq_t load_request(common_info_st * info)
{
	gnutls_x509_crq_t crq;
	int ret;
	gnutls_datum_t dat;
	size_t size;

	if (!info->request)
		return NULL;

	ret = gnutls_x509_crq_init(&crq);
	if (ret < 0) {
		fprintf(stderr, "crq_init: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}

	dat.data = (void *) read_file(info->request, RF_BINARY, &size);
	dat.size = size;

	if (!dat.data) {
		fprintf(stderr, "error reading file at --load-request: %s\n",
			info->request);
		app_exit(1);
	}

	ret = gnutls_x509_crq_import(crq, &dat, info->incert_format);
	if (ret == GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR) {
		fprintf(stderr,
			"import error: could not find a valid PEM header\n");
		app_exit(1);
	}

	free(dat.data);
	if (ret < 0) {
		fprintf(stderr, "error importing certificate request: %s: %s\n",
			info->request, gnutls_strerror(ret));
		app_exit(1);
	}
	return crq;
}

/* Load the CA's private key.
 */
gnutls_privkey_t load_ca_private_key(common_info_st * info)
{
	gnutls_privkey_t key;
	gnutls_datum_t dat;
	size_t size;

	if (info->ca_privkey == NULL) {
		fprintf(stderr, "missing --load-ca-privkey\n");
		app_exit(1);
	}

	if (gnutls_url_is_supported(info->ca_privkey) != 0)
		return _load_url_privkey(info->ca_privkey);

	dat.data = (void *) read_file(info->ca_privkey, RF_BINARY, &size);
	dat.size = size;

	if (!dat.data) {
		fprintf(stderr, "error reading file at --load-ca-privkey: %s\n",
			info->ca_privkey);
		app_exit(1);
	}

	key = _load_privkey(&dat, info);

	free(dat.data);

	return key;
}

/* Loads the CA's certificate
 */
gnutls_x509_crt_t load_ca_cert(unsigned mand, common_info_st * info)
{
	gnutls_x509_crt_t crt;
	int ret;
	gnutls_datum_t dat;
	size_t size;

	if (mand == 0 && info->ca == NULL) {
		return NULL;
	}

	if (info->ca == NULL) {
		fprintf(stderr, "missing --load-ca-certificate\n");
		app_exit(1);
	}

	ret = gnutls_x509_crt_init(&crt);
	if (ret < 0) {
		fprintf(stderr, "crt_init: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}

	if (gnutls_url_is_supported(info->ca) != 0) {
		ret = gnutls_x509_crt_import_url(crt, info->ca, 0);
		if (ret < 0) {
			fprintf(stderr, "error importing CA certificate: %s: %s\n",
				info->ca, gnutls_strerror(ret));
			app_exit(1);
		}
		return crt;
	}

	dat.data = (void *) read_file(info->ca, RF_BINARY, &size);
	dat.size = size;

	if (!dat.data) {
		fprintf(stderr, "error reading file at --load-ca-certificate: %s\n",
			info->ca);
		app_exit(1);
	}

	ret = gnutls_x509_crt_import(crt, &dat, info->incert_format);
	free(dat.data);
	if (ret < 0) {
		fprintf(stderr, "error importing CA certificate: %s: %s\n",
			info->ca, gnutls_strerror(ret));
		app_exit(1);
	}

	return crt;
}

/* Load a public key.
 * @mand should be non zero if it is required to read a public key.
 */
gnutls_pubkey_t load_pubkey(int mand, common_info_st * info)
{
	gnutls_pubkey_t key;
	int ret;
	gnutls_datum_t dat;
	size_t size;

	if (!info->pubkey && !mand)
		return NULL;

	if (info->pubkey == NULL) {
		fprintf(stderr, "missing --load-pubkey\n");
		app_exit(1);
	}

	if (gnutls_url_is_supported(info->pubkey) != 0)
		return _load_url_pubkey(info->pubkey);

	ret = gnutls_pubkey_init(&key);
	if (ret < 0) {
		fprintf(stderr, "privkey_init: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}

	dat.data = (void *) read_file(info->pubkey, RF_BINARY, &size);
	dat.size = size;

	if (!dat.data) {
		fprintf(stderr, "error reading file at --load-pubkey: %s\n", info->pubkey);
		app_exit(1);
	}

	ret = gnutls_pubkey_import(key, &dat, info->incert_format);
	if (ret == GNUTLS_E_BASE64_UNEXPECTED_HEADER_ERROR) {
		ret = gnutls_pubkey_import_x509_raw(key, &dat, info->incert_format, 0);
		if (ret < 0) {
			fprintf(stderr,
				"import error: could not find a valid PEM header; "
				"check if your key has the PUBLIC KEY header\n");
			app_exit(1);
		}
	} else if (ret < 0) {
		fprintf(stderr, "importing public key: %s: %s\n",
			info->pubkey, gnutls_strerror(ret));
		app_exit(1);
	}

	free(dat.data);
	return key;
}

gnutls_pubkey_t load_public_key_or_import(int mand,
					  gnutls_privkey_t privkey,
					  common_info_st * info)
{
	gnutls_pubkey_t pubkey;
	int ret;

	ret = gnutls_pubkey_init(&pubkey);
	if (ret < 0) {
		fprintf(stderr, "gnutls_pubkey_init: %s\n",
			gnutls_strerror(ret));
		app_exit(1);
	}

	if (!privkey || gnutls_pubkey_import_privkey(pubkey, privkey, 0, 0) < 0) {	/* could not get (e.g. on PKCS #11) */
		gnutls_pubkey_deinit(pubkey);
		pubkey = load_pubkey(0, info);
		if (pubkey == NULL && mand) {
			fprintf(stderr, "Could not determine the public key for the operation.\nYou must specify --load-privkey or --load-pubkey if missing.\n");
			app_exit(1);
		}
	}

	return pubkey;
}

static const char *bits_to_sp(gnutls_pk_algorithm_t pk, unsigned int bits)
{
	gnutls_sec_param_t s = gnutls_pk_bits_to_sec_param(pk, bits);
	if (s == GNUTLS_SEC_PARAM_UNKNOWN) {
		return gnutls_sec_param_get_name(GNUTLS_SEC_PARAM_MEDIUM);
	}

	return gnutls_sec_param_get_name(s);
}

int
get_bits(gnutls_pk_algorithm_t key_type, int info_bits,
	 const char *info_sec_param, int warn)
{
	int bits;

	if (info_bits != 0) {
		static int warned = 0;

		if (warned == 0 && warn != 0 && GNUTLS_BITS_ARE_CURVE(info_bits)==0) {
			warned = 1;
			fprintf(stderr,
				"** Note: You may use '--sec-param %s' instead of '--bits %d'\n",
				bits_to_sp(key_type, info_bits), info_bits);
		}
		bits = info_bits;
	} else {
		if (info_sec_param == 0) {
			/* For ECDSA keys use 256 bits or better, as they are widely supported */
			info_sec_param = "HIGH";
		}
		bits =
		    gnutls_sec_param_to_pk_bits(key_type,
						str_to_sec_param
						(info_sec_param));
	}

	return bits;
}

gnutls_sec_param_t str_to_sec_param(const char *str)
{
	if (strcasecmp(str, "low") == 0) {
		return GNUTLS_SEC_PARAM_LOW;
	} else if (strcasecmp(str, "legacy") == 0) {
		return GNUTLS_SEC_PARAM_LEGACY;
	} else if (strcasecmp(str, "normal") == 0 || strcasecmp(str, "medium") == 0) {
		return GNUTLS_SEC_PARAM_MEDIUM;
	} else if (strcasecmp(str, "high") == 0) {
		return GNUTLS_SEC_PARAM_HIGH;
	} else if (strcasecmp(str, "ultra") == 0) {
		return GNUTLS_SEC_PARAM_ULTRA;
	} else if (strcasecmp(str, "future") == 0) {
		return GNUTLS_SEC_PARAM_FUTURE;
	} else {
		fprintf(stderr, "Unknown security parameter string: %s\n",
			str);
		app_exit(1);
	}

}

#define SPACE "\t"
static void
print_hex_datum(FILE * outfile, gnutls_datum_t * dat, int cprint)
{
	unsigned int j;

	if (cprint != 0) {
		fprintf(outfile, "\n" SPACE "\"");
		for (j = 0; j < dat->size; j++) {
			fprintf(outfile, "\\x%.2x",
				(unsigned char) dat->data[j]);
			if ((j + 1) % 16 == 0) {
				fprintf(outfile, "\"\n" SPACE "\"");
			}
		}
		fprintf(outfile, "\";\n\n");

		return;
	}

	fprintf(outfile, "\n" SPACE);
	for (j = 0; j < dat->size; j++) {
		if ((j + 1) % 16 == 0) {
			fprintf(outfile, "%.2x", (unsigned char) dat->data[j]);
			fprintf(outfile, "\n" SPACE);
		} else {
			fprintf(outfile, "%.2x:", (unsigned char) dat->data[j]);
		}
	}
	fprintf(outfile, "\n\n");
}

static void print_head(FILE * out, const char *txt, unsigned int size,
		       int cprint)
{
	unsigned i;
	char *p, *ntxt;
	int ret;

	if (cprint != 0) {
		if (size > 0)
			ret = asprintf(&ntxt, "const unsigned char %s[%u] =",
				       txt, size);
		else
			ret = asprintf(&ntxt, "const unsigned char %s[] =\n",
				       txt);

		if (ret == -1) {
			fprintf(stderr, "memory error\n");
			app_exit(1);
		}

		p = strstr(ntxt, "char");
		p += 5;

		for (i = 0; i < strlen(txt); i++)
			if (p[i] == ' ')
				p[i] = '_';

		fprintf(out, "%s", ntxt);
		free(ntxt);

		return;
	}
	fprintf(out, "%s:", txt);
}

void
print_dsa_pkey(FILE * outfile, gnutls_datum_t * x, gnutls_datum_t * y,
	       gnutls_datum_t * p, gnutls_datum_t * q, gnutls_datum_t * g,
	       int cprint)
{
	if (x) {
		print_head(outfile, "private key", x->size, cprint);
		print_hex_datum(outfile, x, cprint);
	}
	print_head(outfile, "public key", y->size, cprint);
	print_hex_datum(outfile, y, cprint);
	print_head(outfile, "p", p->size, cprint);
	print_hex_datum(outfile, p, cprint);
	print_head(outfile, "q", q->size, cprint);
	print_hex_datum(outfile, q, cprint);
	print_head(outfile, "g", g->size, cprint);
	print_hex_datum(outfile, g, cprint);
}

gnutls_ecc_curve_t str_to_curve(const char *str)
{
unsigned num = 0;
const gnutls_ecc_curve_t *list, *p;

	list = gnutls_ecc_curve_list();

	p = list;
	while(*p != 0) {
		if (strcasecmp(str, gnutls_ecc_curve_get_name(*p)) == 0)
			return *p;
		p++;
		num++;
	}

	fprintf(stderr, "Unsupported curve: %s\nAvailable curves:\n", str);
	if (num == 0)
		printf("none\n");
	p = list;
	while(*p != 0) {
		fprintf(stderr, "\t- %s\n",
		       gnutls_ecc_curve_get_name(*p));
		p++;
	}
	app_exit(1);
}

void
print_ecc_pkey(FILE * outfile, gnutls_ecc_curve_t curve,
	       gnutls_datum_t * k, gnutls_datum_t * x, gnutls_datum_t * y,
	       int cprint)
{
	if (cprint != 0)
		fprintf(outfile, "/* curve: %s */\n",
			gnutls_ecc_curve_get_name(curve));
	else
		fprintf(outfile, "curve:\t%s\n",
			gnutls_ecc_curve_get_name(curve));

	if (k && k->data) {
		print_head(outfile, "private key", k->size, cprint);
		print_hex_datum(outfile, k, cprint);
	}

	if (x && x->data) {
		print_head(outfile, "x", x->size, cprint);
		print_hex_datum(outfile, x, cprint);
	}

	if (y && y->data) {
		print_head(outfile, "y", y->size, cprint);
		print_hex_datum(outfile, y, cprint);
	}
}

static void reverse_datum(gnutls_datum_t *d)
{
	unsigned int i;
	unsigned char c;

	for (i = 0; i < d->size / 2; i++) {
		c = d->data[i];
		d->data[i] = d->data[d->size - i - 1];
		d->data[d->size - i - 1] = c;
	}
}

void
print_gost_pkey(FILE * outfile, gnutls_ecc_curve_t curve,
	       gnutls_digest_algorithm_t digest, gnutls_gost_paramset_t paramset,
	       gnutls_datum_t * k, gnutls_datum_t * x, gnutls_datum_t * y,
	       int cprint)
{
	if (cprint != 0)
		fprintf(outfile, "/* curve: %s */\n",
			gnutls_ecc_curve_get_name(curve));
	else
		fprintf(outfile, "curve:\t%s\n",
			gnutls_ecc_curve_get_name(curve));

	if (cprint != 0)
		fprintf(outfile, "/* digest: %s */\n",
			gnutls_digest_get_name(digest));
	else
		fprintf(outfile, "digest:\t%s\n",
			gnutls_digest_get_name(digest));

	if (cprint != 0)
		fprintf(outfile, "/* paramset: %s */\n",
			gnutls_gost_paramset_get_name(paramset));
	else
		fprintf(outfile, "paramset:\t%s\n",
			gnutls_gost_paramset_get_name(paramset));

	if (k) {
		reverse_datum(k);
		print_head(outfile, "private key", k->size, cprint);
		print_hex_datum(outfile, k, cprint);
	}
	reverse_datum(x);
	reverse_datum(y);
	print_head(outfile, "x", x->size, cprint);
	print_hex_datum(outfile, x, cprint);
	print_head(outfile, "y", y->size, cprint);
	print_hex_datum(outfile, y, cprint);
}

void
print_rsa_pkey(FILE * outfile, gnutls_datum_t * m, gnutls_datum_t * e,
	       gnutls_datum_t * d, gnutls_datum_t * p, gnutls_datum_t * q,
	       gnutls_datum_t * u, gnutls_datum_t * exp1,
	       gnutls_datum_t * exp2, int cprint)
{
	print_head(outfile, "modulus", m->size, cprint);
	print_hex_datum(outfile, m, cprint);
	print_head(outfile, "public exponent", e->size, cprint);
	print_hex_datum(outfile, e, cprint);
	if (d) {
		print_head(outfile, "private exponent", d->size, cprint);
		print_hex_datum(outfile, d, cprint);
		print_head(outfile, "prime1", p->size, cprint);
		print_hex_datum(outfile, p, cprint);
		print_head(outfile, "prime2", q->size, cprint);
		print_hex_datum(outfile, q, cprint);
		print_head(outfile, "coefficient", u->size, cprint);
		print_hex_datum(outfile, u, cprint);
		if (exp1 && exp2) {
			print_head(outfile, "exp1", exp1->size, cprint);
			print_hex_datum(outfile, exp1, cprint);
			print_head(outfile, "exp2", exp2->size, cprint);
			print_hex_datum(outfile, exp2, cprint);
		}
	}
}

void print_pubkey_info(gnutls_pubkey_t pubkey,
		       FILE *outfile,
		       gnutls_certificate_print_formats_t format,
		       gnutls_x509_crt_fmt_t outcert_format,
		       unsigned int outtext)
{
	gnutls_datum_t data;
	int ret;
	size_t size;

	if (outtext) {
		ret = gnutls_pubkey_print(pubkey, format, &data);
		if (ret < 0) {
			fprintf(stderr, "pubkey_print error: %s\n",
				gnutls_strerror(ret));
			app_exit(1);
		}

		fprintf(outfile, "%s\n\n", data.data);
		gnutls_free(data.data);
	}

	fix_lbuffer(0);

	size = lbuffer_size;
	ret =
	    gnutls_pubkey_export(pubkey, outcert_format, lbuffer,
				 &size);
	if (ret < 0) {
		fprintf(stderr, "export error: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}

	fwrite(lbuffer, 1, size, outfile);
}

static void
print_dh_info(FILE * outfile, gnutls_datum_t * p, gnutls_datum_t * g,
	      unsigned int q_bits, int cprint)
{
	if (q_bits > 0) {
		if (cprint != 0)
			fprintf(outfile,
				"\n /* recommended key length: %d bytes */\n\n",
				(7 + q_bits) / 8);
		else
			fprintf(outfile,
				"\nRecommended key length: %d bits\n\n",
				q_bits);
	}

	print_head(outfile, "generator", g->size, cprint);
	print_hex_datum(outfile, g, cprint);

	print_head(outfile, "prime", p->size, cprint);
	print_hex_datum(outfile, p, cprint);


}

static
int import_dsa_dh(gnutls_dh_params_t dh_params, gnutls_datum_t *params, gnutls_x509_crt_fmt_t format)
{
	gnutls_x509_privkey_t pkey;
	int ret;

	ret = gnutls_x509_privkey_init(&pkey);
	if (ret < 0)
		return ret;

	ret = gnutls_x509_privkey_import(pkey, params, format);
	if (ret < 0)
		return ret;

	ret = gnutls_dh_params_import_dsa(dh_params, pkey);

	gnutls_x509_privkey_deinit(pkey);

	return ret;
}

void dh_info(FILE * infile, FILE * outfile, common_info_st * ci)
{
	gnutls_datum_t params;
	size_t size;
	int ret, ret2;
	gnutls_dh_params_t dh_params;
	gnutls_datum_t p, g;
	unsigned int q_bits = 0;

	fix_lbuffer(0);

	if (gnutls_dh_params_init(&dh_params) < 0) {
		fprintf(stderr, "Error in dh parameter initialization\n");
		app_exit(1);
	}

	params.data = (void *) fread_file(infile, 0, &size);
	params.size = size;

	if (params.data == NULL) {
		fprintf(stderr, "Could not read input\n");
		app_exit(1);
	}

	ret =
	    gnutls_dh_params_import_pkcs3(dh_params, &params,
					  ci->incert_format);
	if (ret < 0) {
		/* Try DSA */
		ret2 = import_dsa_dh(dh_params, &params, ci->incert_format);
		if (ret2 < 0) {
			fprintf(stderr, "Error parsing dh params: %s\n",
				gnutls_strerror(ret));
			app_exit(1);
		}
	}

	ret = gnutls_dh_params_export_raw(dh_params, &p, &g, &q_bits);
	if (ret < 0) {
		fprintf(stderr, "Error exporting parameters: %s\n",
			gnutls_strerror(ret));
		app_exit(1);
	}

	if (ci->outtext)
		print_dh_info(outfile, &p, &g, q_bits, ci->cprint);

	if (!ci->cprint) {	/* generate a PKCS#3 structure */
		size_t len = lbuffer_size;

		ret =
		    gnutls_dh_params_export_pkcs3(dh_params,
						  ci->outcert_format,
						  lbuffer, &len);

		if (ret == 0) {
			if (ci->outcert_format == GNUTLS_X509_FMT_PEM) {
				fprintf(outfile, "\n%s", lbuffer);
			} else {
				fwrite(lbuffer, 1, len, outfile);
			}
		} else {
			fprintf(stderr, "Error: %s\n",
				gnutls_strerror(ret));
		}
	}

	gnutls_free(p.data);
	gnutls_free(g.data);
	gnutls_dh_params_deinit(dh_params);
}

int cipher_to_flags(const char *cipher)
{
	if (cipher == NULL) {
		return GNUTLS_PKCS_USE_PBES2_AES_128;
	} else if (strcasecmp(cipher, "3des") == 0) {
		return GNUTLS_PKCS_USE_PBES2_3DES;
	} else if (strcasecmp(cipher, "3des-pkcs12") == 0) {
		return GNUTLS_PKCS_USE_PKCS12_3DES;
	} else if (strcasecmp(cipher, "arcfour") == 0) {
		return GNUTLS_PKCS_USE_PKCS12_ARCFOUR;
	} else if (strcasecmp(cipher, "aes-128") == 0) {
		return GNUTLS_PKCS_USE_PBES2_AES_128;
	} else if (strcasecmp(cipher, "aes-192") == 0) {
		return GNUTLS_PKCS_USE_PBES2_AES_192;
	} else if (strcasecmp(cipher, "aes-256") == 0) {
		return GNUTLS_PKCS_USE_PBES2_AES_256;
	} else if (strcasecmp(cipher, "rc2-40") == 0) {
		return GNUTLS_PKCS_USE_PKCS12_RC2_40;
	} else if (strcasecmp(cipher, "gost28147-tc26z") == 0) {
		return GNUTLS_PKCS_USE_PBES2_GOST_TC26Z;
	} else if (strcasecmp(cipher, "gost28147-cpa") == 0) {
		return GNUTLS_PKCS_USE_PBES2_GOST_CPA;
	} else if (strcasecmp(cipher, "gost28147-cpb") == 0) {
		return GNUTLS_PKCS_USE_PBES2_GOST_CPB;
	} else if (strcasecmp(cipher, "gost28147-cpc") == 0) {
		return GNUTLS_PKCS_USE_PBES2_GOST_CPC;
	} else if (strcasecmp(cipher, "gost28147-cpd") == 0) {
		return GNUTLS_PKCS_USE_PBES2_GOST_CPD;
	} else if (strcasecmp(cipher, "none") == 0) {
		return GNUTLS_PKCS_PLAIN;
	}

	fprintf(stderr, "unknown cipher %s\n", cipher);
	app_exit(1);
}

static void privkey_info_int(FILE *outfile, common_info_st * cinfo,
			     gnutls_x509_privkey_t key)
{
	int ret, key_type;
	unsigned int bits = 0;
	size_t size;
	const char *cprint;
	gnutls_x509_spki_t spki;
	gnutls_digest_algorithm_t dig;

	/* Public key algorithm
	 */
	fprintf(outfile, "Public Key Info:\n");
	ret = gnutls_x509_spki_init(&spki);
	if (ret < 0) {
		fprintf(stderr, "spki_init: %s\n", gnutls_strerror(ret));
		return;
	}

	fprintf(outfile, "\tPublic Key Algorithm: ");

	key_type = gnutls_x509_privkey_get_pk_algorithm2(key, &bits);

	cprint = gnutls_pk_algorithm_get_name(key_type);
	fprintf(outfile, "%s\n", cprint ? cprint : "Unknown");

	if (key_type == GNUTLS_PK_RSA_PSS) {
		unsigned int salt_size;

		ret = gnutls_x509_privkey_get_spki(key, spki, 0);
		if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
			goto spki_skip;

		if (ret < 0) {
			fprintf(stderr, "spki_get: %s\n", gnutls_strerror(ret));
			goto spki_skip;
		}

		ret = gnutls_x509_spki_get_rsa_pss_params(spki, &dig, &salt_size);
		if (ret < 0) {
			fprintf(stderr, "spki_get_rsa_pss_params: %s\n",
				gnutls_strerror(ret));
		} else {
			fprintf(outfile, "\t\tHash Algorithm: %s\n",
				gnutls_digest_get_name(dig));
			fprintf(outfile, "\t\tSalt Length: %d\n", salt_size);
		}
	}

 spki_skip:
	gnutls_x509_spki_deinit(spki);
	fprintf(outfile, "\tKey Security Level: %s (%u bits)\n\n",
		gnutls_sec_param_get_name(gnutls_x509_privkey_sec_param
					  (key)), bits);

	/* Print the raw public and private keys
	 */
	if (GNUTLS_PK_IS_RSA(key_type)) {
		gnutls_datum_t m, e, d, p, q, u, exp1, exp2;

		ret =
		    gnutls_x509_privkey_export_rsa_raw2(key, &m, &e, &d,
							&p, &q, &u, &exp1,
							&exp2);
		if (ret < 0)
			fprintf(stderr,
				"Error in key RSA data export: %s\n",
				gnutls_strerror(ret));
		else {
			print_rsa_pkey(outfile, &m, &e, &d, &p, &q, &u,
				       &exp1, &exp2, cinfo->cprint);

			gnutls_free(m.data);
			gnutls_free(e.data);
			gnutls_free(d.data);
			gnutls_free(p.data);
			gnutls_free(q.data);
			gnutls_free(u.data);
			gnutls_free(exp1.data);
			gnutls_free(exp2.data);
		}
	} else if (key_type == GNUTLS_PK_DSA) {
		gnutls_datum_t p, q, g, y, x;

		ret =
		    gnutls_x509_privkey_export_dsa_raw(key, &p, &q, &g, &y,
						       &x);
		if (ret < 0)
			fprintf(stderr,
				"Error in key DSA data export: %s\n",
				gnutls_strerror(ret));
		else {
			print_dsa_pkey(outfile, &x, &y, &p, &q, &g,
				       cinfo->cprint);

			gnutls_free(x.data);
			gnutls_free(y.data);
			gnutls_free(p.data);
			gnutls_free(q.data);
			gnutls_free(g.data);
		}
	} else if (key_type == GNUTLS_PK_ECDSA ||
		   key_type == GNUTLS_PK_EDDSA_ED25519 ||
		   key_type == GNUTLS_PK_EDDSA_ED448 ||
		   key_type == GNUTLS_PK_ECDH_X25519 ||
		   key_type == GNUTLS_PK_ECDH_X448) {
		gnutls_datum_t y, x, k;
		gnutls_ecc_curve_t curve;

		ret =
		    gnutls_x509_privkey_export_ecc_raw(key, &curve, &x, &y,
						       &k);
		if (ret < 0)
			fprintf(stderr,
				"Error in key ECC data export: %s\n",
				gnutls_strerror(ret));
		else {
			print_ecc_pkey(outfile, curve, &k, &x, &y,
				       cinfo->cprint);

			gnutls_free(x.data);
			gnutls_free(y.data);
			gnutls_free(k.data);
		}
	} else if (key_type == GNUTLS_PK_GOST_01 ||
		   key_type == GNUTLS_PK_GOST_12_256 ||
		   key_type == GNUTLS_PK_GOST_12_512) {
		gnutls_datum_t y, x, k;
		gnutls_ecc_curve_t curve;
		gnutls_digest_algorithm_t digest;
		gnutls_gost_paramset_t paramset;

		ret =
		    gnutls_x509_privkey_export_gost_raw(key, &curve,
							&digest,
							&paramset,
							&x, &y, &k);
		if (ret < 0)
			fprintf(stderr,
				"Error in key GOST data export: %s\n",
				gnutls_strerror(ret));
		else {
			print_gost_pkey(outfile, curve, digest, paramset,
					&k, &x, &y,
					cinfo->cprint);

			gnutls_free(x.data);
			gnutls_free(y.data);
			gnutls_free(k.data);
		}
	}

	size = lbuffer_size;
	ret = gnutls_x509_privkey_get_seed(key, &dig, lbuffer, &size);
	if (ret >= 0) {
		fprintf(outfile, "Validation parameters:\n");
		fprintf(outfile, "\tHash: %s\n",
			gnutls_digest_get_name(dig));
		fprintf(outfile, "\tSeed: %s\n",
			raw_to_hex(lbuffer, size));
	}

	fprintf(outfile, "\n");

	size = lbuffer_size;
	ret =
	     gnutls_x509_privkey_get_key_id(key, GNUTLS_KEYID_USE_SHA256, lbuffer, &size);
	if (ret < 0) {
		fprintf(stderr, "Error in key id calculation: %s\n",
			gnutls_strerror(ret));
	} else {
		fprintf(outfile, "Public Key PIN:\n\tpin-sha256:%s\n",
			raw_to_base64(lbuffer, size));

		fprintf(outfile, "Public Key ID:\n\tsha256:%s\n",
			raw_to_hex(lbuffer, size));

		size = lbuffer_size;
		ret =
		     gnutls_x509_privkey_get_key_id(key, GNUTLS_KEYID_USE_SHA1, lbuffer, &size);
		if (ret >= 0) {
			fprintf(outfile, "\tsha1:%s\n",
				raw_to_hex(lbuffer, size));
		}
	}
	fprintf(outfile, "\n");

}

void
print_private_key(FILE *outfile, common_info_st * cinfo, gnutls_x509_privkey_t key)
{
	int ret;
	size_t size;

	if (!key)
		return;

	/* Only print private key parameters when an unencrypted
	 * format is used */
	switch_to_pkcs8_when_needed(cinfo, key, gnutls_x509_privkey_get_pk_algorithm(key));

	if (!cinfo->pkcs8) {

		if (cinfo->outtext)
			privkey_info_int(outfile, cinfo, key);

		size = lbuffer_size;
		ret = gnutls_x509_privkey_export(key, cinfo->outcert_format,
						 lbuffer, &size);
		if (ret < 0) {
			fprintf(stderr, "privkey_export: %s\n",
				gnutls_strerror(ret));
			app_exit(1);
		}
	} else {
		unsigned int flags = 0;
		const char *pass;

		pass = get_password(cinfo, &flags, 0);
		flags |= cipher_to_flags(cinfo->pkcs_cipher);

		if (cinfo->outtext && (flags & GNUTLS_PKCS_PLAIN))
			privkey_info_int(outfile, cinfo, key);

		size = lbuffer_size;
		ret =
		    gnutls_x509_privkey_export_pkcs8(key, cinfo->outcert_format,
						     pass, flags, lbuffer,
						     &size);
		if (ret < 0) {
			fprintf(stderr, "privkey_export_pkcs8: %s\n",
				gnutls_strerror(ret));
			app_exit(1);
		}
	}

	fwrite(lbuffer, 1, size, outfile);
}

/* If how is zero then the included parameters are used.
 */
int generate_prime(FILE * outfile, int how, common_info_st * info)
{
	int ret;
	gnutls_dh_params_t dh_params;
	gnutls_datum_t p, g;
	int bits = get_bits(GNUTLS_PK_DH, info->bits, info->sec_param, 1);
	unsigned int q_bits = 0, key_bits = 0;

	fix_lbuffer(0);

	gnutls_dh_params_init(&dh_params);

	if (how != 0) {
		fprintf(stderr, "Generating DH parameters (%d bits)...\n",
			bits);
		fprintf(stderr, "(might take long time)\n");
	} else
		fprintf(stderr, "Retrieving DH parameters...\n");

	if (how != 0) {
		if (info->provable != 0) {
			gnutls_x509_privkey_t pkey;

			ret = gnutls_x509_privkey_init(&pkey);
			if (ret < 0) {
				fprintf(stderr,
					"Error initializing key: %s\n",
					gnutls_strerror(ret));
				app_exit(1);
			}

			if (info->seed_size > 0) {
				gnutls_keygen_data_st data;

				if (info->seed_size < 32) {
					fprintf(stderr, "For DH parameter generation a 32-byte seed value or larger is expected (have: %d); use -d 2 for more information.\n", (int)info->seed_size);
					app_exit(1);
				}

				data.type = GNUTLS_KEYGEN_SEED;
				data.data = (void*)info->seed;
				data.size = info->seed_size;

				ret = gnutls_x509_privkey_generate2(pkey, GNUTLS_PK_DSA, bits, GNUTLS_PRIVKEY_FLAG_PROVABLE, &data, 1);
			} else {
				ret = gnutls_x509_privkey_generate(pkey, GNUTLS_PK_DSA, bits, GNUTLS_PRIVKEY_FLAG_PROVABLE);
			}

			if (ret < 0) {
				fprintf(stderr,
					"Error generating DSA parameters: %s\n",
					gnutls_strerror(ret));
				app_exit(1);
			}

			if (info->outcert_format == GNUTLS_X509_FMT_PEM) {
				print_private_key(outfile, info, pkey);
			}

			ret = gnutls_dh_params_import_dsa(dh_params, pkey);
			if (ret < 0) {
				fprintf(stderr,
					"Error importing DSA parameters: %s\n",
					gnutls_strerror(ret));
				app_exit(1);
			}

			gnutls_x509_privkey_deinit(pkey);
		} else {
			ret = gnutls_dh_params_generate2(dh_params, bits);
			if (ret < 0) {
				fprintf(stderr,
					"Error generating parameters: %s\n",
					gnutls_strerror(ret));
				app_exit(1);
			}
		}

		ret =
		    gnutls_dh_params_export_raw(dh_params, &p, &g,
						&q_bits);
		if (ret < 0) {
			fprintf(stderr, "Error exporting parameters: %s\n",
				gnutls_strerror(ret));
			app_exit(1);
		}
	} else {
		if (info->provable != 0) {
			fprintf(stderr, "The DH parameters obtained via this option are not provable\n");
			app_exit(1);
		}
#if defined(ENABLE_DHE) || defined(ENABLE_ANON)
		if (bits <= 2048) {
			p = gnutls_ffdhe_2048_group_prime;
			g = gnutls_ffdhe_2048_group_generator;
			key_bits = gnutls_ffdhe_2048_key_bits;
		} else if (bits <= 3072) {
			p = gnutls_ffdhe_3072_group_prime;
			g = gnutls_ffdhe_3072_group_generator;
			key_bits = gnutls_ffdhe_3072_key_bits;
		} else if (bits <= 4096) {
			p = gnutls_ffdhe_4096_group_prime;
			g = gnutls_ffdhe_4096_group_generator;
			key_bits = gnutls_ffdhe_4096_key_bits;
		} else if (bits <= 6144) {
			p = gnutls_ffdhe_6144_group_prime;
			g = gnutls_ffdhe_6144_group_generator;
			key_bits = gnutls_ffdhe_6144_key_bits;
		} else {
			p = gnutls_ffdhe_8192_group_prime;
			g = gnutls_ffdhe_8192_group_generator;
			key_bits = gnutls_ffdhe_8192_key_bits;
		}

		ret = gnutls_dh_params_import_raw2(dh_params, &p, &g, key_bits);
		if (ret < 0) {
			fprintf(stderr, "Error exporting parameters: %s\n",
				gnutls_strerror(ret));
			app_exit(1);
		}
#elif defined(ENABLE_SRP)
		if (bits <= 1024) {
			p = gnutls_srp_1024_group_prime;
			g = gnutls_srp_1024_group_generator;
		} else if (bits <= 1536) {
			p = gnutls_srp_1536_group_prime;
			g = gnutls_srp_1536_group_generator;
		} else if (bits <= 2048) {
			p = gnutls_srp_2048_group_prime;
			g = gnutls_srp_2048_group_generator;
		} else if (bits <= 3072) {
			p = gnutls_srp_3072_group_prime;
			g = gnutls_srp_3072_group_generator;
		} else {
			p = gnutls_srp_4096_group_prime;
			g = gnutls_srp_4096_group_generator;
		}

		ret = gnutls_dh_params_import_raw(dh_params, &p, &g);
		if (ret < 0) {
			fprintf(stderr, "Error exporting parameters: %s\n",
				gnutls_strerror(ret));
			app_exit(1);
		}
#else
		fprintf(stderr,
			"Parameters unavailable as SRP is disabled.\n");
		app_exit(1);
#endif
	}

	if (info->outtext)
		print_dh_info(outfile, &p, &g, q_bits, info->cprint);

	if (!info->cprint) {	/* generate a PKCS#3 structure */
		size_t len = lbuffer_size;

		ret =
		    gnutls_dh_params_export_pkcs3(dh_params,
						  info->outcert_format,
						  lbuffer, &len);

		if (ret == 0) {
			if (info->outcert_format == GNUTLS_X509_FMT_PEM)
				fprintf(outfile, "\n%s", lbuffer);
			else
				fwrite(lbuffer, 1, len, outfile);

		} else {
			fprintf(stderr, "Error: %s\n",
				gnutls_strerror(ret));
		}

	}

	if (how != 0) {
		gnutls_free(p.data);
		gnutls_free(g.data);
	}

	gnutls_dh_params_deinit(dh_params);

	return 0;
}

void decode_seed(gnutls_datum_t *seed, const char *hex, unsigned hex_size)
{
	int ret;
	size_t seed_size;

	seed->size = hex_size;
	seed->data = malloc(hex_size);

	if (seed->data == NULL) {
		fprintf(stderr, "memory error\n");
		app_exit(1);
	}

	seed_size = hex_size;
	ret = gnutls_hex2bin(hex, hex_size, seed->data, &seed_size);
	if (ret < 0) {
		fprintf(stderr, "Could not hex decode data: %s\n", gnutls_strerror(ret));
		app_exit(1);
	}
	seed->size = seed_size;

	return;
}

gnutls_pk_algorithm_t figure_key_type(const char *key_type)
{
	if (strcasecmp(key_type, "rsa") == 0)
		return GNUTLS_PK_RSA;
	else if (strcasecmp(key_type, "rsa-pss") == 0)
		return GNUTLS_PK_RSA_PSS;
	else if (strcasecmp(key_type, "ed25519") == 0 || strcasecmp(key_type, "eddsa") == 0)
		return GNUTLS_PK_EDDSA_ED25519;
	else if (strcasecmp(key_type, "ed448") == 0)
		return GNUTLS_PK_EDDSA_ED448;
	else if (strcasecmp(key_type, "x25519") == 0)
		return GNUTLS_PK_ECDH_X25519;
	else if (strcasecmp(key_type, "x448") == 0)
		return GNUTLS_PK_ECDH_X448;
	else if (strcasecmp(key_type, "dsa") == 0)
		return GNUTLS_PK_DSA;
	else if (strcasecmp(key_type, "ecdsa") == 0 || strcasecmp(key_type, "ecc") == 0)
		return GNUTLS_PK_ECDSA;
	else if (strcasecmp(key_type, "gost01") == 0)
		return GNUTLS_PK_GOST_01;
	else if (strcasecmp(key_type, "gost12-256") == 0)
		return GNUTLS_PK_GOST_12_256;
	else if (strcasecmp(key_type, "gost12-512") == 0)
		return GNUTLS_PK_GOST_12_512;
	else {
		fprintf(stderr, "unknown key type: %s\n", key_type);
		return GNUTLS_PK_UNKNOWN;
	}
}

gnutls_digest_algorithm_t hash_to_id(const char *hash)
{
	if (strcasecmp(hash, "md5") == 0) {
		fprintf(stderr,
			"Warning: MD5 is broken, and should not be used any more for digital signatures.\n");
		return GNUTLS_DIG_MD5;
	} else if (strcasecmp(hash, "sha1") == 0)
		return GNUTLS_DIG_SHA1;
	else if (strcasecmp(hash, "sha256") == 0)
		return GNUTLS_DIG_SHA256;
	else if (strcasecmp(hash, "sha224") == 0)
		return GNUTLS_DIG_SHA224;
	else if (strcasecmp(hash, "sha384") == 0)
		return GNUTLS_DIG_SHA384;
	else if (strcasecmp(hash, "sha512") == 0)
		return GNUTLS_DIG_SHA512;
	else if (strcasecmp(hash, "sha3-256") == 0)
		return GNUTLS_DIG_SHA3_256;
	else if (strcasecmp(hash, "sha3-224") == 0)
		return GNUTLS_DIG_SHA3_224;
	else if (strcasecmp(hash, "sha3-384") == 0)
		return GNUTLS_DIG_SHA3_384;
	else if (strcasecmp(hash, "sha3-512") == 0)
		return GNUTLS_DIG_SHA3_512;
	else if (strcasecmp(hash, "rmd160") == 0)
		return GNUTLS_DIG_RMD160;
	else {
		return gnutls_digest_get_id(hash);
	}
}

void sign_params_to_flags(common_info_st *cinfo, const char *params)
{
	char *p, *sp;

	sp = strdup(params);
	if (sp == NULL) {
		fprintf(stderr, "memory error\n");
		app_exit(1);
	}

	p = strtok(sp, ",");

	while(p != NULL) {
		if (strcasecmp(p, "rsa-pss")==0) {
			cinfo->rsa_pss_sign = 1;
		} else {
			fprintf(stderr, "Unknown signature parameter: %s\n", p);
			app_exit(1);
		}

		p=strtok(NULL, ",");
	}

	free(sp);
}