Sample code for 30+ languages & platforms
Android™

AES-CMAC

See more Encryption Examples

Demonstrates using the AES-CMAC algorithm, which is a keyed hash function similar to HMAC and Poly1305.

Note: Chilkat added AES-CMAC in version 9.5.0.95.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    CkCrypt2 crypt = new CkCrypt2();

    // Set the MAC algorithm to AES-CMAC
    crypt.put_MacAlgorithm("aes-cmac");

    // AES-CMAC always uses a 16-byte (128-bit) MAC key.
    String keyHex = "2b7e151628aed2a6abf7158809cf4f3c";
    success = crypt.SetMacKeyEncoded(keyHex,"hex");

    // Let's compute the AES-CMAC for the test vector at https://www.rfc-editor.org/rfc/rfc4493#appendix-A
    // Here we have 64 bytes in hex representation.
    String messageBytes = "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710";

    CkBinData bd = new CkBinData();
    bd.AppendEncoded(messageBytes,"hex");

    // Compute the AES-CMAC for the bytes contained in bd and return the AES-CMAC in hex representation.
    crypt.put_EncodingMode("hex_lower");
    String cmac = crypt.macBdENC(bd);
    Log.i(TAG, cmac);
    // Output should be: 51f0bebf7e3b9d92fc49741779363cfe

    // Now do the same for a string:
    String plainText = "'Twas brillig, and the slithy toves\nDid gyre and gimble in the wabe:\nAll mimsy were the borogoves,\nAnd the mome raths outgrabe.";
    String encTag = crypt.macStringENC(plainText);
    Log.i(TAG, encTag);

    // Output should be: 4fca1fcbd265048d247f99ab57fa3ceb

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}