Author Archive

Base64 Encoding and Decoding in Java

Base64 encoding is a convenient way to represent binary data as plain text. This allows for transport of said binary data over a medium that is traditionally more text friendly. In the general case, simply storing binary data as text is quite handy sometimes.

The most common ways to accomplish this are either Base64 encoding, or to HEX. Base64 encoding takes 3 bytes of binary data and turns it into 4 bytes of text. HEX encoding takes 1 byte of binary data, and turns it into 2 bytes of text. 3 bytes of binary data would be transformed into 6 bytes with HEX. While the difference between 4 and 6 bytes isn’t that bad, if you multiply that difference millions of times, the savings really become significant. Therefore, Base64 encoding is more efficient in storage/transport than HEX.

So, here’s my shot at a simple Base64 encoding and decoding in Java. I hammered it out in about 15 minutes; hopefully it’s not horrendously bad. There are tons of other tried/tested Base64 encoders out there; this was an academic exercise at best … for now anyway …

/*
 * Copyright (c) 2014
 * Cole Barnes [cryptofreek{at}gmail{dot}com]
 * https://cryptofreek.org/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package org.cryptofreek.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class CBase64Utils
{
  private static final String BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

  public static String encode(byte[] ba)
  {
    String strB64 = null;

    if (ba == null)
    {
      strB64 = null;
    }
    else
    {
      try
      {
        ByteArrayInputStream in = new ByteArrayInputStream(ba);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        encode(in, out);

        out.flush();
        out.close();
        in.close();

        strB64 = new String(out.toByteArray());
      }
      catch (IOException e)
      {
        strB64 = null;
        e.printStackTrace();
      }
    }

    return strB64;
  }

  public static void encode(InputStream in, OutputStream out) throws IOException
  {
    if (in == null || out == null)
    {
      // nothing to do
    }
    else
    {
      byte[] buff = new byte[3];
      int nRead = 0;
      int nPaddingChars = 0;

      while ((nRead = in.read(buff)) > 0)
      {
        if (nRead == 1)
        {
          // pad last 2 bytes
          buff[1] = 0;
          buff[2] = 0;
          nPaddingChars = 2;
        }
        else if (nRead == 2)
        {
          // pad last byte
          buff[2] = 0;
          nPaddingChars = 1;
        }
        else
        {
          // buffer full, no need to pad
        }

        // a little help here from:
        //    http://www.wikihow.com/Encode-a-String-to-Base64-With-Java
        int n = ((buff[0] & 0xff) << 16) + ((buff[1] & 0xff) << 8) + (buff[2] & 0xff);

        byte[] baTmp = new byte[4];
        baTmp[0] = (byte) BASE64_CHARS.charAt((n >> 18) & 0x3f);
        baTmp[1] = (byte) BASE64_CHARS.charAt((n >> 12) & 0x3f);

        if (nPaddingChars == 2)
        {
          baTmp[2] = (byte) '=';
        }
        else
        {
          baTmp[2] = (byte) BASE64_CHARS.charAt((n >> 6) & 0x3f);
        }

        if (nPaddingChars == 1 || nPaddingChars == 2)
        {
          baTmp[3] = (byte) '=';
        }
        else
        {
          baTmp[3] = (byte) BASE64_CHARS.charAt(n & 0x3f);
        }

        out.write(baTmp);
        out.flush();
      }
    }
  }

  public static byte[] decode(String strB64)
  {
    byte[] ba = null;

    if (strB64 == null)
    {
      ba = null;
    }
    else if (strB64.length() == 0)
    {
      ba = new byte[0];
    }
    else
    {
      try
      {
        byte[] baB64 = strB64.getBytes("UTF-8");
        ByteArrayInputStream in = new ByteArrayInputStream(baB64);
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        decode(in, out);

        out.flush();
        out.close();
        in.close();

        ba = out.toByteArray();
      }
      catch (UnsupportedEncodingException e)
      {
        ba = null;
        e.printStackTrace();
      }
      catch (IOException e)
      {
        ba = null;
        e.printStackTrace();
      }
    }

    return ba;
  }

  public static void decode(InputStream in, OutputStream out) throws IOException
  {
    if (in == null || out == null)
    {
      // nothing to do
    }
    else
    {
      byte[] buff = new byte[4];
      int nBytesRead = 0;

      while ((nBytesRead = in.read(buff)) > 0)
      {
        if (nBytesRead != 4) { throw new IOException("The input was not a valid Base64 encoding; block read was less than 4 bytes."); }

        char c0 = (char) buff[0];
        char c1 = (char) buff[1];
        char c2 = (char) buff[2];
        char c3 = (char) buff[3];

        byte b0 = (byte) BASE64_CHARS.indexOf(c0);
        byte b1 = (byte) BASE64_CHARS.indexOf(c1);
        byte b2 = (c2 == '=')?0:(byte) BASE64_CHARS.indexOf(c2);
        byte b3 = (c3 == '=')?0:(byte) BASE64_CHARS.indexOf(c3);

        int n = ((b0 & 0x3f) << 18) + ((b1 & 0x3f) << 12) + ((b2 & 0x3f) << 6) + ((b3 & 0x3f));

        out.write((byte) (n >> 16) & 0xff);
        if( c2!='=' ) out.write((byte) (n >> 8) & 0xff);
        if( c3!='=' ) out.write((byte) (n) & 0xff);
      }
    }
  }

  public static void main(String[] args)
  {
    // example taken from:
    //    http://en.wikipedia.org/wiki/Base64
    String strKnown = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
    String strKnownB64 = "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=";

    byte[] ba = strKnown.getBytes();

    String strB64 = encode(ba);
    System.out.println("Calculated Base64 string:  " + strB64);
    System.out.println("     Known Base64 string:  " + strKnownB64);
    System.out.println("                   Match:  " + strB64.equals(strKnownB64));

    System.out.println();

    byte[] baData = decode(strB64);
    String str = new String(baData);
    System.out.println("Decoded string:  " + str);
    System.out.println("  Known string:  " + strKnown);
    System.out.println("         Match:  " + str.equals(strKnown));
  }
}

Asynchronous HTTP request using CFNetwork framework.

I wrote a post a few months ago concerning HTTP requests with CFNetwork and WinInet. Read it here:

Making HTTP Requests in C++ with WinInet and CFNetwork

There was a question about making the OS X CFNetwork code asynchronous, so here’s an example of how to do it:

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

std::string strFile;
std::ofstream file;

void _handleFinishCondition( CFReadStreamRef stream, bool bDeleteDownloadedFile, int nExitCode )
{
  file.close();

  if( bDeleteDownloadedFile )
  {
    remove( strFile.c_str() );
  }

  CFReadStreamUnscheduleFromRunLoop( stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes );
  CFReadStreamClose(stream);
  CFRelease(stream);

  std::cout << "exiting with code:  " << nExitCode << std::endl;
  exit(nExitCode);
}

void _httpReqCallback( CFReadStreamRef stream, CFStreamEventType event, void* ptr )
{
  if( !file.is_open() )
  {
    file.open( strFile.c_str(), std::ios::out|std::ios::binary);
  }

  switch( event )
  {
    case kCFStreamEventHasBytesAvailable:
    {
      UInt8 buff[1024];
      CFIndex nBytesRead = CFReadStreamRead(stream, buff, 1024);

      if( nBytesRead>0 )
      {
        file.write( (const char*)buff, nBytesRead );
      }

      break;
    }
    case kCFStreamEventErrorOccurred:
    {
      CFStreamError err = CFReadStreamGetError(stream);
      _handleFinishCondition(stream, true, err.error);
    }
    case kCFStreamEventEndEncountered:
    {
      _handleFinishCondition(stream, false, 0);
    }
  }
}

void doHttpRequest(const char* pstrUrl, const char* pstrOutFile)
{
  strFile = pstrOutFile;
  CFStringRef cfstrUrl = CFStringCreateWithCString(kCFAllocatorDefault, pstrUrl, kCFStringEncodingUTF8);

  CFURLRef cfUrl = CFURLCreateWithString(kCFAllocatorDefault, cfstrUrl, NULL);
  CFHTTPMessageRef cfHttpReq = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("GET"), cfUrl, kCFHTTPVersion1_1);

  CFReadStreamRef readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, cfHttpReq);
  CFOptionFlags optEvents = kCFStreamEventHasBytesAvailable|kCFStreamEventErrorOccurred|kCFStreamEventEndEncountered;

  CFStreamClientContext context = {0, NULL, NULL, NULL, NULL };

  CFReadStreamSetClient(readStream, optEvents, _httpReqCallback, &context );
  CFReadStreamScheduleWithRunLoop( readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes );
  CFReadStreamOpen( readStream );

  CFRunLoopRun();

  CFRelease(cfUrl);
  CFRelease(cfHttpReq);
}

int main(int argc, const char * argv[])
{
  doHttpRequest("http://foo.com/stuff", "/Users/cbarnes/Desktop/file.out");
  return 0;
}

As always, I don’t want to do all the work for you. This is working code, NOT safe code. Please make sure you understand what is happening here, and that you do your own error checking. Please take a look at the CFNetwork docs for detailed info:

CFNetwork Programming Guide

If there are any questions/comments/improvements, please comment.

Encrypting and Decrypting Java – Part 2

A few years ago, I wrote a post regarding file encryption with Java here: https://cryptofreek.org/2010/06/04/encrypting-and-decrypting-files-with-java/

To my amazement, that post still gets tons of hits and it’s linked to from lots of different places. The problem, it’s a bit crusty and I really don’t like it that much. So, here’s a much needed update:


I’m not going to spend much time explaining everything here. Hopefully the comments in the code will do that. This example uses AES, but could be easily modified to use other encryption algorithms.

Generating secure keys is beyond the scope of this post, but take a look here for a decent starting point: https://cryptofreek.org/2012/11/29/pbkdf2-pure-java-implementation/

If you have any questions, let me know!

/*
 * Copyright (c) 2012 Cole Barnes [cryptofreek{at}gmail{dot}com]
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Formatter;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class CEncryptExample
{
  /**
   * Encrypts the data received from the specified InputStream; encrypted data
   * is written to the specified OutputStream.
   *
   * @param key          The secret key used to encrypt the data.
   * @param baIv         The initialization vector to be used in encryption.
   * @param in           InputStream for reading data to encrypt.
   * @param out          OutputStream for writing encrypted data.
   * @param strCipherAlg The encryption algorithm to use; this must correspond
   *                     to something that makes sense with the specified
   *                     secret key.
   * @throws Exception
   */
  public static void encrypt(SecretKey key, byte[] baIv, InputStream in, OutputStream out, String strCipherAlg) throws Exception
  {
    doCrypto(key, baIv, in, out, Cipher.ENCRYPT_MODE, strCipherAlg);
  }

  /**
   * Decrypts the data received from the specified InputStream; decrypted data
   * is written to the specified OutputStream.
   *
   * @param key          The secret key used to decrypt the data.
   * @param baIv         The initialization vector to be used in decryption.
   * @param in           InputStream for reading encrypted data.
   * @param out          OutputStream for writing decrypted data.
   * @param strCipherAlg The encyption algorithm to use; this must correspond
   *                     to something that makes sense with the specified
   *                     secret key.
   * @throws Exception
   */
  public static void decrypt(SecretKey key, byte[] baIv, InputStream in, OutputStream out, String strCipherAlg) throws Exception
  {
    doCrypto(key, baIv, in, out, Cipher.DECRYPT_MODE, strCipherAlg);
  }

  /**
   * Performs the cryptographic operation on the specified IO Streams.  This
   * function is private and is not meant to be called directly.
   *
   * @param key          The secret key used in the crypto operation.
   * @param baIv         The initialization vector used in the crypto operation.
   * @param in           InputStream to from which data is read.
   * @param out          OutputStream to where data is written.
   * @param nMode        Operation mode; either Cipher.DECRYPT_MODE or Cipher.ENCRYPT_MODE
   * @param strCipherAlg The encryption algorithm; this must correspond to
   *                     something that makes sense with the specified secret key
   * @throws Exception
   */
  private static void doCrypto(SecretKey key, byte[] baIv, InputStream in, OutputStream out, int nMode, String strCipherAlg) throws Exception
  {
    Cipher cipher = Cipher.getInstance(strCipherAlg);
    cipher.init(nMode, key, new IvParameterSpec(baIv, 0, cipher.getBlockSize()));

    CipherInputStream cis = new CipherInputStream(in, cipher);

    byte[] baBuff = new byte[1024];
    int nBytesRead = -1;

    while ((nBytesRead = cis.read(baBuff)) != -1)
    {
      out.write(baBuff, 0, nBytesRead);
    }

    cis.close();
    in.close();

    out.flush();
    out.close();
  }

  /* There's only static utility/test functions from here down. */

  private static void doFileCryptoTest(SecretKey key, byte[] baIv, String strCipherAlg) throws Exception
  {
    String strFile = "/Users/cbarnes/Desktop/test.txt";
    String strEncryptedFile = "/Users/cbarnes/Desktop/test.txt.encrypted";
    String strDecryptedFile = "/Users/cbarnes/Desktop/test.txt.decrypted";

    encrypt(key, baIv, new FileInputStream(strFile), new FileOutputStream(strEncryptedFile), strCipherAlg);
    decrypt(key, baIv, new FileInputStream(strEncryptedFile), new FileOutputStream(strDecryptedFile), strCipherAlg);

    System.out.println("Encrypted File Hash:  " + calcDigest(new FileInputStream(strEncryptedFile)));
    System.out.println("Decrypted File Hash:  " + calcDigest(new FileInputStream(strDecryptedFile)));
    System.out.println("     Orig File Hash:  " + calcDigest(new FileInputStream(strFile)));
    System.out.println();
  }

  private static void doByteCryptoTest(SecretKey key, byte[] baIv, String strCipherAlg) throws Exception
  {
    byte[] baData = "This is some data.".getBytes();
    ByteArrayInputStream baisData = new ByteArrayInputStream( baData );
    ByteArrayOutputStream baosEncrytpedData = new ByteArrayOutputStream();

    encrypt(key, baIv, baisData, baosEncrytpedData, strCipherAlg);
    byte[] baEncrytpedData = baosEncrytpedData.toByteArray();

    ByteArrayInputStream baisEncryptedData = new ByteArrayInputStream(baEncrytpedData);
    ByteArrayOutputStream baosDecryptedData = new ByteArrayOutputStream();

    decrypt(key, baIv, baisEncryptedData, baosDecryptedData, strCipherAlg);
    byte[] baDecryptedData = baosDecryptedData.toByteArray();

    System.out.println("Encrypted Data Hash:  " + calcDigest(new ByteArrayInputStream(baEncrytpedData)));
    System.out.println("Decrypted Data Hash:  " + calcDigest(new ByteArrayInputStream(baDecryptedData)));
    System.out.println("     Orig Data Hash:  " + calcDigest(new ByteArrayInputStream(baData)));
    System.out.println();
  }

  private static String calcDigest(InputStream in) throws Exception
  {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");

    byte[] baBuff = new byte[1024];
    int nBytesRead = -1;

    while ((nBytesRead = in.read(baBuff)) != -1)
    {
      digest.update(baBuff, 0, nBytesRead);
    }

    in.close();

    byte[] baDigest = digest.digest();
    StringBuilder sb = new StringBuilder(baDigest.length * 2);
    Formatter formatter = new Formatter(sb);

    for (byte b : baDigest)
    {
      formatter.format("%02x", b);
    }

    formatter.close();
    String strDigest = sb.toString().toLowerCase();

    return strDigest;
  }

  public static void main(String[] args)
  {
    try
    {
      String strKeyAlg = "AES";
      int nKeySize = 128;
      String strCipherAlg = "AES/CBC/PKCS5Padding";

      /* It is your responsibility to come up with a secure manor in which to
       * generate encryption keys!!! */
      byte[] baKey = new byte[nKeySize / 8];
      SecureRandom.getInstance("SHA1PRNG").nextBytes(baKey);
      SecretKey key = new SecretKeySpec(baKey, strKeyAlg);

      /*
       * NEVER reuse initialization vectors (IV)!!!  They should be randomly/securely
       * generated for each separate encryption operation.  The IV should be
       * kept with the encrypted data; it is not "secret" and does not necessarily
       * need to be protected.  You only need to insure new secure IV is generated
       * each time data is encrypted; the same IV is used to decrypt the data.
       */
      byte[] baIv = new byte[128];

      SecureRandom.getInstance("SHA1PRNG").nextBytes(baIv);
      doFileCryptoTest(key, baIv, strCipherAlg);

      SecureRandom.getInstance("SHA1PRNG").nextBytes(baIv);
      doByteCryptoTest(key, baIv, strCipherAlg);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}

PBKDF2 – Pure Java Implementation

Here’s my PBKDF2 implementation. It’s a clean-room implementation straight from RFC 2898. It passes all RFC 6070 test vectors (testing code included).

It’s pure java with no weird requirements or external libraries. It performs reasonably well compared to the stock Java implementation of PBKDF2WithHmacSHA1; sometimes it beats it, sometimes it doesn’t. I’m sure there are ways to optimize performance.

Anyway, enjoy…

/*
 * Copyright (c) 2012
 * Cole Barnes [cryptofreek{at}gmail{dot}com]
 * https://cryptofreek.org/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 * -----------------------------------------------------------------------------
 * 
 * This is a clean-room implementation of PBKDF2 using RFC 2898 as a reference.
 * 
 * RFC 2898:
 * http://tools.ietf.org/html/rfc2898#section-5.2
 * 
 * This code passes all RFC 6070 test vectors:
 * http://tools.ietf.org/html/rfc6070
 * 
 * The function "nativeDerive()" is supplied as an example of the native Java 
 * PBKDF2WithHmacSHA1 implementation.  It is used for benchmarking and 
 * comparison only.
 * 
 * The functions "fromHex()" and "toHex()" came from some message board
 * somewhere.  No license was included.
 * 
 */

import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.spec.KeySpec;
import java.util.Formatter;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class CPbkdf2
{
  /* START RFC 2898 IMPLEMENTATION */
  public static byte[] derive(String P, String S, int c, int dkLen)
  {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try
    {
      int hLen = 20;

      if (dkLen > ((Math.pow(2, 32)) - 1) * hLen)
      {
        System.out.println("derived key too long");
      }
      else
      {
        int l = (int) Math.ceil((double) dkLen / (double) hLen);
        // int r = dkLen - (l-1)*hLen;

        for (int i = 1; i <= l; i++)
        {
          byte[] T = F(P, S, c, i);
          baos.write(T);
        }
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

    byte[] baDerived = new byte[dkLen];
    System.arraycopy(baos.toByteArray(), 0, baDerived, 0, baDerived.length);

    return baDerived;
  }

  private static byte[] F(String P, String S, int c, int i) throws Exception
  {
    byte[] U_LAST = null;
    byte[] U_XOR = null;

    SecretKeySpec key = new SecretKeySpec(P.getBytes("UTF-8"), "HmacSHA1");
    Mac mac = Mac.getInstance(key.getAlgorithm());
    mac.init(key);

    for (int j = 0; j < c; j++)
    {
      if (j == 0)
      {
        byte[] baS = S.getBytes("UTF-8");
        byte[] baI = INT(i);
        byte[] baU = new byte[baS.length + baI.length];

        System.arraycopy(baS, 0, baU, 0, baS.length);
        System.arraycopy(baI, 0, baU, baS.length, baI.length);

        U_XOR = mac.doFinal(baU);
        U_LAST = U_XOR;
        mac.reset();
      }
      else
      {
        byte[] baU = mac.doFinal(U_LAST);
        mac.reset();

        for (int k = 0; k < U_XOR.length; k++)
        {
          U_XOR[k] = (byte) (U_XOR[k] ^ baU[k]);
        }

        U_LAST = baU;
      }
    }

    return U_XOR;
  }

  private static byte[] INT(int i)
  {
    ByteBuffer bb = ByteBuffer.allocate(4);
    bb.order(ByteOrder.BIG_ENDIAN);
    bb.putInt(i);

    return bb.array();
  }
  /* END RFC 2898 IMPLEMENTATION */

  /* START HELPER FUNCTIONS */
  private static String toHex(byte[] ba)
  {
    String strHex = null;

    if (ba != null)
    {
      StringBuilder sb = new StringBuilder(ba.length * 2);
      Formatter formatter = new Formatter(sb);

      for (byte b : ba)
      {
        formatter.format("%02x", b);
      }

      formatter.close();
      strHex = sb.toString().toLowerCase();
    }

    return strHex;
  }

  private static byte[] nativeDerive(String strPassword, String strSalt, int nIterations, int nKeyLen)
  {
    byte[] baDerived = null;

    try
    {
      SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
      KeySpec ks = new PBEKeySpec(strPassword.toCharArray(), strSalt.getBytes("UTF-8"), nIterations, nKeyLen * 8);
      SecretKey s = f.generateSecret(ks);
      baDerived = s.getEncoded();
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

    return baDerived;
  }
  /* END HELPER FUNCTIONS */

  public static void runTestVector(String P, String S, int c, int dkLen, String strExpectedDk)
  {
    System.out.println("Input:");
    System.out.println("  P = \"" + P + "\"");
    System.out.println("  S = \"" + S + "\"");
    System.out.println("  c = " + c);
    System.out.println("  dkLen = " + dkLen);
    System.out.println();

    long nStartDk = System.nanoTime();
    byte[] DK = derive(P, S, c, dkLen);
    long nStopDk = System.nanoTime();
    
    long nStartDkNative = System.nanoTime();
    byte[] DK_NATIVE = nativeDerive(P, S, c, dkLen);
    long nStopDkNative = System.nanoTime();

    System.out.println("Output:");
    System.out.println("  DK          = " + toHex(DK));
    System.out.println("  DK_NATIVE   = " + toHex(DK_NATIVE));
    System.out.println("  DK_EXPECTED = " + strExpectedDk.replaceAll(" ", ""));
    System.out.println();

    System.out.println("Duration [my implementation]:      " + (nStopDk - nStartDk) + " ns" );
    System.out.println("Duration [native implementation]:  " + (nStopDkNative - nStartDkNative) + " ns" );
    
    System.out.println("---------------------------------------------------------------");
    System.out.println();
  }

  public static void RFC6070()
  {
    runTestVector("password", "salt", 1, 20, "0c 60 c8 0f 96 1f 0e 71 f3 a9 b5 24 af 60 12 06 2f e0 37 a6");
    runTestVector("password", "salt", 2, 20, "ea 6c 01 4d c7 2d 6f 8c cd 1e d9 2a ce 1d 41 f0 d8 de 89 57");
    runTestVector("password", "salt", 4096, 20, "4b 00 79 01 b7 65 48 9a be ad 49 d9 26 f7 21 d0 65 a4 29 c1");
    runTestVector("password", "salt", 16777216, 20, "ee fe 3d 61 cd 4d a4 e4 e9 94 5b 3d 6b a2 15 8c 26 34 e9 84");
    runTestVector("passwordPASSWORDpassword", "saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, 25, "3d 2e ec 4f e4 1c 84 9b 80 c8 d8 36 62 c0 e4 4a 8b 29 1a 96 4c f2 f0 70 38");
    runTestVector("pass\0word", "sa\0lt", 4096, 16, "56 fa 6a a7 55 48 09 9d cc 37 d7 f0 34 25 e0 c3");
  }

  public static void main(String[] args)
  {
    RFC6070();
  }
}

RFC 6070 Test Vectors and RFC 2898 implementations that enforce salt lengths.

UGH!!!

A little background: RFC 2898 defines (among other things) the PBKDF2 algorithm for generating encryption keys based on a given password. The details are unimportant, but it produces a salted password hash that is computationally impractical to crack given a sufficiently long salt over enough iterations. RFC 2989 “recommends” an iteration count of 1000 or greater (section “4.2 Iteration Count”). It also says that salts “should” be at least 8 octets (or 64 bits) long (section “4.1 Salt”).

When reading RFC’s, terminology is extremely important in implementation. The words “should” and “recommend” are very different from the word “must” (check out RFC 2119). Things that say “should” are not required to conform to the spec; however, “must” explicitly defines an absolute requirement.

In the world of cryptography, “should” things are very important. Your algorithm may not be as secure as you think if you ignore the “should” stuff, even though you have implemented everything as defined in the RFC. In the case of the PBKDF2 algorithm, simply don’t use salts less than 8 octets and less iterations then 1000. Simple as that. It’s not required by the RFC, it’s just smart.

From a developer’s standpoint, the question always looms: Do I give my users enough rope to hang themselves? When implementing PBKDF2, should I even allow salts of less than 64 bits or small iteration counts? For super secure systems, the answer probably should be “no”.

Now, as a general rule, it’s a bad idea attempt to code your own hashing algorithms. There are only a handful of people on the planet who have a firm enough grasp of modern cryptography to understand all the intricacies and implications of improperly coded cryptographic algorithms. I am not one of those people, and odds are, neither are you. So just don’t do it, especially if there’s a tried-and-true implementation available.

With that said, if you are going to attempt to code your own algorithms, there are certain test vectors that you can run through your code to make sure everything works properly. For PBKDF2 derived keys, those test vectors are defined in RFC 6070. If you are testing PBKDF2 with HmacSHA1, this is the set of data you use to test.

Sooooooooo… I’ve been playing around with PBKDF2 a bit, trying my hand at coding the algorithm in various languages, and testing the implementations that exist in various frameworks. I know I just told you not to do such things, but in fairness I’m not trying to generate the HMACs myself. PBKDF2 isn’t a hashing alogrithm, it takes a bunch of hashes and squarshes them together in such a way that would be extremely difficult and time consuming to crack the key through traditional means. And yes, I said “squarshes”.

Anyway, in testing I find that there are frameworks out there that enforce the recommended salt length specified in RFC 2898. They are incapable of running 5 out of the 6 test vectors in RFC 6070 because their salt is “salt” or “sa\0lt”; both of which are less than 64 bits in length. Like I said “UGH!!!”.

I know this is relatively minor. You can always implicitly test the validity of algorithms by running the same test data through multiple known/working implementations. It’s just the principle of the thing, ya know?

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.

HOWTO: JDBC over an SSH Tunnel

First, credit where credit is due. Most of this code came from here (I just modified it a bit):

http://www.miranet.ch/posts/2008/09/23/howto_jdbc_over_ssh/

You’ll also need JSch (a java implementation of SSH):

http://www.jcraft.com/jsch/

The major function of SSH tunnels are to secure what would otherwise be an unsecure client/server connection. But another awfully handy use of SSH tunnels are accessing remote resources that are not normally exposed. Databases, for example.

I recently needed to access a MySQL database on a remote server from some local Java code. This database is off on a third party hosting server that does not allow outside access to MySQL, but I can login via SSH.

So, here goes:

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class CTestDriver
{
  private static void doSshTunnel( String strSshUser, String strSshPassword, String strSshHost, int nSshPort, String strRemoteHost, int nLocalPort, int nRemotePort ) throws JSchException
  {
    final JSch jsch = new JSch();
    Session session = jsch.getSession( strSshUser, strSshHost, 22 );
    session.setPassword( strSshPassword );
    
    final Properties config = new Properties();
    config.put( "StrictHostKeyChecking", "no" );
    session.setConfig( config );
    
    session.connect();
    session.setPortForwardingL(nLocalPort, strRemoteHost, nRemotePort);
  }
  
  public static void main(String[] args)
  {
    try
    {
      String strSshUser = "ssh_user_name";                  // SSH loging username
      String strSshPassword = "abcd1234";                   // SSH login password
      String strSshHost = "your.ssh.hostname.com";          // hostname or ip or SSH server
      int nSshPort = 22;                                    // remote SSH host port number
      String strRemoteHost = "your.database.hostname.com";  // hostname or ip of your database server
      int nLocalPort = 3366;                                // local port number use to bind SSH tunnel
      int nRemotePort = 3306;                               // remote port number of your database 
      String strDbUser = "db_user_name";                    // database loging username
      String strDbPassword = "4321dcba";                    // database login password
      
      CTestDriver.doSshTunnel(strSshUser, strSshPassword, strSshHost, nSshPort, strRemoteHost, nLocalPort, nRemotePort);
      
      Class.forName("com.mysql.jdbc.Driver");
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:"+nLocalPort, strDbUser, strDbPassword);
      con.close();
    }
    catch( Exception e )
    {
      e.printStackTrace();
    }
    finally
    {
      System.exit(0);
    }
  }
}

So, now I can access the remote database and the traffic is encrypted on top of that!

Same disclaimer as always, this IS NOT production worthy code as is. The exception handling is crap and there’s lots more paranoia to be had. Please follow your own coding best-practices.

XMLHttpRequest (Part 2)

Just a continuation of the last post.

This XMLHttpRequest implementation straightens things out a bit. And, yes, I am well aware that there are better ways to do null checking. But if I did everything for you, you’d never have to learn anything for yourself…

function isObject(obj)
{
  var bIsObject = false;
  
  if( obj )
  {
    bIsObject = ( typeof obj=='object' );
  }
  
  return bIsObject;
}

function getObjectProperty( obj, strPropName )
{
  var prop = null;
  
  if( isObject(obj) && strPropName )
  {
    if( obj.hasOwnProperty(strPropName) )
    {
      prop = obj[strPropName];
    }
  }
  
  return prop;
}

function doHttpRequest( strUrl, objParams )
{
  var xmlhttp = null;

  try
  {
    // for all modern browsers
    xmlhttp = new XMLHttpRequest();
  }
  catch(e1)
  {
    try
    {
      // for IE5 and IE6
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e2)
    {
      alert("XMLHttpRequest object could not be created...");
    }
  }
  
  if( !xmlhttp )
  {
    alert("XMLHttpRequest object could not be created...");
  }
  else
  {
    var objRequestData = getObjectProperty(objParams, 'objRequestData');
    var bDoPost = getObjectProperty(objParams, 'bDoPost');
    var funcCallback = getObjectProperty(objParams, 'funcCallback');
    var objCallbackParams = getObjectProperty(objParams, 'objCallbackParams');
    
    if( !strUrl )
    {
      alert('URL cannot be blank...');
    }
    else
    {
      var strRequestData = '';
      if( objRequestData )
      {
        for( var strKey in objRequestData )
        {
          var strValue = objRequestData[strKey];

          if( strRequestData.length>0 )
          {
            strRequest += "&";
          }

          strRequestData += encodeURIComponent(strKey) + "=" + encodeURIComponent(strValue);
        }
      }
      
      xmlhttp.onreadystatechange = function()
      {
        if(xmlhttp.readyState == 4)
        {
          if( xmlhttp.status!=200 )
          {
            alert("Error in HTTP Request...\n\nStatus: "+xmlhttp.status+"\n"+xmlhttp.statusText);
          }
          else
          {
            if(!objCallbackParams)
            {
              objCallbackParams = { 'xmlhttp':xmlhttp };
            }
            else
            {
              objCallbackParams.xmlhttp = xmlhttp;
            }
            
            if( funcCallback )
            {
              funcCallback(objCallbackParams);
            }
            else
            {
              alert('http request done...');
            }
          }
        }
      }
      
      if( bDoPost )
      {
        xmlhttp.open("POST", strUrl, true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.send(strRequestData);
      }
      else
      {
        xmlhttp.open("GET", strUrl+"?"+strRequestData, true);
        xmlhttp.send(null);
      }
    }
  }
}

XMLHttpRequest

I hate the term “ajax” and I mostly refuse to use it… So I will refrain here.

The following javascript provides the basic/core functionality for all modern web applications: the asynchronous HTTP request.

function doHttpRequest( strUrl, objRequestData, bDoPost, callback )
{
  var xmlhttp = new XMLHttpRequest();
  
  if(!xmlhttp)
  {
    alert('Your browser is too old... Sorry.');
  }
  else
  {
    var strRequestData = "";
    for( var strKey in objRequestData )
    {
      var strValue = objRequestData[strKey];
      
      if( strRequestData.length>0 )
      {
        strRequest += "&";
      }
      
      strRequestData += encodeURIComponent(strKey) + "=" + encodeURIComponent(strValue);
    }
    
    xmlhttp.onreadystatechange = function()
    {
      if(xmlhttp.readyState == 4)
      {
        if( xmlhttp.status!=200 )
        {
          alert("Error in HTTP Request...\n\nStatus: "+xmlhttp.status+"\n"+xmlhttp.statusText);
        }
        else
        {
          var cbParams = { 'xmlhttp':xmlhttp };
          callback(cbParams);
        }
      }
    }
    
    if( bDoPost )
    {
      xmlhttp.open("POST", strUrl, true);
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlhttp.send(strRequestData);
    }
    else
    {
      xmlhttp.open("GET", strUrl+"?"+strRequestData, true);
      xmlhttp.send(null);
    }
  }
}

Anyway, that’s all mostly for my benefit. I usually end up having to write that stupid function from scratch once or twice a month…

You also may ask “why would you bother with the nuts-and-bolts like this when you could use some existing javascript library/framework?”. Well, there are people who use frameworks … and then there are the people who write the frameworks. There’s a lot more job security in the latter :)

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/