first commit
This commit is contained in:
78
aes.go
Normal file
78
aes.go
Normal file
@@ -0,0 +1,78 @@
|
||||
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("c58e5aa2f91ddd5e0947ffc119b029c4")
|
||||
|
||||
var data interface{}
|
||||
|
||||
data = map[string]interface{}{
|
||||
"id_card": "45212220000827423X",
|
||||
"mobile_no": "18276151590",
|
||||
"name": "张荣宏",
|
||||
"time_range": "5",
|
||||
}
|
||||
|
||||
// 将结构体转为 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)
|
||||
}
|
||||
Reference in New Issue
Block a user