xref: /aosp_15_r20/external/tink/go/hybrid/subtle/ecies_hkdf_sender_kem.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2020 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15////////////////////////////////////////////////////////////////////////////////
16
17package subtle
18
19import "github.com/google/tink/go/subtle"
20
21// KEMKey represents a KEM managed key.
22type KEMKey struct {
23	Kem, SymmetricKey []byte
24}
25
26// ECIESHKDFSenderKem represents HKDF-based ECIES-KEM (key encapsulation mechanism)
27// for ECIES sender.
28type ECIESHKDFSenderKem struct {
29	recipientPublicKey *ECPublicKey
30}
31
32// encapsulate generates an HKDF-based KEMKey.
33func (s *ECIESHKDFSenderKem) encapsulate(hashAlg string, salt []byte, info []byte, keySize uint32, pointFormat string) (*KEMKey, error) {
34
35	pvt, err := GenerateECDHKeyPair(s.recipientPublicKey.Curve)
36	if err != nil {
37		return nil, err
38	}
39	pub := pvt.PublicKey
40	secret, err := ComputeSharedSecret(&s.recipientPublicKey.Point, pvt)
41	if err != nil {
42		return nil, err
43	}
44
45	sdata, err := PointEncode(pub.Curve, pointFormat, pub.Point)
46	if err != nil {
47		return nil, err
48	}
49	i := make([]byte, 0, len(sdata)+len(secret))
50	i = append(i, sdata...)
51	i = append(i, secret...)
52
53	sKey, err := subtle.ComputeHKDF(hashAlg, i, salt, info, keySize)
54	if err != nil {
55		return nil, err
56	}
57
58	return &KEMKey{
59		Kem:          sdata,
60		SymmetricKey: sKey,
61	}, nil
62
63}
64