Skip to content

Commit

Permalink
reimpl nonce
Browse files Browse the repository at this point in the history
  • Loading branch information
jrick committed Jun 12, 2024
1 parent 1fdf14a commit 80037d5
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions peer/internal/uprng/uprng.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,20 +41,22 @@ const (

// nonce implements a 12-byte little endian counter suitable for use as an
// incrementing ChaCha20 nonce.
type nonce struct {
limbs [3]uint32
bytes [chacha20.NonceSize]byte
}
type nonce [chacha20.NonceSize]byte

func (n *nonce) inc() {
n0 := binary.LittleEndian.Uint32(n[0:4])
n1 := binary.LittleEndian.Uint32(n[4:8])
n2 := binary.LittleEndian.Uint32(n[8:12])

var carry uint32
n.limbs[0], carry = bits.Add32(n.limbs[0], 1, carry)
n.limbs[1], carry = bits.Add32(n.limbs[1], 0, carry)
n.limbs[2], carry = bits.Add32(n.limbs[2], 0, carry)
n.limbs[0], _ = bits.Add32(n.limbs[0], 0, carry)
binary.LittleEndian.PutUint32(n.bytes[0:4], n.limbs[0])
binary.LittleEndian.PutUint32(n.bytes[4:8], n.limbs[1])
binary.LittleEndian.PutUint32(n.bytes[8:12], n.limbs[2])
n0, carry = bits.Add32(n0, 1, carry)
n1, carry = bits.Add32(n1, 0, carry)
n2, carry = bits.Add32(n2, 0, carry)
n0, _ = bits.Add32(n0, 0, carry)

binary.LittleEndian.PutUint32(n[0:4], n0)
binary.LittleEndian.PutUint32(n[4:8], n1)
binary.LittleEndian.PutUint32(n[8:12], n2)
}

type prng struct {
Expand Down Expand Up @@ -87,7 +89,7 @@ func (p *prng) seed() {
}

// never errors with correct key and nonce sizes
cipher, _ := chacha20.NewUnauthenticatedCipher(p.key, p.nonce.bytes[:])
cipher, _ := chacha20.NewUnauthenticatedCipher(p.key, p.nonce[:])
p.nonce.inc()

p.cipher = cipher
Expand Down

0 comments on commit 80037d5

Please sign in to comment.