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

org.refcodes.security.alt.chaos.ChaosEncrypter Maven / Gradle / Ivy

There is a newer version: 3.3.9
Show 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")
// -----------------------------------------------------------------------------
// 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.security.alt.chaos;

import org.refcodes.security.DecryptionException;
import org.refcodes.security.Encrypter;
import org.refcodes.security.EncryptionException;

/**
 * The {@link ChaosEncrypter} will use byte arrays as input and output types.
 */
public class ChaosEncrypter implements Encrypter {

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

	private double _x;
	private double _a;
	private long _s;
	private byte _previousEncrypted = 0;
	private ChaosOptions _chaosMetrics;
	private ChaosEncrypter _childEncrypter = null;
	private ChaosDecrypter _verifyDecrypter = null;
	// private WeakReference _chaosKeyRef;

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

	/**
	 * Instantiates a new {@link ChaosEncrypter} using the given
	 * {@link ChaosKey} for encrypting.
	 * 
	 * @param aKey The {@link ChaosKey} to use for encrypting.
	 */
	public ChaosEncrypter( ChaosKey aKey ) {
		this( aKey, -1, false );
	}

	/**
	 * Instantiates a new {@link ChaosEncrypter} using the given
	 * {@link ChaosKey} for encrypting.
	 * 
	 * @param aKey The {@link ChaosKey} to use for encrypting.
	 * 
	 * @param aChildDepth The number of children to consider when creating the
	 *        {@link ChaosDecrypter}.
	 */
	public ChaosEncrypter( ChaosKey aKey, int aChildDepth ) {
		this( aKey, aChildDepth, false );
	}

	/**
	 * Instantiates a new {@link ChaosEncrypter} using the given
	 * {@link ChaosKey} for encrypting.
	 * 
	 * @param aKey The {@link ChaosKey} to use for encrypting.
	 * @param isVerify When true then the encryption is verified against an
	 *        according live decryption to throw an
	 *        {@link IllegalStateException} in case encryption and decryption
	 *        differ.
	 */
	public ChaosEncrypter( ChaosKey aKey, boolean isVerify ) {
		this( aKey, -1, isVerify );
	}

	/**
	 * Instantiates a new {@link ChaosEncrypter} using the given
	 * {@link ChaosKey} for encrypting.
	 *
	 * @param aKey The {@link ChaosKey} to use for encrypting.
	 * @param aChildDepth The number of children to consider when creating the
	 *        {@link ChaosDecrypter}.
	 * @param isVerify When true then the encryption is verified against an
	 *        according live decryption to throw an
	 *        {@link IllegalStateException} in case encryption and decryption
	 *        differ.
	 */
	public ChaosEncrypter( ChaosKey aKey, int aChildDepth, boolean isVerify ) {
		init( aKey, aChildDepth );
		if ( isVerify ) {
			_verifyDecrypter = new ChaosDecrypter( aKey, aChildDepth );
		}
	}

	// -------------------------------------------------------------------------

	/**
	 * Instantiates a new {@link ChaosEncrypter} using the given
	 * {@link ChaosKey} for encrypting and the given {@link ChaosEncrypter} as
	 * child encrypter: The {@link ChaosKey} must therefore have no child
	 * {@link ChaosKey} as the child {@link ChaosEncrypter} then cannot
	 * unambiguously be determined!
	 * 
	 * Attention: This constructor usually only is used by libraries which
	 * retrieve the various keys in different processing steps (see
	 * {@link ChaosEncryptionOutputStream}).
	 * 
	 * @param aKey The {@link ChaosKey} to use for encrypting.
	 * @param aChildDepth The number of children to consider when creating the
	 *        {@link ChaosDecrypter}.
	 * @param aChildEncrypter The {@link ChaosEncrypter} to be used as child
	 *        encrypter.
	 * @param isVerify When true then the encryption is verified against an
	 *        according live decryption to throw an
	 *        {@link IllegalStateException} in case encryption and decryption
	 *        differ.
	 * 
	 * @throws IllegalArgumentException thrown in case the chaos key has a child
	 *         key and a child encrypter is provided as well (either the one or
	 *         the other only is allowed).
	 */
	protected ChaosEncrypter( ChaosKey aKey, int aChildDepth, ChaosEncrypter aChildEncrypter, boolean isVerify ) {
		if ( aChildEncrypter != null && aKey.getChild() != null ) {
			throw new IllegalArgumentException( "You provided a chaos key with child and a child encrypiter, either the key can have a child or a child encrypter is provided, but not both at the same time!" );
		}
		init( aKey, aChildDepth );
		if ( aChildEncrypter != null ) {
			_childEncrypter = aChildEncrypter;
		}
		if ( isVerify ) {
			// Reorder the verification decrypter chain |-->
			_verifyDecrypter = new ChaosDecrypter( aKey, aChildDepth, aChildEncrypter._verifyDecrypter );
			aChildEncrypter._verifyDecrypter = null;
			// Reorder the verification decrypter chain <--|
		}
	}

	// -------------------------------------------------------------------------

	private void init( ChaosKey aKey, int aChildDepth ) {
		_x = aKey.getX0();
		_a = aKey.getA();
		_s = aKey.getS();
		_chaosMetrics = aKey.getOptions() != null ? aKey.getOptions() : ChaosMode.NONE;

		if ( aChildDepth != 0 && aKey.getChild() != null ) {
			if ( !aKey.getChild().getOptions().isFixedLength() ) {
				throw new IllegalArgumentException( "The provided chaos key chain is not(!) of a fixed length (<" + aKey.getChild().getOptions() + ">) when applied and requires something like a <" + ChaosEncryptionOutputStream.class.getSimpleName() + "> supporting the variable length features when applied!" );
			}
			_childEncrypter = new ChaosEncrypter( aKey.getChild(), aChildDepth != -1 ? aChildDepth - 1 : -1 );
		}

		if ( aKey.getChild() != null ) {}
		// _chaosKeyRef = new WeakReference( aKey );
	}

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

	/**
	 * {@inheritDoc}
	 */
	@Override
	public byte[] toEncrypted( byte[] aDecrypted ) throws EncryptionException {
		final byte[] theEncrypted = new byte[aDecrypted.length];
		toEncrypted( aDecrypted, 0, aDecrypted.length, theEncrypted, 0 );
		return theEncrypted;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int toEncrypted( byte[] aBuffer, int aOffset, int aLength, byte[] aOutBuffer, int aOutOffset ) throws EncryptionException {

		// Validate buffer sizes |-->
		if ( aOutBuffer.length - aOutOffset < aLength ) {
			throw new ArrayIndexOutOfBoundsException( "Out buffer at index <" + aOutBuffer.length + "> too short to hold encrypted data!" );
		}
		if ( aBuffer.length < aLength + aOffset ) {
			throw new IllegalArgumentException( "The input length <" + aBuffer.length + "> is smaller than the offset <" + aOffset + "> and the processable length <" + aLength + ">!" );
			// Validate buffer sizes <--|
		}

		byte[] theBuffer = aOutBuffer;
		int theOffset = aOutOffset;

		// Child |-->
		if ( _childEncrypter != null ) {
			theBuffer = new byte[aLength];
			theOffset = 0;
		}
		// Child <--|

		// Encryption |-->
		byte n;
		for ( int i = 0; i < aLength; i++ ) {
			n = aBuffer[aOffset + i];

			// MUTATE addition |-->
			if ( _chaosMetrics.isMutateS() ) {
				_s = ChaosKey.addToS( _s, _previousEncrypted );
			}
			// MUTATE addition <--|

			// XOR addition |-->
			if ( _chaosMetrics.isXorNext() ) {
				n = (byte) ( 0xff & ( ( n ) ^ ( _previousEncrypted ) ) );
			}
			// XOR addition <--|

			_x = _x * _a * ( 1 - _x );
			final double k = _s * _x;
			theBuffer[i + theOffset] = (byte) ( ( n + k ) % 256 );

			_previousEncrypted = theBuffer[i + theOffset]; // Take encrypted for XOR
		}
		// Encryption <--|

		// Child |-->
		if ( _childEncrypter != null ) {
			_childEncrypter.toEncrypted( theBuffer, theOffset, aLength, aOutBuffer, aOutOffset );

		}
		// Child <--|

		if ( _verifyDecrypter != null ) {
			verifyEncrypted( aBuffer, aOffset, aLength, aOutBuffer, aOutOffset );
		}

		return aLength;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int encrypt( byte[] aBuffer, int aOffset, int aLength ) throws EncryptionException {
		if ( _verifyDecrypter == null ) {
			return toEncrypted( aBuffer, aOffset, aLength, aBuffer, aOffset );
		}
		final byte[] theBuffer = new byte[aLength];
		final int length = toEncrypted( theBuffer, 0, aLength, aBuffer, aOffset );
		System.arraycopy( theBuffer, 0, aBuffer, aOffset, aLength );
		return length;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int encrypt( byte[] aBuffer ) throws EncryptionException {
		final int theLength = aBuffer.length;
		if ( _verifyDecrypter == null ) {
			return toEncrypted( aBuffer, 0, theLength, aBuffer, 0 );
		}
		final byte[] theBuffer = new byte[theLength];
		final int length = toEncrypted( theBuffer, 0, theLength, aBuffer, 0 );
		System.arraycopy( theBuffer, 0, aBuffer, 0, theLength );
		return length;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void dispose() {
		_a = -1;
		_s = -1;
		_x = -1;
		_previousEncrypted = -1;
		_chaosMetrics = null;
		//	WeakReference theChaosKeyRef = _chaosKeyRef;
		//	if ( theChaosKeyRef != null ) {
		//		ChaosKey theKey = theChaosKeyRef.get();
		//		if ( theKey != null ) {
		//			try {
		//				theKey.dispose();
		//			}
		//			catch ( Exception ignore ) { /* ignore */ }
		//		}
		//		theChaosKeyRef.clear();
		//		_chaosKeyRef = null;
		//	}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String toString() {
		return getClass().getSimpleName() + " [x=" + _x + ", a=" + _a + ", s=" + _s + ", prev=" + _previousEncrypted + ", chaosMetrics=" + _chaosMetrics + "]";
	}

	// /////////////////////////////////////////////////////////////////////////
	// HELPER:
	// /////////////////////////////////////////////////////////////////////////

	private void verifyEncrypted( byte[] aBuffer, int aOffset, int aLength, byte[] aOutBuffer, int aOutOffset ) throws EncryptionException {
		final byte[] theVerifyBuffer = new byte[aLength];
		try {
			_verifyDecrypter.toDecrypted( aOutBuffer, aOutOffset, aLength, theVerifyBuffer, 0 );
			for ( int i = 0; i < aLength; i++ ) {
				if ( theVerifyBuffer[i] != aBuffer[i + aOffset] ) {
					throw new EncryptionException( "Verifying encrypted data for (x = " + _x + ", a = " + _a + ", s = " + _s + ", config = " + _chaosMetrics + ") failed!" );
				}
			}
		}
		catch ( DecryptionException e ) {
			throw new EncryptionException( "Verifying encrypted data for (x = " + _x + ", a = " + _a + ", s = " + _s + ", config = " + _chaosMetrics + ") failed!" );
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy