1 // Copyright 2011 The Go Authors. 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.
5 // Package bcrypt implements Provos and Mazières's bcrypt adaptive hashing
6 // algorithm. See http://www.usenix.org/event/usenix99/provos/provos.pdf
7 package bcrypt // import "golang.org/x/crypto/bcrypt"
9 // The code is a port of Provos and Mazières's C implementation.
15 "golang.org/x/crypto/blowfish"
21 MinCost int = 4 // the minimum allowable cost as passed in to GenerateFromPassword
22 MaxCost int = 31 // the maximum allowable cost as passed in to GenerateFromPassword
23 DefaultCost int = 10 // the cost that will actually be set if a cost below MinCost is passed into GenerateFromPassword
26 // The error returned from CompareHashAndPassword when a password and hash do
28 var ErrMismatchedHashAndPassword = errors.New("crypto/bcrypt: hashedPassword is not the hash of the given password")
30 // The error returned from CompareHashAndPassword when a hash is too short to
32 var ErrHashTooShort = errors.New("crypto/bcrypt: hashedSecret too short to be a bcrypted password")
34 // The error returned from CompareHashAndPassword when a hash was created with
35 // a bcrypt algorithm newer than this implementation.
36 type HashVersionTooNewError byte
38 func (hv HashVersionTooNewError) Error() string {
39 return fmt.Sprintf("crypto/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'", byte(hv), majorVersion)
42 // The error returned from CompareHashAndPassword when a hash starts with something other than '$'
43 type InvalidHashPrefixError byte
45 func (ih InvalidHashPrefixError) Error() string {
46 return fmt.Sprintf("crypto/bcrypt: bcrypt hashes must start with '$', but hashedSecret started with '%c'", byte(ih))
49 type InvalidCostError int
51 func (ic InvalidCostError) Error() string {
52 return fmt.Sprintf("crypto/bcrypt: cost %d is outside allowed range (%d,%d)", int(ic), int(MinCost), int(MaxCost))
59 maxCryptedHashSize = 23
65 // magicCipherData is an IV for the 64 Blowfish encryption calls in
66 // bcrypt(). It's the string "OrpheanBeholderScryDoubt" in big-endian bytes.
67 var magicCipherData = []byte{
68 0x4f, 0x72, 0x70, 0x68,
69 0x65, 0x61, 0x6e, 0x42,
70 0x65, 0x68, 0x6f, 0x6c,
71 0x64, 0x65, 0x72, 0x53,
72 0x63, 0x72, 0x79, 0x44,
73 0x6f, 0x75, 0x62, 0x74,
79 cost int // allowed range is MinCost to MaxCost
84 // GenerateFromPassword returns the bcrypt hash of the password at the given
85 // cost. If the cost given is less than MinCost, the cost will be set to
86 // DefaultCost, instead. Use CompareHashAndPassword, as defined in this package,
87 // to compare the returned hashed password with its cleartext version.
88 func GenerateFromPassword(password []byte, cost int) ([]byte, error) {
89 p, err := newFromPassword(password, cost)
96 // CompareHashAndPassword compares a bcrypt hashed password with its possible
97 // plaintext equivalent. Returns nil on success, or an error on failure.
98 func CompareHashAndPassword(hashedPassword, password []byte) error {
99 p, err := newFromHash(hashedPassword)
104 otherHash, err := bcrypt(password, p.cost, p.salt)
109 otherP := &hashed{otherHash, p.salt, p.cost, p.major, p.minor}
110 if subtle.ConstantTimeCompare(p.Hash(), otherP.Hash()) == 1 {
114 return ErrMismatchedHashAndPassword
117 // Cost returns the hashing cost used to create the given hashed
118 // password. When, in the future, the hashing cost of a password system needs
119 // to be increased in order to adjust for greater computational power, this
120 // function allows one to establish which passwords need to be updated.
121 func Cost(hashedPassword []byte) (int, error) {
122 p, err := newFromHash(hashedPassword)
129 func newFromPassword(password []byte, cost int) (*hashed, error) {
134 p.major = majorVersion
135 p.minor = minorVersion
137 err := checkCost(cost)
143 unencodedSalt := make([]byte, maxSaltSize)
144 _, err = io.ReadFull(rand.Reader, unencodedSalt)
149 p.salt = base64Encode(unencodedSalt)
150 hash, err := bcrypt(password, p.cost, p.salt)
158 func newFromHash(hashedSecret []byte) (*hashed, error) {
159 if len(hashedSecret) < minHashSize {
160 return nil, ErrHashTooShort
163 n, err := p.decodeVersion(hashedSecret)
167 hashedSecret = hashedSecret[n:]
168 n, err = p.decodeCost(hashedSecret)
172 hashedSecret = hashedSecret[n:]
174 // The "+2" is here because we'll have to append at most 2 '=' to the salt
175 // when base64 decoding it in expensiveBlowfishSetup().
176 p.salt = make([]byte, encodedSaltSize, encodedSaltSize+2)
177 copy(p.salt, hashedSecret[:encodedSaltSize])
179 hashedSecret = hashedSecret[encodedSaltSize:]
180 p.hash = make([]byte, len(hashedSecret))
181 copy(p.hash, hashedSecret)
186 func bcrypt(password []byte, cost int, salt []byte) ([]byte, error) {
187 cipherData := make([]byte, len(magicCipherData))
188 copy(cipherData, magicCipherData)
190 c, err := expensiveBlowfishSetup(password, uint32(cost), salt)
195 for i := 0; i < 24; i += 8 {
196 for j := 0; j < 64; j++ {
197 c.Encrypt(cipherData[i:i+8], cipherData[i:i+8])
201 // Bug compatibility with C bcrypt implementations. We only encode 23 of
202 // the 24 bytes encrypted.
203 hsh := base64Encode(cipherData[:maxCryptedHashSize])
207 func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) {
209 csalt, err := base64Decode(salt)
214 // Bug compatibility with C bcrypt implementations. They use the trailing
215 // NULL in the key string during expansion.
216 ckey := append(key, 0)
218 c, err := blowfish.NewSaltedCipher(ckey, csalt)
225 for i = 0; i < rounds; i++ {
226 blowfish.ExpandKey(ckey, c)
227 blowfish.ExpandKey(csalt, c)
233 func (p *hashed) Hash() []byte {
234 arr := make([]byte, 60)
244 copy(arr[n:], []byte(fmt.Sprintf("%02d", p.cost)))
248 copy(arr[n:], p.salt)
250 copy(arr[n:], p.hash)
255 func (p *hashed) decodeVersion(sbytes []byte) (int, error) {
256 if sbytes[0] != '$' {
257 return -1, InvalidHashPrefixError(sbytes[0])
259 if sbytes[1] > majorVersion {
260 return -1, HashVersionTooNewError(sbytes[1])
264 if sbytes[2] != '$' {
271 // sbytes should begin where decodeVersion left off.
272 func (p *hashed) decodeCost(sbytes []byte) (int, error) {
273 cost, err := strconv.Atoi(string(sbytes[0:2]))
277 err = checkCost(cost)
285 func (p *hashed) String() string {
286 return fmt.Sprintf("&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}", string(p.hash), p.salt, p.cost, p.major, p.minor)
289 func checkCost(cost int) error {
290 if cost < MinCost || cost > MaxCost {
291 return InvalidCostError(cost)