Skip to content

Instantly share code, notes, and snippets.

@kraftb
Created April 1, 2014 16:49
Show Gist options
  • Select an option

  • Save kraftb/9918106 to your computer and use it in GitHub Desktop.

Select an option

Save kraftb/9918106 to your computer and use it in GitHub Desktop.
Generate public/private keypair and output to stdout
#!/bin/bash
BITS=2048
# In one line:
# rm -f temp.key && ssh-keygen -t rsa -b 2048 -f temp.key -N "" -q && ssh-keygen -e -f temp.key -m PKCS8 | tr "\n" " " && echo && cat temp.key | tr "\n" " " && echo
# In multiple lines:
rm -f temp.key
ssh-keygen -t rsa -b $BITS -f temp.key -N "" -q
echo
ssh-keygen -e -f temp.key -m PKCS8 | tr "\n" " "
echo
echo
cat temp.key | tr "\n" " "
echo
echo
@santosh0705
Copy link

I was working on a script to generate an SSH key pair and store it directly in my vault. I came across this gist and found @mprasil approach very helpful as a starting point.
That said, I ended up implementing it a bit differently. Since I needed to read both the private and public keys after generation, I decided to run the key generation process itself in the background (instead of backgrounding the file reads). Also the contents are read into a variable which you can use elsewhere in the script. Also does the cleanup on exit.
Here's my version of the code - hope it helps someone else!

local COMMENT="Your comment"
local TEMP_DIR=$(mktemp -d)
trap "rm -rf ${TEMP_DIR}" EXIT
local KEY_FILE="${TEMP_DIR}/key"

mkfifo "${KEY_FILE}" "${KEY_FILE}.pub"
(ssh-keygen -t ed25519 -N '' -q -f "${KEY_FILE}" -C "${COMMENT}" <<< y > /dev/null)&
sleep 0.1
PRI_KEY=$(< "${KEY_FILE}")
PUB_KEY=$(< "${KEY_FILE}.pub")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment