func writeKeyToFile(keyBytes []byte, saveFileTo string) error {
	err := ioutil.WriteFile(saveFileTo, keyBytes, 0600)
	if err != nil {
		return err
	}
	log.Printf("Key saved to: %s", saveFileTo)
	return nil
}
writeKeyToFile writes keys to a file
package main
import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/md5"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/hex"
	"encoding/pem"
	"flag"
	"fmt"
	"golang.org/x/crypto/ssh"
	"io"
	"io/ioutil"
	"log"
	"os"
)
func main() {
	var (
		pkFile string
		pkFileB64 string
		pubFile string
		passphrase string
		bitSize *int
	)
	flag.StringVar(&pkFile, "pkfile", "/dev/null", "PK file path")
	flag.StringVar(&pubFile, "pubfile", "/dev/null", "PUB file path")
	flag.StringVar(&pkFileB64, "pkfile-b64", "/dev/null", "PK B64 file path")
	flag.StringVar(&passphrase, "pass", "/dev/null", "Passphrase for PK")
	bitSize = flag.Int("bits", 4096, "RSA bit size (default: 4096)")
	flag.Parse()
	fmt.Printf("[+] Generating PK\n")
	privateKey, err := generatePrivateKey(*bitSize)
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Printf("[+] Generating PUB from PK (SSH pub)\n")
	publicKeyBytes, err := generatePublicKey(&privateKey.PublicKey)
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Printf("[+] Encoding PK to PEM\n")
	privateKeyBytes := encodePrivateKeyToPEM(privateKey)
	fmt.Printf("[+] Writing PK to file: %s \n", pkFile)
	err = writeKeyToFile(privateKeyBytes, pkFile)
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Printf("[+] Writing PUB to file: %s \n", pubFile)
	err = writeKeyToFile(publicKeyBytes, pubFile)
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Printf("[+] Encrypting PK with passphrase (transmission/storage)\n")
	ciphertext := encBytes(privateKeyBytes, passphrase)
	fmt.Printf("[+] Encoding PK B64 armored PK (transmission)\n")
	ciphertextB64 := base64.StdEncoding.EncodeToString([]byte(ciphertext))
	fmt.Printf("[+] Saving B64 armored PK to file: %s\n", pkFileB64)
	writeKeyToFile([]byte(ciphertextB64), pkFileB64)
}
func generatePrivateKey(bitSize int) (*rsa.PrivateKey, error) {
	privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
	if err != nil {
		return nil, err
	}
	err = privateKey.Validate()
	if err != nil {
		return nil, err
	}
	log.Println("Private Key generated")
	return privateKey, nil
}
func encodePrivateKeyToPEM(privateKey *rsa.PrivateKey) []byte {
	privDER := x509.MarshalPKCS1PrivateKey(privateKey)
	privBlock := pem.Block{
		Type:    "RSA PRIVATE KEY",
		Headers: nil,
		Bytes:   privDER,
	}
	privatePEM := pem.EncodeToMemory(&privBlock)
	return privatePEM
}
func generatePublicKey(privatekey *rsa.PublicKey) ([]byte, error) {
	publicRsaKey, err := ssh.NewPublicKey(privatekey)
	if err != nil {
		return nil, err
	}
	pubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)
	log.Println("Public key generated")
	return pubKeyBytes, nil
}