packagemainimport("bytes""crypto/aes""crypto/cipher""crypto/rand""encoding/base64""errors""fmt""io")funcEncryptAESCBC(key,textstring)(string,error){block,err:=aes.NewCipher([]byte(key))iferr!=nil{return"",err}plaintext:=padCBC([]byte(text))ciphertext:=make([]byte,aes.BlockSize+len(plaintext))iv:=ciphertext[:aes.BlockSize]if_,err:=io.ReadFull(rand.Reader,iv);err!=nil{return"",err}mode:=cipher.NewCBCEncrypter(block,iv)mode.CryptBlocks(ciphertext[aes.BlockSize:],plaintext)returnbase64.StdEncoding.EncodeToString(ciphertext),nil}funcDecryptAESCBC(key,textstring)(string,error){block,err:=aes.NewCipher([]byte(key))iferr!=nil{return"",err}ciphertext,err:=base64.StdEncoding.DecodeString(text)iferr!=nil{return"",err}iflen(ciphertext)<aes.BlockSize{return"",errors.New("ciphertext too short")}iv:=ciphertext[:aes.BlockSize]ciphertext=ciphertext[aes.BlockSize:]iflen(ciphertext)%aes.BlockSize!=0{return"",errors.New("ciphertext is not a multiple of the block size")}mode:=cipher.NewCBCDecrypter(block,iv)mode.CryptBlocks(ciphertext,ciphertext)returnstring(unpadCBC(ciphertext)),nil}// PKCS7 padding
funcpadCBC(in[]byte)[]byte{padding:=aes.BlockSize-(len(in)%aes.BlockSize)padtext:=bytes.Repeat([]byte{byte(padding)},padding)returnappend(in,padtext...)}funcunpadCBC(in[]byte)[]byte{padding:=int(in[len(in)-1])returnin[:len(in)-padding]}funcmain(){key:="example key 1234"text:="Hello, world!"encrypted,err:=EncryptAESCBC(key,text)iferr!=nil{fmt.Println("Error encrypting:",err)return}fmt.Println("Encrypted:",encrypted)decrypted,err:=DecryptAESCBC(key,encrypted)iferr!=nil{fmt.Println("Error decrypting:",err)return}fmt.Println("Decrypted:",decrypted)}