MessageDigestFactory.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */
  20. package org.openspcoop2.utils.digest;

  21. import java.security.MessageDigest;
  22. import java.security.NoSuchAlgorithmException;
  23. import java.security.Provider;
  24. import java.security.Security;

  25. /**
  26.  * MessageDigestFactory
  27.  *
  28.  * @author Poli Andrea (apoli@link.it)
  29.  * @author $Author$
  30.  * @version $Rev$, $Date$
  31.  */
  32. public class MessageDigestFactory {

  33.     private static boolean useBouncyCastleProvider = false;
  34.     public static boolean isUseBouncyCastleProvider() {
  35.         return useBouncyCastleProvider;
  36.     }
  37.     public static void setUseBouncyCastleProvider(boolean useBouncyCastleProvider) {
  38.         MessageDigestFactory.useBouncyCastleProvider = useBouncyCastleProvider;
  39.     }
  40.    
  41.     private static Provider provider = null;
  42.     private static synchronized Provider _getProvider() {
  43.         if ( provider == null )
  44.             provider = Security.getProvider(org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME);
  45.         return provider;
  46.     }
  47.     private static Provider getProvider() {
  48.         if(!useBouncyCastleProvider) {
  49.             return null;
  50.         }
  51.         if ( provider == null )
  52.             return _getProvider();
  53.         return provider;
  54.     }
  55.    
  56.     public static MessageDigest getMessageDigest(String algoritmo) throws NoSuchAlgorithmException {
  57.         MessageDigest digest = null;
  58.         if(useBouncyCastleProvider) {
  59.             digest = MessageDigest.getInstance(algoritmo, getProvider());
  60.         }
  61.         else {
  62.             digest = MessageDigest.getInstance(algoritmo);
  63.         }
  64.         return digest;
  65.     }  
  66.    
  67. }