aboutsummaryrefslogtreecommitdiff
path: root/bhash/bhash.go
blob: 614a30c9e328791c6494430c66462c235237400b (plain)
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
// Package bhash implements bcrypt_pbkdf key derivation function compatible to
// OpenBSD implementation
//
// http://cvsweb.openbsd.org/cgi-bin/cvsweb/src/lib/libutil/bcrypt_pbkdf.c
package bhash

import (
	"bytes"
	"crypto/sha512"
	"encoding/binary"

	"golang.org/x/crypto/blowfish"
)

const (
	magic    = "OxychromaticBlowfishSwatDynamite"
	rounds   = 64
	words    = blowfish.BlockSize
	hashSize = 4 * words
)

// Hash computes bcrypt hash
func Hash(pass, salt []byte) ([]byte, error) {
	c, err := blowfish.NewSaltedCipher(pass, salt)
	if err != nil {
		return nil, err
	}
	// key expansion
	for i := 0; i < rounds; i++ {
		blowfish.ExpandKey(salt, c)
		blowfish.ExpandKey(pass, c)
	}
	// encryption
	buf := new(bytes.Buffer)
	for n := 0; n < len(magic)/words; n++ {
		v := []byte(magic[n*words : (n+1)*words])
		for i := 0; i < rounds; i++ {
			c.Encrypt(v, v)
		}
		// swap bytes and copy out
		var u [2]uint32
		binary.Read(bytes.NewReader(v), binary.LittleEndian, &u)
		binary.Write(buf, binary.BigEndian, u)
	}
	return buf.Bytes(), nil
}

// Pbkdf returns derivated key
func Pbkdf(pass, salt []byte, iter, keyLen int) ([]byte, error) {
	// collapse password
	h := sha512.New()
	h.Write(pass)
	sha2pass := h.Sum(nil)

	numBlocks := (keyLen + hashSize - 1) / hashSize
	out := make([]byte, hashSize)
	key := make([]byte, hashSize*numBlocks)

	for n := 1; n <= numBlocks; n++ {
		// first round, salt is salt
		h.Reset()
		h.Write(salt)
		binary.Write(h, binary.BigEndian, uint32(n))
		tmp, err := Hash(sha2pass, h.Sum(nil))
		if err != nil {
			return nil, err
		}
		copy(out, tmp)

		for i := 1; i < iter; i++ {
			h.Reset()
			h.Write(tmp)
			tmp, err = Hash(sha2pass, h.Sum(nil))
			if err != nil {
				return nil, err
			}
			for x := range tmp {
				out[x] ^= tmp[x]
			}
		}
		// pbkdf2 deviation: output the key material non-linearly
		for x := range out {
			dst := x*numBlocks + (n - 1)
			key[dst] = out[x]
		}
	}
	return key[:keyLen], nil
}