Archive for the ‘Cryptography’ Category

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?

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/

 

sometimes I even confuse myself

I’ve got this long standing personal project that I just can’t seem to finish.  It’s this file encryption program that I only seem to find time to work on in the 30 minutes before bed time.  I’ve got the core written and it’s working mostly everywhere (even on my Droid).  All I’ve got left is to wrap a GUI around it, and I’ll at least have a releasable beta.  I don’t care much for front-end development, so perhaps that’s why I’ve hit a roadblock… No sure.

Anyway, I’m sitting here looking at some of the high level crypto functions and I’m having trouble following the logic.  I can’t tell if my own code is genius or just plain dumb.

Creating your own self-signed certificates and keys (UPDATED)

I’ve set up a little PHP page that will generate self-signed certificates and bundle the associated private key in a PKCS12 file:

http://content.cryptofreek.org/pkcs12/

Basically it uses OpenSSL like this:

openssl genrsa -aes256 2048 > temp.key
openssl req -new -x509 -key temp.key -out temp.crt -days 365 -subj "/CN=John\ Doe/emailAddress=john.doe@mail.com"
openssl pkcs12 -export -in temp.crt -out temp.p12 -name "my self signed P12 from cryptofreek.org" -inkey temp.key

It’s a handy little utility; a quick and dirty way to generate certificates for testing. I’m sure that I will be broaden the features soon.

Originally wrote some bash scripts that used the “openssl” command on the server, but it was kinda hokey with a bit too much file IO.

Now, the backend has been rewritten to use the (sparsely documented) OpenSSL functions in PHP.

Free PKI Certificates from CAcert.org

If you don’t know what a digital certificate is or why you might need one, I’ll save you the effort and you can stop reading here.

If, like me, you are either too poor or too cheap to give VeriSign your money … CAcert.org seems like an ok option.

I know, I know … This IS NOT an enterprise class, super reliable way of certifying users.  However, it is probably good enough for playing with your friends.

Signup is easy, issuing certificates is easy, revoking your certificates is easy.  Go give it a try…

Here’s my cert:

-----BEGIN CERTIFICATE-----
MIIFOTCCAyGgAwIBAgIDCgssMA0GCSqGSIb3DQEBBQUAMHkxEDAOBgNVBAoTB1Jv
b3QgQ0ExHjAcBgNVBAsTFWh0dHA6Ly93d3cuY2FjZXJ0Lm9yZzEiMCAGA1UEAxMZ
Q0EgQ2VydCBTaWduaW5nIEF1dGhvcml0eTEhMB8GCSqGSIb3DQEJARYSc3VwcG9y
dEBjYWNlcnQub3JnMB4XDTExMDQwNDE5NTE0OFoXDTExMTAwMTE5NTE0OFowQDEY
MBYGA1UEAxMPQ0FjZXJ0IFdvVCBVc2VyMSQwIgYJKoZIhvcNAQkBFhVjcnlwdG9m
cmVla0BnbWFpbC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC0
6L3yvvVcvWSkgv7UOaPGWQ9ShrMVfTFC7IpEzIbyluSPlZBNbBeXHdWsu/55X9uh
+A9T1gTwFNQeEXMsbf0rkEB5RwsH74wbkNNV8WYPMYyakdu1Wctlsaf10Wtfd1NR
1eQ4efiONMklZqjIyHRdKbBZLb2qGazMhHp+B3qzbt9vZufAzXcVn+b5Nk8mSbZg
KnPQ+uozy0KNfGs7x2sS9ti0g2G7S7ARdEKPGuJp+My5U8LUTcly4U65huN2uq/d
sh7Jruu0lzZDKqvFI7wnwikkZP/4XfA6Q4IXa58eVoLOCBIc5GVcNibY9kH3L4Ps
ot2TlA6uN9S1InG/9m4HAgMBAAGjggEBMIH+MAwGA1UdEwEB/wQCMAAwVgYJYIZI
AYb4QgENBEkWR1RvIGdldCB5b3VyIG93biBjZXJ0aWZpY2F0ZSBmb3IgRlJFRSBo
ZWFkIG92ZXIgdG8gaHR0cDovL3d3dy5DQWNlcnQub3JnMEAGA1UdJQQ5MDcGCCsG
AQUFBwMEBggrBgEFBQcDAgYKKwYBBAGCNwoDBAYKKwYBBAGCNwoDAwYJYIZIAYb4
QgQBMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcwAYYWaHR0cDovL29jc3AuY2Fj
ZXJ0Lm9yZzAgBgNVHREEGTAXgRVjcnlwdG9mcmVla0BnbWFpbC5jb20wDQYJKoZI
hvcNAQEFBQADggIBAMQ2N9WrIvJCDvT6xSD5wwz+twC919voLMQrRPMbxQWgGoKV
Krtnlh3eGjBzczNIAzFF/1hwhZi0hwwyhw2s+X+lTC/KRGTGw4LUvc0/Ush+uYdr
Kx8LD+BCh68p5LWCb/gJ8y/Q+3SLdxAafoZz4j0CKX3chGRHfMdUDzQDbPHD+SNw
fFAzJTzrWKWgf1zuw+vYAwE/QIFgXg0x3aCWyWXFwcYwmAeFdz0PI0TncWuhOQzU
Cy7PwAbOYp7Lds9zE7vtJol2UwswseRW8ZJ9sgOXzxRTAHm1nSpOO0joKkX+KrkG
QVFBDbZo6nyBclEaXuPtmWNdWflvWafzBWWismYNiFrcJrte0pPtDQsiLyRkSZps
teCxODnzxmfZySDQNnCxrafAajWl19d0B9SemS1sBUBK9sfm7WvcUFerzEqpc1b6
wXeg276hmdPEttmrlzQW/JQ9Sscfa94JzCE9+rHtJcSynv4HPJGH2A787gWODi8a
wWeafs+vAGZ/fNVtFFy4/BAwHbfX/KpoXS5CdIftixq6Mpfd5Tt+N5kk0jS8j74o
7cDPZh3W5ElX0m7AZEEWPSWzITfVXXZXvB1KP8ek/S16gJ9oavxegVIyqUr6ganj
szbkxSK3RKFXb/b+ILXjCoPU2dAP3cBxahA2wS6a2eqh/0w7aymnKRsyFMdJ
-----END CERTIFICATE-----

You can also grab the root and intermediate certificates here.

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.