Repository navigation
Expand file tree
/
Copy pathauth_mysql_native.go
More file actions
63 lines (53 loc) · 1.52 KB
/
Copy pathauth_mysql_native.go
File metadata and controls
63 lines (53 loc) · 1.52 KB
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
// Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2023 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
package mysql
import (
"context"
"crypto/sha1"
)
// nativePasswordPlugin implements the mysql_native_password authentication
type nativePasswordPlugin struct {
simpleAuth
}
func init() {
RegisterAuthPlugin("mysql_native_password", func() AuthPlugin { return &nativePasswordPlugin{} })
}
func (p *nativePasswordPlugin) InitAuth(ctx context.Context, authData []byte, auth *AuthContext) ([]byte, error) {
if auth.Password() == "" {
return nil, nil
}
if len(authData) < 20 {
return nil, ErrMalformPkt
}
return p.scramblePassword(authData[:20], auth.Password()), nil
}
// Hash password using 4.1+ method (SHA1)
func (p *nativePasswordPlugin) scramblePassword(scramble []byte, password string) []byte {
if len(password) == 0 {
return nil
}
// stage1Hash = SHA1(password)
crypt := sha1.New()
crypt.Write([]byte(password))
stage1 := crypt.Sum(nil)
// scrambleHash = SHA1(scramble + SHA1(stage1Hash))
// inner Hash
crypt.Reset()
crypt.Write(stage1)
hash := crypt.Sum(nil)
// outer Hash
crypt.Reset()
crypt.Write(scramble)
crypt.Write(hash)
scramble = crypt.Sum(nil)
// token = scrambleHash XOR stage1Hash
for i := range scramble {
scramble[i] ^= stage1[i]
}
return scramble
}