Skip to content

Commit f06a549

Browse files
committed
feat: add sha512
1 parent c9ef364 commit f06a549

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

sha.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"crypto/hmac"
55
"crypto/sha1"
66
"crypto/sha256"
7+
"crypto/sha512"
78
"encoding/hex"
89
)
910

@@ -46,3 +47,23 @@ func HmacSha256(key string, data string) []byte {
4647
func HmacSha256ToString(key string, data string) string {
4748
return hex.EncodeToString(HmacSha256(key, data))
4849
}
50+
51+
// Sha512 Calculate the sha512 hash of a string
52+
func Sha512(str string) []byte {
53+
h := sha512.New()
54+
_, _ = h.Write([]byte(str))
55+
return h.Sum(nil)
56+
}
57+
58+
// HmacSha512 Calculate the sha512 hash of a string using the HMAC method
59+
func HmacSha512(key string, data string) []byte {
60+
mac := hmac.New(sha512.New, []byte(key))
61+
_, _ = mac.Write([]byte(data))
62+
63+
return mac.Sum(nil)
64+
}
65+
66+
// HmacSha512ToString Calculate the sha512 hash of a string using the HMAC method, outputs lowercase hexits
67+
func HmacSha512ToString(key string, data string) string {
68+
return hex.EncodeToString(HmacSha512(key, data))
69+
}

sha_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,14 @@ func TestHmacSha256ToString(t *testing.T) {
2929
dst := HmacSha256ToString("secret", "apple")
3030
assert.Equal(t, dst, "37431003b2d14b6bddb9334c7ec2ff0ea0c65f96ec650952384e56cae83c398f")
3131
}
32+
33+
func TestSha512(t *testing.T) {
34+
src := "apple"
35+
dst := Sha512(src)
36+
assert.Equal(t, hex.EncodeToString(dst), "844d8779103b94c18f4aa4cc0c3b4474058580a991fba85d3ca698a0bc9e52c5940feb7a65a3a290e17e6b23ee943ecc4f73e7490327245b4fe5d5efb590feb2")
37+
}
38+
39+
func TestHmacSha512ToString(t *testing.T) {
40+
dst := HmacSha512ToString("secret", "apple")
41+
assert.Equal(t, dst, "33c2f1dbd0b93a8a8354ddb888df1ff97b986959d4d710280f66730a913dc9d4535c43a3d51b3c7ff3708355d3d75ab67a105221b8ca803ed4e604f13514b145")
42+
}

0 commit comments

Comments
 (0)