package store import ( "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/sha256" "errors" "io" "golang.org/x/crypto/hkdf" ) // ErrSealed says a sealed value could not be opened: the wrong token, or a // tampered blob. The two are deliberately not distinguished. var ErrSealed = errors.New("cannot open") // seal encrypts a secret so that only the holder of the token can read it. // // This is what keeps a pending claim from being a working credential sitting in // the database. The token is never stored — only its hash — so the key needed // to open this blob does not exist anywhere the database does. // // HKDF rather than using the token directly: the token is also hashed for // lookup, and a value used both as a lookup key and an encryption key is one // change away from having the lookup index hand out the decryption key. func seal(token string, secret []byte) ([]byte, error) { gcm, err := cipherFor(token) if err != nil { return nil, err } nonce := make([]byte, gcm.NonceSize()) if _, err := rand.Read(nonce); err != nil { return nil, err } return gcm.Seal(nonce, nonce, secret, nil), nil } // open reverses seal. func open(token string, sealed []byte) ([]byte, error) { gcm, err := cipherFor(token) if err != nil { return nil, err } if len(sealed) < gcm.NonceSize() { return nil, ErrSealed } out, err := gcm.Open(nil, sealed[:gcm.NonceSize()], sealed[gcm.NonceSize():], nil) if err != nil { return nil, ErrSealed } return out, nil } func cipherFor(token string) (cipher.AEAD, error) { key := make([]byte, 32) // The info string domain-separates this use of the token from its use as a // lookup hash, so neither can ever be derived from the other. if _, err := io.ReadFull(hkdf.New(sha256.New, []byte(token), nil, []byte("llmgw claim seal v1")), key); err != nil { return nil, err } block, err := aes.NewCipher(key) if err != nil { return nil, err } return cipher.NewGCM(block) }