github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/helper/password.go (about)

     1  package helper
     2  
     3  import (
     4  	"crypto/hmac"
     5  	"crypto/md5"
     6  	"crypto/sha1"
     7  	"crypto/sha256"
     8  	"encoding/hex"
     9  	//"fmt"
    10  	"time"
    11  )
    12  
    13  func EncryptHash(password string, salt []byte) string {
    14  	if salt == nil {
    15  		m := md5.New()
    16  		m.Write([]byte(time.Now().String()))
    17  		s := hex.EncodeToString(m.Sum(nil))
    18  		salt = []byte(s[2:10])
    19  	} else if len(salt) != 8 {
    20  		panic("Encrypt_hash: salt != 8")
    21  	}
    22  
    23  	mac := hmac.New(sha256.New, salt)
    24  	mac.Write([]byte(password))
    25  	//s := fmt.Sprintf("%x", (mac.Sum(salt)))
    26  	s := hex.EncodeToString(mac.Sum(nil))
    27  
    28  	hasher := sha1.New()
    29  	hasher.Write([]byte(s))
    30  
    31  	//result := fmt.Sprintf("%x", (hasher.Sum(nil)))
    32  	result := hex.EncodeToString(hasher.Sum(nil))
    33  
    34  	p := string(salt) + result
    35  
    36  	return p
    37  }
    38  
    39  func ValidateHash(hashed string, input_password string) bool {
    40  	switch l := len(hashed); {
    41  	case l == 48:
    42  		salt := hashed[0:8]
    43  		if hashed == EncryptHash(input_password, []byte(salt)) {
    44  			return true
    45  		} else {
    46  			return false
    47  		}
    48  	case l == 32:
    49  		//For discuz
    50  		return false
    51  	}
    52  	return false
    53  }
    54  
    55  /*
    56  func main() {
    57  	hashed := EncryptHash("password", nil)
    58  	fmt.Println(hashed)
    59  	fmt.Println("----------------------------------------------")
    60  	fmt.Println(ValidateHash(hashed, "password"))
    61  }
    62  */