bah.crypto feature request

BlitzMax Forums/Brucey's Modules/bah.crypto feature request

Htbaa(Posted 2009) [#1]
Hey Brucey,

A MD5File() function would be nice, to calculate the hash of a file. Loading a bigfile with LoadText() isn't always going to work.

The Perl module Digest::MD5 (and Digest::MD5::File) are able to do this. The maintainer of that module is using a method called add() which adds to the MD5 hash, so you can open a stream to a file, load it bit by bit and pass the contents to the MD5 object without loading the full file into memory.

Direct link to the C code
Digest::MD5
Digest::MD5::File

It would be really nice if you could add this :-). Thanks.

Update: Browsing through the source wouldn't you be able to do this with MD5_Update() from openssl?


Brucey(Posted 2009) [#2]
Well, all the code is already there for you to make that up yourself :-p
(see the digest example for use of "update" method)

You have the choice of using the "easy" API, or the meaty low-level API.


However, I've just updated all the digest functions to now take either a String (which they did previously) or a TStream.

There's a small "stream_digest.bmx" example too, so that you can see it in action.

Check out latest SVN for the updates.

:o)


Htbaa(Posted 2009) [#3]
I know all the code is there and I'd probably would've been able to do it myself. But, as a programmer I'm lazy :-). So I thank you for doing the hard work ^_^.

So far seems to be working perfectly. Thanks.


Htbaa(Posted 2009) [#4]
One *bug* report :-)

Shouldn't you reset the position of the stream after being done to 0 or the last known position? I currently have to do it manually, no biggie, but it would just be a little bit nicer if it did it by itself.

Anyway, I made a patch. I'm not sure about the stream.Seek(0) if the ctx.DigestUpdate() returns False, but seems logical to me.

Index: crypto.bmx
===================================================================
--- crypto.bmx	(revision 829)
+++ crypto.bmx	(working copy)
@@ -893,10 +893,13 @@
 			End If
 			
 			If Not ctx.DigestUpdate(data, count) Then
+				stream.Seek(0)
 				Return Null
 			End If
 
 		Wend
+
+		stream.Seek(0)
 		
 	Else
 		Return Null



Brucey(Posted 2009) [#5]
Shouldn't you reset the position of the stream after being done to 0 or the last known position?

Well, I can't assume that a stream you are giving me supports Seek(0).
For example, an http stream wouldn't, so I think the interface really needs to be quite generic in that regards. No ?


Htbaa(Posted 2009) [#6]
I hadn't thought of that :-). Good thinking. I'll revert my changes now.