#include "openssl/pkcs12.h"
#include "openssl/bio.h"
#include "openssl/engine.h"
#include "openssl/conf.h"
#include "openssl/err.h"

/* openssl req -x509 -newkey rsa:1024 -keyout key.pem -out cert.pem -days 365 */
/* openssl pkcs12 -export -out pkcs12.p12 -inkey key.pem -in cert.pem         */

/* gcc -ansi -I . -I ./include test.cc ./libcrypto.a -o test.exe */

int main(int argc, char* argv[])
{
  OpenSSL_add_all_algorithms();

  BIO *bp = NULL;
  PKCS12 *p12 = NULL;
  int rc = -1;
  unsigned long err = 0;
  char password[] = "passphrase";

  bp =  BIO_new_file("pkcs12.p12", "r");
  if (bp == NULL) goto cleanup;

  p12 = d2i_PKCS12_bio(bp, NULL);
  if (p12 == NULL) goto cleanup;

  /* Use empty string when no password was applies wit 'openssl pkcs12' */
  rc = PKCS12_newpass(p12, "", password);

 cleanup:

  if (rc == 1)
    {
      fprintf(stdout, "Sucessfully changed password\n");
    }
  else
    {
      err = ERR_get_error();
      fprintf(stderr, "Failed to change password, error %lu\n", err);
    }

  if (p12)
    PKCS12_free(p12);

  if (bp)
    BIO_free_all(bp);

  return 0;
}
