tianyuan-api-server/aes.go
2024-10-02 11:27:51 +08:00

77 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
)
// PKCS7填充
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
// AES CBC模式加密Base64传入传出
func AesEncrypt(plainText, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
blockSize := block.BlockSize()
plainText = PKCS7Padding(plainText, blockSize)
cipherText := make([]byte, blockSize+len(plainText))
iv := cipherText[:blockSize] // 使用前blockSize字节作为IV
_, err = io.ReadFull(rand.Reader, iv)
if err != nil {
return "", err
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText[blockSize:], plainText)
return base64.StdEncoding.EncodeToString(cipherText), nil
}
type Data struct {
Name string `json:"name"`
Email string `json:"email"`
}
func main() {
// 定义 AES 密钥
key, _ := hex.DecodeString("958de6826370b57d9ae93b88e5009e26")
var data interface{}
data = map[string]interface{}{
"id_card": "45212220000827423X",
"name": "张荣宏",
}
// 将结构体转为 JSON 字符串
jsonData, err := json.Marshal(data)
if err != nil {
fmt.Println("JSON 序列化错误:", err)
return
}
// 对 JSON 数据进行加密
encryptedData, err := AesEncrypt(jsonData, key)
if err != nil {
fmt.Println("加密错误:", err)
return
}
// 输出加密后的结果
fmt.Println("加密后的数据:", encryptedData)
}