001/* 002 * (C) Copyright 2006-2019 Nuxeo (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Florent Guillaume 018 */ 019package org.nuxeo.ecm.core.blob; 020 021import java.util.Locale; 022import java.util.Map; 023import java.util.regex.Pattern; 024 025import org.apache.commons.codec.digest.DigestUtils; 026 027/** 028 * Configuration for the digest. 029 * 030 * @since 11.1 031 */ 032public class DigestConfiguration extends PropertyBasedConfiguration { 033 034 public static final String DIGEST_ALGORITHM_PROPERTY = "digest"; 035 036 public static final String DEFAULT_DIGEST_ALGORITHM = "MD5"; 037 038 public final String digestAlgorithm; 039 040 public final Pattern digestPattern; 041 042 public DigestConfiguration(String digestAlgorithm) { 043 super(null, null); 044 this.digestAlgorithm = digestAlgorithm; 045 digestPattern = getDigestPattern(); 046 } 047 048 public DigestConfiguration(String systemPropertyPrefix, Map<String, String> properties) { 049 super(systemPropertyPrefix, properties); 050 digestAlgorithm = getDigestAlgorithm(); 051 digestPattern = getDigestPattern(); 052 } 053 054 protected String getDigestAlgorithm() { 055 return getProperty(DIGEST_ALGORITHM_PROPERTY, DEFAULT_DIGEST_ALGORITHM).toUpperCase(Locale.ENGLISH); 056 } 057 058 protected Pattern getDigestPattern() { 059 // compute a dummy digest (from 0-length input) to know its length and derive a regexp 060 int len = new DigestUtils(digestAlgorithm).digestAsHex(new byte[0]).length(); 061 return Pattern.compile("[0-9a-f]{" + len + "}"); 062 } 063 064 public boolean isValidDigest(String digest) { 065 return digestPattern.matcher(digest).matches(); 066 } 067 068}