05430675def5aed1f08213b4840976317e296ad7
2 * Copyright (C) 2009 Martin Willi
3 * Hochschule fuer Technik Rapperswil
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>.
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
18 #include <credentials/certificates/certificate.h>
19 #include <credentials/certificates/x509.h>
22 * Extract a public key from a private key/certificate
24 static int pub(int argc
, char *argv
[])
26 key_encoding_type_t form
= KEY_PUB_SPKI_ASN1_DER
;
27 credential_type_t type
= CRED_PRIVATE_KEY
;
28 int subtype
= KEY_RSA
;
30 private_key_t
*private;
38 switch (getopt_long(argc
, argv
, "", command_opts
, NULL
))
41 return command_usage(NULL
);
43 dbg_level
= atoi(optarg
);
46 if (streq(optarg
, "rsa"))
48 type
= CRED_PRIVATE_KEY
;
51 else if (streq(optarg
, "ecdsa"))
53 type
= CRED_PRIVATE_KEY
;
56 else if (streq(optarg
, "pkcs10"))
58 type
= CRED_CERTIFICATE
;
59 subtype
= CERT_PKCS10_REQUEST
;
61 else if (streq(optarg
, "x509"))
63 type
= CRED_CERTIFICATE
;
68 return command_usage("invalid input type");
72 if (!get_form(optarg
, &form
, TRUE
))
74 return command_usage("invalid output format");
83 return command_usage("invalid --pub option");
89 cred
= lib
->creds
->create(lib
->creds
, type
, subtype
,
90 BUILD_FROM_FILE
, file
, BUILD_END
);
94 cred
= lib
->creds
->create(lib
->creds
, type
, subtype
,
95 BUILD_FROM_FD
, 0, BUILD_END
);
98 if (type
== CRED_PRIVATE_KEY
)
103 fprintf(stderr
, "parsing private key failed\n");
106 public = private->get_public_key(private);
107 private->destroy(private);
114 fprintf(stderr
, "parsing certificate failed\n");
117 public = cert
->get_public_key(cert
);
122 fprintf(stderr
, "extracting public key failed\n");
125 if (!public->get_encoding(public, form
, &encoding
))
127 fprintf(stderr
, "public key encoding failed\n");
128 public->destroy(public);
131 public->destroy(public);
132 if (fwrite(encoding
.ptr
, encoding
.len
, 1, stdout
) != 1)
134 fprintf(stderr
, "writing public key failed\n");
143 * Register the command.
145 static void __attribute__ ((constructor
))reg()
147 command_register((command_t
) {
149 "extract the public key from a private key/certificate",
150 {"[--in file] [--type rsa|ecdsa|pkcs10|x509] [--outform der|pem|pgp]",
151 "[--debug 0|1|2|3|4]"},
153 {"help", 'h', 0, "show usage information"},
154 {"in", 'i', 1, "input file, default: stdin"},
155 {"type", 't', 1, "type of credential, default: rsa"},
156 {"outform", 'f', 1, "encoding of extracted public key"},
157 {"debug", 'v', 1, "set debug level, default: 1"},