0
1

More than 1 year has passed since last update.

ログイン認証時のパスワード比較(Golangで実装)

Posted at

はじめに

DBにパスワードを平文のまま保存してはいけません。万一、情報漏洩した場合、不正利用されないにパスワードを暗号化する必要があります。今回は、Golangでどう実装するのかを残していきたいと思います。

概要

まず、パスワードを生成します。その後、パスワードを特定されにくくするため、ソルト値を付与。最後に暗号化を実施するという流れで暗号化していきます。
image.png

実装

main.go
package main

import (
	"fmt"

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


func main() {

	solt := "1234567890"
	// パスワードのハッシュ化
	hash, err := EncryptPassword("password"+solt)
	if err != nil {
		panic(err)
	}
	fmt.Println(hash)

	// パスワードの比較
	comparedResult := CompareHashAndPassword(hash, "password"+solt)
	if comparedResult{
		fmt.Println("一致")
	}else{
		fmt.Println("不一致")
	}
}

/** パスワードの暗号化 */
func EncryptPassword(password string) (string, error) {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	return string(hash), err
}

/** パスワード比較(DB格納値とリクエスト値の比較) */
func CompareHashAndPassword(hash, password string) bool {

	err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))

	return err == nil
}
実行結果
~/go/src/jikken$ go run main.go
$2a$10$7HPPxNgVjRgS8KPjg4mIcuyVw/QZg9uE87SHoNbMo3o.31tBpbJoy
一致

ちなみに下記が一致しない場合の実行結果。

実行結果
~/go/src/jikken$ go run main.go
$2a$10$dynJb6kvVDcoOqC4sNdYaecKnhMfGQ6/SQHYhxLLeVUKgtyiE1q6.
不一致

意外と簡単ですね!!!

0
1
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
0
1