问题
I am using AES 256 cbc method to encrypt my files. The column which I am encrypting is called 'Name'. previously before encrypting I had set the varchar length in phpmyadmin for 'Name' to be 20. when I was trying to encrypt , I saw it was short and the entire encrypted string was not getting inserted in the database. So I changed the size of varchar to 50 but still the length is small. I have to do this for other column as well. How do I determine efficient length for 'Name' column.
I am using randomized IV in the encryption as can be seen from the below example.
$encryptionMethod = "AES-256-CBC";
$secretHash = "25c6c7ff35b9979b151f2136cd13b0ff";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($encryptionMethod));
//To encrypt
$encrypted = openssl_encrypt($textToEncrypt, $encryptionMethod, $secretHash,false,$iv);
$encryptedMessage = $encrypted . ':' .base64_encode($iv);
during decryption I use
$parts = explode(':', $encryptedMessage);
// Decrypt the data
$decryptedMessage = openssl_decrypt($parts[0], $encryptionMethod, $secretHash, 0, base64_decode($parts[1]));
echo $decryptedMessage;
since the IV is appended to the encrypted string , how would I be able to calculate the length needed to be defined in the database for the column 'Name'.
回答1:
The block size of AES is 16 bytes, so you you'll need
- the size of your input, rounded up to the closest multiple of 16
- plus, if the input is already a multiple of 16, one block size for the PKCS#5 padding
- plus 16 bytes for the IV
Note that this doesn't necessarily apply to other cipher modes1.
So for 20 bytes of input you'll need a total of 48 bytes. However, you are also base64 encoding the result, which requires at least 33% more space (i.e. you should be storing the raw bytes if you care about space).
You should always concatenate before encoding, otherwise you often waste space with multiple padding byte sequences. If your input is 20 bytes long, encoding the 32 byte ciphertext by itself produces 44 bytes, and encoding the IV produces 24 bytes (both need padding). Concatenating before encoding produces only 64 bytes.
Concatenating before encoding also doesn't require the delimiter, because the length of the IV is known.
1 AEAD ciphers, such as GCM, are generally preferable over CBC, but require more space for storing the authentication hash, obviously.
来源:https://stackoverflow.com/questions/61225459/what-is-the-length-i-must-specify-for-string-encrypted-with-aes-256-cbc-in-the-d