0

CF Equivalent MD5 Hashing Functions for SQL Server 2005+ & Oracle 8+

Coldfusion, Database

Both Oracle and SQL Server have built-in hashing functions. The trick is neither returns a value that is immediately comparable to a hashed value in ColdFusion (i.e. 32 character, hex based, upper case). So some additional conversion is required.

Oracle 8+

I couldn't figure out how to make it work inline with a SELECT statement, so first create a database function MD5_HASH:

CREATE OR REPLACE FUNCTION MD5_HASH (v_input_string in varchar2) RETURN VARCHAR2 IS
    v_checksum VARCHAR2(20);
BEGIN
   v_checksum := dbms_obfuscation_toolkit.md5 (input_string => v_input_string);
   RETURN utl_raw.cast_to_raw(v_checksum);
END;

Then use this with a SELECT statement. The "dbms_obfuscation_toolkit.md5()" generates a RAW value that is then converted with "utl_raw.cast_to_raw()" to return a string than is equivalent to a CF hash() call. So an example SELECT statement:

SELECT MD5_HASH([column]) FROM [table]

SQL Server 2005+

Note there is an option for earlier versions of SQL Server that involve installing a .dll, but this example takes advantage of a function introduced in 2005 "HashBytes()".

SELECT UPPER( RIGHT( master.dbo.fn_varbintohexstr( HashBytes( 'MD5', [column] ) ), 32) )
FROM [table]

A few notes:

  1. master.dbo.fn_varbintohexstr() is an undocumented function, but it has been around for awhile, and doesn't appear to be going anywhere, and I don't know another way to do the conversion
  2. RIGHT( [value], 32) is needed because the value returned has a leading 0x to indicate the value is hexadecimal, which ColdFusion does not do.
  3. Finally UPPER() is there because the value returned is lower cased.
 
Excellent example. I knew this had to be possible!
 
posted 240 days ago
Add Comment Reply to: this comment OR this thread
 

Search