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

org.refcodes.security.alt.chaos.ChaosDecrypter 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")
// -----------------------------------------------------------------------------
// 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.Decrypter;
import org.refcodes.security.DecryptionException;

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

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

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

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

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

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

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

	/**
	 * Instantiates a new {@link ChaosDecrypter} using the given
	 * {@link ChaosKey} for encrypting and the given {@link ChaosDecrypter} as
	 * _child encrypter: TThe {@link ChaosKey} must therefore have no child
	 * {@link ChaosKey} as the child {@link ChaosDecrypter} 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 ChaosDecryptionInputStream}).
	 * 
	 * @param aKey The {@link ChaosKey} to use for decrypting.
	 * @param aChildDepth The number of children to consider when creating the
	 *        {@link ChaosDecrypter}.
	 * @param aChildDecrypter The child {@link ChaosDecrypter} to be used as
	 *        child decrypter.
	 * 
	 * @throws IllegalArgumentException thrown in case the chaos key has a child
	 *         key and a child decrypter is provided as well (either the one or
	 *         the other only is allowed).
	 */
	protected ChaosDecrypter( ChaosKey aKey, int aChildDepth, ChaosDecrypter aChildDecrypter ) {
		if ( aChildDecrypter != 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 ( aChildDecrypter != null ) {
			_childDecrypter = aChildDecrypter;
		}
	}

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

	/**
	 * @param aKey
	 */
	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 <" + ChaosDecryptionInputStream.class.getSimpleName() + "> supporting the variable length features when applied!" );
			}
			_childDecrypter = new ChaosDecrypter( aKey.getChild(), aChildDepth != -1 ? aChildDepth - 1 : -1 );
		}
		// _chaosKeyRef = new WeakReference( aKey );
	}

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

	/**
	 * {@inheritDoc}
	 */
	@Override
	public byte[] toDecrypted( byte[] aEncrypted ) throws DecryptionException {
		final byte[] theDecrypted = new byte[aEncrypted.length];
		toDecrypted( aEncrypted, 0, aEncrypted.length, theDecrypted, 0 );
		return theDecrypted;
	}

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

		// Validate buffer sizes |-->
		if ( aOutBuffer.length - aOutOffset < aLength ) {
			throw new ArrayIndexOutOfBoundsException( "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 = aBuffer;
		int theOffset = aOffset;

		// Child |-->
		if ( _childDecrypter != null ) {
			theBuffer = new byte[aLength];
			theOffset = 0;
			System.arraycopy( aBuffer, aOffset, theBuffer, 0, aLength );
			_childDecrypter.toDecrypted( aBuffer, aOffset, aLength, theBuffer, 0 );
		}
		// Child <--|

		// Decryption |-->
		byte n;
		byte y;
		for ( int i = 0; i < theBuffer.length; i++ ) {
			n = theBuffer[theOffset + i];

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

			_x = _x * _a * ( 1 - _x );
			final double k = _s * _x;
			y = (byte) ( ( n - k ) % 256 );

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

			_previousEncrypted = theBuffer[theOffset + i]; // Take encrypted for XOR

			aOutBuffer[i + aOutOffset] = y;
		}
		// Decryption <--|

		return aLength;
	}

	/**
	 * {@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 + "]";
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy