github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/pingcap/tidb/util/auth.go (about) 1 // Copyright 2015 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package util 15 16 import ( 17 "crypto/sha1" 18 "encoding/hex" 19 20 "github.com/insionng/yougam/libraries/juju/errors" 21 ) 22 23 // CalcPassword is the algorithm convert hashed password to auth string. 24 // See: https://dev.mysql.com/doc/internals/en/secure-password-authentication.html 25 // SHA1( password ) XOR SHA1( "20-bytes random data from server" <concat> SHA1( SHA1( password ) ) ) 26 func CalcPassword(scramble, sha1pwd []byte) []byte { 27 if len(sha1pwd) == 0 { 28 return nil 29 } 30 // scrambleHash = SHA1(scramble + SHA1(sha1pwd)) 31 // inner Hash 32 hash := Sha1Hash(sha1pwd) 33 // outer Hash 34 crypt := sha1.New() 35 crypt.Write(scramble) 36 crypt.Write(hash) 37 scramble = crypt.Sum(nil) 38 // token = scrambleHash XOR stage1Hash 39 for i := range scramble { 40 scramble[i] ^= sha1pwd[i] 41 } 42 return scramble 43 } 44 45 // Sha1Hash is an util function to calculate sha1 hash. 46 func Sha1Hash(bs []byte) []byte { 47 crypt := sha1.New() 48 crypt.Write(bs) 49 return crypt.Sum(nil) 50 } 51 52 // EncodePassword converts plaintext password to hashed hex string. 53 func EncodePassword(pwd string) string { 54 if len(pwd) == 0 { 55 return "" 56 } 57 hash := Sha1Hash([]byte(pwd)) 58 return hex.EncodeToString(hash) 59 } 60 61 // DecodePassword converts hex string password to byte array. 62 func DecodePassword(pwd string) ([]byte, error) { 63 x, err := hex.DecodeString(pwd) 64 if err != nil { 65 return nil, errors.Trace(err) 66 } 67 return x, nil 68 }