#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

#include <pem.h>
#include <x509_vfy.h>
#include <x509.h>
#include <evp.h>
#include <rsa.h>
#include <dsa.h>
#include <dh.h>

#include "libopgp.h"

int main(int argc, char *argv[])
{
  X509 *cert;
  EVP_PKEY *pkey;
  char buf[256], obuf[4200];
  int len;

  while (!feof(stdin)) {
    cert = NULL;
    PEM_read_X509(stdin, &cert, NULL);
    X509_NAME_oneline(X509_get_subject_name(cert), buf, 256);
    pkey = X509_get_pubkey(cert);
    switch (pkey->type) {
    case EVP_PKEY_RSA:
    case EVP_PKEY_RSA2:
      len = PGP_wrkey(obuf, pkey->pkey.rsa, 1, 1, NULL, buf);
      fwrite(obuf, 1, len, stdout);
      break;
    case EVP_PKEY_DH:
      len = PGP_wrkey(obuf, pkey->pkey.dh, 1, 16, NULL, buf);
      fwrite(obuf, 1, len, stdout);
      break;
    case EVP_PKEY_DSA:
    case EVP_PKEY_DSA2:
    case EVP_PKEY_DSA3:
      len = PGP_wrkey(obuf, pkey->pkey.dsa, 1, 17, NULL, buf);
      fwrite(obuf, 1, len, stdout);
      break;
    default:
      fprintf(stderr, "Unknown Algorithm");
      break;
    }
  }
  return 0;
}
