aboutsummaryrefslogtreecommitdiff
path: root/cipher.go
diff options
context:
space:
mode:
authorOnur Gündüz <ogunduz@gmail.com>2026-03-10 11:58:37 +0100
committerOnur Gündüz <ogunduz@gmail.com>2026-03-10 11:58:37 +0100
commit03b95111f19a93ccee00e8e8e0afaab8112f5484 (patch)
treec0bfd7c5c768b441c901645a5a9a83c533eaf56f /cipher.go
parentbcb40853f819cdbea99ec5d0ab2ee7594efd7690 (diff)
downloadnoise-03b95111f19a93ccee00e8e8e0afaab8112f5484.tar.gz
noise-03b95111f19a93ccee00e8e8e0afaab8112f5484.zip
Init package
Diffstat (limited to 'cipher.go')
-rw-r--r--cipher.go123
1 files changed, 123 insertions, 0 deletions
diff --git a/cipher.go b/cipher.go
new file mode 100644
index 0000000..057cf97
--- /dev/null
+++ b/cipher.go
@@ -0,0 +1,123 @@
+package noisehandshake
+
+import (
+ "crypto/cipher"
+ "encoding/binary"
+ "errors"
+ "fmt"
+
+ "golang.org/x/crypto/chacha20poly1305"
+)
+
+const (
+ // MaxMessageLength is the maximum Noise message size.
+ MaxMessageLength = 65535
+ // KeyBytes is the cipher key size. For ChaCha20Poly1305, this is 32 bytes.
+ KeyBytes = 32
+ // MacBytes is the MAC size.
+ MacBytes = 16
+)
+
+var (
+ // ErrCiphertextTooLong indicates message exceeds maximum length.
+ ErrCiphertextTooLong = errors.New("ciphertext exceeds maximum message length")
+ // ErrInvalidKeySize indicates invalid key size.
+ ErrInvalidKeySize = errors.New("invalid key size for ChaCha20Poly1305")
+)
+
+// CipherState represents the cipher state in Noise Protocol.
+type CipherState struct {
+ key []byte
+ aead cipher.AEAD // Reuse AEAD instance for performance
+ nonce uint64
+ nonceBuf [chacha20poly1305.NonceSize]byte
+}
+
+// newCipherState creates a new cipher state with an optional key.
+func newCipherState(key []byte) (*CipherState, error) {
+ cs := &CipherState{
+ nonce: 0,
+ }
+ if key != nil {
+ if len(key) != KeyBytes {
+ return nil, ErrInvalidKeySize
+ }
+ cs.initializeKey(key)
+ }
+ return cs, nil
+}
+
+// initializeKey sets the key and resets the nonce.
+// This assumes key is a valid 32-byte slice. Caller should ensure this is the case.
+func (cs *CipherState) initializeKey(key []byte) {
+ cs.key = make([]byte, len(key))
+ copy(cs.key, key)
+
+ // Initialize the AEAD once for reuse
+ var err error
+ cs.aead, err = chacha20poly1305.New(cs.key)
+ if err != nil {
+ // Should never happen with 32-byte key
+ panic(fmt.Sprintf("cipher: failed to initialize AEAD: %v", err))
+ }
+
+ cs.nonce = 0
+}
+
+// HasKey returns true if the cipher state has a key.
+func (cs *CipherState) HasKey() bool {
+ return cs.aead != nil
+}
+
+// Encrypt encrypts plaintext with associated data, appending the result to dst.
+// If no key is set, it appends the plaintext unchanged.
+func (cs *CipherState) Encrypt(dst, plaintext, ad []byte) ([]byte, error) {
+ if !cs.HasKey() {
+ return append(dst, plaintext...), nil
+ }
+
+ binary.LittleEndian.PutUint64(cs.nonceBuf[4:], cs.nonce)
+
+ ret := cs.aead.Seal(dst, cs.nonceBuf[:], plaintext, ad)
+
+ if len(ret)-len(dst) > MaxMessageLength {
+ return nil, ErrCiphertextTooLong
+ }
+
+ cs.nonce++
+ return ret, nil
+}
+
+// Decrypt decrypts ciphertext with associated data, appending the result to dst.
+// If no key is set, it appends the ciphertext unchanged.
+func (cs *CipherState) Decrypt(dst, ciphertext, ad []byte) ([]byte, error) {
+ if !cs.HasKey() {
+ return append(dst, ciphertext...), nil
+ }
+
+ if len(ciphertext) > MaxMessageLength {
+ return nil, ErrCiphertextTooLong
+ }
+
+ binary.LittleEndian.PutUint64(cs.nonceBuf[4:], cs.nonce)
+
+ ret, err := cs.aead.Open(dst, cs.nonceBuf[:], ciphertext, ad)
+ if err != nil {
+ return nil, fmt.Errorf("decryption failed: %w", err)
+ }
+
+ cs.nonce++
+ return ret, nil
+}
+
+// Clear clears the key from memory.
+func (cs *CipherState) Clear() {
+ if cs.key != nil {
+ for i := range cs.key {
+ cs.key[i] = 0
+ }
+ cs.key = nil
+ }
+ cs.aead = nil
+ cs.nonce = 0
+}