Skip to content

Instantly share code, notes, and snippets.

@v-kolesnikov
Forked from ostinelli/ecdsa_example.rb
Created December 29, 2018 11:55
Show Gist options
  • Save v-kolesnikov/28e89679da8b5c42eb1ad989c7ef7da0 to your computer and use it in GitHub Desktop.
Save v-kolesnikov/28e89679da8b5c42eb1ad989c7ef7da0 to your computer and use it in GitHub Desktop.
ECDSA usage from Ruby.
require 'openssl'
require 'base64'
# ===== \/ sign =====
# generate keys
key = OpenSSL::PKey::EC.new("secp256k1")
key.generate_key
public_key = key.public_key
public_key_hex = public_key.to_bn.to_s(16).downcase # public key in hex format
# sign a message
data = "My message to sign"
signature = key.dsa_sign_asn1(data)
signature_base64 = Base64.encode64(signature).gsub("\n", "")
# ===== \/ verify =====
# rebuild key
group = OpenSSL::PKey::EC::Group.new('secp256k1')
key = OpenSSL::PKey::EC.new(group)
# create point from hex key
public_key_bn = OpenSSL::BN.new(public_key_hex, 16)
public_key = OpenSSL::PKey::EC::Point.new(group, public_key_bn)
key.public_key = public_key
# verify message
data = "My message to sign"
signature = Base64.decode64(signature_base64)
key.dsa_verify_asn1(data, signature)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment