Jun 07

Why doesn’t the standard Java SDK provide a method that returns a 32 character (128bit) String representation of  an MD5 encrypted string… just like most other languages do (PHP, Ruby)… i don’t know! Below are Ruby and PHP examples and then a Java implementation.

Ruby implementation:

require 'digest/md5'
digest = Digest::MD5.hexdigest("encrypt this text")

PHP implementation:

<?php
   $str = "Hello";
   echo md5($str);
?>

Java implementation (2 methods for clarity):

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException

public class MD5 {

public static String digest(String text) {
      throws NoSuchAlgorithmException, UnsupportedEncodingException {
   MessageDigest md = MessageDigest.getInstance("MD5");
   byte[] md5hash = new byte[32];
   md.update(text.getBytes("iso-8859-1"), 0, text.length());
   md5hash = md.digest();
   return convertToHex(md5hash);
}

private static String convertToHex(byte[] b) {
   StringBuilder result = new StringBuilder(32);
   for (int i = 0; i &lt; b.length; i++) {
      result.append(
         Integer.toString( ( b[i] &amp; 0xff ) + 0x100, 16).substring( 1 ));
   }
   return result.toString();
}
}

This isn’t the fastest MD5 implementation, but that isn’t my goal here. I found quite a few implementations when searching, some of which gave results which were not even correct!

Hope this implementation helps someone else.

written by admin \\ tags: , , ,

Jun 04

So you want to use ActiveRecord outside of the Rails framework? It’s not hard to do. Firstly make sure you have active record installed, which you can do by executing:

gem install activerecord

Then, the code below is all you need to get started (with an example DAO – DvdTitle at the end)

require "rubygems"
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter =&gt; "mysql",
  :host =&gt; "127.0.0.1",
  :username =&gt; "username",
  :database =&gt; "dvdsale_development",
  :password =&gt; "secret")

class DvdTitle &lt; ActiveRecord::Base
end

puts DvdTitle.find(1).name

My environment:

Ruby version 1.8.6 (i386-mswin32)
RubyGems version 1.3.3
Rails version 2.2.2
Active Record version 2.2.2

written by admin \\ tags: , ,