Do not query for CKA_ALWAYS_AUTHENTICATE if PKCS#11 Cryptoki version < 2.20
[strongswan.git] / src / pki / commands / gen.c
1 /*
2 * Copyright (C) 2009 Martin Willi
3 * Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include "pki.h"
17
18 /**
19 * Generate a private key
20 */
21 static int gen()
22 {
23 cred_encoding_type_t form = PRIVKEY_ASN1_DER;
24 key_type_t type = KEY_RSA;
25 u_int size = 0;
26 private_key_t *key;
27 chunk_t encoding;
28 char *arg;
29
30 while (TRUE)
31 {
32 switch (command_getopt(&arg))
33 {
34 case 'h':
35 return command_usage(NULL);
36 case 't':
37 if (streq(arg, "rsa"))
38 {
39 type = KEY_RSA;
40 }
41 else if (streq(arg, "ecdsa"))
42 {
43 type = KEY_ECDSA;
44 }
45 else
46 {
47 return command_usage("invalid key type");
48 }
49 continue;
50 case 'f':
51 if (!get_form(arg, &form, CRED_PRIVATE_KEY))
52 {
53 return command_usage("invalid key output format");
54 }
55 continue;
56 case 's':
57 size = atoi(arg);
58 if (!size)
59 {
60 return command_usage("invalid key size");
61 }
62 continue;
63 case EOF:
64 break;
65 default:
66 return command_usage("invalid --gen option");
67 }
68 break;
69 }
70 /* default key sizes */
71 if (!size)
72 {
73 switch (type)
74 {
75 case KEY_RSA:
76 size = 2048;
77 break;
78 case KEY_ECDSA:
79 size = 384;
80 break;
81 default:
82 break;
83 }
84 }
85 key = lib->creds->create(lib->creds, CRED_PRIVATE_KEY, type,
86 BUILD_KEY_SIZE, size, BUILD_END);
87 if (!key)
88 {
89 fprintf(stderr, "private key generation failed\n");
90 return 1;
91 }
92 if (!key->get_encoding(key, form, &encoding))
93 {
94 fprintf(stderr, "private key encoding failed\n");
95 key->destroy(key);
96 return 1;
97 }
98 key->destroy(key);
99 if (fwrite(encoding.ptr, encoding.len, 1, stdout) != 1)
100 {
101 fprintf(stderr, "writing private key failed\n");
102 free(encoding.ptr);
103 return 1;
104 }
105 free(encoding.ptr);
106 return 0;
107 }
108
109 /**
110 * Register the command.
111 */
112 static void __attribute__ ((constructor))reg()
113 {
114 command_register((command_t) {
115 gen, 'g', "gen", "generate a new private key",
116 {"[--type rsa|ecdsa] [--size bits] [--outform der|pem|pgp]"},
117 {
118 {"help", 'h', 0, "show usage information"},
119 {"type", 't', 1, "type of key, default: rsa"},
120 {"size", 's', 1, "keylength in bits, default: rsa 2048, ecdsa 384"},
121 {"outform", 'f', 1, "encoding of generated private key"},
122 }
123 });
124 }
125