将加密/解密相关的包从encoding目录迁移到crypto目录下,并改进包中的interface{]参数转换方式

This commit is contained in:
john 2018-08-08 10:05:16 +08:00
parent e8b83d4db6
commit 5ad9b272a6
5 changed files with 18 additions and 29 deletions

View File

@ -11,10 +11,10 @@ import (
"hash/crc32"
)
func EncodeString(v string) uint32 {
func EncryptString(v string) uint32 {
return crc32.ChecksumIEEE([]byte(v))
}
func EncodeBytes(v []byte) uint32 {
func EncryptBytes(v []byte) uint32 {
return crc32.ChecksumIEEE(v)
}

View File

@ -1,4 +1,4 @@
package gdes_test
package gdes
import (
"testing"

View File

@ -10,46 +10,35 @@ package gmd5
import (
"crypto/md5"
"fmt"
"encoding/json"
"reflect"
"os"
"io"
"gitee.com/johng/gf/g/os/glog"
"gitee.com/johng/gf/g/util/gconv"
)
// 将任意类型的变量进行md5摘要(注意map等非排序变量造成的不同结果)
func Encode(v interface{}) string {
func Encrypt(v interface{}) string {
h := md5.New()
if "string" == reflect.TypeOf(v).String() {
h.Write([]byte(v.(string)))
} else {
b, err := json.Marshal(v)
if err != nil {
return ""
} else {
h.Write(b)
}
}
h.Write([]byte(gconv.Bytes(v)))
return fmt.Sprintf("%x", h.Sum(nil))
}
// 将字符串进行MD5哈希摘要计算
func EncodeString(v string) string {
func EncryptString(v string) string {
h := md5.New()
h.Write([]byte(v))
return fmt.Sprintf("%x", h.Sum(nil))
}
// 将文件内容进行MD5哈希摘要计算
func EncodeFile(path string) string {
func EncryptFile(path string) string {
f, e := os.Open(path)
if e != nil {
glog.Fatalln(e)
return ""
}
h := md5.New()
_, e = io.Copy(h, f)
if e != nil {
glog.Fatalln(e)
return ""
}
return fmt.Sprintf("%x", h.Sum(nil))
}

View File

@ -12,32 +12,32 @@ import (
"encoding/hex"
"os"
"io"
"gitee.com/johng/gf/g/os/glog"
"gitee.com/johng/gf/g/encoding/gmd5"
"gitee.com/johng/gf/g/util/gconv"
)
// 将任意类型的变量进行SHA摘要(注意map等非排序变量造成的不同结果)
// 内部使用了md5计算因此效率会稍微差一些更多情况请使用 EncodeString
func Encode(v interface{}) string {
return EncodeString(gmd5.Encode(v))
func Encrypt(v interface{}) string {
r := sha1.Sum(gconv.Bytes(v))
return hex.EncodeToString(r[:])
}
// 对字符串行SHA1摘要计算
func EncodeString(s string) string {
func EncryptString(s string) string {
r := sha1.Sum([]byte(s))
return hex.EncodeToString(r[:])
}
// 对文件内容进行SHA1摘要计算
func EncodeFile(path string) string {
func EncryptFile(path string) string {
f, e := os.Open(path)
if e != nil {
glog.Fatalln(e)
return ""
}
h := sha1.New()
_, e = io.Copy(h, f)
if e != nil {
glog.Fatalln(e)
return ""
}
return hex.EncodeToString(h.Sum(nil))
}