webpush icon indicating copy to clipboard operation
webpush copied to clipboard

Private key scalar not in the interval

Open Rolleander opened this issue 10 months ago • 0 comments

There seems to be an issue when working with unsigned-number scalar private keys (but still a valid key pair).

  1. Generated a key pair with the node web push library (https://www.npmjs.com/package/web-push#command-line), which creates an unsigned-number scalar as the private key
  2. Load keypair with VapidKeys.fromUncompressedBytes(), which treats the private key as a signed number (hence it will result in a negative scalar when the leading bit is a 1)
  3. Exception will occur in the initSign(privateKey) inside of the areKeysValidPair method: Scalar is not in the inerval [1, n -1]

Strangely this exception only appears for me in a deployed environment with Java 21, locally with Java 17 it didnt seem to mind the negative scalar. Tried both with the default sun provider and bouncycastle with the same key-pair.

Fix: https://github.com/interaso/webpush/blob/2485bbf667d396f4c45cef0a13e8421cd7128ca6/src/main/kotlin/com/interaso/webpush/Crypto.kt#L220

This should create the BigInteger from a unsigned byte array, same as with the public key:

generatePrivate(ECPrivateKeySpec(BigInteger(1, bytes), secp256r1parameterSpec)) as ECPrivateKey

After this change it correctly works with unsigned number private key scalars and does not result in a wrongly negative private key scalar (which should never happen)

Rolleander avatar Dec 17 '24 16:12 Rolleander