// Command client is a self-contained example of a Go service calling the KMS. // // It uses only the Go standard library, so you can copy this file into any project. // (Inside this repository you can also use the kmsclient package for request signing.) // // One-time setup, on the machine that runs your service: // // (umask 077; openssl genpkey -algorithm ed25519 -out client.key) # private key: never leaves this machine // openssl pkey -in client.key -pubout -out client.pub # public key: give it to the KMS admin // // The admin registers client.pub (Web UI → "API clients", or POST /v1/clients), then grants // this client operations on a key (panel "Izin", or PUT /v1/clients/{id}/grants/{key_id}). // // Run: // // KMS_URL=http://localhost:8080 KMS_CLIENT_ID=cli_... KMS_CLIENT_KEY_FILE=client.key \ // KMS_KEY_ID=key_... go run ./examples/client // // The demo needs the "encrypt", "decrypt" and "datakey" operations on KMS_KEY_ID. package main import ( "bytes" "context" "crypto" "crypto/aes" "crypto/cipher" "crypto/ecdsa" "crypto/ed25519" "crypto/elliptic" "crypto/rand" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/hex" "encoding/json" "encoding/pem" "errors" "fmt" "io" "log" "net/http" "net/url" "os" "strconv" "strings" "time" ) // --------------------------------------------------------------------------- // KMS client // --------------------------------------------------------------------------- // Client calls the KMS API as one registered API client. Every request is signed with the // client's private key (Ed25519 or ECDSA P-256); the KMS holds only the public key. type Client struct { BaseURL string // e.g. "https://kms.internal" ClientID string // "cli_..." from the KMS admin Key crypto.Signer // ed25519.PrivateKey or *ecdsa.PrivateKey (P-256) HTTP *http.Client } // NewClient parses a PKCS#8 PEM private key (as written by `openssl genpkey`). func NewClient(baseURL, clientID string, privateKeyPEM []byte) (*Client, error) { block, _ := pem.Decode(privateKeyPEM) if block == nil || block.Type != "PRIVATE KEY" { return nil, errors.New(`expected a PKCS#8 "PRIVATE KEY" PEM block`) } parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("parse private key: %w", err) } var key crypto.Signer switch k := parsed.(type) { case ed25519.PrivateKey: key = k case *ecdsa.PrivateKey: if k.Curve != elliptic.P256() { return nil, errors.New("ECDSA key must use P-256") } key = k default: return nil, fmt.Errorf("unsupported key type %T (use Ed25519 or ECDSA P-256)", parsed) } return &Client{ BaseURL: strings.TrimRight(baseURL, "/"), ClientID: clientID, Key: key, HTTP: &http.Client{Timeout: 10 * time.Second}, }, nil } // APIError is a non-2xx answer from the KMS. type APIError struct { Status int // HTTP status code Message string // the "error" field of the response } func (e *APIError) Error() string { return fmt.Sprintf("kms: %d %s", e.Status, e.Message) } // IsForbidden reports whether err means this client lacks a grant for the key/operation // (or the key does not exist: the KMS does not tell the two apart). func IsForbidden(err error) bool { var e *APIError return errors.As(err, &e) && e.Status == http.StatusForbidden } // Key is key metadata. Key material never leaves the KMS. type Key struct { ID string `json:"id"` Name string `json:"name"` State string `json:"state"` CurrentVersion int `json:"current_version"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } // GetKey returns metadata of a key. Needs any grant on the key. func (c *Client) GetKey(ctx context.Context, keyID string) (Key, error) { var k Key err := c.do(ctx, http.MethodGet, "/v1/keys/"+url.PathEscape(keyID), nil, &k) return k, err } // Encrypt encrypts plaintext (max ~48 KiB) under the key's current version. aad is optional // context (e.g. "tenant:42") that must be given again, byte for byte, to decrypt. // Needs the "encrypt" grant. func (c *Client) Encrypt(ctx context.Context, keyID string, plaintext, aad []byte) (ciphertext []byte, keyVersion int, err error) { var out struct { Ciphertext []byte `json:"ciphertext"` KeyVersion int `json:"key_version"` } err = c.do(ctx, http.MethodPost, "/v1/keys/"+url.PathEscape(keyID)+"/encrypt", map[string][]byte{"plaintext": plaintext, "aad": aad}, &out) return out.Ciphertext, out.KeyVersion, err } // Decrypt returns the plaintext of a ciphertext from Encrypt or GenerateDataKey. // Needs the "decrypt" grant. func (c *Client) Decrypt(ctx context.Context, keyID string, ciphertext, aad []byte) ([]byte, error) { var out struct { Plaintext []byte `json:"plaintext"` } err := c.do(ctx, http.MethodPost, "/v1/keys/"+url.PathEscape(keyID)+"/decrypt", map[string][]byte{"ciphertext": ciphertext, "aad": aad}, &out) return out.Plaintext, err } // DataKey is a fresh 256-bit key for envelope encryption. type DataKey struct { Plaintext []byte // use locally, then zero it; never store or log it Ciphertext []byte // store this next to your data KeyVersion int } // GenerateDataKey creates a data key. Needs the "datakey" grant (and "decrypt" later, to // recover the plaintext data key from its ciphertext). func (c *Client) GenerateDataKey(ctx context.Context, keyID string, aad []byte) (DataKey, error) { var out struct { Plaintext []byte `json:"plaintext"` Ciphertext []byte `json:"ciphertext"` KeyVersion int `json:"key_version"` } err := c.do(ctx, http.MethodPost, "/v1/keys/"+url.PathEscape(keyID)+"/datakey", map[string][]byte{"aad": aad}, &out) return DataKey{out.Plaintext, out.Ciphertext, out.KeyVersion}, err } // ReEncryptResult is the answer of ReEncrypt. type ReEncryptResult struct { Ciphertext []byte `json:"ciphertext"` KeyID string `json:"key_id"` KeyVersion int `json:"key_version"` SourceKeyVersion int `json:"source_key_version"` } // ReEncrypt moves a ciphertext to the latest version of destKeyID ("" = the same key) // without the plaintext leaving the KMS. newAAD, when non-nil, replaces the AAD. // Needs "decrypt" on keyID and "encrypt" on the destination. func (c *Client) ReEncrypt(ctx context.Context, keyID string, ciphertext, aad []byte, destKeyID string, newAAD []byte) (ReEncryptResult, error) { body := map[string]any{"ciphertext": ciphertext, "aad": aad} if destKeyID != "" { body["destination_key_id"] = destKeyID } if newAAD != nil { body["new_aad"] = newAAD } var out ReEncryptResult err := c.do(ctx, http.MethodPost, "/v1/keys/"+url.PathEscape(keyID)+"/reencrypt", body, &out) return out, err } // do sends one signed JSON request and decodes the JSON answer into out. func (c *Client) do(ctx context.Context, method, path string, in, out any) error { var body []byte if in != nil { var err error if body, err = json.Marshal(in); err != nil { return err } } req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, bytes.NewReader(body)) if err != nil { return err } if in != nil { req.Header.Set("Content-Type", "application/json") } if err := c.sign(req, body); err != nil { return err } resp, err := c.HTTP.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode/100 != 2 { var e struct { Error string `json:"error"` } _ = json.NewDecoder(resp.Body).Decode(&e) return &APIError{Status: resp.StatusCode, Message: e.Error} } if out == nil { return nil } return json.NewDecoder(resp.Body).Decode(out) } // sign adds the four X-KMS-* headers. The signed string is, joined with "\n": // KMS-SIG-V1, client id, unix timestamp, nonce, METHOD, escaped path[?raw query], // hex(SHA-256(body)). func (c *Client) sign(req *http.Request, body []byte) error { nonceBytes := make([]byte, 16) if _, err := rand.Read(nonceBytes); err != nil { return err } nonce := base64.RawURLEncoding.EncodeToString(nonceBytes) ts := strconv.FormatInt(time.Now().Unix(), 10) target := req.URL.EscapedPath() if req.URL.RawQuery != "" { target += "?" + req.URL.RawQuery } msg := stringToSign(c.ClientID, ts, nonce, req.Method, target, body) var sig []byte switch k := c.Key.(type) { case ed25519.PrivateKey: sig = ed25519.Sign(k, msg) case *ecdsa.PrivateKey: digest := sha256.Sum256(msg) var err error if sig, err = ecdsa.SignASN1(rand.Reader, k, digest[:]); err != nil { return err } default: return fmt.Errorf("unsupported key type %T", c.Key) } req.Header.Set("X-KMS-Client-ID", c.ClientID) req.Header.Set("X-KMS-Timestamp", ts) req.Header.Set("X-KMS-Nonce", nonce) req.Header.Set("X-KMS-Signature", base64.StdEncoding.EncodeToString(sig)) return nil } func stringToSign(clientID, timestamp, nonce, method, target string, body []byte) []byte { sum := sha256.Sum256(body) return []byte(strings.Join([]string{ "KMS-SIG-V1", clientID, timestamp, nonce, strings.ToUpper(method), target, hex.EncodeToString(sum[:]), }, "\n")) } // --------------------------------------------------------------------------- // Envelope encryption: encrypt large data locally with a KMS data key // --------------------------------------------------------------------------- // Envelope is what you store: the data encrypted locally plus the data key encrypted by the // KMS. None of it is secret on its own. type Envelope struct { KeyID string `json:"key_id"` EncryptedDataKey []byte `json:"encrypted_data_key"` Ciphertext []byte `json:"ciphertext"` // nonce || AES-256-GCM ciphertext || tag } // SealEnvelope encrypts data of any size: the KMS only ever sees the 32-byte data key. func SealEnvelope(ctx context.Context, c *Client, keyID string, data, aad []byte) (Envelope, error) { dk, err := c.GenerateDataKey(ctx, keyID, aad) if err != nil { return Envelope{}, err } defer clear(dk.Plaintext) gcm, err := newGCM(dk.Plaintext) if err != nil { return Envelope{}, err } nonce := make([]byte, gcm.NonceSize()) if _, err := rand.Read(nonce); err != nil { return Envelope{}, err } return Envelope{KeyID: keyID, EncryptedDataKey: dk.Ciphertext, Ciphertext: gcm.Seal(nonce, nonce, data, aad)}, nil } // OpenEnvelope asks the KMS to decrypt the data key, then decrypts the data locally. func OpenEnvelope(ctx context.Context, c *Client, env Envelope, aad []byte) ([]byte, error) { dk, err := c.Decrypt(ctx, env.KeyID, env.EncryptedDataKey, aad) if err != nil { return nil, err } defer clear(dk) gcm, err := newGCM(dk) if err != nil { return nil, err } ns := gcm.NonceSize() if len(env.Ciphertext) < ns { return nil, errors.New("envelope ciphertext too short") } return gcm.Open(nil, env.Ciphertext[:ns], env.Ciphertext[ns:], aad) } func newGCM(key []byte) (cipher.AEAD, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } return cipher.NewGCM(block) } // --------------------------------------------------------------------------- // Demo // --------------------------------------------------------------------------- func main() { keyPEM, err := os.ReadFile(mustEnv("KMS_CLIENT_KEY_FILE")) if err != nil { log.Fatal(err) } c, err := NewClient(mustEnv("KMS_URL"), mustEnv("KMS_CLIENT_ID"), keyPEM) clear(keyPEM) if err != nil { log.Fatal(err) } keyID := mustEnv("KMS_KEY_ID") ctx := context.Background() if err := run(ctx, c, keyID, os.Stdout); err != nil { if IsForbidden(err) { log.Fatalf("%v\nThis client has no grant for that operation on %s: ask the KMS admin (panel \"Izin\").", err, keyID) } log.Fatal(err) } } func run(ctx context.Context, c *Client, keyID string, out io.Writer) error { k, err := c.GetKey(ctx, keyID) if err != nil { return err } fmt.Fprintf(out, "key %s (%s), state %s, current version v%d\n", k.Name, k.ID, k.State, k.CurrentVersion) // 1. Small secrets (tokens, NIK, account numbers): encrypt directly in the KMS. aad := []byte("tenant:42") ct, v, err := c.Encrypt(ctx, keyID, []byte("contoh data rahasia"), aad) if err != nil { return err } fmt.Fprintf(out, "encrypt: %d-byte ciphertext under v%d\n", len(ct), v) pt, err := c.Decrypt(ctx, keyID, ct, aad) if err != nil { return err } fmt.Fprintf(out, "decrypt: %q\n", pt) // 2. Large data (files, documents): envelope encryption with a data key. doc := bytes.Repeat([]byte("isi dokumen besar. "), 10_000) env, err := SealEnvelope(ctx, c, keyID, doc, aad) if err != nil { return err } fmt.Fprintf(out, "envelope: %d bytes of data sealed locally, data key wrapped by the KMS\n", len(doc)) back, err := OpenEnvelope(ctx, c, env, aad) if err != nil { return err } fmt.Fprintf(out, "envelope open: %d bytes, identical: %v\n", len(back), bytes.Equal(back, doc)) return nil } func mustEnv(name string) string { v := os.Getenv(name) if v == "" { log.Fatalf("missing environment variable %s", name) } return v }