Debian Codegraph @

pkg/bcrypt_pbkdf/bcrypt_pbkdf.go

raw symbols SCIP
1 // Copyright 2014 Dmitry Chestnykh. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package bcrypt_pbkdf implements password-based key derivation function based
6 // on bcrypt compatible with bcrypt_pbkdf(3) from OpenBSD.
7 package bcrypt_pbkdf
8
9 import (
10 "crypto/sha512"
11 "errors"
12
13 // NOTE! Requires blowfish package version from Aug 1, 2014 or later.
14 // Will produce incorrect results if the package is older.
15 // See commit message for details: http://goo.gl/wx6g8O
16 "golang.org/x/crypto/blowfish"
17 )
18
19 // Key derives a key from the password, salt and rounds count, returning a
20 // []byte of length keyLen that can be used as cryptographic key.
21 //
22 // Remember to get a good random salt of at least 16 bytes. Using a higher
23 // rounds count will increase the cost of an exhaustive search but will also
24 // make derivation proportionally slower.
25 func Key(password, salt []byte, rounds, keyLen int) ([]byte, error) {
26 if rounds < 1 {
27 return nil, errors.New("bcrypt_pbkdf: number of rounds is too small")
28 }
29 if len(password) == 0 {
30 return nil, errors.New("bcrypt_pbkdf: empty password")
31 }
32 if len(salt) == 0 || len(salt) > 1<<20 {
33 return nil, errors.New("bcrypt_pbkdf: bad salt length")
34 }
35 if keyLen > 1024 {
36 return nil, errors.New("bcrypt_pbkdf: keyLen is too large")
37 }
38 var shapass, shasalt [sha512.Size]byte
39 var out, tmp [32]byte
40 var cnt [4]byte
41
42 numBlocks := (keyLen + len(out) - 1) / len(out)
43 key := make([]byte, numBlocks*len(out))
44
45 h := sha512.New()
46 h.Write(password)
47 h.Sum(shapass[:0])
48
49 for block := 1; block <= numBlocks; block++ {
50 h.Reset()
51 h.Write(salt)
52 cnt[0] = byte(block >> 24)
53 cnt[1] = byte(block >> 16)
54 cnt[2] = byte(block >> 8)
55 cnt[3] = byte(block)
56 h.Write(cnt[:])
57 bcryptHash(tmp[:], shapass[:], h.Sum(shasalt[:0]))
58 copy(out[:], tmp[:])
59
60 for i := 2; i <= rounds; i++ {
61 h.Reset()
62 h.Write(tmp[:])
63 bcryptHash(tmp[:], shapass[:], h.Sum(shasalt[:0]))
64 for j := 0; j < len(out); j++ {
65 out[j] ^= tmp[j]
66 }
67 }
68
69 for i, v := range out {
70 key[i*numBlocks+(block-1)] = v
71 }
72 }
73 return key[:keyLen], nil
74 }
75
76 var magic = []byte("OxychromaticBlowfishSwatDynamite")
77
78 func bcryptHash(out, shapass, shasalt []byte) {
79 c, err := blowfish.NewSaltedCipher(shapass, shasalt)
80 if err != nil {
81 panic(err)
82 }
83 for i := 0; i < 64; i++ {
84 blowfish.ExpandKey(shasalt, c)
85 blowfish.ExpandKey(shapass, c)
86 }
87 copy(out[:], magic)
88 for i := 0; i < 32; i += 8 {
89 for j := 0; j < 64; j++ {
90 c.Encrypt(out[i:i+8], out[i:i+8])
91 }
92 }
93 // Swap bytes due to different endianness.
94 for i := 0; i < 32; i += 4 {
95 out[i+3], out[i+2], out[i+1], out[i] = out[i], out[i+1], out[i+2], out[i+3]
96 }
97 }