RustCrypto / formats

Cryptography-related format encoders/decoders: DER, PEM, PKCS, PKIX
250 stars 132 forks source link

spki: Document how to convert between `SubjectPublicKeyInfoRef` (or owned) and e.g. `p256::PublicKey` #1604

Open str4d opened 1 week ago

str4d commented 1 week ago

As part of migrating age-plugin-yubikey to yubikey 0.8 (using VS Code and rust-analyzer), I encountered SubjectPublicKeyInfo in a certificate. I need to parse this into an Option<p256::PublicKey> (returning None if invalid or not P-256), but there is no documentation anywhere in the spki crate on how to do this.

I found SubjectPublicKeyInfo::from_key which is how to convert any type implementing EncodePublicKey into an SPKI, but there is no equivalent reverse method. A DecodePublicKey trait exists, but there is no reference to it in the documentation of SubjectPublicKeyInfo (or its owned or ref aliases). DecodePublicKey also doesn't document how it should be used either.

I then turned to the p256 crate's documentation:

I finally noticed the impl<T> DecodePublicKey for T where T: for<'a> TryFrom<SubjectPublicKeyInfoRef<'a>> at the bottom of the DecodePublicKey documentation, which gave me the idea to just try p256::PublicKey::try_from(spki), and it worked!

The conversion process should be greatly simplified, by way of one or more of the following:

tarcieri commented 1 week ago

Would a suggestion to use TryFrom and a adding list to the spki crate's rustdoc of some of the types in various RustCrypto crates which support the conversion be helpful here?

str4d commented 1 week ago

Yes, that's my second suggestion above.