Cüzdan kanıt örnekleri
Bu sayfada
Argus Wallet API'ye yapılan her çağrı bir DPoP kanıtı taşır. Para hareket ettiren veya PIN'i doğrulayan çağrı ayrıca bir PIN kanıtı taşır. Kuralları Kanıtlar bölümü anlatır. Bu sayfa o kurallara uyan kodu verir.
Örnekler yalnızca platformun kendi kütüphanelerini kullanır, eklenecek paket yoktur. Her biri iki kanıtı oluşturur ve diğer rehberlerde gösterilen istekleri gönderir.
| Dil | Gereksinim |
|---|---|
| Go | crypto/hpke için Go 1.26 veya üstü. |
| Swift | CryptoKit'in HPKE desteği için iOS 17 veya üstü ya da macOS 14 veya üstü. |
| Kotlin | Android 13 (API 33) veya üstü ya da JDK 11 veya üstü. Android'de HPKE sınıfı yoktur, bu yüzden örnek HPKE adımlarını kendisi yazar. |
Her örnek ne yapar
Üç örneğin de dört parçası aynıdır. Adlar her dilin alışkanlığına uyar.
DPoP, bir isteğin kanıtını oluşturur.htm, sorgusuzhtu,iat, yeni birjtive sunucunonce'unu imzalar. İstek bir erişim belirteci taşıyorsaathekler.SealPIN, PIN'i PIN kanıtı bölümünde gösterildiği gibi mühürler: temel kipte HPKE, anahtarıninfometni, ilişkili veri yok, şifreli metnin önünde kapsüllenmiş anahtar.Do, isteği gönderir ve her yanıttakiDPoP-Nonce'u saklar. 401use_dpop_noncegelirse kanıtları yeni nonce ile yeniden oluşturur ve isteği aynıIdempotency-Keyile bir kez daha gönderir.Confirm, challenge'ı cihaz anahtarıyla imzalar veconfirmamaçlı bir PIN kanıtı mühürler. Cihaz ve PIN ile onaylayın bölümü bunu ister.
PIN kanıtı, isteğin DPoP kanıtındaki nonce'u içerir. Bu yüzden istek gövdesi, nonce'u alan bir işlevdir ve örnek yeniden denemede onu tekrar çağırır. İlk çağrıda henüz nonce yoktur. Sunucu use_dpop_nonce yanıtlar ve yeniden denemede nonce hazırdır.
Uygulamada cihaz anahtarı Secure Enclave'de veya Android Keystore'da durur. Örnekler anahtarı aynı çağrılarla kullanır, bu yüzden donanım anahtarı da uyar. Bir örneğin ürettiği anahtar yeni bir cihazdır. Her istek iki uygulama başlığını taşır. Sürümü kendi uygulamanızın sürümüne ayarlayın.
Go
İki dosyayı aynı klasöre kaydedin (örneğin client.go ve main.go), sonra bir kez go mod init proofs çalıştırın. İlk dosyada kanıtlar ve istemci vardır. İkincisi cihazı bağlar ve hesapları okur.
package main
import (
"bytes"
"crypto/ecdh"
"crypto/ecdsa"
"crypto/hpke"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"io"
"net/http"
"strings"
"time"
)
var b64 = base64.RawURLEncoding
// Client calls the Wallet API with the device key. Nonce is the DPoP-Nonce of the last answer.
type Client struct {
Base string // for example https://wallet.pf.organizer.tr/w1
Key *ecdsa.PrivateKey
Token string // the access token; empty until a session is open
Nonce string
}
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}
func randomID() string {
b := make([]byte, 16)
rand.Read(b)
return b64.EncodeToString(b)
}
// Sign returns the ES256 signature of data as r followed by s, 32 bytes each.
func (c *Client) Sign(data []byte) []byte {
digest := sha256.Sum256(data)
r, s, err := ecdsa.Sign(rand.Reader, c.Key, digest[:])
if err != nil {
panic(err)
}
out := make([]byte, 64)
r.FillBytes(out[:32])
s.FillBytes(out[32:])
return out
}
// JWK is the public half of the device key.
func (c *Client) JWK() map[string]string {
pub := must(c.Key.PublicKey.Bytes()) // 0x04, x, y
return map[string]string{"kty": "EC", "crv": "P-256", "x": b64.EncodeToString(pub[1:33]), "y": b64.EncodeToString(pub[33:])}
}
// Thumbprint is the RFC 7638 thumbprint of the device key: the device of a PIN proof before the device has an id.
func (c *Client) Thumbprint() string {
j := c.JWK()
sum := sha256.Sum256([]byte(`{"crv":"P-256","kty":"EC","x":"` + j["x"] + `","y":"` + j["y"] + `"}`))
return b64.EncodeToString(sum[:])
}
// DPoP builds the proof of one request. url is the full URL; the query is left out.
func (c *Client) DPoP(method, url string) string {
claims := map[string]any{
"jti": randomID(), "htm": method, "htu": strings.SplitN(url, "?", 2)[0],
"iat": time.Now().Unix(), "nonce": c.Nonce,
}
if c.Token != "" { // only a request that carries an access token
sum := sha256.Sum256([]byte(c.Token))
claims["ath"] = b64.EncodeToString(sum[:])
}
header := map[string]any{"typ": "dpop+jwt", "alg": "ES256", "jwk": c.JWK()}
input := b64.EncodeToString(must(json.Marshal(header))) + "." + b64.EncodeToString(must(json.Marshal(claims)))
return input + "." + b64.EncodeToString(c.Sign([]byte(input)))
}
// Do sends one request. body gets the nonce that the request's DPoP proof names, so that a PIN proof inside the body
// names the same one. A use_dpop_nonce answer is retried once, with the nonce it carries and the same Idempotency-Key.
func (c *Client) Do(method, path string, body func(nonce string) (any, error)) (int, map[string]any, error) {
idempotencyKey := randomID()
for attempt := 0; ; attempt++ {
var payload io.Reader
if body != nil {
v, err := body(c.Nonce)
if err != nil {
return 0, nil, err
}
payload = bytes.NewReader(must(json.Marshal(v)))
}
req := must(http.NewRequest(method, c.Base+path, payload))
req.Header.Set("Argus-App-Platform", "ios")
req.Header.Set("Argus-App-Version", "2.4.0")
req.Header.Set("DPoP", c.DPoP(method, c.Base+path))
if c.Token != "" {
req.Header.Set("Authorization", "DPoP "+c.Token)
}
if method == http.MethodPost {
req.Header.Set("Idempotency-Key", idempotencyKey)
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return 0, nil, err
}
raw, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if n := resp.Header.Get("DPoP-Nonce"); n != "" {
c.Nonce = n // every answer carries one: keep the latest
}
var out map[string]any
json.Unmarshal(raw, &out)
if e, _ := out["error"].(map[string]any); resp.StatusCode == 401 && e["code"] == "use_dpop_nonce" && attempt == 0 {
continue
}
return resp.StatusCode, out, nil
}
}
// PinKey is an entry of GET /pin_keys.
type PinKey struct {
ID string `json:"id"`
Key string `json:"key"`
Current bool `json:"current"`
Info string `json:"info"`
}
// SealPIN builds the pin_proof object. device is the wdv_ id, or the thumbprint for purpose "enrol". digest is the
// challenge's digest for purpose "confirm" and empty for the others.
func SealPIN(k PinKey, pin, purpose, device, digest, nonce string) (map[string]string, error) {
public, err := b64.DecodeString(k.Key)
if err != nil {
return nil, err
}
recipient, err := hpke.DHKEM(ecdh.X25519()).NewPublicKey(public)
if err != nil {
return nil, err
}
plain := must(json.Marshal(map[string]string{"pin": pin, "purpose": purpose, "device": device, "digest": digest, "nonce": nonce}))
// Seal returns the encapsulated key followed by the ciphertext. There is no associated data.
sealed, err := hpke.Seal(recipient, hpke.HKDFSHA256(), hpke.AES256GCM(), []byte(k.Info), plain)
if err != nil {
return nil, err
}
return map[string]string{"key_id": k.ID, "ciphertext": b64.EncodeToString(sealed)}, nil
}
// Confirm confirms a draft, for example at /transfers/{id}/confirm. challenge is the draft's challenge object.
func (c *Client) Confirm(path string, challenge map[string]any, pin, device string, key PinKey) (int, map[string]any, error) {
canonical, _ := challenge["canonical"].(string)
digest, _ := challenge["digest"].(string)
version, _ := challenge["draft_version"].(float64)
signature := b64.EncodeToString(c.Sign([]byte(canonical))) // the bytes exactly as they arrived
return c.Do("POST", path, func(nonce string) (any, error) {
proof, err := SealPIN(key, pin, "confirm", device, digest, nonce)
return map[string]any{"challenge_version": int(version), "signature": signature, "pin_proof": proof}, err
})
}
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/json"
"fmt"
"os"
)
// Run it with ARGUS_WALLET_BASE (for example https://wallet.pf.organizer.tr/w1), ARGUS_ENROLMENT (the handle of a sign-up
// whose code you verified) and ARGUS_PIN (six digits). It binds a new device and reads the accounts.
func main() {
// In the app the key lives in the keystore. A new key here is a new device.
c := &Client{Base: os.Getenv("ARGUS_WALLET_BASE"), Key: must(ecdsa.GenerateKey(elliptic.P256(), rand.Reader))}
// The first call also gives the first nonce. GET /pin_keys ignores the DPoP proof.
var keys struct{ Data []PinKey }
_, answer, _ := c.Do("GET", "/pin_keys", nil)
json.Unmarshal(must(json.Marshal(answer)), &keys)
var pinKey PinKey
for _, k := range keys.Data {
if k.Current {
pinKey = k
}
}
// Bind the device. There is no access token yet, so the DPoP proof has no ath.
status, session, _ := c.Do("POST", "/devices/bind", func(nonce string) (any, error) {
proof, err := SealPIN(pinKey, os.Getenv("ARGUS_PIN"), "enrol", c.Thumbprint(), "", nonce)
return map[string]any{
"enrolment": os.Getenv("ARGUS_ENROLMENT"), "device_name": "Test phone",
"device_key": c.JWK(), "attestation": "sandbox", "pin_proof": proof,
}, err
})
if status != 201 {
panic(fmt.Sprint("bind: ", status, session))
}
c.Token = session["access_token"].(string)
// Every later proof carries ath.
status, accounts, _ := c.Do("GET", "/accounts", nil)
out, _ := json.MarshalIndent(accounts, "", " ")
fmt.Println(status, string(out))
}
Önce bir test kullanıcısı kaydedin: SMS kodunu gönderin ve Kodu kontrol edin bölümlerindeki gibi. Yanıttaki enrolment değerini saklayın. Sonra programı çalıştırın:
export ARGUS_WALLET_BASE=https://wallet.pf.organizer.tr/w1
export ARGUS_ENROLMENT=p3GuQwVIwZ2exwjtgD-ZpWP2jKcaytgacHAsifeWSII
export ARGUS_PIN=739150
go run .
Yanıt 200'dür ve yeni kullanıcının hesaplarını taşır.
Go ile transferi onaylayın
Üçüncü bir dosya ekleyin: transfer.go. Kimliği doğrulanmış ve gönderilebilir parası olan bir kullanıcı adına para gönderir. sendMoney üç şey alır: GET /accounts yanıtındaki wal_ kimliği, cihazı bağlayan çağrının yanıtı (session) ve main'in okuduğu PIN anahtarı. Hesaplar çağrısından sonra main içinden çağırın.
package main
import (
"fmt"
"os"
)
func sendMoney(c *Client, account string, session map[string]any, pinKey PinKey) {
_, recipient, _ := c.Do("POST", "/recipients/resolve", func(string) (any, error) {
return map[string]any{"phone": "+905550801402"}, nil
})
_, draft, _ := c.Do("POST", "/transfers", func(string) (any, error) {
return map[string]any{
"from_account": account, "recipient": recipient["recipient"], "amount": 2500,
"currency": "TRY", "description": "Kitap bedeli", "purpose": "friend_personal",
}, nil
})
challenge := draft["challenge"].(map[string]any)
status, sent, _ := c.Confirm("/transfers/"+draft["id"].(string)+"/confirm", challenge,
os.Getenv("ARGUS_PIN"), session["device"].(string), pinKey)
fmt.Println(status, sent["status"])
}
Transfer hemen deftere işlenir. Yanıt 200'dür ve status değeri completed olur.
Swift
WalletProofs.swift adıyla kaydedin. Uygulamada key türünü SecureEnclave.P256.Signing.PrivateKey yapın. Örneğin anahtar üzerinde yaptığı iki çağrı (publicKey ve signature(for:)) Secure Enclave anahtarında da aynıdır.
import CryptoKit
import Foundation
func base64URL(_ data: Data) -> String {
data.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
func base64URLDecode(_ text: String) -> Data? {
var s = text.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
s += String(repeating: "=", count: (4 - s.count % 4) % 4)
return Data(base64Encoded: s)
}
func jsonData(_ object: Any) throws -> Data {
try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys, .withoutEscapingSlashes])
}
/// An entry of GET /pin_keys.
struct PinKey: Decodable {
let id: String
let key: String
let current: Bool
let info: String
}
enum ProofError: Error { case badPinKey }
final class WalletClient {
let base: String // for example https://wallet.pf.organizer.tr/w1
let key: P256.Signing.PrivateKey // in the app: a SecureEnclave.P256.Signing.PrivateKey, used the same way
var token: String? // the access token; nil until a session is open
var nonce = "" // the DPoP-Nonce of the last answer
init(base: String, key: P256.Signing.PrivateKey) {
self.base = base
self.key = key
}
/// ES256: r followed by s, 32 bytes each (the raw form, not DER).
func sign(_ data: Data) throws -> Data {
try key.signature(for: data).rawRepresentation
}
/// The public half of the device key.
var jwk: [String: String] {
let xy = key.publicKey.rawRepresentation // x followed by y
return ["kty": "EC", "crv": "P-256", "x": base64URL(xy.prefix(32)), "y": base64URL(xy.suffix(32))]
}
/// RFC 7638 thumbprint: the device of a PIN proof before the device has an id.
var thumbprint: String {
let j = jwk
let canonical = "{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"\(j["x"]!)\",\"y\":\"\(j["y"]!)\"}"
return base64URL(Data(SHA256.hash(data: Data(canonical.utf8))))
}
/// The DPoP proof of one request. The query is left out of htu.
func dpop(method: String, url: URL) throws -> String {
var parts = URLComponents(url: url, resolvingAgainstBaseURL: false)!
parts.query = nil
var claims: [String: Any] = [
"jti": UUID().uuidString.lowercased(), "htm": method, "htu": parts.string!,
"iat": Int(Date().timeIntervalSince1970), "nonce": nonce,
]
if let token { // only a request that carries an access token
claims["ath"] = base64URL(Data(SHA256.hash(data: Data(token.utf8))))
}
let header: [String: Any] = ["typ": "dpop+jwt", "alg": "ES256", "jwk": jwk]
let input = base64URL(try jsonData(header)) + "." + base64URL(try jsonData(claims))
return input + "." + base64URL(try sign(Data(input.utf8)))
}
/// The pin_proof object. device is the wdv_ id, or the thumbprint for purpose "enrol". digest is the challenge's
/// digest for purpose "confirm" and empty for the others.
func sealPIN(_ pin: String, purpose: String, device: String, digest: String = "", nonce: String,
with pinKey: PinKey) throws -> [String: String] {
guard let raw = base64URLDecode(pinKey.key) else { throw ProofError.badPinKey }
let recipient = try Curve25519.KeyAgreement.PublicKey(rawRepresentation: raw)
let plain = try jsonData(["pin": pin, "purpose": purpose, "device": device, "digest": digest, "nonce": nonce])
let suite = HPKE.Ciphersuite(kem: .Curve25519_HKDF_SHA256, kdf: .HKDF_SHA256, aead: .AES_GCM_256)
var sender = try HPKE.Sender(recipientKey: recipient, ciphersuite: suite, info: Data(pinKey.info.utf8))
let sealed = try sender.seal(plain) // no associated data
return ["key_id": pinKey.id, "ciphertext": base64URL(sender.encapsulatedKey + sealed)]
}
/// Sends one request. body gets the nonce that the request's DPoP proof names, so that a PIN proof inside the body
/// names the same one. A use_dpop_nonce answer is retried once, with the nonce it carries and the same
/// Idempotency-Key.
func send(_ method: String, _ path: String,
body: ((String) throws -> [String: Any])? = nil) async throws -> (status: Int, json: [String: Any]) {
let idempotencyKey = UUID().uuidString.lowercased()
var attempt = 0
while true {
var request = URLRequest(url: URL(string: base + path)!)
request.httpMethod = method
request.setValue("ios", forHTTPHeaderField: "Argus-App-Platform")
request.setValue("2.4.0", forHTTPHeaderField: "Argus-App-Version")
request.setValue(try dpop(method: method, url: request.url!), forHTTPHeaderField: "DPoP")
if let token { request.setValue("DPoP " + token, forHTTPHeaderField: "Authorization") }
if let body {
request.httpBody = try jsonData(try body(nonce))
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
if method == "POST" { request.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key") }
let (data, response) = try await URLSession.shared.data(for: request)
let http = response as! HTTPURLResponse
if let latest = http.value(forHTTPHeaderField: "DPoP-Nonce") { nonce = latest } // keep the latest
let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
let code = (json["error"] as? [String: Any])?["code"] as? String
if http.statusCode == 401, code == "use_dpop_nonce", attempt == 0 {
attempt += 1
continue
}
return (http.statusCode, json)
}
}
/// Confirms a draft, for example at /transfers/{id}/confirm. challenge is the draft's challenge object.
func confirm(_ path: String, challenge: [String: Any], pin: String, device: String,
with pinKey: PinKey) async throws -> (status: Int, json: [String: Any]) {
let canonical = challenge["canonical"] as! String
let digest = challenge["digest"] as! String
let signature = base64URL(try sign(Data(canonical.utf8))) // the bytes exactly as they arrived
return try await send("POST", path) { nonce in
[
"challenge_version": challenge["draft_version"]!,
"signature": signature,
"pin_proof": try self.sealPIN(pin, purpose: "confirm", device: device, digest: digest, nonce: nonce, with: pinKey),
]
}
}
}
Bir async işlevden çağırın:
let client = WalletClient(base: "https://wallet.pf.organizer.tr/w1", key: deviceKey)
client.token = accessToken // from the answer of POST /devices/bind
let (status, accounts) = try await client.send("GET", "/accounts")
// Send money. account is the wal_ id of the accounts answer, recipient the wrc_ id of POST /recipients/resolve.
let (_, draft) = try await client.send("POST", "/transfers") { _ in
["from_account": account, "recipient": recipient, "amount": 2500, "currency": "TRY",
"description": "Kitap bedeli", "purpose": "friend_personal"]
}
let challenge = draft["challenge"] as! [String: Any]
let (sentStatus, sent) = try await client.confirm(
"/transfers/\(draft["id"] as! String)/confirm", challenge: challenge, pin: pin, device: deviceID, with: pinKey)
Kotlin
WalletProofs.kt adıyla kaydedin. Android'le gelen org.json'ı kullanır. send ve confirm çağrılarını ana iş parçacığının dışında yapın. Uygulamada deviceKey, Android Keystore'un anahtar çiftidir.
import org.json.JSONObject
import java.math.BigInteger
import java.net.HttpURLConnection
import java.net.URL
import java.security.KeyFactory
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.MessageDigest
import java.security.Signature
import java.security.interfaces.ECPublicKey
import java.security.interfaces.XECPublicKey
import java.security.spec.NamedParameterSpec
import java.security.spec.XECPublicKeySpec
import java.util.Base64
import java.util.UUID
import javax.crypto.Cipher
import javax.crypto.KeyAgreement
import javax.crypto.Mac
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
/** An entry of GET /pin_keys: the current one, with its base64url public key and info string. */
data class PinKey(val id: String, val key: String, val info: String)
private fun b64url(data: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(data)
private fun sha256(data: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(data)
private fun unsigned32(v: BigInteger): ByteArray {
val raw = v.toByteArray().let { if (it.size > 32) it.copyOfRange(it.size - 32, it.size) else it }
return ByteArray(32 - raw.size) + raw
}
/** The JCA and the Android Keystore sign in DER. The wallet wants r followed by s, 32 bytes each. */
private fun derToRaw(der: ByteArray): ByteArray {
var i = if ((der[1].toInt() and 0x80) != 0) 3 else 2 // skip the SEQUENCE header
val parts = ArrayList<ByteArray>()
repeat(2) {
val length = der[i + 1].toInt() and 0xff // der[i] is the INTEGER tag
parts.add(unsigned32(BigInteger(1, der.copyOfRange(i + 2, i + 2 + length))))
i += 2 + length
}
return parts[0] + parts[1]
}
// HPKE (RFC 9180) base mode with DHKEM(X25519, HKDF-SHA256), HKDF-SHA256 and AES-256-GCM, from the JDK's primitives.
// X25519 in KeyAgreement needs Android 13 (API 33) or a JDK 11 or later.
private val kemSuite = "KEM".toByteArray() + byteArrayOf(0x00, 0x20)
private val suite = "HPKE".toByteArray() + byteArrayOf(0x00, 0x20, 0x00, 0x01, 0x00, 0x02)
private fun hmac(key: ByteArray, data: ByteArray): ByteArray =
Mac.getInstance("HmacSHA256").run {
init(SecretKeySpec(key, "HmacSHA256"))
doFinal(data)
}
private fun labeledExtract(id: ByteArray, salt: ByteArray, label: String, ikm: ByteArray): ByteArray =
hmac(if (salt.isEmpty()) ByteArray(32) else salt, "HPKE-v1".toByteArray() + id + label.toByteArray() + ikm)
// One HMAC block is enough: every length used here is at most 32.
private fun labeledExpand(id: ByteArray, prk: ByteArray, label: String, info: ByteArray, length: Int): ByteArray {
val labeled = byteArrayOf((length shr 8).toByte(), length.toByte()) + "HPKE-v1".toByteArray() + id + label.toByteArray() + info
return hmac(prk, labeled + byteArrayOf(1)).copyOf(length)
}
/** The encapsulated key followed by the ciphertext. There is no associated data. */
private fun hpkeSeal(publicKey: ByteArray, info: ByteArray, plaintext: ByteArray): ByteArray {
val recipient = KeyFactory.getInstance("XDH")
.generatePublic(XECPublicKeySpec(NamedParameterSpec.X25519, BigInteger(1, publicKey.reversedArray())))
val ephemeral = KeyPairGenerator.getInstance("X25519").generateKeyPair()
val enc = unsigned32((ephemeral.public as XECPublicKey).u).reversedArray()
val dh = KeyAgreement.getInstance("X25519").run {
init(ephemeral.private)
doPhase(recipient, true)
generateSecret()
}
val sharedSecret = labeledExpand(
kemSuite, labeledExtract(kemSuite, ByteArray(0), "eae_prk", dh), "shared_secret", enc + publicKey, 32,
)
val context = byteArrayOf(0) + // base mode
labeledExtract(suite, ByteArray(0), "psk_id_hash", ByteArray(0)) +
labeledExtract(suite, ByteArray(0), "info_hash", info)
val secret = labeledExtract(suite, sharedSecret, "secret", ByteArray(0))
val key = labeledExpand(suite, secret, "key", context, 32)
val baseNonce = labeledExpand(suite, secret, "base_nonce", context, 12)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, baseNonce))
return enc + cipher.doFinal(plaintext)
}
class WalletClient(
private val base: String, // for example https://wallet.pf.organizer.tr/w1
private val deviceKey: KeyPair, // in the app: the EC P-256 key pair of the Android Keystore
) {
var token: String? = null // the access token; null until a session is open
var nonce = "" // the DPoP-Nonce of the last answer
/** ES256: r followed by s, 32 bytes each. */
fun sign(data: ByteArray): ByteArray {
val signature = Signature.getInstance("SHA256withECDSA")
signature.initSign(deviceKey.private)
signature.update(data)
return derToRaw(signature.sign())
}
/** The public half of the device key. */
fun jwk(): Map<String, String> {
val point = (deviceKey.public as ECPublicKey).w
return mapOf("kty" to "EC", "crv" to "P-256", "x" to b64url(unsigned32(point.affineX)), "y" to b64url(unsigned32(point.affineY)))
}
/** RFC 7638 thumbprint: the device of a PIN proof before the device has an id. */
fun thumbprint(): String {
val j = jwk()
return b64url(sha256("""{"crv":"P-256","kty":"EC","x":"${j["x"]}","y":"${j["y"]}"}""".toByteArray()))
}
/** The DPoP proof of one request. The query is left out of htu. */
fun dpop(method: String, url: String): String {
val claims = JSONObject(
mapOf("jti" to UUID.randomUUID().toString(), "htm" to method, "htu" to url.substringBefore('?'), "iat" to System.currentTimeMillis() / 1000, "nonce" to nonce),
)
token?.let { claims.put("ath", b64url(sha256(it.toByteArray()))) } // only a request that carries an access token
val header = JSONObject(mapOf("typ" to "dpop+jwt", "alg" to "ES256", "jwk" to JSONObject(jwk())))
val input = b64url(header.toString().toByteArray()) + "." + b64url(claims.toString().toByteArray())
return input + "." + b64url(sign(input.toByteArray()))
}
/**
* The pin_proof object. device is the wdv_ id, or the thumbprint for purpose "enrol". digest is the challenge's
* digest for purpose "confirm" and empty for the others.
*/
fun sealPin(pinKey: PinKey, pin: String, purpose: String, device: String, digest: String, nonce: String): JSONObject {
val plain = JSONObject(mapOf("pin" to pin, "purpose" to purpose, "device" to device, "digest" to digest, "nonce" to nonce))
val sealed = hpkeSeal(Base64.getUrlDecoder().decode(pinKey.key), pinKey.info.toByteArray(), plain.toString().toByteArray())
return JSONObject(mapOf("key_id" to pinKey.id, "ciphertext" to b64url(sealed)))
}
/**
* Sends one request. body gets the nonce that the request's DPoP proof names, so that a PIN proof inside the body
* names the same one. A use_dpop_nonce answer is retried once, with the nonce it carries and the same
* Idempotency-Key. Call it off the main thread.
*/
fun send(method: String, path: String, body: ((String) -> JSONObject)? = null): Pair<Int, JSONObject> {
val idempotencyKey = UUID.randomUUID().toString()
var attempt = 0
while (true) {
val connection = URL(base + path).openConnection() as HttpURLConnection
connection.requestMethod = method
connection.setRequestProperty("Argus-App-Platform", "android")
connection.setRequestProperty("Argus-App-Version", "2.4.0")
connection.setRequestProperty("DPoP", dpop(method, base + path))
token?.let { connection.setRequestProperty("Authorization", "DPoP $it") }
if (method == "POST") connection.setRequestProperty("Idempotency-Key", idempotencyKey)
if (body != null) {
connection.setRequestProperty("Content-Type", "application/json")
connection.doOutput = true
connection.outputStream.use { it.write(body(nonce).toString().toByteArray()) }
}
val status = connection.responseCode
connection.getHeaderField("DPoP-Nonce")?.let { nonce = it } // every answer carries one: keep the latest
val text = (if (status < 400) connection.inputStream else connection.errorStream).bufferedReader().use { it.readText() }
val json = JSONObject(text)
if (status == 401 && json.optJSONObject("error")?.optString("code") == "use_dpop_nonce" && attempt == 0) {
attempt++
continue
}
return status to json
}
}
/** Confirms a draft, for example at /transfers/{id}/confirm. challenge is the draft's challenge object. */
fun confirm(path: String, challenge: JSONObject, pin: String, device: String, pinKey: PinKey): Pair<Int, JSONObject> {
val signature = b64url(sign(challenge.getString("canonical").toByteArray())) // the bytes exactly as they arrived
return send("POST", path) { latest ->
JSONObject()
.put("challenge_version", challenge.getInt("draft_version"))
.put("signature", signature)
.put("pin_proof", sealPin(pinKey, pin, "confirm", device, challenge.getString("digest"), latest))
}
}
}
Şöyle kullanın:
val client = WalletClient("https://wallet.pf.organizer.tr/w1", deviceKeyPair)
client.token = accessToken // from the answer of POST /devices/bind
val (status, accounts) = client.send("GET", "/accounts")
// Send money. account is the wal_ id of the accounts answer, recipient the wrc_ id of POST /recipients/resolve.
val (_, draft) = client.send("POST", "/transfers") {
JSONObject(mapOf("from_account" to account, "recipient" to recipient, "amount" to 2500, "currency" to "TRY", "description" to "Kitap bedeli", "purpose" to "friend_personal"))
}
val (sentStatus, sent) = client.confirm("/transfers/${draft.getString("id")}/confirm", draft.getJSONObject("challenge"), pin, deviceId, pinKey)
Kanıt reddedilirse
| Kod | Durum | Ne kontrol edilir |
|---|---|---|
use_dpop_nonce |
401 | Örnekler bir kez yeniden dener. İki kez gelirse nonce son yanıttakiyle aynı değildir. |
dpop_invalid |
401 | htu sorgusuz tam URL'dir. iat sunucu saatinden en fazla 60 saniye farklıdır. ath yalnızca istek belirteç taşıyorsa vardır. İmza DER değil, 64 bayttır. |
parameter_invalid, param değeri pin_proof |
400 | Kanıt başka bir nonce, amaç veya cihaz için mühürlenmiş ya da nonce'u daha önce kullanılmış. İsteğin DPoP kanıtındaki nonce ile yeniden mühürleyin ve yeni bir Idempotency-Key gönderin. |
pin_key_unknown |
400 | Anahtar artık yayında değil. GET /pin_keys'i yeniden okuyun. |
signature_invalid |
400 | Challenge geldiği gibi imzalanmadı. canonical baytlarını ayrıştırmadan imzalayın. |
Sonraki adım: Tüm rotaları ve alanları Argus Wallet API referansında bulun.