Browse Source

添加md5和sha256

yjp 1 year ago
parent
commit
3a617ffb02
2 changed files with 31 additions and 2 deletions
  1. 11 0
      encoding/encoding.go
  2. 20 2
      encoding/encoding_test.go

+ 11 - 0
encoding/encoding.go

@@ -4,7 +4,10 @@ import (
 	"bytes"
 	"crypto/aes"
 	"crypto/cipher"
+	"crypto/md5"
+	"crypto/sha256"
 	"encoding/base64"
+	"fmt"
 )
 
 func AESEncrypt(originData string, key string) (string, error) {
@@ -47,6 +50,14 @@ func AESDecrypt(encrypted string, key string) (string, error) {
 	return string(originData), nil
 }
 
+func MD5(origin string) string {
+	return fmt.Sprintf("%x", md5.New().Sum([]byte(origin)))
+}
+
+func SHA256(origin string) string {
+	return fmt.Sprintf("%x", sha256.Sum256([]byte(origin)))
+}
+
 func pkcs7Padding(ciphertext []byte, blockSize int) []byte {
 	padding := blockSize - len(ciphertext)%blockSize
 	padText := bytes.Repeat([]byte{byte(padding)}, padding)

+ 20 - 2
encoding/encoding_test.go

@@ -13,8 +13,8 @@ func TestAES(t *testing.T) {
 		t.Fatal(err)
 	}
 
-	if encrypted == "" {
-		t.Fatal("加密没有密文")
+	if encrypted != "gp4ij9IRlDNQLDNQFwPOhg==" {
+		t.Fatal("加密密文不正确")
 	}
 
 	decrypted, err := AESDecrypt(encrypted, key)
@@ -26,3 +26,21 @@ func TestAES(t *testing.T) {
 		t.Fatal("解密内容和加密内容不一致")
 	}
 }
+
+func TestMD5(t *testing.T) {
+	origin := "foo"
+	md5Str := MD5(origin)
+
+	if md5Str != "666f6fd41d8cd98f00b204e9800998ecf8427e" {
+		t.Fatal("md5字符串不正确")
+	}
+}
+
+func TestSHA256(t *testing.T) {
+	origin := "foo"
+	sha256Str := SHA256(origin)
+
+	if sha256Str != "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae" {
+		t.Fatal("sha256字符串不正确")
+	}
+}