Reputation: 61
I encrypt a (tar) file use python and padding using PKCS#7. This encrypted file is then to a client (a router with OpenWRT). This router uses the (linux) shell with the openssl
command to decrypt it. This last step however fails with the following info:
bad decrypt
2011837512:error:06065064:lib(6):func(101):reason(100):NA:0:
tar: short read
Perhaps the problem lies in the padding, so I want to know what arguments to use for openssl
to avoid this issue. Are there any other commands than -nopad
related to padding?
The following Python code is used to encrypt the tar file:
# Encrypt file
def aes_encrypt_file(in_filename, out_filename, key, iv):
block_size = AES.block_size
pad = lambda s: s + (block_size - len(s) % block_size) \
* chr(block_size - len(s) % block_size)
cipher = aes_build_cipher(key, iv)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
while True:
buf = infile.read(1024)
if len(buf) == 0:
break
elif len(buf) % block_size != 0:
buf = pad(buf)
outfile.write(cipher.encrypt(buf))
The following shell command is used to decrypt the tar file on the router:
openssl aes-256-cbc -d -nosalt -K $sum256 -iv $iv -in ${PACKAGE} | tar xzf -
Upvotes: 2
Views: 2702
Reputation: 61
The problem is solved, and the following Python code is correct.
# Encrypt file
def aes_encrypt_file(in_filename, out_filename, key, iv):
block_size = AES.block_size
pad = lambda s: s + (block_size - len(s) % block_size) \
* chr(block_size - len(s) % block_size)
cipher = aes_build_cipher(key, iv)
with open(in_filename, 'rb') as infile:
with open(out_filename, 'wb') as outfile:
buf = infile.read()
buf = pad(buf)
outfile.write(cipher.encrypt(buf))
@owlstead @jww Thanks a lot for your help
Upvotes: 1
Reputation: 94068
Generally you are moving in the right direction with regards to the AES mode and padding. You however pad and encrypt not the entire plaintext but each and every block of (max) 1024 bytes. This won't decrypt correctly if seen as a single encrypted file, therefore the padding at the end of the plaintext will be incorrect and you will see a failure.
Upvotes: 1