Laden eines Zertifikats aus einer Datei

In diesem Thema wird beschrieben, wie Sie ein Zertifikat aus einer Zertifikatdatei laden.

Laden eines Zertifikats aus einer Zertifikatdatei

  1. Öffnen Sie die Zertifikatdatei für den Lesezugriff.
  2. Lesen Sie den Inhalt der Zertifikatdatei in den Zertifikatpuffer ein.
  3. Erstellen Sie ein Zertifikat mit dem Inhalt des Puffers.
// In the interest of simplicity, this example
//  uses a fixed-length buffer to hold the certificate. 
// A more robust solution would be to query the size
//  of the certificate file and dynamically
//  allocate a buffer of that size or greater.
#define CERTIFICATE_BUFFER_SIZE 1024

HRESULT  hr                  = S_OK;
BYTE     certEncoded[CERTIFICATE_BUFFER_SIZE] = {0};
DWORD    certEncodedSize     = 0L;
HANDLE   certFileHandle      = NULL;
BOOL     result              = FALSE;

// open the certificate file
certFileHandle = CreateFile(certFile, 
    GENERIC_READ, 
    0, 
    NULL, 
    OPEN_EXISTING, 
    FILE_ATTRIBUTE_NORMAL, 
    NULL);
if (INVALID_HANDLE_VALUE == certFileHandle) {
    hr = HRESULT_FROM_WIN32(GetLastError());
}

if (SUCCEEDED(hr)) {
    // if the buffer is large enough
    //  read the certificate file into the buffer
    if (GetFileSize (certFileHandle, NULL) <= CERTIFICATE_BUFFER_SIZE) {
        result = ReadFile(certFileHandle, 
            certEncoded, 
            CERTIFICATE_BUFFER_SIZE, 
            &certEncodedSize, 
            NULL);
        if (!result) {
            // the read failed, return the error as an HRESULT
            hr = HRESULT_FROM_WIN32(GetLastError());
        } else {
            hr = S_OK;
        }
    } else {
        // The certificate file is larger than the allocated buffer.
        //  To handle this error, you could dynamically allocate
        //  the certificate buffer based on the file size returned or 
        //  use a larger static buffer.
        hr = HRESULT_FROM_WIN32(ERROR_MORE_DATA);
    }    
}
if (SUCCEEDED(hr))
{
    // create a certificate from the contents of the buffer
    *cert = CertCreateCertificateContext(X509_ASN_ENCODING, 
        certEncoded, 
        certEncodedSize);
    if (!(*cert)) {
        hr = HRESULT_FROM_WIN32(GetLastError());
        CloseHandle(certFileHandle);
        hr = E_FAIL;
    } else {
        hr = S_OK;
    }
}
// close the certificate file
if (NULL != certFileHandle) CloseHandle(certFileHandle);

Nächste Schritte

Überprüfen, ob das System eine Digestmethode unterstützt

Überprüfen, ob ein Zertifikat eine Signaturmethode unterstützt

Einbetten von Zertifikatketten in ein Dokument

In diesem Beispiel verwendet

CreateFile

ReadFile

CertCreateCertificateContext

Weitere Informationen

Kryptografie-API

Kryptografiefunktionen

API-Fehler bei der digitalen XPS-Signatur

XPS-Dokumentfehler

XML Paper Specification