Skip to content
Advertisement

Matching blowfish encryption in php openssl_encrypt and golang blowfish

PHP:

JavaScript

This prints(first line is IV, second one is encrypted text:

JavaScript

Copying that IV to golang:

JavaScript

I get:

JavaScript

I Tried with ECB mode as well. I was able to match first 8 bytes once but I messed something up. I’m trying to figure out how the php version handles it so that I can match go implementation, but I’m failing so far.

Advertisement

Answer

The following issues cause the different results:

  • Blowfish has an 8 bytes block size and a variable key size between 4 and 56 bytes. In PHP there is a bug for Blowfish that pads shorter keys to 16 bytes with 0 values. Since version 7.1.8 there is a flag that prevents this: OPENSSL_DONT_ZERO_PAD_KEY. If this flag is additionally set (OPENSSL_RAW_DATA | OPENSSL_DONT_ZERO_PAD_KEY), the following output results (in the required environment):

    JavaScript

    Here there is an online PHP environment where the flag can be set.

  • The padding defined in Go is Zero padding while in the PHP code PKCS7 padding is used by openssl (as default). For PKCS7 the following changes are necessary (without comments, using the same names):

    JavaScript

    With this change the Go – Code gives the same result:

    JavaScript

    The 0 at the end is caused by a too large buffer for the ciphertext. In the Go code the length of the output buffer is calculated with plaintext length plus block size (8 bytes for Blowfish), which ensures that there is enough space for padding, since the maximum padding is one block. With shorter padding the buffer is too large, e.g. in the current case the plaintext has a length of 9 bytes, which results in a buffer of 17 bytes. The ciphertext has a length of 16 bytes, which leads to the 0 at the end. If desired, the exactly required buffer size can be determined as plaintext length plus padding length (the latter being determined analogous to padlen in the pad function).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement