github.com/tooploox/oya@v0.0.21-0.20230524103240-1cda1861aad6/pkg/secrets/pgp.go (about)

     1  package secrets
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os/exec"
     6  
     7  	mig "github.com/mozilla/mig/pgp"
     8  	"gopkg.in/yaml.v2"
     9  )
    10  
    11  func generatePGPKeyPair(email, name, desc string) (KeyPair, error) {
    12  	pubkey, privkey, fp, err := mig.GenerateKeyPair(name, desc, email)
    13  	if err != nil {
    14  		return KeyPair{}, err
    15  	}
    16  	return KeyPair{
    17  		Public:      string(pubkey),
    18  		Private:     string(privkey),
    19  		Fingerprint: string(fp),
    20  	}, nil
    21  }
    22  
    23  type SopsYaml struct {
    24  	CreationRules []CreationRule `yaml:"creation_rules"`
    25  }
    26  
    27  type CreationRule struct {
    28  	PGP string `yaml:"pgp"`
    29  }
    30  
    31  func GeneratePGPSopsYaml(keyPair KeyPair) error {
    32  	sops := SopsYaml{
    33  		CreationRules: []CreationRule{
    34  			{PGP: keyPair.Fingerprint},
    35  		},
    36  	}
    37  
    38  	content, err := yaml.Marshal(sops)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	return ioutil.WriteFile(".sops.yaml", content, 0644)
    43  }
    44  
    45  func LoadPGPSopsYaml() (SopsYaml, error) {
    46  	contents, err := ioutil.ReadFile(".sops.yaml")
    47  	if err != nil {
    48  		return SopsYaml{}, err
    49  	}
    50  
    51  	var sops SopsYaml
    52  	return sops, yaml.Unmarshal(contents, &sops)
    53  }
    54  
    55  func ImportPGPKeypair(keyPair KeyPair) error {
    56  	cmd := exec.Command("gpg", "--import")
    57  	in, err := cmd.StdinPipe()
    58  	if err != nil {
    59  		return err
    60  	}
    61  	if err = cmd.Start(); err != nil {
    62  		return err
    63  	}
    64  	if _, err := in.Write(([]byte)(keyPair.Private)); err != nil {
    65  		return err
    66  	}
    67  	in.Close()
    68  	return cmd.Wait()
    69  }
    70  
    71  func RemovePGPKeypairs(fingerprints []string) error {
    72  	for _, fingerprint := range fingerprints {
    73  		if err := exec.Command("gpg", "--batch", "--yes", "--delete-secret-keys", fingerprint).Run(); err != nil {
    74  			return err
    75  		}
    76  		if err := exec.Command("gpg", "--batch", "--yes", "--delete-key", fingerprint).Run(); err != nil {
    77  			return err
    78  		}
    79  	}
    80  	return nil
    81  }