Skip to content

Commit

Permalink
add: md5 function
Browse files Browse the repository at this point in the history
  • Loading branch information
xvrzhao committed Apr 15, 2020
1 parent 7e8524f commit d4e59e5
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 15 deletions.
13 changes: 13 additions & 0 deletions crypto/md5.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package crypto

import (
"crypto/md5"
"encoding/hex"
)

// Md5 Calculate the md5 hash of str and return the hex string of the result.
func Md5(str string) string {
h := md5.New()
h.Write([]byte(str))
return hex.EncodeToString(h.Sum(nil))
}
9 changes: 9 additions & 0 deletions crypto/md5_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package crypto

import "testing"

func TestMd5(t *testing.T) {
if Md5("xvrzhao") != "6452adf3f17e11c592f0c3e7e0afa302" {
t.Error("md5 failed")
}
}
17 changes: 3 additions & 14 deletions password/salt_hash.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package password

import (
"crypto/md5"
"encoding/hex"
"github.com/micro-stacks/utils/crypto"
"github.com/micro-stacks/utils/strings"
)

Expand All @@ -11,23 +10,13 @@ import (
// saltHashPassword = md5(md5(password) + salt)
func SaltHashPwd(password string, saltLen int) (saltHashPassword, salt string) {
salt = strings.RandLetterNum(saltLen)
h := md5.New()
h.Write([]byte(password))
saltHashPassword = hex.EncodeToString(h.Sum(nil)) + salt
h.Reset()
h.Write([]byte(saltHashPassword))
saltHashPassword = hex.EncodeToString(h.Sum(nil))
saltHashPassword = crypto.Md5(crypto.Md5(password) + salt)
return
}

// VerifySaltHashPwd verifies whether saltHashPassword was generated from password and salt.
func VerifySaltHashPwd(password, salt, saltHashPassword string) bool {
h := md5.New()
h.Write([]byte(password))
p := hex.EncodeToString(h.Sum(nil)) + salt
h.Reset()
h.Write([]byte(p))
if p = hex.EncodeToString(h.Sum(nil)); p != saltHashPassword {
if crypto.Md5(crypto.Md5(password)+salt) != saltHashPassword {
return false
}
return true
Expand Down
2 changes: 1 addition & 1 deletion password/salt_hash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ func TestVerifySaltHashPwd(t *testing.T) {

t.Log(p, s, sp)

if b := VerifySaltHashPwd(p, s, sp); b != true {
if b := VerifySaltHashPwd(p, s, sp); !b {
t.Fail()
return
}
Expand Down

0 comments on commit d4e59e5

Please sign in to comment.