我需要将证书(X509 .cer文件)安装到当前用户的Trusted Publishers存储中,因此它将显示在证书管理器下:
我可以通过双击.cer文件,然后通过一些对话框单击我的方式来安装证书。
但是我需要使用原始Windows API以编程方式安装它。
这个问题与this SO question差不多,只是C或C ++而不是C#。
答案 0 :(得分:0)
实际上很简单:
遵循快速而肮脏的示例程序,将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);
}