Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
71 commits
Select commit Hold shift + click to select a range
9ffc3ee
feat(localproof): add signed device observation API
PDFly-source Dec 1, 2026
cde4b59
feat(localproof): wire authenticated device routes
PDFly-source Dec 1, 2026
c3e7ed9
feat(localproof): add idempotent device observation schema
PDFly-source Dec 1, 2026
6ce41b0
feat(localproof): wire schema and deployment checks
PDFly-source Dec 1, 2026
3c3ff5b
feat(localproof): wire schema and deployment checks
PDFly-source Dec 1, 2026
0a4cde6
feat(localproof): wire schema and deployment checks
PDFly-source Dec 1, 2026
1be7834
feat(localproof): wire schema and deployment checks
PDFly-source Dec 1, 2026
8b7e5e3
test(localproof): cover route isolation and invalid payloads
PDFly-source Dec 1, 2026
359a7df
ci(localproof): validate module and schema during release
PDFly-source Dec 1, 2026
6cb4f2c
ci(localproof): syntax check device routes in staging
PDFly-source Dec 1, 2026
1fb6fa4
ci(localproof): run worker tests for LocalProof branch
PDFly-source Dec 1, 2026
72c48a9
fix(localproof): enforce active device at observation commit
PDFly-source Dec 1, 2026
f66d484
feat(localproof-android): add opt-in Keystore companion
PDFly-source Dec 1, 2026
77a43e2
feat(localproof-android): add opt-in Keystore companion
PDFly-source Dec 1, 2026
ac69fa1
feat(localproof-android): add opt-in Keystore companion
PDFly-source Dec 1, 2026
31bd983
feat(localproof-android): add opt-in Keystore companion
PDFly-source Dec 1, 2026
ac24ec2
feat(localproof-android): add opt-in Keystore companion
PDFly-source Dec 1, 2026
443800d
feat(localproof-android): add opt-in Keystore companion
PDFly-source Dec 1, 2026
3d27532
feat(localproof-android): add opt-in Keystore companion
PDFly-source Dec 1, 2026
3627863
feat(localproof-android): add opt-in Keystore companion
PDFly-source Dec 1, 2026
02f6346
feat(localproof-android): add opt-in Keystore companion
PDFly-source Dec 1, 2026
efe93fc
feat(localproof-android): add opt-in Keystore companion
PDFly-source Dec 1, 2026
f7865f2
fix(localproof): permit secure device API CORS headers
PDFly-source Dec 1, 2026
34f1561
security(localproof): encrypt saved API key with Android Keystore
PDFly-source Dec 1, 2026
4da0f8a
security(localproof): protect merchant API key and require HTTPS
PDFly-source Dec 1, 2026
ce4a40f
ci(localproof): build Android debug APK on pull requests
PDFly-source Dec 1, 2026
1313dbe
ci(localproof): run regression tests on feature branch pushes
PDFly-source Dec 1, 2026
14205ae
ci(localproof): enable push validation for LocalProof branch
PDFly-source Dec 1, 2026
513c793
ci(localproof): enable feature branch push checks
PDFly-source Dec 1, 2026
8107c9c
fix(ci): correct LocalProof migration workflow YAML
PDFly-source Dec 1, 2026
52e0936
fix(ci): correct LocalProof migration workflow YAML
PDFly-source Dec 1, 2026
378dd1a
fix(localproof): allow CORS preflight for device revocation and signe…
PDFly-source Dec 1, 2026
fa537ae
fix(localproof): validate package metadata and revocation race
PDFly-source Dec 1, 2026
ec02a15
privacy(localproof): require explicit notification observation consent
PDFly-source Dec 1, 2026
7be7e36
privacy(localproof): enforce consent before notification parsing
PDFly-source Dec 1, 2026
a40f0c4
privacy(localproof): stop local capture before device revocation
PDFly-source Dec 1, 2026
4a697df
feat(localproof): add merchant device and observation panel
PDFly-source Dec 1, 2026
2384101
docs(localproof): update implementation and release status
PDFly-source Dec 1, 2026
dacb60a
docs(localproof): update README implementation status
PDFly-source Dec 1, 2026
96f9f00
test(localproof): prove signed observations cannot mutate payment state
PDFly-source Dec 1, 2026
6a58227
fix(android): validate HTTPS before network actions
PDFly-source Dec 1, 2026
1c6a22e
security(android): enforce HTTPS for LocalProof API requests
PDFly-source Dec 1, 2026
dc5e0c5
fix(ci): install supported Android SDK packages directly
PDFly-source Dec 1, 2026
2f540ac
ci(localproof): add Android APK build to PR regression workflow
PDFly-source Dec 1, 2026
ee1fc54
feat(localproof): record parsed credit or debit direction
PDFly-source Dec 1, 2026
51cfc88
feat(localproof): retain parsed transaction direction as untrusted me…
PDFly-source Dec 1, 2026
ab4b84f
feat(localproof): include direction in fresh LocalProof schema
PDFly-source Dec 1, 2026
b182f00
chore(db): align LocalProof schema snapshot with direction field
PDFly-source Dec 1, 2026
365ef59
ci(db): apply LocalProof direction migration in production release
PDFly-source Dec 1, 2026
9f0ba43
ci(db): apply LocalProof direction migration in staging
PDFly-source Dec 1, 2026
1ba24e6
feat(android): label notification observation direction
PDFly-source Dec 1, 2026
f1f2019
feat(localproof): show parsed direction in merchant observations
PDFly-source Dec 1, 2026
8377f9b
test(localproof): include direction in signed observation contract
PDFly-source Dec 1, 2026
9d0de9e
fix(ci): resolve Android sdkmanager from installed SDK root
PDFly-source Dec 1, 2026
edbaf0d
fix(ci): resolve SDK manager in standalone Android workflow
PDFly-source Dec 1, 2026
4713fcf
fix(ci): resolve Android SDK manager from runner installation
PDFly-source Dec 1, 2026
cc8d186
fix(dashboard): include LocalProof in merchant navigation tracking
PDFly-source Dec 1, 2026
26321e8
ci(localproof): use shared worker PR workflow for APK build
PDFly-source Dec 1, 2026
d87886f
fix(android): clarify DER signature length bitmask
PDFly-source Dec 1, 2026
8dc7029
ci(pages): align LocalProof documentation validation
PDFly-source Dec 1, 2026
4886b54
docs(localproof): document direction metadata and offline queue limit…
PDFly-source Dec 1, 2026
186f7ab
ci(db): verify LocalProof direction schema before production Worker r…
PDFly-source Dec 1, 2026
a89de13
ci(db): verify LocalProof direction schema in staging
PDFly-source Dec 1, 2026
dedf6cc
test(localproof): cover forged signatures and merchant isolation
PDFly-source Dec 1, 2026
9a6a7d5
ci(db): validate LocalProof D1 migrations in worker PR checks
PDFly-source Dec 1, 2026
8eb37be
fix(db): keep direction addition isolated in migration 0029
PDFly-source Dec 1, 2026
a1f0d30
fix(release): make LocalProof direction migration rerun-safe
PDFly-source Dec 1, 2026
cbe054b
fix(staging): make LocalProof direction migration rerun-safe
PDFly-source Dec 1, 2026
4d88f20
fix(localproof): support safe same-merchant device re-enrollment
PDFly-source Dec 1, 2026
512c53c
fix(ci): validate fresh LocalProof schema without reapplying additive…
PDFly-source Dec 1, 2026
b09ab15
fix(ci): apply additive LocalProof direction migration in local schem…
PDFly-source Dec 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/deploy-pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ jobs:
grep -q "paynex-api.sbn50088.workers.dev/dashboard" docs/dashboard/index.html
grep -q "Test API health" docs/docs/index.html
grep -q "menuToggle" docs/index.html
grep -q "no Android companion APK" docs/LOCALPROOF-STATUS.md
grep -q "Android companion source" docs/LOCALPROOF-STATUS.md
node scripts/validate-pages.mjs
- uses: actions/configure-pages@v5
with:
Expand Down
17 changes: 16 additions & 1 deletion .github/workflows/deploy-production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ jobs:
run: |
node --check src/index.js
node --check src/auth.js
node --check src/localproof.js
- name: Run complete Worker regression suite
run: npm test
- name: Verify required production secrets exist (names only)
Expand Down Expand Up @@ -184,11 +185,25 @@ jobs:
run: npx wrangler d1 execute paynex-db --remote --file=./migrations/0027_backfill_merchant_mode_onboarding.sql
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- name: Apply LocalProof device observation schema (idempotent)
run: npx wrangler d1 execute paynex-db --remote --file=./migrations/0028_localproof_device_observation.sql
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- name: Apply LocalProof observation direction migration (skip if already present)
run: |
if npx wrangler d1 execute paynex-db --remote --command "SELECT direction FROM localproof_observations LIMIT 0" --json >/dev/null 2>&1; then
echo "LocalProof direction column already exists."
else
npx wrangler d1 execute paynex-db --remote --file=./migrations/0029_localproof_observation_direction.sql
fi
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- name: Verify production schema before Worker rollout
run: |
set -euo pipefail
npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('gateway_applications','account','orders','payment_attempts','payment_routing_rules','reconciliation_batches','saas_invoices','ledger_accounts','ledger_journals','ledger_entries','merchant_review_records') ORDER BY name" --json
npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('gateway_applications','account','orders','payment_attempts','payment_routing_rules','reconciliation_batches','saas_invoices','ledger_accounts','ledger_journals','ledger_entries','merchant_review_records','localproof_devices','localproof_nonces','localproof_observations','localproof_audit_events') ORDER BY name" --json
npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM sqlite_master WHERE type='table' AND name='merchant_payment_confirmations'" --json
npx wrangler d1 execute paynex-db --remote --command "SELECT direction FROM localproof_observations LIMIT 0" --json
npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('merchant_mode_onboarding','merchant_kyc_documents','merchant_limited_access','merchant_limited_workspace','merchant_sandbox_checkouts') ORDER BY name" --json
npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM sqlite_master WHERE type='index' AND name IN ('idx_merchant_payment_confirmations_order','idx_merchant_payment_confirmations_reference') ORDER BY name" --json
npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM pragma_table_info('merchants') WHERE name IN ('upi_account_type','upi_ownership_verified') ORDER BY name" --json
Expand Down
16 changes: 16 additions & 0 deletions .github/workflows/deploy-worker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jobs:
- name: Check Worker and onboarding script syntax
run: |
node --check worker/src/index.js
node --check worker/src/localproof.js
node --check scripts/provision-merchant.mjs
node --check scripts/approve-merchant.mjs
- name: Install Worker dependencies
Expand Down Expand Up @@ -94,6 +95,21 @@ jobs:
run: npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0027_backfill_merchant_mode_onboarding.sql --env staging
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- name: Apply LocalProof device observation schema (idempotent)
working-directory: worker
run: npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0028_localproof_device_observation.sql --env staging
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- name: Apply LocalProof observation direction migration (skip if already present)
working-directory: worker
run: |
if npx wrangler d1 execute paynex-v2-staging --remote --command "SELECT direction FROM localproof_observations LIMIT 0" --env staging --json >/dev/null 2>&1; then
echo "LocalProof direction column already exists."
else
npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0029_localproof_observation_direction.sql --env staging
fi
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- name: Verify merchant attestation staging schema
working-directory: worker
run: |
Expand Down
39 changes: 37 additions & 2 deletions .github/workflows/worker-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: PAYNEX worker tests

on:
pull_request:
branches: [main, feat/hybrid-settlement-commission-ready-20261129, feat/phase3-unified-checkout-byok-20261129, integration/paynex-v2-auth-safe-20261130, feat/oxigendev-limited-merchant-access]
branches: [main, feat/hybrid-settlement-commission-ready-20261129, feat/phase3-unified-checkout-byok-20261129, integration/paynex-v2-auth-safe-20261130, feat/oxigendev-limited-merchant-access, feat/localproof-secure-device-observation]
push:
branches: [main, feat/provider-contract-hardening, feat/better-auth-google-email, feat/phase3-unified-checkout-byok-20261129, integration/paynex-v2-auth-safe-20261130, feat/oxigendev-limited-merchant-access]
branches: [main, feat/provider-contract-hardening, feat/better-auth-google-email, feat/phase3-unified-checkout-byok-20261129, integration/paynex-v2-auth-safe-20261130, feat/oxigendev-limited-merchant-access, feat/localproof-secure-device-observation]

jobs:
worker-tests:
Expand All @@ -23,5 +23,40 @@ jobs:
run: |
node --check src/index.js
node --check src/auth.js
node --check src/localproof.js
- name: Validate LocalProof D1 migrations locally
run: |
npx wrangler d1 execute paynex-db --local --file=./migrations/0028_localproof_device_observation.sql
npx wrangler d1 execute paynex-db --local --file=./migrations/0029_localproof_observation_direction.sql
npx wrangler d1 execute paynex-db --local --command "SELECT direction FROM localproof_observations LIMIT 0"
- name: Run worker tests
run: npm test

android-debug-apk:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "17"
- name: Install Android SDK packages
run: |
SDK_ROOT="${ANDROID_HOME:-$ANDROID_SDK_ROOT}"
SDKMANAGER="$(find "$SDK_ROOT/cmdline-tools" -type f -name sdkmanager | sort | tail -n 1)"
test -x "$SDKMANAGER"
yes | "$SDKMANAGER" --licenses >/dev/null
"$SDKMANAGER" "platforms;android-35" "build-tools;35.0.0" "platform-tools"
- name: Build LocalProof debug APK
uses: gradle/gradle-build-action@v3
with:
gradle-version: "8.9"
build-root-directory: android
arguments: --no-daemon :app:assembleDebug
- name: Upload debug APK
uses: actions/upload-artifact@v4
with:
name: paynex-localproof-debug-apk
path: android/app/build/outputs/apk/debug/app-debug.apk
if-no-files-found: error
retention-days: 14
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,4 @@ Then configure the Razorpay webhook secret. Until the migration and secret are c

## LocalProof Android companion — current status

The LocalProof notification-listener companion is **not implemented and no APK is available yet**. The implementation scope and safety gates are tracked in [docs/LOCALPROOF-STATUS.md](docs/LOCALPROOF-STATUS.md). A future Android notification observation may assist reconciliation only; it must never mark a transaction paid or activate a subscription. Only an authorised provider's authenticated server-side confirmation can do that.
LocalProof backend and initial Android companion source are implemented on the draft feature PR. The Android app uses an Android Keystore P-256 signing key, encrypted API-key storage, explicit notification-listener consent and local-only parsing of allowlisted UPI app notifications. The Worker stores signed device observations as **unverified reconciliation hints only**. No notification can mark a transaction paid, post a verified ledger entry or trigger fulfilment. The CI debug-APK build and physical Android 16 device validation must pass before rollout. See [docs/LOCALPROOF-STATUS.md](docs/LOCALPROOF-STATUS.md) for current release gates.
31 changes: 31 additions & 0 deletions android/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# PAYNEX LocalProof Android companion (early access)

This is an opt-in notification observation companion, not a payment app or bank integration.

## Build
- Android Studio with JDK 17 and Android SDK 35
- Open the `android/` folder and build the `app` debug variant.
- The CI workflow builds a debug APK and stores it as a GitHub Actions artifact.

## Pairing
1. Sign in to the PAYNEX merchant dashboard and create/use an active merchant API key.
2. Enter the Worker URL and API key in the app.
3. Add only the exact package names of UPI apps you choose to observe.
4. Tap Enroll this device.
5. Tap Enable notification access and explicitly enable PAYNEX LocalProof in Android Settings.
6. Keep the phone unlocked/online when notifications arrive.

The P-256 private key is generated and held by Android Keystore; it is not exported. The server receives only the public key. The app signs timestamp + nonce + exact JSON request bytes.

## Data minimisation
Notification text is processed locally only. The app uploads the source package, parser version, event ID, observation time and optional parsed amount/UTR. Full notification bodies, account numbers, contacts and inbox history are not uploaded. Configure an explicit package allowlist. The app does not read SMS inboxes.

## Limits
- Notification formats vary by UPI app, bank and language; parsing is best-effort and requires real-device testing.
- Notifications may be delayed, absent, duplicated or spoofed.
- A LocalProof observation never marks an order/payment paid, posts a verified ledger journal, activates a subscription, or triggers fulfilment.
- This initial companion does not yet have a durable offline retry queue or in-app observation history.
- Do not use this as a substitute for checking the receiving bank/UPI app.

## Privacy and control
Disable notification access in Android Settings to stop observation. Revoke the device in-app to invalidate its API identity. Clear app data/uninstalling the app removes local settings; server-side device revocation should be done first where possible.
20 changes: 20 additions & 0 deletions android/app/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.paynex.localproof"
compileSdk = 35
defaultConfig {
applicationId = "com.paynex.localproof"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "0.1.0"
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions { jvmTarget = "17" }
}
15 changes: 15 additions & 0 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application android:allowBackup="false" android:label="PAYNEX LocalProof" android:theme="@android:style/Theme.Material.Light.NoActionBar">
<activity android:name=".MainActivity" android:exported="true">
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>
</activity>
<service
android:name=".LocalProofNotificationListener"
android:label="PAYNEX LocalProof notification observation"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
android:exported="true">
<intent-filter><action android:name="android.service.notification.NotificationListenerService" /></intent-filter>
</service>
</application>
</manifest>
57 changes: 57 additions & 0 deletions android/app/src/main/java/com/paynex/localproof/Api.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.paynex.localproof

import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
import java.util.UUID

object Api {
private fun request(base: String, path: String, method: String, apiKey: String, body: String): String {
require(base.startsWith("https://",true)) { "HTTPS Worker URL required" }
val url=URL(base.trimEnd('/')+path)
val connection=(url.openConnection() as HttpURLConnection).apply {
requestMethod=method; connectTimeout=12000; readTimeout=12000
setRequestProperty("Accept","application/json")
if(apiKey.isNotBlank()) setRequestProperty("Authorization","Bearer $apiKey")
if(method!="GET") { doOutput=true; setRequestProperty("Content-Type","application/json"); outputStream.use { it.write(body.toByteArray()) } }
}
val code=connection.responseCode
val stream=if(code in 200..299) connection.inputStream else connection.errorStream
val result=stream?.bufferedReader()?.use { it.readText() } ?: ""
connection.disconnect()
if(code !in 200..299) throw IllegalStateException("PAYNEX API HTTP $code: $result")
return result
}
fun enroll(base:String,apiKey:String):String {
val body=JSONObject().put("label",android.os.Build.MANUFACTURER+" "+android.os.Build.MODEL)
.put("public_key_jwk",DeviceCrypto.publicJwk()).toString()
return request(base,"/api/v1/localproof/devices","POST",apiKey,body)
}
fun send(base:String,deviceId:String,event:JSONObject) {
require(base.startsWith("https://",true)) { "HTTPS Worker URL required" }
val raw=event.toString()
val timestamp=System.currentTimeMillis().toString()
val nonce=Base64Url.randomNonce()
val signature=DeviceCrypto.sign("$timestamp.$nonce.$raw")
val connection=(URL(base.trimEnd('/')+"/api/v1/localproof/events").openConnection() as HttpURLConnection).apply {
requestMethod="POST"; connectTimeout=12000; readTimeout=12000; doOutput=true
setRequestProperty("Content-Type","application/json")
setRequestProperty("X-LocalProof-Device",deviceId)
setRequestProperty("X-LocalProof-Timestamp",timestamp)
setRequestProperty("X-LocalProof-Nonce",nonce)
setRequestProperty("X-LocalProof-Signature",signature)
outputStream.use { it.write(raw.toByteArray()) }
}
val code=connection.responseCode
val stream=if(code in 200..299) connection.inputStream else connection.errorStream
val result=stream?.bufferedReader()?.use { it.readText() } ?: ""
connection.disconnect()
if(code !in 200..299) throw IllegalStateException("Observation rejected: HTTP $code $result")
}
}
object Base64Url {
fun randomNonce():String {
val bytes=ByteArray(24); java.security.SecureRandom().nextBytes(bytes)
return android.util.Base64.encodeToString(bytes,android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING)
}
}
60 changes: 60 additions & 0 deletions android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.paynex.localproof

import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import org.json.JSONObject
import java.math.BigInteger
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.Signature
import java.security.interfaces.ECPublicKey

object DeviceCrypto {
private const val ALIAS = "paynex-localproof-device-p256"
private fun b64(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING)
private fun coordinate(value: BigInteger): ByteArray {
val raw = value.toByteArray()
val unsigned = if (raw.size == 33 && raw[0] == 0.toByte()) raw.copyOfRange(1, raw.size) else raw
return ByteArray(32).also { unsigned.copyInto(it, 32 - unsigned.size) }
}
fun publicJwk(): JSONObject {
val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val existing = ks.getKey(ALIAS, null)
if (existing == null) {
val generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore")
generator.initialize(KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY)
.setAlgorithmParameterSpec(java.security.spec.ECGenParameterSpec("secp256r1"))
.setDigests(KeyProperties.DIGEST_SHA256)
.setUserAuthenticationRequired(false)
.build())
generator.generateKeyPair()
}
val publicKey = ks.getCertificate(ALIAS).publicKey as ECPublicKey
return JSONObject().put("kty","EC").put("crv","P-256")
.put("x",b64(coordinate(publicKey.w.affineX))).put("y",b64(coordinate(publicKey.w.affineY))).put("ext",true)
}
private fun derToRaw(der: ByteArray): ByteArray {
var i = 0
require(der[i++].toInt() == 0x30)
var sequenceLength = der[i++].toInt() and 0xff
if ((sequenceLength and 0x80) != 0) { val n=sequenceLength and 0x7f; sequenceLength=0; repeat(n) { sequenceLength=(sequenceLength shl 8) or (der[i++].toInt() and 0xff) } }
require(der[i++].toInt() == 0x02)
val rLen=der[i++].toInt() and 0xff; val r=der.copyOfRange(i,i+rLen); i+=rLen
require(der[i++].toInt() == 0x02)
val sLen=der[i++].toInt() and 0xff; val s=der.copyOfRange(i,i+sLen)
fun fixed(v: ByteArray): ByteArray {
val clean=if(v.size>32 && v[0]==0.toByte()) v.copyOfRange(1,v.size) else v
require(clean.size<=32)
return ByteArray(32).also { clean.copyInto(it,32-clean.size) }
}
return fixed(r)+fixed(s)
}
fun sign(message: String): String {
val ks=KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val privateKey=ks.getKey(ALIAS,null) as java.security.PrivateKey
val signer=Signature.getInstance("SHA256withECDSA")
signer.initSign(privateKey); signer.update(message.toByteArray(Charsets.UTF_8))
return b64(derToRaw(signer.sign()))
}
}
Loading
Loading