package info.frostfs.sdk; import com.google.protobuf.ByteString; import com.google.protobuf.Message; import info.frostfs.sdk.exceptions.ValidationFrostFSException; import org.apache.commons.lang3.StringUtils; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import static info.frostfs.sdk.constants.ErrorConst.INPUT_PARAM_IS_MISSING; import static java.util.Objects.isNull; public class Helper { private static final String SHA256 = "SHA-256"; private static final int HEX_RADIX = 16; private Helper() { } public static MessageDigest getSha256Instance() { try { return MessageDigest.getInstance(SHA256); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static byte[] getSha256(byte[] value) { if (isNull(value)) { throw new ValidationFrostFSException(INPUT_PARAM_IS_MISSING); } return getSha256Instance().digest(value); } public static ByteString getSha256(Message value) { if (isNull(value)) { throw new ValidationFrostFSException(INPUT_PARAM_IS_MISSING); } return ByteString.copyFrom(getSha256(value.toByteArray())); } public static String getHexString(byte[] value) { if (isNull(value) || value.length == 0) { throw new ValidationFrostFSException(INPUT_PARAM_IS_MISSING); } return String.format("%0" + (value.length << 1) + "x", new BigInteger(1, value)); } public static byte[] getByteArrayFromHex(String hex) { if (StringUtils.isBlank(hex)) { throw new ValidationFrostFSException(INPUT_PARAM_IS_MISSING); } return new BigInteger(hex, HEX_RADIX).toByteArray(); } }