opensc
NPCI secure-component & UPI Lite / Lite X wallet reimplementation
Loading...
Searching...
No Matches
Using opensc

opensc has three parts:

  • lite/ — the UPI Lite and Lite X wallet, in C.
  • python/ — the same wallet and the signing engine, in Python.
  • secure_component.c — the native signing engine, in C.

Use the C library in an app. Use the Python code as a reference and for tests.

Set up the environment (C)

The wallet runs against an environment that you supply. Build one, then pass its address to every wallet call.

lite_env env = {0};
env.clock = lite_clock_fixed_new(1767225600000LL);
env.signer_upi_cert = cert; // signer-upi.crt bytes
env.signer_upi_cert_len = cert_len;
const lite_crypto * lite_crypto_openssl(void)
Returns the OpenSSL-backed crypto vtable (statically allocated; do not free).
lite_clock * lite_clock_fixed_new(int64_t millis)
Allocates a fixed clock reading millis. Free with lite_clock_fixed_free().
lite_rng * lite_rng_seeded_new(uint64_t seed)
Allocates a deterministic (seeded) RNG. Free with lite_rng_seeded_free().
lite_keystore * lite_keystore_mem_new(void)
Allocates an in-memory software keystore (for tests). Free with lite_keystore_mem_free().
lite_store * lite_store_mem_new(void)
Allocates an in-memory store (for tests). Free with lite_store_mem_free().
Everything the wallet needs, injected so tests can pin the clock, RNG and keys.
Definition env.h:26
lite_store * store
SharedPreferences-shaped persistence.
Definition env.h:29
lite_keystore * keystore
Alias-keyed key storage/signing.
Definition env.h:28
const lite_crypto * crypto
Stateless crypto primitives.
Definition env.h:27
size_t signer_upi_cert_len
Length of signer_upi_cert in bytes.
Definition env.h:33
const uint8_t * signer_upi_cert
PEM/DER of signer-upi.crt, used to verify riskRules.
Definition env.h:32
const lite_clock * clock
Time source.
Definition env.h:30
const lite_rng * rng
Randomness source.
Definition env.h:31

Online UPI Lite (C)

Call the functions in this order:

  1. Build the alias with lite_alias().
  2. Onboard with the first signed state with lite_onboard().
  3. Read the binding with lite_is_bound().
  4. Read the balance with lite_balance().
  5. Sign a payment with lite_spend().
  6. Apply a new signed state with lite_sync().
  7. Remove the device with lite_unbind().
char alias[256];
lite_alias(env.crypto, "DEV123", "9000000000", "ACC789", "UPI", alias, sizeof alias);
lite_onboard(&env, alias, signed_state); // returns LITE_SYNC_OK
lite_is_bound(&env, alias, &bi); // LITE_BIND_YES
lite_balance(&env, alias, &bal); // bal.balance, bal.pending_count
lite_txn txn = {"100.00", "TXN1", "20260101120000", "5001234567",
"merchant@upi", "com.phonepe.app", "9000000000", "DEV123"};
char out[8192];
lite_spend(&env, alias, &txn, 0, out, sizeof out); // 0 = debit, 1 = credit
lite_sync(&env, alias, next_signed_state);
lite_unbind(&env, alias);
long lite_alias(const lite_crypto *c, const char *device_id, const char *mobile, const char *account_ref, const char *service, char *out, size_t cap)
alias = Base64NoWrap(SHA256(deviceId + mobile + accountRef + service)). Returns length or -1.
Result of lite_balance().
Definition wallet.h:36
Result of lite_is_bound().
Definition wallet.h:27
A spend request. All fields are caller-owned strings.
Definition wallet.h:43
int lite_balance(lite_env *env, const char *alias, lite_balance_info *out)
Computes spendable/non-spendable balance and pending count into out. LITE_OK or LITE_ERR.
int lite_unbind(lite_env *env, const char *alias)
Removes the device binding: deletes the alias keys and clears the vault record. LITE_OK.
int lite_spend(lite_env *env, const char *alias, const lite_txn *txn, int is_credit, char *out, size_t cap)
Signs a spend, writing {"riskParams":..,"signature":..} JSON to out. Enforces the PendingTxn gate....
int lite_onboard(lite_env *env, const char *alias, const char *signed_state_json)
Establishes vault + spend key + session key, then applies the first signed state blob....
int lite_is_bound(lite_env *env, const char *alias, lite_bind_info *out)
Reports binding status into out. Returns LITE_BIND_YES or LITE_BIND_NO.
int lite_sync(lite_env *env, const char *alias, const char *signed_state_json)
Applies a signed state blob: verify, require a newer timestamp, replace state, clear PendingTxn....

Call lite_sync() after each payment. Until you do, lite_spend() returns LITE_SPEND_SYNC_REQUIRED.

Offline UPI Lite X (C)

A transfer runs between two devices: the payer (sends money) and the payee (receives money). Each device runs its own purse. Because the devices are offline, your app carries these messages between them over any channel (QR code, NFC, Bluetooth):

Both devices run the setup and identity steps. Values named their_* arrive from the other device.

Setup and identity (each device):

  1. Start your purse with litex_purse_start().
  2. Make your challenge with litex_get_purse_info(). Send it to the other device.
  3. Sign your identity with litex_assert_identity(), using the challenge you received. Send the result.
  4. Verify the identity you received with litex_verify_identity().
litex_purse_start(&me, &env, "PAYER", 500.0);
char my_challenge[32];
litex_get_purse_info(&me, 500.0, my_challenge, sizeof my_challenge); // send to the other device
litex_identity my_id = {"P", "LITE", "INR", "IN", "PREPAID", NULL};
char my_doc[1024];
litex_assert_identity(&me, &my_id, their_challenge, my_doc, sizeof my_doc); // send my_doc
litex_verify_identity(&me, their_doc, my_challenge);
int litex_assert_identity(litex_purse *p, const litex_identity *id, const char *remote_challenge, char *out_json, size_t cap)
Asserts this purse's identity, signing the fields + remote_challenge; writes an identity doc....
long litex_get_purse_info(litex_purse *p, double balance, char *challenge_out, size_t cap)
Bootstrap: generate the LOCAC challenge, record balance, arm the purse. Writes challenge hex; length ...
int litex_purse_start(litex_purse *p, lite_env *env, const char *alias, double balance)
Initializes a purse with its alias and balance, generating its offline key. 0 on success.
int litex_verify_identity(litex_purse *p, const char *remote_json, const char *our_challenge)
Verifies a remote identity doc against our_challenge; on success adopts its key as remote_pub....
Purse identity fields (assert/verifyIdentity).
Definition litex.h:88
A purse party in the offline transfer handshake.
Definition litex.h:71

Then run the transfer. Both devices use the same agreed transfer x (amount, parties, timestamp). Each device sends the message it produces to the other.

The payer runs:

  1. Call litex_start_debit(x).
  2. Call litex_request_value(their_reqs). Send the TRAS it returns.
  3. Call litex_acknowledge_value(their_reqs, tras, their_acks).

The payee runs:

  1. Call litex_start_credit(x). Send the REQS it returns.
  2. Call litex_transfer_value(my_reqs, their_tras). Send the ACKS it returns.
// This device is the payer. their_reqs and their_acks arrive from the payee.
litex_xfer x = {"P","1","p@upi","Q","1","q@upi","1767225600000","INR","50.00"};
char tras[512];
litex_request_value(&me, their_reqs, tras, sizeof tras); // send tras to the payee
litex_acknowledge_value(&me, their_reqs, tras, their_acks);
int litex_start_debit(litex_purse *p, const litex_xfer *x)
Payer: IDLE -> AWAITING_REQ; declines on insufficient balance (PVR bit 7,8). Fills txn_id....
int litex_acknowledge_value(litex_purse *p, const char *reqs, const char *tras, const char *acks)
Payer: AWAITING_ACK -> IDLE; verifies ACKS over payload+REQS+TRAS. LX_OK/LX_BAD_SIG/LX_ERR_STATE.
int litex_request_value(litex_purse *p, const char *reqs, char *tras_out, size_t cap)
Payer: AWAITING_REQ -> AWAITING_ACK; verifies REQS, signs TRAS into tras_out. LX_OK/LX_BAD_SIG/LX_ERR...
One leg of an offline P2P transfer. Field order matches the CL's generateSignaturePayload.
Definition litex.h:58

Online UPI Lite (Python)

The Python API mirrors the C API.

import opensc_lite as o
pem, sign_state = o.make_test_ca()
env = o.Env(signer_cert_pem=pem)
al = o.alias("DEV123", "9000000000", "ACC789", "UPI")
o.onboard(env, al, sign_state('{"BAL":"5000.00","LTL":"1000.00","ACSTATUS":"A","timestamp":"1000"}'))
o.is_bound(env, al)
o.balance(env, al)
txn = {"amount": "100.00", "txn_id": "TXN1", "ts": "20260101120000",
"payer_lite_acc": "5001234567", "payee_addr": "merchant@upi",
"app_id": "com.phonepe.app", "mobile": "9000000000", "device_id": "DEV123"}
o.spend(env, al, txn, False) # False = debit, True = credit
o.sync(env, al, sign_state('{"BAL":"4900.00","LTL":"1000.00","ACSTATUS":"A","timestamp":"2000"}'))
o.unbind(env, al)

Signing engine (Python)

The signing engine signs and verifies data with per-alias device keys that stay in the keystore. Use it to:

  • sign an offline transaction payload with a device key, named by alias
  • verify a signature you received from another device
  • export a device's public key so another party can verify its signatures

Call the methods in this order:

  1. Create a SecureComponent.
  2. Sign a payload with sign(data, alias, use_ec). It returns the signature bytes.
  3. Export the public key with public_key_der(alias, "EC"). Send it to the verifier.
  4. Verify a received signature with verify(data, signature_base64, public_key_der).
import base64
from secure_component import SecureComponent
sc = SecureComponent()
# Sign a payload with the device's offline key.
sig = sc.sign("5241234567890123|100.00|20260803", "NPCI_UPI_LITE_X", use_ec=True)
# Share this public key with the other party.
pub = sc.public_key_der("NPCI_UPI_LITE_X", "EC")
# Anyone holding the public key can verify the signature.
sc.verify("5241234567890123|100.00|20260803", base64.b64encode(sig).decode(), pub) # True

Pass use_ec=True to sign with ECDSA-SHA256, or use_ec=False for RSA-PSS-SHA512. sign() creates the alias key the first time you use it. verify() checks ECDSA-SHA256 signatures only.

Sign a PIN credential block (OTP or Debit Card)

Setting or changing a UPI PIN produces a credential block that the device signs with its EC key. The verification method decides which credentials the block carries:

  • OTP: an OTP (type OTP, subtype SMS) and the new PIN (type PIN, subtype NMPIN).
  • Debit Card: the ATM PIN (type PIN, subtype ATMPIN) and an OTP, plus the new PIN (subtype NMPIN).

The signing step is identical for both; only the captured credentials differ. Sign the block with the EC key, then attach the signature and the public key:

  1. Build the credential block for the chosen method.
  2. Sign it with sign(block, alias, use_ec=True).
  3. Put the base64 signature in signatureValue and public_key_der(alias, "EC") in keyValue.
import base64, json, time
from secure_component import SecureComponent
sc = SecureComponent()
ALIAS = "NPCI_CL"
def sign_credential(cred_type, cred_blocks):
block = json.dumps({"version": "1.0", "credType": cred_type,
"credBlocks": cred_blocks}, separators=(",", ":"))
sig = sc.sign(block, ALIAS, use_ec=True) # SHA256withECDSA
pub = sc.public_key_der(ALIAS, "EC") # ECwithSPEC256r1
return {
"version": "1.0",
"credType": cred_type,
"credBlocks": cred_blocks,
"trust": {
"owner": "DEVICE-OS",
"keyType": "ECwithSPEC256r1",
"keyValue": base64.b64encode(pub).decode(),
"signatureType": "SHA256withECDSA",
"signatureValue": base64.b64encode(sig).decode(),
"timestamp": str(int(time.time() * 1000)),
},
}
# OTP flow: an OTP plus the new PIN.
otp_doc = sign_credential("OTP|NMPIN", [
{"type": "OTP", "subtype": "SMS"},
{"type": "PIN", "subtype": "NMPIN"},
])
# Debit Card flow: the ATM PIN and an OTP, plus the new PIN.
card_doc = sign_credential("ATMPIN|OTP|NMPIN", [
{"type": "PIN", "subtype": "ATMPIN"},
{"type": "OTP", "subtype": "SMS"},
{"type": "PIN", "subtype": "NMPIN"},
])

The captured values go inside credBlocks as an encrypted PID block with an HMAC. Building that block is a separate step; the signing engine produces only the signatureValue and the keyValue.