// KEKS/CM -- KEKS-encoded cryptographic messages
// Copyright (C) 2024-2025 Sergey Matveev <stargrave@stargrave.org>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, version 3 of the License.
//
// 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program.  If not, see <http://www.gnu.org/licenses/>.

package gost

import (
	"bytes"
	"hash"
	"io"

	"go.cypherpunks.su/gogost/v6/gost3410"
	"go.cypherpunks.su/gogost/v6/gost34112012256"
	"go.cypherpunks.su/gogost/v6/gost34112012512"
)

func Verify(algo string, pub, signed, signature []byte) (valid bool, err error) {
	var pk *gost3410.PublicKey
	pk, err = gost3410.NewPublicKeyBE(CurveByName(algo), pub)
	if err != nil {
		return
	}
	var hasher hash.Hash
	switch algo {
	case GOST3410256A:
		hasher = gost34112012256.New()
	case GOST3410512C:
		hasher = gost34112012512.New()
	}
	_, err = io.Copy(hasher, bytes.NewReader(signed))
	if err != nil {
		return
	}
	hsh := hasher.Sum(nil)
	valid, err = pk.VerifyDigest(hsh,
		append(signature[len(signature)/2:], signature[:len(signature)/2]...))
	return
}

func VerifyPrehash(algo string, pub, hsh, signature []byte) (valid bool, err error) {
	var pk *gost3410.PublicKey
	pk, err = gost3410.NewPublicKeyBE(CurveByName(algo), pub)
	if err != nil {
		return
	}
	valid, err = pk.VerifyDigest(hsh,
		append(signature[len(signature)/2:], signature[:len(signature)/2]...))
	return
}
