aboutsummaryrefslogtreecommitdiff
path: root/bhash/bhash.go
blob: 443a862dbfa10c6a5212338aa7a1f3897a3b1367 (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
package bhash

import (
	"bytes"
	"crypto/sha512"
	"log"

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

var magic = []byte("OxychromaticBlowfishSwatDynamite")

const rounds = 64

func Hash(pass, salt []byte) []byte {
	c, err := blowfish.NewSaltedCipher(pass, salt)
	if err != nil {
		panic(err)
	}
	// key expansion
	for i := 0; i < rounds; i++ {
		blowfish.ExpandKey(salt, c)
		blowfish.ExpandKey(pass, c)
	}
	// encryption
	buf := new(bytes.Buffer)
	bSz := c.BlockSize()
	for n := 0; n < len(magic)/bSz; n++ {
		b := make([]byte, bSz)
		copy(b, magic[n*bSz:(n+1)*bSz])
		for i := 0; i < rounds; i++ {
			c.Encrypt(b, b)
		}
		// copy out
		b[0], b[1], b[2], b[3] = b[3], b[2], b[1], b[0]
		b[4], b[5], b[6], b[7] = b[7], b[6], b[5], b[4]
		buf.Write(b)
	}
	return buf.Bytes()
}

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

	out := make([]byte, 32) // XXX

	for count := 1; keyLen > 0; count++ {
		countSalt := []byte{byte(count >> 24), byte(count >> 16), byte(count >> 8), byte(count)}
		// first round salt is salt
		h.Reset()
		h.Write(salt)
		h.Write(countSalt)
		sha2salt := h.Sum(nil)
		tmp := Hash(sha2pass, sha2salt)
		copy(out, tmp)
		log.Println(out)

		for i := 1; i < iter; i++ {
			h.Reset()
			h.Write(tmp)
			sha2salt = h.Sum(nil)
			tmp = Hash(sha2pass, sha2salt)
			log.Println(len(tmp), len(out))
			for i := range out {
				out[i] ^= tmp[i]
			}
			log.Println(out)
		}

		keyLen-- // XXX
	}

	return nil
}