Wednesday, March 5, 2008

[Java How To] #3 Creating MD5 Hashes Without a Plugin

*UPDATE: Servoy 4 appears to provide a built-in function for creating base-64-encoded, MD5 hashes. The function is located in "Utils" and as of RC1 is named "stringMD5HashBase64".


A PDF version of this post, which includes a code walkthru, is available here



Java How-To's are intended to provide real-world examples of how Java can be used to easily extend Servoy in useful ways. I will try to post a new one as often as possible.

Description

If you thought you needed a plugin to create MD5 hashes, think again. Because Servoy has such great support for Java, you can actually create MD5 hashes without using a plugin, by simply embedding some Java code directly within your Servoy method.

Java Classes Used

For more information about any of the Java classes used, click their corresponding link below.


Total Lines of Code

20 or so

The Servoy Code

var string_to_hash = 'Hello World!';

// Get an array of bytes from the input string
var in_array = Array(string_to_hash.length);
var in_char;

for (var i = 0; i < in_char =" string_to_hash.slice(i,i+1)" inbytearray =" new" i =" 0;" md =" Packages.java.security.MessageDigest.getInstance(" md5_bytearray =" md.digest(in_array);" md5_hash =" '';//empty" md5_array =" new" i =" 0;"> 2) {
// Take right most 2 chars
md5_array[i] = md5_array[i].substr(md5_array[i].length - 2, 2);
}

if ((md5_byteArray[i] >= 0 ) && (md5_byteArray[i] <= 15)) { // Pre-pend a '0' since the hex to string fails to do so - typical to forget! md5_array[i] = '0' + md5_array[i]; } md5_hash += md5_array[i];//concatenate } return md5_hash;

In Summary

That's it! Creating MD5 hashes without a plugin. Please post any questions or comments you may have to the blog.

IMPORTANT: Please be advised that you should always backup your Servoy solution before implementing or attempting any of the techniques described in this blog. None of the techniques described are guaranteed to work in any way shape or form, or for any specific purpose. Use them entirely at your own risk.

3 comments:

Ryan said...

I looks like the code formatter is dropping an extra 'null' on line 30. The 'return nullnull;' is not in the plain text version of the code.

Tom Parry said...

I think that Jeff should fix this - he is the one that mangles the code I send!

Jeff Bader said...

Sorry 'bout that :-) I'll have a look. I think though unfortunately that the null string is an artifact of the source formatter script I am using. If you look at the plain-text version using the "view plain" link or if you use the "copy to clipboard" link the extra null is NOT there.

Post a Comment