Skip to content

Instantly share code, notes, and snippets.

@alex
Created January 16, 2023 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex/413a9a1855b956dd0a8e3b0f9fefbd8b to your computer and use it in GitHub Desktop.
Save alex/413a9a1855b956dd0a8e3b0f9fefbd8b to your computer and use it in GitHub Desktop.
const EC_PUBLIC_KEY_OID: asn1::ObjectIdentifier = asn1::oid!(1, 2, 840, 10045, 2, 1);
const P256_OID: asn1::ObjectIdentifier = asn1::oid!(1, 2, 840, 10045, 3, 1, 7);
#[derive(asn1::Asn1Read)]
struct SubjectPublicKeyInfo<'a> {
algorithm: AlgorithmIdentifier<'a>,
subject_public_key: asn1::BitString<'a>,
}
#[derive(asn1::Asn1Read)]
struct AlgorithmIdentifier<'a> {
algorithm: asn1::ObjectIdentifier,
params: Option<asn1::Tlv<'a>>,
}
fn parse_key(
data: &[u8],
) -> Result<openssl::pkey::PKey<openssl::pkey::Public>, openssl::error::ErrorStack> {
let spki = asn1::parse_single::<SubjectPublicKeyInfo>(data).unwrap();
return match spki.algorithm.algorithm {
EC_PUBLIC_KEY_OID => {
let curve_oid = spki
.algorithm
.params
.unwrap()
.parse::<asn1::ObjectIdentifier>()
.unwrap();
let curve_nid = match curve_oid {
P256_OID => openssl::nid::Nid::X9_62_PRIME256V1,
_ => panic!("Unrecognized curve OID"),
};
let group = openssl::ec::EcGroup::from_curve_name(curve_nid)?;
let mut bn_ctx = openssl::bn::BigNumContext::new()?;
let ec_point = openssl::ec::EcPoint::from_bytes(
&group,
spki.subject_public_key.as_bytes(),
&mut bn_ctx,
)?;
let ec_key = openssl::ec::EcKey::from_public_key(&group, &ec_point)?;
openssl::pkey::PKey::from_ec_key(ec_key)
}
_ => panic!("Unrecognized key algorithm OID"),
};
}
fn main() {
const KEY_BYTES: &[u8] = b"0Y0\x13\x06\x07*\x86H\xce=\x02\x01\x06\x08*\x86H\xce=\x03\x01\x07\x03B\x00\x04)'\xb1\x05\x12\xba\xe3\xed\xdc\xfeFx(\x12\x8b\xad)\x03&\x99\x19\xf7\x08`i\xc8\xc4\xdfls(8\xc7xyd\xea\xac\x00\xe5\x92\x1f\xb1I\x8a`\xf4`gf\xb3\xd9hP\x01U\x8d\x1a\x97NsAQ>";
for i in 0..10240 {
let pkey = parse_key(KEY_BYTES).unwrap();
pkey.ec_key().unwrap();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment