I have been learning about OTP lately and I wondered, if I was to use it for encryption of a file (like a photo or even a video), I would need really looong key.
Example program is simple: input is password and file name, output is encrypted file.
One of my ideas was to create a hash of the password, but just 512 bits (I am using sha512
) are still shorter than average file. My final solution was to take hash of the password, divide it into two halves (first 256 and last 256 bits) and sha512
each one of them (this doubles size of the key). Then, for each of the resulting hashes, I repeat the process untill I reach the length of the file.
When I get to the length of the file, I just use the resulting hashes concatenated together to form a key with which I then encrypt the file.
Implementation in Python:
def get_key(passwd, filename):
size = os.path.getsize(filename)
pwd = passwd + filename
initial_key = sha512(pwd.encode())
subkeys = [initial_key[32:], initial_key[:32]]
while len(subkeys) * 32 < size:
new_subkeys = []
for k in subkeys:
k_hash = sha512(k)
new_subkeys.extend([k_hash[32:], k_hash[:32]])
subkeys = new_subkeys
key = b''.join(subkeys)[:size]
return key
This method is, however, relatively slow. Therefore, my question is, is there a better way of producing "hash" of length equal to the length of a file?
Is my method of dividing and concatenating hashes even secure?
Note about the One time password: I would probably concatenate the password with absolute path of the file before hashing, so that there are no reused keys.