# Verify signed responses

This guide adds signature checks to your application. At the end, your application trusts an answer from the License API or the Distribution API only when its signature is valid.

## Before you start

- Your application calls the License API or the Distribution API. See [Add your application](../../licensing/add-your-application/).
- You have a [signing key](../../../concepts/signing-keys/). Copy its key ID and its public key in Base64 from the dashboard.

The examples call `https://license.seatify.dev`. The Distribution API signs its answers in the same way and with the same key. In curl, the keys are the variables `$SEATIFY_PUBLISHABLE_KEY` and `$SEATIFY_SIGNING_KEY_ID`. In the other languages, they are variables of your application.

## Steps

{{% steps %}}

### Embed the public key

Put the key ID and the public key in your application as constants. Never download the key at run time. A person who can change an answer can also change a downloaded key.

You can embed more than one key. Each signature names the key ID of the key that made it. See [Rotate signing keys](../rotate-signing-keys/).

### Send a nonce and the key ID

Send two more headers with each request:

| Header | Value |
| --- | --- |
| `Seatify-Nonce` | A new random value, such as a UUID. Seatify includes the value in the signature. A recorded answer then does not match a new request. |
| `Seatify-Signing-Key` | The key ID of the embedded key. Seatify then signs with this key, also after you rotate keys. |

Keep the nonce until the answer arrives. Your application needs the nonce to verify the answer.

{{< tabs >}}
{{< tab name="curl" >}}
```bash
curl -i https://license.seatify.dev/v1/ping \
  -H "Seatify-Publishable-Key: $SEATIFY_PUBLISHABLE_KEY" \
  -H "Seatify-Signing-Key: $SEATIFY_SIGNING_KEY_ID" \
  -H "Seatify-Nonce: $(uuidgen)"
```
{{< /tab >}}
{{< tab name="Swift" >}}
```swift
let nonce = UUID().uuidString

var request = URLRequest(url: URL(string: "https://license.seatify.dev/v1/ping")!)
request.setValue(publishableKey, forHTTPHeaderField: "Seatify-Publishable-Key")
request.setValue(signingKeyID, forHTTPHeaderField: "Seatify-Signing-Key")
request.setValue(nonce, forHTTPHeaderField: "Seatify-Nonce")

let (data, response) = try await URLSession.shared.data(for: request)
guard let response = response as? HTTPURLResponse else { throw InvalidSignature() }
let body = try verifyResponse(request, nonce: nonce, data: data, response: response)
```
{{< /tab >}}
{{< tab name="C#" >}}
```csharp
var nonce = Guid.NewGuid().ToString();

using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Get, "https://license.seatify.dev/v1/ping");
request.Headers.Add("Seatify-Publishable-Key", publishableKey);
request.Headers.Add("Seatify-Signing-Key", signingKeyId);
request.Headers.Add("Seatify-Nonce", nonce);

using var response = await client.SendAsync(request);
var body = await VerifyResponse(response, nonce);
```
{{< /tab >}}
{{< tab name="Go" >}}
```go
nonce := rand.Text()

req, err := http.NewRequest("GET", "https://license.seatify.dev/v1/ping", nil)
if err != nil {
	return err
}
req.Header.Set("Seatify-Publishable-Key", publishableKey)
req.Header.Set("Seatify-Signing-Key", signingKeyID)
req.Header.Set("Seatify-Nonce", nonce)

res, err := http.DefaultClient.Do(req)
if err != nil {
	return err
}
defer res.Body.Close()

body, err := verifyResponse(res, nonce)
```
{{< /tab >}}
{{< tab name="JavaScript" >}}
```javascript
const nonce = crypto.randomUUID();
const url = "https://license.seatify.dev/v1/ping";

const response = await fetch(url, {
  headers: {
    "Seatify-Publishable-Key": publishableKey,
    "Seatify-Signing-Key": signingKeyId,
    "Seatify-Nonce": nonce,
  },
});
const body = await verifyResponse("GET", url, nonce, response);
```
{{< /tab >}}
{{< /tabs >}}

The answer carries the signature in these headers:

```text
Date: Fri, 25 Sep 2026 21:28:39 GMT
Digest: sha-256=<SHA-256 of the body in Base64>
Seatify-Nonce: dd3c79ab-0581-45b2-aee6-6ddd7cf2095d
Seatify-Signature: keyid="<key id>", algorithm="ed25519", signature="<signature in Base64>", headers="(request-target) host date digest seatify-nonce"

{"message":"pong","api":"license","product":{"id":"<product id>","name":"Atlas Server","code":"ATLAS"}}
```

### Verify the response

Verify every answer before your application uses it. If any check fails, your application must not use the answer.

1. Compute the SHA-256 of the response body, exactly as your application received it. Encode the hash in standard Base64, and put `sha-256=` in front of it. Check that the result equals the `Digest` header.
2. Read the parameters of the `Seatify-Signature` header. Each parameter has the form `name="value"`. A comma and a space separate the parameters.
3. Check that `algorithm` is `ed25519` and that `headers` is `(request-target) host date digest seatify-nonce`.
4. Find the embedded public key that has the key ID in `keyid`. If no embedded key has this ID, the answer is not valid.
5. Build the signing string. See [Signing string](#signing-string).
6. Verify the Ed25519 signature in `signature` over the signing string. The signature is in standard Base64.

Build the signing string from the request that your application sent and from the digest that it computed. Do not copy these values from the answer. Take only the date from the answer.

{{< tabs >}}
{{< tab name="curl" >}}
This step runs inside your application. Choose a language tab to see the code.
{{< /tab >}}
{{< tab name="Swift" >}}
```swift
import CryptoKit
import Foundation

struct InvalidSignature: Error {}

let publicKeys = ["<key id>": "<public key in Base64>"]
let signedHeaders = "(request-target) host date digest seatify-nonce"

func verifyResponse(_ request: URLRequest, nonce: String, data: Data, response: HTTPURLResponse) throws -> Data {
    let digest = "sha-256=" + Data(SHA256.hash(data: data)).base64EncodedString()
    guard response.value(forHTTPHeaderField: "Digest") == digest else { throw InvalidSignature() }

    var parameters: [String: String] = [:]
    for parameter in (response.value(forHTTPHeaderField: "Seatify-Signature") ?? "").components(separatedBy: ", ") {
        guard let separator = parameter.firstIndex(of: "=") else { throw InvalidSignature() }
        let value = parameter[parameter.index(after: separator)...]
        parameters[String(parameter[..<separator])] = value.trimmingCharacters(in: CharacterSet(charactersIn: "\""))
    }

    guard parameters["algorithm"] == "ed25519",
          parameters["headers"] == signedHeaders,
          let encodedKey = parameters["keyid"].flatMap({ publicKeys[$0] }),
          let keyData = Data(base64Encoded: encodedKey),
          let signature = parameters["signature"].flatMap({ Data(base64Encoded: $0) }),
          let url = request.url,
          let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
          let host = url.host,
          let date = response.value(forHTTPHeaderField: "Date")
    else { throw InvalidSignature() }

    var target = components.percentEncodedPath
    if let query = components.percentEncodedQuery {
        target += "?" + query
    }
    let method = (request.httpMethod ?? "GET").lowercased()

    let signingString = [
        "(request-target): \(method) \(target)",
        "host: \(host)",
        "date: \(date)",
        "digest: \(digest)",
        "seatify-nonce: \(nonce)",
    ].joined(separator: "\n")

    let publicKey = try Curve25519.Signing.PublicKey(rawRepresentation: keyData)
    guard publicKey.isValidSignature(signature, for: Data(signingString.utf8)) else { throw InvalidSignature() }

    return data
}
```
{{< /tab >}}
{{< tab name="C#" >}}
```csharp
using System.Security.Cryptography;
using System.Text;
// .NET has no Ed25519, so the signature check uses the NSec.Cryptography package.
using NSec.Cryptography;

var publicKeys = new Dictionary<string, string> { ["<key id>"] = "<public key in Base64>" };
const string signedHeaders = "(request-target) host date digest seatify-nonce";

async Task<byte[]> VerifyResponse(HttpResponseMessage response, string nonce)
{
    var body = await response.Content.ReadAsByteArrayAsync();
    var request = response.RequestMessage!;

    // NonValidated returns each header as it was received.
    string Header(string name) =>
        response.Headers.NonValidated.TryGetValues(name, out var values) ? values.ToString() : "";

    var digest = "sha-256=" + Convert.ToBase64String(SHA256.HashData(body));
    if (Header("Digest") != digest)
        throw new InvalidDataException("The response signature is not valid.");

    var parameters = Header("Seatify-Signature")
        .Split(", ")
        .Select(parameter => parameter.Split('=', 2))
        .Where(pair => pair.Length == 2)
        .ToDictionary(pair => pair[0], pair => pair[1].Trim('"'));

    if (parameters.GetValueOrDefault("algorithm") != "ed25519"
        || parameters.GetValueOrDefault("headers") != signedHeaders
        || !publicKeys.TryGetValue(parameters.GetValueOrDefault("keyid", ""), out var encodedKey)
        || !parameters.TryGetValue("signature", out var signature))
        throw new InvalidDataException("The response signature is not valid.");

    var signingString = string.Join("\n",
        $"(request-target): {request.Method.Method.ToLowerInvariant()} {request.RequestUri!.PathAndQuery}",
        $"host: {request.RequestUri.Host}",
        $"date: {Header("Date")}",
        $"digest: {digest}",
        $"seatify-nonce: {nonce}");

    var publicKey = PublicKey.Import(SignatureAlgorithm.Ed25519, Convert.FromBase64String(encodedKey), KeyBlobFormat.RawPublicKey);
    if (!SignatureAlgorithm.Ed25519.Verify(publicKey, Encoding.UTF8.GetBytes(signingString), Convert.FromBase64String(signature)))
        throw new InvalidDataException("The response signature is not valid.");

    return body;
}
```
{{< /tab >}}
{{< tab name="Go" >}}
```go
var errInvalidSignature = errors.New("the response signature is not valid")

var publicKeys = map[string]string{"<key id>": "<public key in Base64>"}

const signedHeaders = "(request-target) host date digest seatify-nonce"

func verifyResponse(res *http.Response, nonce string) ([]byte, error) {
	body, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	bodyHash := sha256.Sum256(body)
	digest := "sha-256=" + base64.StdEncoding.EncodeToString(bodyHash[:])
	if res.Header.Get("Digest") != digest {
		return nil, errInvalidSignature
	}

	parameters := map[string]string{}
	for _, parameter := range strings.Split(res.Header.Get("Seatify-Signature"), ", ") {
		name, value, found := strings.Cut(parameter, "=")
		if !found {
			return nil, errInvalidSignature
		}
		parameters[name] = strings.Trim(value, `"`)
	}

	encodedKey, found := publicKeys[parameters["keyid"]]
	if parameters["algorithm"] != "ed25519" || parameters["headers"] != signedHeaders || !found {
		return nil, errInvalidSignature
	}

	publicKey, err := base64.StdEncoding.DecodeString(encodedKey)
	if err != nil {
		return nil, errInvalidSignature
	}
	signature, err := base64.StdEncoding.DecodeString(parameters["signature"])
	if err != nil {
		return nil, errInvalidSignature
	}

	signingString := strings.Join([]string{
		"(request-target): " + strings.ToLower(res.Request.Method) + " " + res.Request.URL.RequestURI(),
		"host: " + res.Request.URL.Host,
		"date: " + res.Header.Get("Date"),
		"digest: " + digest,
		"seatify-nonce: " + nonce,
	}, "\n")

	if !ed25519.Verify(publicKey, []byte(signingString), signature) {
		return nil, errInvalidSignature
	}

	return body, nil
}
```
{{< /tab >}}
{{< tab name="JavaScript" >}}
```javascript
const publicKeys = { "<key id>": "<public key in Base64>" };
const signedHeaders = "(request-target) host date digest seatify-nonce";

const encoder = new TextEncoder();
const fromBase64 = (value) => Uint8Array.from(atob(value), (c) => c.charCodeAt(0));
const toBase64 = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes)));

async function verifyResponse(method, url, nonce, response) {
  const body = await response.arrayBuffer();

  const digest = "sha-256=" + toBase64(await crypto.subtle.digest("SHA-256", body));
  if (response.headers.get("Digest") !== digest) {
    throw new Error("The response signature is not valid.");
  }

  const parameters = Object.fromEntries(
    (response.headers.get("Seatify-Signature") ?? "").split(", ").map((parameter) => {
      const separator = parameter.indexOf("=");
      return [parameter.slice(0, separator), parameter.slice(separator + 1).replaceAll('"', "")];
    }),
  );

  const encodedKey = publicKeys[parameters.keyid];
  if (parameters.algorithm !== "ed25519" || parameters.headers !== signedHeaders || !encodedKey) {
    throw new Error("The response signature is not valid.");
  }

  const target = new URL(url);
  const signingString = [
    `(request-target): ${method.toLowerCase()} ${target.pathname}${target.search}`,
    `host: ${target.host}`,
    `date: ${response.headers.get("Date")}`,
    `digest: ${digest}`,
    `seatify-nonce: ${nonce}`,
  ].join("\n");

  const publicKey = await crypto.subtle.importKey("raw", fromBase64(encodedKey), { name: "Ed25519" }, false, ["verify"]);
  const verified = await crypto.subtle.verify(
    { name: "Ed25519" },
    publicKey,
    fromBase64(parameters.signature),
    encoder.encode(signingString),
  );
  if (!verified) {
    throw new Error("The response signature is not valid.");
  }

  return JSON.parse(new TextDecoder().decode(body));
}
```
{{< /tab >}}
{{< /tabs >}}

#### Signing string

The signing string has five lines. A line feed (`\n`) separates the lines. There is no line feed after the last line.

| Line | Value |
| --- | --- |
| `(request-target): ` | The request method in lower case, a space, and the path with its query string. Use the path and the query string exactly as your application sent them. |
| `host: ` | The host that your application called, such as `license.seatify.dev`. |
| `date: ` | The value of the `Date` header of the answer. |
| `digest: ` | The digest that your application computed in check 1. |
| `seatify-nonce: ` | The nonce that your application sent. If your application sent no nonce, the line ends after the colon and the space. |

For the ping request above, the signing string is:

```text
(request-target): get /v1/ping
host: license.seatify.dev
date: Fri, 25 Sep 2026 21:28:39 GMT
digest: sha-256=<SHA-256 of the body in Base64>
seatify-nonce: dd3c79ab-0581-45b2-aee6-6ddd7cf2095d
```

### Use the answer

Parse the body only after the signature is valid. Then decide on `valid` as usual. See [Handle the answer](../../licensing/add-your-application/#handle-the-answer).

{{% /steps %}}

## Check the date

The signature covers the `Date` header, so nobody can change the date of an answer. Your application can compare this date with the clock of the device. Reject an answer whose date is too far from the clock. Choose a limit that fits your application, such as five minutes.

Your application can also store the date of each valid answer as the latest time that it has seen. The [Offline validation](../../offline-use/offline-validation/#check-the-contents) guide uses this time to detect a clock that is set back.

## When verification fails

| Situation | What your application does |
| --- | --- |
| The answer has no `Seatify-Signature` header. | Do not use the answer to allow access. An answer with a status other than 200 is not signed. That includes every 400, 401 and 429. Handle the status as in [Handle the answer](../../licensing/add-your-application/#handle-the-answer). |
| The digest does not match, or the signature does not verify. | Something changed the answer on the way. Handle the answer as if the API could not be reached. |
| No embedded key has the key ID. | Send `Seatify-Signing-Key` with each request. Without it, Seatify signs with the active key, and the active key changes when you rotate keys. |

A refusal with `valid` set to `false` is signed too. Your application can trust an `expired` answer as much as a valid one.

Some answers of the Distribution API are never signed, such as the download redirects. See [Signed data](../../../concepts/signing-keys/#signed-data).

If the License API cannot be reached, your application can use its license file. See [Offline validation](../../offline-use/offline-validation/).

## Next steps

- [Rotate signing keys](../rotate-signing-keys/)
- [Offline validation](../../offline-use/offline-validation/)
- [Signing keys](../../../concepts/signing-keys/)
- [Ping](../../../license-api/ping/)

