go实现是和之前我python和jsAES加解密的方式一样,可以相互解密。
文件结构
encryption.go
package encryption import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/sha256" "encoding/base64" "encoding/hex" ) // PKCS7Padding填充 func PKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) } // 加密函数 func AesEncrypt(plaintext []byte, key []byte, iv []byte) (string, error) { block, err := aes.NewCipher(key) if err != nil { return "", err } //判断加密快的大小 blockSize := block.BlockSize() //填充 encryptBytes := PKCS7Padding(plaintext, blockSize) //初始化加密数据接收切片 crypted := make([]byte, len(encryptBytes)) //使用cbc加密模式 blockMode := cipher.NewCBCEncrypter(block, iv) //执行加密 blockMode.CryptBlocks(crypted, encryptBytes) // Base64编码 return base64.StdEncoding.EncodeToString(crypted), nil } // Sha256 func Sha256(text string) string { hash := sha256.Sum256([]byte(text)) hexHash := hex.EncodeToString(hash[:]) return hexHash } // PKCS7UnPadding去除填充 func PKCS7UnPadding(data []byte, blockSize int) []byte { length := len(data) unpadding := int(data[length-1]) return data[:(length - unpadding)] } // 解密函数 func AesDecrypt(ciphertext string, key []byte, iv []byte) ([]byte, error) { data, err := base64.StdEncoding.DecodeString(ciphertext) if err != nil { return nil, err } block, err := aes.NewCipher(key) if err != nil { return nil, err } mode := cipher.NewCBCDecrypter(block, iv) mode.CryptBlocks(data, data) // 去除PKCS7Padding data = PKCS7UnPadding(data, block.BlockSize()) return data, nil } func GetDataAes(key string, text string) string { key_sha := Sha256(key) de_key := key_sha[10:26] iv := Sha256(de_key)[20:36] key_byte := []byte(de_key) iv_byte := []byte(iv) ret_byte, err := AesDecrypt(text, key_byte, iv_byte) if err != nil { return "" } return string(ret_byte) } func SetDataAes(key string, text string) string { key_sha := Sha256(key) de_key := key_sha[10:26] iv := Sha256(de_key)[20:36] key_byte := []byte(de_key) iv_byte := []byte(iv) text_byte := []byte(text) ret_str, err := AesEncrypt(text_byte, key_byte, iv_byte) if err != nil { return "" } return ret_str }
main.go
package main import ( "encoding/json" "fmt" "test_t/encryption" ) type Te struct { Name string `json:"name"` Sort int `json:"sort"` } // 主函数 func main() { k := "123456" v := "1arUxHy1ZjRcIORnEs8d/nL+R1546eOPjJzXwYoGC0rxIONR/FQy59SVVJMM7LX0" ret := encryption.GetDataAes(k, v) fmt.Println(ret) k1 := "123456" v1 := Te{Name: "string", Sort: 2147483647} sv1, err := json.Marshal(v1) if err != nil { return } ret1 := encryption.SetDataAes(k1, string(sv1)) fmt.Println(ret1) }
运行结果
拿到python和js中也是可以解密的
标签:AES,return,string,err,加解密,iv,key,go,byte From: https://www.cnblogs.com/moon3496694/p/18540278