SHA 256 hash for Oracle in Java

Oracle 11g doesn’t provide a SHA 256 function. I couldn’t find any SHA256 code that doesn’t have any dependencies. I wrote this class so that Oracle can use just this class alone for a SHA256 function.

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

/**
 * This is a class exclusively created for use in Oracle. This doesn't have any dependencies besides a JVM.
 * com.jReward.security.SHA256EncoderForOracle
 *
 * @author Suneel
 * @version $Revision: 1.1.2.4 $
 * @since Oct 25, 2010 12:05:23 PM
 */
public class SHA256EncoderForOracle
{

 public static String getSHA256( String pwd ) throws Exception
 {
 MessageDigest messageDigest = MessageDigest.getInstance( "SHA-256" );
 byte[] digest;
 try
 {
 digest = messageDigest.digest( mergePasswordAndSalt( pwd.toUpperCase(), "1234", false ).getBytes( "UTF-8" ) );
 }
 catch( UnsupportedEncodingException e )
 {
 throw new IllegalStateException( "UTF-8 not supported!" );
 }

 StringBuilder sb = new StringBuilder();
 for ( byte element : digest )
 {
 sb.append( Integer.toString( ( element & 0xff ) + 0x100, 16 ).substring( 1 ) );
 }

 return sb.toString().toUpperCase();

 }

 protected static String mergePasswordAndSalt( String password, Object salt, boolean strict )
 {
 if ( password == null )
 {
 password = "";
 }

 if ( strict && ( salt != null ) )
 {
 if ( ( salt.toString().lastIndexOf( "{" ) != -1 ) || ( salt.toString().lastIndexOf( "}" ) != -1 ) )
 {
 throw new IllegalArgumentException( "Cannot use { or } in salt.toString()" );
 }
 }

 if ( ( salt == null ) || "".equals( salt ) )
 {
 return password;
 }
 else
 {
 return password + "{" + salt.toString() + "}";
 }
 }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: