完成游戏人生账号绑定、解绑、绑定信息的接口开发
This commit is contained in:
58
utility/encrypt/aes.go
Normal file
58
utility/encrypt/aes.go
Normal file
@ -0,0 +1,58 @@
|
||||
package encrypt
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// AesEncrypt 使用 AES-CBC 模式对数据进行加密。
|
||||
//
|
||||
// 参数:
|
||||
// - plainText: 原始明文数据(必须是任意长度)
|
||||
// - key: 加密密钥(长度必须是 16、24 或 32 字节)
|
||||
// - iv: 初始化向量(必须是 16 字节)
|
||||
//
|
||||
// 返回值:
|
||||
// - 加密后的密文
|
||||
// - 错误信息(如果加密失败)
|
||||
func AesEncrypt(plainText, key, iv []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(iv) != aes.BlockSize {
|
||||
return nil, errors.New("IV 长度必须为 16 字节")
|
||||
}
|
||||
|
||||
plainText = pkcs7Padding(plainText, aes.BlockSize)
|
||||
cipherText := make([]byte, len(plainText))
|
||||
|
||||
mode := cipher.NewCBCEncrypter(block, iv)
|
||||
mode.CryptBlocks(cipherText, plainText)
|
||||
|
||||
return cipherText, nil
|
||||
}
|
||||
|
||||
// pkcs7Padding 对数据进行 PKCS7 填充。
|
||||
//
|
||||
// 参数:
|
||||
// - data: 原始数据
|
||||
// - blockSize: 块大小(通常为 16)
|
||||
//
|
||||
// 返回值:
|
||||
// - 填充后的数据
|
||||
func pkcs7Padding(data []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(data)%blockSize
|
||||
padText := bytesRepeat(byte(padding), padding)
|
||||
return append(data, padText...)
|
||||
}
|
||||
|
||||
// bytesRepeat 返回一个重复 count 次的字节切片。
|
||||
func bytesRepeat(b byte, count int) []byte {
|
||||
buf := make([]byte, count)
|
||||
for i := 0; i < count; i++ {
|
||||
buf[i] = b
|
||||
}
|
||||
return buf
|
||||
}
|
||||
19
utility/encrypt/bs4.go
Normal file
19
utility/encrypt/bs4.go
Normal file
@ -0,0 +1,19 @@
|
||||
package encrypt
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
)
|
||||
|
||||
// Base64Encode 对字符串进行 base64 编码
|
||||
func Base64Encode(data []byte) string {
|
||||
return base64.StdEncoding.EncodeToString(data)
|
||||
}
|
||||
|
||||
// Base64Decode 对 base64 编码的字符串进行解码
|
||||
func Base64Decode(encoded string) ([]byte, error) {
|
||||
decodedBytes, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return decodedBytes, nil
|
||||
}
|
||||
@ -1,4 +1,4 @@
|
||||
package utility
|
||||
package encrypt
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
package utility
|
||||
package encrypt
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
Reference in New Issue
Block a user