Sample code for 30+ languages & platforms
Java

Sign a JWS with an HMAC Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetMacKey, which sets the symmetric MAC key for a signature. The key bytes are supplied in a named encoding such as hex or base64.

Background. HMAC-based JWS (for example HS256) authenticates the payload with a shared symmetric key that both signer and verifier possess.

Chilkat Java Downloads

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

public class ChilkatExample {

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

        // Protected header specifying HMAC-SHA256.
        JsonObject header = new JsonObject();
        header.updateString("alg", "HS256");
        try {
            jws.setProtectedHeader(0, header);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        boolean bIncludeBom = false;
        try {
            jws.setPayload("This is the content to sign.", "utf-8", bIncludeBom);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Set the symmetric MAC key for signature 0.  The key bytes are provided in the named encoding (here
        // base64).  In production, obtain the key from a secure source rather than hard-coding it.
        String base64Key = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=";
        String jwsCompact;
        try {
            jws.setMacKey(0, base64Key, "base64");

            jwsCompact = jws.createJws();
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        System.out.println(jwsCompact);
    }
}