aboutsummaryrefslogtreecommitdiff
path: root/internal/cryptocore/nonce.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/cryptocore/nonce.go')
-rw-r--r--internal/cryptocore/nonce.go44
1 files changed, 44 insertions, 0 deletions
diff --git a/internal/cryptocore/nonce.go b/internal/cryptocore/nonce.go
new file mode 100644
index 0000000..72d8588
--- /dev/null
+++ b/internal/cryptocore/nonce.go
@@ -0,0 +1,44 @@
+package cryptocore
+
+import (
+ "bytes"
+ "crypto/rand"
+ "encoding/binary"
+ "encoding/hex"
+ "fmt"
+
+ "github.com/rfjakob/gocryptfs/internal/toggledlog"
+)
+
+// 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
+}
+
+// Return a secure random uint64
+func RandUint64() uint64 {
+ b := RandBytes(8)
+ return binary.BigEndian.Uint64(b)
+}
+
+type nonceGenerator struct {
+ lastNonce []byte
+ nonceLen int // bytes
+}
+
+// Get a random "nonceLen"-byte nonce
+func (n *nonceGenerator) Get() []byte {
+ nonce := RandBytes(n.nonceLen)
+ toggledlog.Debug.Printf("nonceGenerator.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
+}