Sample code for 30+ languages & platforms
Android™

Encrypt a JWE with a Password (PBES2)

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPassword, which sets the PBES2 password for a recipient. The example uses PBES2-HS256+A128KW key management with AES-128-GCM content encryption.

Background. PBES2 derives a key-wrapping key from a password using a salt and iteration count, allowing password-based JWE encryption. The password should come from a secure source.

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;

    CkJwe jwe = new CkJwe();

    //  Protected header: PBES2 password-based key management with AES-128-GCM content encryption.
    CkJsonObject header = new CkJsonObject();
    header.UpdateString("alg","PBES2-HS256+A128KW");
    header.UpdateString("enc","A128GCM");
    success = jwe.SetProtectedHeader(header);
    if (success == false) {
        Log.i(TAG, jwe.lastErrorText());
        return;
        }

    //  Set the PBES2 password for recipient 0.  The password should come from a secure source rather than
    //  being hard-coded.
    String password = "myPassword";
    success = jwe.SetPassword(0,password);
    if (success == false) {
        Log.i(TAG, jwe.lastErrorText());
        return;
        }

    String jweCompact = jwe.encrypt("This is the secret content.","utf-8");
    if (jwe.get_LastMethodSuccess() == false) {
        Log.i(TAG, jwe.lastErrorText());
        return;
        }

    Log.i(TAG, jweCompact);

  }

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