aboutsummaryrefslogtreecommitdiff
path: root/cryptfs/nonce.go
blob: 0ba079b154f2a8ef219acdb47a3e22dfcad1a2e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package cryptfs

import (
	"bytes"
	"fmt"
	"crypto/rand"
	"encoding/hex"
)

// Get "n" random bytes from /dev/urandom or panic
func RandBytes(n int) []byte {
	b := make([]byte, n)
	_, err := rand.Read(b)
	if err != nil {
		panic("Failed to read random bytes: " + err.Error())
	}
	return b
}

var gcmNonce nonce96

type nonce96 struct {
	lastNonce []byte
}

// Get a random 96 bit nonce
func (n *nonce96) Get() []byte {
	nonce := RandBytes(12)
	Debug.Printf("nonce96.Get(): %s\n", hex.EncodeToString(nonce))
	if bytes.Equal(nonce, n.lastNonce) {
		m := fmt.Sprintf("Got the same nonce twice: %s. This should never happen!", hex.EncodeToString(nonce))
		panic(m)
	}
	n.lastNonce = nonce
	return nonce
}