RSA icon indicating copy to clipboard operation
RSA copied to clipboard

Easy to Misuse API For PEM Encoding ( On Master )

Open zicklag opened this issue 5 years ago • 1 comments

Hey there, I just noticed that it is extremely easy when using the PEM encoding traits to accidentally generate a public key when you mean to generate a private key PEM. For instance ( Key Pair is just a simple struct of mine ):

This works as expected:

let mut rng = rand::rngs::OsRng;
let private = rsa::RSAPrivateKey::new(&mut rng, 4096)?;
let public = rsa::RSAPublicKey::from(&private);

use rsa::PublicKeyPemEncoding;
use rsa::PrivateKeyPemEncoding;
Ok(KeyPair {
    private: private.to_pem_pkcs8()?,
    public: public.to_pem_pkcs8()?,
})

This actually generates two public keys:

let mut rng = rand::rngs::OsRng;
let private = rsa::RSAPrivateKey::new(&mut rng, 4096)?;
let public = rsa::RSAPublicKey::from(&private);

use rsa::PublicKeyPemEncoding;
// Say we accidentally forget to include the private key trait
// use rsa::PrivateKeyPemEncoding;
Ok(KeyPair {
    private: private.to_pem_pkcs8()?,
    public: public.to_pem_pkcs8()?,
})

Apparently the PublicKeyPemEncoding trait is implemented for private keys with the same function name: to_pem_pks8. I think an easy solution to this would be to name the to_pem_pkcs8 functions specific to the type of key you want to generate such as to_public_pem_pkcs8 or something like that.

zicklag avatar Sep 16 '20 17:09 zicklag

What benefit to these traits provide over just having the methods on the RSAPrivateKey and RSAPublicKey structs?

aloucks avatar Sep 17 '20 01:09 aloucks

The encoding API has since changed to use the pkcs1 and pkcs8 crates which have an API similar to what was suggested here

tarcieri avatar Apr 25 '23 03:04 tarcieri