Coverage Report - no.sesat.search.security.MD5Generator
 
Classes in this File Line Coverage Branch Coverage Complexity
MD5Generator
0%
0/12
0%
0/2
1.75
 
 1  
 /* Copyright (2007) Schibsted Søk AS
 2  
  * This file is part of SESAT.
 3  
  *
 4  
  *   SESAT is free software: you can redistribute it and/or modify
 5  
  *   it under the terms of the GNU Affero General Public License as published by
 6  
  *   the Free Software Foundation, either version 3 of the License, or
 7  
  *   (at your option) any later version.
 8  
  *
 9  
  *   SESAT is distributed in the hope that it will be useful,
 10  
  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 11  
  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12  
  *   GNU Affero General Public License for more details.
 13  
  *
 14  
  *   You should have received a copy of the GNU Affero General Public License
 15  
  *   along with SESAT.  If not, see <http://www.gnu.org/licenses/>.
 16  
  */
 17  
 package no.sesat.search.security;
 18  
 
 19  
 import org.apache.commons.codec.binary.Hex;
 20  
 
 21  
 import java.security.MessageDigest;
 22  
 import java.security.NoSuchAlgorithmException;
 23  
 
 24  
 /**
 25  
  *
 26  
  * @version <tt>$Revision: 6596 $</tt>
 27  
  */
 28  
 public final class MD5Generator {
 29  
 
 30  0
     private static final byte[] EMPTY_STRING = new byte[0];
 31  
 
 32  
     private final String secret;
 33  
 
 34  0
     public MD5Generator(final String secret) {
 35  
 
 36  0
         this.secret = secret;
 37  0
     }
 38  
 
 39  
     public String generateMD5(final String s) {
 40  
 
 41  0
         final MessageDigest digest  = getDigest("MD5");
 42  
 
 43  0
         digest.update(null != s ? s.getBytes() : EMPTY_STRING);
 44  0
         digest.update(secret.getBytes());
 45  
 
 46  0
         return String.valueOf(Hex.encodeHex(digest.digest()));
 47  
     }
 48  
 
 49  
     public boolean validate(final String s, final String hash) {
 50  
 
 51  0
         return generateMD5(s).equals(hash);
 52  
 
 53  
     }
 54  
 
 55  
     /**
 56  
      * Returns a MessageDigest for the given <code>algorithm</code>.
 57  
      *
 58  
      * @param algorithm The MessageDigest algorithm name.
 59  
      * @return An digest instance.
 60  
      * @throws RuntimeException when a {@link java.security.NoSuchAlgorithmException} is caught,
 61  
      */
 62  
     static MessageDigest getDigest(String algorithm) {
 63  
 
 64  
         try {
 65  0
             return MessageDigest.getInstance(algorithm);
 66  0
         } catch (NoSuchAlgorithmException e) {
 67  0
             throw new RuntimeException(e.getMessage());
 68  
         }
 69  
     }
 70  
 }