简体   繁体   中英

OpenSSL File encryption in PHP and decrypting in C++

How do I encrypt a file contents in PHP using OpenSSL and decrypt it in C++? Here's my code:

$dll = file('file.dll')[0];

$iv = substr(hash('sha256', 'test'), 0, 16);
$key = substr(hash('sha256', 'test'), 0, 32);

$dll_en = openssl_encrypt($dll, "AES-256-CBC", $key, 0, $iv);

and here's c++

int main() {
    /* A 256 bit key */
    byte* key = (byte*)"9f86d081884c7d659a2feaa0c55ad015";
    /* A 128 bit IV */
    byte* iv = (byte*)"9f86d081884c7d65";

    std::vector<byte> data = base64_decode("CyeJtJecBChtVSxeTLw9mYKapHwLNJed/5VVuyGOHNSTksBzH1Ym2JwLJv/LvlT9tqMEahwcX7Yj9jYVRCSnTliz/zQYk0pIi8CKTEGkqffqZd8CdA6joLMl9Ym6d+5wERgHEotURq8Kn+H3/GbUuEBUtLL9Cd1+VsKWDyqkE1c=");
    byte* ciphertext = new byte[data.size()];

    for (size_t i = 0; i < data.size(); i++)
    {
        ciphertext[i] = data.at(i);
    }

    byte decryptedtext[8096];
    int decryptedtext_len;

    decryptedtext_len = decrypt(ciphertext, data.size(), key, iv, decryptedtext);
    decryptedtext[decryptedtext_len] = 0;

    std::cout << decryptedtext;

    return 0;
}

The decrypt function is from here

The first line of the dll is MZ @? ? ! L !This program cannot be run in DOS mode. but all I get in console is MZÉ . What am I doing wrong?

Nothing is wrong except your choice of output method!

Since you're passing a byte* to std::cout , the only way it knows when to stop is to treat the input as a C-string, a sequence of 8-bit bytes. When it encounters one with value ZERO, it thinks it's a null terminator and stops. It's working as it should.

But your input is not ASCII! It is arbitrary, "binary" data.

You should instead use something like std::cout.write(decryptedtext, decryptedtext_len) , which just chucks all your bytes out to the output stream. It's then up to your console/teletype/printer to render that as it deems fit (which may still not be identical to what you're looking for, depending on settings).

Nothing, you just get things in ASCII instead of UTF-8 while printing a binary file, and characters are skipped until a 00 valued byte is encountered rather than printed out with as a diamond with a question mark. Perform a binary compare instead.

Of course you should note that key and IV calculation of the key and even more the IV is entirely insecure in PHP mode and that CBC mode doesn't provide authentication, so the code is not as secure as it should be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM