Skip to content

Instantly share code, notes, and snippets.

@kingsleyh
Created April 21, 2020 17:12
Show Gist options
  • Save kingsleyh/78cfb065e46917d6d70ac5cac180f98e to your computer and use it in GitHub Desktop.
Save kingsleyh/78cfb065e46917d6d70ac5cac180f98e to your computer and use it in GitHub Desktop.
openssl pkey verify
def self.verify2(hex_public_key : String, message : String, r : String, s : String)
pkey = LibECCrypto.EVP_PKEY_new()
# Create a EC key structure, setting the group type from NID
eccgrp_id = LibECCrypto.OBJ_txt2nid("secp256k1")
raise "Error could not set EC group" unless eccgrp_id != 0
myecc = LibECCrypto.EC_KEY_new_by_curve_name(eccgrp_id)
raise "Error could not create curve" if myecc.null?
# convert binary public key to point
eccgrp = LibECCrypto.EC_GROUP_new_by_curve_name(eccgrp_id)
raise "Error could not get the group curve" if eccgrp.null?
ec_point = LibECCrypto.EC_POINT_new(eccgrp)
raise "Error could not create point from group" if ec_point.null?
point_res = LibECCrypto.EC_POINT_hex2point(eccgrp, hex_public_key.to_unsafe, ec_point, nil)
raise "Error could not get point from public key" if point_res.null?
# set the public key on the EC structure
set_pub_key = LibECCrypto.EC_KEY_set_public_key(myecc, ec_point)
raise "Error could not set public key to EC" unless set_pub_key == 1
set_pkey = LibECCrypto.EVP_PKEY_set1_EC_KEY(pkey, myecc)
raise "Error could not set EC key as EVP key" unless set_pkey == 1
ctx = LibECCrypto.EVP_PKEY_CTX_new(pkey, nil)
raise "Error could not create an EVP PKEY context" if ctx.null?
v_init = LibECCrypto.EVP_PKEY_verify_init(ctx)
raise "Error could verify init" unless v_init == 1
# EVP_PKEY_CTX_set_signature_md(ctx, EVP_sha256())
algo = LibCrypto.evp_sha256()
set_sign = LibECCrypto.EVP_PKEY_CTX_ctrl(ctx, -1, LibECCrypto::EVP_PKEY_OP_TYPE_SIG, LibECCrypto::EVP_PKEY_CTRL_MD, 0, algo)
raise "Error could not set algorithm onto context" unless set_sign == 1
# LibECCrypto.EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx, "secp256k1")
# set_curve = LibECCrypto.EVP_PKEY_CTX_set_ec_paramgen_curve_name(ctx, "secp256k1")
# p set_curve
# LibECCrypto.EVP_PKEY_CTX_set_ec_param_enc(ctx, LibECCrypto::OPENSSL_EC_NAMED_CURVE)
# set_enc = LibECCrypto.EVP_PKEY_CTX_ctrl(ctx, LibECCrypto::EVP_PKEY_EC, (LibECCrypto::EVP_PKEY_OP_PARAMGEN | LibECCrypto::EVP_PKEY_OP_KEYGEN), LibECCrypto::EVP_PKEY_CTRL_EC_PARAM_ENC, LibECCrypto::OPENSSL_EC_NAMED_CURVE, nil)
# p set_enc`
sig = r + s
sig_len = sig.bytesize
message_len = message.bytesize
rv = LibECCrypto.EVP_PKEY_verify(ctx, sig, sig_len, message, message_len)
pp rv
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment