pgp-key-management/keys/generate-keys.go

124 lines
2.0 KiB
Go

package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"path/filepath"
//"io"
//"github.com/ProtonMail/go-crypto/openpgp/armor"
)
func main() {
err := run()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
names := []string{
"internal-A",
"internal-B",
"customer-A",
"customer-B",
"customer-C",
}
for _, name := range names {
fmt.Println("Generating keypair for", name)
err := keypair(name)
if err != nil {
return err
}
}
return nil
}
const (
keyDir string = "./"
)
func keypair(name string) error {
const bitSize int = 4096
key, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
return err
}
pub := key.Public()
keyPem := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
},
)
pubPem := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: x509.MarshalPKCS1PublicKey(pub.(*rsa.PublicKey)),
},
)
err = os.WriteFile(filepath.Join(keyDir, "public", name+".pem"), pubPem, 0644)
if err != nil {
return err
}
err = os.WriteFile(filepath.Join(keyDir, "private", name+".pem"), keyPem, 0644)
if err != nil {
return err
}
pubDerRaw, err := x509.MarshalPKIXPublicKey(pub.(*rsa.PublicKey))
if err != nil {
return err
}
pubDer := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: pubDerRaw,
},
)
err = os.WriteFile(filepath.Join(keyDir, "public", name+".asc"), pubDer, 0644)
if err != nil {
return err
}
//err = encodeToArmor(filepath.Join(keyDir, "public", name+".asc"), pub.(*rsa.PublicKey))
//if err != nil {
// return err
//}
return nil
}
//func encodeToArmor(filename string, key *rsa.PublicKey) error {
// outfile, err := os.Create(filename)
// if err != nil {
// return err
// }
// defer outfile.Close()
//
// writer, err := armor.Encode(outfile, "PGP PUBLIC KEY", nil)
// if err != nil {
// return err
// }
// defer writer.Close()
//
// _, err = writer.Write(key.)
// return err
//}