Which algorithm(s) do we use to generate private public keys on the NOSTR and how are they converted to nsec/npub form? Any references will be helpful. #asknostr

Reply to this note

Please Login to reply.

Discussion

🫡

The secret key is generated by a strong random source, sometimes augmented by the additional use of a CSPRNG like ChaCha - which is basically a cryptographic hash function, this CSPRNG is used by the Linux kernel and others in addition to random input from other sources, to provide a reasonably high volume of random bits for security purposes.

The public key is derived from this private key via the use of scalar math with Elliptic Curve Digital Signature Algorithm methods (ECDSA) and the secp256k1 elliptic curve group, which is a bunch of deterministically generated prime numbers (chosen by satoshi because of its deterministic generation method, unlike many other EC groups which are a little massaged).

The public key from this is 512 bytes long, made of two coordinates each 256 bits long, and normally is "compressed" to 257 bits, as due to the symmetry of elliptic curves, only the sign (smallest/least significant bit) of the second coordinate matters.

Then, following the method devised in BIP-340, if the public key generated is odd (would have a 1 bit at position 257) the private key is inverted, all 1s become 0 and vice versa. This will then generate a public key that is 256 bits long, the purpose of this was to eliminate the overflow into a 33rd byte that is normal for ECDSA public keys, and wasteful on the limited bitcoin block.

Thus we have a 256 bit secret key and a 256 bit public key, these are encoded as hexadecimal (1 character per 4 bits) for the hex, or prefixed with nsec/npub and the key is encoded with base32, which provides 5 bits per 1 character.

I forgot the signatures. Those are done via Schnorr scalar math, similar to ECDSA but less computationally expensive and always produce a neat 64 byte long signature, on top of the 32 byte hash (ID) of the event, which is generated by normalizing its structure into a uniform, json array format with a first field being an integer 0 followed by a comma, and no whitespace except spaces inside the JSON strings (json standard).

There, that's the most concise version of the distinctive details of how Nostr cryptography works. It's the same as bitcoin Musig2 and Taproot signature algorithms, without the other complicated parts of those two protocols.

The only reason we didn't have schnorr signatures from the beginning of Bitcoin was because Schnorr patented it, and in response the government funded the development of ECDSA which is less efficient but not encumbered by patent claims. It took quite a long time for schnorr signatures to be added to bitcoin after the patent expired.