summaryrefslogtreecommitdiff
path: root/src/scrypt.go
blob: 70140aba3f04017db522c27329165d258ceaf143 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package scrypt

import (
	"crypto/rand"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"os"
	"slices"
)



/*
#define _XOPEN_SOURCE 700
#include <stdlib.h>
#include <scrypt-kdf.h>
*/
import "C"



const (
	MinimumPasswordLength = 16
	_SALT_MIN_LENGTH = 32
	_DESIRED_LENGTH = 32
	_N = 1 << 15
	r  = 8
	p  = 1
)


var (
	ErrSaltTooSmall = errors.New("scrypt: salt is too small")
	ErrInternal     = errors.New("scrypt: internal error")
)



type HashInput struct{
	Password []byte
	Salt     []byte
}

type CheckInput struct{
	Password []byte
	Salt     []byte
	Hash     []byte
}



// Package scrypt implements the scrypt key derivation function as defined in
// Colin Percival's paper "Stronger Key Derivation via Sequential Memory-Hard
// Functions" (https://www.tarsnap.com/scrypt/scrypt.pdf).
//
//
// Key derives a key from the password, salt, and cost parameters, returning
// a byte slice of length keyLen that can be used as cryptographic key.
//
// N is a CPU/memory cost parameter, which must be a power of 2 greater than 1.
// r and p must satisfy r * p < 2³⁰. If the parameters do not satisfy the
// limits, the function returns a nil byte slice and an error.
//
// For example, you can get a derived key for e.g. AES-256 (which needs a
// 32-byte key) by doing:
//
//	dk, err := scrypt.Key([]byte("some password"), salt, 32768, 8, 1, 32)
//
// The recommended parameters for interactive logins as of 2017 are N=32768, r=8
// and p=1. The parameters N, r, and p should be increased as memory latency and
// CPU parallelism increases; consider setting N to the highest power of 2 you
// can derive within 100 milliseconds. Remember to get a good random salt.
func scrypt(
	password []byte,
	salt []byte,
	N int,
	r int,
	p int,
	outlen int,
) ([]byte, error) {
	passwordbuf := C.CBytes(password)
	saltbuf     := C.CBytes(salt)
	defer C.free(passwordbuf)
	defer C.free(saltbuf)

	outbuf := C.malloc(C.size_t(outlen))
	defer C.free(outbuf)

	rv := C.scrypt_kdf(
		(*C.uint8_t)(passwordbuf),
		C.size_t(len(password)),
		(*C.uint8_t)(saltbuf),
		C.size_t(len(salt)),
		C.uint64_t(N),
		C.uint32_t(r),
		C.uint32_t(p),
		(*C.uint8_t)(outbuf),
		C.size_t(outlen),
	)
	if rv != 0 {
		return nil, ErrInternal
	}

	out := C.GoBytes(outbuf, C.int(outlen))
	return out, nil
}

func Hash(input HashInput) ([]byte, error) {
	if len(input.Salt) < _SALT_MIN_LENGTH {
		return nil, ErrSaltTooSmall
	}

	hash, err := scrypt(
		input.Password,
		input.Salt,
		_N,
		r,
		p,
		_DESIRED_LENGTH,
	)
	return hash, err
}

func SaltFrom(r io.Reader) ([]byte, error) {
	buffer := make([]byte, _SALT_MIN_LENGTH)
	_, err := io.ReadFull(r, buffer)
	if err != nil {
		return nil, err
	}
	return buffer, nil
}

func Salt() ([]byte, error) {
	return SaltFrom(rand.Reader)
}

func Check(input CheckInput) (bool, error) {
	hashInput := HashInput{
		Password: input.Password,
		Salt:     input.Salt,
	}

	candidate, err := Hash(hashInput)
	if err != nil {
		return false, err
	}

	return slices.Equal(candidate, input.Hash), nil
}



func Main() {
	if len(os.Args) != 3 {
		fmt.Fprintf(os.Stderr, "Usage: scrypt PASSWORD SALT\n")
		os.Exit(2)
	}

	password := []byte(os.Args[1])
	salt     := []byte(os.Args[2])
	input    := HashInput{
		Password: password,
		Salt:     salt,
	}

	payload, err := Hash(input)
	if err != nil {
		if err == ErrSaltTooSmall {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(2)
		}
		panic(err)
	}

	fmt.Println(hex.EncodeToString(payload))
}