German English
Radio

Encryption and Decryption of data with AES-CBC

An encrypted data transmission in wireless communication is of particular importance. Encryption prevents from unauthorized listening on the radio channel. A good encryption method is the Advanced Encryption Standard (AES) which is freely available and may be used without licensing fees. The transceiver on radio module Preon32 contains a hardware AES implementation for fast AES encryption and decryption.
This examples shows how to encrypt and decrypt 4 blocks of data, 16 bytes each, using the AES-CBC method. The advantage of the CBC method is, that the data blocks are chained such way that a block is dependent on all prior blocks. This method offers better security than ECB one.
/*
 * Copyright (c) 2011., Virtenio GmbH
 * All rights reserved.
 */

package com.virtenio.webdemo;

import com.virtenio.drivers.ieee_802_15_4.AT86RF231;
import com.virtenio.drivers.ieee_802_15_4.NativeAT86RF231;

import java.io.IOException;

public class RadioAESCBC {

    public static void main(String[] args) throws IOException {

        NativeAT86RF231 t = NativeAT86RF231.getInstance(0);
        t.open();
        t.setState(AT86RF231.STATE_TRX_OFF);

        byte[] key0 = {
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
        };
        byte[] data = new byte[]{
                // 64 bytes
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
        };
        byte[] iv = new byte[]{
                // input vector
                15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
        };
        byte[] decryptRoundKey = new byte[16];

        // AES-CBC Encryption/Decryption with byte-array
        {
            // dummy data to get first round key
            t.aesSetKey(key0);
            t.aesEncryptCBC(new byte[16], 0,
                            new byte[16], 0, 16, iv);
            t.aesGetKey(decryptRoundKey);

            byte[] data_encrypted = new byte[data.length];

            // encrypt data 64 byte
            t.aesSetKey(key0);
            t.aesEncryptCBC(data, 0,
                            data_encrypted, 0, data.length, iv);
            t.aesGetKey(decryptRoundKey);

            byte[] data_decrypted = new byte[data.length];

            // decrypt data 64 byte
            t.aesSetKey(decryptRoundKey);
            t.aesDecryptCBC(data_encrypted, 0,
                            data_decrypted, 0, data_encrypted.length, iv);
        }
        t.close();
    }
}