Search code examples
ccryptographyopensslaeslibgcrypt

Encrypting a file from a password using libgcrypt


I'm developing simple software that does aes256-cbc encryption of a file. I'm using GNU/Linux and libgcrypt-1.5.0. The IV is randomly generated with the OpenSSL rand function and the IV is stored before the ciphertext in the output file. I'm using the PKCS#7 padding method.

Now I am in doubt about how to proceed:

  1. It is better to use sha256 repeated 50,000 times of the inputed password to encrypt the file, or it is better to use the password given by the user?

  2. If I want to check the correctness of the inputed password, I have to store it into the encrypted file (obviously encrypted). Is it correct to do this?


Solution

    1. Use PBKDF2 to derive a key as indiv suggested.
    2. Use PBKDF2 with a different salt to derive an authentication key and append a MAC to your encrypted data (after encryption is more secure than before encryption). Verify the MAC in order to check whether the password is correct or not, and that the data has not been tampered with. If you are unsure when choosing a MAC, use HMAC with SHA-512 (assuming you are using AES-256 as per your question).

    Instead of using PBKDF2 twice with different paddings, you can use a single invocation of PBKDF2 to generate both the encryption and the authentication keys at the same time, by generating a key of the combined size of your encryption key and authentication key in one go.

    Note that depending on the padding for deciding whether the key was good can result in CBC padding oracle attacks. For file encryption such attacks might not be applicable, depending on the exact circumstances, but it seems prudent practice to use a proper MAC for data authentication anyway, since you also want to prevent bit flipping attacks and other malicious modifications to your data.