Make writing keys.dat safer by creating a backup file

Just overwriting the file may cause its loss in case the overall disk write operation fails in the middle.
Created a .bak file for the duration of the write operation to prevent such possible file loss.