First of, do not use MD5, it's insecure, use SHA2 instead.
I would recommend against putting the length header in front. It makes the file hard to read by other programs.
Many programs use the first few bytes to denote the file type.
Adding stuff there will break that.
If you make sure your hash text is always the same length, the solution is easy.
Just add it to the end of the file.
Then the decoding works like this:
- Read in the last x chars into a string.
- Check to see if it matches you hash_text layout
- Extract the hash value.
- Rehash the whole file (except the last x chars) to see if the hash holds.
Have a look at how gpg does it and copy that scheme.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v0.9.7 (GNU/Linux)
Comment: For info see http://www.gnupg.org
iEYEARECAAYFAjdYCQoACgkQJ9S6ULt1dqz6IwCfQ7wP6i/i8HhbcOSKF4ELyQB1
oCoAoOuqpRqEzr4kOkQqHRLE/b8/Rw2k
=y6kj
-----END PGP SIGNATURE-----
Note that if you change the file by adding a signature to it, you will prevent most other programs from working with your files.
Maybe it's a better idea to put the signature in a companion file that contains a link to the original.