I am trying to load a private key in PEM file, and then extract the public key portion. Unfortunately I have not had any success with this, and I have not found a crate that can help with this.
After closed and down voted questions on StackOverflow:
I am here to ask for pointers. How may I load a PEM file that contains a private key, and extract the public portion, with the option to even export it as a PEM file?
I'm not sure we are talking about the same thing. Slightly adapting the example found in the documentation, you could just perform a naïve linear search on all returned entries and pick whichever one you need: Rust Explorer
Every time I've used PEM, the tools which created the cert created separate files for the public and private parts. I've only had to recover public keys from private keys while developing Blockchain libraries and tools, which have their own (not PEM) formats.
Is there a reason you need to do public key recovery with PEM? Note that ECC is the only widespread algorithm which can do public key recovery, and it's not the only algorithm commonly used with PEM. ECC also requires some extra bits stored with the private key to indicate which of up to 4 solutions is the published public key; I doubt PEM stores those bits.
Okay, so there are two (actually, three) separate issues here:
Parsing and emitting PEM files with arbitrary content.
This is exactly what the pem crate is for.
Mathematically computing (not "extracting from a file") an RSA public key given only the information of the private key.
This is impossible (or at least, as strong a problem as breaking RSA and factoring are)
Extracting only the public key from a file that contains information about both the private and the public key, which some systems confusingly just call a "private key".
This is possible, but you'll have to parse the internal, possibly DER-encoded ASN.1 structure of the file. In which case, this has borderline nothing to do with PEM.
Which one of these 3 problems are you trying to solve?
You're adding a requirement to RSA. An RSA implementation only has to store (d, n) for the private key, which isn't enough to calculate e for the public key.
Okay, so it's actually #3 (OpenSSL's "private" key files contain information for the private and the public key).
Assuming you meant public_key_from_pem, this sounds like it solves your original question exactly. If that is not the case, could you elaborate what problem it doesn't solve that you still need to address?