TDD driven AES Encryption, from scratch

Because documentation and testing come first

Measuring test coverage, 93% test coverage


Documentation matters!


All the details

AES_java

// but click here for the full uncensored code

  /**
   * Applies S-Box substitution to each byte of a state matrix.
   * 
   * @param s
   *          A state matrix having Nb columns and 4 rows.
   * @return s, after S-box substitution is applied to each byte.
   */
  protected int[][] subBytes(int[][] s) {
    for (int i = 0; i < 4; i++) {
      for (int j = 0; j < Nb; j++) {
        s[i][j] = subWord(s[i][j]) & 0xFF;
      }
    }
    return s;
  }

  /**
   * Applies S-box substitution to each byte of a 4-byte word.
   * 
   * @param w
   *          A 4-byte word.
   * @return w, after S-box substitution is applied to each byte.
   */
  protected static int subWord(int w) {
    int subWord = 0;
    for (int i = 24; i >= 0; i -= 8) {
      int in = w << i >>> 24;
      subWord |= sBox[in] << (24 - i);
    }
    return subWord;
  }

  /**
   * Multiplies x times a polynomial b(x) in GF(2^8) modulo the irreducible
   * polynomial m(x) = x^8+x^4+x^3+x+1. (i.e. m(x) = 0x11b).
   * 
   * @param b
   *          A polynomial b(x) = b7x^7+b6x^6+b5x^5+b4x^4+b3x^3+b2x^2+b1x+b0 in
   *          GF(2^8).
   * @return xb(x) mod x8+x4+x3+x+1.
   */
  protected static int xtime(int b) {
    if ((b & 0x80) == 0)
      return b << 1;
    return (b << 1) ^ 0x11b;
  }
}