|
@@ -0,0 +1,92 @@
|
|
|
+package services
|
|
|
+
|
|
|
+import (
|
|
|
+ "crypto/aes"
|
|
|
+ "crypto/cipher"
|
|
|
+ "crypto/rand"
|
|
|
+ "encoding/base64"
|
|
|
+ "fmt"
|
|
|
+ "io"
|
|
|
+ "strconv"
|
|
|
+)
|
|
|
+
|
|
|
+var aseKey = []byte("kmk6ln3n4mibig8p") // 加密密钥(必须是16、24或32字节)
|
|
|
+
|
|
|
+func init() {
|
|
|
+ // 原始数据
|
|
|
+ originalData := 123
|
|
|
+
|
|
|
+ // 加密数据
|
|
|
+ encryptedData, err := encrypt(originalData, aseKey)
|
|
|
+ if err != nil {
|
|
|
+ fmt.Println("加密时出错:", err)
|
|
|
+ return
|
|
|
+ }
|
|
|
+ fmt.Println("加密后的数据:", encryptedData)
|
|
|
+
|
|
|
+ // 解密数据
|
|
|
+ decryptedData, err := decrypt(encryptedData, aseKey)
|
|
|
+ if err != nil {
|
|
|
+ fmt.Println("解密时出错:", err)
|
|
|
+ return
|
|
|
+ }
|
|
|
+ fmt.Println("解密后的数据:", decryptedData)
|
|
|
+}
|
|
|
+
|
|
|
+func encrypt(data int, key []byte) (string, error) {
|
|
|
+ // 将数据转换为字节数组
|
|
|
+ dataBytes := []byte(fmt.Sprintf("%d", data))
|
|
|
+
|
|
|
+ // 创建一个新的 AES 块
|
|
|
+ block, err := aes.NewCipher(key)
|
|
|
+ if err != nil {
|
|
|
+ return "", err
|
|
|
+ }
|
|
|
+
|
|
|
+ // 创建一个加密流
|
|
|
+ ciphertext := make([]byte, aes.BlockSize+len(dataBytes))
|
|
|
+ iv := ciphertext[:aes.BlockSize]
|
|
|
+ if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
|
|
+ return "", err
|
|
|
+ }
|
|
|
+
|
|
|
+ // 使用密钥加密数据
|
|
|
+ stream := cipher.NewCFBEncrypter(block, iv)
|
|
|
+ stream.XORKeyStream(ciphertext[aes.BlockSize:], dataBytes)
|
|
|
+
|
|
|
+ // 返回加密后的数据(使用base64编码以便于传输)
|
|
|
+ return base64.StdEncoding.EncodeToString(ciphertext), nil
|
|
|
+}
|
|
|
+
|
|
|
+func decrypt(data string, key []byte) (int, error) {
|
|
|
+ // 解码base64数据
|
|
|
+ ciphertext, err := base64.StdEncoding.DecodeString(data)
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
+
|
|
|
+ // 创建一个新的 AES 块
|
|
|
+ block, err := aes.NewCipher(key)
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
+
|
|
|
+ // 解密流
|
|
|
+ if len(ciphertext) < aes.BlockSize {
|
|
|
+ return 0, fmt.Errorf("加密数据长度不够")
|
|
|
+ }
|
|
|
+ iv := ciphertext[:aes.BlockSize]
|
|
|
+ ciphertext = ciphertext[aes.BlockSize:]
|
|
|
+
|
|
|
+ // 解密数据
|
|
|
+ stream := cipher.NewCFBDecrypter(block, iv)
|
|
|
+ stream.XORKeyStream(ciphertext, ciphertext)
|
|
|
+
|
|
|
+ // 将解密的数据转换为int
|
|
|
+ decryptedData, err := strconv.Atoi(string(ciphertext))
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
+
|
|
|
+ return decryptedData, nil
|
|
|
+}
|