github.com/dgraph-io/dgraph@v1.2.8/types/password.go (about) 1 /* 2 * Copyright 2017-2018 Dgraph Labs, Inc. and Contributors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package types 18 19 import ( 20 "golang.org/x/crypto/bcrypt" 21 22 "github.com/pkg/errors" 23 ) 24 25 const ( 26 pwdLenLimit = 6 27 ) 28 29 // Encrypt encrypts the given plain-text password. 30 func Encrypt(plain string) (string, error) { 31 if len(plain) < pwdLenLimit { 32 return "", errors.Errorf("Password too short, i.e. should have at least 6 chars") 33 } 34 35 encrypted, err := bcrypt.GenerateFromPassword([]byte(plain), bcrypt.DefaultCost) 36 if err != nil { 37 return "", err 38 } 39 40 return string(encrypted), nil 41 } 42 43 // VerifyPassword checks that the plain-text password matches the encrypted password. 44 func VerifyPassword(plain, encrypted string) error { 45 if len(plain) < pwdLenLimit || len(encrypted) == 0 { 46 return errors.Errorf("Invalid password/crypted string") 47 } 48 49 return bcrypt.CompareHashAndPassword([]byte(encrypted), []byte(plain)) 50 }