#!/bin/sh
#
# $Revision: 45a6d8582b36 $ $Date: Thu, 14 Mar 2024 21:47:43 -0400 $
# $Source: /doc/html/htdocs/dotfiles/top/dot-ssh/newkey $
# $Host: furbag.my.domain $
# $UUID: e3787f7f-c88b-3d93-ab09-34d5df231d25 $
#
#< newkey: create RSA/ECDSA/ED25519 keys for a given host.
# Default is to create id_{rsa,ecdsa,ed25519} files.

export PATH=/usr/local/bin:/bin:/usr/bin

# Arguments: no hostname means create a default key.
case "$#" in
    0) host='id' ;;
    *) host=$1 ;;
esac

# Do not overwrite existing files.
set X $(ls ${host}_* 2> /dev/null | wc -l)
shift
case "$1" in
    0) ;;
    *) echo "please delete ${host}_ files:"; ls ${host}_*; exit 1 ;;
esac

# Real work starts here.
echo Generating RSA keypair
ssh-keygen -o -b 4096 -t rsa -C "you@yourhost.com" -N '' -f ${host}_rsa

echo Generating ED25519 keypair
ssh-keygen -o -t ed25519 -C "you@yourhost.com" -N '' -f ${host}_ed25519

## https://security.stackexchange.com/questions/143442/
## Do not consider the other new ECC algorithm called ECDSA.  It is
## considered suspect (it has known weaknesses and since the US government
## has been involved in its development, it may be compromised beyond that).
## Ed25519 was developed without any known government involvement.

#echo Generating ECDSA keypair
#ssh-keygen -o -t ecdsa -C "you@yourhost.com" -N '' -f ${host}_ecdsa

echo
echo Files:
ls -lF ${host}_*

echo
echo Full public keys:
cat ${host}_*.pub

echo
echo Public keys for LOG:

for file in ${host}_*.pub
do
    set X $(cat $file); type=$2; key=$3; host=$4
    begin=$(echo "$key" | cut -c1-20)
    end=$(echo "$key" | sed -e 's/.*\(..........\)$/\1/')
    echo "$type $begin[...]$end $host"
done

exit 0
