001 /*--------------------------------------------------------------------------+ 002 $Id: Digester.java 26268 2010-02-18 10:44:30Z juergens $ 003 | | 004 | Copyright 2005-2010 Technische Universitaet Muenchen | 005 | | 006 | Licensed under the Apache License, Version 2.0 (the "License"); | 007 | you may not use this file except in compliance with the License. | 008 | You may obtain a copy of the License at | 009 | | 010 | http://www.apache.org/licenses/LICENSE-2.0 | 011 | | 012 | Unless required by applicable law or agreed to in writing, software | 013 | distributed under the License is distributed on an "AS IS" BASIS, | 014 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 015 | See the License for the specific language governing permissions and | 016 | limitations under the License. | 017 +--------------------------------------------------------------------------*/ 018 package edu.tum.cs.commons.digest; 019 020 import java.security.MessageDigest; 021 import java.security.NoSuchAlgorithmException; 022 import java.util.Collection; 023 import java.util.List; 024 025 import edu.tum.cs.commons.collections.CollectionUtils; 026 import edu.tum.cs.commons.error.EnvironmentError; 027 import edu.tum.cs.commons.string.StringUtils; 028 029 /** 030 * Utility functions for creation of digests. 031 * 032 * @author juergens 033 * @author $Author: juergens $ 034 * @version $Rev: 26268 $ 035 * @levd.rating GREEN Hash: 3CB40A00577C76D6DEA0297E30EEA8F7 036 */ 037 public class Digester { 038 039 /** Digester used to create Digester hashes. */ 040 private static MessageDigest digester = getMD5(); 041 042 /** 043 * Computes an MD5 hash for a string. The fingerprint is the digester hash 044 * of the string. It is always 32 characters long and only uses characters 045 * from [0-9A-F]. 046 */ 047 public static String createMD5Digest(String base) { 048 digester.reset(); 049 digester.update(base.getBytes()); 050 051 return StringUtils.encodeAsHex(digester.digest()); 052 } 053 054 /** 055 * Computes an MD5 hash for a collection of strings. The strings are sorted 056 * before MD5 computation, so that the resulting MD5 hash is independent of 057 * the order of the strings in the collection. 058 */ 059 public static String createMD5Digest(Collection<String> bases) { 060 List<String> sortedBases = CollectionUtils.sort(bases); 061 return createMD5Digest(StringUtils.concat(sortedBases, 062 StringUtils.EMPTY_STRING)); 063 } 064 065 /** 066 * Returns Digester digester or throws an AssertionError if the Digester 067 * could not be located. 068 */ 069 public static MessageDigest getMD5() { 070 try { 071 return MessageDigest.getInstance("MD5"); 072 } catch (NoSuchAlgorithmException e) { 073 throw new EnvironmentError( 074 "MD5 algorithm found. Please check your JRE installation", 075 e); 076 } 077 078 } 079 080 }