Sample code for 30+ languages & platforms
Java

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 Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Jws;

public class ChilkatExample {

    public static void main(String[] args) {
        Jws jws = new Jws();

        // Load the JWS compact serialization.
        String jwsCompact = "eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>";
        try {
            jws.loadJws(jwsCompact);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Provide the key for signature 0 (here an HMAC key).
        String base64Key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=";
        try {
            jws.setMacKey(0, base64Key, "base64");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            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) {
            System.out.println(jws.getLastErrorText());
            return;
        }

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

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