libgocryptfs/cryptfs/nonce.go
Jakob Unterwurzacher e6b7353f4e Switch nonce generation to purely random
The old implementation of counting up from a random starting
point had the problem that is allowed an attacker to find out
the write order of the blocks.
2015-10-04 21:36:16 +02:00

37 lines
701 B
Go

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
}