Ruby secp256k1 implementation with an optional C extension to mitigate side channel attacks
Be the first to ask Simon Bettison something.
What do you think? ...
secp256k1-native provides secp256k1 elliptic curve operations for Ruby. It includes a pure‑Ruby implementation and an optional native C extension that offers constant‑time guarantees and ~22× speedup.
The library supports field arithmetic, scalar arithmetic, Jacobian point operations, windowed‑NAF and Montgomery ladder scalar multiplication, and SEC1 point encoding/decoding.
When the C extension is compiled it replaces hot‑path operations; otherwise the pure‑Ruby fallback works on any Ruby 2.7+ platform. The gem is used by bsv‑ruby‑sdk and can be installed via gem install secp256k1-native.
Earn XP for sharing
Sign in to get a personal referral link and earn XP every time someone visits through your link.
No reviews yet — be the first.
gem install secp256k1-nativegem install secp256k1-native```ruby
require 'secp256k1'
# Generator point
g = Secp256k1::Point.generator
# Scalar multiplication (constant-time by default — safe for all scalars)
secret = 0xcafebabe
pubkey = g.mul(secret)
puts pubkey.x.to_s(16)
# Variable-time scalar multiplication (faster, for public scalars only)
scalar = 0xdeadbeef
point = g.mul_vt(scalar)
# SEC1 encoding / decoding
compressed = pubkey.to_octet_string(:compressed) # 33 bytes
uncompressed = pubkey.to_octet_string(:uncompressed) # 65 bytes
decoded = Secp256k1::Point.from_bytes(compressed)
# Field arithmetic
a = Secp256k1::P - 1
b = Secp256k1.fmul(a, a) # modular multiplication
c = Secp256k1.fadd(a, b) # modular addition
d = Secp256k1.finv(a) # modular inverse (Fermat)
# Scalar arithmetic (mod N)
k = Secp256k1.scalar_inv(42) # scalar inverse
```