Keys¶
A Nostr account is identified by a public key. Whoever holds the matching private key can sign for that account, so your app's first decision is where to keep that key: locally, in a browser extension, or with a remote signer.
For a local account, load an existing key from hex or nsec text. Public keys have their own hex and npub forms:
NostrPrivateKey secret = NostrPrivateKey.fromBech32(userSuppliedNsec);
NostrKeyPair keys = new NostrKeyPair(secret);
NostrPublicKey identity = keys.getPublicKey();
String npub = identity.asBech32();
To create a new account, use new NostrKeyPair(). Keep that identity between launches if the user expects to return to the same account.
Clear key material from memory
You can optionally call close() on a private key or key pair to erase its internal private-key bytes immediately. The closed key can no longer be used.
Store a private key with a passphrase¶
Before saving a key, encrypt it as an ncryptsec string. This is the NIP-49 format; recovering the key requires the passphrase:
String encrypted = secret.asNcryptsec(passphrase).await();
NostrPrivateKey restored = NostrPrivateKey.fromNcryptsec(encrypted, passphrase).await();
Key derivation takes time by design, which is why these calls are asynchronous. Save the encrypted string in protected application storage and ask the user for their passphrase when needed.
If you use a browser or remote signer, the private key can stay outside your application entirely.