Loading…

Kryptel/Java

Example of Block Encryption

Block Encryption

This example illustrates using of IBlockCipher interface. Although that interface offers fully functional ciphering, its use is rather limited because the size of the input data must be a multiple of cipher's blocksize.

The example program encrypts N_BLOCKS blocks, decrypts them back, and compares the result with the original data. Even if of no practical value for end user, this program may be useful for testing a new cipher implementation.

import static com.kryptel.Guids.CID_CIPHER_AES;
import static com.kryptel.Guids.IID_IBlockCipher;
import static com.kryptel.Guids.IID_IBlockCipherParams;

import java.util.Arrays;
import java.util.Random;

import com.kryptel.IKryptelComponent;
import com.kryptel.Loader;
import com.kryptel.cipher.IBlockCipher;
import com.kryptel.cipher.IBlockCipherParams;


public class BlockCiphering {

  static final int N_BLOCKS = 4;

  public static void main(String[] args) {
    try {
      IKryptelComponent compCipher = Loader.CreateComponent(CID_CIPHER_AES);

      // Set cipher parameters
      IBlockCipherParams cipherParams =
            (IBlockCipherParams)compCipher.GetInterface(IID_IBlockCipherParams);
      cipherParams.SetBlockSize(16);  // Set block size to 128 bits
      cipherParams.SetKeySize(16);    // Set key size to 128 bits
      cipherParams.SetChainingMode(IBlockCipherParams.MODE_CBC); // Set CBC chaining mode

      // Set the encryption key
      // We don't set init vector, so all zeros init vector will be used
      byte key[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
      cipherParams.SetKey(key, 0, key.length);

      byte[] plaintext = new byte [N_BLOCKS * cipherParams.GetBlockSize()];
      Random rnd = new Random();
      rnd.nextBytes(plaintext);  // Random input data

      IBlockCipher blockCipher = (IBlockCipher)compCipher.GetInterface(IID_IBlockCipher);

      // Encrypt (the whole buffer)
      byte[] ciphertext = Arrays.copyOf(plaintext, plaintext.length);
      blockCipher.Init();
      blockCipher.Encrypt(ciphertext, 0, ciphertext.length);
      blockCipher.Done();

      // Decrypt back (block by block)
      byte[] decryptedtext = Arrays.copyOf(ciphertext, ciphertext.length);
      blockCipher.Init();
      for (int i = 0; i < N_BLOCKS; i++)
          blockCipher.Decrypt(decryptedtext,
                              i * cipherParams.GetBlockSize(),
                              cipherParams.GetBlockSize());
      blockCipher.Done();

      System.out.println(Arrays.equals(plaintext, decryptedtext)
                          ? "Cipher works correctly"
                          : "Decrypted data don't match!!!");
    }
    catch (Exception ex) {
      System.out.println(ex.toString());
    }
  }
}

Cipher interfaces used: IBlockCipher, IBlockCipherParams.

More about components: Components, Loader class, IKryptelComponent interface.