All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.refcodes.forwardsecrecy.EncryptionProviderImpl Maven / Gradle / Ivy

The newest version!
// /////////////////////////////////////////////////////////////////////////////
// REFCODES.ORG
// =============================================================================
// This code is copyright (c) by Siegfried Steiner, Munich, Germany, distributed
// on an "AS IS" BASIS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, and licen-
// sed under the following (see "http://en.wikipedia.org/wiki/Multi-licensing")
// licenses:
// =============================================================================
// GNU General Public License, v3.0 ("http://www.gnu.org/licenses/gpl-3.0.html")
// together with the GPL linking exception applied; as being applied by the GNU
// Classpath ("http://www.gnu.org/software/classpath/license.html")
// =============================================================================
// Apache License, v2.0 ("http://www.apache.org/licenses/TEXT-2.0")
// =============================================================================
// Please contact the copyright holding author(s) of the software artifacts in
// question for licensing issues not being covered by the above listed licenses,
// also regarding commercial licensing models or regarding the compatibility
// with other open source licenses.
// /////////////////////////////////////////////////////////////////////////////

package org.refcodes.forwardsecrecy;

import java.io.UnsupportedEncodingException;
import java.security.Provider;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.exceptions.EncryptionInitializationException;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
import org.refcodes.data.Delimiter;
import org.refcodes.data.Encoding;
import org.refcodes.exception.Trap;
import org.refcodes.security.Algorithm;
import org.refcodes.security.EncryptionException;

/**
 * This class is a basic implementation of the {@link EncryptionProvider}
 * interface.
 */
public class EncryptionProviderImpl implements EncryptionProvider {

	// /////////////////////////////////////////////////////////////////////////
	// STATICS:
	// /////////////////////////////////////////////////////////////////////////

	private static final Logger LOGGER = Logger.getLogger( EncryptionProviderImpl.class.getName() );

	// /////////////////////////////////////////////////////////////////////////
	// VARIABLES:
	// /////////////////////////////////////////////////////////////////////////

	private EncryptionService _encryptionService;
	private StandardPBEStringEncryptor _stringEncryptor;
	private String _cipherUid = null;
	private Provider _jceProvider;;
	private String _jceAlgorithm;

	// /////////////////////////////////////////////////////////////////////////
	// CONSTRUCTORS:
	// /////////////////////////////////////////////////////////////////////////

	/**
	 * Constructs the {@link EncryptionProvider} with the given
	 * {@link EncryptionService} and with the specified JCE {@link Provider} as
	 * well as the according JCE algorithm.
	 * 
	 * @param aEncryptionService The {@link EncryptionService} to be used by the
	 *        provider.
	 * @param aJceProvider The JCE {@link Provider} to be used.
	 * @param aJceAlgorithm the JCE algorithm to be used by the JCE
	 *        {@link Provider}.
	 */
	public EncryptionProviderImpl( EncryptionService aEncryptionService, Provider aJceProvider, String aJceAlgorithm ) {
		_encryptionService = aEncryptionService;
		_jceProvider = aJceProvider;
		_jceAlgorithm = aJceAlgorithm;
		nextCipherVersion();
	}

	/**
	 * Constructs the {@link EncryptionProvider} using AES as implemented by the
	 * {@link BouncyCastleProvider}.
	 * 
	 * @param aEncryptionService The service to be used by the provider.
	 */
	public EncryptionProviderImpl( EncryptionService aEncryptionService ) {
		this( aEncryptionService, new BouncyCastleProvider(), Algorithm.AES.getName() );
	}

	// /////////////////////////////////////////////////////////////////////////
	// METHODS:
	// /////////////////////////////////////////////////////////////////////////

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String toEncrypted( String aInput ) throws EncryptionException {
		if ( ForwardSecrecyUtility.hasEncryptionPattern( aInput ) ) {
			LOGGER.log( Level.WARNING, "The provided text may have already been encrypted with a cipher UID beginning with \"" + aInput.substring( 0, ForwardSecrecyUtility.CIPHER_UID_TIMESTAMP_LENGTH ) + "...\"!" );
		}
		try {
			return _cipherUid + Delimiter.CIPHER_UID.getChar() + _stringEncryptor.encrypt( aInput );
		}
		catch ( EncryptionOperationNotPossibleException | EncryptionInitializationException e ) {
			throw new EncryptionException( Trap.asMessage( e ), e );
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int toEncrypted( byte[] abUFFER, int aOffset, int aLength, byte[] aOutBuffer, int aOutOffset ) throws EncryptionException {
		final byte[] theInputHex = Arrays.copyOfRange( abUFFER, aOffset, aOffset + aLength );
		String theInputText;
		try {
			theInputText = new String( theInputHex, Encoding.UTF_8.getCode() );
		}
		catch ( UnsupportedEncodingException e ) {
			theInputText = new String( theInputHex );
		}
		final String theOutputText = toEncrypted( theInputText );
		byte[] theOutputHex;
		try {
			theOutputHex = theOutputText.getBytes( Encoding.UTF_8.getCode() );
		}
		catch ( UnsupportedEncodingException e ) {
			theOutputHex = theOutputText.getBytes();
		}

		if ( aOutBuffer.length < aOutOffset + theOutputHex.length ) {
			throw new ArrayIndexOutOfBoundsException( "The encrypted data is of length <" + theOutputHex.length + "> though your buffer with length <" + aOutBuffer.length + "> does not provide enugh elements after offset <" + aOutOffset + ">." );
		}

		for ( int i = 0; i < theOutputHex.length; i++ ) {
			aOutBuffer[aOutOffset + i] = theOutputHex[i];
		}
		return theOutputHex.length;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void nextCipherVersion() {
		final CipherVersion theCipherVersion = _encryptionService.next();
		_stringEncryptor = new StandardPBEStringEncryptor();
		_stringEncryptor.setProvider( _jceProvider );
		_stringEncryptor.setAlgorithm( _jceAlgorithm );
		_stringEncryptor.setPassword( theCipherVersion.getCipher() );
		_cipherUid = theCipherVersion.getUniversalId();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void dispose() {
		final Provider theProvider = _jceProvider;
		if ( theProvider != null ) {
			theProvider.clear();
			_jceProvider = null;
		}
		_encryptionService = null;
		_jceAlgorithm = null;
		_cipherUid = null;
		_stringEncryptor = null;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy