Created
August 17, 2023 16:41
-
-
Save zedalaye/8ac6bbad060ea691887a81fa53006d0c to your computer and use it in GitHub Desktop.
Instanciate an OpenSSL::PKey::EC from a raw private key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Tested using | |
# Ruby v3.2.2 / openssl gem v3.1.0 | |
# Ubuntu with OpenSSL 3.0.2 | |
require 'openssl' | |
class ECKey | |
CURVE='prime256v1' | |
def self.get_raw_private_key | |
ec_key = OpenSSL::PKey::EC.generate(CURVE) | |
ec.private_key.to_s(2) | |
end | |
def self.load_key(raw_private_key) | |
OpenSSL::PKey::EC.new(build_der_from_raw_private_key(raw_private_key)) | |
end | |
def self.build_der_from_raw_private_key(data) | |
# Decode the Private Key as a BigNumber (BN) | |
private_key = OpenSSL::BN.new(data, 2) | |
# Compute the Public Key using the curve group generator | |
group = OpenSSL::PKey::EC::Group.new(CURVE) | |
public_key = group.generator.mul(private_key) | |
# Build a DER using ASN1, this one fakes what OpenSSL produces for | |
# OpenSSL::PKey::EC.generate('prime256v1').to_der | |
# Which can be decoded using OpenSSL::ASN1.decode(der) | |
asn1 = OpenSSL::ASN1::Sequence.new( | |
[ | |
OpenSSL::ASN1::Integer.new(OpenSSL::BN.new(1)), | |
OpenSSL::ASN1::OctetString.new(data), | |
OpenSSL::ASN1::ASN1Data.new([OpenSSL::ASN1::ObjectId.new(CURVE)], 0, :CONTEXT_SPECIFIC), | |
OpenSSL::ASN1::ASN1Data.new([OpenSSL::ASN1::BitString.new(public_key.to_bn.to_s(2))], 1, :CONTEXT_SPECIFIC) | |
] | |
) | |
asn1.to_der | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment