Sample code for 30+ languages & platforms
Java

Validate a JWS with a Public Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetPublicKey, which sets the public key used to validate a signature of a loaded JWS.

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. The public key verifies a signature created with the corresponding private key. Validate returns 1 when valid, 0 when not, or a negative value on error.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    CkJws jws = new CkJws();

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

    //  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 signer's public key and set it for validating signature 0.
    CkPublicKey pubKey = new CkPublicKey();
    success = pubKey.LoadFromFile("qa_data/signer_pubkey.pem");
    if (success == false) {
        System.out.println(pubKey.lastErrorText());
        return;
        }

    success = jws.SetPublicKey(0,pubKey);
    if (success == false) {
        System.out.println(jws.lastErrorText());
        return;
        }

    //  Validate the signature.  Validate returns 1 when valid, 0 when not, or a negative value on error.
    int v = jws.Validate(0);
    if (v < 0) {
        System.out.println(jws.lastErrorText());
        return;
        }

    if (v != 1) {
        System.out.println("The signature is not valid.");
        return;
        }

    System.out.println("The signature is valid.");
  }
}