Simple sample source code to hash and encode the hashed value using Base4 or HEX
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
public class TestMessageDigest {
/**
* @param args
*/
public static void main(String[] args) {
TestMessageDigest test = null;
String rawPass = "passwordInClearTxt";
String encodedPass = null;
test = new TestMessageDigest( "SHA-256", true );
encodedPass = test.encodePassword( rawPass );
System.out.println( encodedPass );
test = new TestMessageDigest( "SHA-256", false );
encodedPass = test.encodePassword( rawPass );
System.out.println( encodedPass );
test = new TestMessageDigest( "SHA-512", true );
encodedPass = test.encodePassword( rawPass );
System.out.println( encodedPass );
test = new TestMessageDigest( "SHA-512", false );
encodedPass = test.encodePassword( rawPass );
System.out.println( encodedPass );
}
private TestMessageDigest(String algorithm, boolean encodeHashAsBase64) {
super( );
this.algorithm = algorithm;
this.encodeHashAsBase64 = encodeHashAsBase64;
}
private String algorithm;
private boolean encodeHashAsBase64 = false;
public String encodePassword(String rawPass) {
MessageDigest messageDigest = getMessageDigest( );
byte[] digest;
try {
digest = messageDigest.digest( rawPass.getBytes( "UTF-8" ) );
} catch ( UnsupportedEncodingException e ) {
throw new IllegalStateException( "UTF-8 not supported!" );
}
if ( encodeHashAsBase64 ) {
return new String( Base64.encodeBase64( digest ) );
} else {
return new String( Hex.encodeHex( digest ) );
}
}
protected final MessageDigest getMessageDigest()
throws IllegalArgumentException {
try {
return MessageDigest.getInstance( algorithm );
} catch ( NoSuchAlgorithmException e ) {
throw new IllegalArgumentException( "No such algorithm ["
+ algorithm + "]" );
}
}
}
No comments:
Post a Comment