Skip to content

Android API: pairing, signed requests, sealed answers

Version 0.2, 2026-10-05
Audience The developer of the Android app
Reference code src/BankSync.DeviceAuth (shared, no dependencies) and samples/BankSync.PhoneSimulator

The server exposes a small read-only API. A phone proves who it is with a key that never leaves its secure hardware, and the server's answers are encrypted to the phone, so a proxy such as Cloudflare carries ciphertext. There is no password, token or cookie on the phone to steal.

If the app is written in C# for .NET Android, reference BankSync.DeviceAuth and use BankSyncPhoneClient: it does everything in this document. The app only supplies two small classes, shown under "Keys". Other languages implement the formats below; DeviceJwt.cs and SealedResponse.cs are short and are the reference.

1. The picture

sequenceDiagram
    autonumber
    participant O as Owner (web pages, home network)
    participant P as Phone app
    participant S as Server (through Cloudflare)

    Note over P: Once: make two keys in the Keystore<br/>signing key (ES256) and encryption key (ECDH P-256)
    O->>S: Phones -> Pair a phone
    S-->>O: code 95VR-8FMF (10 minutes, once)
    O->>P: types the code
    P->>S: POST /api/pair/claim { code, deviceName, algorithm, publicKey, encryptionKey }
    S-->>P: { deviceId, audience, serverTime, keyFingerprint, sealedResponses }
    Note over P: keeps deviceId + audience (not secret)

    loop every request
        P->>P: new token: iss, aud, iat, exp, jti, htm, htu, qh, signed with the Keystore key
        P->>S: GET /api/transactions?take=50   Authorization: Device <token>
        S->>S: check signature, request binding, time, single use
        S-->>P: 200 application/vnd.banksync.sealed+json  { v, epk, nonce, ct }
        P->>P: open with the Keystore encryption key and the token's jti
    end

2. Keys

Make two EC P-256 keys in the Android Keystore, with StrongBox where the phone has it. Neither can be exported.

Key Purpose Notes
Signing key PURPOSE_SIGN, digest SHA-256, curve secp256r1 Algorithm name on the wire: ES256
Encryption key PURPOSE_AGREE_KEY, curve secp256r1 Android 12 (API 31) and later. Before that the Keystore cannot do ECDH; see the note below.

Optionally require the user's biometrics or screen lock to use the signing key (setUserAuthenticationRequired(true) with a validity window of a few minutes). Then a thief with the unlocked-but-idle phone still needs the owner.

Older Android

Without PURPOSE_AGREE_KEY the encryption key would have to be a software key held in the app, wrapped by a Keystore AES key. That works, but it is weaker, because the key exists in the app's memory while in use. Setting the app's minimum to Android 12 avoids the question. This is a design choice that should be made before the app is written, not after.

The server wants both public keys as base64 of the X.509 SubjectPublicKeyInfo, which is what Java's PublicKey.getEncoded() returns.

The two classes the app supplies

IJwtSigner and IKeyAgreement (in BankSync.DeviceAuth). Sketch for .NET Android; it has not been compiled or run on a device:

using Java.Security;
using Javax.Crypto;
using BankSync.DeviceAuth;

sealed class KeystoreSigner(IPrivateKey key) : IJwtSigner
{
    public string Algorithm => "ES256";

    public byte[] Sign(byte[] data)
    {
        var signature = Signature.GetInstance("SHA256withECDSA")!;
        signature.InitSign(key);
        signature.Update(data);
        var der = signature.Sign()!;                 // Java gives DER; JWS wants r || s
        return JwsSignature.DerToP1363(der);         // 64 bytes
    }
}

sealed class KeystoreAgreement(IPrivateKey key) : IKeyAgreement
{
    public byte[] DeriveSharedSecret(byte[] serverEphemeralSpki)
    {
        var peer = KeyFactory.GetInstance("EC")!.GeneratePublic(new Java.Security.Spec.X509EncodedKeySpec(serverEphemeralSpki))!;
        var agreement = KeyAgreement.GetInstance("ECDH")!;
        agreement.Init(key);
        agreement.DoPhase(peer, true);
        return agreement.GenerateSecret()!;          // the raw X coordinate, 32 bytes: what the server expects
    }
}

Key generation (also a sketch): KeyPairGenerator.GetInstance(KeyProperties.KeyAlgorithmEc, "AndroidKeyStore") with KeyGenParameterSpec.Builder(alias, KeyStorePurpose.Sign) for the signing key and KeyGenParameterSpec.Builder(alias, KeyStorePurpose.AgreeKey) for the encryption key, both with SetAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1")), SetDigests("SHA-256") on the signing key.

3. Pairing

POST /api/pair/claim, no authentication, JSON. Rate limited to 10 requests a minute per client.

{
  "code": "95VR-8FMF",
  "deviceName": "Pixel 8",
  "algorithm": "ES256",
  "publicKey": "<base64 SPKI of the signing key>",
  "encryptionKey": "<base64 SPKI of the encryption key>"
}

Success, 200:

{
  "deviceId": "911bec54374f47269e4dbac288bb1804",
  "audience": "banksync",
  "serverTime": 1790000000,
  "keyFingerprint": "a3f1-90bc-22de-7788",
  "sealedResponses": true
}

Store deviceId and audience in app-private storage; they are not secret. Show keyFingerprint to the user and compare it with DevicePublicKey.Fingerprint(signingSpki) computed on the phone: they must match the line on the server's Phones page.

Failure, 400: { "error": "…", "failure": "WrongCode" } (also NoOffer, Expired). The messages are written to be shown to the person. Five wrong codes destroy the code; ask the owner for a new one.

4. Signing a request

Header: Authorization: Device <token>. The token is a JWT:

header   { "alg": "ES256", "typ": "JWT", "kid": "<deviceId>" }
payload  { "iss": "<deviceId>", "aud": "<audience>", "iat": 1790000000, "exp": 1790000060,
           "jti": "<16 random bytes, base64url>", "htm": "GET", "htu": "/api/transactions",
           "qh": "<base64url SHA-256 of the raw query string without '?', or of the empty string>" }
signature  ES256, 64 bytes (r || s), base64url

Rules:

  • A new token for every request, including retries. A token works once; resending one is a replay and is refused.
  • htu is the request path only, exactly as sent, with no host and no query. qh is the SHA-256 of the raw query string exactly as sent, without the leading ?.
  • exp - iat must be at most 120 seconds; 60 is the default. The phone's clock may be up to 60 seconds off.
  • Use DeviceJwt.Create(...) rather than writing this by hand.

5. Endpoints

All read-only apart from refresh. Answers are sealed (section 6). Enums are words.

Method and path Purpose
GET /api/status Consent state, days left, whether renewal is needed, last sync
GET /api/accounts The accounts with masked IBAN, name, date range
GET /api/accounts/{id}/balances Latest balances. Nordea: ITBD booked, ITAV available, VALU value-dated
GET /api/transactions accountId, from, to (yyyy-MM-dd), text, skip, take (default 50, at most 1000)
GET /api/summary Monthly income and spend; accountId, months
POST /api/refresh Fetch now. Uses the phone's own address, which the bank does not count against the daily limit

Real examples (sandbox data, as opened on the phone):

{ "state": "None", "validUntil": null, "daysLeft": null, "needsRenewal": true,
  "createdAt": null, "accountCount": 0, "lastSuccessfulSync": null, "backfillComplete": false, "lastError": null }
{ "items": [], "total": 0, "skip": 0, "take": 5 }
{ "transactionsNew": 0, "transactionsUpdated": 0, "ok": true }

ConsentState is one of None, Pending, Active, Expiring, Expired, Revoked. When needsRenewal is true the app should offer a way to open the server's address in the browser so the owner can renew with MitID.

6. Opening an answer

A 200 from these endpoints has Content-Type: application/vnd.banksync.sealed+json:

{ "v": 1, "epk": "<base64 SPKI of a fresh server key>", "nonce": "<base64, 12 bytes>", "ct": "<base64, ciphertext then 16-byte tag>" }

To open it:

  1. secret = ECDH of your encryption private key and epk (the raw X coordinate).
  2. key = HKDF-SHA256, input secret, 32 bytes out, salt = SHA-256(epk bytes ‖ your encryption public key SPKI bytes), info = UTF-8 banksync/sealed/v1|<deviceId>|<jti of the request token>.
  3. AES-256-GCM decrypt ct with key and nonce, authenticated data = UTF-8 banksync/v1|<jti>|200.

The result is the JSON. A failure to decrypt means the answer is not for this request or was altered: discard it. SealedResponse.Open(...) does all of it; BankSyncPhoneClient calls it for you, using the jti of the token it just sent.

Error answers (4xx, 5xx) are plain JSON with an error text and carry no data.

7. Errors

Status Meaning App behaviour
401, header WWW-Authenticate: Device Not accepted: revoked, locked out, unknown device, token problem, or clock more than a minute off Do not retry in a loop. Compare the response Date header with the phone's clock; if it differs by over a minute, tell the user to fix the time. Otherwise treat as revoked and offer to pair again.
403 with an error Paired without an encryption key Pair again
429 Too many pairing attempts, or too many failed requests from this address Wait; for failed requests, 15 minutes
400 Bad parameters Fix the request
5xx Server or bank trouble Retry later with a new token

Five forged or unknown tokens from one address lock that address out for 15 minutes, so a bug that signs requests wrongly will lock the phone out. Test with the simulator first.

8. Behind Cloudflare Access

If the owner set up the optional Access gate, every request to the hostname needs two more headers, from a service token created in Cloudflare:

CF-Access-Client-Id: <id>
CF-Access-Client-Secret: <secret>

BankSyncPhoneClient takes them as extraHeaders. They go on every request, including pairing. The owner enters them once into the app (or scans a code); store them in the app's encrypted storage, never in the APK or in logs.

9. Rules for the app

  • Keep deviceId, audience and the server address in app-private storage; keep the service-token secret, if any, in EncryptedSharedPreferences or the Keystore.
  • Never log tokens, answers, or the service-token secret.
  • Mark the screens that show balances FLAG_SECURE so they stay out of screenshots and the recents list.
  • Do not cache answers on disk unencrypted. If the app keeps an offline copy, encrypt it with a Keystore key.
  • Query strings are visible to Cloudflare (the answers are not). Keep sensitive text out of searches.
  • Do not pin Cloudflare's certificate: it rotates. The signed requests and sealed answers do not depend on the TLS layer for secrecy, which is the point.

10. Trying it before the app exists

samples/BankSync.PhoneSimulator does all of the above with software keys, so you can prove a deployment, including the tunnel and the Access gate, before any Android code exists:

dotnet run --project samples/BankSync.PhoneSimulator -- pair https://bank.example.com 95VR-8FMF "My PC"
dotnet run --project samples/BankSync.PhoneSimulator -- status
dotnet run --project samples/BankSync.PhoneSimulator -- get /api/transactions take=5
dotnet run --project samples/BankSync.PhoneSimulator -- refresh

It keeps its private keys in a plain file, for testing only. The real app keeps them in the Keystore.