
com.github.bloodshura.x.cryptography.AbstractDigest 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.math.BaseConverter;
import javax.annotation.Nonnull;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public abstract class AbstractDigest extends AbstractByteArraySalted implements Encrypter {
private final MessageDigest digest;
public AbstractDigest(@Nonnull MessageDigest digest) {
this.digest = digest;
}
public AbstractDigest(@Nonnull String digestName) throws CryptoException {
this(digestFor(digestName));
}
@Nonnull
@Override
public byte[] encrypt(@Nonnull byte[] data) throws CryptoException {
if (hasSalt()) {
getDigest().update(getSalt());
}
getDigest().update(data);
return getDigest().digest();
}
@Nonnull
@Override
public String encryptToStr(@Nonnull byte[] data) throws CryptoException {
return encryptToStr(data, BaseConverter.HEXADECIMAL);
}
@Nonnull
public String encryptToStr(@Nonnull byte[] data, int radix) throws CryptoException {
return new BigInteger(1, encrypt(data)).toString(radix);
}
@Nonnull
@Override
public String encryptToStr(@Nonnull CharSequence sequence) throws CryptoException {
return encryptToStr(sequence, BaseConverter.HEXADECIMAL);
}
@Nonnull
public String encryptToStr(@Nonnull CharSequence sequence, int radix) throws CryptoException {
return new BigInteger(1, encrypt(sequence)).toString(radix);
}
@Nonnull
public MessageDigest getDigest() {
return digest;
}
private static MessageDigest digestFor(String digestName) throws CryptoException {
try {
return MessageDigest.getInstance(digestName);
}
catch (NoSuchAlgorithmException exception) {
throw new CryptoException(exception);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy