Wednesday, July 8, 2009

Script to generate Oracle password hashes

Function to use username||password as a seed to generate Oracle password hashes.

(based on examples on petefinnigan.com)

create or replace function password_hash (username in varchar2, password in varchar2) return varchar2 is

raw_key_v raw(128):= hextoraw('0123456789ABCDEF');
ascii_string_v varchar2(124):='';
uni_string_v raw(128) := '';
hex_string_v varchar2(2048) := '';
raw_string_v raw(2048) :='';
length_v number :=0;
current_char_v char(1);
padd_lenth_v number := 0;
password_hash_raw_v raw(2048) :='';
password_hash_hex_v varchar2(16) := '';

begin
length_v:=length(username||password);

for i in 1..length_v loop
current_char_v:=substr(upper(username||password),i,1);
ascii_string_v:=ascii_string_v||chr(0)||current_char_v;
end loop;

length_v:= mod((length_v*2),8);

if (length_v = 0) then
padd_lenth_v:= 0;
else
padd_lenth_v:=8 - length_v;
end if;

for i in 1..padd_lenth_v loop
ascii_string_v:=ascii_string_v||chr(0);
end loop;

uni_string_v:=utl_raw.cast_to_raw(ascii_string_v);
dbms_obfuscation_toolkit.desencrypt(input => uni_string_v, key => raw_key_v, encrypted_data => raw_string_v);
hex_string_v:=rawtohex(raw_string_v);

length_v:=length(hex_string_v);

raw_key_v:=hextoraw(substr(hex_string_v,(length_v-16+1),16));
dbms_obfuscation_toolkit.desencrypt(input => uni_string_v, key => raw_key_v, encrypted_data => password_hash_raw_v);

hex_string_v:=rawtohex(password_hash_raw_v);
length_v:=length(hex_string_v);
password_hash_hex_v:=substr(hex_string_v,(length_v-16+1),16);

return(password_hash_hex_v);
end;
/
show errors;


SQL> select password from dba_users where username = 'DUMMY';

PASSWORD
------------------------------
448E9EB8FEF04D8B

SQL> select password_hash('dummy','dummypw') from dual;

PASSWORD_HASH('DUMMY','DUMMYPW')
--------------------------------------------------------------------------------
448E9EB8FEF04D8B