According to OpenSSL docs, the -kfile reads the password from the first line in the file. This means that the password contains text, not binary data.
If your random data begins with a newline, then the first "line" in the file is empty. Therefore, I guess that the problem occurs every two hundred fifty six times or so. :-)
Try converting $password from binary to printed hexadecimal characters before storing them in a file, or (if you want to increase the key space) discard non-printable bytes.
You can also make sure that the file is readable only by you; otherwise, the password is available for tracking.
source share