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

com.github.bloodshura.x.cryptography.BuildableCipher Maven / Gradle / Ivy

/*
 * Copyright (c) 2013-2018, João Vitor Verona Biazibetti - All Rights Reserved
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see .
 *
 * https://www.github.com/BloodShura
 */

package com.github.bloodshura.x.cryptography;

import com.github.bloodshura.x.cryptography.exception.CryptoException;
import com.github.bloodshura.x.cryptography.exception.SaltRequiredException;

import javax.annotation.Nonnull;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.security.GeneralSecurityException;

public class BuildableCipher {
	public static final int DECRYPT = 0x2;
	public static final int ENCRYPT = 0x1;
	public static final int UNWRAP = 0x4;
	public static final int WRAP = 0x3;
	private final Cipher cipher;
	private final Mode mode;
	private final AbstractCipher parent;

	protected BuildableCipher(@Nonnull AbstractCipher parent, @Nonnull Mode mode) throws CryptoException {
		try {
			this.cipher = parent.createCipher();

			if (!parent.hasSalt()) {
				throw new SaltRequiredException();
			}

			cipher.init(mode.value, parent.getSecretKeySpec());

			this.mode = mode;
			this.parent = parent;
		}
		catch (GeneralSecurityException exception) {
			throw new CryptoException(exception);
		}
	}

	@Nonnull
	public byte[] end() throws CryptoException {
		try {
			return cipher.doFinal();
		}
		catch (BadPaddingException | IllegalBlockSizeException exception) {
			throw new CryptoException(exception);
		}
	}

	@Nonnull
	public byte[] end(@Nonnull byte[] data) throws CryptoException {
		try {
			return cipher.doFinal(data);
		}
		catch (BadPaddingException | IllegalBlockSizeException exception) {
			throw new CryptoException(exception);
		}
	}

	@Nonnull
	public Mode getMode() {
		return mode;
	}

	@Nonnull
	public AbstractCipher getParent() {
		return parent;
	}

	public void update(@Nonnull byte[] data) {
		cipher.update(data);
	}

	public static enum Mode {
		DECRYPT(0x2),
		ENCRYPT(0x1),
		UNWRAP(0x4),
		WRAP(0x3);

		private final int value;

		private Mode(int value) {
			this.value = value;
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy