types/key: add MachinePrecomputedSharedKey.Open

Follow-up to cfdb862673

Updates tailscale/corp#1709

Change-Id: I7af931a2cb55f9006e1029381663ac21d1794242
Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
pull/5128/head^2
Brad Fitzpatrick 2 years ago committed by Brad Fitzpatrick
parent be8a0859a9
commit 2024008667

@ -132,6 +132,21 @@ func (k MachinePrecomputedSharedKey) Seal(cleartext []byte) (ciphertext []byte)
return box.SealAfterPrecomputation(nonce[:], cleartext, &nonce, &k.k) return box.SealAfterPrecomputation(nonce[:], cleartext, &nonce, &k.k)
} }
// Open opens the NaCl box ciphertext, which must be a value created by
// MachinePrecomputedSharedKey.Seal or MachinePrivate.SealTo, and returns the
// inner cleartext if ciphertext is a valid box for the shared key k.
func (k MachinePrecomputedSharedKey) Open(ciphertext []byte) (cleartext []byte, ok bool) {
if k == (MachinePrecomputedSharedKey{}) {
panic("can't open with zero keys")
}
if len(ciphertext) < 24 {
return nil, false
}
var nonce [24]byte
copy(nonce[:], ciphertext)
return box.OpenAfterPrecomputation(nil, ciphertext[len(nonce):], &nonce, &k.k)
}
// OpenFrom opens the NaCl box ciphertext, which must be a value // OpenFrom opens the NaCl box ciphertext, which must be a value
// created by SealTo, and returns the inner cleartext if ciphertext is // created by SealTo, and returns the inner cleartext if ciphertext is
// a valid box from p to k. // a valid box from p to k.

@ -107,6 +107,14 @@ func TestSealViaSharedKey(t *testing.T) {
t.Fatal("failed to decrypt") t.Fatal("failed to decrypt")
} }
if string(back) != clear { if string(back) != clear {
t.Errorf("got %q; want cleartext %q", back, clear) t.Errorf("OpenFrom got %q; want cleartext %q", back, clear)
}
backShared, ok := shared.Open(enc)
if !ok {
t.Fatal("failed to decrypt from shared key")
}
if string(backShared) != clear {
t.Errorf("Open got %q; want cleartext %q", back, clear)
} }
} }

Loading…
Cancel
Save