github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/github/secret.go (about) 1 package github 2 3 import ( 4 "crypto/rand" 5 "encoding/base64" 6 7 "github.com/google/go-github/v45/github" 8 "golang.org/x/crypto/nacl/box" 9 10 "github.com/SAP/jenkins-library/pkg/log" 11 ) 12 13 // CreateEncryptedSecret creates an encrypted secret using a public key from a GitHub repository, which can be sent through the GitHub API 14 // https://github.com/google/go-github/blob/master/example/newreposecretwithxcrypto/main.go 15 func CreateEncryptedSecret(secretName, secretValue string, publicKey *github.PublicKey) (*github.EncryptedSecret, error) { 16 decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey.GetKey()) 17 if err != nil { 18 log.Entry().Warn("Could not decode public key from base64") 19 return nil, err 20 } 21 22 var boxKey [32]byte 23 copy(boxKey[:], decodedPublicKey) 24 secretBytes := []byte(secretValue) 25 encryptedSecretBytes, err := box.SealAnonymous([]byte{}, secretBytes, &boxKey, rand.Reader) 26 if err != nil { 27 log.Entry().Warn("Could not encrypt secret using public key") 28 return nil, err 29 } 30 31 encryptedSecretString := base64.StdEncoding.EncodeToString(encryptedSecretBytes) 32 33 githubSecret := &github.EncryptedSecret{ 34 Name: secretName, 35 KeyID: publicKey.GetKeyID(), 36 EncryptedValue: encryptedSecretString, 37 } 38 return githubSecret, nil 39 }