-1
$\begingroup$

Consider the function below:

 def dec args=password, iv, encrypted
    decipher = OpenSSL::Cipher.new('aes-128-cbc')
    decipher.decrypt
    decipher.padding = 0
    decipher.key = Digest::SHA256.hexdigest(password) # just for simplicity;  use PBKDF2 for real applications
    decipher.iv = Base64.decode64(iv)
    plain = decipher.update(Base64.decode64(encrypted)) + decipher.final
    return plain
  end

That function will correctly decipher a text, but it may add extra invisible chars, depending on the size of the original plain text. Then, the length must be stored in the file, together with encrypted and iv, and the decryption function becomes:

 def dec args=password, iv, encrypted, length
    decipher = OpenSSL::Cipher.new('aes-128-cbc')
    decipher.decrypt
    decipher.padding = 0
    decipher.key = Digest::SHA256.hexdigest(password) # just for simplicity;  use PBKDF2 for real applications
    decipher.iv = Base64.decode64(iv)
    plain = decipher.update(Base64.decode64(encrypted)) + decipher.final
    return plain[0..(length-1)]
  end

I suspect that the storing of the length in the encrypted file be a cryptographic weakness. What's the proper way of solving it?

$\endgroup$
1
$\begingroup$

I suspect that the storing of the length in the encrypted file be a cryptographic weakness.

It's not. Encryption is commonly considered secure whenever the ciphertext allows the attacker to infer nothing about the plaintext other than its size. Plaintext length is not considered a secret.

While this would not protect unpadded "yes"/"no" messages encrypted with one-symbol block size, that is a weakness of the entire communication scheme (using two string aliases to convey a bool), not the algorithm. With practical block sizes length could be used to identify video files, too. But this is simply outside the scope of encryption to protect.

If you have to protect plaintext length, use padding with any secure cryptographic scheme.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.