其实很简单:
下面的快速和肮脏的样本程序将证书添加到
cert.cer
文件到当前用户的“受信任的发布者”证书存储。
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>
#pragma comment (lib, "crypt32.lib")
void MyHandleError(LPCTSTR psz)
{
fprintf(stderr, TEXT("An error occurred in the program.\n"));
fprintf(stderr, TEXT("%s\n"), psz);
fprintf(stderr, TEXT("Error number %x.\n"), GetLastError());
exit(1);
}
int main()
{
HCERTSTOR hCertStore;
if (hCertStore = CertOpenSystemStore(NULL, "TrustedPublisher"))
{
fprintf(stderr, "The %s store has been opened. \n", pszStoreName);
}
else
{
MyHandleError("The store was not opened.");
}
// Open and read certificat file
HANDLE hfile = CreateFile("cert.cer", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hfile == INVALID_HANDLE_VALUE)
{
MyHandleError("File could not be opened.");
}
DWORD size = GetFileSize(hfile, NULL);
if (size == INVALID_FILE_SIZE)
{
MyHandleError("GetFileSize failed.");
}
char *pFileContent = (char*)malloc(size);
DWORD sizeread;
ReadFile(hfile, pFileContent, size, &sizeread, NULL);
CloseHandle(hfile);
// pFileContent points to certificat bytes, size contains the certificat size
if (!CertAddEncodedCertificateToStore(hCertStore, X509_ASN_ENCODING,
(const BYTE*)pFileContent, size,
CERT_STORE_ADD_NEW,
NULL)
)
{
MyHandleError("CertAddEncodedCertificateToStore failed.");
}
free(pFileContent);
CertCloseStore(hCertStore, 0);
}