package server import ( "crypto/pbkdf2" "crypto/sha256" "encoding/binary" "errors" "math/bits" ) // scryptKey derives an RFC 7914 scrypt key. It is the same function Node's // crypto.scrypt and Python's hashlib.scrypt compute, so the web proxy, the // ./password script and this server verify one stored hash. The standard // library has PBKDF2 but no scrypt, and this small implementation avoids a // new module dependency. func scryptKey(password, salt []byte, n, r, p, keyLen int) ([]byte, error) { if n <= 1 || n&(n-1) != 0 { return nil, errors.New("scrypt: N must be a power of two greater than 1") } if r <= 0 || p <= 0 || keyLen <= 0 || r*p >= 1<<30 || r > (1<<31-1)/128/p || n > (1<<31-1)/128/r { return nil, errors.New("scrypt: parameters out of range") } b, err := pbkdf2.Key(sha256.New, string(password), salt, 1, p*128*r) if err != nil { return nil, err } xy := make([]uint32, 64*r) v := make([]uint32, 32*n*r) for i := 0; i < p; i++ { scryptROMix(b[i*128*r:], r, n, v, xy) } return pbkdf2.Key(sha256.New, string(password), b, 1, keyLen) } func scryptROMix(b []byte, r, n int, v, xy []uint32) { words := 32 * r x, y := xy[:words], xy[words:] for i := range x { x[i] = binary.LittleEndian.Uint32(b[i*4:]) } for i := 0; i < n; i++ { copy(v[i*words:], x) scryptBlockMix(x, y, r) } for i := 0; i < n; i++ { j := int(x[(2*r-1)*16] & uint32(n-1)) for k := range x { x[k] ^= v[j*words+k] } scryptBlockMix(x, y, r) } for i := range x { binary.LittleEndian.PutUint32(b[i*4:], x[i]) } } // scryptBlockMix computes BlockMix_salsa20/8 of b in place, using y as scratch. func scryptBlockMix(b, y []uint32, r int) { var x [16]uint32 copy(x[:], b[(2*r-1)*16:]) for i := 0; i < 2*r; i++ { for k := range x { x[k] ^= b[i*16+k] } salsa208(&x) // Even blocks go to the first half of the output, odd to the second. copy(y[(i/2+(i%2)*r)*16:], x[:]) } copy(b, y[:32*r]) } func salsa208(b *[16]uint32) { x := *b rotl := bits.RotateLeft32 for i := 0; i < 8; i += 2 { x[4] ^= rotl(x[0]+x[12], 7) x[8] ^= rotl(x[4]+x[0], 9) x[12] ^= rotl(x[8]+x[4], 13) x[0] ^= rotl(x[12]+x[8], 18) x[9] ^= rotl(x[5]+x[1], 7) x[13] ^= rotl(x[9]+x[5], 9) x[1] ^= rotl(x[13]+x[9], 13) x[5] ^= rotl(x[1]+x[13], 18) x[14] ^= rotl(x[10]+x[6], 7) x[2] ^= rotl(x[14]+x[10], 9) x[6] ^= rotl(x[2]+x[14], 13) x[10] ^= rotl(x[6]+x[2], 18) x[3] ^= rotl(x[15]+x[11], 7) x[7] ^= rotl(x[3]+x[15], 9) x[11] ^= rotl(x[7]+x[3], 13) x[15] ^= rotl(x[11]+x[7], 18) x[1] ^= rotl(x[0]+x[3], 7) x[2] ^= rotl(x[1]+x[0], 9) x[3] ^= rotl(x[2]+x[1], 13) x[0] ^= rotl(x[3]+x[2], 18) x[6] ^= rotl(x[5]+x[4], 7) x[7] ^= rotl(x[6]+x[5], 9) x[4] ^= rotl(x[7]+x[6], 13) x[5] ^= rotl(x[4]+x[7], 18) x[11] ^= rotl(x[10]+x[9], 7) x[8] ^= rotl(x[11]+x[10], 9) x[9] ^= rotl(x[8]+x[11], 13) x[10] ^= rotl(x[9]+x[8], 18) x[12] ^= rotl(x[15]+x[14], 7) x[13] ^= rotl(x[12]+x[15], 9) x[14] ^= rotl(x[13]+x[12], 13) x[15] ^= rotl(x[14]+x[13], 18) } for i := range b { b[i] += x[i] } }