Hash functions in java

2 minute read

The output length of each hash functions

  • md5 : 128 bits (32 bytes)

    (ex) 8380482228e75045a7d14e063bde014b

  • sha-1 : 160 bits (40 bytes)

    (ex) 764C46AE8BC50C4823E50F18DA45B9A21E8DD10B

  • sha-256 : 256 bits (64 bytes)

    (ex) be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912

Base64 encoding/decoding

Case #1: Using java library

import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

public class Base64Test {

    public static void main(String[] args)  {
        String text = "test string";
        byte[] targetBytes = text.getBytes();
        
        // Base64 encoding
        Encoder encoder = Base64.getEncoder();
        byte[] encodedBytes = encoder.encode(targetBytes);
        
        // Base64 decoding
        Decoder decoder = Base64.getDecoder();
        byte[] decodedBytes = decoder.decode(encodedBytes);
        
        System.out.println("PlainText : " + text);
        System.out.println("Encoded   : " + new String(encodedBytes));
        System.out.println("Decoded   : " + new String(decodedBytes));
    }
}

Case #2: Using Apache Commons Codec library

import org.apache.commons.codec.binary.Base64;

public class Base64Test2 {
    public static void main(String args[]) {
        String text = "test string";

        // base64 encoding
        byte[] encodedBytes = Base64.encodeBase64(text.getBytes());

        // base64 decoding
        byte[] decodedBytes = Base64.decodeBase64(encodedBytes);

        System.out.println("PlainText : " + text);
        System.out.println("Encoded   : " + new String(encodedBytes));
        System.out.println("Decoded   : " + new String(decodedBytes));
    }
}

Hash functions

md5

    /**
	 * Get md5 hash String
	 * @param s
	 * @return
	 */
	public static final String md5(final String msg) {
	    try {
	        // Create MD5 Hash
	        MessageDigest digest = MessageDigest.getInstance("MD5");
	        digest.update(msg.getBytes());
	        byte messageDigest[] = digest.digest();

	        // Create Hex String
			return bytesToHex1(messageDigest);

	    } catch (NoSuchAlgorithmException e) {
	        Log.e(TAG, "ERROR:" + e.getMessage());
	    }
	    return "";
	}

md5 can be used to get android device id for Admob.

SHA-256

/**
 * Get SHA-256 hash Array
 * 
 * @param bytes
 * @return
 * @throws NoSuchAlgorithmException 
 */
public static byte[] sha256(String msg) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(msg.getBytes());
    
    return md.digest();
}

// Run example
final static char[] hexArray = "0123456789abcdef".toCharArray();
System.out.println(bytesToHex1(sha256("needjarvis")));
System.out.println(bytesToHex2(sha256("needjarvis"))); 

// Two results are same.
// f204250d7fd90ceebca11068ecf17318b554d06808b4615ca3e7347e08947816
// f204250d7fd90ceebca11068ecf17318b554d06808b4615ca3e7347e08947816


BitcoinWiki: SHA-256

Converting functions for hex string

Case #1 : Simple and easy

/**
 * Convert hash bytes to hex string
 * 
 * @param bytes
 * @return
 */
public static String bytesToHex1(byte[] bytes) {
    StringBuilder builder = new StringBuilder();
    for (byte b: bytes) {
      builder.append(String.format("%02x", b));
    }
    return builder.toString();
}

Case #2 : Complex but fast

/**
 * Convert hash bytes to hex String
 * 
 * @param bytes
 * @return
 */
public static String bytesToHex2(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

Tags:

Categories:

Updated:

Leave a comment