Skip to content

Instantly share code, notes, and snippets.

@ostinelli
Last active April 14, 2024 17:32
Show Gist options
  • Save ostinelli/1770a93d5c01376728c9 to your computer and use it in GitHub Desktop.
Save ostinelli/1770a93d5c01376728c9 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)
@cpapidas
Copy link

If you are getting an error about immutability, use the following

key = OpenSSL::PKey::EC.generate("secp256k1")

instead of

key = OpenSSL::PKey::EC.new("secp256k1") # IT'S WRONG FOR OPENSSL 3

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