티스토리 뷰

프로그래밍/Go

[bcrypt] 비밀번호 생성, 확인

메모하는습관 2015. 11. 12. 14:57

bcrypt 설치

go get -u -v golang.org/x/crypto/bcrypt



예제 코드

package main

import (
	"golang.org/x/crypto/bcrypt"
)

func main() {
	pwd := "abcdefg1234"
	hashedPwd, err := GeneratePassword(pwd)

	if err == nil {
		equalPwd := EqualPassword(hashedPwd, pwd)

		fmt.Println("hashed password : ", hashedPwd)
		fmt.Println("equal password : ", equalPwd)
	}
}

func GeneratePassword(password string) (string, error) {
	pass := []byte(password)

	hashed, err := bcrypt.GenerateFromPassword(pass, bcrypt.DefaultCost)

	return string(hashed), err
}

func EqualPassword(hashedPassword string, password string) bool {
	return bcrypt.CompareHashAndPassword(
		[]byte(hashedPassword),
		[]byte(password)) == nil
}

결과

hashed password :  $2a$10$zwLky147As5Ch4rwEG7Ih./v68OTq0vWyXyBPcnmvMYKdL82eAXr6
equal password :  true



댓글
댓글쓰기 폼
«   2020/08   »
            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          
Total
411,868
Today
20
Yesterday
143
글 보관함