Replace implementation with a port of ref10 code.

This implementation is much faster and is now constant-time.