From 417a0f01f840a01747c45e685c1612b2a500d81f Mon Sep 17 00:00:00 2001 From: Jakub Jelen Date: Fri, 11 Aug 2023 16:53:40 +0200 Subject: [PATCH] examples: Demonstrate export of different key formats Signed-off-by: Jakub Jelen Reviewed-by: Andreas Schneider --- examples/keygen2.c | 46 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/examples/keygen2.c b/examples/keygen2.c index bbe15e0e..466e075b 100644 --- a/examples/keygen2.c +++ b/examples/keygen2.c @@ -38,6 +38,7 @@ struct arguments_st { unsigned long bits; char *file; char *passphrase; + char *format; int action_list; }; @@ -96,6 +97,16 @@ static struct argp_option options[] = { .doc = "List the Fingerprint of the given key\n", .group = 0 }, + { + .name = "format", + .key = 'm', + .arg = "FORMAT", + .flags = 0, + .doc = "Write the file in specific format. The supported values are " + "'PEM'and 'OpenSSH' file format. By default Ed25519 " + "keys are exported in OpenSSH format and others in PEM.\n", + .group = 0 + }, { /* End of the options */ 0 @@ -168,6 +179,9 @@ static error_t parse_opt (int key, char *arg, struct argp_state *state) case 'l': arguments->action_list = 1; break; + case 'm': + arguments->format = strdup(arg); + break; case ARGP_KEY_ARG: if (state->arg_num > 0) { /* Too many arguments. */ @@ -382,8 +396,36 @@ int main(int argc, char *argv[]) } /* Write the private key */ - rc = ssh_pki_export_privkey_file(key, arguments.passphrase, NULL, NULL, - arguments.file); + if (arguments.format != NULL) { + if (strcasecmp(arguments.format, "PEM") == 0) { + rc = ssh_pki_export_privkey_file_format(key, + arguments.passphrase, + NULL, + NULL, + arguments.file, + SSH_FILE_FORMAT_PEM); + } else if (strcasecmp(arguments.format, "OpenSSH") == 0) { + rc = ssh_pki_export_privkey_file_format(key, + arguments.passphrase, + NULL, + NULL, + arguments.file, + SSH_FILE_FORMAT_OPENSSH); + } else { + rc = ssh_pki_export_privkey_file_format(key, + arguments.passphrase, + NULL, + NULL, + arguments.file, + SSH_FILE_FORMAT_DEFAULT); + } + } else { + rc = ssh_pki_export_privkey_file(key, + arguments.passphrase, + NULL, + NULL, + arguments.file); + } if (rc != SSH_OK) { fprintf(stderr, "Error: Failed to write private key file"); goto end;