5e7839fd6588848f065195ef146d9eaae888fdb5
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(CMD_PUB
, NULL
);
43 if (streq(optarg
, "rsa"))
45 type
= CRED_PRIVATE_KEY
;
48 else if (streq(optarg
, "ecdsa"))
50 type
= CRED_PRIVATE_KEY
;
53 else if (streq(optarg
, "x509"))
55 type
= CRED_CERTIFICATE
;
60 return command_usage(CMD_PUB
, "invalid input type");
64 if (!get_form(optarg
, &form
, TRUE
))
66 return command_usage(CMD_PUB
, "invalid output format");
75 return command_usage(CMD_PUB
, "invalid --pub option");
81 cred
= lib
->creds
->create(lib
->creds
, type
, subtype
,
82 BUILD_FROM_FILE
, file
, BUILD_END
);
86 cred
= lib
->creds
->create(lib
->creds
, type
, subtype
,
87 BUILD_FROM_FD
, 0, BUILD_END
);
90 if (type
== CRED_PRIVATE_KEY
)
95 fprintf(stderr
, "parsing private key failed\n");
98 public = private->get_public_key(private);
99 private->destroy(private);
106 fprintf(stderr
, "parsing certificate failed\n");
109 public = cert
->get_public_key(cert
);
114 fprintf(stderr
, "extracting public key failed\n");
117 if (!public->get_encoding(public, form
, &encoding
))
119 fprintf(stderr
, "public key encoding failed\n");
120 public->destroy(public);
123 public->destroy(public);
124 if (fwrite(encoding
.ptr
, encoding
.len
, 1, stdout
) != 1)
126 fprintf(stderr
, "writing public key failed\n");
135 * Register the command.
137 static void __attribute__ ((constructor
))reg()
139 command_register(CMD_PUB
, (command_t
) {
141 "extract the public key from a private key/certificate",
142 {"[--in file] [--type rsa|ecdsa|x509] [--outform der|pem|pgp]"},
144 {"help", 'h', 0, "show usage information"},
145 {"in", 'i', 1, "input file, default: stdin"},
146 {"type", 't', 1, "type of credential, default: rsa"},
147 {"outform", 'f', 1, "encoding of extracted public key"},