概述
目录
- Bcrypt加密:
- Scrypt加密
Bcrypt加密:
package main
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
return string(bytes), err
}
func CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}
func main() {
password := "secret"
hash, _ := HashPassword(password) // ignore error for the sake of simplicity
fmt.Println("Password:", password)
fmt.Println("Hash:
", hash)
match := CheckPasswordHash(password, hash)
fmt.Println("Match:
", match)
}
Scrypt加密
官网案例:
package main
import (
"encoding/base64"
"fmt"
"log"
"golang.org/x/crypto/scrypt"
)
func main() {
// DO NOT use this salt value; generate your own random salt. 8 bytes is
// a good length.
salt := []byte{0xc8, 0x28, 0xf2, 0x58, 0xa7, 0x6a, 0xad, 0x7b}
dk, err := scrypt.Key([]byte("some password"), salt, 1<<15, 8, 1, 32)
if err != nil {
log.Fatal(err)
}
fmt.Println(base64.StdEncoding.EncodeToString(dk))
}
func ScryptPw(password string) string {
const KeyLen = 10
salt := make([]byte, 8)
salt = []byte{12, 32, 4, 6, 66, 22, 222, 11}
HashPw, err := scrypt.Key([]byte(password), salt, 16384, 8, 1, KeyLen)
if err != nil {
log.Fatal(err)
}
fpwd := base64.StdEncoding.EncodeToString(HashPw)
return fpwd
}
最后
以上就是留胡子时光为你收集整理的Bcrypt和Scrypt加密的全部内容,希望文章能够帮你解决Bcrypt和Scrypt加密所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复