shz.core.hash.MdHash Maven / Gradle / Ivy
package shz.core.hash;
import shz.core.NullHelp;
import shz.core.PRException;
import shz.core.constant.ArrayConstant;
import shz.core.io.IOHelp;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.function.BiConsumer;
public enum MdHash implements IMdHash {
MD5("MD5"),
SHA1("SHA-1"),
SHA224("SHA-224"),
SHA256("SHA-256"),
SHA384("SHA-384"),
SHA512("SHA-512"),
;
private final String algorithm;
MdHash(String algorithm) {
this.algorithm = algorithm;
}
private MessageDigest md() {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw PRException.of(e);
}
}
@Override
public byte[] hash(byte[] bytes) {
if (NullHelp.isEmpty(bytes)) return ArrayConstant.EMPTY_BYTE_ARRAY;
return md().digest(bytes);
}
@Override
public byte[] hash(InputStream is) {
if (is == null) return ArrayConstant.EMPTY_BYTE_ARRAY;
MessageDigest md = md();
IOHelp.read(is, (BiConsumer) (buffer, len) -> md.update(buffer, 0, len));
return md.digest();
}
@Override
public byte[] hash(URL url) {
if (url == null) return ArrayConstant.EMPTY_BYTE_ARRAY;
try {
return hash(url.openConnection().getInputStream());
} catch (IOException e) {
throw PRException.of(e);
}
}
@Override
public byte[] hash(Path path) {
return hash(IOHelp.newBufferedInputStream(path));
}
@Override
public byte[] hash(File file) {
return hash(file.toPath());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy