Search code examples
phpmysqlencryptioncryptographyphp-openssl

Openssl Encryption Random Key&IV- Store in DB


I have read a lot about encryption and know a lot of new things have come out since php 7. I am writing two functions (encrypt and decrpyt) to store encrypted data in my db.

I understand how openssl function works but I am wondering if I am storing it in my db properly or should i say securely. My code is as follows:

function wm_encryptString($string) {
    $method = 'aes-256-xts';
    $key = random_bytes(16);
    $iv = random_bytes(16);
    $cipherText = openssl_encrypt($string, $method, $key, 0, $iv);
    $cipherText = $key.$iv.$cipherText;
    $cipherText = base64_encode($cipherText);
    return $cipherText;
}

function wm_decryptString($cipher) {
    $cipher = base64_decode($cipher);
    $method = 'aes-256-xts';
    $key = substr($cipher, 0, 16);
    $iv = substr($cipher, 16, 16);
    $cipher = substr($cipher, 32);
    $readableText = openssl_decrypt($cipher, $method, $key, 0, $iv);
    return $readableText;
}

When i run these two functions it encrypts and decrypts just fine. My specific question is, Is using random bytes to generate the Key and IV secure and is appending it to the cipher text secure for storage in the db? I am storing some sensitive information and want to make sure it is encrypted securely.

My second question is, I know I can encrypt strings using these function but can I encrypt blobs using this same function? I am storing some documents in my db (I know many of you will say never to store documents in db but Im using db because I am only storing a few documents, less than 100, and it makes back up easier). Can I encrypt a blob/file using this same function?

Any feedback would be appreciated as I want my app to be as secure as possible. Note I know i must take a lot more security measure to ensure my application is secure, my question is specific to encryption. Thank you.


Solution

    1. Random bytes for the key and IV is good, prefixing the IV to the encrypted data is good, both are secure choices.

    2. Encryption is byte based, it does not care about any encoding, blob or otherwise. For text get the bytes as utf-8.

    3. Why did you choose XTS mode, it is generally used for disk encryption? See You Dont Want XTS. Generally CBC or CTR mode is the correct choice. Note that with CBC do not return adding errors, with CTR never use the same IV (counter initial value) and key–it is easy to get that wrong.

    Finally, how do you plan to secure the encryption key(s)? That is the hard part.