
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/des.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/pkcs12.h>
#include "pkmang.h"
//#include "NSPUSERDB.h"
#include "apps.h"
#define PROG pkcs12_main

EVP_CIPHER *enc;


#define NOKEYS		0x1
#define NOCERTS 	0x2
#define INFO		0x4
#define CLCERTS		0x8
#define CACERTS		0x10

int get_cert_chain(X509 *cert, STACK **chain);
int dump_cert_text (BIO *out, X509 *x);
int dump_certs_keys_p12(BIO *out, PKCS12 *p12, char *pass, int passlen, int options);
int dump_certs_pkeys_bags(BIO *out, STACK *bags, char *pass, int passlen, int options);
int dump_certs_pkeys_bag(BIO *out, PKCS12_SAFEBAG *bags, char *pass, int passlen, int options);
int print_attribs(BIO *out, STACK *attrlst, char *name);
void hex_prin(BIO *out, unsigned char *buf, int len);
int alg_print(BIO *x, X509_ALGOR *alg);
int cert_load(BIO *in, STACK *sk);

int main()
{
	FILE *fp;
	PKCS12 *p12 = NULL,*pp12=NULL;
	EVP_PKEY* pk=NULL,*pkey;
	SNF_DATABASE *m_pkdb=NULL;
	SNF_PRIKEY *pPriKey=NULL;
	STACK *sk;	
	X509 *x509,*cert;
	char *mykey;
	int len;

	if((fp = fopen("hailong_chen.p12","rb")) == NULL)
	{
		printf("open file error!\n");
		return -1;
	}

	fseek(fp,0,SEEK_END);

	len = ftell(fp);

	fseek(fp,0,SEEK_SET);

	mykey = (char *)malloc(len);

	fread(mykey,len,1,fp);

	fclose(fp);
	d2i_PKCS12(&p12, &mykey, len);

	SSLeay_add_all_algorithms();
	PKCS12_parse(p12,"1234", &pkey, &cert,
								 NULL);

/*	if( !iGetPKDatabase( &m_pkdb, "isafe1"))
	{
		sk=sk_new((int (*)())SNF_PRIKEY_X509_email_cmp);
		m_pkdb=SNF_DATABASE_set(sk,"isafe1");
	}
	
	SavePKtoDatabase(&m_pkdb, cert, pkey, "1234");



	if( NSP_USER_Open("isafe")) return FALSE;


	NSP_USER_Import(cert);

	NSP_USER_Save();

	pPriKey = FindPKbyEmail(m_pkdb, "hailong_chen@hotmail.com");

	if( SNF_ENCRYPT_KEY_decrypt(&pk, pPriKey->key.enc_key, ASN1_INTEGER_get(pPriKey->key_type), "1234", 4) == NULL)
	{
		goto end;
	}

*/	if((fp = fopen("hailong_chen1.p12","w")) == NULL)
	{
		printf("open file error!\n");
		return -1;
	}

	pp12 = PKCS12_create("1234", "My Certificate", pkey, cert, NULL, 0,0,0,0,0);
	i2d_PKCS12_fp(fp, pp12);
	PKCS12_free(pp12);
	fclose(fp);

end:
	;

}

