Skip to content

Instantly share code, notes, and snippets.

@kingsleyh
Created December 9, 2018 18:29
Show Gist options
  • Save kingsleyh/822b56de16f444e27371da30e9aa8365 to your computer and use it in GitHub Desktop.
Save kingsleyh/822b56de16f444e27371da30e9aa8365 to your computer and use it in GitHub Desktop.
OpenSSL EC
# http://fm4dd.com/openssl/eckeycreate.htm
# https://stackoverflow.com/questions/34404427/how-do-i-check-if-an-evp-pkey-contains-a-private-key
# https://davidederosa.com/basic-blockchain-programming/elliptic-curve-keys/
lib LibSSL
fun EC_KEY_generate_key(key : LibC::Int*) : LibC::Int
fun EC_KEY_new_by_curve_name(i : LibC::Int) : LibC::Int*
fun OBJ_txt2nid(s : LibC::Char*) : LibC::Int
fun EVP_PKEY_new : LibC::Int*
fun EVP_PKEY_assign(pkey : LibC::Int*, type : LibC::Int, key : Void*) : LibC::Int
alias EcKeySt = Void
alias EVP_PKEY = Void*
alias EC_KEY = Void*
alias EcPoint = Void*
fun EVP_PKEY_get1_EC_KEY(pkey : LibC::Int*) : EcKeySt*
fun EVP_PKEY_bits(pkey : LibC::Int*) : LibC::Int
fun EC_KEY_get0_private_key(pkey : LibC::Int*) : LibC::Int*
fun EC_KEY_get0_public_key(key : LibC::Int*) : EcPoint
fun BN_bn2hex(a : LibC::Int*) : LibC::Char*
fun BN_bn2dec(a : LibC::Int*) : LibC::Char*
type EcGroup = Void*
enum PointConversionFormT
PointConversionCompressed = 2
PointConversionUncompressed = 4
PointConversionHybrid = 6
end
fun EC_POINT_point2hex(x0 : EcGroup, x1 : EcPoint, form : PointConversionFormT) : LibC::Char*
fun EC_GROUP_new_by_curve_name(nid : LibC::Int) : EcGroup
fun EC_KEY_free(key : LibC::Int*)
fun EC_POINT_free(point : EcPoint)
fun EC_GROUP_free(group : EcGroup)
end
# Create a EC key sructure, setting the group type from NID
eccgrp = LibSSL.OBJ_txt2nid("secp256k1")
myecc = LibSSL.EC_KEY_new_by_curve_name(eccgrp);
# Create the public/private EC key pair here
LibSSL.EC_KEY_generate_key(myecc)
# Get the private key
bn = LibSSL.EC_KEY_get0_private_key(myecc)
private_key_pointer = LibSSL.BN_bn2hex(bn)
private_key = String.new(private_key_pointer).downcase
puts private_key
# Get the public key
ec_point = LibSSL.EC_KEY_get0_public_key(myecc)
form = LibSSL::PointConversionFormT::PointConversionUncompressed
grp = LibSSL.EC_GROUP_new_by_curve_name(eccgrp)
public_key_pointer = LibSSL.EC_POINT_point2hex(grp, ec_point, form)
public_key = String.new(public_key_pointer).downcase
puts public_key
# Free up mem
LibSSL.EC_KEY_free(myecc);
LibSSL.EC_GROUP_free(grp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment