Golang 加密/解密算法

李鹏0 1,404 次浏览

这个算法是针对之前 PHP 加密算法(可逆) 中的算法得来的。
 
 

package main


import (
	"crypto/md5"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	// "log"
	// "reflect"
)

//生成 MD5
func Md5(str string) string {
	h := md5.New()
	io.WriteString(h, str)
	str = fmt.Sprintf("%x", h.Sum(nil))
	return str
}

// Base64Decode
func Base64Decode(str string) string {
	data, _ := base64.StdEncoding.DecodeString(str)
	return string(data)
}

// Base64Encode
func Base64Encode(str string) string {
	return base64.StdEncoding.EncodeToString([]byte(str))
}

// 解密
func Decrypt(data string, key string) (map[string]interface{}, error) {
	key = Md5(key)

	var (
		char = ""
		str  = ""
		x    = 0
		l    = len(key)
	)
	data = Base64Decode(data)
	lenths := len(data)

	for i := 0; i < lenths; i++ {
		if x == l {
			x = 0
		}
		char = char + fmt.Sprintf("%s", key[x:x+1])
		x++
	}

	for i := 0; i < lenths; i++ {
		if data[i : i+1][0] < char[i : i+1][0] {
			str = str + string(char[i : i+1][0]-data[i : i+1][0])
		} else {
			str = str + string((data[i : i+1][0])-(char[i : i+1][0]))
		}
	}
	var newData map[string]interface{}
	if err := json.Unmarshal([]byte(str), &newData); err != nil {
		return newData, errors.New("数据错误")
	}

	return newData, nil
}

// 数据加密
func Encrypt(data *map[string]interface{}, key string) (string, error) {
	var (
		char, str string
		x, l, n   int
		err       error
		u8        []uint8
	)

	key = Md5(key)
	l = len(key)

	res, err := json.Marshal(data)
	if err != nil {
		return "", err
	}
	str = string(res)
	n = len(str)

	for i := 0; i < n; i++ {
		if x == l {
			x = 0
		}
		char += string(key[x])
		x++
	}

	for i := 0; i < n; i++ {
		u8 = append(u8, str[i]+char[i])
	}
	return Base64Encode(string(u8)), nil
}


发表评论

? razz sad evil ! smile oops grin eek shock ??? cool lol mad twisted roll wink idea arrow neutral cry mrgreen