2016-02-06 19:20:54 +01:00
|
|
|
package configfile
|
2015-09-13 21:47:18 +02:00
|
|
|
|
|
|
|
import (
|
2016-06-05 14:26:16 +02:00
|
|
|
"log"
|
2015-11-29 21:41:38 +01:00
|
|
|
"math"
|
|
|
|
"os"
|
2016-02-06 19:20:54 +01:00
|
|
|
|
|
|
|
"golang.org/x/crypto/scrypt"
|
|
|
|
|
|
|
|
"github.com/rfjakob/gocryptfs/internal/cryptocore"
|
2016-06-15 23:30:44 +02:00
|
|
|
"github.com/rfjakob/gocryptfs/internal/tlog"
|
2015-09-13 21:47:18 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2016-10-02 06:14:18 +02:00
|
|
|
// ScryptDefaultLogN is the default scrypt logN configuration parameter.
|
2015-09-13 21:47:18 +02:00
|
|
|
// 1 << 16 uses 64MB of memory,
|
|
|
|
// takes 4 seconds on my Atom Z3735F netbook
|
2016-02-06 19:20:54 +01:00
|
|
|
ScryptDefaultLogN = 16
|
2015-09-13 21:47:18 +02:00
|
|
|
)
|
|
|
|
|
2016-10-02 06:14:18 +02:00
|
|
|
// ScryptKDF is an instance of the scrypt key deriviation function.
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2016-10-02 06:14:18 +02:00
|
|
|
// NewScryptKDF returns a new instance of ScryptKDF.
|
|
|
|
func NewScryptKDF(logN int) ScryptKDF {
|
|
|
|
var s ScryptKDF
|
2016-02-06 19:20:54 +01:00
|
|
|
s.Salt = cryptocore.RandBytes(cryptocore.KeyLen)
|
2015-11-29 18:52:58 +01:00
|
|
|
if logN <= 0 {
|
2016-02-06 19:20:54 +01:00
|
|
|
s.N = 1 << ScryptDefaultLogN
|
2015-11-29 18:52:58 +01:00
|
|
|
} else {
|
|
|
|
if logN < 10 {
|
2016-06-15 23:30:44 +02:00
|
|
|
tlog.Fatal.Println("Error: scryptn below 10 is too low to make sense. Aborting.")
|
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
|
2016-02-06 19:20:54 +01:00
|
|
|
s.KeyLen = cryptocore.KeyLen
|
2015-09-13 21:47:18 +02:00
|
|
|
return s
|
|
|
|
}
|
|
|
|
|
2016-10-02 06:14:18 +02:00
|
|
|
// DeriveKey returns a new key from a supplied password.
|
|
|
|
func (s *ScryptKDF) DeriveKey(pw string) []byte {
|
2015-09-13 21:47:18 +02:00
|
|
|
k, err := scrypt.Key([]byte(pw), s.Salt, s.N, s.R, s.P, s.KeyLen)
|
|
|
|
if err != nil {
|
2016-06-05 14:26:16 +02:00
|
|
|
log.Panicf("DeriveKey failed: %v", err)
|
2015-09-13 21:47:18 +02:00
|
|
|
}
|
|
|
|
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).
|
2016-10-02 06:14:18 +02:00
|
|
|
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
|
|
|
}
|