How Generate SSH Public & Private Key Pair?


#1

I Use openssl and pem generate SSH key, and got private key data. But I couldn’t find a way encode public key data to PKIX format.

extern crate openssl;
extern crate pem;

use openssl::rsa::Rsa;
use pem::{Pem, encode};

fn main() {
  // Generate a new 4096-bit key.
  let rsa = Rsa::generate(4096).unwrap();

  let public_key = rsa.public_key_to_der().unwrap();
  let private_key = rsa.private_key_to_der().unwrap();

  let private_pem = Pem {
    tag: String::from("RSA PRIVATE KEY"),
    contents: private_key,
  };
  let private = encode(&private_pem);

  println!("{}", private);
}

The program will print private pem data like this,

-----BEGIN RSA PRIVATE KEY-----
MIIJKAIBAAKCAgEA3xLeYYMmdqDrmqR07ja+Xe5l0CiIXlWLkg0igXxYNHqUMpto
M4XVmTTVYIfjKabf1Pj7ik+fJ+EMS8jcKq/wlEIbJtRFC+cqmZ3TlFYW+SqfEjKJ
P1SuGZV10umrQK2vau9A0HZC8DZ/Naq2DjeNlbuIvWI0Ivp9iy2hMzsDud/u4Y/1
JVJ3pxcWSKqmfPZ4r/qIeT0Y47k7i0Jls03eX1Fs3HcpHpIBRDFJ8pFb3CRGhtxI
V3LuLx616xKquxAPM/VOxIqmI1sSxz9DGNa2G3lm48DbxkvlqDdCuFTc8zNQteqI
Kt4OdZfBv5dbBuI4v47hnU4zkQ/LYMlr+m45Ys1YAsCq5fRbejB4BVLHvllVVYVR
gBrmPWZ9zAbTKGDl3093exF6anUR5Mn7svFwyGMLjWbkSoM+k97Vdd0swLGS2gui
A65qs4OvwtsgCMqULSQznFGxh/UoS3onZzW0V+XcLflCJkonY8uJqmsd6jO3h254
otkExKvPJYCmzBTe7NtDFbv0o3uqbZfqavWFkQ/ACSWjiDzNN+5KZp1o7gqr08aM
kMsSs3Fw9f6cCrVhEZHYCi3zaNzbDFoXPYKSrukdNmh+VyHcPXsjb377WPtfNHJ3
FNb1DpTFttbQCeDYcboHYQ9QYJ8NINuiSlKg4WCdTm3GEM9Ubk06ZKuSjNUCAwEA
AQKCAgAdDEH1BLT/g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rSLJqWHrfCUae+IO6P7TAmkkgHtrTouHILY9vFiMX9KytjDGI463CJLPK
mD9RRzJl4tnKa5nPukINDOkRjErmS3UcO/lFRvQFSH8HUhk3Dwrtiuxpp/aqMMxa
VgXqpTUkGkZom42D8SuTcWuNQ8PfaaqDCGa0XRw0nJrxAlT1ov1Xao8wU/q5QfhO
IF3w+N/IhFx6Z2v21rlm9Eech5L6T3ZlItrSfBf7rYpHw+VhGgFcBXZZLr0OQT2A
shk5sPDyKzu0YFl/7afqb7H7D6Cb1Sm44L+P3CVxD7P13FCHdVtB2AAkmng=
-----END RSA PRIVATE KEY-----

#2

PKIX is probably the binary DER format. You can transform PEM to DER the following way:

openssl x509 -in certificate.pem -inform pem -out certificate.der -outform der

#3

Yeah, I know the command. I just want to do it with Rust.


#4

Finally, I resolved the question.

Actually, I want to generate SSH2 format public key and PEM format private key for the SSH connection. There are some demo codes in my rust-learning repository. Also I am working on submitting some PRs into openssh-keys #9 .