Skip to content

Commit

Permalink
add Encrypt method to ClientKey
Browse files Browse the repository at this point in the history
  • Loading branch information
joeshaw committed Feb 7, 2023
1 parent 3861879 commit 5a09a2f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
16 changes: 16 additions & 0 deletions fastly/secret_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@ package fastly
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
"encoding/json"
"fmt"
"strconv"
"time"

"golang.org/x/crypto/nacl/box"
)

// Secret Store.
Expand Down Expand Up @@ -408,6 +412,18 @@ func (ck *ClientKey) ValidateSignature(signingKey ed25519.PublicKey) bool {
return ed25519.Verify(signingKey, ck.PublicKey, ck.Signature)
}

// Encrypt uses the client key to encrypt the provided plaintext
// using a libsodium-compatible sealed box.
// https://pkg.go.dev/golang.org/x/crypto/nacl/box#SealAnonymous
// https://libsodium.gitbook.io/doc/public-key_cryptography/sealed_boxes
func (ck *ClientKey) Encrypt(plaintext []byte) ([]byte, error) {
if len(ck.PublicKey) != 32 {
return nil, fmt.Errorf("invalid public key length %d", len(ck.PublicKey))
}

return box.SealAnonymous(nil, plaintext, (*[32]byte)(ck.PublicKey), rand.Reader)
}

// CreateClientKey creates a new time-limited client key for locally
// encrypting secrets before uploading them to the Fastly API.
func (c *Client) CreateClientKey() (*ClientKey, error) {
Expand Down
5 changes: 1 addition & 4 deletions fastly/secret_store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,9 @@ package fastly
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
"fmt"
"sort"
"testing"

"golang.org/x/crypto/nacl/box"
)

func TestClient_CreateSecretStore(t *testing.T) {
Expand Down Expand Up @@ -221,7 +218,7 @@ func TestClient_CreateSecret_clientEncryption(t *testing.T) {
t.Fatalf("signature validation failed")
}

enc, err := box.SealAnonymous(nil, []byte("secretum servare"), (*[32]byte)(ck.PublicKey), rand.Reader)
enc, err := ck.Encrypt([]byte("secretum servare"))
if err != nil {
t.Fatalf("error locally encrypting secret: %v", err)
}
Expand Down

0 comments on commit 5a09a2f

Please sign in to comment.