Sample code for 30+ languages & platforms
Android™

Validate a JWS Signature

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.Validate, which validates exactly one signature, identified by a zero-based index, using the key configured at that same index.

Background. Validate returns 1 when the signature or MAC is cryptographically valid, 0 when it is not, or a negative value on error. The verifying key must be provided before validating.

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;

    CkJws jws = new CkJws();

    //  Load the JWS compact serialization.
    String jwsCompact = "eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>";
    success = jws.LoadJws(jwsCompact);
    if (success == false) {
        Log.i(TAG, jws.lastErrorText());
        return;
        }

    //  Provide the key for signature 0 (here an HMAC key).
    String base64Key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=";
    success = jws.SetMacKey(0,base64Key,"base64");
    if (success == false) {
        Log.i(TAG, jws.lastErrorText());
        return;
        }

    //  Validate the signature identified by the zero-based index, using the key configured at that index.
    //  Validate returns 1 when the signature or MAC is cryptographically valid, 0 when it is not, or a
    //  negative value on error.
    int v = jws.Validate(0);
    if (v < 0) {
        Log.i(TAG, jws.lastErrorText());
        return;
        }

    if (v != 1) {
        Log.i(TAG, "The signature is not valid.");
        return;
        }

    Log.i(TAG, "The signature is valid.");

  }

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