#!/bin/bash
#
# Author: Georg Voell - georg.voell@standby.cloud
# Version: @(#)createkeys 1.0.7 31.07.2025 (c)2025 Standby Cloud
#
# Generate all needed SSH Keys to access Oracle Cloud
#
# Version history:
#
# V 1.0.0 23.12.2018 New version
# V 1.0.1 28.05.2020 Renamed PKSC#8 key to '.pk8' and API Key to '.pem'
# V 1.0.2 26.06.2020 Create RSA keys with 4096 bits for stronger encryption
# V 1.0.3 16.09.2020 Fixes bug: PK8 key with passphrase could not be created
# V 1.0.4 18.11.2021 Support newer version from puttygen
# V 1.0.5 29.04.2023 Only create Putty Keys if puttygen is installed
# V 1.0.6 28.08.2023 openssl V3.x is fips enabled
# V 1.0.7 31.07.2025 Append "OCI_API_KEY" to PK8 key (needed for oci cli)
#

# Set HOME if it isn't defined
if [ "$HOME" = "" ]; then
	export USER=`whoami`	# Current user
	export HOME=$(eval echo ~${USER})
	export LOCALCALL="false"
else
	export LOCALCALL="true"
fi

# Set PATH to something useful
PATH=${HOME}/.local/bin:${HOME}/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:$PATH

function errormsg() {
	local normal='\033[0m'
	local redcol='\033[0;91m' # Highlighted red
	
	local number=${1}         # Error Number
	local errmsg=${2}         # Error Message
	local errrsn=${3}         # Error Reason
	
	if [ "$LOCALCALL" = "true" ]; then
		# Assuming local call
		if [ "$errrsn" = "" ]; then
			printf "${redcol}ERROR(%02d): ${errmsg}${normal}\n" $number > /dev/stderr
		else
			printf "${redcol}ERROR(%02d): ${errmsg} (${errrsn})${normal}\n" $number > /dev/stderr
		fi
	else
		# Assuming call via keygen.pl (URL)
		printf "Content-type:text/html\n\n"
		if [ "$errrsn" = "" ]; then
			printf "<b>Application Error: (%s) %s</b>\n" "$number" "$errmsg"
		else
			printf "<b>Application Error: (%s) %s (${errrsn})</b>\n" "$number" "$errmsg"
		fi
	fi
}

function compare() {
	a=${1}
	b=${2}
	
	numstr=`echo "$a" | grep '^[0123456789]*$'`
	if [ "$numstr" = "" ]; then
		exitcode=2
		errormsg $exitcode "Not a number." "1: '$a'"
		return $exitcode
	fi
	
	numstr=`echo "$b" | grep '^[0123456789]*$'`
	if [ "$numstr" = "" ]; then
		exitcode=2
		errormsg $exitcode "Not a number." "2: '$b'"
		return $exitcode
	fi
	
	if [ $a -eq $b ]; then
		echo "same"
	else
		if [ $a -gt $b ]; then
			echo "older"
		else
			echo "newer"
		fi
	fi
}

function split() {
	a=${1}
	grepres=`echo $a | grep '\.'`
	if [ "$grepres" = "" ]; then
		echo $a
	else
		result=`echo $a | cut -d'.' -f1`
		echo $result
	fi
}

function check() {
	par1=`split $param1`
	par2=`split $param2`
	
	result=`compare $par1 $par2`
	stat=$?
	
	if [ $stat -eq 0 ]; then
		if [ "$result" = "same" ]; then
			param1=`echo $param1 | sed 's|^'$par1'.||'`
			param2=`echo $param2 | sed 's|^'$par2'.||'`
			
			if [ "$param1" != "" -a "$param2" != "" ]; then
				result=`check`
				stat=$?
				
				if [ $stat -eq 0 ]; then
					echo $result
				fi
			else
				echo "same"
			fi
		else
			echo $result
		fi
	fi
	
	return $stat
}

function compare-version () {
	param1=${1}
	param2=${2}

	if [ "$param1" = "$param2" ]; then
		echo "same"
	else
		result=`check`
		stat=$?
		
		if [ $stat -eq 0 ]; then
			echo $result
		fi
	fi
}

function check-version () {
	local search=${1}
	local minimum=${2}
	
	# Preset
	local stat=0
	local tool=""
	local version=""
	local okstr=""
	local result=""

	tool=`which "$search" 2>/dev/null`
	if [ ! -x "$tool" ]; then
		echo "$tool not found"
		stat=1
	else
		if [ "$minimum" != "" ]; then
			version=`$tool --version 2>&1 | head -n 1 | cut -d' ' -f3`
			if [ "$version" != "" ]; then
				result=`compare-version "$minimum" "$version"`
				if [ "$result" = "same" -o "$result" = "newer" ]; then
					okstr="ok"
				else
					okstr="need $minimum"
					stat=2
				fi
				
				printf "%s\t%s\t%s\n" "$tool" "$version" "$okstr"
			fi
		else
			printf "%s\n" "$tool"
		fi
	fi
	
	return $stat
}

# Return the key type
function KeyType() {
	local privkey=${1}
	
	# Preset
	local keytype=""
	local keysignature=""
	local result=""
	local encrypted=""
	
	# Possible results:
	#
	#  UNKNOWN or INVALID
	#
	#  RSA-PRIVATE-KEY NONE or RSA-PRIVATE-KEY CIPHER
	#  PRIVATE-KEY NONE or PRIVATE-KEY CIPHER
	#  OPENSSH-PRIVATE-KEY-Vx NONE or OPENSSH-PRIVATE-KEY-Vx CIPHER
	#  PUTTY-PRIVATE-KEY-Vx NONE or PUTTY-PRIVATE-KEY-Vx CIPHER
	#
	#  SSH-RSA-PUBLIC-KEY   # SSH
	#  RSA-PUBLIC-KEY       # RSA
	#  PUBLIC-KEY           # API
	
	if [ -r "$privkey" ]; then
		# Get first non empty line and last non empty line from key
		keysignature=`grep . "$privkey" | head -n 1`
		result=`grep . "$privkey" | tail -n 1`
		
		case "$keysignature" in
			"-----BEGIN RSA PUBLIC KEY-----")
				if [ "$result" = "-----END RSA PUBLIC KEY-----" ]; then
					keytype="RSA-PUBLIC-KEY"
				else
					keytype="INVALID"
				fi
				;;
			"-----BEGIN RSA PRIVATE KEY-----")
				if [ "$result" = "-----END RSA PRIVATE KEY-----" ]; then
					encrypted=`grep "ENCRYPTED" "$privkey"`
					if [ "$encrypted" != "" ]; then
						result=`grep "^DEK-Info: " "$privkey" | cut -d' ' -f2 | cut -d',' -f1`
						keytype="RSA-PRIVATE-KEY $result"
					else
						keytype="RSA-PRIVATE-KEY NONE"
					fi
				else
					keytype="INVALID"
				fi
				;;
			"-----BEGIN OPENSSH PRIVATE KEY-----")
				if [ "$result" = "-----END OPENSSH PRIVATE KEY-----" ]; then
					# result=`ssh-keygen -y -P "" -f "$privkey" 2>/dev/null`
					result=`grep -v "^-----" "$privkey" | head -n 1 | base64 -d  2>/dev/null | sed 's|^openssh-key-||' \
						| tr '[:lower:]' '[:upper:]' | tr '\n' ' ' | tr '\06' ' ' | tr '\04' ' '`
					encrypted=`echo "$result" | cut -d ' ' -f2`
					result=`echo $result | cut -d ' ' -f1`
					keytype="OPENSSH-PRIVATE-KEY-$result $encrypted"
				else
					keytype="INVALID"
				fi
				;;
			"-----BEGIN PUBLIC KEY-----")
				if [ "$result" = "-----END PUBLIC KEY-----" ]; then
					keytype="PUBLIC-KEY"
				else
					keytype="INVALID"
				fi
				;;
			"-----BEGIN PRIVATE KEY-----")
				if [ "$result" = "-----END PRIVATE KEY-----" ]; then
					keytype="PRIVATE-KEY NONE"
				else
					keytype="INVALID"
				fi
				;;
			"-----BEGIN ENCRYPTED PRIVATE KEY-----")
				if [ "$result" = "-----END ENCRYPTED PRIVATE KEY-----" ]; then
					result=`$opensslinst asn1parse -inform PEM -offset 50 -in "$privkey" | head -n 1 | cut -d':' -f4 | tr '[:lower:]' '[:upper:]'`
					keytype="PRIVATE-KEY $result"
				else
					keytype="INVALID"
				fi
				;;
			"PuTTY-User-Key-File-2: ssh-rsa" | "PuTTY-User-Key-File-3: ssh-rsa")
				encrypted=`grep '^Encryption: ' "$privkey" | cut -d ' ' -f2- | tr '[:lower:]' '[:upper:]'`
				result=`echo "$result" | grep '^Private-MAC: ' | cut -d ' ' -f2-`
				if [ "$result" = "" ]; then
					keytype="INVALID"
				else
					result=`echo "$keysignature" | sed 's|^PuTTY-User-Key-File-|V|' | sed 's|: ssh-rsa$||'`
					keytype="PUTTY-PRIVATE-KEY-$result $encrypted"
				fi
				;;
			*)
				if [ "$keysignature" = "$result" ]; then
					# Just one line in file
					result=`echo "$keysignature" | grep '^ssh-rsa '`
					if [ "$result" != "" ]; then
						# Line begins with ssh-rsa
						result=`echo "$keysignature" | cut -d' ' -f2`
						if [ "$result" != "" ]; then
							# We have a key behind ssh-rsa signature
							keytype="SSH-RSA-PUBLIC-KEY"
						else
							keytype="INVALID"
						fi
					fi
				else
					keytype="UNKNOWN"
				fi
		esac
	fi
	
	echo "$keytype"
}

# Get the fingerprint from public api key or private key
function GetFingerprint() {
	local privkey=${1}
	local pp=${2}
	
	# Preset
	local fp=""
	local addparams=""
	local encrypted=""
	local result=""
	local stat=1
	
	if [ -r "$privkey" ]; then
		result=`KeyType "$privkey"`
		encrypted=`echo "$result" | cut -d ' ' -f2`
		result=`echo "$result" | cut -d ' ' -f1`
		
		if [ "$result" = "PUBLIC-KEY" ]; then
			$opensslinst pkey -pubin -in "$privkey" -pubout -outform DER -out "$scratchfile" 2>/dev/null
			stat=$?
		else
			if [ "$encrypted" = "NONE" ]; then
				$opensslinst rsa -inform PEM -in "$privkey" -pubout -outform DER -out "$scratchfile" 2>/dev/null
				stat=$?
			else
				if [ "$pp" != "" ]; then
					$opensslinst rsa -inform PEM -in "$privkey" -passin "pass:$pp" -pubout -outform DER -out "$scratchfile" 2>/dev/null
					stat=$?
				fi
			fi
		fi
		
		if [ $stat -eq 0 ]; then
			if [ -f "$scratchfile" ]; then
				if [ "$fipsenabled" = "true" ]; then
					fp=`cat "$scratchfile" | md5sum | cut -d' ' -f1 | sed 's|..|\:&|g' | cut -d':' -f2-`
				else
					fp=`cat "$scratchfile" | $opensslinst md5 -c 2>/dev/null | cut -d ' ' -f2`	# Old: sed 's|(stdin)= ||g'
				fi
			fi

		fi
		
		# Cleanup
		if [ -f "$scratchfile" ]; then
			rm -f "$scratchfile"
		fi
	fi
	
	# Return result
	echo "$fp"
}

# Check if cipher is valid
function CheckCipher() {
	local cipher=${1}

	# Preset
	if [ "$cipher" != "" ]; then
		# lowercase cipher string
		cipher=`echo "$cipher" | tr '[:upper:]' '[:lower:]' | sed 's|-cbc$||' | sed 's|-ctr$||' | sed 's|des-ede3|des3|' | sed 's|-||'`
	fi
	
	case "$cipher" in
		des | des3)
			cipher="$cipher"
			;;
		aes128 | aes192 | aes256)
			cipher="$cipher"
			;;
		idea | seed)
			cipher="$cipher"
			;;
		camellia128 | camellia192 | camellia256)
			cipher="$cipher"
			;;
		*)
			# Default
			cipher="des3"
	esac
	
	echo "$cipher"
}

# Change private key passphrase
function ChangeRSAPassphrase() {
	local useputty=${1}
	local privkey=${2}
	local oldpp=${3}
	local newpp=${4}
	local cipher=${5}

	# Preset
	local stat=1
	local result=""
	local encrypted=""
	if [ "$useputty" != "" ]; then
		# lowercase useputty string
		useputty=`echo "$useputty" | tr '[:upper:]' '[:lower:]'`
	fi

	if [ -r "$privkey" ]; then
		touch $scratchfile
		chmod 600 $scratchfile
		
		if [ "$useputty" = "true" ]; then
			echo "" > ${scratchfile}.empty
			
			if [ "$oldpp" != "" ]; then
				# Create decrypted key
				mv -f "$privkey" "${privkey}.enc"
				echo "$oldpp" > $scratchfile
				$puttygeninst "${privkey}.enc" -P --old-passphrase $scratchfile --new-passphrase ${scratchfile}.empty \
					-O private-openssh -o "$privkey" 2>/dev/null
				stat=$?
				
				if [ $stat -gt 0 ]; then
					mv -f "${privkey}.enc" "$privkey"
				fi
			fi
			
			if [ "$newpp" != "" ]; then
				echo "$newpp" > $scratchfile
				$puttygeninst "$privkey" -P --old-passphrase $scratchfile --new-passphrase $scratchfile -O private-openssh \
					-o "${privkey}.enc" 2>/dev/null
				stat=$?
				
				if [ $stat -eq 0 ]; then
					# Encrypt private key
					ChangeRSAPassphrase "false" "$privkey" "" "$newpp" "des3"
					stat=$?
				fi
			else
				if [ -f "${privkey}.enc" ]; then
					rm -f "${privkey}.enc"
				fi
			fi
			
			rm -f ${scratchfile}.empty
		else
			if [ "$newpp" = "" ]; then
				$opensslinst rsa -inform PEM -in "$privkey" -passin "pass:$oldpp" -outform PEM -out $scratchfile \
					-passout "pass:$newpp" 2>/dev/null
				stat=$?
			else
				cipher=`CheckCipher "$cipher"`
				$opensslinst rsa -$cipher -inform PEM -in "$privkey" -passin "pass:$oldpp" -outform PEM -out $scratchfile \
					-passout "pass:$newpp" 2>/dev/null
				stat=$?
			fi
			
			if [ $stat -eq 0 ]; then
				mv -f "$scratchfile" "$privkey"
			fi
		fi
		
		# Cleanup
		if [ -f "$scratchfile" ]; then
			rm -f $scratchfile
		fi
	fi
	
	return $stat
}

# Create putty private keys
function CreatePrivatePuttyKeys() {
	local username=${1}
	local privkey=${2}
	local pp=${3}
	
	# Preset
	local stat=1
	
	# Take encrypted putty key if it exists
	if [ -r "${privkey}.enc" ]; then
		privkey="${privkey}.enc"
	fi
	
	if [ -r "$privkey" ]; then
		touch $scratchfile
		chmod 600 $scratchfile
		echo "$pp" > $scratchfile
		
		if [ "$puttygenok" = "ok" ]; then
			$puttygeninst "$privkey" -P --old-passphrase $scratchfile --new-passphrase $scratchfile -C "$username" \
				--ppk-param version=2 -O private -o "${puttyfile}.ppk" 2>/dev/null
			stat=$?
			
			if [ $stat -eq 0 ]; then
				$puttygeninst -q "$privkey" -P --old-passphrase $scratchfile --new-passphrase $scratchfile -C "$username" \
					--ppk-param version=3 -O private -o "${puttyfile}.pp3" 2>/dev/null
				stat=$?
			fi
		else
			$puttygeninst -q "$privkey" -P --old-passphrase $scratchfile --new-passphrase $scratchfile -C "$username" \
				-O private -o "${puttyfile}.ppk" 2>/dev/null
			stat=$?
		fi
		
		rm -f $scratchfile
	fi
	
	return $stat
}

# Generate public key in PEM format
function CreatePublicApiKey() {
	local privkey=${1}
	local pp=${2}

	# Preset
	local stat=1
	
	if [ -r "$privkey" ]; then
		$opensslinst rsa -inform PEM -in "$privkey" -passin "pass:$pp" -pubout -outform PEM -out "${apifile}.pem" 2>/dev/null
		stat=$?
	fi
	
	return $stat
}

# Create private key with PKCS#8 format
function CreatePrivatePkcs8Key() {
	local privkey=${1}
	local pp=${2}

	# Preset
	local stat=1

	if [ -r "$privkey" ]; then
		touch "${keyfile}.pk8"
		chmod 600 "${keyfile}.pk8"
		if [ "$pp" != "" ]; then
			$opensslinst pkcs8 -topk8 -v2 aes-256-cbc -inform PEM -in "$privkey" -passin "pass:$pp" -passout "pass:$pp" \
				-outform PEM -out "${privkey}.pk8" 2>/dev/null
			stat=$?
		else
			$opensslinst pkcs8 -topk8 -inform PEM -in "$privkey" -outform PEM -nocrypt -out "${privkey}.pk8" 2>/dev/null
			stat=$?
		fi
		
		if [ $stat -gt 0 ]; then
			rm -f "${privkey}.pk8"
		else
			echo "OCI_API_KEY" >> "${privkey}.pk8"
		fi
	fi
	
	return $stat
}

# Create SSH-RSA public key from private key
function CreateRSAPublicKey {
	local useputty=${1}
	local username=${2}
	local privkey=${3}
	local pp=${4}

	# Preset
	local stat=1
	local result=""
	if [ "$useputty" != "" ]; then
		# lowercase useputty string
		useputty=`echo "$useputty" | tr '[:upper:]' '[:lower:]'`
	fi
	
	if [ "$username" != "" -a "$privkey" != "" ]; then
		if [ "$useputty" = "true" ]; then
			touch $scratchfile
			chmod 600 $scratchfile
			echo "$pp" > $scratchfile
			
			$puttygeninst -q "$privkey" -P --old-passphrase $scratchfile --new-passphrase $scratchfile -O public-openssh \
				-C "$username" -o "${privkey}.pub" 2>/dev/null
			stat=$?
			
			rm -f $scratchfile
		else
			result=`$keygeninst -y -f "$privkey" -P "$pp" 2>/dev/null`
			stat=$?
			
			if [ $stat -eq 0 ]; then
				echo "$result $username" > "${privkey}.pub"
			fi
		fi
	fi
	
	return $stat
}

# Create private and public RSA keys - If encrypted: AES-128-CBC (ssh-keygen) or DES-EDE3-CBC (puttygen)
function CreateRSAKeys() {
	local useputty=${1}
	local username=${2}
	local privkey=${3}
	local pp=${4}

	# Preset
	local stat=1
	if [ "$useputty" != "" ]; then
		# lowercase useputty string
		useputty=`echo "$useputty" | tr '[:upper:]' '[:lower:]'`
	fi
	
	if [ "$username" != "" -a "$privkey" != "" ]; then
		if [ ! -r "$privkey" -a ! -r "${privkey}.pub" ]; then
			if [ "$useputty" = "true" ]; then
				# Create standard rsa private key with puttygen
				touch $scratchfile
				chmod 600 $scratchfile
				echo "" > $scratchfile
				
				$puttygeninst -q -t rsa -b $bits -P --old-passphrase $scratchfile --new-passphrase $scratchfile -O private-openssh \
					-C "$username" -o "$privkey" 2>/dev/null
				stat=$?
				
				if [ $stat -eq 0 ]; then
					# Create ssh-rsa public key
					CreateRSAPublicKey "false" "$username" "$privkey" ""
					stat=$?
					
					if [ $stat -eq 0 -a "$pp" != "" ]; then
						# Create encrypted RSA key with puttygen
						echo "$pp" > $scratchfile
						$puttygeninst -q "$privkey" -P --old-passphrase $scratchfile --new-passphrase $scratchfile -O private-openssh \
							-C "$username" -o "${privkey}.enc" 2>/dev/null
						stat=$?
					fi
				fi
				
				rm -f $scratchfile
			else
				# Create unencrypted keys with ssh-keygen
				$keygeninst -q -t rsa -N "" -b $bits -C "$username" -m PEM -f "$privkey" 2>/dev/null		# PEM not pem or PKCS8
				stat=$?
			fi
			
			if [ $stat -eq 0 -a "$pp" != "" ]; then
				# Encrypt private key
				ChangeRSAPassphrase "false" "$privkey" "" "$pp" "des3"
				stat=$?
			fi
		fi
	fi

	return $stat
}

### Main

username=${1}
passphrase=${2}

if [ "$username" = "" ]; then
	errormsg 1 "Please specify a username e.g. 'opc@hostname'."
	exit 1
fi

neededputtygenversion="0.76"
puttygenok="no"

need="ssh-keygen"
keygeninst=`check-version "$need"`
stat=$?
if [ $stat -gt 0 ]; then
	errormsg 2 "No '$need' in PATH." "$PATH"
	exit 2
fi

need="openssl"
opensslinst=`check-version "$need"`
stat=$?
if [ $stat -gt 0 ]; then
	errormsg 2 "No '$need' in PATH." "$PATH"
	exit 2
else
	osslvers=`openssl version | head -n 1 | cut -d' ' -f2`
	osslmain=`echo "$osslvers" | cut -d'.' -f1`
fi

need="puttygen"
result=`check-version "$need" $neededputtygenversion`
stat=$?
if [ $stat -gt 0 ]; then
	# errormsg 2 "No '$need' in PATH. Please install it e.g. for Oracle / Rad Hat Linux: 'sudo yum install putty'" "$PATH"
	# exit 2
	puttygeninst=""
else
	# puttygen installed - check version
	puttygeninst=`echo "$result" | cut -d$'\t' -f1`
	puttygenversion=`echo "$result" | cut -d$'\t' -f2`
	puttygenok=`echo "$result" | cut -d$'\t' -f3`
fi

# Define scratch
pid="$$"                                                    # Get the process id from current shell
tmpdir="/tmp"                                               # Temporary directory
timestamp=`date '+%y%m%d%H%M%S'`                            # Current date and time
scratchfile="${tmpdir}/createkeys.${timestamp}.${pid}.tmp"  # Temporary file

bits=3072	# 4096  # Lenght of the key: 2048 would be less secure
keyname="id_rsa"
puttyname="id_putty"
apiname="api_pub"
keyfile="${username}/$keyname"
puttyfile="${username}/$puttyname"
apifile="${username}/$apiname"
infofile="${username}/info.txt"
progdir=`dirname $0`

# Check if we are on a fips enabled platform
result=`sysctl crypto.fips_enabled 2>/dev/null`
if [ "$result" = "crypto.fips_enabled = 1" ]; then
	fipsenabled="true"
else
	fipsenabled="false"
fi

#files=`ls`
#for file in $files; do
#	printf "${file}: "
#	KeyType "$file"
#done
#exit

# Change current directory to temporary dir
# cd "$progdir"
cd "$tmpdir"

if [ -d "$username" ]; then
	errormsg 3 "User folder '$username' already exists."
	exit 3
else
	# Create folder in keys directory
	mkdir -p "$username"
	stat=$?

	if [ $stat -gt 0 -o ! -d "$username" ]; then
		errormsg 4 "Could not create user folder '$username'."
		exit 4
	else
		if [ "$passphrase" != "" ]; then
			# Check length of string must be at least 5 chars
			result=`printf "${#passphrase}"`
			if [ $result -lt 5 ]; then
				errormsg 5 "Passphrase has less then 5 chars." "Passphrase: '$passphrase'"
				rmdir "$username"
				exit 5
			fi
		fi
		
		CreateRSAKeys "$fipsenabled" "$username" "$keyfile" "$passphrase"
		stat=$?

		if [ $stat -gt 0 ]; then
			errormsg 6 "Unable to create standard rsa private key and standard rsa public key." "Code: $stat"
			rm -fR "$username"
			exit 6
		else
			if [ "$puttygeninst" != "" ]; then
				CreatePrivatePuttyKeys "$username" "$keyfile" "$passphrase"
				stat=$?
			fi
		fi
		
		if [ $stat -gt 0 ]; then
			errormsg 7 "Unable to create putty private key." "Code: $stat"
			rm -fR "$username"
			exit 7
		else
			CreatePrivatePkcs8Key "$keyfile" "$passphrase"
			stat=$?
		fi

		if [ $stat -gt 0 ]; then
			errormsg 8 "Unable to create PKCS#8 private key." "Code: $stat"
			rm -fR "$username"
			exit 8
		else
			CreatePublicApiKey "$keyfile" "$passphrase"
			stat=$?
		fi
		
		if [ $stat -gt 0 ]; then
			errormsg 9 "Unable to create public key in pem format for API access." "Code: $stat"
			rm -fR "$username"
			exit 9
		else
			# Get Fingerprint
			if [ -r "${apifile}.pem" ]; then
				fp=`GetFingerprint "${apifile}.pem"`
				stat=$?
			else
				fp=`GetFingerprint "$keyfile" "$passphrase"`
				stat=$?
			fi
			
			if [ $stat -gt 0 ]; then
				errormsg 10 "Unable to get fingerprint." "Code: $stat"
				rm -fR "$username" $scratchfile
				exit 10
			else
				# Move encrypted rsa private key
				if [ -f "${keyfile}.enc" ]; then
					mv -f "${keyfile}.enc" "$keyfile"
				fi

				# Change filerights
				touch "$infofile"
				chmod 600 "$infofile"
				
				# Create the info file
				if [ "$passphrase" != "" ]; then
					printf "                Passphrase: '%s'\n\n" "$passphrase" > "$infofile"
				else
					printf "                Passphrase: Unused\n\n" > "$infofile"
				fi

				if [ -f "${keyfile}.pub" ]; then
					printf "     Public Key file (ssh): '%s'\n\n" "${keyname}.pub" >> "$infofile"
				fi
				if [ -f "$keyfile" ]; then
					printf "    Private Key file (ssh): '%s'\n" "$keyname" >> "$infofile"
				fi
				if [ -f "${keyfile}.pk8" ]; then
					printf " Private Key file (PKCS#8): '%s'\n" "${keyname}.pk8" >> "$infofile"
				fi

				echo "" >> "$infofile"

				if [ "$puttygeninst" != "" ]; then
					if [ -f "${puttyfile}.ppk" ]; then
						printf "  Private Key file (putty): '%s' (older format v2)\n" "${puttyname}.ppk" >> "$infofile"
					fi
					if [ -f "${puttyfile}.pp3" ]; then
						printf "  Private Key file (putty): '%s' (newer format v3)\n" "${puttyname}.pp3" >> "$infofile"
					fi

					echo "" >> "$infofile"
				fi

				if [ -f "${apifile}.pem" ]; then
					printf " Public Key file (OCI-API): '%s'\n" "${apiname}.pem" >> "$infofile"
					printf "               Fingerprint: '%s'\n" "$fp" >> "$infofile"
				fi
			fi
		fi

		if [ $stat -eq 0 ]; then
			# Zip the keys directory
			zip -q -r "${username}.zip" "$username" -x \*.DS_Store\*
			stat=$?
			
			if [ "$LOCALCALL" = "true" ]; then
				if [ $stat -eq 0 ]; then
					# Creation was succcessful - Display success message
					echo "Created keys in '${tmpdir}/${username}.zip'. Please use 'unzip' to extract files."
				else
					errormsg 11 "Unable to zip keys." "Code: $stat"
					rm -fR "$username" $scratchfile
					exit 11
				fi
			fi
		fi
		
		# Cleanup
		rm -fR "$username" $scratchfile
	fi
fi


