2015-09-03 18:57:28 +02:00
|
|
|
package cryptfs
|
2015-09-03 18:22:18 +02:00
|
|
|
|
|
|
|
import (
|
2015-10-04 21:36:16 +02:00
|
|
|
"bytes"
|
2015-10-04 14:36:20 +02:00
|
|
|
"crypto/rand"
|
2015-09-03 18:22:18 +02:00
|
|
|
"encoding/hex"
|
2015-10-07 22:58:22 +02:00
|
|
|
"fmt"
|
2015-09-03 18:22:18 +02:00
|
|
|
)
|
|
|
|
|
2015-09-13 17:55:07 +02:00
|
|
|
// Get "n" random bytes from /dev/urandom or panic
|
|
|
|
func RandBytes(n int) []byte {
|
|
|
|
b := make([]byte, n)
|
2015-09-03 18:22:18 +02:00
|
|
|
_, err := rand.Read(b)
|
|
|
|
if err != nil {
|
2015-10-04 21:36:16 +02:00
|
|
|
panic("Failed to read random bytes: " + err.Error())
|
2015-09-03 18:22:18 +02:00
|
|
|
}
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
2015-10-04 21:36:16 +02:00
|
|
|
var gcmNonce nonce96
|
|
|
|
|
|
|
|
type nonce96 struct {
|
|
|
|
lastNonce []byte
|
2015-09-03 18:22:18 +02:00
|
|
|
}
|
|
|
|
|
2015-10-04 21:36:16 +02:00
|
|
|
// Get a random 96 bit nonce
|
2015-09-03 18:22:18 +02:00
|
|
|
func (n *nonce96) Get() []byte {
|
2015-10-04 21:36:16 +02:00
|
|
|
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)
|
2015-09-03 18:22:18 +02:00
|
|
|
}
|
2015-10-04 21:36:16 +02:00
|
|
|
n.lastNonce = nonce
|
|
|
|
return nonce
|
2015-09-03 18:22:18 +02:00
|
|
|
}
|