ChecksumHelper.kt
/*
Copyright (C) 2026 Sber
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.archtool.helper
import jakarta.xml.bind.DatatypeConverter
import org.archtool.data.exception.ErrorCode
import org.archtool.data.exception.SeafException
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.io.InputStream
import java.security.MessageDigest
/**
* Класс для работы c checksum
* Использует алгоритм указанный в константе CHECKSUM_ALGORITHM = SHA-256
* Не управляет потоками аргументами, открывать, закрывать и ловить ошибки должна вызывающая сторона
*/
@Component
class ChecksumHelper {
private val log = LoggerFactory.getLogger(javaClass)
/**
* Расчет checksum на основе inputStream
*
* @param inputStream - поток данных по которому будет рассчитана checksum !!! метод не управляет потоком, только читает из него
* @return checksum в виде строки
*/
fun calcChecksum(inputStream: InputStream): String {
val actualChecksum = try {
val digest = MessageDigest.getInstance(CHECKSUM_ALGORITHM)
val buffer = ByteArray(8192)
var bytesRead: Int
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
digest.update(buffer, 0, bytesRead)
}
DatatypeConverter.printHexBinary(digest.digest())
} catch (e: Exception) {
log.error("Ошибка при проверке контрольной суммы файла", e)
throw SeafException(ErrorCode.BAD_REQUEST, "Ошибка при проверке контрольной суммы файла")
}
return actualChecksum
}
/**
* Метод проверяет что переданный inputStream имеет checksum равную переданной checksum
* Алгоритм для расчета checksum указан в константе CHECKSUM_ALGORITHM = SHA-256
* Сравнение значений checksum производится без учета регистра
* @param inputStream - поток данных по которому будет рассчитана checksum, !!! метод не управляет потоком, только читает из него
* @param expectedChecksum - ожидаемое значение checksum
*/
fun validateChecksum(inputStream: InputStream, expectedChecksum: String, context: String? = null) {
val actualChecksum = calcChecksum(inputStream)
// ignore case т.к. чексумма не зависит от регистра
// https://en.wikipedia.org/wiki/Hexadecimal
// Common convention: Typically, a hex representation convention allows either lower or upper case letters
// and treats the letter the same regardless of its case.
if (!actualChecksum.equals(expectedChecksum, ignoreCase = true)) {
log.error(
"Несовпадение контрольной суммы файла ({}). Ожидалось: {}, получено: {}",
context,
expectedChecksum,
actualChecksum
)
throw SeafException(
ErrorCode.BAD_REQUEST,
"Не пройдена проверка чек-суммы, попробуйте выполнить отправку ещё раз. Если ошибка возникнет снова, обратитесь в поддержку SEAF.Era"
)
}
}
companion object {
private const val CHECKSUM_ALGORITHM = "SHA-256"
}
}