// 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 balloon

import (
	"crypto/hkdf"
	"errors"
	"hash"

	"go.cypherpunks.su/balloon/v3"
	cmenc "go.cypherpunks.su/keks/cm/enc"
	chaPoly "go.cypherpunks.su/keks/cm/enc/chapoly"
	"golang.org/x/crypto/blake2b"
	"golang.org/x/crypto/chacha20poly1305"
)

const (
	BalloonBLAKE2bHKDF = "balloon-blake2b-hkdf"
	SaltLen            = 16
	HKDFInfo           = "cm/encrypted/balloon-blake2b-hkdf"
)

func blake2bHash() hash.Hash {
	h, err := blake2b.New512(nil)
	if err != nil {
		panic(err)
	}
	return h
}

func Decapsulate(kem cmenc.KEM, id, passphrase []byte) (cek []byte, err error) {
	if len(kem.Salt) == 0 {
		return nil, errors.New("missing salt")
	}
	if kem.BalloonCost == nil {
		return nil, errors.New("missing cost")
	}
	var kek []byte
	kek, err = hkdf.Expand(
		blake2bHash,
		balloon.H(
			blake2bHash,
			passphrase,
			kem.Salt,
			int(kem.BalloonCost.S),
			int(kem.BalloonCost.T),
			int(kem.BalloonCost.P),
		),
		string(append([]byte(HKDFInfo), id...)),
		chacha20poly1305.KeySize,
	)
	if err != nil {
		return nil, err
	}
	return chaPoly.Unwrap(kek, kem.CEK)
}
