SOL9 2.0 Sample: CryptMsg

SOL9 2.0 Samples

1 Screenshot


2 Source code

/*
 * CryptMsg.cpp 
 * Copyright (c) 2009 Antillia.com TOSHIYUKI ARAI. ALL RIGHTS RESERVED. 
 */


// SOL9
// 2009/03/24


#include <sol/crypt/CryptServiceProvider.h>
#include <sol/crypt/CertSystemStore.h>
#include <sol/crypt/CertContext.h>

#include <sol/crypt/CryptMsg.h>

#include <sol/crypt/MessageEncryptor.h>

/*
 In this example, you have a certificate of exchange-type in MY certStore.
For example, you can make a certifiate in the following way;
      makecert -r -pe -n "CN=SOL" -b 03/23/2009 -e 03/31/2040 -sky exchange -ss my SOL.cer

 */
void _tmain(int argc, TCHAR** argv)
{
    try {
        CryptServiceProvider csp;

        CertSystemStore certStore(csp, _T("MY"));

        printf("1 Try to find a recipient certificate\n");

        PCCERT_CONTEXT pContext = certStore.getRecipientCert();
        if (pContext) {
            printf("2 OK, found a recpient certificate\n");
            CertContext cert(pContext);

            BYTE* bytes = (BYTE*)"SOL9 C++ Class Library. Hello world";

            DWORD size = strlen((char*)bytes) + 1;
    
            BYTE* encData = NULL;
            DWORD encDataSize = 0;
            printf("3 Try to messageEncryptor.encrypt()\n");             

            MessageEncryptor messageEncryptor;
            if (messageEncryptor.encrypt(csp.getProviderHandle(), pContext, bytes, size,
                &encData, &encDataSize) == NO_ERROR) {
                printf("4 OK, messageEncryptor.encrypt()\n");
            } else {
                printf("5 Failed, messageEncryptor.encrypt()\n");
                throw GetLastError();
            }

            //
            CryptMsg cryptMsg;

            printf("6 Try to cryptMsg.open()\n");             

            if (cryptMsg.open() == NO_ERROR) {
                printf("7 OK, cryptMsg.open()\n");
                printf("8 Try to cryptMsg.update() with encrypted data by messageEncryptor.encrypt()\n");             

                if (cryptMsg.update(encData, encDataSize, TRUE) ==NO_ERROR) {
                    printf("9 OK, cryptMsg.update()\n");
                } else {
                    printf("10 Failed, cryptMsg.update() %x\n", GetLastError());
                }

                cryptMsg.close();
                printf("11 cryptMsg.close()\n");

            } else {
                printf("12 Failed, cryptMsg.open()\n");
            }

            delete [] encData;

        } else {
            printf("13 Failed in certStore.getRecipientCert()\n");
        }
    } catch (...) {
        printf("14 Exception: %x\n", GetLastError());
    }
}

Last modified: 11 Nov 2009

Copyright (c) 2009 Antillia.com ALL RIGHTS RESERVED.