Question

I'm developing a Bitbucket API wrapper in JavaScript. I'm trying to write tests for the method which adds an SSH key. My naive attempt at creating a believable SSH key was unsuccessful. Here's how I generated a dummy key:

  1. start with "ssh-rsa "
  2. append the Base64-encoded representation of a 279 character string of random characters
  3. append " "
  4. append a 16 character string of random characters
  5. append "@"
  6. append a 16 character string of random characters
  7. append ".com"

Bitbucket returns 400 Bad Request when I POST an SSH key generated in this manner. Fortunately I have access to Bitbucket's source code, so I've been able to dig a little deeper. Bitbucket validates SSH keys by running them through ssh-keygen.

I don't understand how SSH keys are generated, so I might be asking a silly question. Is it possible to generate an SSH key convincing enough to fool ssh-keygen? Here's the output:

$ ssh-keygen -l -f ~/Desktop/dummy_rsa.pub 
buffer_get_string_ret: bad string length 1903654498
key_from_blob: can't read key type
key_read: key_from_blob cXd2YnRzZXpha3Rld2V4YmdieWdoeWl2aXpla3hkaHBodnlteHl2ZHl0bnloYmRyYWZrdnVxaWR3cHBydnFmZWFkaHp0aGRwYml6ZXVxY3ZlZ3NiZ29lanl0cG9vZmlnZ2dyZmJ3aWxsdXJhb2puYWRjY3F0YW5rcGV3Z3dkc3lxd2tkb3d6emFzbXpubXJ1eGN2bm53a3l6bmRjenV1dnplbnFtZ3Z5bm96ZGZhandwcG9mcHVoaWFkZ25ud3VkdnB0enV6Zm51bWVxanhzanlwa2ZodGxpd2xld2pnY3dhbmJ6aXVyamp6c29rbm54dHp2enJmeWhnY2ZrcWlqemFscGNnbWJsY3lpcmRtYXFkbHB6c3l0 duvrnzsladfrmccr@xqrbenpfryhoklgw.com
 failed
/Users/dc/Desktop/dummy_rsa.pub is not a public key file.

To be clear, I don't need to generate a "valid" SSH key, I just need to be able to test various API endpoints. Also, since the tests run in a browser, I can't shell out to generate a key.

Was it helpful?

Solution

SSH keys are not just random strings of characters, so that's why they don't pass verification.

This library here called Javascript Cryptography Toolkit can help you generate RSA keys (used by SSH).

They have a demo of generating the key: https://github.com/ats4u/titaniumcore/blob/master/crypto/RSA.sample1.html

As you can see from the source code of the demo page, the toolkit is quite heavy weight, but if that's what you need, then that's what you have to use, I guess. Ofcourse it would have been much simpler to just offload key generation to the server, but if you are writing a client side only library, then you have to stick with this.

2019 update: updated links to github.

OTHER TIPS

If you end up making an AJAX call to your existing lightweight Ruby Sinatra app to generate and retrieve an SSH key, you can use the sshkey Gem to do so https://rubygems.org/gems/sshkey

This doesn't answer how to do it in pure JavaScript but provides an alternate avenue based on your specific application architecture (see comments below question).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top