Archive for the ‘Windows’ Category

Making HTTP Requests in C++ with WinInet and CFNetwork

First, a disclaimer: I love cURL, but there are times when you simply do not want/need to use third-party libraries. This post has nothing to do with cURL. It has everything to do with making HTTP requests with the native API’s for doing HTTP requests on Windows and OS X.

If you are here, odds are that you’ve just spent the last few hours in a futile attempt to understand either the WinInet or CFNetwork documentation. In fairness, the documentation from Microsoft and Apple is decent enough … But let’s face it, you want a quick and dirty example and there are none.

The following snippets are complete working examples. They are simple HTTP GET requests from start to finish. They DO NOT take into consideration proxy servers or HTTP auth. They DO NOT show you how to do an HTTP post. Once you get the basics though, it’s really not that far of a leap to get the rest.

If anyone would like to dive into those subject in more detail, we certainly can. Let me know, and we can talk.

Note that there’s not a lot of error handling in the code below. Just take a look at the API docs for information about what these functions return, and how to respond to errors.

Windows via WinInet:

#include <Windows.h>
#include <WinInet.h>
#include <iostream>
#include <string>

int main(int argc, char *argv[])
{
  HINTERNET hInternet = InternetOpenW(L"MyUserAgent", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

  if( hInternet==NULL )
  {
    std::cout << "InternetOpenW failed with error code " << GetLastError() << std::endl;
  }
  else
  {
    HINTERNET hConnect = InternetConnectW(hInternet, L"www.your_server.com", 80, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);

    if( hConnect==NULL )
    {
      std::cout << "InternetConnectW failed with error code " << GetLastError() << std::endl;
    }
    else
    {
      const wchar_t* parrAcceptTypes[] = { L"text/*", NULL };
      HINTERNET hRequest = HttpOpenRequestW(hConnect, L"GET", L"", NULL, NULL, parrAcceptTypes, 0, 0);

      if( hRequest==NULL )
      {
        std::cout << "HttpOpenRequestW failed with error code " << GetLastError() << std::endl;
      }
      else
      {
        BOOL bRequestSent = HttpSendRequestW(hRequest, NULL, 0, NULL, 0);

        if( !bRequestSent )
        {
          std::cout << "HttpSendRequestW failed with error code " << GetLastError() << std::endl;
        }
        else
        {
          std::string strResponse;
          const int nBuffSize = 1024;
          char buff[nBuffSize];

          BOOL bKeepReading = true;
          DWORD dwBytesRead = -1;

          while(bKeepReading && dwBytesRead!=0)
          {
            bKeepReading = InternetReadFile( hRequest, buff, nBuffSize, &dwBytesRead );
            strResponse.append(buff, dwBytesRead);
          }

          std::cout << strResponse << std::endl;
        }

        InternetCloseHandle(hRequest);
      }

      InternetCloseHandle(hConnect);
    }

    InternetCloseHandle(hInternet);
  }

  return 0;
}

OS X via CFNetwork*

#include <iostream>
#include <fstream>
#include <CoreFoundation/CoreFoundation.h>
#include <CFNetwork/CFNetwork.h>
#include <CFNetwork/CFHTTPStream.h>

int main(int argc, char *argv[])
{
  CFURLRef cfUrl = CFURLCreateWithString(kCFAllocatorDefault, CFSTR("http://www.foo.com/stuff"), NULL);
  CFHTTPMessageRef cfHttpReq = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), cfUrl, kCFHTTPVersion1_1);

  CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, cfHttpReq);
  CFReadStreamOpen(readStream);

  CFMutableDataRef cfResp = CFDataCreateMutable(kCFAllocatorDefault, 0);

  CFIndex numBytesRead;

  do
  {
    const int nBuffSize = 1024;
    UInt8 buff[nBuffSize];
    numBytesRead = CFReadStreamRead(readStream, buff, nBuffSize);

    if( numBytesRead > 0 )
    {
      CFDataAppendBytes(cfResp, buff, numBytesRead);
    }
    else if( numBytesRead < 0 )
    {
      CFStreamError error = CFReadStreamGetError(readStream);
      std::cout << error.error << std::endl;
    }
  } while( numBytesRead > 0 );

  CFReadStreamClose(readStream);

  // to write to file, uncomment code below.
  //std::ofstream oFile;
  //oFile.open("/Users/cbarnes/Desktop/file.out", std::ios::out|std::ios::binary);
  //oFile.write( (const char*)CFDataGetBytePtr(cfResp), CFDataGetLength(cfResp));

  CFRelease(cfUrl);
  CFRelease(cfHttpReq);
  CFRelease(readStream);
  CFRelease(cfResp);

  return 0;
}

* To keep things simple, this code does not use run loops, polling, or callbacks. It just blocks until the request is complete. If you’d like to see an example of such, let me know.

Simple File Encrypter v0.3b

Simple File Encrypter version 0.3b is done.  Tested on Windows, OS X, Linux, and Solaris.

http://projects.cryptofreek.org/SimpleFileEncrypter/

 

Encrypting and Decrypting Files with Java

This information is old and crufty. There’s still some decent stuff here, but check up the updated version here: https://cryptofreek.org/2012/12/10/encrypting-and-decrypting-java-part-2/

I’m working on a little app that can do simple and portable file encryption across different operating systems.  Something I can put on a thumb drive to encrypt files so that when I inevitably loose the drive, all my documents aren’t public knowledge.

Most modern operating systems offer file encryption … a lot of new external drives and flash drives come with programs that will encrypt the filesystem … but all of those things are a huge pain when you live on multiple platforms.  I move files around between my Windows, Mac, and Solaris computers at work and my Linux boxes at home.  I need something simple to get the job done that works on all of the above.  Java lets me do this pretty easily, let’s take a look …

Cryptography is still a bit of a black art, even when looking at high level API’s like we’ll see in this example.  There are any number of different ways to do this using different types of keys and algorithms.  In this example, I’ll be using a simple password based symmetric key with Triple DES (DESede) encryption (PKCS #5, RFC2898).  Please see the RFC doc for a definition of terminology.

Creating the cipher

The first step is generating an encryption key and using it to create a cipher:

public static Cipher createCipher( char[] password,
                                   int nMode,
                                   byte[] baSalt,
                                   int nInterations ) throws NoSuchAlgorithmException,
                                                     InvalidKeySpecException,
                                                     InvalidKeyException,
                                                     InvalidAlgorithmParameterException,
                                                     NoSuchPaddingException
{
  Cipher cipher = null;

  PBEParameterSpec pbeParamSpec = new PBEParameterSpec( baSalt, nInterations );

  PBEKeySpec pbeKeySpec = new PBEKeySpec( password );
  SecretKeyFactory keyFac = SecretKeyFactory.getInstance( "PBEWithSHA1AndDESede" );
  SecretKey key = keyFac.generateSecret( pbeKeySpec );

  cipher = Cipher.getInstance( "PBEWithSHA1AndDESede" );
  cipher.init( nMode, key, pbeParamSpec );

  return cipher;
}

Encrypting/Decrypting with IO Streams

Once the cipher is created, the crypto operation is as easy as reading and writing to IO streams. These could be any streams you could think of, but in this case we are using file streams:

public static void doCrypto( InputStream in, OutputStream out, Cipher cipher ) throws IOException
{
  CipherOutputStream cos = new CipherOutputStream( out, cipher );
  byte[] baChunck = new byte[1024];

  for( int nRead = 0; nRead &gt;= 0; nRead = in.read( baChunck ) )
  {
    cos.write( baChunck, 0, nRead );
  }

  in.close();
  out.close();
  cos.close();
}

Done!

That’s it, here’s a full working example:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

public class CCryptoUtils
{
  public static Cipher createCipher( char[] password,
                                     int nMode,
                                     byte[] baSalt,
                                     int nInterations ) throws NoSuchAlgorithmException,
                                                       InvalidKeySpecException,
                                                       InvalidKeyException,
                                                       InvalidAlgorithmParameterException,
                                                       NoSuchPaddingException
  {
    Cipher cipher = null;

    PBEParameterSpec pbeParamSpec = new PBEParameterSpec( baSalt, nInterations );

    PBEKeySpec pbeKeySpec = new PBEKeySpec( password );
    SecretKeyFactory keyFac = SecretKeyFactory.getInstance( "PBEWithSHA1AndDESede" );
    SecretKey key = keyFac.generateSecret( pbeKeySpec );

    cipher = Cipher.getInstance( "PBEWithSHA1AndDESede" );
    cipher.init( nMode, key, pbeParamSpec );

    return cipher;
  }

  public static void doCrypto( InputStream in, OutputStream out, Cipher cipher ) throws IOException
  {
    CipherOutputStream cos = new CipherOutputStream( out, cipher );
    byte[] baChunck = new byte[128];

    for( int nRead = 0; nRead &gt;= 0; nRead = in.read( baChunck ) )
    {
      cos.write( baChunck, 0, nRead );
    }

    in.close();
    cos.close();
  }

  public static void doFileOperation( File fileIn,
                                      File fileOut,
                                      int nMode,
                                      char[] password,
                                      byte[] baSalt,
                                      int nIterations ) throws InvalidKeyException,
                                                       NoSuchAlgorithmException,
                                                       InvalidKeySpecException,
                                                       InvalidAlgorithmParameterException,
                                                       NoSuchPaddingException,
                                                       FileNotFoundException,
                                                       IOException
  {
    Cipher cipher = createCipher( password, nMode, baSalt, nIterations );
    doCrypto( new FileInputStream( fileIn ),
              new FileOutputStream( fileOut ),
              cipher );
  }

  public static void main( String[] args )
  {
    char[] password = "mypassword".toCharArray();
    byte[] baSalt = "'~7&amp;03~/.".getBytes();
    int nIterations = 1;

    File fileToEncrypt = new File( "/Users/cryptofreek/Desktop/test.txt" );
    File fileEncrypted = new File( "/Users/cryptofreek/Desktop/test.txt.encrypted" );
    File fileDecrypted = new File( "/Users/cryptofreek/Desktop/test.txt.decrypted" );

    try
    {
      doFileOperation( fileToEncrypt,
                       fileEncrypted,
                       Cipher.ENCRYPT_MODE,
                       password,
                       baSalt,
                       nIterations );

      doFileOperation( fileEncrypted,
                       fileDecrypted,
                       Cipher.DECRYPT_MODE,
                       password,
                       baSalt,
                       nIterations );
    }
    catch( Exception e )
    {
      e.printStackTrace();
    }
  }
}

Update:  The real beauty of using IO streams like this is that you do not have to worry as much about Java’s heap space.  Your memory usage rarely grows past the chunk size specified in the “doCrypto()” function; even if you are operating on huge files.