title: Invalid OpenSSH key format when importing an ec2 key form an existing one
body: <p>I am using the ruby EC2 SDK, Version 2. The private key material of a key generated with EC2 is stored in a string. I am trying to generate the public key material that is necessary to import the key into EC2 using <code>OpenSSL::PKey::RSA</code></p>
  
  <p>After that I am trying to <a href="http://docs.aws.amazon.com/sdkforruby/api/Aws/EC2/Resource.html#import_key_pair-instance_method" rel="nofollow noreferrer">import</a> the key pair.</p>
  
  <p>It looks like this:</p>
  
  <pre><code>kk=OpenSSL::PKey::RSA.new my_private_key_material
  pub=kk.public_key
  ec2.import_key_pair({key_name: "my_key", public_key_material: pub.export})
  </code></pre>
  
  <p>The API is throwing this error:</p>
  
  <pre><code>*** Aws::EC2::Errors::InvalidKeyFormat Exception: Key is not in valid OpenSSH public key format
  </code></pre>
  
  <p>I am not sure what is wrong and how to generate the public key material correctly. I already tried to Base64 encode the public key string without success.</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I tried a couple of new things.
  I generated a new key using the EC2 web console from scratch and then geneerated the public one the way Raphael points out below with </p>
  
  <pre><code>openssl rsa -in mykey.pem -outform PEM -pubout -out mykey.pub
  </code></pre>
  
  <p>The key is not encrypted.</p>
  
  <p>Whey trying to import the public key, either with the web console or by code, I get the same error.</p>
  
  <p><strong>Edit 2</strong></p>
  
  <p>I found this.</p>
  
  <p>When generating the public key with a different command, it works: </p>
  
  <pre><code>ssh-keygen -y
  </code></pre>
  
  <p>The generated public key looks different. It starts with </p>
  
  <pre><code>ssh-rsa AAAAB3NzaC1yc2EAAAADA....
  </code></pre>
  
  <p>While the first generated one starts with</p>
  
  <pre><code>-----BEGIN PUBLIC KEY-----
  MIIBIjANBgkqhkiG....
  </code></pre>
  
  <p>Now the question is how to generate the first format in ruby. I also found <a href="https://stackoverflow.com/questions/12749858/rsa-public-key-format">this</a> post on different formats.</p>