2015-09-13 21:47:18 +02:00
|
|
|
package cryptfs
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"golang.org/x/crypto/scrypt"
|
2015-11-29 21:41:38 +01:00
|
|
|
"math"
|
|
|
|
"os"
|
2015-09-13 21:47:18 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// 1 << 16 uses 64MB of memory,
|
|
|
|
// takes 4 seconds on my Atom Z3735F netbook
|
2015-11-29 18:52:58 +01:00
|
|
|
SCRYPT_DEFAULT_LOGN = 16
|
2015-09-13 21:47:18 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type scryptKdf struct {
|
2015-10-04 14:36:20 +02:00
|
|
|
Salt []byte
|
|
|
|
N int
|
|
|
|
R int
|
|
|
|
P int
|
2015-09-13 21:47:18 +02:00
|
|
|
KeyLen int
|
|
|
|
}
|
|
|
|
|
2015-11-29 18:52:58 +01:00
|
|
|
func NewScryptKdf(logN int) scryptKdf {
|
2015-09-13 21:47:18 +02:00
|
|
|
var s scryptKdf
|
|
|
|
s.Salt = RandBytes(KEY_LEN)
|
2015-11-29 18:52:58 +01:00
|
|
|
if logN <= 0 {
|
|
|
|
s.N = 1 << SCRYPT_DEFAULT_LOGN
|
|
|
|
} else {
|
|
|
|
if logN < 10 {
|
2015-12-06 14:24:45 +01:00
|
|
|
fmt.Printf("Error: scryptn below 10 is too low to make sense. Aborting.\n")
|
2015-11-29 18:52:58 +01:00
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
s.N = 1 << uint32(logN)
|
|
|
|
}
|
2015-09-13 21:47:18 +02:00
|
|
|
s.R = 8 // Always 8
|
|
|
|
s.P = 1 // Always 1
|
|
|
|
s.KeyLen = KEY_LEN
|
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *scryptKdf) DeriveKey(pw string) []byte {
|
|
|
|
k, err := scrypt.Key([]byte(pw), s.Salt, s.N, s.R, s.P, s.KeyLen)
|
|
|
|
if err != nil {
|
|
|
|
panic(fmt.Sprintf("DeriveKey failed: %s", err.Error()))
|
|
|
|
}
|
|
|
|
return k
|
|
|
|
}
|
2015-11-29 18:52:58 +01:00
|
|
|
|
|
|
|
// LogN - N is saved as 2^LogN, but LogN is much easier to work with.
|
|
|
|
// This function gives you LogN = Log2(N).
|
|
|
|
func (s *scryptKdf) LogN() int {
|
2015-11-29 21:41:38 +01:00
|
|
|
return int(math.Log2(float64(s.N)) + 0.5)
|
2015-11-29 18:52:58 +01:00
|
|
|
}
|