ChecksumUtils.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

  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project

  https://dochub.info

  The use of this product or its derivatives for any purpose cannot be a secret.


  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.

  Maintainers:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025

  Contributors:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025
*/

package org.archtool.archloader.utils

import jakarta.xml.bind.DatatypeConverter
import java.io.InputStream
import java.security.MessageDigest
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import org.archtool.archloader.exception.UserDataException

/**
 * Класс для работы c checksum
 * Использует алгоритм указанный в константе CHECKSUM_ALGORITHM = SHA-256
 * Не управляет потоками аргументами, открывать, закрывать и ловить ошибки должна вызывающая сторона
 */
@Component
class ChecksumUtils {

    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 UserDataException("Ошибка при проверке контрольной суммы файла")
        }
        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 UserDataException(
                "Не пройдена проверка чек-суммы, попробуйте выполнить отправку ещё раз. Если ошибка возникнет снова, обратитесь в поддержку SEAF.Era"
            )
        }
    }

    companion object {
        private const val CHECKSUM_ALGORITHM = "SHA-256"
    }
}