项目介绍:
http://docs.getui.com/geyan/elogin/
接入指南之服务器端(包括其他语言的关键代码):
http://docs.getui.com/geyan/server/
签名函数
//signature 签名
//返回sign和timestamp
func signature(appKey string, masterSecret string) (sign string, timestamp int) {
timestamp = int(time.Now().Unix() * 1000)
original := fmt.Sprintf("%v%v%v", appKey, timestamp, masterSecret)
hash := sha256.New()
hash.Write([]byte(original))
sum := hash.Sum(nil)
sign = fmt.Sprintf("%x", sum)
return
}
解密手机号
//decryptCode 解码手机号
func decryptCode(pn, key string) (ret string, err error) {
if len(pn) == 0 || len(key) == 0 {
err = fmt.Errorf("却少参数")
return
}
//长度大于16,只取16位
if len(key) > 16 {
key = key[:16]
}
ret, err = utils.AESDecrypt(pn, key)
return
}
AES CBC 编/解密完整代码
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/hex"
)
const (
//iv 值
iv = "0000000000000000"
)
//AESEncrypt AES CBC encrypt
func AESEncrypt(plainText string, key string) string {
bKey := []byte(key)
bIV := []byte(iv)
bPlainText := PKCS5Padding([]byte(plainText), aes.BlockSize, len(plainText))
block, _ := aes.NewCipher(bKey)
cipherText := make([]byte, len(bPlainText))
mode := cipher.NewCBCEncrypter(block, bIV)
mode.CryptBlocks(cipherText, bPlainText)
//注意:此处使用hex编码
return hex.EncodeToString(cipherText)
}
//PKCS5Padding PKCS5Padding
func PKCS5Padding(cipherText []byte, blockSize int, after int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
//AESDecrypt 解码
func AESDecrypt(decodeStr string, key string) (string, error) {
bKey := []byte(key)
bIV := []byte(iv)
//注意:此处使用使用hex解码
decodeBytes, err := hex.DecodeString(decodeStr)
if err != nil {
return "", err
}
block, err := aes.NewCipher(bKey)
if err != nil {
return "", err
}
blockMode := cipher.NewCBCDecrypter(block, bIV)
origData := make([]byte, len(decodeBytes))
blockMode.CryptBlocks(origData, decodeBytes)
origData = PKCS5UnPadding(origData)
return string(origData), nil
}
//PKCS5UnPadding PKCS5UnPadding
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unPadding := int(origData[length-1])
return origData[:(length - unPadding)]
}
加密解测试
//TestEncrypt 加密
func TestEncrypt(t *testing.T) {
key := "4OeK4LK1CVAlvCw1"
phone := "13888889999"
str := utils.AESEncrypt(phone, key)
fmt.Println("encrypt:", phone, str)
}
//TestDecrypt 解密
func TestDecrypt(t *testing.T) {
pn := "83b180cc035298f0e285aeeb4901678c"
key := "4OeK4LK1CVAlvCw1"
phone, err := utils.AESDecrypt(pn, key)
if err != nil {
t.Fatal("fail", err)
}
fmt.Println("decrypt:", pn, phone)
}