From d0ce2d1ecdfae15c4ec6c6a16e6fb171d25960d4 Mon Sep 17 00:00:00 2001 From: DavidWed Date: Wed, 23 Nov 2016 13:33:19 +0100 Subject: pki: Add ssh_pki_export_privkey_base64() Fixes T53 Signed-off-by: DavidWedderwille Reviewed-by: Andreas Schneider --- include/libssh/libssh.h | 5 ++++ src/pki.c | 61 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/include/libssh/libssh.h b/include/libssh/libssh.h index 1c8dd7cd..a83bd8a2 100644 --- a/include/libssh/libssh.h +++ b/include/libssh/libssh.h @@ -647,6 +647,11 @@ LIBSSH_API int ssh_pki_import_privkey_base64(const char *b64_key, ssh_auth_callback auth_fn, void *auth_data, ssh_key *pkey); +LIBSSH_API int ssh_pki_export_privkey_base64(const ssh_key privkey, + const char *passphrase, + ssh_auth_callback auth_fn, + void *auth_data, + char **b64_key); LIBSSH_API int ssh_pki_import_privkey_file(const char *filename, const char *passphrase, ssh_auth_callback auth_fn, diff --git a/src/pki.c b/src/pki.c index 22ff3cd5..f463288a 100644 --- a/src/pki.c +++ b/src/pki.c @@ -596,6 +596,67 @@ int ssh_pki_import_privkey_base64(const char *b64_key, return SSH_OK; } + /** + * @brief Convert a private key to a pem base64 encoded key, or OpenSSH format for + * keytype ssh-ed25519 + * + * @param[in] privkey The private key to export. + * + * @param[in] passphrase The passphrase to use to encrypt the key with or + * NULL. An empty string means no passphrase. + * + * @param[in] auth_fn An auth function you may want to use or NULL. + * + * @param[in] auth_data Private data passed to the auth function. + * + * @param[out] b64_key A pointer to store the allocated base64 encoded key. You + * need to free the buffer. + * + * @return SSH_OK on success, SSH_ERROR on error. + */ +int ssh_pki_export_privkey_base64(const ssh_key privkey, + const char *passphrase, + ssh_auth_callback auth_fn, + void *auth_data, + char **b64_key) +{ + ssh_string blob; + unsigned char *b64; + + if (privkey == NULL || !ssh_key_is_private(privkey)) { + return SSH_ERROR; + } + + if (privkey->type == SSH_KEYTYPE_ED25519){ + blob = ssh_pki_openssh_privkey_export(privkey, + passphrase, + auth_fn, + auth_data); + } else { + blob = pki_private_key_to_pem(privkey, + passphrase, + auth_fn, + auth_data); + } + if (blob == NULL) { + return SSH_ERROR; + } + + + b64 = malloc(ssh_string_len(blob)); + if(b64 == NULL){ + ssh_string_free(blob); + return SSH_ERROR; + } + + memcpy(b64,ssh_string_data(blob),ssh_string_len(blob)); + + ssh_string_free(blob); + + *b64_key = (char *)b64; + + return SSH_OK; +} /** * @brief Import a key from a file. -- cgit v1.2.3