Search code examples
encryptionrustcryptographyrsa

How to convert RSA private key to pem


I need to convert the private key generated using RsaPrivateKey::new() to pem but can't figure out how to do this through the documentation

use rsa::{PublicKey, RsaPrivateKey, RsaPublicKey, PaddingScheme, pkcs8::EncodePrivateKey};

// create a private key
let mut rng = rand::thread_rng();
let bits = 2048;
let private_key = RsaPrivateKey::new(&mut rng, bits).expect("Failed to generate key");
// create a public key / address
let public_key = RsaPublicKey::from(&private_key);

Creating the pem returns an error saying that LineEnding is undeclared but that is how they do it in the documentation:

let priv_pem = RsaPrivateKey::to_pkcs8_pem(&private_key, line_ending: LineEnding::default);

Solution

  • You need to import LineEnding from pkcs8, or qualify it as from that crate:

    use rsa::pkcs8::{LineEnding, EncodePrivateKey};
    
    let priv_pem = RsaPrivateKey::to_pkcs8_pem(&private_key, LineEnding::default);
    

    or

    use rsa::pkcs8::{self, EncodePrivateKey};
    
    let priv_pem = RsaPrivateKey::to_pkcs8_pem(&private_key, pkcs8::LineEnding::default);