SOL9 Sample: MessageEncDec

SOL9 2.0 Samples

1 Screenshot


2 Source code

/*
 * MessageEncDec.cpp 
 * Copyright (c) 2015 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/CertSelectionDialog.h>
#include <sol/crypt/CryptMsg.h>

#include <sol/crypt/MessageEncryptor.h>
#include <sol/crypt/MessageDecryptor.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"));

        
    // Find the first recipient certificate of keySpec AT_KEYEXCHANGE
    printf("1 Try to find the first recipient certificate of keyExchange\n");

    PCCERT_CONTEXT pContext = certStore.getRecipientCert();
    
    if (pContext) {
      printf("2 OK, found a recipient certificate of keyExchange\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() OriginalMessage=%s\n", bytes);       

      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();
      }

      //
      BYTE* decData = NULL;
      DWORD decDataSize = 0;

      MessageDecryptor messageDecryptor;
      if (messageDecryptor.decrypt(certStore.getStoreHandle(), encData, encDataSize,
        &decData, &decDataSize) == NO_ERROR) {
        printf("6 OK, messageDecryptor.decrypt() DecryptedMessage=%s\n", decData);
      } else {
        printf("7 Failed, messageDecryptor.decrypt()\n");
        throw GetLastError();
      }

      delete [] encData;
      
      delete [] decData;

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

Last modified: 2 May 2016

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