' ********************************************************
' PROGRAM:	md5.bac
' PURPOSE:	easy message digest rev. 5 implementation
' AUTHOR:		vovchik (Puppy Linux forum)	
' DEPENDS:	gcc, bacon, libssl
' PLATFORM:	Puppy Linux (actually, any *nix)
' DATE:		06-03-2012
' NOTES:		uses MD5 from libssl
' LICENSE:	GPL3
' ********************************************************


' *********************
' IMPORTS
' *********************
TRAP LOCAL

IMPORT MD5(char*, int, char*) FROM "libssl.so.1.0.0" TYPE void

' *********************
' END IMPORTS
' *********************


' *********************
' SUBS & FUNCTIONS
' *********************

' ------------------
FUNCTION HASH$(STRING my_asc$)
' ------------------
	' MD5 hash function returns proper 32-byte hex string
	' first create buffer (x), since function writes
	' 16-byte hash into a char buffer
	LOCAL x[16] TYPE char
	LOCAL str_len, i TYPE int
	LOCAL my_hex$ TYPE STRING
	str_len = LEN(my_asc$)
	my_hex$ = ""
	' MD5 arguments:
	'      arg 1 is source string
	'      arg 2 is len of source string 
	'      arg 3 is 16-byte char buffer for storing results from function
	' send user string to MD5 function
	MD5(my_asc$, str_len, x)
	' make 32-byte hex char string from contents of
	' char array x[0-15] as hash result
	FOR i = 0 TO 15
		my_hex$ = CONCAT$(my_hex$, RIGHT$(CONCAT$("0", LCASE$(HEX$(x[i]))), 2))
	NEXT i
	' return concatenated hex hash as string var
	RETURN my_hex$
END FUNCTION

' *********************
' END SUBS & FUNCTIONS
' *********************


' *********************
' MAIN
' *********************

text$ = "The quick brown fox jumps over the lazy dog"
check_sum$ = "9e107d9d372bb6826bd81d3542a419d6"
PRINT "Test of string with known hash"
PRINT "Org string: ", text$
PRINT "Should be:  ", check_sum$
hash_hex$ = HASH$(text$)
PRINT "Hash test:  ", hash_hex$
IF EQUAL(hash_hex$, check_sum$) THEN
	PRINT "MD5 test passed."
ELSE
	PRINT "MD5 test failed."
END IF
text$ = ""
check_sum$ = "d41d8cd98f00b204e9800998ecf8427e"
PRINT "Now empty buffer test"
PRINT "Should be:  ", check_sum$
hash_hex$ = HASH$(text$)
PRINT "Hash test:  ", hash_hex$
IF EQUAL(hash_hex$, check_sum$) THEN
	PRINT "MD5 test passed."
ELSE
	PRINT "MD5 test failed."
END IF
PRINT "Nice!"
END

' *********************
' END MAIN
' *********************