don't write file if opening a stream to encrypt the data fails

discovered this issue while testing #7829 

cc @PVince81 please have a look, thanks!