Sample code for 30+ languages & platforms
Android™

Load and Validate a JWS from a StringBuilder

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.LoadJwsSb, which loads a JWS from a StringBuilder (here read from a file). The example then supplies the MAC key and validates the signature.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. Validate returns 1 when the signature or MAC is cryptographically valid, 0 when it is not, or a negative value on error.

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

    //  The file path is relative to the application's current working directory.  An absolute path may
    //  also be used.  Supply the path appropriate to your own environment.

    //  Load the JWS text from a file into a StringBuilder.
    CkStringBuilder sbJws = new CkStringBuilder();
    boolean bLoaded = sbJws.LoadFile("qa_data/message.jws","utf-8");
    if (bLoaded != true) {
        Log.i(TAG, "Failed to load the JWS file.");
        return;
        }

    //  Load the JWS from the StringBuilder.
    success = jws.LoadJwsSb(sbJws);
    if (success == false) {
        Log.i(TAG, jws.lastErrorText());
        return;
        }

    String base64Key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=";
    success = jws.SetMacKey(0,base64Key,"base64");
    if (success == false) {
        Log.i(TAG, jws.lastErrorText());
        return;
        }

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