Skip to content

Instantly share code, notes, and snippets.

@emboss
Created August 4, 2012 00:58
Show Gist options
  • Save emboss/3253173 to your computer and use it in GitHub Desktop.
Save emboss/3253173 to your computer and use it in GitHub Desktop.
Compute EC public key from private key and generator
require 'openssl'
group = OpenSSL::PKey::EC::Group.new('prime256v1')
generator = group.generator #the generator point
ec = OpenSSL::PKey::EC.new
ec.group = group
ec.generate_key #generate a key pair
priv = ec.private_key #this is a random number, a OpenSSL::BN
# the public point P is given by P = priv * G,
# where s is the private key and G is the generator point
pub_point = generator.mul(priv)
puts ec.public_key == pub_point # true, now convert the point to an EC
pub_ec = OpenSSL::PKey::EC.new
pub_ec.group = group
pub_ec.public_key = pub_point
puts ec.to_text
puts pub_ec.to_text #pub parts are equal!
puts pub_ec.to_pem #to serialize it in PEM format
@xkvyor
Copy link

xkvyor commented Jan 12, 2015

This code is really helpful. Thank you very much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment