Channels ▼
RSS

Security

Encrypting and Decrypting Data with the CryptoAPI


January 2002/Systems Insider

Listing 3: main.cpp
The sample program for encrypting and decrypting

// main.cpp

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0400
#endif

#include <tchar.h>
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <wincrypt.h>
#include "crypto.h"

#define RW_SIZE         512
#define BUFFER_SIZE     RW_SIZE * 2

//---------------------------------------------------------------
void DisplayUsage(void)
{
    _tprintf(TEXT("Usage:\n"));
    _tprintf(TEXT("  Encrypt file1 to file2: "));
    _tprintf(TEXT("crypto -e password file1 file2\n"));
    _tprintf(TEXT("  Decrypt file1 to file2: "));
    _tprintf(TEXT("crypto -d password file1 file2\n"));
}

//---------------------------------------------------------------
BOOL myEOF(HANDLE hFile, DWORD dwFileSize)
{
    DWORD dwCurPos = SetFilePointer(hFile, 0, NULL, FILE_CURRENT);
    if (dwCurPos >= dwFileSize) {
        return TRUE;
    } else {
        return FALSE;

    }
}

//---------------------------------------------------------------
int main (int argc, char **argv)
{
    // Validate command line parameters

    if (argc < 5) {
        DisplayUsage();
        return 0;
    }

    BOOL bEncrypt;
    if (lstrcmpi(argv[1], TEXT("-e")) == 0) {
        bEncrypt = TRUE;
    } else if (lstrcmpi(argv[1], TEXT("-d")) == 0) {
        bEncrypt = FALSE;
    } else {
        DisplayUsage();
        return 0;
    }

    // Open the input and output files

    HANDLE hFile1 = CreateFile((LPSTR)argv[3], GENERIC_ALL, 0, 
                               NULL, OPEN_EXISTING,
                               FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile1 == INVALID_HANDLE_VALUE) {
        DisplayUsage();
        _tprintf(TEXT("CreateFile %s failed (%x)\n"),
                 (LPSTR)argv[3], GetLastError());
        return 0;
    }

    HANDLE hFile2 = CreateFile((LPTSTR)argv[4], GENERIC_ALL, 0, 
                               NULL, CREATE_ALWAYS,
                               FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile2 == INVALID_HANDLE_VALUE) {
        CloseHandle(hFile1);
        DisplayUsage();
        _tprintf(TEXT("CreateFile %s failed (%x)\n"),
                 (LPSTR)argv[4], GetLastError());
        return 0;
    }

    // Allocate buffer to read/write and encrypt.decrypt data

    LPBYTE pBuffer = (LPBYTE)malloc(BUFFER_SIZE);
    if (pBuffer == NULL) {
        CloseHandle(hFile1);
        CloseHandle(hFile2);
        _tprintf(TEXT("malloc failed (%x)\n"), GetLastError());
        return 0;
    }

    DWORD dwBytesW = 0, dwBytes = 0;
    DWORD dwFileSize = GetFileSize(hFile1, NULL);

    // Allocate a CMyCrypto object

    CMyCrypto myCrypto((LPSTR)argv[2], CALG_RC4);

    if (bEncrypt) {

        // Read data from file1, save encrypted data to file2

        while (ReadFile(hFile1, pBuffer, RW_SIZE, &dwBytes, NULL)
               && dwBytes > 0) {
            if (myCrypto.Encrypt(pBuffer, &dwBytes, BUFFER_SIZE,
                                 myEOF(hFile1, dwFileSize))) {
                WriteFile(hFile2, pBuffer, dwBytes, &dwBytesW, 
                          NULL);
            }
        }

    } else {

        // Read data from file1, save decrypted data to file2

        while (ReadFile(hFile1, pBuffer, RW_SIZE, &dwBytes, NULL)
               && dwBytes > 0) {
            if (myCrypto.Decrypt(pBuffer, &dwBytes, 
                                 myEOF(hFile1, dwFileSize))) {
                WriteFile(hFile2, pBuffer, dwBytes, &dwBytesW,
                          NULL);
            }
        }
    }

    free(pBuffer);
    CloseHandle(hFile1);
    CloseHandle(hFile2);
    return 0;
}


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video