/*

  ssh2pgputil.c

  Authors:
        Timo J. Rinne <tri@ssh.fi>

  Copyright (C) 1999 SSH Communications Security Oy, Espoo, Finland
  All rights reserved.
                  
  Small wrapper functions for OpenPGP stuff.

*/

#include "ssh2includes.h"

#ifdef WITH_PGP

#include "sshpgp.h"
#include "sshuser.h"
#include "sshuserfile.h"
#include "sshfilebuffer.h"
#include "sshuserfilebuf.h"
#include "sshconfig.h"
#include "ssh2pgp.h"
#include "readpass.h"

#define SSH_DEBUG_MODULE "Ssh2PgpUtil"

SshPrivateKey ssh2_pgp_privkey_import(unsigned char *blob,
                                      size_t blob_len,
                                      const char *passphrase,
                                      const char *comment,
                                      SshConfig config)
{
  SshPgpSecretKey pgpkey;
  SshPrivateKey key;
  size_t dlen;
  char buf[256];
  char *pass;

  if (passphrase == NULL)
    dlen = ssh_pgp_secret_key_decode(blob, 
                                     blob_len,
                                     &pgpkey);
  else
    dlen = ssh_pgp_secret_key_decode_with_passphrase(blob, 
                                                     blob_len, 
                                                     passphrase,
                                                     &pgpkey);
  if (dlen == 0)
    {
      return NULL;
    }
  if (pgpkey->key != NULL)
    {
      if (ssh_private_key_copy(pgpkey->key, &key) != SSH_CRYPTO_OK)
        {
          ssh_pgp_secret_key_free(pgpkey);
          return NULL;
        }
      ssh_pgp_secret_key_free(pgpkey);
      return key;
    }
  else
    {
      ssh_pgp_secret_key_free(pgpkey);
    }
  snprintf(buf, sizeof (buf),
           "Passphrase for pgp key%s%s%s: ",
           comment ? " \"" : "",
           comment ? comment : "",
           comment ? "\"" : "");
  if (!config->batch_mode)
    pass = ssh_read_passphrase(buf , FALSE);
  else
    pass = NULL;
  
  if (pass && *pass)
    {
      dlen = ssh_pgp_secret_key_decode_with_passphrase(blob, 
                                                       blob_len, 
                                                       pass,
                                                       &pgpkey);
      memset(pass, 'F', strlen(pass));
      ssh_xfree(pass);
      if (dlen == 0)
        {
          return NULL;
        }
      if (pgpkey->key != NULL)
        {
          if (ssh_private_key_copy(pgpkey->key, &key) != SSH_CRYPTO_OK)
            {
              ssh_pgp_secret_key_free(pgpkey);
              return NULL;
            }
          ssh_pgp_secret_key_free(pgpkey);
          return key;
        }
      else
        {
          ssh_pgp_secret_key_free(pgpkey);
          return NULL;
        }
    }
  return NULL;
}

#endif /* WITH_PGP */
/* eof (ssh2pgputil.c) */
