paragonie / phpecc

Pure PHP Elliptic Curve Cryptography Library
16 stars 3 forks source link

Cryptographic Hardening (NIST P-256, P-384) #14

Closed paragonie-security closed 5 months ago

paragonie-security commented 5 months ago

Closes #11 and #12.

This pull request does a few things:

  1. Provides Complete Addition Formulas for a=-3 Weierstrass curves. This ensures that point addition and point doubling are exception-free and avoid timing leaks.
  2. Uses windowed scalar multiplication with constant-time conditional swaps to maximize performance without a security loss.
  3. Hard-codes the pre-calculated tables needed for scalar multiplication of the base point, which speeds up keypair generation.
  4. Implements Barrett reduction (with a pre-calculated R factor for each curve) to avoid division for reduction modulo a prime. Division and modulo reduction are generally not constant-time.

This implementations assumes that bigint multiplication is constant-time. On most hardware, this is a good assumption. BearSSL has good documentation on the hardware where this assumption is false. The odds are good that you're running PHP on hardware that uses constant-time multiplication.

Despite being PHP implementations of constant-time code, the performance hit for using these curves is minimal. There is probably some opportunity for further optimizations.

We do not force the use of our implementation by default, due to the minor performance hit it does have. To use the new code:

  $nistFactory = EccFactory::getNistCurves($adapter);

- $g256 = $nistFactory->generator256($rng);
+ $g256 = $nistFactory->generator256($rng, true);

- $g384 = $nistFactory->generator384$rng);
+ $g384 = $nistFactory->generator384($rng, true);

- $p256 = $bistFactory->curve256();
+ $p256 = $nistFactory->optimizedCurve256();

- $p384 = $bistFactory->curve384();
+ $p384 = $nistFactory->optimizedCurve384();

We will update EasyECC to use this API in the next release.