OLD | NEW |
(Empty) | |
| 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 |
| 5 package org.chromium.chrome.browser.util; |
| 6 |
| 7 import android.util.Log; |
| 8 |
| 9 import java.security.MessageDigest; |
| 10 import java.security.NoSuchAlgorithmException; |
| 11 import java.util.Formatter; |
| 12 |
| 13 import javax.annotation.Nullable; |
| 14 |
| 15 /** |
| 16 * Helper functions for working with hashes. |
| 17 */ |
| 18 public final class HashUtil { |
| 19 private static final String TAG = HashUtil.class.getSimpleName(); |
| 20 |
| 21 private HashUtil() { |
| 22 } |
| 23 |
| 24 public static class Params { |
| 25 private final String mText; |
| 26 private String mSalt; |
| 27 |
| 28 public Params(String text) { |
| 29 mText = text; |
| 30 } |
| 31 |
| 32 public Params withSalt(String salt) { |
| 33 mSalt = salt; |
| 34 return this; |
| 35 } |
| 36 } |
| 37 |
| 38 public static String getMd5Hash(Params params) { |
| 39 return getHash(params, "MD5"); |
| 40 } |
| 41 |
| 42 private static String getHash(Params params, String algorithm) { |
| 43 try { |
| 44 String digestText = params.mText + (params.mSalt == null ? "" : para
ms.mSalt); |
| 45 MessageDigest m = MessageDigest.getInstance(algorithm); |
| 46 byte[] digest = m.digest(digestText.getBytes()); |
| 47 return encodeHex(digest); |
| 48 } catch (NoSuchAlgorithmException e) { |
| 49 Log.e(TAG, "Unable to find digest algorithm " + algorithm); |
| 50 return null; |
| 51 } |
| 52 } |
| 53 |
| 54 private static String encodeHex(byte[] data) { |
| 55 StringBuilder sb = new StringBuilder(data.length * 2); |
| 56 Formatter formatter = new Formatter(sb); |
| 57 for (byte b : data) { |
| 58 formatter.format("%02x", b); |
| 59 } |
| 60 return sb.toString(); |
| 61 } |
| 62 } |
OLD | NEW |