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

com.github.bloodshura.x.cryptography.impl.hash.BlowfishCrypt 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.impl.hash;

import com.github.bloodshura.x.charset.Encoding;
import com.github.bloodshura.x.cryptography.Encrypter;
import com.github.bloodshura.x.cryptography.exception.CryptoException;
import com.github.bloodshura.x.util.XApi;
import org.mindrot.jbcrypt.BCrypt;

import javax.annotation.Nonnull;

public class BlowfishCrypt implements Encrypter {
	private int saltRounds;

	public BlowfishCrypt() {
		this(10);
	}

	public BlowfishCrypt(int saltRounds) {
		setSaltRounds(saltRounds);
	}

	public boolean check(@Nonnull String plain, @Nonnull String hash) {
		try {
			return BCrypt.checkpw(plain, hash);
		}
		catch (IllegalArgumentException exception) {
			// Maybe the hash isn't even a BCrypt hash... let's just fail silently here.
			return false;
		}
	}

	@Nonnull
	@Override
	public byte[] encrypt(@Nonnull byte[] data) throws CryptoException {
		return encrypt(Encoding.UTF_8.build(data));
	}

	@Nonnull
	@Override
	public byte[] encrypt(@Nonnull CharSequence sequence) throws CryptoException {
		return Encoding.UTF_8.encode(encryptToStr(sequence));
	}

	@Nonnull
	@Override
	public String encryptToStr(@Nonnull byte[] data) throws CryptoException {
		return encryptToStr(Encoding.UTF_8.build(data));
	}

	@Nonnull
	@Override
	public String encryptToStr(@Nonnull CharSequence sequence) throws CryptoException {
		return BCrypt.hashpw(sequence.toString(), BCrypt.gensalt(getSaltRounds()));
	}

	public int getSaltRounds() {
		return saltRounds;
	}

	public void setSaltRounds(int saltRounds) {
		XApi.require(saltRounds >= 4 && saltRounds <= 30, "Illegal salt rounds: " + saltRounds + "; expected to be between 4 and 30, inclusive");

		this.saltRounds = saltRounds;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy