2
0

More than 1 year has passed since last update.

goでパスワードを平文ではなくハッシュ化して保存し、ログインまで行う

Posted at

goでパスワードのハッシュ化と、
ハッシュ化したパスワードを使用してログイン機能作ってみたかったので、
テスト的ではありますが作ってみました。

実装

ハッシュ化と称号に関してはbcryptを使用します。

$ go get golang.org/x/crypto/bcrypt

リクエストで文字列のパスワードを受け取ってハッシュ化する関数は以下のような形。
bycrypt.GenerateFromPassword()で文字列をハッシュ化します

func encryptPassword(password string) (string, error) {
	// パスワードの文字列をハッシュ化する
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return "", err
	}
	return string(hash), nil
}

GenerateFromPassword returns the bcrypt hash of the password at the given cost. If the cost given is less than MinCost, the cost will be set to DefaultCost, instead. Use CompareHashAndPassword, as defined in this package, to compare the returned hashed password with its cleartext version. GenerateFromPassword does not accept passwords longer than 72 bytes, which is the longest password bcrypt will operate on.

和訳

GenerateFromPassword は、与えられたコストでパスワードの bcrypt ハッシュを返します。指定されたコストが MinCost より小さい場合は、代わりに DefaultCost が設定されます。このパッケージで定義されている CompareHashAndPassword を使用して、返されたハッシュ化されたパスワードとその平文バージョンを比較します。GenerateFromPassword は、bcrypt が操作できる最長パスワードである 72 バイトより長いパスワードを受け付けません。

リクエストで受け取ったパスワードと、
ハッシュで保存されているパスワードを比較して判定する関数は以下のような形。
bcrypt.CompareHashAndPassword()で比較を行います。

func compareHashPassword(hashedPassword, requestPassword string) error {
	// パスワードの文字列をハッシュ化して、既に登録されているハッシュ化したパスワードと比較します
	if err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(requestPassword)); err != nil {
		return err
	}
	return nil
}

CompareHashAndPassword compares a bcrypt hashed password with its possible plaintext equivalent. Returns nil on success, or an error on failure.

和訳

CompareHashAndPassword は、bcrypt でハッシュ化されたパスワードと、それに相当する可能性のある平文とを比較します。成功した場合は nil を返し、失敗した場合はエラーを返します。

補足

Chat GPTに聞いてみましたが、bcryptのセキュリティ性に関しては問題なさそうな感じです

スクリーンショット 2023-09-17 19.54.52.png

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0