### 使用場景
+ 對用戶輸入的密碼進行加密
+ 用戶登錄時對用戶的密碼進行比對
### 例子
```go
package main
import (
"errors"
"fmt"
"golang.org/x/crypto/bcrypt"
)
func main() {
userPassword := "123456"
passwordbyte, err := GeneratePassword(userPassword)
if err != nil {
fmt.Println("加密出錯了")
}
fmt.Println(passwordbyte)
// passwordstring := string(passwordbyte)
// fmt.Println(passwordstring)
//模擬這個字符串是從數據庫讀取出來的 值是12345678
mysql_password := "$2a$10$I8WaWXgiBw8j/IBejb3t/.s5NoOYLvoQzL6mIM2g3TEu4z0HenzqK"
isOk, _ := ValidatePassword(userPassword, mysql_password)
if !isOk {
fmt.Println("密碼錯誤")
return
}
fmt.Println(isOk)
}
//GeneratePassword 給密碼就行加密操作
func GeneratePassword(userPassword string) ([]byte, error) {
return bcrypt.GenerateFromPassword([]byte(userPassword), bcrypt.DefaultCost)
}
//ValidatePassword 密碼比對
func ValidatePassword(userPassword string, hashed string) (isOK bool, err error) {
if err = bcrypt.CompareHashAndPassword([]byte(hashed), []byte(userPassword)); err != nil {
return false, errors.New("密碼比對錯誤!")
}
return true, nil
}
```
**注意**
`golang.org/x/crypto/bcrypt`這個包下載有些難度,需要的小伙伴可以自行百度
官網地址:http://golang.org/x/crypto/bcrypt