1// Copyright 2013 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5package org.chromium.chrome.browser.util; 6 7import android.util.Log; 8 9import java.security.MessageDigest; 10import java.security.NoSuchAlgorithmException; 11import java.util.Formatter; 12 13/** 14 * Helper functions for working with hashes. 15 */ 16public final class HashUtil { 17 private static final String TAG = "HashUtil"; 18 19 private HashUtil() { 20 } 21 22 public static class Params { 23 private final String mText; 24 private String mSalt; 25 26 public Params(String text) { 27 mText = text; 28 } 29 30 public Params withSalt(String salt) { 31 mSalt = salt; 32 return this; 33 } 34 } 35 36 public static String getMd5Hash(Params params) { 37 return getHash(params, "MD5"); 38 } 39 40 private static String getHash(Params params, String algorithm) { 41 try { 42 String digestText = params.mText + (params.mSalt == null ? "" : params.mSalt); 43 MessageDigest m = MessageDigest.getInstance(algorithm); 44 byte[] digest = m.digest(digestText.getBytes()); 45 return encodeHex(digest); 46 } catch (NoSuchAlgorithmException e) { 47 Log.e(TAG, "Unable to find digest algorithm " + algorithm); 48 return null; 49 } 50 } 51 52 private static String encodeHex(byte[] data) { 53 StringBuilder sb = new StringBuilder(data.length * 2); 54 Formatter formatter = new Formatter(sb); 55 for (byte b : data) { 56 formatter.format("%02x", b); 57 } 58 return sb.toString(); 59 } 60} 61