Debian Codegraph @

noiseutil/aesgcm.go

raw
1 package noiseutil
2
3 import (
4 "crypto/cipher"
5 "encoding/binary"
6 "errors"
7
8 "github.com/flynn/noise"
9 )
10
11 // CipherStateAESGCM is the data-plane wrapper for the AES-GCM AEAD cipher.
12 // AES-GCM uses big-endian nonce encoding per the Noise spec.
13 type CipherStateAESGCM struct {
14 c cipher.AEAD
15 }
16
17 // NewCipherStateAESGCM extracts the underlying AEAD from the post-handshake noise.CipherState.
18 // The caller is responsible for ensuring the noise cipher is actually AES-GCM,
19 // otherwise the type assertion still succeeds but the nonce endianness will be wrong on the wire.
20 func NewCipherStateAESGCM(s *noise.CipherState) *CipherStateAESGCM {
21 return &CipherStateAESGCM{c: s.Cipher().(cipher.AEAD)}
22 }
23
24 func (s *CipherStateAESGCM) EncryptDanger(out, ad, plaintext []byte, n uint64, nb []byte) ([]byte, error) {
25 if s == nil {
26 return nil, errors.New("no cipher state available to encrypt")
27 }
28 nb[0] = 0
29 nb[1] = 0
30 nb[2] = 0
31 nb[3] = 0
32 binary.BigEndian.PutUint64(nb[4:], n)
33 return s.c.Seal(out, nb, plaintext, ad), nil
34 }
35
36 func (s *CipherStateAESGCM) DecryptDanger(out, ad, ciphertext []byte, n uint64, nb []byte) ([]byte, error) {
37 if s == nil {
38 return []byte{}, nil
39 }
40 nb[0] = 0
41 nb[1] = 0
42 nb[2] = 0
43 nb[3] = 0
44 binary.BigEndian.PutUint64(nb[4:], n)
45 return s.c.Open(out, nb, ciphertext, ad)
46 }
47
48 func (s *CipherStateAESGCM) Overhead() int {
49 if s == nil {
50 return 0
51 }
52 return s.c.Overhead()
53 }