I am trying to achieve AES-256-CBC encryption in PHP. I got a data output from Golang code. I am try to get encrypted values in PHP, but it always failed I try to decrypt it .
Here is my encrypt&decrypt code in Golang
var key = "abcdabcdabcdabcd"
func main() {
str := "hello world"
fmt.Printf("Origin Data : %v\n", str)
encryptStr := Encrypt(str)
fmt.Printf("Encrypt Data : %v\n", encryptStr)
decryptstr := Decrypt(encryptStr)
fmt.Printf("Decrypt Data : %v\n", decryptstr)
}
func Encrypt(str string) string {
data := PKCS5Padding([]byte(str))
iv := make([]byte, 16)
rand.Read(iv)
blockCipher, err := aes.NewCipher([]byte(key))
if err != nil {
panic(err)
}
c := cipher.NewCBCEncrypter(blockCipher, iv)
c.CryptBlocks(data, data)
data = append(iv, data...)
return hex.EncodeToString(data)
}
func Decrypt(str string) string {
origin, _ := hex.DecodeString(str)
iv := origin[:16]
data := origin[16:]
block, err := aes.NewCipher([]byte(key))
if err != nil {
panic(err)
}
c := cipher.NewCBCDecrypter(block, iv)
c.CryptBlocks(data, data)
return string(data)
}
func PKCS5Padding(ciphertext []byte) []byte {
padding := aes.BlockSize - len(ciphertext)