woodpecker/pkg/yaml/secure/secure.go

47 lines
1.2 KiB
Go
Raw Normal View History

package secure
import (
"crypto/rsa"
2015-09-07 19:13:27 +00:00
"crypto/x509"
"encoding/pem"
2015-09-07 19:50:21 +00:00
"github.com/drone/drone/Godeps/_workspace/src/github.com/square/go-jose"
)
2015-09-07 19:13:27 +00:00
// Encrypt encrypts a secret string.
func Encrypt(in, privKey string) (string, error) {
rsaPrivKey, err := decodePrivateKey(privKey)
if err != nil {
2015-09-07 19:13:27 +00:00
return "", err
}
2015-09-07 19:13:27 +00:00
return encrypt(in, &rsaPrivKey.PublicKey)
}
2015-09-07 19:13:27 +00:00
// decodePrivateKey is a helper function that unmarshals a PEM
// bytes to an RSA Private Key
func decodePrivateKey(privateKey string) (*rsa.PrivateKey, error) {
derBlock, _ := pem.Decode([]byte(privateKey))
return x509.ParsePKCS1PrivateKey(derBlock.Bytes)
}
2015-09-07 19:13:27 +00:00
// encrypt encrypts a plaintext variable using JOSE with
// RSA_OAEP and A128GCM algorithms.
func encrypt(text string, pubKey *rsa.PublicKey) (string, error) {
var encrypted string
var plaintext = []byte(text)
2015-08-19 14:11:24 +00:00
2015-09-07 19:13:27 +00:00
// Creates a new encrypter using defaults
encrypter, err := jose.NewEncrypter(jose.RSA_OAEP, jose.A128GCM, pubKey)
if err != nil {
return encrypted, err
}
2015-09-07 19:13:27 +00:00
// Encrypts the plaintext value and serializes
// as a JOSE string.
object, err := encrypter.Encrypt(plaintext)
if err != nil {
return encrypted, err
}
return object.CompactSerialize()
2015-08-19 14:11:24 +00:00
}