Pfx certificate import to USB key (CODE)

Source: Internet
Author: User

5. complete code

# Include "stdafx. H"
# Include <windows. h>
# Include <wincrypt. h>
# Include <stdio. h>

// Global CSP handle
Hcryptprov = NULL; // handle for a cryptographic

Void tosmartcard (hcertstore hsystemstore)
{
Pccert_context pcertcontext = NULL;
Char psznamestring [256];
DWORD dwkeyspec;
Hcryptkey userkey = 0;

DWORD dwbloblen;
Byte * pbkeyblob;
Hcryptkey hpubkey = NULL;
Int error;

// Cryptacquirecertificateprivatekey exported handle
Hcryptprov hcrypt = NULL;

// Just for test provider name
Byte pbdata [1000]; // 1000 will hold the longest

// Key container name.
DWORD cbdata;
Cbdata = 1000;

//-------------------------------------------------------------------
// Find the certificates in the system store.
// In fact, just have one.

While (pcertcontext = certenumcertificatesinstore (
Hsystemstore,
Pcertcontext) // on the first call to the function,
// This parameter is null
// On all subsequent CILS,
// This parameter is the last pointer
// Returned by the function
{
//----------------------------------------------------------------
// Do whatever is needed for a current certificate.
//...
//--------------------------------------------------------------------
// Find and print the name of the subject of the certificate
// Just retrieved.

If (certgetnamestring (
Pcertcontext,
Cert_name_simple_display_type,
0,
Null,
Psznamestring,
128 ))
{
Printf ("Certificate for % s has been retrieved. \ n", psznamestring );

If (! (Cryptacquirecertificateprivatekey (
Pcertcontext,
0,
Null,
& Hcrypt, // & hcryptprov, // note that hcrypt output should not be hcryptprov.
& Dwkeyspec,
Null )))
{
Printf ("cryptacquirecertificateprivatekey. \ n ");
}

// Test hcrypt, try to get its name;
// I guess it is wrong, not Microsoft base..., but the following
// Microsoft enhanced cryptographic provider V1.0

If (cryptgetprovparam (
Hcrypt,
Pp_name,
Pbdata,
& Cbdata,
0 ))
{
Printf ("cryptgetprovparam succeeded. \ n ");
Printf ("provider name: % s \ n", pbdata );
}

If (! Cryptgetuserkey (
Hcrypt, // not hcryptprov,
At_keyexchange, // dwkeyspec,
& Userkey
))

{
Printf ("cryptgetuserkey error. \ n ");
}

//--------------------------------------------------------------------
// Export the public/private key-pair.

If (cryptexportkey (
Userkey,
Null,
Privatekeyblob,
0,
Null,
& Dwbloblen ))
{
Printf ("Size of the Blob for the public/private key pair determined. \ n ");
}
Else
{
Printf ("error computing blob length. \ n ");
Exit (1 );
}

//--------------------------------------------------------------------
// Allocate memory for the pbkeyblob.

If (pbkeyblob = (byte *) malloc (dwbloblen ))
{
Printf ("memory has been allocated for the Blob. \ n ");
}
Else
{
Printf ("out of memory. \ n ");
Exit (1 );
}

//--------------------------------------------------------------------
// Do the actual exporting into the key blob.

If (cryptexportkey (
Userkey,
Null,
Privatekeyblob,
0,
Pbkeyblob,
& Dwbloblen ))
{
Printf ("contents have been written to the Blob. \ n ");
}
Else
{
Printf ("error exporting key. \ n ");
Exit (1 );
}

If (cryptimportkey (
Hcryptprov,
Pbkeyblob,
Dwbloblen,
0,
0,
& Hpubkey ))
{
Printf ("the key has been imported. \ n ");
}
Else
{
Printf ("Public Key import failed. \ n ");
Exit (1 );
}

// Not this one
// If (! Cryptsetkeyparam (userkey, kp_certificate, pcertcontext-> pbcertencoded, 0 ))
If (! Cryptsetkeyparam (hpubkey, kp_certificate, pcertcontext-> pbcertencoded, 0 ))
{

Error = getlasterror ();
Printf ("cryptsetkeyparam 0x % x \ n", error );

If (error! = Nte_bad_type ){
// If error is bad_type then we just can't set the property.
// Likely means our provider isn' t a smart card.
// If there was another error, we shoshould report it.
Printf ("cryptsetkeyparam failed (0x80090020 usually means no room on card) 0x % x \ n", error );

}
}

If (hpubkey ){
Cryptdestroykey (hpubkey );
}

//--------------------------------------------------------------------
// Allocate memory for the pbkeyblob.
If (pbkeyblob)
Free (pbkeyblob );

}
Else
{
Printf ("certgetname failed. \ n ");
}

Certfreecertificatecontext (pcertcontext );

} // End of while
}

Void installpfx (char * filename, char * password)
{
Handle hfile;
Bool bresult;
Byte inbuffer [10000];
DWORD nbytestoread = 0;
DWORD nbytesread;

Wchar wszpassword [20];
Hcertstore pfxcert = NULL;

Hfile = createfile (filename, // open myfile. txt
Generic_read, // open for reading
File_pai_read, // share for reading
Null, // No security
Open_existing, // existing file only
File_attribute_normal, // normal file
Null); // No ATTR. Template

If (hfile = invalid_handle_value)
{
Printf ("cocould not open file. \ n"); // process error
Return;
}

Nbytestoread = getfilesize (hfile, null );

Printf ("file size is % d \ n", nbytestoread );

Bresult = readfile (hfile, & inbuffer, nbytestoread, & nbytesread, null );

If (bresult) // reading is OK.
{
Crypt_data_blob pfxblob;
Pfxblob. cbdata = nbytesread;
Pfxblob. pbdata = inbuffer;

If (pfxispfxblob (& pfxblob ))
{
Printf ("It's A pfx certificate. \ n ");

Multibytetowidechar (cp_acp, 0, password,
Strlen (password) + 1, wszpassword,
Sizeof (wszpassword)/sizeof (wszpassword [0]);

If (null! = Pfximportcertstore (
& Pfxblob,
Wszpassword,
0x21 // crypt_user_protected
)
)
{
Printf ("It's A pfx import OK. \ n ");

Pfxcert = pfximportcertstore (
& Pfxblob,
Wszpassword,
0x21 // crypt_user_protected
);

Tosmartcard (pfxcert );

// List all my certificates
// Tosmartcard (hsystemstore );

}

}
}

Closehandle (hfile );
}

Void opencert (hcryptprov hprov)
{
//--------------------------------------------------------------------
// Declare and initialize variables.

Hcertstore hsystemstore; // system store handle

//--------------------------------------------------------------------
// Open the my system certificate store. The same call can be
// Used with the name of a different system store, such as my or root,
// As the second parameter.

If (hsystemstore = certopensystemstore (
Hprov,
"My "))
{
Printf ("the my system store is open. Continue. \ n ");
}
Else
{
Printf ("the my system store did not open. \ n ");
Exit (1 );
}

// Use the store as needed.
//...

Installpfx ("d :\\ exported. pfx", "123456 ");

// When done using the store, close it.
If (! Certclosestore (hsystemstore, cert_close_store_check_flag ))
{
Printf ("unable to close the my system store. \ n ");
Exit (1 );
}
}

Int main (INT argc, char * argv [])
{

//--------------------------------------------------------------------
// Declare and initialize variables.

// Provider context.
Lpcstr username = "mykeycontainer"; // name of the key container
Lpcstr providername = "esafe Cryptographic Service Provider V2.0 ";

// To be used.
//--------------------------------------------------------------------
// Attempt to acquire a context and a key
// Container. The context will use the default CSP
// For the rsa_full provider type. dwflags is set to 0
// To attempt to open an existing key container.

If (cryptacquirecontext (
& Hcryptprov, // handle to the CSP
Username, // container name
Providername, // use the default provider
Prov_rsa_full, // provider type
0) // flag values
{
Printf ("a crypto context with the % s key container \ n", username );
Printf ("has been acquired. \ n ");

Opencert (hcryptprov );

}
Else
{
//--------------------------------------------------------------------
// An error occurred in acquiring the context. This cocould mean
// That the key container requested does not exist. In this case,
// The function can be called again to attempt to create a new key
// Container. error codes are defined in winerror. h.
If (getlasterror () = nte_bad_keyset)
{
If (cryptacquirecontext (
& Hcryptprov,
Username,
Providername,
Prov_rsa_full,
Crypt_newkeyset ))
{
Printf ("a new key container has been created. \ n ");
Opencert (hcryptprov );
}
Else
{
Printf ("cocould not create a new key container. \ n ");
Exit (1 );
}
}
Else
{
Printf ("A Cryptographic Service handle cocould not be acquired. \ n ");
Exit (1 );
}

} // End of else

//--------------------------------------------------------------------
// A cryptographic context and a key container is available. Perform
// Any functions that require a cryptographic provider handle.

//--------------------------------------------------------------------
// When the handle is no longer needed, it must be released.

If (cryptreleasecontext (hcryptprov, 0 ))
{
Printf ("the handle has been released. \ n ");
}
Else
{
Printf ("the handle cocould not be released. \ n ");
}

Return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.