Sample code for 30+ languages & platforms
Android™

Example: Crypt2.RandomizeIV method

Demonstrates using a random initialization vector for AES GCM encryption.

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();

    crypt.put_CryptAlgorithm("aes");
    crypt.put_CipherMode("gcm");
    crypt.put_KeyLength(256);

    String K = "000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F";
    String AAD = "feedfacedeadbeeffeedfacedeadbeefabaddad2";
    String PT = "This is the text to be AES-GCM encrypted.";

    //  Generate a random IV.
    crypt.RandomizeIV();
    String IV = crypt.getEncodedIV("hex");

    crypt.SetEncodedKey(K,"hex");

    success = crypt.SetEncodedAad(AAD,"hex");

    //  Return the encrypted bytes as base64
    crypt.put_EncodingMode("base64");
    crypt.put_Charset("utf-8");
    String cipherText = crypt.encryptStringENC(PT);
    if (crypt.get_LastMethodSuccess() != true) {
        Log.i(TAG, crypt.lastErrorText());
        return;
        }

    //  Get the GCM authenticated tag computed when encrypting.
    String authTag = crypt.getEncodedAuthTag("base64");

    Log.i(TAG, "Cipher Text: " + cipherText);
    Log.i(TAG, "Auth Tag: " + authTag);

    //  Let's send the IV, CipherText, and AuthTag to the decrypting party.
    //  We'll send them concatenated like this: [IV || Ciphertext || AuthTag]
    //  In base64 format.
    CkBinData bdEncrypted = new CkBinData();
    bdEncrypted.AppendEncoded(IV,"hex");
    bdEncrypted.AppendEncoded(cipherText,"base64");
    bdEncrypted.AppendEncoded(authTag,"base64");

    String concatenatedGcmOutput = bdEncrypted.getEncoded("base64");
    Log.i(TAG, "Concatenated GCM Output: " + concatenatedGcmOutput);

    //  Sample output so far:

    //  -------------------------------------------------------------------------------------
    //  Now let's GCM decrypt...
    //  -------------------------------------------------------------------------------------

    CkCrypt2 decrypt = new CkCrypt2();

    //  The values shared and agreed upon by both sides beforehand are: algorithm, cipher mode, secret key, and AAD.
    //  Sometimes the IV can be a value already known and agreed upon, but in this case the encryptor sends the IV to the decryptor.
    decrypt.put_CryptAlgorithm("aes");
    decrypt.put_CipherMode("gcm");
    decrypt.put_KeyLength(256);
    decrypt.SetEncodedKey(K,"hex");
    decrypt.SetEncodedAad(AAD,"hex");

    CkBinData bdFromEncryptor = new CkBinData();
    bdFromEncryptor.AppendEncoded(concatenatedGcmOutput,"base64");

    int sz = bdFromEncryptor.get_NumBytes();

    //  Extract the parts.
    String extractedIV = bdFromEncryptor.getEncodedChunk(0,16,"hex");
    String extractedCipherText = bdFromEncryptor.getEncodedChunk(16,sz - 32,"base64");
    String expectedAuthTag = bdFromEncryptor.getEncodedChunk(sz - 16,16,"base64");

    //  Before GCM decrypting, we must set the authenticated tag to the value that is expected.
    //  The decryption will fail if the resulting authenticated tag is not equal to the expected result.
    success = decrypt.SetEncodedAuthTag(expectedAuthTag,"base64");

    //  Also set the IV.
    decrypt.SetEncodedIV(extractedIV,"hex");

    //  Decrypt..
    decrypt.put_EncodingMode("base64");
    decrypt.put_Charset("utf-8");
    String decryptedText = decrypt.decryptStringENC(extractedCipherText);
    if (decrypt.get_LastMethodSuccess() != true) {
        //  Failed.  The resultant authenticated tag did not equal the expected authentication tag.
        Log.i(TAG, decrypt.lastErrorText());
        return;
        }

    Log.i(TAG, "Decrypted: " + decryptedText);

  }

  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."
  }
}