github.com/ethersphere/bee/v2@v2.2.0/pkg/crypto/dh.go (about) 1 // Copyright 2020 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package crypto 6 7 import ( 8 "crypto/ecdsa" 9 "errors" 10 ) 11 12 // DH is an interface allowing to generate shared keys for public key 13 // using a salt from a known private key 14 // TODO: implement clef support beside in-memory 15 type DH interface { 16 SharedKey(public *ecdsa.PublicKey, salt []byte) ([]byte, error) 17 } 18 19 type defaultDH struct { 20 key *ecdsa.PrivateKey 21 } 22 23 // NewDH returns an ECDH shared secret key generation seeded with in-memory private key 24 func NewDH(key *ecdsa.PrivateKey) DH { 25 return &defaultDH{key} 26 } 27 28 // SharedKey creates ECDH shared secret using the in-memory key as private key and the given public key 29 // and hashes it with the salt to return the shared key 30 // safety warning: this method is not meant to be exposed as it does not validate private and public keys 31 // are on the same curve 32 func (dh *defaultDH) SharedKey(pub *ecdsa.PublicKey, salt []byte) ([]byte, error) { 33 x, _ := pub.Curve.ScalarMult(pub.X, pub.Y, dh.key.D.Bytes()) 34 if x == nil { 35 return nil, errors.New("shared secret is point at infinity") 36 } 37 return LegacyKeccak256(append(x.Bytes(), salt...)) 38 }