Niguai
Niguai

Reputation: 85

PHP AES-256-CBC encryption from Golang given data

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)%aes.BlockSize
    padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    return append(ciphertext, padtext...)
}

AND I can get the output :

Origin Data : hello world
Encrypt Data : efb5e55e9d2d15e6a61dcfeef322b0da839674e76666962d41f6a00a04d84adf
Decrypt Data : hello world

Run code in here

My php code

public function Decode(){

        //encrypt string from golang
        $strFromGolang = "efb5e55e9d2d15e6a61dcfeef322b0da839674e76666962d41f6a00a04d84adf";
        $decode = hex2bin($strFromGolang);

        $key = "abcdabcdabcdabcd";
        //format
        $data = substr($decode, 16);
        $iv = substr($decode, 0, 16);

        $decrypt = openssl_decrypt($data, 'aes-256-cbc', $key, 0, $iv);
        var_dump($decrypt);
    }

and the value $decrypt get false

How do I do to fix my php code to make $decrypt decrypt success ?

Upvotes: 1

Views: 772

Answers (1)

Alex Howansky
Alex Howansky

Reputation: 53513

You've got two issues:

First, the GO encrypt is not using AES-256-CBC, it's using AES-128-CBC. I'm not sure how to fix this on the GO side, but on the PHP side, just use AES-128-CBC as your cipher string.

Second, the PHP decrypt expects to operate on BASE64 encoded text, not a raw binary string. To decrypt a raw binary string like in your case, you will need to pass the optional OPENSSL_RAW_DATA flag:

$decrypt = openssl_decrypt($data, 'aes-128-cbc', $key, OPENSSL_RAW_DATA, $iv);

Upvotes: 2

Related Questions