티스토리 뷰

프로그래밍/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



댓글
댓글쓰기 폼