From 6c53012543906b8dd783bea16fe9ccd171b67be7 Mon Sep 17 00:00:00 2001 From: Martin Geno Date: Thu, 12 May 2016 19:16:39 +0200 Subject: [PATCH] password lib with autoupgrade example --- lib_password/check_login.go | 14 ++++++++++ lib_password/password.go | 55 +++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 lib_password/check_login.go create mode 100644 lib_password/password.go diff --git a/lib_password/check_login.go b/lib_password/check_login.go new file mode 100644 index 0000000..44ee745 --- /dev/null +++ b/lib_password/check_login.go @@ -0,0 +1,14 @@ +package libPassword + +import "fmt" + +func main(){ + password_str := "root" + x,err :=Validate("pbkdf2_sha1$10000$a5viM+Paz3o=$orD4shu1Ss+1wPAhAt8hkZ/fH7Y=",password_str); if x { + fmt.Println("Valide") + if err { + fmt.Print("Deprecated,replace with: ") + fmt.Println(NewHesh(password_str)) + } + } +} diff --git a/lib_password/password.go b/lib_password/password.go new file mode 100644 index 0000000..5e08c89 --- /dev/null +++ b/lib_password/password.go @@ -0,0 +1,55 @@ +package libPassword + +import "golang.org/x/crypto/pbkdf2" +import "hash" +import "strconv" +import "encoding/base64" +import "crypto/sha1" +import "crypto/sha256" +import "crypto/sha512" +import "crypto/rand" +import "fmt" +import "strings" + +const ( + salt_length = 8 + hesh_length = 20 + interations = 10000 + hashfunc string = "sha256" +) +var hashlib = map[string] func()hash.Hash{ + "sha1":sha1.New, + "sha256":sha256.New, + "sha512":sha512.New, + } + +func Validate(hash,password string)(output,replace bool){ + parts := strings.Split(hash,"$") + if len(parts) == 3 { + return false,false + } + cur_iter,err := strconv.Atoi(parts[1]) + if err != nil { + return false,false + } + hashfunc_c := strings.Split(parts[0],"_")[1] + replace = (hashfunc_c!=hashfunc) + + dk := pbkdf2.Key([]byte(password), []byte(parts[2]), cur_iter, len(parts[3])-8, hashlib[hashfunc_c]) + x := fmt.Sprintf("pbkdf2_%s$%s$%s$%s",hashfunc_c,parts[1],parts[2],base64.StdEncoding.EncodeToString(dk)) + output = (x==hash) + return +} +func GenerateRandomString(n int) (string, error) { + b := make([]byte, n) + _, err := rand.Read(b) + if err != nil { + return "", err + } + return base64.URLEncoding.EncodeToString(b), nil +} +func NewHesh(password string)string{ + salt,_ := GenerateRandomString(salt_length) + dk := pbkdf2.Key([]byte(password), []byte(salt), interations, hesh_length, hashlib[hashfunc]) + return fmt.Sprintf("pbkdf2_%s$%d$%s$%s",hashfunc,interations,salt,base64.StdEncoding.EncodeToString(dk)) +}