Skip to content

Commit

Permalink
Read multiline signing private key from the config and remove base64 …
Browse files Browse the repository at this point in the history
…encoding support
  • Loading branch information
erickskrauch committed Mar 5, 2024
1 parent 436ff7c commit 528b131
Showing 1 changed file with 19 additions and 25 deletions.
44 changes: 19 additions & 25 deletions internal/di/security.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"strings"
"errors"
"log/slog"

signerClient "ely.by/chrly/internal/client/signer"
"ely.by/chrly/internal/client/signer"
"ely.by/chrly/internal/http"
"ely.by/chrly/internal/security"

Expand All @@ -19,47 +19,41 @@ import (
var securityDiOptions = di.Options(
di.Provide(newSigner,
di.As(new(http.Signer)),
di.As(new(signerClient.Signer)),
di.As(new(signer.Signer)),
),
di.Provide(newSignerService),
)

func newSigner(config *viper.Viper) (*security.Signer, error) {
var privateKey *rsa.PrivateKey
var err error

keyStr := config.GetString("chrly.signing.key")
if keyStr == "" {
// TODO: log a message about the generated signing key and the way to specify it permanently
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
privateKey, err = rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}

return security.NewSigner(privateKey), nil
}
slog.Warn("A private signing key has been generated. To make it permanent, specify the valid RSA private key in the config parameter chrly.signing.key")
} else {
keyBytes := []byte(keyStr)
rawPem, _ := pem.Decode(keyBytes)
if rawPem == nil {
return nil, errors.New("unable to decode pem key")
}

var keyBytes []byte
if strings.HasPrefix(keyStr, "base64:") {
base64Value := keyStr[7:]
decodedKey, err := base64.URLEncoding.DecodeString(base64Value)
privateKey, err = x509.ParsePKCS1PrivateKey(rawPem.Bytes)
if err != nil {
return nil, err
}

keyBytes = decodedKey
} else {
keyBytes = []byte(keyStr)
}

rawPem, _ := pem.Decode(keyBytes)
privateKey, err := x509.ParsePKCS1PrivateKey(rawPem.Bytes)
if err != nil {
return nil, err
}

return security.NewSigner(privateKey), nil
}

func newSignerService(signer signerClient.Signer) http.SignerService {
return &signerClient.LocalSigner{
Signer: signer,
func newSignerService(s signer.Signer) http.SignerService {
return &signer.LocalSigner{
Signer: s,
}
}

0 comments on commit 528b131

Please sign in to comment.