Hash functions in java
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));
}
}
Base64 vs BaseusURL
/**
* This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" equivalents as specified in "Table 1: The Base64 Alphabet" of RFC 2045 (and RFC 4648).
*/
private static final char[] toBase64 = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
/**
* It's the lookup table for "URL and Filename safe Base64" as specified in Table 2 of the RFC 4648, with the '+' and '/' changed to '-' and '_'. This table is used when BASE64_URL is specified.
*/
private static final char[] toBase64URL = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
};
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
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);
}
Leave a comment