Sample code for 30+ languages & platforms
Android™

Get ECC Public Key in JWK Format (JSON Web Key)

See more ECC Examples

Demonstrates how to get an ECC public key in JWK (JSON Web Key) format.

Note: This example requires Chilkat v9.5.0.66 or later.

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;

    // Note: This example requires Chilkat v9.5.0.66 or later.

    // Load a PEM file into memory.
    CkStringBuilder sbPem = new CkStringBuilder();
    success = sbPem.LoadFile("qa_data/pem/ecc_public.pem","utf-8");
    if (success != true) {
        Log.i(TAG, "Failed to load PEM file.");
        return;
        }

    // Load the PEM into a public key object.
    CkPublicKey pubKey = new CkPublicKey();
    success = pubKey.LoadFromString(sbPem.getAsString());
    if (success != true) {
        Log.i(TAG, pubKey.lastErrorText());
        return;
        }

    // Get the public key in JWK format:
    String jwk = pubKey.getJwk();

    // The GetJwk method will return the JWK in the most compact JSON format possible,
    // as a single line with no extra whitespace.  To get a more human-readable JWK (for this example),
    // load into a Chilkat JSON object and emit non-compact:

    CkJsonObject json = new CkJsonObject();
    json.Load(jwk);
    json.put_EmitCompact(false);
    Log.i(TAG, "ECC Public Key in JWK format:");
    Log.i(TAG, json.emit());

    // Sample output:
    // { 
    //   "kty": "EC",
    //   "crv": "P-256",
    //   "x": "oBUyo8CQAFPeYPvv78ylh5MwFZjTCLQeb042TjiMJxE",
    //   "y": "vvQyxZkUjJQUPU_0bCy3Pj5qQdfu8jwEfqEeYGZ95CU"
    // }
    // 
    // Additional information can be added like this:
    json.AppendString("use","enc");
    json.AppendString("kid","123ABC");

    // Now examine the JSON:
    Log.i(TAG, json.emit());

    // { 
    //   "kty": "EC",
    //   "crv": "P-256",
    //   "x": "oBUyo8CQAFPeYPvv78ylh5MwFZjTCLQeb042TjiMJxE",
    //   "y": "vvQyxZkUjJQUPU_0bCy3Pj5qQdfu8jwEfqEeYGZ95CU",
    //   "use": "enc",
    //   "kid": "123ABC"
    // }

  }

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